text
stringlengths 8
6.88M
|
|---|
#include <iostream>
using namespace std;
int main()
{
cout << "Input english lower case: "
char ch;
cin >> ch;
char result = ch+('a'-'A');
cout << "Output english upper case: " << result << endl;
return 0;
}
|
/********************************************************************************
** Form generated from reading UI file 'gamewindow.ui'
**
** Created by: Qt User Interface Compiler version 5.5.1
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_GAMEWINDOW_H
#define UI_GAMEWINDOW_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QMenuBar>
#include <QtWidgets/QStatusBar>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_GameWindow
{
public:
QWidget *centralwidget;
QMenuBar *menubar;
QStatusBar *statusbar;
void setupUi(QMainWindow *GameWindow)
{
if (GameWindow->objectName().isEmpty())
GameWindow->setObjectName(QStringLiteral("GameWindow"));
GameWindow->setEnabled(true);
GameWindow->resize(1200, 600);
QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(GameWindow->sizePolicy().hasHeightForWidth());
GameWindow->setSizePolicy(sizePolicy);
GameWindow->setMinimumSize(QSize(1200, 600));
GameWindow->setMaximumSize(QSize(1200, 600));
GameWindow->setCursor(QCursor(Qt::CrossCursor));
centralwidget = new QWidget(GameWindow);
centralwidget->setObjectName(QStringLiteral("centralwidget"));
GameWindow->setCentralWidget(centralwidget);
menubar = new QMenuBar(GameWindow);
menubar->setObjectName(QStringLiteral("menubar"));
menubar->setGeometry(QRect(0, 0, 1200, 20));
GameWindow->setMenuBar(menubar);
statusbar = new QStatusBar(GameWindow);
statusbar->setObjectName(QStringLiteral("statusbar"));
GameWindow->setStatusBar(statusbar);
retranslateUi(GameWindow);
QMetaObject::connectSlotsByName(GameWindow);
} // setupUi
void retranslateUi(QMainWindow *GameWindow)
{
GameWindow->setWindowTitle(QApplication::translate("GameWindow", "MainWindow", 0));
} // retranslateUi
};
namespace Ui {
class GameWindow: public Ui_GameWindow {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_GAMEWINDOW_H
|
class Solution {
public:
int calculate(string s) {
stack<int> stk;
char sign = '+';
if(s[0] == '-') sign = '-';
int num = 0;
for(int i = 0; i < s.length(); i++)
{
char ch = s[i];
if(isdigit(ch)) num = num*10 + (ch-'0');
if((!isdigit(ch) && ch != ' ') || i == s.length()-1){
if(sign == '+') stk.push(num);
else if(sign == '-') stk.push(-num);
else if(sign == '*')
{
int pre = stk.top();
stk.pop();
stk.push(pre*num);
}
else if(sign == '/'){
int pre = stk.top();
stk.pop();
stk.push(pre/num);
}
num = 0;
sign = ch;
}
}
int result = 0;
while(!stk.empty())
{
result += stk.top();
stk.pop();
}
return result;
}
bool isdigit(char ch)
{
return ch >= '0' && ch <= '9';
}
};
|
// -*- C++ -*-
//
// Copyright (C) 1998, 1999, 2000, 2002 Los Alamos National Laboratory,
// Copyright (C) 1998, 1999, 2000, 2002 CodeSourcery, LLC
//
// This file is part of FreePOOMA.
//
// FreePOOMA is free software; you can redistribute it and/or modify it
// under the terms of the Expat license.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Expat
// license for more details.
//
// You should have received a copy of the Expat license along with
// FreePOOMA; see the file LICENSE.
//
//-----------------------------------------------------------------------------
// Paws test 8: Send and Receive an int and double set of scalars,
// plus a dynamic array, in conjunction with test 7.
//-----------------------------------------------------------------------------
#include "Pooma/Pooma.h"
#if POOMA_PAWS
#include "Pooma/Paws.h"
#endif // POOMA_PAWS
#include "Pooma/DynamicArrays.h"
#include "Pooma/Domains.h"
#include "Utilities/Tester.h"
int main(int argc, char *argv[])
{
// Initialize POOMA and output stream, using Tester class
Pooma::initialize(argc, argv);
Pooma::Tester tester(argc, argv);
tester.out() << argv[0] << ": Paws DynmaicArray send/receive test B\n";
tester.out() << "----------------------------------------------------";
tester.out() << std::endl;
#if POOMA_PAWS
// Some scalars to send and receive
int s1 = 1, origs1 = 1;
double s2 = 2.5, origs2 = 2.5;
int iters = 10;
// DynamicArrays for reference ...
Interval<1> refdomain(100);
Loc<1> refblocks(2);
GridPartition<1> refgpar(refblocks);
LocalMapper<1> refcmap(refgpar);
DynamicLayout reflayout(refdomain, refgpar, refcmap);
DynamicArray<float, MultiPatch<DynamicTag,Dynamic> > refa1(reflayout);
DynamicArray<int, MultiPatch<DynamicTag,Dynamic> > refa2(reflayout);
DynamicArray<double, Dynamic> refa3(30);
// DynamicArrays to receive ...
Interval<1> domain(3);
Loc<1> blocks(3);
GridPartition<1> gpar(blocks);
LocalMapper<1> cmap(gpar);
DynamicLayout layout(domain, gpar, cmap);
DynamicLayout layout2(domain, gpar, cmap);
DynamicArray<float, MultiPatch<DynamicTag,Dynamic> > a1(layout);
DynamicArray<int, MultiPatch<DynamicTag,Dynamic> > a2(layout);
DynamicArray<double, MultiPatch<DynamicTag,Dynamic> > a3(layout2);
// Initialize the arrays
refa1 = 1 + iota(refa1.domain()).comp(0);
refa2 = 1000 + refa1;
refa3 = 4.5;
a1 = 0;
a2 = 0;
a3 = 0;
Pooma::blockAndEvaluate();
// Create a Paws connection
tester.out() << "Creating PawsConnection object ..." << std::endl;
Connection<Paws> *paws = new Connection<Paws>("test8", argc, argv);
tester.out() << "Finished creating PawsConnection object." << std::endl;
// Establish connections for the two scalars
tester.out() << "Connecting s1 = " << s1 << " for input ..." << std::endl;
ConnectorBase *s1p = paws->connectScalar("s1", s1, ConnectionBase::in);
tester.out() << "Connecting s2 = " << s2 << " for output ..." << std::endl;
ConnectorBase *s2p = paws->connectScalar("s2", s2, ConnectionBase::out);
tester.out() << "Connecting iters = " << iters << " for input ...";
tester.out() << std::endl;
ConnectorBase *iterp = paws->connectScalar("iters",iters,ConnectionBase::in);
// Establish connections for the arrays
tester.out() << "Connecting a1 = " << a1 << " for input ..." << std::endl;
paws->connect("a1", a1, ConnectionBase::in);
tester.out() << "Connecting a2 = " << a2 << " for input ..." << std::endl;
paws->connect("a2", a2, ConnectionBase::in);
tester.out() << "Connecting a3 = " << a3 << " for input ..." << std::endl;
paws->connect("a3", a3, ConnectionBase::in);
// Wait for everything to be ready to proceed
tester.out() << "Waiting for ready signal ..." << std::endl;
paws->ready();
tester.out() << "Ready complete, moving on." << std::endl;
// Modify s1, and update
s1 *= 2;
tester.out() << "Updating current s1 = " << s1 << " and s2 = " << s2;
tester.out() << ", plus arrays ..." << std::endl;
paws->update();
// Report the results
tester.out() << "Received update. New values:" << std::endl;
tester.out() << " s1 = " << s1 << " (should be " << origs1 << ")\n";
tester.out() << " s2 = " << s2 << " (should be " << origs2 << ")\n";
tester.out() << std::endl;
tester.check("s1 OK", s1 == origs1);
tester.check("s2 OK", s2 == origs2);
// Disconnect the scalars
int connections = paws->size();
tester.out() << "Disconnecting scalars ..." << std::endl;
delete s1p;
delete s2p;
delete iterp;
tester.check("3 less connections", paws->size() == (connections - 3));
// Do, in a loop, updates of the receiver. Add one to the arrays each time,
// plus delete the second element.
int myiters = iters;
while (myiters-- > 0)
{
refa1 += 1;
refa2 += 1;
refa3 += 1;
Pooma::blockAndEvaluate();
refa1.destroy(Interval<1>(1,1), ShiftUp());
refa1.sync();
tester.out() << "Receiving for iters = " << myiters << std::endl;
paws->update();
// Compare to reference
tester.check("a1 size", a1.domain().size() == refa1.domain().size());
tester.check("a2 size", a2.domain().size() == refa2.domain().size());
tester.check("a3 size", a3.domain().size() == refa3.domain().size());
int a1msd = sum((a1 - refa1)*(a1 - refa1));
int a2msd = sum((a2 - refa2)*(a2 - refa2));
int a3msd = sum((a3 - refa3)*(a3 - refa3));
tester.check("a1 MSD", a1msd == 0);
tester.check("a2 MSD", a2msd == 0);
tester.check("a3 MSD", a3msd == 0);
}
// Delete PAWS connection, disconnecting us from the other code.
tester.out() << "Deleting Connection<Paws> object ..." << std::endl;
delete paws;
#else // POOMA_PAWS
tester.out() << "Please configure with --paws to use this test code!"
<< std::endl;
#endif // POOMA_PAWS
// Finish up and report results
tester.out() << "-------------------------------------------" << std::endl;
int retval = tester.results("Paws DynamicArray send/receive test A");
Pooma::finalize();
return retval;
}
// ACL:rcsinfo
// ----------------------------------------------------------------------
// $RCSfile: paws_test8.cpp,v $ $Author: richard $
// $Revision: 1.8 $ $Date: 2004/11/01 18:16:24 $
// ----------------------------------------------------------------------
// ACL:rcsinfo
|
//
// main.cpp
// 3 tensor factorization
//
// Created by Vanellope on 5/16/16.
// Copyright © 2016 Vanellope. All rights reserved.
//
#include <iostream>
#include <fstream>
#include <math.h>
#define MAX_FACT 490000
#define MAX_ENTITY 15000
#define MAX_RELATION 1400
#define F 483142
#define E 14951
#define R 1345
#define RE 20 //RE=10Rr,Rr<15
#define Rr 2
#define Ita 5
#define SMP 0.001
using namespace std;
int train[MAX_FACT][3];
int valid[MAX_FACT][3];
int test[MAX_FACT][3];
double a[MAX_ENTITY][Rr+1][RE+1];
double b[RE+1][MAX_RELATION][RE+1];
double c[RE+1][Rr+1][MAX_ENTITY];
double a1[MAX_ENTITY][Rr+1][RE+1];
double b1[RE+1][MAX_RELATION][RE+1];
double c1[RE+1][Rr+1][MAX_ENTITY];
void input()
{
FILE *fp1=fopen("FB15K/m3train.dat","r");
FILE *fp2=fopen("FB15K/m3valid.dat","r");
FILE *fp3=fopen("FB15K/m3test.dat","r");
for(long i=1;i<=F;i++)
fscanf(fp1,"%d%d%d",&train[i][0],&train[i][1],&train[i][2]);
for(int i=1;i<=59071;i++)
fscanf(fp3,"%d%d%d",&test[i][0],&test[i][1],&test[i][2]);
for(int i=1;i<=50000;i++)
fscanf(fp2,"%d%d%d",&valid[i][0],&valid[i][1],&valid[i][2]);
return;
}
void initialize(){
double ini=pow(1.0/RE/RE/Rr,1.0/3)*2;
for(long s=1;s<=E;s++)
for(long r=1;r<=Rr;r++)
for(long o=1;o<=RE;o++)
a[s][r][o]=(ini*rand())/RAND_MAX-ini;
for(long s=1;s<=RE;s++)
for(long r=1;r<=R;r++)
for(long o=1;o<=RE;o++)
b[s][r][o]=(ini*rand())/RAND_MAX-ini;
for(long s=1;s<=RE;s++)
for(long r=1;r<=Rr;r++)
for(long o=1;o<=E;o++)
c[s][r][o]=(ini*rand())/RAND_MAX-ini;
return;
}
void initialize1(){
for(long s=1;s<=E;s++)
for(long r=1;r<=Rr;r++)
for(long o=1;o<=RE;o++)
a1[s][r][o]=0;
for(long s=1;s<=RE;s++)
for(long r=1;r<=R;r++)
for(long o=1;o<=RE;o++)
b1[s][r][o]=0;
for(long s=1;s<=RE;s++)
for(long r=1;r<=Rr;r++)
for(long o=1;o<=E;o++)
c1[s][r][o]=0;
return;
}
double tensor(long s,long r,long o){
double x=0;
for(long r1=1;r1<=Rr;r1++)
for(long o1=1;o1<=RE;o1++)
for(long s1=1;s1<=RE;s1++)
{
x+=a[s][r1][o1]*b[s1][r][o1]*c[s1][r1][o];
}
return x;
}
double norm(){
double x=0;
for(long s=1;s<=E;s++)
for(long r=1;r<=Rr;r++)
for(long o=1;o<=RE;o++)
x+=a1[s][r][o]*a1[s][r][o];
for(long s=1;s<=RE;s++)
for(long r=1;r<=R;r++)
for(long o=1;o<=RE;o++)
x+=b1[s][r][o]*b1[s][r][o];
for(long s=1;s<=RE;s++)
for(long r=1;r<=Rr;r++)
for(long o=1;o<=E;o++)
x+=c1[s][r][o]*c1[s][r][o];
return x;
}
void renew(double y){
for(long s=1;s<=E;s++)
for(long r=1;r<=Rr;r++)
for(long o=1;o<=RE;o++)
a[s][r][o]+=a1[s][r][o]*y;
for(long s=1;s<=RE;s++)
for(long r=1;r<=R;r++)
for(long o=1;o<=RE;o++)
b[s][r][o]+=b1[s][r][o]*y;
for(long s=1;s<=RE;s++)
for(long r=1;r<=Rr;r++)
for(long o=1;o<=E;o++)
c[s][r][o]+=c1[s][r][o]*y;
return ;
}
void evaluate(){
double value[MAX_ENTITY],temp;
long eva=0;
for(long f=1;f<=50000;f++){
long s=valid[f][0],r=valid[f][1],o=valid[f][2],num=0;
temp=tensor(s,r,o);
for(long o1=1;o1<=E;o1++){
if(o1!=o&&tensor(s,r,o1)>temp) num++;
if(num>=10) break;
}
if(num<10) eva++;
// cout<<f<<'\n';
}
cout<<"Ans= "<<(double)eva/50000<<'\n';
system("pause");
}
void training()
{
// double pre=-1*F*SMP;
// cout<<pre<<'\n';
long times=0;
while(1)
{
times++;
double loss=0;
initialize1();
for(long f=1;f<=F*SMP;f++)
{
long temp=rand()/(double)RAND_MAX*F+1;
if(temp<1||temp>F) continue;
long s=train[temp][0], r=train[temp][1], o=train[temp][2];
double x=tensor(s,r,o);
loss+=(x-1)*(x-1);
double y=-2*(x-1);
for(long r1=1;r1<=Rr;r1++)
for(long o1=1;o1<=RE;o1++)
for(long s1=1;s1<=RE;s1++)
{
a1[s][r1][o1]+=y*b[s1][r][o1]*c[s1][r1][o];
b1[s1][r][o1]+=y*a[s][r1][o1]*c[s1][r1][o];
c1[s1][r1][o]+=y*b[s1][r][o1]*a[s][r1][o1];
}
// cout<<temp<<'\n';
}
for(long f=1;f<=F*SMP;f++)
{
long s=rand()/(double)RAND_MAX*E+1, r=rand()/(double)RAND_MAX*R+1, o=rand()/(double)RAND_MAX*E+1;
if(s<1||s>E||r<1||r>R||o<1||o>E) continue;
double x=tensor(s,r,o);
double y=-2*(x+1)/Ita;
loss+=(x+1)*(x+1)/Ita;
for(long r1=1;r1<=Rr;r1++)
for(long o1=1;o1<=RE;o1++)
for(long s1=1;s1<=RE;s1++)
{
a1[s][r1][o1]+=y*b[s1][r][o1]*c[s1][r1][o];
b1[s1][r][o1]+=y*a[s][r1][o1]*c[s1][r1][o];
c1[s1][r1][o]+=y*b[s1][r][o1]*a[s][r1][o1];
}
}
double x=norm(),y=0.01;
// if(loss>700) y=0.05;
cout<<times<<' '<<loss<<' '<<x<<' '<<'\n';
renew(y);
if(times%1000==0){system("pause");
int ok=0;
cout<<"Evaluate now or Continue(evaluation may last more than 20 minutes)? Evaluate=1, Continue=0.";
cin>>ok;
if(ok) evaluate();
}
}
return;
}
int main()
{
srand((unsigned)(time(NULL)));
input();
initialize();
training();
system("pause");
return 0;
}
|
#pragma once
#include <algorithm>
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <fstream>
#include <functional>
#include <iostream>
#include <list>
#include <set>
#include <stdio.h>
#include <string>
#include <cstring>
#include <sys/mman.h>
#include <sys/stat.h>
#include <thread>
#include <unistd.h> // ftruncate
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace fastBPE {
using namespace std;
const size_t kMaxPairs = 1000 * 1000 * 1000;
// const size_t kThreads = max(1, min(10, int(thread::hardware_concurrency())));
const size_t kThreads = 4;
const char *kEndWord = "</w>";
const size_t kEndWordLength = 4;
const char *kTokenDelim = "@@";
const size_t kTokenDelimLength = 2;
int safeOpen(const char *file_path, int flags, mode_t mode = 0) {
int fd = open(file_path, flags, mode);
if (fd < 0) {
fprintf(stderr, "Cannot open text file %s\n", file_path);
exit(EXIT_FAILURE);
}
return fd;
}
void readText(const char *fp, unordered_map<string, uint32_t> &word_count) {
string cur_word;
uint64_t total = 0;
auto deal_with_char = [&](char cur_char){
if (cur_char == ' ' || cur_char == '\n') {
if (cur_word.size() == 0)
return;
// end of word
auto it = word_count.find(cur_word);
int count = it != word_count.end() ? it->second : 0;
word_count[cur_word] = count + 1;
total++;
cur_word.clear();
} else {
cur_word.push_back(cur_char);
}
};
if (string(fp).compare("-") == 0) {
for (std::string line; std::getline(std::cin, line);) {
for(char c: line){
deal_with_char(c);
}
deal_with_char('\n');
}
}
else {
int fd = safeOpen(fp, O_RDONLY);
struct stat s;
fstat(fd, &s);
fprintf(stderr, "Loading vocabulary from %s ...\n", fp);
size_t size = s.st_size;
char *f = (char *)mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
for (size_t i = 0; i < size; i++) {
deal_with_char(f[i]);
}
}
fprintf(stderr, "Read %lu words (%lu unique) from text file.\n", total,
word_count.size());
}
std::pair<size_t, uint64_t> output_or_count(
unordered_map<string, string> &bpe, size_t size, char *f, char *fo
) {
string cur_word;
size_t charOut = 0;
uint64_t total = 0;
for (size_t i = 0; i < size; i++) {
auto &cur_char = f[i];
if (cur_char == ' ' || cur_char == '\n') {
if (cur_word.size() == 0) {
if (fo != nullptr) fo[charOut] = cur_char;
charOut++;
continue;
}
// end of word : write bpe to output
auto it = bpe.find(cur_word);
assert(it != bpe.end());
for (auto x : it->second) {
if (fo != nullptr) fo[charOut] = x;
charOut++;
}
if (fo != nullptr) fo[charOut] = cur_char;
charOut++;
total++;
cur_word.clear();
} else {
cur_word.push_back(cur_char);
}
}
return std::make_pair(charOut, total);
}
void outputText(const char *fpo, const char *fp,
unordered_map<string, string> &bpe) {
int fd = safeOpen(fp, O_RDONLY);
auto fdOut = safeOpen(fpo, O_RDWR | O_CREAT | O_TRUNC, 0666);
struct stat s;
fstat(fd, &s);
fprintf(stderr, "Applying BPE to %s ...\n", fp);
auto size = s.st_size;
char *f = (char *)mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, 0);
auto p = output_or_count(bpe, size, f, nullptr);
size_t out_size = p.first;
if (ftruncate(fdOut, out_size) < 0) {
fprintf(stderr, "Couldn't truncate output file %s to size %lu\n", fpo,
out_size);
exit(EXIT_FAILURE);
}
char *fo = (char *)mmap(NULL, out_size, PROT_WRITE, MAP_SHARED, fdOut, 0);
if (fo == MAP_FAILED) {
fprintf(stderr, "Output memory map failed : %d.\n", errno);
exit(EXIT_FAILURE);
}
p = output_or_count(bpe, size, f, fo);
fprintf(stderr, "Modified %lu words from text file.\n", p.second);
munmap(fo, out_size);
munmap(f, size);
close(fdOut);
close(fd);
}
struct pair_hash {
template <class T1, class T2> size_t operator()(const pair<T1, T2> &p) const {
auto h1 = hash<T1>{}(p.first);
auto h2 = hash<T2>{}(p.second);
size_t seed = h1;
// boost::hash_combine
return h2 + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
};
void tokenize(const unordered_map<string, uint32_t> &word_count,
unordered_map<string, uint32_t> &token_to_int,
vector<string> &int_to_token, vector<list<uint32_t>> &words,
vector<int32_t> &counts) {
for (auto &x : word_count) {
auto &word = x.first;
words.push_back(list<uint32_t>());
auto ¤t_word = words.back();
counts.push_back(x.second);
int pos = 0, realLength = 0;
int lastStart = 0;
while (word[pos]) {
bool newChar = (word[pos] & 0xc0) != 0x80; // not a continuation byte
realLength += newChar;
// new token
if (newChar && pos > 0) {
auto new_token = word.substr(lastStart, pos - lastStart);
if (token_to_int.count(new_token) == 0) {
int_to_token.push_back(new_token);
token_to_int[new_token] = int_to_token.size() - 1;
}
current_word.push_back(token_to_int[new_token]);
lastStart = pos;
}
pos++;
}
auto new_token = word.substr(lastStart, string::npos) + kEndWord;
if (token_to_int.count(new_token) == 0) {
int_to_token.push_back(new_token);
token_to_int[new_token] = int_to_token.size() - 1;
}
current_word.push_back(token_to_int[new_token]);
}
}
void tokenize_str(const unordered_map<string, uint32_t> &word_count,
unordered_map<string, vector<string>> &words) {
for (auto &x : word_count) {
auto &word = x.first;
words[word] = vector<string>();
int pos = 0, realLength = 0;
int lastStart = 0;
while (word[pos]) {
bool newChar = (word[pos] & 0xc0) != 0x80; // not a continuation byte
realLength += newChar;
// new token
if (newChar && pos > 0) {
auto new_token = word.substr(lastStart, pos - lastStart);
words[word].push_back(new_token);
lastStart = pos;
}
pos++;
}
auto new_token = word.substr(lastStart, string::npos) + kEndWord;
words[word].push_back(new_token);
}
}
using tp = pair<uint32_t, uint32_t>;
using tps = pair<string, string>;
using ctp = pair<int32_t, tp>;
using pc = unordered_map<tp, ctp *, pair_hash>;
void count_in_word(
list<uint32_t> &word, uint32_t wi, uint32_t count, pc &pair_counts,
vector<pair<int32_t, tp>> &contiguous_counts,
unordered_map<tp, unordered_set<uint32_t>, pair_hash> &where) {
bool second = false;
tp cur_pair;
for (uint32_t token : word) {
if (second) {
cur_pair.first = cur_pair.second;
}
cur_pair.second = token;
if (second) {
auto it = pair_counts.find(cur_pair);
if (it == pair_counts.end()) {
contiguous_counts.emplace_back(0, cur_pair);
auto *added = &contiguous_counts.back();
pair_counts.emplace(piecewise_construct, forward_as_tuple(cur_pair),
forward_as_tuple(added));
where[cur_pair].emplace();
}
if (count > 0) {
where[cur_pair].insert(wi);
} else {
where[cur_pair].erase(wi);
}
pair_counts[cur_pair]->first += count;
} else {
second = true;
}
}
}
void find_maxp(vector<pair<int32_t, tp>> &contiguous_counts, tp &maxp,
int32_t &max_c) {
max_c = 0;
for (const ctp &x : contiguous_counts) {
if (x.first > max_c) {
max_c = x.first;
maxp = x.second;
} else if (x.first == max_c and x.second < maxp) {
maxp = x.second;
}
}
}
void getvocab(const char *inputFile1, const char *inputFile2) {
// get vocab
unordered_map<string, uint32_t> word_count;
readText(inputFile1, word_count);
if (strcmp(inputFile2, "") != 0) {
readText(inputFile2, word_count);
}
// sort vocab
auto compFunctor = [](pair<string, int> elem1, pair<string, int> elem2) {
return elem1.second > elem2.second ||
(elem1.second == elem2.second && elem1.first < elem2.first);
};
set<pair<string, int>, decltype(compFunctor)> sorted_vocab(
word_count.begin(), word_count.end(), compFunctor);
assert(word_count.size() == sorted_vocab.size());
// print sorted vocab
for (auto element : sorted_vocab)
cout << element.first << " " << element.second << endl;
}
void learnbpe(const uint32_t kNPairs, const char *inputFile1,
const char *inputFile2) {
// get vocab
unordered_map<string, uint32_t> word_count;
readText(inputFile1, word_count);
if (strcmp(inputFile2, "") != 0) {
readText(inputFile2, word_count);
}
// a token is an int, it represents a string
unordered_map<string, uint32_t> token_to_int;
vector<string> int_to_token;
vector<list<uint32_t>> words;
vector<int32_t> counts;
tokenize(word_count, token_to_int, int_to_token, words, counts);
vector<pair<int32_t, tp>> contiguous_counts;
contiguous_counts.reserve(kMaxPairs);
pc pair_counts;
unordered_map<tp, unordered_set<uint32_t>, pair_hash> where_to_update;
tp cur_pair;
int32_t max_c = 0;
tp max_p;
for (uint32_t wi = 0; wi < words.size(); wi++) {
count_in_word(words[wi], wi, counts[wi], pair_counts, contiguous_counts,
where_to_update);
}
find_maxp(contiguous_counts, max_p, max_c);
for (size_t i = 0; i < kNPairs; i++) {
if (max_c == 0) {
break;
}
// create new token for pair. replace
auto new_token = int_to_token[max_p.first] + int_to_token[max_p.second];
cout << int_to_token[max_p.first] << " " << int_to_token[max_p.second]
<< " " << max_c << endl;
uint32_t new_token_id = int_to_token.size();
int_to_token.push_back(new_token);
token_to_int[new_token] = new_token_id;
max_c = 0;
auto change_count = [&](tp pair, int32_t v, uint32_t wi) {
auto it = pair_counts.find(pair);
if (it != pair_counts.end()) {
// assert(it->second + v >= 0);
it->second->first += v;
} else {
if (v > 0) {
contiguous_counts.emplace_back(v, pair);
pair_counts.emplace(piecewise_construct, forward_as_tuple(pair),
forward_as_tuple(&(contiguous_counts.back())));
where_to_update[pair] = unordered_set<uint32_t>();
}
}
if (v > 0)
where_to_update[pair].insert(wi);
};
for (auto wi : where_to_update[max_p]) {
auto &cur_word = words[wi];
auto it = cur_word.begin();
bool second = false;
while (it != cur_word.end()) {
if (second) {
cur_pair.first = cur_pair.second;
}
cur_pair.second = *it;
if (second) {
// found the pair
if (cur_pair == max_p) {
it--; // points to first element of pair
// if there is a token before us
if (it != cur_word.begin()) {
it--;
change_count(make_pair(*it, cur_pair.first), -counts[wi], wi);
change_count(make_pair(*it, new_token_id), counts[wi], wi);
it++;
}
it = cur_word.insert(it, new_token_id); // it points to new token
it++; // it points to first element of pair
it = cur_word.erase(it); // it points to second element of pair
it = cur_word.erase(it); // it points to next value
// if there is a token after the one we inserted
if (it != cur_word.end()) {
change_count(make_pair(cur_pair.second, *it), -counts[wi], wi);
change_count(make_pair(new_token_id, *it), counts[wi], wi);
}
cur_pair.second = new_token_id;
} else {
it++;
}
} else {
second = true;
it++;
}
}
}
if (pair_counts.find(max_p) != pair_counts.end()){
pair_counts[max_p]->first = 0;
}
find_maxp(contiguous_counts, max_p, max_c);
}
}
void split(vector<string> &splits, const string &text, char sep) {
size_t start = 0, end = 0;
while ((end = text.find(sep, start)) != string::npos) {
if (end != start)
splits.push_back(text.substr(start, end - start));
start = end + 1;
}
if (end != start && start < text.size())
splits.push_back(text.substr(start));
}
void readVocab(const char *fp, unordered_map<string, uint32_t> &vocab) {
ifstream file(fp);
if (!file) {
fprintf(stderr, "Cannot open vocabulary file %s\n", fp);
exit(EXIT_FAILURE);
}
fprintf(stderr, "Loading vocabulary from %s ...\n", fp);
string line;
uint64_t total = 0;
while (getline(file, line)) {
vector<string> splits;
split(splits, line, ' ');
assert(splits.size() == 2);
assert(vocab.find(splits[0]) == vocab.end());
int count = stoi(splits[1]);
vocab[splits[0]] = count;
total += count;
}
fprintf(stderr, "Read %lu words (%lu unique) from vocabulary file.\n", total,
vocab.size());
}
void readCodes(const char *fp, unordered_map<tps, uint32_t, pair_hash> &codes,
unordered_map<string, tps> &reversed_codes) {
ifstream file(fp);
if (!file) {
fprintf(stderr, "Cannot open codes file %s\n", fp);
exit(EXIT_FAILURE);
}
fprintf(stderr, "Loading codes from %s ...\n", fp);
string line;
while (getline(file, line)) {
vector<string> splits;
split(splits, line, ' ');
assert(splits.size() == 3);
auto pair = make_pair(splits[0], splits[1]);
string concat = splits[0] + splits[1];
assert(codes.find(pair) == codes.end());
assert(reversed_codes.find(concat) == reversed_codes.end());
codes[pair] = codes.size();
reversed_codes[concat] = pair;
}
fprintf(stderr, "Read %lu codes from the codes file.\n", codes.size());
}
void decompose(const string s, vector<string> &newSubwords,
const unordered_map<string, tps> &reversed_codes,
const unordered_map<string, uint32_t> &vocab, bool isFinal) {
auto it = reversed_codes.find(s);
if (it == reversed_codes.end()) {
// TODO this whole block below is just some sanity check
// if we cannot un-merge a subword, it has to be a char
string s2 = isFinal ? s.substr(0, s.size() - kEndWordLength) : s;
int count = 0;
for (size_t j = 0; j < s2.size(); j++) {
if ((s2[j] & 0xc0) != 0x80) {
count++;
}
}
assert(count == 1);
newSubwords.push_back(s);
return;
}
assert(it != reversed_codes.end());
string token1 = it->second.first;
if (vocab.find(token1 + kTokenDelim) == vocab.end()) {
decompose(token1, newSubwords, reversed_codes, vocab, false);
} else {
newSubwords.push_back(token1);
}
string token2 = it->second.second;
auto query = token2 + kTokenDelim;
if (isFinal) {
query = token2.substr(0, token2.size() - kEndWordLength);
}
if (vocab.find(query) == vocab.end()) {
decompose(token2, newSubwords, reversed_codes, vocab, isFinal);
} else {
newSubwords.push_back(token2);
}
}
void limitVocab(const vector<string> &subwords, vector<string> &newSubwords,
const unordered_map<string, tps> &reversed_codes,
const unordered_map<string, uint32_t> &vocab) {
string query;
for (size_t i = 0; i < subwords.size(); i++) {
bool isFinal = i == subwords.size() - 1;
auto &subword = subwords[i];
if (isFinal) {
query = subword.substr(0, subword.size() - kEndWordLength);
} else {
query = subword + kTokenDelim;
}
if (vocab.find(query) == vocab.end()) {
decompose(subword, newSubwords, reversed_codes, vocab, isFinal);
} else {
newSubwords.push_back(subword);
}
}
}
string process_bpe(vector<string> &subwords,
unordered_map<tps, uint32_t, pair_hash> &codes,
unordered_map<string, tps> &reversed_codes,
unordered_map<string, uint32_t> &vocab) {
// merge subWords as much as possible
vector<string> newSubwords;
while (subwords.size() > 1) {
// find the best pair
int bestPairId = -1;
auto bestPair = codes.end(); // TODO ugly hack that works
for (size_t i = 0; i < subwords.size() - 1; i++) {
auto pair = make_pair(subwords[i], subwords[i + 1]);
auto it = codes.find(pair);
int pairRank = it == codes.end() ? -1 : it->second;
if (pairRank >= 0 && (bestPairId == -1 || int(bestPair->second) > pairRank)) {
bestPair = it;
bestPairId = i;
}
}
// if we cannot merge anything, stop
if (bestPairId == -1) {
break;
}
// otherwise, merge subWords
bool justMerged = false;
newSubwords = vector<string>();
for (size_t i = 0; i < subwords.size(); i++) {
if ((i + 1 < subwords.size()) && (not justMerged) &&
subwords[i] == bestPair->first.first &&
subwords[i + 1] == bestPair->first.second) {
newSubwords.push_back(subwords[i] + subwords[i + 1]);
justMerged = true;
} else {
if (not justMerged) {
newSubwords.push_back(subwords[i]);
}
justMerged = false;
}
}
subwords = newSubwords;
}
// check that we are only using words in the dictionary
if (vocab.size() > 0) {
vector<string> newSubwords;
limitVocab(subwords, newSubwords, reversed_codes, vocab);
subwords = newSubwords;
}
// concat subWords
string result;
for (auto x : subwords) {
result = result + x + kTokenDelim + " ";
}
return result.substr(
0,
result.size() - kEndWordLength - kTokenDelimLength - 1 // "</w>@@ "
);
}
void applybpe(const char *outputFile, const char *inputFile,
const char *codesPath, const char *vocabPath) {
// read vocabulary (to which we want to limit the output file)
unordered_map<string, uint32_t> vocab;
if (strcmp(vocabPath, "") != 0) {
readVocab(vocabPath, vocab);
}
// read codes
unordered_map<tps, uint32_t, pair_hash> codes;
unordered_map<string, tps> reversed_codes;
readCodes(codesPath, codes, reversed_codes);
// read input file words
unordered_map<string, uint32_t> word_count;
readText(inputFile, word_count);
// tokenize
unordered_map<string, vector<string>> bpeTok;
tokenize_str(word_count, bpeTok);
vector<pair<string, vector<string>>> bpeTokVec;
for (auto x : bpeTok) {
bpeTokVec.push_back(x);
}
// apply BPE codes to each word
unordered_map<string, string> bpe[kThreads];
vector<thread> threads;
for (size_t i = 0; i < kThreads; i++) {
threads.emplace_back(
[&](size_t this_thread) {
for (size_t w = this_thread; w < bpeTokVec.size(); w += kThreads) {
auto &x = bpeTokVec[w];
bpe[this_thread][x.first] = process_bpe(x.second, codes, reversed_codes, vocab);
}
},
i
);
}
unordered_map<string, string> final_bpe;
for (size_t i = 0; i < kThreads; i++) {
threads[i].join();
for (auto x : bpe[i]) {
final_bpe[x.first] = x.second;
}
}
// output
outputText(outputFile, inputFile, final_bpe);
}
class BPEApplyer {
private:
unordered_map<string, uint32_t> vocab;
unordered_map<tps, uint32_t, pair_hash> codes;
unordered_map<string, tps> reversed_codes;
public:
BPEApplyer(const string& codesPath, const string& vocabPath) {
if (vocabPath.size() > 0) readVocab(vocabPath.c_str(), vocab);
readCodes(codesPath.c_str(), codes, reversed_codes);
}
vector<string> apply(vector<string>& sentences) {
vector<string> res;
for(auto &s: sentences) {
res.emplace_back("");
string& cur = res.back();
vector<string> words;
split(words, s, ' ');
for (size_t i = 0; i < words.size(); i++) {
auto word = words[i];
vector<string> word_bpes;
int pos = 0, realLength = 0;
int lastStart = 0;
while (word[pos]) {
bool newChar = (word[pos] & 0xc0) != 0x80; // not a continuation byte
realLength += newChar;
if (newChar && pos > 0) {
auto new_token = word.substr(lastStart, pos - lastStart);
word_bpes.push_back(new_token);
lastStart = pos;
}
pos++;
}
auto bpe = word.substr(lastStart, string::npos) + kEndWord;
word_bpes.push_back(bpe);
cur += process_bpe(word_bpes, codes, reversed_codes, vocab);
if (i < words.size() - 1) cur += " ";
}
}
return res;
}
};
void applybpe_stream(const char *codesPath, const char *vocabPath) {
BPEApplyer applyer(codesPath, vocabPath);
std::string line;
while(std::getline(std::cin, line)) {
vector<string> tmp;
tmp.push_back(line);
for(auto& l : applyer.apply(tmp)){
std::cout << l << std::endl;
}
}
}
};
|
#include <whiskey/AST/NodeType.hpp>
namespace whiskey {
namespace {
NodeTypeInfo nodeTypeInfos[] {
NodeTypeInfo("None", NodeTypeCategory::None, {}),
NodeTypeInfo("List", NodeTypeCategory::Internal, {FieldTag::List_Children}),
NodeTypeInfo("TypeVoid", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicBool", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicInt8", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicInt16", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicInt32", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicInt64", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicUInt8", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicUInt16", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicUInt32", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicUInt64", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicFloat32", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicFloat64", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeAtomicReal", NodeTypeCategory::Type, {}),
NodeTypeInfo("TypeSymbol", NodeTypeCategory::Type, {FieldTag::TypeSymbol_TemplateEvalArgs}),
NodeTypeInfo("TypeAccessUnary", NodeTypeCategory::Type, {FieldTag::TypeAccessUnary_Arg}),
NodeTypeInfo("TypeAccess", NodeTypeCategory::Type, {FieldTag::TypeAccess_Args}),
NodeTypeInfo("TypeGroup", NodeTypeCategory::Type, {FieldTag::TypeGroup_Arg}),
NodeTypeInfo("TypeFunction", NodeTypeCategory::Expr, {FieldTag::TypeFunction_Return, FieldTag::TypeFunction_Args}),
NodeTypeInfo("ExprLiteralBool", NodeTypeCategory::Expr, {FieldTag::ExprLiteralBool_Value}),
NodeTypeInfo("ExprLiteralInt8", NodeTypeCategory::Expr, {FieldTag::ExprLiteralInt8_Value}),
NodeTypeInfo("ExprLiteralInt16", NodeTypeCategory::Expr, {FieldTag::ExprLiteralInt16_Value}),
NodeTypeInfo("ExprLiteralInt32", NodeTypeCategory::Expr, {FieldTag::ExprLiteralInt32_Value}),
NodeTypeInfo("ExprLiteralInt64", NodeTypeCategory::Expr, {FieldTag::ExprLiteralInt64_Value}),
NodeTypeInfo("ExprLiteralUInt8", NodeTypeCategory::Expr, {FieldTag::ExprLiteralUInt8_Value}),
NodeTypeInfo("ExprLiteralUInt16", NodeTypeCategory::Expr, {FieldTag::ExprLiteralUInt16_Value}),
NodeTypeInfo("ExprLiteralUInt32", NodeTypeCategory::Expr, {FieldTag::ExprLiteralUInt32_Value}),
NodeTypeInfo("ExprLiteralUInt64", NodeTypeCategory::Expr, {FieldTag::ExprLiteralUInt64_Value}),
NodeTypeInfo("ExprLiteralChar8", NodeTypeCategory::Expr, {FieldTag::ExprLiteralChar8_Value}),
NodeTypeInfo("ExprLiteralChar16", NodeTypeCategory::Expr, {FieldTag::ExprLiteralChar16_Value}),
NodeTypeInfo("ExprLiteralChar32", NodeTypeCategory::Expr, {FieldTag::ExprLiteralChar32_Value}),
NodeTypeInfo("ExprLiteralFloat32", NodeTypeCategory::Expr, {FieldTag::ExprLiteralFloat32_Value}),
NodeTypeInfo("ExprLiteralFloat64", NodeTypeCategory::Expr, {FieldTag::ExprLiteralFloat64_Value}),
NodeTypeInfo("ExprLiteralReal", NodeTypeCategory::Expr, {FieldTag::ExprLiteralReal_Value}),
NodeTypeInfo("ExprSymbol", NodeTypeCategory::Expr, {FieldTag::ExprSymbol_TemplateEvalArgs}),
NodeTypeInfo("ExprAccessUnary", NodeTypeCategory::Expr, {FieldTag::ExprAccessUnary_Arg}),
NodeTypeInfo("ExprAccess", NodeTypeCategory::Expr, {FieldTag::ExprAccess_Args}),
NodeTypeInfo("ExprGroup", NodeTypeCategory::Expr, {FieldTag::ExprGroup_Arg}),
NodeTypeInfo("ExprCall", NodeTypeCategory::Expr, {FieldTag::ExprCall_Callee, FieldTag::ExprCall_Args}),
NodeTypeInfo("ExprAdd", NodeTypeCategory::Expr, {FieldTag::ExprAdd_Args}),
NodeTypeInfo("ExprIncPre", NodeTypeCategory::Expr, {FieldTag::ExprIncPre_Arg}),
NodeTypeInfo("ExprIncPost", NodeTypeCategory::Expr, {FieldTag::ExprIncPost_Arg}),
NodeTypeInfo("ExprSub", NodeTypeCategory::Expr, {FieldTag::ExprSub_LHS, FieldTag::ExprSub_RHS}),
NodeTypeInfo("ExprNeg", NodeTypeCategory::Expr, {FieldTag::ExprNeg_Arg}),
NodeTypeInfo("ExprDecPre", NodeTypeCategory::Expr, {FieldTag::ExprDecPre_Arg}),
NodeTypeInfo("ExprDecPost", NodeTypeCategory::Expr, {FieldTag::ExprDecPost_Arg}),
NodeTypeInfo("ExprMul", NodeTypeCategory::Expr, {FieldTag::ExprMul_Args}),
NodeTypeInfo("ExprExp", NodeTypeCategory::Expr, {FieldTag::ExprExp_LHS, FieldTag::ExprExp_RHS}),
NodeTypeInfo("ExprDiv", NodeTypeCategory::Expr, {FieldTag::ExprDiv_LHS, FieldTag::ExprDiv_RHS}),
NodeTypeInfo("ExprDivInt", NodeTypeCategory::Expr, {FieldTag::ExprDivInt_LHS, FieldTag::ExprDivInt_RHS}),
NodeTypeInfo("ExprDivReal", NodeTypeCategory::Expr, {FieldTag::ExprDivReal_LHS, FieldTag::ExprDivReal_RHS}),
NodeTypeInfo("ExprMod", NodeTypeCategory::Expr, {FieldTag::ExprMod_LHS, FieldTag::ExprMod_RHS}),
NodeTypeInfo("ExprBitNot", NodeTypeCategory::Expr, {FieldTag::ExprBitNot_Arg}),
NodeTypeInfo("ExprBitAnd", NodeTypeCategory::Expr, {FieldTag::ExprBitAnd_Args}),
NodeTypeInfo("ExprBitOr", NodeTypeCategory::Expr, {FieldTag::ExprBitOr_Args}),
NodeTypeInfo("ExprBitXor", NodeTypeCategory::Expr, {FieldTag::ExprBitXor_Args}),
NodeTypeInfo("ExprBitShL", NodeTypeCategory::Expr, {FieldTag::ExprBitShL_LHS, FieldTag::ExprBitShL_RHS}),
NodeTypeInfo("ExprBitShR", NodeTypeCategory::Expr, {FieldTag::ExprBitShR_LHS, FieldTag::ExprBitShR_RHS}),
NodeTypeInfo("ExprLT", NodeTypeCategory::Expr, {FieldTag::ExprLT_LHS, FieldTag::ExprLT_RHS}),
NodeTypeInfo("ExprLE", NodeTypeCategory::Expr, {FieldTag::ExprLE_LHS, FieldTag::ExprLE_RHS}),
NodeTypeInfo("ExprGT", NodeTypeCategory::Expr, {FieldTag::ExprGT_LHS, FieldTag::ExprGT_RHS}),
NodeTypeInfo("ExprGE", NodeTypeCategory::Expr, {FieldTag::ExprGE_LHS, FieldTag::ExprGE_RHS}),
NodeTypeInfo("ExprNE", NodeTypeCategory::Expr, {FieldTag::ExprNE_LHS, FieldTag::ExprNE_RHS}),
NodeTypeInfo("ExprEQ", NodeTypeCategory::Expr, {FieldTag::ExprEQ_LHS, FieldTag::ExprEQ_RHS}),
NodeTypeInfo("ExprBoolNot", NodeTypeCategory::Expr, {FieldTag::ExprBoolNot_Arg}),
NodeTypeInfo("ExprBoolAnd", NodeTypeCategory::Expr, {FieldTag::ExprBoolAnd_Args}),
NodeTypeInfo("ExprBoolOr", NodeTypeCategory::Expr, {FieldTag::ExprBoolOr_Args}),
NodeTypeInfo("ExprBoolImplies", NodeTypeCategory::Expr, {FieldTag::ExprBoolImplies_Args}),
NodeTypeInfo("ExprAddAssign", NodeTypeCategory::Expr, {FieldTag::ExprAddAssign_LHS, FieldTag::ExprAddAssign_RHS}),
NodeTypeInfo("ExprSubAssign", NodeTypeCategory::Expr, {FieldTag::ExprSubAssign_LHS, FieldTag::ExprSubAssign_RHS}),
NodeTypeInfo("ExprMulAssign", NodeTypeCategory::Expr, {FieldTag::ExprMulAssign_LHS, FieldTag::ExprMulAssign_RHS}),
NodeTypeInfo("ExprExpAssign", NodeTypeCategory::Expr, {FieldTag::ExprExpAssign_LHS, FieldTag::ExprExpAssign_RHS}),
NodeTypeInfo("ExprDivAssign", NodeTypeCategory::Expr, {FieldTag::ExprDivAssign_LHS, FieldTag::ExprDivAssign_RHS}),
NodeTypeInfo("ExprDivIntAssign", NodeTypeCategory::Expr, {FieldTag::ExprDivIntAssign_LHS, FieldTag::ExprDivIntAssign_RHS}),
NodeTypeInfo("ExprDivRealAssign", NodeTypeCategory::Expr, {FieldTag::ExprDivRealAssign_LHS, FieldTag::ExprDivRealAssign_RHS}),
NodeTypeInfo("ExprModAssign", NodeTypeCategory::Expr, {FieldTag::ExprModAssign_LHS, FieldTag::ExprModAssign_RHS}),
NodeTypeInfo("ExprBitAndAssign", NodeTypeCategory::Expr, {FieldTag::ExprBitAndAssign_LHS, FieldTag::ExprBitAndAssign_RHS}),
NodeTypeInfo("ExprBitOrAssign", NodeTypeCategory::Expr, {FieldTag::ExprBitOrAssign_LHS, FieldTag::ExprBitOrAssign_RHS}),
NodeTypeInfo("ExprBitXorAssign", NodeTypeCategory::Expr, {FieldTag::ExprBitXorAssign_LHS, FieldTag::ExprBitXorAssign_RHS}),
NodeTypeInfo("ExprBitShLAssign", NodeTypeCategory::Expr, {FieldTag::ExprBitShLAssign_LHS, FieldTag::ExprBitShLAssign_RHS}),
NodeTypeInfo("ExprBitShRAssign", NodeTypeCategory::Expr, {FieldTag::ExprBitShRAssign_LHS, FieldTag::ExprBitShRAssign_RHS}),
NodeTypeInfo("ExprAssign", NodeTypeCategory::Expr, {FieldTag::ExprAssign_LHS, FieldTag::ExprAssign_RHS}),
NodeTypeInfo("StmtEmpty", NodeTypeCategory::Stmt, {}),
NodeTypeInfo("StmtExpr", NodeTypeCategory::Stmt, {FieldTag::StmtExpr_Expr}),
NodeTypeInfo("StmtDecl", NodeTypeCategory::Stmt, {FieldTag::StmtDecl_Decl}),
NodeTypeInfo("StmtReturn", NodeTypeCategory::Stmt, {FieldTag::StmtReturn_Arg}),
NodeTypeInfo("StmtContinue", NodeTypeCategory::Stmt, {FieldTag::StmtContinue_Name}),
NodeTypeInfo("StmtBreak", NodeTypeCategory::Stmt, {FieldTag::StmtBreak_Name}),
NodeTypeInfo("StmtIf", NodeTypeCategory::Stmt, {FieldTag::StmtIf_Condition, FieldTag::StmtIf_Then, FieldTag::StmtIf_Else}),
NodeTypeInfo("StmtWhile", NodeTypeCategory::Stmt, {FieldTag::StmtWhile_Condition, FieldTag::StmtWhile_Body, FieldTag::StmtWhile_Name}),
NodeTypeInfo("StmtFor", NodeTypeCategory::Stmt, {FieldTag::StmtFor_Decls, FieldTag::StmtFor_Condition, FieldTag::StmtFor_Steps, FieldTag::StmtFor_Body, FieldTag::StmtFor_Name}),
NodeTypeInfo("StmtForEach", NodeTypeCategory::Stmt, {FieldTag::StmtForEach_Decl, FieldTag::StmtForEach_Sequence, FieldTag::StmtForEach_Body, FieldTag::StmtForEach_Name}),
NodeTypeInfo("StmtBlock", NodeTypeCategory::Stmt, {FieldTag::StmtBlock_Stmts, FieldTag::StmtBlock_Scope}),
NodeTypeInfo("DeclVariable", NodeTypeCategory::Decl, {FieldTag::DeclVariable_Type, FieldTag::DeclVariable_TemplateDeclArgs, FieldTag::DeclVariable_Initial}),
NodeTypeInfo("DeclFunction", NodeTypeCategory::Decl, {FieldTag::DeclFunction_Return, FieldTag::DeclFunction_TemplateDeclArgs, FieldTag::DeclFunction_Args, FieldTag::DeclFunction_Body, FieldTag::DeclFunction_Scope}),
NodeTypeInfo("DeclClass", NodeTypeCategory::Decl, {FieldTag::DeclClass_TemplateDeclArgs, FieldTag::DeclClass_Inherits, FieldTag::DeclClass_Members, FieldTag::DeclClass_Scope}),
NodeTypeInfo("DeclNamespace", NodeTypeCategory::Decl, {FieldTag::DeclNamespace_Members, FieldTag::DeclNamespace_Scope}),
NodeTypeInfo("Import", NodeTypeCategory::Import, {FieldTag::Import_Path}),
NodeTypeInfo("Unit", NodeTypeCategory::Unit, {FieldTag::Unit_Members, FieldTag::Unit_Scope})
};
}
bool evalNodeType(const std::string &text, NodeType &value) {
for (size_t i = 0; i < sizeof(nodeTypeInfos) / sizeof(NodeTypeInfo); ++i) {
if (nodeTypeInfos[i].getName() == text) {
value = static_cast<NodeType>(i);
return true;
}
}
return false;
}
bool evalFieldTag(NodeType nodeType, const std::string &text, FieldTag &value) {
for (FieldTag j : nodeTypeInfos[static_cast<ssize_t>(nodeType)].getFields()) {
if (FieldTagInfo::get(j).getName() == text) {
value = j;
return true;
}
}
return false;
}
std::ostream &operator<<(std::ostream &os, NodeType value) {
os << NodeTypeInfo::get(value).getName();
return os;
}
std::ostream &operator<<(std::ostream &os, NodeTypeCategory value) {
switch (value) {
case NodeTypeCategory::None:
os << "None";
break;
case NodeTypeCategory::Internal:
os << "Internal";
break;
case NodeTypeCategory::Type:
os << "Type";
break;
case NodeTypeCategory::Expr:
os << "Expr";
break;
case NodeTypeCategory::Stmt:
os << "Stmt";
break;
case NodeTypeCategory::Decl:
os << "Decl";
break;
case NodeTypeCategory::Import:
os << "Import";
break;
case NodeTypeCategory::Unit:
os << "Unit";
break;
}
return os;
}
const NodeTypeInfo &NodeTypeInfo::get(NodeType type) {
return nodeTypeInfos[static_cast<int>(type)];
}
NodeTypeInfo::NodeTypeInfo(std::string name, NodeTypeCategory category, std::initializer_list<FieldTag> fields) : name(name), category(category), fields(fields) {}
const std::string &NodeTypeInfo::getName() const {
return name;
}
NodeTypeCategory NodeTypeInfo::getCategory() const {
return category;
}
const std::vector<FieldTag> &NodeTypeInfo::getFields() const {
return fields;
}
}
|
#pragma once
#include <math/common.h>
#include <lua/common.h>
namespace glm {
inline static void bind(lua_State* L)
{
using namespace LuaIntf;
LuaBinding(L).beginClass<vec3>("vec3")
.addConstructor(LUA_ARGS(_opt<float>, _opt<float>, _opt<float>))
.addVariable("x", &vec3::x)
.addVariable("y", &vec3::y)
.addVariable("z", &vec3::z)
.addStaticFunction("add", [](const vec3& a, const vec3& b){ return a+b; })
.addStaticFunction("sub", [](const vec3& a, const vec3& b){ return a-b; })
.addStaticFunction("mul", [](const vec3& a, const vec3& b){ return a*b; })
.addStaticFunction("div", [](const vec3& a, const vec3& b){ return a/b; })
.addStaticFunction("dot", [](const vec3& a, const vec3& b){ return dot(a, b); })
.addStaticFunction("cross", [](const vec3& a, const vec3& b){ return cross(a, b); })
.addStaticFunction("length", [](const vec3& v){ return length(v); })
.addStaticFunction("normalize", [](const vec3& v){ return normalize(v); })
.endClass();
}
} // glm
|
#include "Region.h"
Region::Region(std::string _name)
{
this->name = _name;
}
Region::~Region()
{
//dtor
}
ZLevel* Region::GetLevel(int z)
{
try
{
return levels.at(z);
}
catch (std::out_of_range& e)
{
return NULL;
}
}
void Region::SetLevel(ZLevel* level, int z)
{
try
{
levels.at(z) = level;
}
catch (std::out_of_range& e)
{
levels.push_back(level);
}
}
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* Licensed under the Apache License, Version 2.0(the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef __REF_COUNT_H__
#define __REF_COUNT_H__
#include <mutex>
namespace sc {
class RefCount {
public:
int get_value(void) {
std::unique_lock<std::mutex> lck(this->mLock);
return this->mCount;
}
int increase(void) {
std::unique_lock<std::mutex> lck(this->mLock);
this->mCount++;
return this->mCount;
}
int decrease(void) {
std::unique_lock<std::mutex> lck(this->mLock);
this->mCount--;
return this->mCount;
}
RefCount(void) {
this->mCount = 0;
}
protected:
int mCount;
std::mutex mLock;
}; /* class RefCount */
} /* namespace sc */
#endif /* !defined(__REF_COUNT_H__) */
|
#include "structure.h"
#include "constantes.h"
void affichergrille(SDL_Surface *affichage, int x, int y)
{
SDL_Surface *grille=NULL;
SDL_Rect grilleposition;
grille = SDL_LoadBMP("grille.bmp");
SDL_SetColorKey(grille, SDL_SRCCOLORKEY, SDL_MapRGB(grille->format, 255, 255, 255));
grilleposition.x = x;
grilleposition.y = y;
SDL_BlitSurface(grille, NULL, affichage, &grilleposition);
SDL_FreeSurface(grille);
};
void ecriretexte(SDL_Surface *affichage, char phrase[200], TTF_Font *police_ecrire, SDL_Color couleur_police, int x, int y)
{
SDL_Surface *texte;
SDL_Rect texteposition;
texte = TTF_RenderText_Blended(police_ecrire, phrase, couleur_police);
texteposition.x = x;
texteposition.y = y;
SDL_BlitSurface(texte, NULL, affichage, &texteposition);
SDL_FreeSurface(texte);
};
int casechoisie(SDL_Surface *affichage, int eventx, int eventy, int IndexX, int IndexY, int *pointeurX, int *pointeurY) // on lui indique la position cliquée, ainsi que l'index de la grille (l'index de la premiere grille est le point en haut à gauche de la case A1).
{
for(int i=1;i<11;i++)
{
if (((IndexX+LargeurCase<eventx)&&(eventx<IndexX+LargeurCase*11))&&((IndexY+HauteurCase<eventy)&&(eventy<IndexY+HauteurCase*11)))
{
if ((IndexX+i*LargeurCase < eventx) && (eventx < IndexX+LargeurCase+i*LargeurCase))
{
*pointeurX = i;
}
if ((IndexY+i*HauteurCase < eventy) && (eventy < IndexY+HauteurCase+i*HauteurCase))
{
*pointeurY = i;
}
}
}
};
void dessinernavire(SDL_Surface *affichage, TBateau bateau, TIndexGrille grillepos)
{
SDL_Surface *bateau=NULL;
SDL_Rect beateaupos;
bateau = SDL_LoadBMP(bateau.cheminskin);
beateaupos.x = x;
beateaupos.y = y;
SDL_BlitSurface(bateau, NULL, affichage, &beateaupos);
SDL_FreeSurface(bateau);
};
|
/*
* ADEXTENDER.h
*
* Created on: Jun 14, 2016
* Author: Prustya
*/
#ifndef ADEXTENDER_H_
#define ADEXTENDER_H_
// ---------- SYSTEM INCLUDE --------------------------------------------------------------------- //
#if ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
#include "AD533X_type.h"
#include "ADS101X_type.h"
#include "AD7124_regs.h"
#include "AD7124_def.h"
#include <Wire.h>
#include <SPI.h>
// ---------- EXTERNAL MODULE INCLUDE ------------------------------------------------------------ //
// N/A
// ---------- PUBLIC PROGRAMMING DEFINE ---------------------------------------------------------- //
#define AD533X_DEFAULT_ADDRESS 0x0C
#define ADS101x_DEFAULT_ADDRESS 0x48
#define I2C_WR_BIT 0
#define I2C_RD_BIT 1
// ---------- ENUMERATOR DEFINITION -------------------------------------------------------------- //
typedef enum {
AD_EXTENDER_MODE_0_5_V = 0,
AD_EXTENDER_MODE_0_10_V,
AD_EXTENDERMODE_0_20_mA,
AD_EXTENDER_MODE_4_20_mA,
AD_EXTENDER_MODE_TC,
}E_ADEXTENDER_MODE;
typedef enum {
AD_EXTENDER_OUT_CH1 = 1,
AD_EXTENDER_OUT_CH2 = 2
}E_ADEXTENDER_OUT_CHANNEL;
typedef enum {
AD_EXTENDER_ADC_CH_0 = 0,
AD_EXTENDER_ADC_CH_1,
AD_EXTENDER_ADC_CH_2,
AD_EXTENDER_ADC_CH_3,
AD_EXTENDER_ADC_CH_4
}E_ADEXTENDER_ADC_CH;
typedef enum {
AD_DISABLE = 0,
AD_ENABLE
}E_ADEXTENDER_STA;
// ---------- TYPEDEF DATA TYPE DEFINITION ------------------------------------------------------- //
// N/A
// ---------- STRUCT OR UNION DATA TYPE DEFINITION ----------------------------------------------- //
// N/A
// ---------- PUBLIC MACRO DEFINITION ------------------------------------------------------------ //
// N/A
// ---------- EXTERN FUNCTION -------------------------------------------------------------------- //
// N/A
// ---------- EXTERN VARIABLE -------------------------------------------------------------------- //
// N/A
// ---------- CLASS DECLARATION ----------------------------------------------------------------- //
class ADEXTENDER {
public:
ADEXTENDER(void);
virtual ~ADEXTENDER();
uint8_t Begin(void);
uint8_t ADCSetZero(uint16_t u16Value);
uint8_t ADCSetSpan(uint16_t u16Value);
uint8_t DACSetZero(uint16_t u16Value);
uint8_t DACSetSpan(uint16_t u16Value);
uint8_t DACUpdateVaule(
AD533X_OUT_SEL eOutSelect,
AD533X_POWER_DOWN_MODE ePowerMode,
uint8_t bCLR,
uint8_t bLDAC,
uint16_t u16Value);
uint8_t DACUpdateVaule(
AD533X_OUT_SEL eOutSelect,
uint16_t u16Value);
uint8_t DACSetOutByVoltage(
E_ADEXTENDER_OUT_CHANNEL eChannal,
E_ADEXTENDER_MODE eMode,
uint16_t u16Volage);
uint8_t DACSetOutByCurrent(
E_ADEXTENDER_OUT_CHANNEL eChannal,
E_ADEXTENDER_MODE eMode,
uint16_t u16Current);
uint8_t ADCReset(void);
uint8_t ADCReadStatus(void);
uint8_t ADCRead(E_ADEXTENDER_ADC_CH eChannel, E_ADEXTENDER_MODE eMode, uint32_t pOut[], uint32_t pu32Step[]);
uint8_t ADCReadWithPrintOut(E_ADEXTENDER_ADC_CH eChannel, uint32_t pOut[]);
uint8_t ADCConfigControl(uint16_t u16Value);
uint8_t ADCSetChannelControl(E_ADEXTENDER_ADC_CH eCh, E_ADEXTENDER_STA eSta);
uint8_t ADCConfigChannel(E_ADEXTENDER_ADC_CH eCh, uint8_t u8config, E_ADEXTENDER_STA en);
uint16_t ADCGetConfigChannel(E_ADEXTENDER_ADC_CH eCh);
uint8_t ADCSetConfig(uint8_t u8Entry, uint8_t vrefSel, uint8_t pga);
uint16_t ADCGetConfig(uint8_t u8Entry);
uint8_t ADCSetReadTimeOut(uint16_t u16Interval);
private :
uint8_t aDCWriteErrorEn(uint32_t u32Value);
uint8_t aDCStartConversion(E_ADEXTENDER_ADC_CH eChannel);
uint8_t aDCGetConversionValue(uint32_t data[]);
// I2C read write function
uint8_t deviceWrite(uint8_t u8DevAddr, uint8_t u8Reg, uint16_t u16Value);
uint8_t deviceRead(uint8_t u8DevAddr, uint8_t u8Reg, uint16_t pu16Value[]);
// SIP read write function
uint8_t deviceSPIWrite(uint8_t u8Reg, uint8_t pu8Data[], uint8_t u8Length);
uint8_t deviceSPIRead(uint8_t u8Reg, uint8_t u8Length, uint8_t pu8DataOut[]);
uint8_t aDCReadRegister(ad7124_reg_access eRegister, uint8_t u8Size, uint32_t u32Out[]);
uint8_t aDCReadRegisterWithPrintOut(ad7124_reg_access eRegister, uint8_t u8Size, uint32_t u32Out[]);
uint8_t aDCWriteRegisterWithPrintOut(ad7124_reg_access eRegister,
uint32_t u32Value, uint8_t u8Size, uint8_t u8Verify);
uint8_t aDCWriteRegister(ad7124_reg_access eRegister,
uint32_t u32Value, uint8_t u8Size, uint8_t u8Verify);
uint8_t computeCRC8(uint8_t pBuf[], uint8_t bufSize);
private :
//uint8_t u8ADCAddress;
uint8_t u8DACAddress;
uint16_t u16ADCZero;
uint16_t u16ADCSpan;
uint16_t u16DACZero;
uint16_t u16DACSpan;
uint16_t u16VrefDAC;
uint16_t u16VrefADC;
uint16_t u16ADCResolution;
uint8_t u16DACResolution;
uint16_t u16ReadTimeout;
};
// ---------- END OF CLASS DECLARATION ---------------------------------------------------------- //
#endif /* ADEXTENDER_H_ */
|
#include "Light.h"
Light::Light(vec3 pos, vec3 dir, vec3 ambient, vec3 diffuse, vec3 specular, LType lType, int number) {
//Light position and direction
Lpos = pos;
Ldirection = dir;
//Light intensity value
Lambient = ambient;
Ldiffuse = diffuse;
Lspecular = specular;
//Light type and number
LightType = lType;
lightNumber = number;
switch (lType) {
case DIRECTIONAL:
break;
case POINT:
break;
case SPOT:
break;
default:
break;
}
}
void Light::SetAtt(float constant, float lineal, float quadratic) {
c1 = constant, c2 = lineal, c3 = quadratic;
}
void Light::SetAperture(float min, float max) {
MinAperture = min;
MaxAperture = max;
}
void Light::SetLight(Shader *shad, vec3 CamPos) {
std::string variable;
vec3 result;
glUniform3f(glGetUniformLocation(shad->Program, "viewPos"), CamPos.x, CamPos.y, CamPos.z);
switch (LightType){
case DIRECTIONAL:
//Light Direction
glUniform3f(glGetUniformLocation(shad->Program, "dlight.direction"), Ldirection.x, Ldirection.y, Ldirection.z);
//Ambiental light
result = Lambient;
glUniform3f(glGetUniformLocation(shad->Program, "dlight.ambient"), result.x, result.y, result.z);
result = vec3(0.0);
//Diffuse light
result = Ldiffuse;
glUniform3f(glGetUniformLocation(shad->Program, "dlight.diffuse"), result.x, result.y, result.z);
result = vec3(0.0);
//Specular light
result = Lspecular;
glUniform3f(glGetUniformLocation(shad->Program, "dlight.specular"), result.x, result.y, result.z);
result = vec3(0.0);
//Light color
glUniform3f(glGetUniformLocation(shad->Program, "dlight.color"), Lcolor.x, Lcolor.y, Lcolor.z);
break;
case POINT:
variable = "plight[" + std::to_string(lightNumber) + "]";
//Light Position
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".position").c_str()), Lpos.x, Lpos.y, Lpos.z);
//Light Direction
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".direction").c_str()), Ldirection.x, Ldirection.y, Ldirection.z);
//Ambiental light
result = Lambient;
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".ambient").c_str()), result.x, result.y, result.z);
result = vec3(0.0);
//Diffuse light
result = Ldiffuse;
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".diffuse").c_str()), result.x, result.y, result.z);
result = vec3(0.0);
//Specular light
result = Lspecular;
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".specular").c_str()), result.x, result.y, result.z);
result = vec3(0.0);
//Light color
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".color").c_str()), Lcolor.x, Lcolor.y, Lcolor.z);
//Constant, linear and quadratic attenuation
glUniform1f(glGetUniformLocation(shad->Program, std::string(variable + ".constant").c_str()), c1);
glUniform1f(glGetUniformLocation(shad->Program, std::string(variable + ".linear").c_str()), c2);
glUniform1f(glGetUniformLocation(shad->Program, std::string(variable + ".quadratic").c_str()), c3);
break;
case SPOT:
variable = "slight[" + std::to_string(lightNumber) + "]";
//Light Position
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".position").c_str()), Lpos.x, Lpos.y, Lpos.z);
//Light Direction
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".direction").c_str()), Ldirection.x, Ldirection.y, Ldirection.z);
//Ambiental light
result = Lambient;
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".ambient").c_str()), result.x, result.y, result.z);
result = vec3(0.0);
//Diffuse light
result = Ldiffuse;
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".diffuse").c_str()), result.x, result.y, result.z);
result = vec3(0.0);
//Specular light
result = Lspecular;
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".specular").c_str()), result.x, result.y, result.z);
result = vec3(0.0);
//Light color
glUniform3f(glGetUniformLocation(shad->Program, std::string(variable + ".color").c_str()), Lcolor.x, Lcolor.y, Lcolor.z);
//Min and max aperture
glUniform1f(glGetUniformLocation(shad->Program, std::string(variable + ".minAperture").c_str()), MinAperture);
glUniform1f(glGetUniformLocation(shad->Program, std::string(variable + ".maxAperture").c_str()), MaxAperture);
//Constant, linear and quadratic attenuation
glUniform1f(glGetUniformLocation(shad->Program, std::string(variable + ".constant").c_str()), c1);
glUniform1f(glGetUniformLocation(shad->Program, std::string(variable + ".linear").c_str()), c2);
glUniform1f(glGetUniformLocation(shad->Program, std::string(variable + ".quadratic").c_str()), c3);
break;
default:
break;
}
}
void Light::Rotate(vec3 rotation) {
//opcional
}
void Light::SetDirection(vec3 dir) {
Ldirection = dir;
}
vec3 Light::GetPosition() {
return Lpos;
}
void Light::SetPosition(vec3 pos) {
Lpos = pos;
}
void Light::SetColor(vec3 color) {
Lcolor = color;
}
vec3 Light::GetColor() {
return Lcolor;
}
|
/**
* John Bradley (jrb@turrettech.com)
*/
#pragma once
#include <string>
#include <vector>
namespace BSP {
extern void ReplaceStringInPlace(std::string& subject, const std::string& search, const std::string& replace);
extern std::string ReplaceString(std::string subject, const std::string& search, const std::string& replace);
std::vector<std::string> &Split(const std::string &s, char delim, std::vector<std::string> &elems);
std::vector<std::string> Split(const std::string &s, char delim);
extern std::string IntegerToString(int integer);
extern void ReplaceStringInPlace(std::wstring& subject, const std::wstring& search, const std::wstring& replace);
extern std::wstring ReplaceString(std::wstring subject, const std::wstring& search, const std::wstring& replace);
extern std::wstring IntegerToWString(int integer);
extern std::string UTF16ToUTF8(std::wstring &utf16String);
extern std::wstring UTF8ToUTF16(const std::string& utf8String);
}
|
#ifndef __LayerGameOver_H__
#define __LayerGameOver_H__
#include "cocos2d.h"
USING_NS_CC;
class LayerGameOver :public CCLayer
{
public:
static CCScene * scene();
CREATE_FUNC(LayerGameOver);
bool init();
void restartGameMCallBack(CCObject *obj);
};
#endif
|
#include "BVHList.h"
BVHList::BVHList()
{
}
BVHList::~BVHList()
{
size_t sz = bvhList.size();
for (size_t i = 0; i < sz; ++i)
delete bvhList[i];
}
void BVHList::AddBVH(BVH* bvh)
{
bvhList.push_back(bvh);
frame_no.push_back(0);
animation_time.push_back(0);
}
int BVHList::GetSize()
{
return bvhList.size();
}
BVH* BVHList::GetBVHIndex(int i)
{
return bvhList[i];
}
int BVHList::GetFrameNo(int i)
{
return frame_no[i];
}
void BVHList::SetFrameNo(int i, int frameNumber)
{
frame_no[i] = frameNumber;
}
void BVHList::IncreFrameNo(int i)
{
frame_no[i]++;
}
void BVHList::DecreFrameNo(int i)
{
frame_no[i]--;
}
float BVHList::GetAnimationTime(int i)
{
return animation_time[i];
}
void BVHList::SetAnimationTime(int i, float time)
{
animation_time[i] = time;
}
void BVHList::IncreAnimationTime(int i)
{
animation_time[i] += bvhList[i]->GetInterval();
}
void BVHList::DecreAnimationTime(int i)
{
animation_time[i] -= bvhList[i]->GetInterval();
}
void BVHList::RemoveBVHIndex(int i)
{
delete bvhList[i];
//bvhList.pop_back();
bvhList.erase(bvhList.begin() + i);
animation_time.erase(animation_time.begin() + i);
frame_no.erase(frame_no.begin() + i);
//animation_time.pop_back();
//frame_no.pop_back();
}
|
#ifndef __HAVE_ANIMATED_SPRITE
#define __HAVE_ANIMATED_SPRITE
#include <map>
#include <vector>
#include <string>
#include <SDL.h>
#include <SDL_image.h>
#include "camera.h"
#ifdef HAVE_GRAPHICS
class AnimatedSprite {
public:
AnimatedSprite();
virtual ~AnimatedSprite();
void render(const Camera& camera, const Point& pos) const;
void add_animation(const std::string& name, const std::vector<unsigned>& frames);
void add_animation(unsigned num_frames, std::string name, ...);
void set_animation(std::string name);
void set_animation_speed(unsigned speed);
void set_image(const char* src);
void update_animation();
private:
Point m_tile_size;
Point m_sprite_size;
SDL_Rect m_sprite_rect;
SDL_Surface* m_sprite;
std::map<const std::string, const std::vector<unsigned> > m_animations;
unsigned m_current_animation_frame;
unsigned m_update_counter;
unsigned m_animation_speed;
std::string m_current_animation;
};
#endif
#endif
|
/***************************************************************************
* Filename : GameObject.cpp
* Name : Ori Lazar
* Date : 03/11/2019
* Description : Contains the implementation for the game object structure.
This object may contain any number of game components,
These could be rendering, physics or other components.
.---.
.'_:___".
|__ --==|
[ ] :[|
|__| I=[|
/ / ____|
|-/.____.'
/___\ /___\
***************************************************************************/
#include "expch.h"
#include "GameObject.h"
#include "Core/Renderer/Renderer.h"
#include <algorithm>
#include <imgui.h>
namespace Exalted
{
GameObject::GameObject(std::string objectName)
: m_ObjectName(objectName), m_BoundingRadius(1.f), m_DistanceFromCamera(0.f), m_IsTransparent(false)
{
static uint32_t id = 0;
m_Id = id++;
m_ChildrenObjectsList.reserve(2);
m_Transform = Exalted::CreateRef<GameTransform>();
m_Shader = Shader::Create(DEFAULT_VERTEX_SHADER, DEFAULT_FRAGMENT_SHADER);
EX_CORE_INFO("GameObject {0} Constructed with no shader.", m_ObjectName);
}
GameObject::GameObject(std::string objectName, Ref<Shader>& shader)
: m_ObjectName(objectName), m_BoundingRadius(1.f), m_DistanceFromCamera(0.f), m_IsTransparent(false)
{
static uint32_t id = 0;
m_Id = id++;
m_Transform = Exalted::CreateRef<GameTransform>();
m_Shader = shader;
EX_CORE_INFO("GameObject {0} Constructed with a custom shader", objectName);
}
void GameObject::Update(Timestep deltaTime)
{
for (std::vector<GameComponent*>::iterator i = m_GameComponents.begin(); i != m_GameComponents.end(); ++i)
(*i)->Update(deltaTime);
if (m_pParent)
m_Transform->SetWorldTransform(m_pParent->GetTransform()->WorldTransform);
else
m_Transform->SetWorldTransform();
if (m_PointLight)
m_PointLight->Position = glm::vec3(m_Transform->WorldTransform[3]);
if (m_SpotLight)
m_SpotLight->Position = glm::vec3(m_Transform->WorldTransform[3]);
for (std::vector<GameObject*>::iterator i = m_ChildrenObjectsList.begin(); i != m_ChildrenObjectsList.end(); ++i)
(*i)->Update(deltaTime);
}
void GameObject::RemoveGameComponent(GameComponent* pGameComponent)
{
const std::vector<GameComponent*>::iterator objectPosition = std::find(m_GameComponents.begin(), m_GameComponents.end(), &(*pGameComponent));
if (objectPosition != m_GameComponents.end())
{
m_GameComponents.erase(objectPosition);
pGameComponent->RemovedFromGameObject();
}
}
void GameObject::RemoveChildObject(GameObject* pGameObject)
{
const std::vector<GameObject*>::iterator objectPosition = std::find(m_ChildrenObjectsList.begin(), m_ChildrenObjectsList.end(), pGameObject);
if (objectPosition != m_ChildrenObjectsList.end())
{
m_ChildrenObjectsList.erase(objectPosition);
EX_CORE_WARN("Removed {0} from {1}.", pGameObject->m_ObjectName, m_ObjectName);
delete pGameObject;
}
else
EX_CORE_WARN("Gameobject {0} is not a child of {1}, cannot remove it.", pGameObject->m_ObjectName, m_ObjectName);
}
void GameObject::DestroyGameObject()
{
const unsigned int objectListSize = static_cast<const unsigned int>(m_ChildrenObjectsList.size());
for (unsigned int i = 0; i < objectListSize; i++)
delete m_ChildrenObjectsList[i];
}
void GameObject::RenderHierarchyGUI()
{
ImGui::Begin("Scene Hierarchy");
OnImGuiRender();
ImGui::Text("-------------------------------");
ImGui::End();
}
void GameObject::OnImGuiRender()
{
ImGuiInputTextFlags flags = ImGuiInputTextFlags_AutoSelectAll;
ImGui::Text("-------------------------------");
ImGui::Text(GetUiText(m_ObjectName).c_str());
ImGui::Text("-------------------------------");
ImGui::Checkbox(GetUiText("Active").c_str(), &m_Active);
ImGui::InputFloat3(GetUiText("Position [x,y,z]").c_str(), (float*) & (m_Transform->Position) ,"%.3f");
ImGui::InputFloat3(GetUiText("Rotation [x,y,z]").c_str(), (float*) & (m_Transform->Rotation), "%.3f");
ImGui::InputFloat3(GetUiText("Scale [x,y,z]").c_str(), (float*) & (m_Transform->Scale), "%.3f");
for (std::vector<GameObject*>::iterator i = m_ChildrenObjectsList.begin(); i != m_ChildrenObjectsList.end(); ++i)
{
(*i)->OnImGuiRender();
}
}
}
|
#ifndef CELL_H
#define CELL_H
#include <iostream>
#include <tuple>
// See Cell.cpp for detailed comments.
class Cell {
private:
int Bomb;
int XPos, YPos;
int NumNeighbours;
int Revealed;
int Flagged;
public:
Cell();
void SetXPos(int);
void SetYPos(int);
void SetBomb();
int IsBomb();
void IncNumNeighbours();
int GetNumNeighbours();
void Clear();
int IsRevealed();
void ToggleFlag();
int IsFlagged();
};
#endif
|
#ifndef STACK_VECTOR_H
#define STACK_VECTOR_H
#include "../vector/vector.h"
template <typename T> class Stack : public Vector<T> {
public:
void push ( T const &e ) { insert ( this->size(), e ); }
T pop () { return remove ( this->size() - 1 ); }
T &top () { return ( *this ) [this->size() - 1]; }
};
#endif /* ifndef STACK_VECTOR_H */
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Character.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jwon <jwon@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/26 17:54:36 by jwon #+# #+# */
/* Updated: 2021/01/26 19:45:16 by jwon ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CHARACTER_HPP
# define CHARACTER_HPP
# include <iostream>
# include <string>
# include "AWeapon.hpp"
# include "Enemy.hpp"
class Character
{
public:
Character(std::string const &name);
Character(Character const &ref);
Character& operator=(Character const &ref);
~Character();
std::string getName() const;
int getAP() const;
AWeapon *getWeapon() const;
void recoverAP();
void equip(AWeapon *weapon);
void attack(Enemy *enemy);
private:
Character();
std::string m_name;
int m_ap;
AWeapon *m_weapon;
};
std::ostream& operator<<(std::ostream &os, const Character &ref);
#endif
|
/**
* File: boggle.cpp
* ----------------
* Implements the game of Boggle.
*/
#include <cctype>
#include <iostream>
using namespace std;
#include "simpio.h"
#include "gwindow.h"
#include "gboggle.h"
#include "map.h"
#include "grid.h"
#include "random.h"
#include "lexicon.h"
const int kBoggleWindowWidth = 650;
const int kBoggleWindowHeight = 350;
const int kBoggleBoardSize = 4;
const int kBoggleCubesSize = 16;
const string kStandardCubes[16] = {
"AAEEGN", "ABBJOO", "ACHOPS", "AFFKPS",
"AOOTTW", "CIMOTU", "DEILRX", "DELRVY",
"DISTTY", "EEGHNW", "EEINSU", "EHRTVW",
"EIOSST", "ELRTTY", "HIMNQU", "HLNNRZ"
};
const string kBigBoggleCubes[25] = {
"AAAFRS", "AAEEEE", "AAFIRS", "ADENNN", "AEEEEM",
"AEEGMU", "AEGMNN", "AFIRSY", "BJKQXZ", "CCNSTW",
"CEIILT", "CEILPT", "CEIPST", "DDLNOR", "DDHNOT",
"DHHLOR", "DHLNOR", "EIIITT", "EMOTTT", "ENSSSU",
"FIPRSY", "GORRVW", "HIPRRY", "NOOTUW", "OOOTTU"
};
static void playGame();
static void welcome();
static void giveInstructions();
static bool responseIsAffirmative(const string& prompt);
static void createBoard(Vector<Vector<string> >& cubes, Grid<char>& board);
static void forceBoardConfig(Grid<char>& board);
static bool isWord(string playerword, Lexicon& english);
static bool notUsed(string playerword, Set<string>& usedwords);
static bool longEnough(string playerword);
static bool findStart(string playerword, Grid<char>& board);
static bool findSquares(string playerword, Grid<char>& board, Vector<GPoint>& path, Set<GPoint>& usedsquares, Vector<int>& lastwordsize, string& found);
static void nextSquare(string playerword, Grid<char>& board, Vector<GPoint>& path, Set<GPoint>& usedsquares, string& found, int dir);
static void removeSquare(Vector<GPoint>& path, Set<GPoint>& usedsquares, Vector<int>& lastwordsize, string& found);
static void highlightWord(Vector<GPoint>& path);
static bool wordHasGrown(Vector<int>& lastwordsize, string& found);
static void computerTurn(Grid<char>& board, Set<string>& usedwords, Lexicon& english);
static bool findWords(Grid<char>& board, Vector<GPoint>& path, Vector<int>& lastwordsize, Set<GPoint>& usedsquares, Set<string>& foundwords, string& compfound, Set<string>& usedwords, Lexicon& english, bool endcheck);
static void buildWord(Grid<char>& board, Vector<GPoint>& path, Set<GPoint>& usedsquares, Set<string>& foundwords, string& compfound, Set<string>& usedwords, Lexicon& english, int dir);
static void processSquare(Vector<GPoint>& path, Set<GPoint>& usedsquares, Set<string>& foundwords, string& compfound, Set<string>& usedwords, Lexicon& english, string& temporary, GPoint& result);
int main() {
while (true) {
playGame();
if (!responseIsAffirmative("Would you like to play again?")) {
break;
}
}
return 0;
}
static void playGame() {
GWindow gw(kBoggleWindowWidth, kBoggleWindowHeight);
initGBoggle(gw);
welcome();
Lexicon english("EnglishWords.dat");
if (responseIsAffirmative("Do you need instructions? ")) {
giveInstructions();
}
Vector<Vector<string> > cubes;
Grid<char> board(kBoggleBoardSize, kBoggleBoardSize);
drawBoard(kBoggleBoardSize, kBoggleBoardSize);
createBoard(cubes, board);
Set<string> usedwords;
cout << "I'll give you a chance to set up the board to your specification, which makes it easier to confirm your boggle program is working." << endl;
if (responseIsAffirmative("Do you want to force the board configuration? ")) {
forceBoardConfig(board);
}
else {
createBoard(cubes, board);
}
for (int boardx = 0; boardx < kBoggleBoardSize; boardx++) {
for (int boardy = 0; boardy < kBoggleBoardSize ; boardy++) {
char letter = board.get(boardx, boardy);
labelCube(boardx, boardy,letter);
}
}
cout << endl;
cout << "Ok, take all the time you want and find all the words you can! Signal that you're finished by entering an empty line." << endl;
while (true) {
cout << "Enter a word :";
string playerwordinit = getLine();
string playerword = toUpperCase(playerwordinit);
if (playerword == "") {
break;
}
if (isWord(playerword, english) && notUsed(playerword, usedwords) && longEnough(playerword)) {
if (findStart(playerword, board)) {
usedwords.add(playerword);
}
else {
cout << "You can't make that word." << endl;
}
}
}
computerTurn(board, usedwords, english);
}
static void welcome() {
cout << "Welcome! You're about to play an intense game ";
cout << "of mind-numbing Boggle. The good news is that ";
cout << "you might improve your vocabulary a bit. The ";
cout << "bad news is that you're probably going to lose ";
cout << "miserably to this little dictionary-toting hunk ";
cout << "of silicon. If only YOU had a gig of RAM..." << endl << endl;
}
static void giveInstructions() {
cout << endl;
cout << "The boggle board is a grid onto which I ";
cout << "I will randomly distribute cubes. These ";
cout << "6-sided cubes have letters rather than ";
cout << "numbers on the faces, creating a grid of ";
cout << "letters on which you try to form words. ";
cout << "You go first, entering all the words you can ";
cout << "find that are formed by tracing adjoining ";
cout << "letters. Two letters adjoin if they are next ";
cout << "to each other horizontally, vertically, or ";
cout << "diagonally. A letter can only be used once ";
cout << "in each word. Words must be at least four ";
cout << "letters long and can be counted only once. ";
cout << "You score points based on word length: a ";
cout << "4-letter word is worth 1 point, 5-letters ";
cout << "earn 2 points, and so on. After your puny ";
cout << "brain is exhausted, I, the supercomputer, ";
cout << "will find all the remaining words and double ";
cout << "or triple your paltry score." << endl << endl;
cout << "Hit return when you're ready...";
getLine();
}
static bool responseIsAffirmative(const string& prompt) {
while (true) {
string answer = getLine(prompt);
if (!answer.empty()) {
switch (toupper(answer[0])) {
case 'Y': return true;
case 'N': return false;
}
}
cout << "Please answer yes or no." << endl;
}
}
static void createBoard(Vector<Vector<string> >& cubes, Grid<char>& board) {
for (int i = 0; i < 16; i++) {
Vector<string> onecube;
for (int letter = 0; letter < 6; letter++) {
string cube = kStandardCubes[i];
string side = cube.substr(letter, 1);
onecube.add(side);
}
cubes.add(onecube);
}
for (int swap = 0; swap < cubes.size(); swap++) {
int swap2 = randomInteger(swap, cubes.size() - 1);
Vector<string> element1 = cubes.get(swap);
Vector<string> element2 = cubes.get(swap2);
cubes.set(swap2, element1);
cubes.set(swap, element2);
}
Vector<string> selections;
for (int x = 0; x < 16; x++) {
Vector<string> cubethrow = cubes.get(x);
int random = randomInteger(0, 5);
string selection = cubethrow.get(random);
selections.add(selection);
}
int selectionsindex = 0;
for (int boardx = 0; boardx < kBoggleBoardSize; boardx++) {
for (int boardy = 0; boardy < kBoggleBoardSize ; boardy++) {
string position = selections.get(selectionsindex);
char position2 = position[0];
board.set(boardx, boardy, position2);
selectionsindex++;
}
}
}
static void forceBoardConfig(Grid<char>& board) {
cout << "Enter a 16-character string to identify which letters you want on the cubes." << endl;
cout << "The first 4 letters are the cubes on the top row from left to right, the next 4 letters are the second row, and so on." << endl;
cout << "Enter the string: ";
string playerselect = getLine();
cout << "This is the playerselect " + playerselect << endl;
if (playerselect.size() < kBoggleCubesSize) {
cout << "That string isnt long enough!" << endl;
forceBoardConfig(board);
}
else if (playerselect.size() >= kBoggleCubesSize) {
int stringindex = 0;
for (int boardx = 0; boardx < kBoggleBoardSize; boardx++) {
for (int boardy = 0; boardy < kBoggleBoardSize ; boardy++) {
char select = playerselect[stringindex];
char upperselect = toupper(select);
board.set(boardx, boardy, upperselect);
stringindex++;
}
}
}
}
static bool isWord(string playerword, Lexicon& english) {
if (english.contains(playerword)) {
return true;
}
else {
cout << "That isn't a word!" << endl;
}
return false;
}
static bool notUsed(string playerword, Set<string>& usedwords) {
if (usedwords.contains(playerword)) {
cout << "You already used that word." << endl;
return false;
}
return true;
}
static bool longEnough(string playerword) {
if (playerword.size() < 4) {
cout << "I'm sorry, but we have our standards." << endl;
cout << "That word doesn't meet the minimum word length." << endl;
return false;
}
return true;
}
static bool findStart(string playerword, Grid<char>& board) {
char beginning = playerword[0];
char uppercase = toupper(beginning);
for (int x = 0; x < kBoggleBoardSize; x++) {
for (int y = 0; y < kBoggleBoardSize; y++) {// loop cycles through each space of the board looking for start letter
char boardlocation = board.get(x, y);
if (uppercase == boardlocation) {
Vector<GPoint> path;// stores path of matched letters
Vector<int> lastwordsize;// stores size of the word in the previous turn to check wordhasgrown
Set<GPoint> usedsquares;// stores the usedsquares so they arent re-used in same word
string found = playerword.substr(0, 1);
lastwordsize.insert(0, 1);
GPoint start(x, y);
path.add(start);
usedsquares.add(start);
if (findSquares(playerword, board, path, usedsquares, lastwordsize, found)) {
highlightWord(path);
recordWordForPlayer(playerword, HUMAN);
return true;
}
}
}
}
return false;
}
static bool findSquares(string playerword, Grid<char>& board, Vector<GPoint>& path, Set<GPoint>& usedsquares, Vector<int>& lastwordsize, string& found) {
if (playerword == found) {// Base case of found word matches the player input word
return true;
}
if (found.size() == 0) {// if the found word goes back to empty, return false and cycle to the next start letter
return false;
}
for (int dir = 0; dir < 8; dir++) {// loop of 8, one per possible direction
nextSquare(playerword, board, path, usedsquares, found, dir);// returns GPoint of next square
if (wordHasGrown(lastwordsize, found)) {// if the word has grown
if (findSquares(playerword, board, path, usedsquares, lastwordsize, found)) {// recurse to new loop till its solved
return true;
}
}
}
removeSquare(path, usedsquares, lastwordsize, found);// remove square after the loop and rewind to earlier decision
return false;
}
static void nextSquare(string playerword, Grid<char>& board, Vector<GPoint>& path, Set<GPoint>& usedsquares, string& found, int dir) {
GPoint newstart = path.get(path.size() - 1);
int x = newstart.getX();
int y = newstart.getY();
int length = found.size();
char target = playerword[length];
if (dir == 0) {// dir is loop number from findsquares- direction
if (board.inBounds(x + 1, y)) {
char thisone = board[x + 1][y]; // for each cycle of the loop check a letter on the board around the source tile
GPoint result(x + 1, y);
if (target == thisone && !usedsquares.contains(result)) {
found = found + target;
path.add(result);
usedsquares.add(result);
}
}
}
if (dir == 1) {
if (board.inBounds(x - 1, y)) {
char thisone = board[x - 1][y];
GPoint result(x - 1, y);
if (target == thisone && !usedsquares.contains(result)) {
found = found + target;
path.add(result);
usedsquares.add(result);
}
}
}
if (dir == 2) {
if (board.inBounds(x, y + 1)) {
char thisone = board[x][y + 1];
GPoint result(x, y + 1);
if (target == thisone && !usedsquares.contains(result)) {
found = found + target;
path.add(result);
usedsquares.add(result);
}
}
}
if (dir == 3) {
if (board.inBounds(x, y - 1)) {
char thisone = board[x][y - 1];
GPoint result(x, y - 1);
if (target == thisone && !usedsquares.contains(result)) {
found = found + target;
path.add(result);
usedsquares.add(result);
}
}
}
if (dir == 4) {
if (board.inBounds(x - 1, y - 1)) {
char thisone = board[x - 1][y - 1];
GPoint result(x - 1, y - 1);
if (target == thisone && !usedsquares.contains(result)) {
found = found + target;
path.add(result);
usedsquares.add(result);
}
}
}
if (dir == 5) {
if (board.inBounds(x + 1, y - 1)) {
char thisone = board[x + 1][y - 1];
GPoint result(x + 1, y - 1);
if (target == thisone && !usedsquares.contains(result)) {
found = found + target;
path.add(result);
usedsquares.add(result);
}
}
}
if (dir == 6) {
if (board.inBounds(x + 1, y + 1)) {
char thisone = board[x + 1][y + 1];
GPoint result(x + 1, y + 1);
if (target == thisone && !usedsquares.contains(result)) {
found = found + target;
path.add(result);
usedsquares.add(result);
}
}
}
if (dir == 7) {
if (board.inBounds(x - 1, y + 1)) {
char thisone = board[x - 1][y + 1];
GPoint result(x - 1, y + 1);
if (target == thisone && !usedsquares.contains(result)) {
found = found + target;
path.add(result);
usedsquares.add(result);
}
}
}
}
static void removeSquare(Vector<GPoint>& path, Set<GPoint>& usedsquares, Vector<int>& lastwordsize, string& found) {
if (found.length() > 0) {
GPoint erase = path.get(path.size() - 1);
found.erase(found.length() - 1);
int newwordsize = found.length();
lastwordsize.set(0, newwordsize);
path.remove(path.size() - 1);
usedsquares.remove(erase);
}
}
static void highlightWord(Vector<GPoint>& path) {
for (int i = 0; i < path.size(); i++) {
GPoint update1 = path.get(i);
int x = update1.getX();
int y = update1.getY();
highlightCube(x, y, true);
}
pause(200);
for (int n = 0; n < path.size(); n++) {
GPoint update2 = path.get(n);
int x = update2.getX();
int y = update2.getY();
highlightCube(x, y, false);
}
}
static bool wordHasGrown(Vector<int>& lastwordsize, string& found) {//
int currentsize = found.length();
int lastsize = lastwordsize.get(0);
if (lastsize >= currentsize) {
lastwordsize.set(0, currentsize);
return false;
}
else if (lastsize < currentsize){
lastwordsize.set(0, currentsize);
return true;
}
}
static void computerTurn(Grid<char>& board, Set<string>& usedwords, Lexicon& english) {
Set<string> foundwords;
for (int x = 0; x <= kBoggleBoardSize; x++) {
for (int y = 0; y <= kBoggleBoardSize; y++) {
string compfound;
if (x < kBoggleBoardSize && y < kBoggleBoardSize) {
char boardlocation = board.get(x, y);
compfound = compfound + boardlocation;
}
Vector<GPoint> path;// stores path of matched letters
Vector<int> lastwordsize;// stores size of the word in the previous turn to check wordhasgrown
Set<GPoint> usedsquares;// stores the usedsquares so they arent re-used in same word
bool endcheck = false;// during the loop send out false for recursive base case
if (x == kBoggleBoardSize || y == kBoggleBoardSize) {
endcheck = true;// hits the final extra loop and sends true
}
lastwordsize.insert(0, 1);
GPoint start(x, y);
path.add(start);
usedsquares.add(start);
if (findWords(board, path, lastwordsize, usedsquares, foundwords, compfound, usedwords, english, endcheck)) {
break;
}
}
}
foreach (string word in foundwords) {
recordWordForPlayer(word, COMPUTER);
}
}
static bool findWords(Grid<char>& board, Vector<GPoint>& path, Vector<int>& lastwordsize, Set<GPoint>& usedsquares, Set<string>& foundwords, string& compfound, Set<string>& usedwords, Lexicon& english, bool endcheck) {
if (endcheck == true) {// base case is the extra loop in computerturn that sends out endcheck bool
return true;
}
if (compfound.size() == 0) {
return false;
}
for (int dir = 0; dir < 8; dir++) {
buildWord(board, path, usedsquares, foundwords, compfound, usedwords, english, dir);
if (wordHasGrown(lastwordsize, compfound)) {// re-use wordhasgrown function
if (findWords(board, path, lastwordsize, usedsquares, foundwords, compfound, usedwords, english, endcheck)) {
return true;
}
}
}
removeSquare(path, usedsquares, lastwordsize, compfound);// re-use removesquare function
return false;
}
static void buildWord(Grid<char>& board, Vector<GPoint>& path, Set<GPoint>& usedsquares, Set<string>& foundwords, string& compfound, Set<string>& usedwords, Lexicon& english, int dir) {
GPoint newstart = path.get(path.size() - 1);
int x = newstart.getX();
int y = newstart.getY();
string temporary = compfound;
if (dir == 0) {// dir is loop number from findsquares- direction
if (board.inBounds(x + 1, y)) {
char thisone = board[x + 1][y]; // for each cycle of the loop check a letter on the board around the source tile
temporary = temporary + thisone;
GPoint result(x + 1, y);
if (usedsquares.contains(result) == false) {
processSquare(path, usedsquares, foundwords, compfound, usedwords, english, temporary, result);
}
}
}
if (dir == 1) {
if (board.inBounds(x - 1, y)) {
char thisone = board[x - 1][y];
temporary = temporary + thisone;
GPoint result(x - 1, y);
if (usedsquares.contains(result) == false) {
processSquare(path, usedsquares, foundwords, compfound, usedwords, english, temporary, result);
}
}
}
if (dir == 2) {
if (board.inBounds(x, y + 1)) {
char thisone = board[x][y + 1];
temporary = temporary + thisone;
GPoint result(x, y + 1);
if (usedsquares.contains(result) == false) {
processSquare(path, usedsquares, foundwords, compfound, usedwords, english, temporary, result);
}
}
}
if (dir == 3) {
if (board.inBounds(x, y - 1)) {
char thisone = board[x][y - 1];
temporary = temporary + thisone;
GPoint result(x, y - 1);
if (usedsquares.contains(result) == false) {
processSquare(path, usedsquares, foundwords, compfound, usedwords, english, temporary, result);
}
}
}
if (dir == 4) {
if (board.inBounds(x - 1, y - 1)) {
char thisone = board[x - 1][y - 1];
temporary = temporary + thisone;
GPoint result(x - 1, y - 1);
if (usedsquares.contains(result) == false) {
processSquare(path, usedsquares, foundwords, compfound, usedwords, english, temporary, result);
}
}
}
if (dir == 5) {
if (board.inBounds(x + 1, y - 1)) {
char thisone = board[x + 1][y - 1];
temporary = temporary + thisone;
GPoint result(x + 1, y - 1);
if (usedsquares.contains(result) == false) {
processSquare(path, usedsquares, foundwords, compfound, usedwords, english, temporary, result);
}
}
}
if (dir == 6) {
if (board.inBounds(x + 1, y + 1)) {
char thisone = board[x + 1][y + 1];
temporary = temporary + thisone;
GPoint result(x + 1, y + 1);
if (usedsquares.contains(result) == false) {
processSquare(path, usedsquares, foundwords, compfound, usedwords, english, temporary, result);
}
}
}
if (dir == 7) {
if (board.inBounds(x - 1, y + 1)) {
char thisone = board[x - 1][y + 1];
temporary = temporary + thisone;
GPoint result(x - 1, y + 1);
if (usedsquares.contains(result) == false) {
processSquare(path, usedsquares, foundwords, compfound, usedwords, english, temporary, result);
}
}
}
}
static void processSquare(Vector<GPoint>& path, Set<GPoint>& usedsquares, Set<string>& foundwords, string& compfound, Set<string>& usedwords, Lexicon& english, string& temporary, GPoint& result) {
if (english.containsPrefix(temporary) || english.contains(temporary)) {
path.add(result);
usedsquares.add(result);
compfound = temporary;
if (english.contains(compfound) && compfound.size() >= 4 && !usedwords.contains(compfound)) {
foundwords.add(compfound);
}
}
}
|
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QtDebug>
#include <QThread>
#include <QRegExp>
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
serialport = new QSerialPort();
ui->pushButton_close->setEnabled(false);
//connect serialport signal and slot.
connect(serialport,SIGNAL(readyRead()),this,SLOT(processSerialRec()));
qcp_init();
//Timer Init
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),
this,SLOT(timerUpdate()));
timer->start(25);
//定时更新各种指示控件
timer_indicators = new QTimer(this);
connect(timer_indicators, SIGNAL(timeout()),
this,SLOT(timerUpdate_indicators()));
timer_indicators->start(100);
//启动接收
//ui->pushButton_open->clicked();
ui->pushButton_close->setEnabled(false);
//错误帧计数
bad_frame_counter=0;
}
MainWindow::~MainWindow()
{
serialport->close();
delete ui;
}
void MainWindow::qcp_init(void)
{
ui->customPlot->addGraph();
ui->customPlot->xAxis->setRange(0,PIC_WIDTH);
ui->customPlot->yAxis->setRange(-20000, 20000);
ui->customPlot->graph(0)->setPen(QPen(QColor(255,0,0)));
ui->customPlot->graph(0)->setName(QString::number(1));
ui->customPlot->addGraph();
ui->customPlot->graph(1)->setPen(QPen(QColor(0,255,0)));
ui->customPlot->graph(1)->setName(QString::number(2));
ui->customPlot->addGraph();
ui->customPlot->graph(2)->setPen(QPen(QColor(128,0,255)));
ui->customPlot->graph(2)->setName(QString::number(3));
ui->customPlot->addGraph();
ui->customPlot->graph(3)->setPen(QPen(QColor(0,128,255)));
ui->customPlot->graph(3)->setName(QString::number(4));
ui->customPlot->addGraph();
ui->customPlot->graph(4)->setPen(QPen(QColor(0,255,128)));
ui->customPlot->graph(4)->setName(QString::number(5));
ui->customPlot->addGraph();
ui->customPlot->graph(5)->setPen(QPen(QColor(255,128,0)));
ui->customPlot->graph(5)->setName(QString::number(6));
QColor graph_color[3]={QColor(128,128,128),QColor(60,128,200),QColor(90,30,128)};
for(int i=0;i<3;i++)
{
ui->customPlot->addGraph();
ui->customPlot->graph(i+6)->setPen(QPen(graph_color[i]));
ui->customPlot->graph(i+6)->setName(QString::number(i+7));
}
//legend
//可见
ui->customPlot->legend->setVisible(true);
//将图例矩形域放到右上角
ui->customPlot->axisRect()->insetLayout()->setInsetAlignment(0,Qt::AlignTop|Qt::AlignRight);
//设置图例背景色
ui->customPlot->legend->setBrush(QColor(255,255,255,0));
//ui->customPlot->yAxis2->setRange(-5,+5);
//ui->customPlot->yAxis->setLabel("adc_value");
//ui->customPlot->yAxis2->setVisible(true);
//ui->customPlot->yAxis2->setLabel("voltage(V)");
for(int i=0;i<Channel_Number;i++)
{
rec[i].resize(PIC_WIDTH);
}
x.resize(PIC_WIDTH);
for(int i=0;i<PIC_WIDTH;i++){
x[i]=i;
}
// 支持鼠标拖拽轴的范围、滚动缩放轴的范围,左键点选图层(每条曲线独占一个图层)
ui->customPlot->setInteractions(QCP::iRangeDrag | QCP::iRangeZoom
| QCP::iSelectPlottables | QCP::iSelectItems
| QCP::iSelectLegend);
//设置Legend只能选择图例
ui->customPlot->legend->setSelectableParts(QCPLegend::spItems);
connect(ui->customPlot,SIGNAL(selectionChangedByUser()),this,SLOT(selectionChanged()));
}
void MainWindow::on_pushButton_open_clicked()
{
serialport->setPortName("COM"+QString::number(ui->spinBox_comPort->value()));
serialport->setBaudRate(QSerialPort::Baud115200,QSerialPort::AllDirections);
serialport->setDataBits(QSerialPort::Data8);
serialport->setParity(QSerialPort::NoParity);
serialport->setStopBits(QSerialPort::OneStop);
serialport->setFlowControl(QSerialPort::NoFlowControl);
serialport->setReadBufferSize(1024);
if(serialport->open(QIODevice::ReadWrite))
{
ui->pushButton_close->setEnabled(true);
ui->pushButton_open->setEnabled(false);
}
}
void MainWindow::on_pushButton_close_clicked()
{
serialport->close();
ui->pushButton_close->setEnabled(false);
ui->pushButton_open->setEnabled(true);
}
void MainWindow::processSerialRec()
{
QByteArray arr;
arr=serialport->readAll();
// qDebug()<<arr;
for(int i=0;i<arr.length();i++)
{
rec_fifo.enqueue(arr.at(i));
}
//qDebug("l=%d (0)=%x",arr.length(),arr.at(0)&0xff);
}
void MainWindow::dataParser(QString &s, float (&AccGyroRaw)[9])
{
QRegExp reg_pattern("\\[([0-9]{1,2})\\]=(.+),");
reg_pattern.setMinimal(true); //非贪婪模式
int pos=0;
while((pos=reg_pattern.indexIn(s,pos))!=-1) //找下一个匹配
{
pos+=reg_pattern.matchedLength(); //指针往下移动
QStringList list = reg_pattern.capturedTexts(); //匹配字符串
//qDebug()<<"reg:"<<QString::number(i)<<"=="<<list.at(i);
AccGyroRaw[list.at(1).toInt()]=list.at(2).toFloat();
//qDebug()<<"====";
}
}
void MainWindow::timerUpdate()
{
int FRAME_LENGTH = ui->spinBox_frameLength->value();//100; //Magic Number//"NRF= 0 DevID=34 [0]=-6622.0 [1]= 28.0 [2]=15892.0 [3]= -523.0 [4]= 235.0 [5]= -40.0\n"
QString rec_str;
while(rec_fifo.size()>=FRAME_LENGTH)
{
rec_str.resize(FRAME_LENGTH);
for(int i=0;i<FRAME_LENGTH;i++)
{
char c=rec_fifo.dequeue();
if(c==0x0A && i!=FRAME_LENGTH-1) //换行符,出现太早,丢弃坏帧
{
bad_frame_counter++;
qDebug()<<rec_str<<"return at"<<QString::number(i)<<"fifo size"<<rec_fifo.size();
return;
}
rec_str[i]=c;
}
qDebug()<<rec_str<<"fifo size"<<rec_fifo.size();
//转化新的到的一帧数据
float AccGyroRaw[9];
dataParser(rec_str,AccGyroRaw);
//qDebug()<<AccGyroRaw[0]<<AccGyroRaw[1]<<AccGyroRaw[2]<<AccGyroRaw[3]<<AccGyroRaw[4]<<AccGyroRaw[5];
QString debugValueString;
for(int i=0;i<Channel_Number;i++)
{
debugValueString+="["+QString::number(i)+"]="+QString::number(AccGyroRaw[i])+" ";
}
qDebug()<<debugValueString;
//往前搬移
for(int i=0;i<PIC_WIDTH-1;i++)
{
for(int j=0;j<Channel_Number;j++)
rec[j][i]=rec[j][i+1];
}
//最后一个数据是新的数据
for(int i=0;i<Channel_Number;i++)
{
rec[i][PIC_WIDTH-1]=AccGyroRaw[i];
//绘制完整的一帧数据
ui->customPlot->graph(i)->setData(x,rec[i]);
}
}
//全部数据写完以后再重绘
ui->customPlot->replot();
//FIFO使用率
ui->progressBar->setValue(rec_fifo.count());
}
void MainWindow::timerUpdate_indicators()
{
//错误帧计数
ui->lcdNumber_badFrame->display(bad_frame_counter);
}
void MainWindow::selectionChanged()
{
//遍历整个图和图例,如果选中了图或者图例,就选中另一个对应的元素
for(int i=0;i<ui->customPlot->graphCount();i++)
{
QCPGraph *graph = ui->customPlot->graph(i);
QCPPlottableLegendItem *item = ui->customPlot->legend->itemWithPlottable(graph);
if(item->selected() || graph->selected())
{
item->setSelected(true);
graph->setSelection(QCPDataSelection(graph->data()->dataRange()));
}
}
}
void MainWindow::on_pushButton_autoscale_clicked()
{
for(int i=0;i<Channel_Number;i++)
ui->customPlot->graph(i)->rescaleAxes(true);
ui->customPlot->rescaleAxes(true);
}
void MainWindow::on_pushButton_ShowHide_clicked()
{
for(int i=0;i<ui->customPlot->graphCount();i++)
{
QCPGraph *graph = ui->customPlot->graph(i);
QCPPlottableLegendItem *item = ui->customPlot->legend->itemWithPlottable(graph);
if(item->selected() || graph->selected())
{
graph->setVisible(!graph->visible()); //隐藏或者显示
}
}
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "AbstractCardiacProblem.hpp"
#include "DistributedVector.hpp"
#include "Exception.hpp"
#include "GenericMeshReader.hpp"
#include "Hdf5ToCmguiConverter.hpp"
#include "Hdf5ToMeshalyzerConverter.hpp"
#include "Hdf5ToVtkConverter.hpp"
#include "HeartConfig.hpp"
#include "HeartEventHandler.hpp"
#include "LinearSystem.hpp"
#include "PetscTools.hpp"
#include "PostProcessingWriter.hpp"
#include "ProgressReporter.hpp"
#include "TimeStepper.hpp"
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::AbstractCardiacProblem(
AbstractCardiacCellFactory<ELEMENT_DIM, SPACE_DIM>* pCellFactory)
: mMeshFilename(""), // i.e. undefined
mAllocatedMemoryForMesh(false),
mWriteInfo(false),
mPrintOutput(true),
mpCardiacTissue(NULL),
mpSolver(NULL),
mpCellFactory(pCellFactory),
mpMesh(NULL),
mSolution(NULL),
mCurrentTime(0.0),
mpTimeAdaptivityController(NULL),
mpWriter(NULL),
mUseHdf5DataWriterCache(false),
mHdf5DataWriterChunkSizeAndAlignment(0)
{
assert(mNodesToOutput.empty());
if (!mpCellFactory)
{
EXCEPTION("AbstractCardiacProblem: Please supply a cell factory pointer to your cardiac problem constructor.");
}
HeartEventHandler::BeginEvent(HeartEventHandler::EVERYTHING);
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::AbstractCardiacProblem()
// It doesn't really matter what we initialise these to, as they'll be overwritten by
// the serialization methods
: mMeshFilename(""),
mAllocatedMemoryForMesh(false), // Handled by AbstractCardiacTissue
mWriteInfo(false),
mPrintOutput(true),
mVoltageColumnId(UINT_MAX),
mTimeColumnId(UINT_MAX),
mNodeColumnId(UINT_MAX),
mpCardiacTissue(NULL),
mpSolver(NULL),
mpCellFactory(NULL),
mpMesh(NULL),
mSolution(NULL),
mCurrentTime(0.0),
mpTimeAdaptivityController(NULL),
mpWriter(NULL),
mUseHdf5DataWriterCache(false),
mHdf5DataWriterChunkSizeAndAlignment(0)
{
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::~AbstractCardiacProblem()
{
delete mpCardiacTissue;
if (mSolution)
{
PetscTools::Destroy(mSolution);
}
if (mAllocatedMemoryForMesh)
{
delete mpMesh;
}
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::Initialise()
{
HeartEventHandler::BeginEvent(HeartEventHandler::READ_MESH);
if (mpMesh)
{
if (PetscTools::IsParallel() && !dynamic_cast<DistributedTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>*>(mpMesh))
{
WARNING("Using a non-distributed mesh in a parallel simulation is not a good idea.");
}
}
else
{
// If no mesh has been passed, we get it from the configuration file
try
{
if (HeartConfig::Instance()->GetLoadMesh())
{
CreateMeshFromHeartConfig();
std::shared_ptr<AbstractMeshReader<ELEMENT_DIM, SPACE_DIM> > p_mesh_reader
= GenericMeshReader<ELEMENT_DIM, SPACE_DIM>(HeartConfig::Instance()->GetMeshName());
mpMesh->ConstructFromMeshReader(*p_mesh_reader);
}
else if (HeartConfig::Instance()->GetCreateMesh())
{
CreateMeshFromHeartConfig();
assert(HeartConfig::Instance()->GetSpaceDimension() == SPACE_DIM);
double inter_node_space = HeartConfig::Instance()->GetInterNodeSpace();
switch (HeartConfig::Instance()->GetSpaceDimension())
{
case 1:
{
c_vector<double, 1> fibre_length;
HeartConfig::Instance()->GetFibreLength(fibre_length);
mpMesh->ConstructRegularSlabMesh(inter_node_space, fibre_length[0]);
break;
}
case 2:
{
c_vector<double, 2> sheet_dimensions; //cm
HeartConfig::Instance()->GetSheetDimensions(sheet_dimensions);
mpMesh->ConstructRegularSlabMesh(inter_node_space, sheet_dimensions[0], sheet_dimensions[1]);
break;
}
case 3:
{
c_vector<double, 3> slab_dimensions; //cm
HeartConfig::Instance()->GetSlabDimensions(slab_dimensions);
mpMesh->ConstructRegularSlabMesh(inter_node_space, slab_dimensions[0], slab_dimensions[1], slab_dimensions[2]);
break;
}
default:
NEVER_REACHED;
}
}
else
{
NEVER_REACHED;
}
mAllocatedMemoryForMesh = true;
}
catch (Exception& e)
{
EXCEPTION(std::string("No mesh given: define it in XML parameters file or call SetMesh()\n") + e.GetShortMessage());
}
}
mpCellFactory->SetMesh(mpMesh);
HeartEventHandler::EndEvent(HeartEventHandler::READ_MESH);
HeartEventHandler::BeginEvent(HeartEventHandler::INITIALISE);
// If the user requested transmural stuff, we fill in the mCellHeterogeneityAreas here
if (HeartConfig::Instance()->AreCellularTransmuralHeterogeneitiesRequested())
{
mpCellFactory->FillInCellularTransmuralAreas();
}
delete mpCardiacTissue; // In case we're called twice
mpCardiacTissue = CreateCardiacTissue();
HeartEventHandler::EndEvent(HeartEventHandler::INITIALISE);
// Delete any previous solution, so we get a fresh initial condition
if (mSolution)
{
HeartEventHandler::BeginEvent(HeartEventHandler::COMMUNICATION);
PetscTools::Destroy(mSolution);
mSolution = NULL;
HeartEventHandler::EndEvent(HeartEventHandler::COMMUNICATION);
}
// Always start at time zero
mCurrentTime = 0.0;
// For Bidomain with bath, this is where we set up the electrodes
SetElectrodes();
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::CreateMeshFromHeartConfig()
{
mpMesh = new DistributedTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>(HeartConfig::Instance()->GetMeshPartitioning());
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetBoundaryConditionsContainer(boost::shared_ptr<BoundaryConditionsContainer<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM> > pBcc)
{
this->mpBoundaryConditionsContainer = pBcc;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::PreSolveChecks()
{
if (mpCardiacTissue == NULL) // if tissue is NULL, Initialise() probably hasn't been called
{
EXCEPTION("Cardiac tissue is null, Initialise() probably hasn't been called");
}
if (HeartConfig::Instance()->GetSimulationDuration() <= mCurrentTime)
{
EXCEPTION("End time should be in the future");
}
if (mPrintOutput)
{
if ((HeartConfig::Instance()->GetOutputDirectory() == "") || (HeartConfig::Instance()->GetOutputFilenamePrefix() == ""))
{
EXCEPTION("Either explicitly specify not to print output (call PrintOutput(false)) or specify the output directory and filename prefix");
}
}
double end_time = HeartConfig::Instance()->GetSimulationDuration();
double pde_time = HeartConfig::Instance()->GetPdeTimeStep();
/*
* MatrixIsConstant stuff requires CONSTANT dt - do some checks to make sure
* the TimeStepper won't find non-constant dt.
* Note: printing_time does not have to divide end_time, but dt must divide
* printing_time and end_time.
* HeartConfig checks pde_dt divides printing dt.
*/
///\todo remove magic number? (#1884)
if (fabs(end_time - pde_time * round(end_time / pde_time)) > 1e-10)
{
EXCEPTION("PDE timestep does not seem to divide end time - check parameters");
}
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
Vec AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::CreateInitialCondition()
{
DistributedVectorFactory* p_factory = mpMesh->GetDistributedVectorFactory();
Vec initial_condition = p_factory->CreateVec(PROBLEM_DIM);
DistributedVector ic = p_factory->CreateDistributedVector(initial_condition);
std::vector<DistributedVector::Stripe> stripe;
stripe.reserve(PROBLEM_DIM);
for (unsigned i = 0; i < PROBLEM_DIM; i++)
{
stripe.push_back(DistributedVector::Stripe(ic, i));
}
for (DistributedVector::Iterator index = ic.Begin();
index != ic.End();
++index)
{
stripe[0][index] = mpCardiacTissue->GetCardiacCell(index.Global)->GetVoltage();
if (PROBLEM_DIM == 2)
{
stripe[1][index] = 0;
}
}
ic.Restore();
return initial_condition;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetMesh(AbstractTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>* pMesh)
{
/*
* If this fails the mesh has already been set. We assert rather throw
* an exception to avoid a memory leak when checking it throws correctly.
*/
assert(mpMesh == NULL);
assert(pMesh != NULL);
mAllocatedMemoryForMesh = false;
mpMesh = pMesh;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::PrintOutput(bool printOutput)
{
mPrintOutput = printOutput;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetWriteInfo(bool writeInfo)
{
mWriteInfo = writeInfo;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
Vec AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::GetSolution()
{
return mSolution;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
DistributedVector AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::GetSolutionDistributedVector()
{
return mpMesh->GetDistributedVectorFactory()->CreateDistributedVector(mSolution);
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
double AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::GetCurrentTime()
{
return mCurrentTime;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
AbstractTetrahedralMesh<ELEMENT_DIM, SPACE_DIM>& AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::rGetMesh()
{
assert(mpMesh);
return *mpMesh;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
AbstractCardiacTissue<ELEMENT_DIM, SPACE_DIM>* AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::GetTissue()
{
if (mpCardiacTissue == NULL)
{
EXCEPTION("Tissue not yet set up, you may need to call Initialise() before GetTissue().");
}
return mpCardiacTissue;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetUseTimeAdaptivityController(
bool useAdaptivity,
AbstractTimeAdaptivityController* pController)
{
if (useAdaptivity)
{
assert(pController);
mpTimeAdaptivityController = pController;
}
else
{
mpTimeAdaptivityController = NULL;
}
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::Solve()
{
PreSolveChecks();
std::vector<double> additional_stopping_times;
SetUpAdditionalStoppingTimes(additional_stopping_times);
TimeStepper stepper(mCurrentTime,
HeartConfig::Instance()->GetSimulationDuration(),
HeartConfig::Instance()->GetPrintingTimeStep(),
false,
additional_stopping_times);
// Note that SetUpAdditionalStoppingTimes is a method from the BidomainWithBath class it adds
// electrode events into the regular time-stepping
// EXCEPTION("Electrode switch on/off events should coincide with printing time steps.");
if (!mpBoundaryConditionsContainer) // the user didn't supply a bcc
{
// Set up the default bcc
mpDefaultBoundaryConditionsContainer.reset(new BoundaryConditionsContainer<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>);
for (unsigned problem_index = 0; problem_index < PROBLEM_DIM; problem_index++)
{
mpDefaultBoundaryConditionsContainer->DefineZeroNeumannOnMeshBoundary(mpMesh, problem_index);
}
mpBoundaryConditionsContainer = mpDefaultBoundaryConditionsContainer;
}
assert(mpSolver == NULL);
mpSolver = CreateSolver(); // passes mpBoundaryConditionsContainer to solver
// If we have already run a simulation, use the old solution as initial condition
Vec initial_condition;
if (mSolution)
{
initial_condition = mSolution;
}
else
{
initial_condition = CreateInitialCondition();
}
std::string progress_reporter_dir;
if (mPrintOutput)
{
HeartEventHandler::BeginEvent(HeartEventHandler::WRITE_OUTPUT);
bool extending_file = false;
try
{
extending_file = InitialiseWriter();
}
catch (Exception& e)
{
delete mpWriter;
mpWriter = NULL;
delete mpSolver;
if (mSolution != initial_condition)
{
/*
* A PETSc Vec is a pointer, so we *don't* need to free the memory if it is
* freed somewhere else (e.g. in the destructor). If this is a resumed solution
* we set initial_condition = mSolution earlier. mSolution is going to be
* cleaned up in the constructor. So, only PetscTools::Destroy( initial_condition ) when
* it is not equal to mSolution.
*/
PetscTools::Destroy(initial_condition);
}
throw e;
}
/*
* If we are resuming a simulation (i.e. mSolution already exists) and
* we are extending a .h5 file that already exists then there is no need
* to write the initial condition to file - it is already there as the
* final solution of the previous run.
*/
if (!(mSolution && extending_file))
{
WriteOneStep(stepper.GetTime(), initial_condition);
mpWriter->AdvanceAlongUnlimitedDimension();
}
HeartEventHandler::EndEvent(HeartEventHandler::WRITE_OUTPUT);
progress_reporter_dir = HeartConfig::Instance()->GetOutputDirectory();
}
else
{
progress_reporter_dir = ""; // progress printed to CHASTE_TEST_OUTPUT
}
BOOST_FOREACH (boost::shared_ptr<AbstractOutputModifier> p_output_modifier, mOutputModifiers)
{
p_output_modifier->InitialiseAtStart(this->mpMesh->GetDistributedVectorFactory(), this->mpMesh->rGetNodePermutation());
p_output_modifier->ProcessSolutionAtTimeStep(stepper.GetTime(), initial_condition, PROBLEM_DIM);
}
/*
* Create a progress reporter so users can track how much has gone and
* estimate how much time is left. Note this has to be done after the
* InitialiseWriter above (if mPrintOutput==true).
*/
ProgressReporter progress_reporter(progress_reporter_dir,
mCurrentTime,
HeartConfig::Instance()->GetSimulationDuration());
progress_reporter.Update(mCurrentTime);
mpSolver->SetTimeStep(HeartConfig::Instance()->GetPdeTimeStep());
if (mpTimeAdaptivityController)
{
mpSolver->SetTimeAdaptivityController(mpTimeAdaptivityController);
}
while (!stepper.IsTimeAtEnd())
{
// Solve from now up to the next printing time
mpSolver->SetTimes(stepper.GetTime(), stepper.GetNextTime());
mpSolver->SetInitialCondition(initial_condition);
AtBeginningOfTimestep(stepper.GetTime());
try
{
try
{
mSolution = mpSolver->Solve();
}
catch (const Exception& e)
{
#ifndef NDEBUG
PetscTools::ReplicateException(true);
#endif
throw e;
}
#ifndef NDEBUG
PetscTools::ReplicateException(false);
#endif
}
catch (const Exception& e)
{
// Free memory
delete mpSolver;
mpSolver = NULL;
if (initial_condition != mSolution)
{
/*
* A PETSc Vec is a pointer, so we *don't* need to free the memory if it is
* freed somewhere else (e.g. in the destructor). Later, in this while loop
* we will set initial_condition = mSolution (or, if this is a resumed solution
* it may also have been done when initial_condition was created). mSolution
* is going to be cleaned up in the destructor. So, only PetscTools::Destroy()
* initial_condition when it is not equal to mSolution (see #1695).
*/
PetscTools::Destroy(initial_condition);
}
// Re-throw
HeartEventHandler::Reset();
CloseFilesAndPostProcess();
throw e;
}
// Free old initial condition
HeartEventHandler::BeginEvent(HeartEventHandler::COMMUNICATION);
PetscTools::Destroy(initial_condition);
HeartEventHandler::EndEvent(HeartEventHandler::COMMUNICATION);
// Initial condition for next loop is current solution
initial_condition = mSolution;
// Update the current time
stepper.AdvanceOneTimeStep();
mCurrentTime = stepper.GetTime();
// Print out details at current time if asked for
if (mWriteInfo)
{
HeartEventHandler::BeginEvent(HeartEventHandler::WRITE_OUTPUT);
WriteInfo(stepper.GetTime());
HeartEventHandler::EndEvent(HeartEventHandler::WRITE_OUTPUT);
}
BOOST_FOREACH (boost::shared_ptr<AbstractOutputModifier> p_output_modifier, mOutputModifiers)
{
p_output_modifier->ProcessSolutionAtTimeStep(stepper.GetTime(), mSolution, PROBLEM_DIM);
}
if (mPrintOutput)
{
// Writing data out to the file <FilenamePrefix>.dat
HeartEventHandler::BeginEvent(HeartEventHandler::WRITE_OUTPUT);
WriteOneStep(stepper.GetTime(), mSolution);
// Just flags that we've finished a time-step; won't actually 'extend' unless new data is written.
mpWriter->AdvanceAlongUnlimitedDimension();
HeartEventHandler::EndEvent(HeartEventHandler::WRITE_OUTPUT);
}
progress_reporter.Update(stepper.GetTime());
OnEndOfTimestep(stepper.GetTime());
}
// Free solver
delete mpSolver;
mpSolver = NULL;
// Close the file that stores voltage values
progress_reporter.PrintFinalising();
BOOST_FOREACH (boost::shared_ptr<AbstractOutputModifier> p_output_modifier, mOutputModifiers)
{
p_output_modifier->FinaliseAtEnd();
}
CloseFilesAndPostProcess();
HeartEventHandler::EndEvent(HeartEventHandler::EVERYTHING);
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::CloseFilesAndPostProcess()
{
// Close files
if (!mPrintOutput)
{
// Nothing to do
return;
}
HeartEventHandler::BeginEvent(HeartEventHandler::WRITE_OUTPUT);
// If write caching is on, the next line might actually take a significant amount of time.
delete mpWriter;
mpWriter = NULL;
HeartEventHandler::EndEvent(HeartEventHandler::WRITE_OUTPUT);
FileFinder test_output(HeartConfig::Instance()->GetOutputDirectory(), RelativeTo::ChasteTestOutput);
/********************************************************************************
* Run all post processing.
*
* The PostProcessingWriter class examines what is requested in HeartConfig and
* adds the relevant data to the HDF5 file.
* This is converted to different visualizer formats along with the solution
* in the DATA_CONVERSION block below.
*********************************************************************************/
HeartEventHandler::BeginEvent(HeartEventHandler::POST_PROC);
if (HeartConfig::Instance()->IsPostProcessingRequested())
{
PostProcessingWriter<ELEMENT_DIM, SPACE_DIM> post_writer(*mpMesh,
test_output,
HeartConfig::Instance()->GetOutputFilenamePrefix(),
"V",
mHdf5DataWriterChunkSizeAndAlignment);
post_writer.WritePostProcessingFiles();
}
HeartEventHandler::EndEvent(HeartEventHandler::POST_PROC);
/********************************************************************************************
* Convert HDF5 datasets (solution and postprocessing maps) to different visualizer formats
********************************************************************************************/
HeartEventHandler::BeginEvent(HeartEventHandler::DATA_CONVERSION);
// Only if results files were written and we are outputting all nodes
if (mNodesToOutput.empty())
{
if (HeartConfig::Instance()->GetVisualizeWithMeshalyzer())
{
// Convert simulation data to Meshalyzer format
Hdf5ToMeshalyzerConverter<ELEMENT_DIM, SPACE_DIM> converter(test_output,
HeartConfig::Instance()->GetOutputFilenamePrefix(),
mpMesh,
HeartConfig::Instance()->GetOutputUsingOriginalNodeOrdering(),
HeartConfig::Instance()->GetVisualizerOutputPrecision());
std::string subdirectory_name = converter.GetSubdirectory();
HeartConfig::Instance()->Write(false, subdirectory_name);
}
if (HeartConfig::Instance()->GetVisualizeWithCmgui())
{
// Convert simulation data to Cmgui format
Hdf5ToCmguiConverter<ELEMENT_DIM, SPACE_DIM> converter(test_output,
HeartConfig::Instance()->GetOutputFilenamePrefix(),
mpMesh,
GetHasBath(),
HeartConfig::Instance()->GetVisualizerOutputPrecision());
std::string subdirectory_name = converter.GetSubdirectory();
HeartConfig::Instance()->Write(false, subdirectory_name);
}
if (HeartConfig::Instance()->GetVisualizeWithVtk())
{
// Convert simulation data to VTK format
Hdf5ToVtkConverter<ELEMENT_DIM, SPACE_DIM> converter(test_output,
HeartConfig::Instance()->GetOutputFilenamePrefix(),
mpMesh,
false,
HeartConfig::Instance()->GetOutputUsingOriginalNodeOrdering());
std::string subdirectory_name = converter.GetSubdirectory();
HeartConfig::Instance()->Write(false, subdirectory_name);
}
if (HeartConfig::Instance()->GetVisualizeWithParallelVtk())
{
// Convert simulation data to parallel VTK (pvtu) format
Hdf5ToVtkConverter<ELEMENT_DIM, SPACE_DIM> converter(test_output,
HeartConfig::Instance()->GetOutputFilenamePrefix(),
mpMesh,
true,
HeartConfig::Instance()->GetOutputUsingOriginalNodeOrdering());
std::string subdirectory_name = converter.GetSubdirectory();
HeartConfig::Instance()->Write(false, subdirectory_name);
}
}
HeartEventHandler::EndEvent(HeartEventHandler::DATA_CONVERSION);
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::DefineWriterColumns(bool extending)
{
if (!extending)
{
if (mNodesToOutput.empty())
{
//Set writer to output all nodes
mpWriter->DefineFixedDimension(mpMesh->GetNumNodes());
}
else
{
// Added for #2980
if (mpMesh->rGetNodePermutation().size() > 0)
{
if (HeartConfig::Instance()->GetOutputUsingOriginalNodeOrdering())
{
EXCEPTION("HeartConfig setting `GetOutputUsingOriginalNodeOrdering` is meaningless when outputting particular nodes in parallel. (Nodes are written with their original indices by default).");
}
std::vector<unsigned> nodes_to_output_permuted(mNodesToOutput.size());
for (unsigned i = 0; i < mNodesToOutput.size(); i++)
{
nodes_to_output_permuted[i] = mpMesh->rGetNodePermutation()[mNodesToOutput[i]];
}
mpWriter->DefineFixedDimension(mNodesToOutput, nodes_to_output_permuted, mpMesh->GetNumNodes());
} else {
// Output only the nodes indicated
mpWriter->DefineFixedDimension(mNodesToOutput, mNodesToOutput, mpMesh->GetNumNodes());
}
}
// mNodeColumnId = mpWriter->DefineVariable("Node", "dimensionless");
mVoltageColumnId = mpWriter->DefineVariable("V", "mV");
// Only used to get an estimate of the # of timesteps below
TimeStepper stepper(mCurrentTime,
HeartConfig::Instance()->GetSimulationDuration(),
HeartConfig::Instance()->GetPrintingTimeStep());
mpWriter->DefineUnlimitedDimension("Time", "msecs", stepper.EstimateTimeSteps() + 1); // plus one for start and end points
}
else
{
mVoltageColumnId = mpWriter->GetVariableByName("V");
}
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::DefineExtraVariablesWriterColumns(bool extending)
{
mExtraVariablesId.clear();
// Check if any extra output variables have been requested
if (HeartConfig::Instance()->GetOutputVariablesProvided())
{
// Get their names in a vector
std::vector<std::string> output_variables;
HeartConfig::Instance()->GetOutputVariables(output_variables);
const unsigned num_vars = output_variables.size();
mExtraVariablesId.reserve(num_vars);
// Loop over them
for (unsigned var_index = 0; var_index < num_vars; var_index++)
{
// Get variable name
std::string var_name = output_variables[var_index];
// Register it (or look it up) in the data writer
unsigned column_id;
if (extending)
{
column_id = this->mpWriter->GetVariableByName(var_name);
}
else
{
// Difficult to specify the units, as different cell models
// at different points in the mesh could be using different units.
column_id = this->mpWriter->DefineVariable(var_name, "unknown_units");
}
// Store column id
mExtraVariablesId.push_back(column_id);
}
}
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::WriteExtraVariablesOneStep()
{
// Get the variable names in a vector
std::vector<std::string> output_variables;
unsigned num_vars = mExtraVariablesId.size();
if (num_vars > 0)
{
HeartConfig::Instance()->GetOutputVariables(output_variables);
}
assert(output_variables.size() == num_vars);
// Loop over the requested variables
for (unsigned var_index = 0; var_index < num_vars; var_index++)
{
// Create vector for storing values over the local nodes
Vec variable_data = this->mpMesh->GetDistributedVectorFactory()->CreateVec();
DistributedVector distributed_var_data = this->mpMesh->GetDistributedVectorFactory()->CreateDistributedVector(variable_data);
// Loop over the local nodes and gather the data
for (DistributedVector::Iterator index = distributed_var_data.Begin();
index != distributed_var_data.End();
++index)
{
// If the region is in the bath
if (HeartRegionCode::IsRegionBath(this->mpMesh->GetNode(index.Global)->GetRegion()))
{
// Then we just pad the output with zeros, user currently needs to find a nice
// way to deal with this in processing and visualization.
distributed_var_data[index] = 0.0;
}
else
{
// Find the variable in the cell model and store its value
distributed_var_data[index] = this->mpCardiacTissue->GetCardiacCell(index.Global)->GetAnyVariable(output_variables[var_index], mCurrentTime);
}
}
distributed_var_data.Restore();
// Write it to disc
this->mpWriter->PutVector(mExtraVariablesId[var_index], variable_data);
PetscTools::Destroy(variable_data);
}
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
bool AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::InitialiseWriter()
{
bool extend_file = (mSolution != NULL);
// I think this is impossible to trip; certainly it's very difficult!
assert(!mpWriter);
if (extend_file)
{
FileFinder h5_file(OutputFileHandler::GetChasteTestOutputDirectory() + HeartConfig::Instance()->GetOutputDirectory()
+ "/" + HeartConfig::Instance()->GetOutputFilenamePrefix() + ".h5",
RelativeTo::Absolute);
//We are going to test for existence before creating the file.
//Therefore we should make sure that this existence test is thread-safe.
//(If another process creates the file too early then we may get the wrong answer to the
//existence question).
PetscTools::Barrier("InitialiseWriter::Extension check");
if (!h5_file.Exists())
{
extend_file = false;
}
else // if it does exist check that it is sensible to extend it by running from the archive we loaded.
{
Hdf5DataReader reader(HeartConfig::Instance()->GetOutputDirectory(),
HeartConfig::Instance()->GetOutputFilenamePrefix(),
true);
std::vector<double> times = reader.GetUnlimitedDimensionValues();
if (times.back() > mCurrentTime)
{
EXCEPTION("Attempting to extend " << h5_file.GetAbsolutePath() << " with results from time = " << mCurrentTime << ", but it already contains results up to time = " << times.back() << "."
" Calling HeartConfig::Instance()->SetOutputDirectory() before Solve() will direct results elsewhere.");
}
}
PetscTools::Barrier("InitialiseWriter::Extension check");
}
mpWriter = new Hdf5DataWriter(*mpMesh->GetDistributedVectorFactory(),
HeartConfig::Instance()->GetOutputDirectory(),
HeartConfig::Instance()->GetOutputFilenamePrefix(),
!extend_file, // don't clear directory if extension requested
extend_file,
"Data",
mUseHdf5DataWriterCache);
/* If user has specified a chunk size and alignment parameter, pass it
* through. We set them to the same value as we think this is the most
* likely use case, specifically on striped filesystems where a chunk
* should squeeze into a stripe.
* Only happens if !extend_file, i.e. we're NOT loading a checkpoint, or
* we are loading a checkpoint but the H5 file doesn't exist yet.
*/
if (!extend_file && mHdf5DataWriterChunkSizeAndAlignment)
{
mpWriter->SetTargetChunkSize(mHdf5DataWriterChunkSizeAndAlignment);
mpWriter->SetAlignment(mHdf5DataWriterChunkSizeAndAlignment);
}
// Define columns, or get the variable IDs from the writer
DefineWriterColumns(extend_file);
// Possibility of applying a permutation
if (HeartConfig::Instance()->GetOutputUsingOriginalNodeOrdering())
{
bool success = mpWriter->ApplyPermutation(mpMesh->rGetNodePermutation(), true /*unsafe mode - extending*/);
if (success == false)
{
//It's not really a permutation, so reset
HeartConfig::Instance()->SetOutputUsingOriginalNodeOrdering(false);
}
}
if (!extend_file)
{
mpWriter->EndDefineMode();
}
return extend_file;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetUseHdf5DataWriterCache(bool useCache)
{
mUseHdf5DataWriterCache = useCache;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetHdf5DataWriterTargetChunkSizeAndAlignment(hsize_t size)
{
mHdf5DataWriterChunkSizeAndAlignment = size;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetOutputNodes(std::vector<unsigned>& nodesToOutput)
{
mNodesToOutput = nodesToOutput;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
Hdf5DataReader AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::GetDataReader()
{
if ((HeartConfig::Instance()->GetOutputDirectory() == "") || (HeartConfig::Instance()->GetOutputFilenamePrefix() == ""))
{
EXCEPTION("Data reader invalid as data writer cannot be initialised");
}
return Hdf5DataReader(HeartConfig::Instance()->GetOutputDirectory(), HeartConfig::Instance()->GetOutputFilenamePrefix());
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
bool AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::GetHasBath()
{
return false;
}
template <unsigned ELEMENT_DIM, unsigned SPACE_DIM, unsigned PROBLEM_DIM>
void AbstractCardiacProblem<ELEMENT_DIM, SPACE_DIM, PROBLEM_DIM>::SetElectrodes()
{
}
// Explicit instantiation
// Monodomain
template class AbstractCardiacProblem<1, 1, 1>;
template class AbstractCardiacProblem<1, 2, 1>;
template class AbstractCardiacProblem<1, 3, 1>;
template class AbstractCardiacProblem<2, 2, 1>;
template class AbstractCardiacProblem<3, 3, 1>;
// Bidomain
template class AbstractCardiacProblem<1, 1, 2>;
template class AbstractCardiacProblem<2, 2, 2>;
template class AbstractCardiacProblem<3, 3, 2>;
// Extended Bidomain
template class AbstractCardiacProblem<1, 1, 3>;
template class AbstractCardiacProblem<2, 2, 3>;
template class AbstractCardiacProblem<3, 3, 3>;
|
#include "timer.h"
//
// Default Constructor
//
Timer::Timer() :
start(std::chrono::high_resolution_clock::now()) {
}
//
// Copy Constructor
//
Timer::Timer(Timer& t) :
start(t.start) {
}
//
// Move Constructor
//
Timer::Timer(Timer&& t) :
start(std::move(t.start)) {
}
//
// startTime
//
void Timer::startTimer() {
this->start = std::chrono::high_resolution_clock::now();
}
//
// timeElapsed
//
long long Timer::timeElapsed() {
auto diff = std::chrono::high_resolution_clock::now() - start;
// use the difference from now and start to figure elapsed time
return std::chrono::duration_cast<std::chrono::microseconds>(diff).count();
}
//
// Destructor
//
Timer::~Timer() {
}
|
#include "MyTextEdit.h"
#include <QBuffer>
#include <QDebug>
#include <QKeyEvent>
#include <QApplication>
#include <QClipboard>
#include <QTextCursor>
#include <QDateTime>
MyTextEdit::MyTextEdit(QWidget *parent) :
QTextEdit(parent)
{
initData();
}
void MyTextEdit::keyPressEvent(QKeyEvent *event)
{
if(event->matches(QKeySequence::Paste))
{//如果是粘贴组合键
qDebug()<<"按下了粘贴组合键";
QClipboard *clipboard = QApplication::clipboard();
//还要进行类型的判断
const QMimeData *mimeData = clipboard->mimeData();
if(mimeData->hasImage())
{
qDebug()<<"剪贴板含有图片";
//插入图片
QPixmap tempPix = qvariant_cast<QPixmap>(mimeData->imageData());
pastePicture(tempPix);//处理粘贴图片的函数
}
else if(mimeData->hasText())
{
qDebug()<<"剪贴板含有文字";
this->setText(mimeData->text());
}
else if(mimeData->hasHtml())
{
qDebug()<<"剪贴板含有HTML";
this->setHtml(mimeData->html());
}
else
{
qDebug()<<"剪贴板含有其他东西";
}
}
/*
else if(event->key() == Qt::Key_Backspace)
{//按下的是退格键,
QTextEdit::keyPressEvent(event);
qDebug()<<"按下退格键";
}
*/
else
{//如果是其他情况
qDebug()<<"按下了其他组合键";
QTextEdit::keyPressEvent(event);
}
}
void MyTextEdit::pastePicture(const QPixmap &tempPix)
{
++count;
QByteArray bytes;
QBuffer buffer(&bytes);
buffer.open(QIODevice::WriteOnly);
tempPix.save(&buffer, "PNG"); //
emit signalPastePicture(bytes);
QString filePath =QString("./temp/%1.png").arg(QString::number(count));
tempPix.save(filePath, "PNG");
this->insertImage(filePath);
}
void MyTextEdit::initData()
{
count = 100;
}
void MyTextEdit::setInsertTextFormat(QFont font, QColor color)
{//简单点说就是实现随意更改输入字体和颜色
//// 设置光标的选区,使格式作用于选区内的字符,若没有选区则作用于光标所在处的字符
QTextCharFormat fmt;
fmt.setForeground(color);
fmt.setFont(font);
QTextCursor cursor = textCursor();
cursor.mergeCharFormat(fmt);
mergeCurrentCharFormat(fmt);
}
void MyTextEdit::insertImage(const QString &path)
{
this->insertHtml(QString("<img src=%1 />").arg(path));
}
void MyTextEdit::insertNickName_DateTime(const QString &nickName, const QDateTime &time, int type)
{
QTextCursor cursor = this->textCursor();
cursor.movePosition(QTextCursor::End);
this->setTextCursor(cursor);
if(MESSAGE_SELF == type)
{//前后都加<br />分割
this->insertHtml(QString("<br /><span style=\" %1\">%2 %3</span><br />")
.arg(" color:#27ff0f;").arg(nickName).arg(time.time().toString("hh:mm:ss")));
}
else if(MESSAGE_FRIEND == type)
{
this->insertHtml(QString("<br /><span style=\" %1\">%2 %3</span><br />")
.arg(" color:#1d64ff;").arg(nickName).arg(time.time().toString("hh:mm:ss")));
}
else
{
qDebug()<<"判断类型的时候出错拉";
return;
}
}
void MyTextEdit::insertChatMessage(const QString &html)
{
this->insertHtml(html);
}
|
#include "phasemap.h"
#include "dataprocess.h"
#include <algorithm>
#define _USE_MATH_DEFINES
#include <math.h>
#include <iostream>
using namespace std;
double wrap(double phs){
while (phs < M_PI)
phs += 2 * M_PI;
while (phs > M_PI)
phs -= 2 * M_PI;
return phs;
}
uchar PhaseMap::indexValid(int i, int j){
return mask.at<uchar>(i, j) && (status.at<uchar>(i,j) == 'u');
}
void PhaseMap::updatePrior(int is, int js, int ip, int jp, priority_queue<E>& PQ){
if (indexValid(is, js)){
double dp = wrap(phase_u.at<double>(is, js) - phase_u.at<double>(ip, jp));
double newprior = abs(dp) /*- 0.001 * dis.at<double>(is,js)*/;
if (newprior < prior.at<double>(is, js)){
dph.at<double>(is, js) = dp;
prior.at<double>(is, js) = newprior;
}
PQ.push(E(abs(prior.at<double>(is, js)), Vec2i(is, js), Vec2i(ip, jp)));
}
}
void PhaseMap::updatePrior(int is, int js, int ip, int jp, multiset<E>& MSET){
if (indexValid(is, js)){
double w = wrap(phase_o.at<double>(is, js) - phase_o.at<double>(ip, jp));
double ps = prior.at<double>(is, js);
prior.at<double>(is, js) = abs(w) < abs(ps) ? w : ps;
MSET.insert(E(abs(prior.at<double>(is, js)), Vec2i(is, js), Vec2i(ip, jp)));
}
}
void PhaseMap::updateSurroundPrior(int i, int j, priority_queue<E>& PQ){
updatePrior(i, j - 1, i, j, PQ);
updatePrior(i, j + 1, i, j, PQ);
updatePrior(i - 1, j, i, j, PQ);
updatePrior(i + 1, j, i, j, PQ);
}
void PhaseMap::updateSurroundPrior(int i, int j, multiset<PQElem<Vec2i>>& MSET){
updatePrior(i, j - 1, i, j, MSET);
updatePrior(i, j + 1, i, j, MSET);
updatePrior(i - 1, j, i, j, MSET);
updatePrior(i + 1, j, i, j, MSET);
}
PhaseMap::PhaseMap(double* phs, Mat m , int* size) :r(size[0]), c(size[1]){
phase_o = Mat(r, c, CV_64F, phs);
phase_u = phase_o.clone();
transpose(m, mask);
prior = Mat(r, c, CV_64F, 100.0f);
dph = Mat(r, c, CV_64F, 0.0f);
dis = Mat(r, c, CV_64F, 0.0f);
status = Mat(r, c, CV_8U, 'u');
}
void PhaseMap::unwrapMST(const Vec2i& pt){
/*for (int i = 0; i < dis.rows; i++){
for (int j = 0; j < dis.cols; j++){
dis.at<double>(i, j) = abs(i - pt(0)) + abs(j - pt(1));
}
}*/
cout << "Start pixel:(" << pt(0) << "," << pt(1) << ")" << endl;
prior.at<double>(pt) = 0;
priority_queue<E> PQ;
PQ.push(E(prior.at<double>(pt), pt, pt));
/* for debug
int count = 0;
Mat savemat;*/
while (!PQ.empty()){
E pqe = PQ.top(); PQ.pop(); // dequeue
if (status.at<uchar>(pqe.self) == 'v') continue;
else
updateSurroundPrior(pqe.self(0), pqe.self(1), PQ);
// phase unwrap
phase_u.at<double>(pqe.self) = phase_u.at<double>(pqe.parent) + dph.at<double>(pqe.self);
status.at<uchar>(pqe.self) = 'v'; //visited
/* for debug
count++;
if (count % 1000 == 999){
convert(phase_u, savemat);
imwrite(format("progress%d.bmp", count), savemat);
}*/
}
}
void PhaseMap::show(string winname, string mapname){
if (mapname == "phase")
mrishow(winname, phase_u);
else if (mapname == "prior")
mrishow(winname, prior);
else if (mapname == "mask")
imshow(winname, mask * 255);
else if (mapname == "diff")
mrishow(winname, dph);
}
|
#include <Wire.h>
int counter = 0 ;
/* Pins */
int red = 9, blue = 3, green = 5 ;
/* PWM values */
int pwm_red = 255, pwm_green = 255, pwm_blue = 255 ;
void setup() {
pinMode(red, OUTPUT);
pinMode(blue, OUTPUT);
pinMode(green, OUTPUT);
Wire.begin(0);
Wire.onReceive(receiveEvent);
Serial.begin(9600);
}
void loop() {
analogWrite(blue, pwm_blue);
analogWrite(red, pwm_red);
analogWrite(green, pwm_green);
}
void receiveEvent(int howMany) {
while (1 < Wire.available()) { // loop through all but the last
char c = Wire.read(); // receive byte as a character
}
int x = Wire.read(); // receive byte as an integer
if(counter==0){
counter=1 ;
pwm_red = 255-x;
}
else if(counter==1){
counter=2 ;
pwm_green=255-x ;
}
else if(counter==2){
counter=0;
pwm_blue=255-x ;
Serial.println((String) "r : " + pwm_red);
Serial.println((String) "g : " + pwm_green);
Serial.println((String) "b :" + pwm_blue);
}
}
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Security::Cryptography::DataProtection {
struct IDataProtectionProvider;
struct IDataProtectionProviderFactory;
struct DataProtectionProvider;
}
namespace Windows::Security::Cryptography::DataProtection {
struct IDataProtectionProvider;
struct IDataProtectionProviderFactory;
struct DataProtectionProvider;
}
namespace Windows::Security::Cryptography::DataProtection {
template <typename T> struct impl_IDataProtectionProvider;
template <typename T> struct impl_IDataProtectionProviderFactory;
}
}
|
#include <iostream>
#include <string>
using namespace std;
class Kucing {
private :
string nama;
string warna;
int umur;
public :
Kucing (string n, string w, int u){
this->nama = n;
this->warna = w;
this->umur = u;
}
void setNama(string nama){
this->nama = nama;
}
string getNama(){
return this->nama;
}
void setWarna(string warna){
this->warna = warna;
}
string getWarna(){
return this->warna;
}
void setUmur(int umur){
this->umur = umur;
}
int getumur(){
return this->umur;
}
void tickle(){
cout << "meoww ..." << endl;
}
};
class Orang{
private:
string nama;
int umur;
public:
Orang(string n , int u){
this->nama = n;
this->umur = u;
}
string getNama(){
return nama;
}
int getUmur(){
return umur;
}
void setNama(string n){
this->nama = n;
}
void setUmur(int u){
this->umur = u;
}
void sayHello(){
cout << "Hai, nama saya " << this->nama << endl << "Saya berumur " << this->umur << " tahun." << endl;
}
};
int main(){
// Orang susi = Orang("Susi Similikiti", 20);
// susi.sayHello();
return 0;
}
|
/**
* ****************************************************************************
* Copyright (c) 2015, Robert Lukierski.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ****************************************************************************
* Intel RealSense Driver.
* ****************************************************************************
*/
#ifndef REALSENSE_DRIVER_HPP
#define REALSENSE_DRIVER_HPP
#include <stdint.h>
#include <stddef.h>
#include <stdexcept>
#include <cstring>
#include <string>
#include <sstream>
#include <memory>
#include <chrono>
#include <functional>
#include <CameraDrivers.hpp>
#ifdef CAMERA_DRIVERS_HAVE_CAMERA_MODELS
#include <CameraModels/CameraModels.hpp>
#endif // CAMERA_DRIVERS_HAVE_CAMERA_MODELS
namespace drivers
{
namespace camera
{
/**
* RealSense Driver.
*
* Supports:
* BRIGHTNESS - brightness
* AUTO_EXPOSURE - automatic exposure
* SHARPNESS - sharpness
* WHITE_BALANCE - (auto)white balance
* HUE - hue
* SATURATION -saturation
* GAMMA - gamma
* SHUTTER - manual exposure
* GAIN - gain
* TEMPERATURE - backlight compensation
*/
class RealSense : public CameraDriverBase
{
public:
struct RealSenseAPIPimpl;
class RealSenseException : public std::exception
{
public:
RealSenseException(int status, const char* file, int line);
virtual ~RealSenseException() throw() { }
virtual const char* what() const throw()
{
return errormsg.c_str();
}
private:
std::string errormsg;
};
RealSense();
virtual ~RealSense();
void open(unsigned int idx = 0);
void close();
void start();
void stop();
void setDepthMode(std::size_t w, std::size_t h, unsigned int fps, bool aligned_to_color = false, bool aligned_to_rectified_color = false);
void setRGBMode(std::size_t w, std::size_t h, unsigned int fps, EPixelFormat pixfmt, bool rectified = false, bool aligned_to_depth = false);
void setIR1Mode(std::size_t w, std::size_t h, unsigned int fps);
void setIR2Mode(std::size_t w, std::size_t h, unsigned int fps);
void setDepthCallback(FrameCallback c);
void unsetDepthCallback();
void setRGBCallback(FrameCallback c);
void unsetRGBCallback();
void setIR1Callback(FrameCallback c);
void unsetIR1Callback();
void setIR2Callback(FrameCallback c);
void unsetIR2Callback();
void setMotionCallback(MotionCallback c);
void unsetMotionCallback();
void setEventCallback(EventCallback c);
void unsetEventCallback();
std::size_t getRGBWidth() const;
std::size_t getRGBHeight() const;
EPixelFormat getRGBPixelFormat() const;
std::size_t getDepthWidth() const;
std::size_t getDepthHeight() const;
EPixelFormat getDepthPixelFormat() const;
std::size_t getIR1Width() const;
std::size_t getIR1Height() const;
EPixelFormat getIR1PixelFormat() const;
std::size_t getIR2Width() const;
std::size_t getIR2Height() const;
EPixelFormat getIR2PixelFormat() const;
float getDepthScale() const;
void getRGBIntrinsics(float& fx, float& fy, float& u0, float& v0, std::array<float,5>* dist = nullptr) const;
void getDepthIntrinsics(float& fx, float& fy, float& u0, float& v0, std::array<float,5>* dist = nullptr) const;
void getIR1Intrinsics(float& fx, float& fy, float& u0, float& v0, std::array<float,5>* dist = nullptr) const;
void getIR2Intrinsics(float& fx, float& fy, float& u0, float& v0, std::array<float,5>* dist = nullptr) const;
void getExtrinsicsDepthToColor(float& tx, float& ty, float&tz, std::array<float,9>* rotMat = nullptr) const;
void getExtrinsicsColorToDepth(float& tx, float& ty, float&tz, std::array<float,9>* rotMat = nullptr) const;
#ifdef CAMERA_DRIVERS_HAVE_CAMERA_MODELS
void getRGBIntrinsics(cammod::PinholeDisparity<float>& cam) const;
void getRGBIntrinsics(cammod::PinholeDisparityBrownConrady<float>& cam) const;
void getDepthIntrinsics(cammod::PinholeDisparity<float>& cam) const;
void getDepthIntrinsics(cammod::PinholeDisparityBrownConrady<float>& cam) const;
void getIR1Intrinsics(cammod::PinholeDisparity<float>& cam) const;
void getIR1Intrinsics(cammod::PinholeDisparityBrownConrady<float>& cam) const;
void getIR2Intrinsics(cammod::PinholeDisparity<float>& cam) const;
void getIR2Intrinsics(cammod::PinholeDisparityBrownConrady<float>& cam) const;
#endif // CAMERA_DRIVERS_HAVE_CAMERA_MODELS
virtual bool getFeaturePower(EFeature fidx) { return true; }
virtual bool getFeatureAuto(EFeature fidx);
virtual void setFeatureAuto(EFeature fidx, bool b);
virtual uint32_t getFeatureValue(EFeature fidx) { return (uint32_t)getFeatureValueAbs(fidx); }
virtual float getFeatureValueAbs(EFeature fidx);
virtual uint32_t getFeatureMin(EFeature fidx);
virtual uint32_t getFeatureMax(EFeature fidx);
virtual void setFeatureValue(EFeature fidx, uint32_t val) { setFeatureValueAbs(fidx, (float)val); }
virtual void setFeatureValueAbs(EFeature fidx, float val);
private:
virtual bool isOpenedImpl() const;
virtual bool isStartedImpl() const { return is_running; }
virtual bool captureFrameImpl(FrameBuffer* cf1, FrameBuffer* cf2, FrameBuffer* cf3, FrameBuffer* cf4, int64_t timeout = 0);
std::unique_ptr<RealSenseAPIPimpl> m_pimpl;
bool is_running;
};
}
}
#endif // REALSENSE_DRIVER_HPP
|
// generated from rosidl_generator_cpp/resource/idl.hpp.em
// generated code does not contain a copyright notice
#ifndef PIVOT_MSG__MSG__PIVOT_HPP_
#define PIVOT_MSG__MSG__PIVOT_HPP_
#include "pivot_msg/msg/detail/pivot__struct.hpp"
#include "pivot_msg/msg/detail/pivot__builder.hpp"
#include "pivot_msg/msg/detail/pivot__traits.hpp"
#endif // PIVOT_MSG__MSG__PIVOT_HPP_
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QDebug>
#include <QFileDialog>
#include <QSerialPort>
#include <QSerialPortInfo>
#include <QList>
#include <QMessageBox>
#include "waveplot/wavesetting.h"
#include "serial/serialthread.h"
#include "board/gyroscopeview.h"
#include "board/magview.h"
#include "serial/serialsetting.h"
#include "map/setpoint.h"
#include "protocol/setting.h"
#include "protocol/types.h"
#include "protocol/checksum.h"
#include "protocol/helper.h"
#include "protocol/package.h"
#include "database/database.h"
#include "config/toconfig.h"
#include "database/databasethread.h"
#include <QWidget>
#include <QtGui>
#include <QPixmap>
#include <QPaintEvent>
#include <QPainter>
#include <QPoint>
#include <QRect>
#include <QRectF>
#include <QToolButton>
#include <QThread>
#include "waveplot/signalchoose.h"
#include <qwebengineview.h>
#include <QFileInfo>
#include <QtWebChannel/QtWebChannel>
#include <map/document.h>
#include <QFile>
#include <QWebChannel>
#include "iostream"
using namespace std;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow {
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
signals:
void remote_sensor_infos(void);
private slots:
void set_start();
void on_button_3D_clicked();
void on_toolButton_serial_clicked();
void on_verticalSlider_pitch_valueChanged(int value);
void on_dial_pitch_valueChanged(int value);
void on_signal_choose_clicked();
void display_dashboard();
void on_clearbutton_clicked();
void labei_display();
void display_3D();
void on_toolButton_9_clicked();
void on_toolButton_8_clicked();
void on_toolButton_mappoints_clicked();
void on_toolButton_setting_clicked();
void on_toolButton_13_clicked();
void on_toolButton_12_clicked();
void on_toolButton_14_clicked();
void on_toolButton_mappoints_send_clicked();
private:
Ui::MainWindow *ui;
Gyroscopeview *DISPLAY_gyroscope;
Magview *DISPLAY_mg;
Signalchoose *signal_choose;
QWebChannel *m_webChannel;
Document *m_jsContext;
Setpoint *setpoint;
Setting *protocolsetting;
Database *database;
};
#endif // MAINWINDOW_H
|
// Copyright (c) 2015 University of Szeged.
// Copyright (c) 2015 The Chromium Authors.
// All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sprocket/browser/ui/authentication_dialog.h"
#include "base/strings/utf_string_conversions.h"
#include "sprocket/browser/resource_dispatcher_host_delegate.h"
#if defined(USE_AURA)
#include "ui/views/controls/label.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/box_layout.h"
#endif
SprocketAuthenticationDialog::SprocketAuthenticationDialog(
SprocketResourceDispatcherHostLoginDelegate* delegate,
std::string& realm,
std::string& host)
: delegate_(delegate) {
message_ = base::ASCIIToUTF16("The server " + host + " requires a username and password. " +
"The server says: " + realm + ".");
#if defined(USE_AURA)
SetLayoutManager(new views::BoxLayout(views::BoxLayout::kVertical, 10, 10, 10));
label_ = new views::Label;
label_->SetMultiLine(true);
label_->SetText(message_);
AddChildView(label_);
AddChildView(new views::Label(base::ASCIIToUTF16("Username:")));
username_prompt_ = new views::Textfield;
AddChildView(username_prompt_);
AddChildView(new views::Label(base::ASCIIToUTF16("Password:")));
password_prompt_ = new views::Textfield;
password_prompt_->SetTextInputType(ui::TEXT_INPUT_TYPE_PASSWORD);
AddChildView(password_prompt_);
#elif defined(OS_ANDROID)
CreateJavaObject();
#endif
}
SprocketAuthenticationDialog::~SprocketAuthenticationDialog() {
}
#if defined(USE_AURA)
base::string16 SprocketAuthenticationDialog::GetWindowTitle() const {
return base::ASCIIToUTF16("Authentication required");
}
bool SprocketAuthenticationDialog::Cancel() {
delegate_->InputProvided(base::string16(), base::string16());
return true;
}
bool SprocketAuthenticationDialog::Accept(bool window_closing) {
if (window_closing)
Cancel();
else
delegate_->InputProvided(username_prompt_->text(), password_prompt_->text());
return true;
}
int SprocketAuthenticationDialog::GetDialogButtons() const {
return ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL;
}
base::string16 SprocketAuthenticationDialog::GetDialogButtonLabel(ui::DialogButton button) const {
if (button == ui::DIALOG_BUTTON_OK)
return base::ASCIIToUTF16("Login");
else if (button == ui::DIALOG_BUTTON_CANCEL)
return base::ASCIIToUTF16("Cancel");
else
return base::string16();
}
gfx::Size SprocketAuthenticationDialog::GetPreferredSize() const {
const int width = 600;
const int height = views::DialogDelegateView::GetPreferredSize().height()
+ label_->GetHeightForWidth(width);
return gfx::Size(width, height);
}
#endif
|
#pragma once
#include "GuiItem.h"
#include <iostream>
#include <map>
#include <ft2build.h>
#include <freetype\freetype.h>
using namespace std;
struct Character {
GLuint TextureID; // ID handle of the glyph texture
glm::ivec2 Size; // Size of glyph
glm::ivec2 Bearing; // Offset from baseline to left/top of glyph
GLuint Advance; // Horizontal offset to advance to next glyph
};
class GUIText : public GuiItem {
private:
glm::mat4 _projection;
const char* _fontPath;
FT_Library _ft;
FT_Face _face;
int _fontSize;
map<GLchar, Character> Characters;
GLuint VAO, VBO;
Shader *_shader;
bool initFT();
bool initFace();
void loadFont();
void setupBuffers();
public:
GUIText();
GUIText(Shader *shader, glm::mat4 proj, const char* fontPath, int size) : _shader(shader), _projection(proj), _fontPath(fontPath), _fontSize(size) {}
~GUIText();
bool init();
void setFontSize(int size);
void renderText(std::string text, GLfloat x, GLfloat y, GLfloat scale, glm::vec3 color);
void updateProj(glm::mat4 proj) { _projection = proj; } // Update the width and height when resize window
void draw(DrawData &data);
void update(UpdateData &data);
};
|
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll n,a[150005],is[150005];
int main()
{
while(~scanf("%lld",&n)) {
memset(is,0,sizeof(is)); //初始化状态,因为是多个测试用例
for(int i = 0; i < n; i++)
cin >> a[i];
sort(a,a+n);
ll sum = 0; //最有解
for(int i = 0; i < n; i++) {
if(is[a[i]-1] == 0 && a[i] != 1) { //先判断该数的左边
sum++;
is[a[i-1]] = 1;
}
else if(is[a[i]] == 0 ) { //左边不满足,判断该数位置
sum++;
is[a[i]] = 1;
}
else if(is[a[i]+1] == 0) { //该数本身位置不满足,判断右边
sum++;
is[a[i]+1] = 1;
}
}
cout << sum << endl;
}
return 0;
}
|
class Solution {
public:
int countBinarySubstrings(string s) {
int n = s.size(), zeros = 0, ones= 0, res = 0;
if (s[0] == '0') zeros++;
else ones++;
for (int i = 1; i < n; i++) {
if (s[i] == '0') {
zeros = (s[i - 1] == '0') ? zeros + 1 : 1;
if (ones >= zeros) res++;
}
else if (s[i] == '1') {
ones = (s[i - 1] == '1') ? ones + 1 : 1;
if (zeros >= ones) res++;
}
}
return res;
}
};
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Management.2.h"
WINRT_EXPORT namespace winrt {
namespace Windows::Management {
struct WINRT_EBO MdmAlert :
Windows::Management::IMdmAlert
{
MdmAlert(std::nullptr_t) noexcept {}
MdmAlert();
};
struct WINRT_EBO MdmSession :
Windows::Management::IMdmSession
{
MdmSession(std::nullptr_t) noexcept {}
};
struct MdmSessionManager
{
MdmSessionManager() = delete;
static Windows::Foundation::Collections::IVectorView<hstring> SessionIds();
static Windows::Management::MdmSession TryCreateSession();
static void DeleteSessionById(hstring_view sessionId);
static Windows::Management::MdmSession GetSessionById(hstring_view sessionId);
};
}
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: eyohn <sopka13@mail.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/08 18:17:14 by eyohn #+# #+# */
/* Updated: 2021/07/08 20:18:27 by eyohn ### ########.fr */
/* */
/* ************************************************************************** */
#include "AMateria.hpp"
#include "ICharacter.hpp"
#include "Character.hpp"
#include "Cure.hpp"
#include "Ice.hpp"
#include "IMateriaSource.hpp"
#include "MateriaSource.hpp"
int main(void)
{
IMateriaSource* src = new MateriaSource();
src->LearnMateria(new Ice());
src->LearnMateria(new Cure());
ICharacter* me = new Character("me");
AMateria* tmp;
tmp = src->createMateria("ice");
me->equip(tmp);
tmp = src->createMateria("cure");
me->equip(tmp);
tmp = src->createMateria("ice");
me->equip(tmp);
tmp = src->createMateria("ice");
me->equip(tmp);
ICharacter* bob = new Character("bob");
ICharacter* loly = new Character("loly");
me->use(0, *bob);
me->use(1, *bob);
me->use(2, *loly);
me->use(3, *loly);
delete loly;
delete bob;
delete me;
delete src;
return 0;
}
|
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include<iostream>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode *dummy=new ListNode(0);
dummy->next=head;
ListNode *newd=dummy;
ListNode *fir=dummy->next;
ListNode *sec=dummy->next->next;
ListNode *last=dummy->next->next->next;
while(sec!=NULL){
helper(newd,fir,sec,last);
if(last==NULL||last->next==NULL)
break;
newd=fir;
fir=last;
sec=last->next;
last=last->next->next;
}
return dummy->next;
}
private:
void helper(ListNode *newd, ListNode *fir, ListNode *sec, ListNode *last){
newd->next=fir->next;
fir->next=sec->next;
sec->next=fir;
}
};
|
#include <string>
#include <iostream>
#include <fstream>
#include "CipherInterface.h"
#include "AES.h"
#include "DES.h"
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
using namespace std;
/*Case insensitive string comparison helper function used in processing command line arguments*/
bool iequals(const string&, const string&);
/*Error checking to see if we have correctly set up an instance of our cipher*/
void assertValidCipherAssignment(const CipherInterface*);
/*Validate the key against the type of cypher selected and assign the cipher's key*/
void validateAndSetKey(CipherInterface* const, const string&);
/*Perform either encryption or decryption and write to output file*/
void performOperation(CipherInterface* const, const string&, const string&, const string&, const bool&);
int main(int argc, char** argv)
{
//Testing
//CipherInterface* cipher = new DES();
//CipherInterface* cipher1 = new AES();
//validateAndSetKey(cipher, "0123456789abcdef");
//validateAndSetKey(cipher1, "00112233445566778899aabbccddeeff");
//performOperation(cipher, "enc", "small.txt", "desencrypt.txt", false);
//performOperation(cipher1, "enc", "small.txt", "aesencrypt.txt", true);;
//performOperation(cipher, "enc", "big.txt", "desencrypt.txt", false);
//performOperation(cipher1, "enc", "big.txt", "aesencrypt.txt", true);
//performOperation(cipher, "dec", "desencrypt.txt", "desdecrypt.txt", false);
//performOperation(cipher1, "dec", "csencrypt.txt", "aesdecrypt.txt", true);
//return 0;
/*Make sure we have only 5 command line arguments before moving forward*/
if (argc != 6)
{
cout << "cipher.exe only accepts 5 arguments: <CIPHER NAME> <KEY> <ENC/DEC> <INPUTFILE> <OUTPUT FILE>" << endl;
exit(-1);
}
/*Variables used to parse the command line argument and execute the ciphers dynamically*/
string cipherName = argv[1];
string key = argv[2];
string operation = argv[3];
string inputFileName = argv[4];
string outputFileName = argv[5];
CipherInterface* cipher = NULL; /*pointer to an instance of our cipher*/
bool isAES; //false = DES, true = AES
if (iequals(cipherName, "AES"))
{
cipher = new AES();
isAES = true;
if (iequals(operation, "ENC"))
{
key.insert(0, 1, '1');
}
else
{
key.insert(0, 1, '0');
}
}
else if (iequals(cipherName, "DES"))
{
isAES = false;
cipher = new DES();
}
else
{
assertValidCipherAssignment(cipher);
}
validateAndSetKey(cipher, key);
performOperation(cipher, operation, inputFileName, outputFileName, isAES);
return 0;
}
void validateAndSetKey(CipherInterface* const cipher, const string& key)
{
bool validKey = cipher->setKey((const unsigned char *)key.c_str());
if (!validKey)
{
cout << "This key is not valid for the selected cipher!" << endl;
exit(-1);
}
}
void performOperation(CipherInterface* const cipher, const string& operation, const string& inputFilename, const string& outputFilename, const bool& isAES)
{
const char* c_in_filename = inputFilename.c_str();
const char* c_out_filename = outputFilename.c_str();
FILE *fileReader;
FILE *fileWriter;
/*Encrypt or decrypt block by block*/
if (iequals(operation, "ENC"))
{
fileReader = fopen(c_in_filename, "rb");
fileWriter = fopen(c_out_filename, "wb");
//Depending on the algorithm used we will be encrypting/decrypting using different block sizes
if (isAES)
{
bool doneEncrypting = false;
while (!doneEncrypting)
{
unsigned char plaintextBlock[16];
memset(plaintextBlock,'\0', 16); //assume padding
uint8_t charsReadSuccessfully = fread(plaintextBlock, 1, 16, fileReader);
if(charsReadSuccessfully != 16) //If block is incomplete
{
unsigned char * ciphertextBlockPtr;
uint8_t charsWroteSuccessfully;
uint8_t charsRemaining = 16 - charsReadSuccessfully; //Get remaining characters in case block is unfinished
if(charsRemaining != 16) // If charsRemaining is 16, then the block is empty anyways so don't bother with padding
{
ciphertextBlockPtr = cipher->encrypt(plaintextBlock); //encrypt padded block
charsWroteSuccessfully = fwrite(ciphertextBlockPtr, 1, 16, fileWriter); //write the last block to file
delete [] ciphertextBlockPtr;
if(charsWroteSuccessfully != 16)
{
cout << "Something may be up with file writing AES ENC";
}
}
else
{
charsRemaining = 0;
}
memset(plaintextBlock,'\0', 15); //Create padding block that will give us information on the amount of padding used.
plaintextBlock[15] = charsRemaining; //Set the last byte to the amount of padding used is the last
ciphertextBlockPtr = cipher->encrypt(plaintextBlock); //encrypt padding info block
charsWroteSuccessfully = fwrite(ciphertextBlockPtr, 1, 16, fileWriter);//write padding info block
delete [] ciphertextBlockPtr; //free memory
if(charsWroteSuccessfully != 16)
{
cout << "Something may be up with file writing AES ENC";
}
doneEncrypting = true; //We are done encrypting
}
else //block is full, encrypt normally
{
unsigned char * ciphertextBlockPtr = cipher->encrypt(plaintextBlock); //encrypt block
uint8_t charsWroteSuccessfully = fwrite(ciphertextBlockPtr, 1, 16, fileWriter);
delete [] ciphertextBlockPtr;
if(charsWroteSuccessfully != 16)
{
cout << "Something may be up with file writing AES ENC";
}
}
}
}
else //DES
{
bool doneEncrypting = false;
while (!doneEncrypting)
{
unsigned char plaintextBlock[8];
memset(plaintextBlock,'\0', 8);
uint8_t charsReadSuccessfully = fread(plaintextBlock, 1, 8, fileReader);
if(charsReadSuccessfully != 8)
{
unsigned char * ciphertextBlockPtr;
uint8_t charsWroteSuccessfully;
uint8_t charsRemaining = 8 - charsReadSuccessfully;
if(charsRemaining != 8)
{
ciphertextBlockPtr = cipher->encrypt(plaintextBlock);
charsWroteSuccessfully = fwrite(ciphertextBlockPtr, 1, 8, fileWriter);
delete [] ciphertextBlockPtr;
if(charsWroteSuccessfully != 8)
{
cout << "Something may be up with file writing DES ENC";
}
}
else
{
charsRemaining = 0;
}
memset(plaintextBlock,'\0', 7);
plaintextBlock[7] = charsRemaining;
ciphertextBlockPtr = cipher->encrypt(plaintextBlock);
charsWroteSuccessfully = fwrite(ciphertextBlockPtr, 1, 8, fileWriter);
delete [] ciphertextBlockPtr;
if(charsWroteSuccessfully != 8)
{
cout << "Something may be up with file writing DES ENC";
}
doneEncrypting = true;
}
else
{
unsigned char * ciphertextBlockPtr = cipher->encrypt(plaintextBlock);
uint8_t charsWroteSuccessfully = fwrite(ciphertextBlockPtr, 1, 8, fileWriter);
delete [] ciphertextBlockPtr;
if(charsWroteSuccessfully != 8)
{
cout << "Something may be up with file writing DES ENC";
}
}
}
}
fclose(fileReader);
fclose(fileWriter);
}
else if (iequals(operation, "DEC"))
{
fileReader = fopen(c_in_filename, "rb");
fileWriter = fopen(c_out_filename, "wb");
fseek (fileReader , 0 , SEEK_END);
long fileSize = ftell(fileReader); //calculate file size
rewind(fileReader);
if (isAES)
{
long numBlocksToDecrypt = ceil(fileSize / 16.0); //n = (size -1) / blocksize
for(int i = 0; i < numBlocksToDecrypt; i++)
{
unsigned char ciphertextBlock[16];
memset(ciphertextBlock,'\0', 16);
uint8_t charsReadSuccessfully = fread(ciphertextBlock, 1, 16, fileReader);
if(charsReadSuccessfully != 16)
{
cout << "Issue reading file during AES DEC\n";
}
unsigned char * plaintextBlockPtr = cipher->decrypt(ciphertextBlock);
if(i == numBlocksToDecrypt - 2) //If we're on the final block before the padding block
{
unsigned char encryptedPaddingInfoBlock[16]; //We are going to look ahead at the padding block to see how we'll handle the last legit block
charsReadSuccessfully = fread(encryptedPaddingInfoBlock, 1, 16, fileReader); //read the next block which should be the encrypted padding information block
if(charsReadSuccessfully != 16)
{
cout << "Issue reading padding block during AES DEC\n";
}
unsigned char * paddingInfoBlock = cipher->decrypt(encryptedPaddingInfoBlock); //decrypt that block to get padding information
int paddingNumber = paddingInfoBlock[15];
delete [] paddingInfoBlock; //done using, free memory
if(paddingNumber != 0)//If last byte of padding block is 0 or null, padding was not used.
{
int8_t charsWroteSuccessfully = fwrite(plaintextBlockPtr, 1, 16 - paddingNumber, fileWriter); //Padding was used so write back the non-padded portion of the last block
delete [] plaintextBlockPtr;
if(charsWroteSuccessfully != 16 - paddingNumber)
{
cout << "Issue writing final block to file during AES DEC\n";
}
break;
}
else
{
int8_t charsWroteSuccessfully = fwrite(plaintextBlockPtr, 1, 16, fileWriter); //Padding was not used, so write the last block in whole
delete [] plaintextBlockPtr;
if(charsWroteSuccessfully != 16 )
{
cout << "Issue writing a block to file during AES DEC\n";
}
break;
}
}
else
{
fwrite(plaintextBlockPtr, 1, 16, fileWriter);
delete [] plaintextBlockPtr;
}
}
}
else //DES
{
long numBlocksToDecrypt = ceil(fileSize / 8.0); //n = (size -1) / blocksize (the -1 is to account for that last byte).
for(int i = 0; i < numBlocksToDecrypt; i++)
{
unsigned char ciphertextBlock[8];
memset(ciphertextBlock,'\0', 8);
uint8_t charsReadSuccessfully = fread(ciphertextBlock, 1, 8, fileReader);
if(charsReadSuccessfully != 8)
{
cout << "Issue reading file during DES DEC\n";
}
unsigned char * plaintextBlockPtr = cipher->decrypt(ciphertextBlock);
if(i == numBlocksToDecrypt - 2) //If we're on the second to last block
{
unsigned char encryptedPaddingInfoBlock[8];
charsReadSuccessfully = fread(encryptedPaddingInfoBlock, 1, 8, fileReader); // read the next block which should be the encrypted padding information block
if(charsReadSuccessfully != 8)
{
cout << "Issue reading file during DES DEC\n";
}
unsigned char * paddingInfoBlock = cipher->decrypt(encryptedPaddingInfoBlock); //decrypt that block to get padding information
int paddingNumber = paddingInfoBlock[7];
delete [] paddingInfoBlock;
if(paddingNumber != 0)//If last byte of padding block is not 0 or null, padding was used.
{
uint8_t charsWroteSuccessfully = fwrite(plaintextBlockPtr, 1, 8 - paddingNumber, fileWriter);
delete [] plaintextBlockPtr;
if(charsWroteSuccessfully != 8 - paddingNumber)
{
cout << "Issue writing final block to file during DES DEC\n";
}
break;
}
else
{
fwrite(plaintextBlockPtr, 1, 8, fileWriter);
delete [] plaintextBlockPtr;
break;
}
}
else
{
fwrite(plaintextBlockPtr, 1, 8, fileWriter);
delete [] plaintextBlockPtr;
}
}
}
fclose(fileReader);
fclose(fileWriter);
}
else
{
cout << "This is not a valid operation!" << endl;
exit(-1);
}
}
bool iequals(const string& a, const string& b) //case insensitive comparison
{
unsigned int sz = a.size();
if (b.size() != sz)
return false;
for (unsigned int i = 0; i < sz; ++i)
if (tolower(a[i]) != tolower(b[i]))
return false;
return true;
}
void assertValidCipherAssignment(const CipherInterface* cipher)
{
/*Error checking*/
if (!cipher)
{
fprintf(stderr, "ERROR [%s %s %d]: could not allocate memory\n",
__FILE__, __FUNCTION__, __LINE__);
exit(-1);
}
else
{
cout << "Undefined state!";
}
}
|
/*
Author: Nayeemul Islam Swad
Idea:
- Let dp[i] be the maximum answer if we only consider the intervals
(l, r, a) with i <= l. Our final answer would be dp[1].
- To calculate dp[i], let's iterate over the possible positions j of the
first occurrence of a set bit and take maximum among them. To handle
the case when there's no set bit in [i, n], dp[i] should be at least 0.
- Now, we need to find dp[i] once we fix j. Its actually
(dp[j + 1] + contribution(j)), where contribution(j) = sum of a_k such
that j lies in the interval (l_k, r_k, a_k) and i <= l_k.
- To quickly find the maximum among all such positions for j and quickly
calculate contribution(j), we can use lazy segment tree. We'll maintain
lz[j] = dp[j] + contribution(j - 1) using the lazy segment tree.
- We'll iterate over i in decreasing order starting at n. When calculating
dp[i] notice that contribution(j) remains almost the same as it was when
we calculated dp[i + 1], it might only change if some intervals starting
at i covers j. So we should iterate over the intervals (l_k, r_k, a_k)
such that l_k = i and add a_k to lz[i + 1 ... r_k + 1] using the lazy
segment tree. Then we can query the segment tree for
dp[i] = query(i + 1... n + 1) and set lz[i] = dp[i] in the segment tree.
*/
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
#define x first
#define y second
#ifdef LOCAL
#include "/Users/swad/Desktop/CP/debug.h"
#endif
const int N = int(2e5) + 10;
template <typename T>
class LazyST {
private:
int n;
vector<T> a;
vector<T> st, lz;
T lz_default;
T (*st_merge)(T, T);
T (*lz_merge)(T, T);
void build(int stI, int L, int R) {
if (L == R) {
st[stI] = a[L - 1];
return;
}
int mid = (L + R) >> 1;
build(stI << 1, L, mid);
build(stI << 1 | 1, mid + 1, R);
st[stI] = st_merge(st[stI << 1], st[stI << 1 | 1]);
}
void update(int stI, int L, int R, int l, int r, T val) {
if (l <= L && R <= r) lz[stI] = lz_merge(lz[stI], val);
else {
int mid = (L + R) >> 1;
if (l <= mid) update(stI << 1, L, mid, l, min(r, mid), val);
if (mid + 1 <= r) update(stI << 1 | 1, mid + 1, R, max(l, mid + 1), r, val);
}
if (L == R) st[stI] = lz_merge(a[L - 1], lz[stI]);
else st[stI] = lz_merge(st_merge(st[stI << 1], st[stI << 1 | 1]), lz[stI]);
}
T query(int stI, int L, int R, int l, int r) {
if (l <= L && R <= r) return st[stI];
int mid = (L + R) >> 1;
if (r <= mid) return lz_merge(query(stI << 1, L, mid, l, r), lz[stI]);
else if (mid + 1 <= l) return lz_merge(query(stI << 1 | 1, mid + 1, R, l, r), lz[stI]);
else return st_merge(
lz_merge(query(stI << 1, L, mid, l, mid), lz[stI]),
lz_merge(query(stI << 1 | 1, mid + 1, R, mid + 1, r), lz[stI])
);
}
public:
LazyST(vector<T> a, T (*st_merge)(T, T), T (*lz_merge)(T, T), T lz_default, bool build_init) {
n = a.size();
this->a = a;
st.resize(4 * n + 1);
lz.resize(4 * n + 1, lz_default);
this->lz_default = lz_default;
this->st_merge = st_merge;
this->lz_merge = lz_merge;
if (build_init) build(1, 1, n);
}
T query(int l, int r) { // range [l, r], 1-based index
return query(1, 1, n, l, r);
}
void update(int l, int r, T val) { // range [l, r], 1-based index
update(1, 1, n, l, r, val);
}
};
int n, m;
vector<pii> ranges_at[N];
int main() {
#ifdef LOCAL
freopen("in", "r", stdin);
freopen("out", "w", stdout);
#endif
scanf("%d %d", &n, &m);
for (int i = 1; i <= m; i++) {
int l, r, val;
scanf("%d %d %d", &l, &r, &val);
ranges_at[l].push_back({r, val});
}
vector<ll> dps(n + 1, 0);
LazyST<ll> lzst = LazyST<ll>(
dps,
[](ll i, ll j) {return max(i, j);},
[](ll i, ll j) {return i + j;},
0,
false
);
for (int l = n; l >= 1; l--) {
for (pii p : ranges_at[l]) lzst.update(l + 1, p.x + 1, p.y);
lzst.update(l, l, max(0LL, lzst.query(l + 1, n + 1)));
}
printf("%lld\n", lzst.query(1, 1));
return 0;
}
|
#include "BasicCalculator.hpp"
#include <stack>
using namespace std;
int BasicCalculator::calculate(string s) {
vector<BasicCalculator::Token> tks = parse(s);
stack<char> ops;
stack<int> vals;
for (auto &t : tks) {
if (t.type == BasicCalculator::Token::OPERAND)
vals.push(t.tk.val);
else if (t.tk.op == ')') {
if (ops.top() != '(') {
int second = vals.top();
vals.pop();
int first = vals.top();
vals.pop();
vals.push(calc(first, second, ops.top()));
ops.pop();
}
ops.pop();
} else if (t.tk.op == '(')
ops.push(t.tk.op);
else {
if (!ops.empty() && (ops.top() == '+' || ops.top() == '-')) {
int second = vals.top();
vals.pop();
int first = vals.top();
vals.pop();
vals.push(calc(first, second, ops.top()));
ops.pop();
}
ops.push(t.tk.op);
}
}
if (!ops.empty()) {
int second = vals.top();
vals.pop();
int first = vals.top();
vals.pop();
vals.push(calc(first, second, ops.top()));
ops.pop();
}
return vals.top();
}
vector<BasicCalculator::Token> BasicCalculator::parse(string s) {
vector<BasicCalculator::Token> res;
int i = 0;
int j = 0;
while (i < s.size()) {
BasicCalculator::Token t;
j = i;
if (s[j] == '(' || s[j] == ')' || s[j] == '+' || s[j] == '-') {
t.type = BasicCalculator::Token::OPERATOR;
t.tk.op = s[j];
res.push_back(t);
i++;
} else if (s[j] == ' ')
i++;
else {
do {
j++;
} while (j < s.size() && isdigit(s[j]));
t.type = BasicCalculator::Token::OPERAND;
t.tk.val = stoi(s.substr(i, j - i));
res.push_back(t);
i = j;
}
}
return res;
}
int BasicCalculator::calc(int first, int second, char op) {
if (op == '+')
return first + second;
else
return first - second;
}
|
/*
* Copyright (c) 2012 Joey Yore
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <iostream>
#include "../datastructures/hashTable.h"
using namespace std;
int main() {
//Constructors
cout << "Testing Constructors...";
HashTable<int> cht1;
HashTable<int> cht2(150);
HashTable<int> *cht3 = new HashTable<int>;
cout << "PASS" << endl;
//Put
bool tput = true;
cout << "Testing Put...";
tput &= (cht1.put("test1",10) == 0);
tput &= (cht1.put("test2",10) == 0);
tput &= (cht1.put("test3",10) == 0);
tput &= (cht1.put("test1",20) == 1);
tput &= (cht3->put("test1",20) == 0);
cout << (tput ? "PASS" : "FAIL") << endl;
//Get
bool tget = true;
int v;
cout << "Testing Get...";
tget &= (cht1.get("test1",v) == 0) && (v == 20);
tget &= (cht1.get("test2",v) == 0) && (v == 10);
tget &= (cht1.get("test3",v) == 0) && (v == 10);
tget &= (cht1.get("test4",v) == -1);
cout << (tget ? "PASS" : "FAIL") << endl;
//Destructors
cout << "Testing Destructor...";
delete cht3;
cout << "PASS" << endl;
return 0;
}
|
#ifndef __SHORTCUT_H__
#define __SHORTCUT_H__
#include <vector>
#include <string>
#include "SDL/include/SDL_scancode.h"
class Shortcut
{
public:
Shortcut();
Shortcut(std::string name, std::vector<SDL_Scancode> keys);
bool Pressed();
bool Held();
public:
std::string name;
std::vector<SDL_Scancode> keys;
friend class ModuleGui;
};
#endif
|
#include <iostream>
#include <vector>
#include <algorithm>
//#include <exception>
using namespace std;
namespace Graph {
auto Parents = vector<int>();
struct Edge {
Edge(int start, int end, int weight):Start(start),End(end),Weight(weight)
{}
int Weight;
int Start;
int End;
bool operator<(const Edge &rhs) const
{
return Weight < rhs.Weight;
}
};
ostream& operator<<(ostream& os, const Edge& edge)
{
os << "(" << edge.Start << " " << edge.End << ") -> " << edge.Weight;
return os;
}
void SetRoot(int node, int root)
{
Parents[node] = root;
}
int FindRoot(int node)
{
return Parents[node];
}
vector<Edge*> Kruskal(int numVertices, vector<Edge> &edges)
{
auto minSpanForest = vector<Edge*>();
for( int i=0; i<numVertices; i++) {
Parents.push_back(i);
}
sort(edges.begin(), edges.end());
for( auto pE = edges.begin(); pE != edges.end(); pE++ ) {
auto rootS = FindRoot(pE->Start);
auto rootE = FindRoot(pE->End);
if( rootE == rootS ) {
continue;
}
if( rootS == pE->Start ) {
SetRoot(pE->Start, rootE);
}
else {
SetRoot(pE->End, rootS);
}
minSpanForest.push_back(&(*pE));
}
return minSpanForest;
}
}
int main()
{
using namespace Graph;
int numVertices = 9;
auto graphEdges = vector<Edge>({
Edge(0,3,9),
Edge(0,5,4),
Edge(0,8,5),
Edge(1,4,8),
Edge(1,7,7),
Edge(2,6,12),
Edge(3,5,2),
Edge(3,6,8),
Edge(3,8,20),
Edge(4,7,10),
Edge(6,8,7),
});
auto minSpanForest = Kruskal(numVertices, graphEdges);
for( auto edge : graphEdges ) {
cout << edge << endl;
}
cout << endl;
for( auto edge : minSpanForest ) {
cout << *edge << endl;
}
}
|
#include<bits/stdc++.h>
using namespace std;
bool repeatedSubstringPattern(string s)
{
int n = s.size();
for(int i=2;i<=n;i++)
{
if((n%i) !=0)// it doesnot divide the string into equal parts.
{
continue;
}
int len = n/i;
string temp = "";
for(int j=0;j<n/len;j++)
{
temp = temp + s.substr(0,len);
}
if(temp==s)
{
return true;
}
}
return false;
}
int main()
{
string s;
cin >> s;
cout << repeatedSubstringPattern(s) << endl;
return 0;
}
|
#include <Model/thanos.h>
#include <Model/utils.h>
#include <Model/dataStructures/LinkedList.h>
#include <Model/Mundo/RangoEtario.h>
#include <Model/Mundo/familia.h>
#include <Model/Mundo/Acciones.h>
Persona::Persona(int _ID, eGenero _genero, string _nombre, string _apellido, string _creencia, string _profesion, Ubicacion * ub){
ID = _ID;
nombre = _nombre;
apellido = _apellido;
genero = _genero;
creencia = _creencia;
profesion = _profesion;
ubicacion = ub;
amigos = new LinkedList<Persona *>();
killLog = new LinkedList<string>();
savedLog = new LinkedList<string>();
edad = new RangoEtario();
familia = new Familia(this);
edad->generarFecha();
edad->asignarRango();
generarEstado();
isAlive = true;
deporte = new Ejercicio();
acciones = new Acciones();
puntosThanos = 0;
}
void Persona::generarEstado(){
int probEstado = Utils::getRandom(0, 100);
if (probEstado < 10 || RangoEtario::esMenor(edad->rango)){
estado = soltero;
} else if (probEstado < 20){
estado = divorciado;
} else {
estado = casado;
}
}
// Retorna la ID de una persona
int Persona::getID(){
return ID;
}
// Retorna la ID de una persona
int Persona::getPoints(Persona * persona){
return (persona == NULL) ? 0: persona->getPoints();
}
// Retorna la ID de una persona
int Persona::getPoints(){
return puntosThanos;
}
// Dada una persona retorna su ID (se usa para el algoritmo de ordenamiento)
// Si es nulo retorna 0
int Persona::getID(Persona * persona){
return (persona == NULL) ? 0 : persona->getID();
}
void Persona::generarAcciones(){
}
// Retorna true si tienen algun amigo en comun
bool Persona::amigosComun(Persona * persona){
Node<Persona *> * nodo = persona->amigos->firstNode;
for (int i = 0; i < (int) persona->amigos->length; i++){
Persona * comun = nodo->data;
Node<Persona *> * tmp = comun->amigos->firstNode;
for (int j = 0; j < comun->amigos->length; j++){
if (tmp->data->ID == ID){
return true;
}
tmp = tmp->next;
}
nodo = nodo->next;
}
return false;
}
// Genera los amigos de las personas
void Persona::generarAmigos(vector<Persona *> vPersonas){
int cant = Utils::getRandom(0, 50);
if (cant == 0) return;
int start = Utils::getRandom(0, vPersonas.size() - 1);
for (int i = start; i < (int) vPersonas.size(); i++){
if (amigos->length >= cant) break;
if (ubicacion != NULL && vPersonas[i]->ubicacion->pais == ubicacion->pais){
amigos->add(vPersonas[i]);
} else if (Utils::getRandom(0, 100) <= 40){
amigos->add(vPersonas[i]);
} else if (Utils::getRandom(0, 100) <= 70 && amigosComun(vPersonas[i])){
amigos->add(vPersonas[i]);
vPersonas[i]->amigos->add(this);
}
}
}
string Persona::getInfo(){
string estaVivo = (isAlive) ? "Esta vivo" : "Esta muerto";
string anio = to_string(edad->fechaDeNacimiento[2]);
string mes = to_string(edad->fechaDeNacimiento[1]);
string dia = to_string(edad->fechaDeNacimiento[0]);
string conyugue = (familia->conyugue == NULL) ? "N/A" : familia->conyugue->nombre + ", ID#" + to_string(familia->conyugue->ID);
string info = "Persona: " + nombre + " " + apellido + "\n";
info += "ID#" + to_string(ID) + "\n";
info += "Vivo: " + estaVivo + "\n";
info += "Creencia: " + creencia + "\n";
info += "Profesion: " + profesion + "\n";
if (ubicacion != NULL)
info += "Continente: " + ubicacion->continente + ", Pais: " + ubicacion->pais + "\n";
info += "Fecha de nacimiento: " + anio + "/" + mes + "/" + dia + "\n";
info += "Conyugue: " + conyugue + "\n";
info += "----------------------------------------------\n";
info += "Log de muertes: \n";
for (int i = 0; i < killLog->length; i++){
info += killLog->get(i) + "\n";
}
info += "----------------------------------------------\n";
info += "Log de rescates: \n";
for (int i = 0; i < savedLog->length; i++){
info += savedLog->get(i) + "\n";
}
info += "----------------------------------------------\n";
info += "Deportes: \n";
info += "Cantidad de veces por semana: " + to_string(deporte->cantidad) + "\n";
info += "Lista: \n";
for (int i = 0; i < (int) deporte->vDeportes.size(); i++){
info += deporte->vDeportes[i] + " ";
}
info += "\n";
info += "----------------------------------------------\n";
info += "Paises visitados: \n";
for (int i = 0; i < (int) turismo.size(); i++)
if (turismo[i] != NULL)
if (!turismo[i]->pais.empty())
info += turismo[i]->pais + " ";
info += "\n";
info += "----------------------------------------------\n";
info += "Lista de acciones: \n";
info += acciones->getInfo();
info += "\n";
info += "----------------------------------------------\n";
info += "Amigos: \n";
for (int j = 0; j < amigos->length; j++){
info += "ID#" + to_string(amigos->get(j)->ID) + ", Nombre: " + amigos->get(j)->nombre + "\n";
}
info += "\n";
info += "----------------------------------------------\n";
info += "Hijos: \n";
for (int j = 0; j < familia->hijos->length; j++){
info += "ID#" + to_string(familia->hijos->get(j)->ID) + ", Nombre: " + familia->hijos->get(j)->nombre + "\n";
}
info += "\n";
info += "----------------------------------------------\n";
return info;
}
|
//
// Created by yulichao on 2020/9/27.
#include <iostream>
using namespace std;
/*static*/ int gsi = 100;
/*static*/ void staticTestPrint() {
cout << "I am static test print !" << endl;
}
//
|
#ifndef PERMUTATION_SEQUENCE_HPP_
#define PERMUTATION_SEQUENCE_HPP_
#include <string>
#include <vector>
using namespace std;
class PermutationSequence {
public:
string getPermutation(int n, int k);
};
#endif // PERMUTATION_SEQUENCE_HPP_
|
#include<bits/stdc++.h>
using namespace std;
const int N=1e6+2;
int n,m,d[N];
string s[N];
struct box{
int x,y,w;
};
int dx[]={0,0,-1,1,-1,-1,1,1};
int dy[]={1,-1,0,0,-1,1,1,-1};
int get_id(int i,int j){
return (i-1)*m+j;
}
void init(){
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++) d[get_id(i,j)]=1e9;
}
void input(){
for (int i=1;i<=n;i++){
cin>>s[i];
s[i] = " "+s[i];
}
}
void bfs_01(){
deque <box> dq;
for (int i=2;i<=n;i++){
if (s[i][1]!='@'){
d[get_id(i,1)]=bool(s[i][1]=='.');
dq.push_back({i,1,d[get_id(i,1)]});
}
}
for (int i=2;i<=m;i++){
if (s[n][i]!='@'){
d[get_id(n,i)]=bool(s[n][i]=='.');
dq.push_back({n,i,d[get_id(n,i)]});
}
}
while (dq.size()){
box u = dq.front();
dq.pop_front();
//cout<<u.x<<" "<<u.y<<" "<<u.w<<endl;
for (int i=0;i<8;i++){
int vx = u.x + dx[i];
int vy = u.y + dy[i];
if (vx>=1 && vx<=n && vy>=1 && vy<=m)
if (s[vx][vy]!='@'){
int uv = bool(s[vx][vy]=='.');
if (d[get_id(vx,vy)]>u.w + uv){
d[get_id(vx,vy)] = u.w + uv;
if (uv==0) dq.push_front({vx,vy,d[get_id(vx,vy)]});
else dq.push_back({vx,vy,d[get_id(vx,vy)]});
}
}
}
}
}
void solve(){
if (s[1][1]=='#' || s[n][m]=='#') {
cout<<0<<'\n';
return;
}
if (s[1][1]=='.' || s[n][m]=='.'){
cout<<1<<'\n';
return;
}
bfs_01();
int res = 1e9;
for (int i=2;i<=m;i++)
res=min(res,d[get_id(1,i)]);
for (int i=1;i<n;i++)
res=min(res,d[get_id(i,m)]);
if (res==1e9) res = -1;
cout<<res<<'\n';
}
int main(){
//freopen("atm.inp","r",stdin);
while (1){
cin>>n>>m;
if (n==0 && m==0) break;
init();
input();
solve();
}
return 0;
}
|
//
// Created by vladimir on 10/5/19.
//
#ifndef TAREA1_SEGURIDAD_STORE_H
#define TAREA1_SEGURIDAD_STORE_H
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <string>
#include <regex>
#include <mysql_connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
using namespace std;
class Store {
private:
/*
* Variable initialization
*/
// Database information
string sql_db_url, sql_db_username, sql_db_password;
// Determines if user is login
bool user_login, user_login_fail;
// Stores logged user information
string user_id, user_name;
// Boolean values for dynamic product templates
bool product_template, product_template_conn;
/*
* Methods
*/
static bool check_product_conn_URL(const string &line);
static bool check_product_URL(const string &line);
static string format_email(const string &line);
static string get_cookie_token(const string &line);
static string get_product_id_from_URL(const string &line);
static string get_token(const string &line);
vector<string> get_cookie_tokens(const string &line);
static vector<string> get_tokens(const string &line);
static void contact_template();
static void general_search_template();
static void print_header();
static void print_footer();
string get_user_active_cart_id();
void buy_template();
void cart_template();
void contact_conn_template();
void create_new_cart(const string &username);
void general_search_conn_template();
void login_template(const string &data);
void no_login_template(const string &data);
static bool string_only_letters_and_numbers(string s);
static string remove_string_sum_signs(string s);
public:
Store();
void run();
};
#endif //TAREA1_SEGURIDAD_STORE_H
|
// pool.hpp
// declares functions and structs required pool.cpp
#ifndef POOL_H
#define POOL_H
// stdlib includes
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
// custom includes
#include "../../shared/slinked_list.hpp"
class pool
{
private:
// total size of pool in bytes
std::size_t total_size;
// size of a single chunk in bytes
std::size_t chunk_size;
// keep track of current and peak size because why not
std::size_t peak_size, curr_size;
// memory region start pointer
void* start_ptr = NULL;
// free list
slinked_list<std::size_t> free_list;
public:
// default constructor
// total size MUST be a multiple of chunk size
// proper usage is to call "pool((n * sizeof(data)), sizeof(data))"
pool(const std::size_t intotal_size, const std::size_t inchunk_size)
: total_size(intotal_size)
, chunk_size(inchunk_size)
, peak_size(0)
, curr_size(0)
{}
// destructor
~pool()
{
// just free the whole chunk we allocated
free(start_ptr);
}
// initialize
// call after calling constructor
void init()
{
// allocate full amount of memory required
start_ptr = malloc(total_size);
// figure out number of chunks
const std::size_t chunk_count = total_size / chunk_size;
// create linked list with all free positions
for (std::size_t i = 0; i < chunk_count; i++)
{
// determine address for start of chunk
std::size_t addr = (std::size_t)((std::size_t)start_ptr + (i * chunk_size));
// push onto free list
free_list.push_front(addr);
}
}
// allocate
void* alloc(const std::size_t size)
{
// if size is not correct, return NULL
// on the caller to check that they actually got good memory back
if (size != chunk_size)
{
return NULL;
}
// get next free position from free list
// then remove it from free list
std::size_t free_pos = free_list.front();
free_list.pop_front();
// update amount of memory used
curr_size += chunk_size;
peak_size = std::max(peak_size, curr_size);
// return the retrieved address as a void pointer
return (void*)free_pos;
}
// free
void free(void* pointer)
{
// drop the current used size
curr_size -= chunk_size;
// push pointer onto freelist
free_list.push_front((std::size_t)pointer);
}
// simple getters for internal data
// get total size
std::size_t get_total_size()
{
return total_size;
}
// get chunk size
std::size_t get_chunk_size()
{
return chunk_size;
}
// get peak size
std::size_t get_peak_size()
{
return peak_size;
}
// get current size
std::size_t get_curr_size()
{
return curr_size;
}
};
#endif
|
//
// AUCallbacks.hpp
// AudioEngineTests
//
// Created by birney on 2020/5/2.
// Copyright © 2020 rongcloud. All rights reserved.
//
#ifndef AUCallbacks_hpp
#define AUCallbacks_hpp
#import <AudioUnit/AudioUnit.h>
#include "CARingBuffer.h"
NS_ASSUME_NONNULL_BEGIN
struct AUCallbackRef {
AudioUnit m_audioUnit;
CARingBuffer* m_buffer;
Float64 m_firstInputSampleTime;
Float64 m_firstOutputSampleTime;
Float64 m_inToOutSampleTimeOffset;
AUCallbackRef(AudioUnit unit, CARingBuffer* buffer) {
m_audioUnit = unit;
m_buffer = buffer;
m_firstInputSampleTime = -1;
m_firstOutputSampleTime = -1;
m_inToOutSampleTimeOffset = -1;
}
~AUCallbackRef() {
}
};
OSStatus recordCallback1(void* _Nullable inRefCon,
AudioUnitRenderActionFlags* _Nonnull ioActionFlags,
const AudioTimeStamp* _Nonnull inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList* __nullable ioData);
OSStatus playoutCallback1(void* _Nullable inRefCon,
AudioUnitRenderActionFlags* _Nonnull ioActionFlags,
const AudioTimeStamp* _Nonnull inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList* __nullable ioData);
OSStatus playoutCallback2(void* _Nullable inRefCon,
AudioUnitRenderActionFlags* _Nonnull ioActionFlags,
const AudioTimeStamp* _Nonnull inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList* __nullable ioData);
NS_ASSUME_NONNULL_END
#endif /* AUCallbacks_hpp */
|
#include "arcpch.h"
#include "ModelRenderer.h"
#include <Arcane/Graphics/Shader.h>
#include <Arcane/Graphics/Camera/FPSCamera.h>
#include <Arcane/Graphics/Renderer/GLCache.h>
namespace Arcane
{
ModelRenderer::ModelRenderer(FPSCamera *camera) :
m_Camera(camera), NDC_Plane(), NDC_Cube()
{
// Configure and cache OpenGL state
m_GLCache = GLCache::GetInstance();
m_GLCache->SetDepthTest(true);
m_GLCache->SetBlend(false);
m_GLCache->SetFaceCull(true);
}
void ModelRenderer::SubmitOpaque(RenderableModel *renderable) {
m_OpaqueRenderQueue.push_back(renderable);
}
void ModelRenderer::SubmitTransparent(RenderableModel *renderable) {
m_TransparentRenderQueue.push_back(renderable);
}
void ModelRenderer::SetupOpaqueRenderState() {
m_GLCache->SetDepthTest(true);
m_GLCache->SetBlend(false);
m_GLCache->SetFaceCull(true);
m_GLCache->SetCullFace(GL_BACK);
}
void ModelRenderer::SetupTransparentRenderState() {
m_GLCache->SetDepthTest(true);
m_GLCache->SetBlend(true);
m_GLCache->SetFaceCull(false);
}
void ModelRenderer::FlushOpaque(Shader *shader, RenderPassType pass) {
m_GLCache->SetShader(shader);
// Render opaque objects
while (!m_OpaqueRenderQueue.empty()) {
RenderableModel *current = m_OpaqueRenderQueue.front();
SetupModelMatrix(current, shader, pass);
current->Draw(shader, pass);
m_OpaqueRenderQueue.pop_front();
}
}
void ModelRenderer::FlushTransparent(Shader *shader, RenderPassType pass) {
m_GLCache->SetShader(shader);
// Sort then render transparent objects (from back to front, does not account for rotations or scaling)
std::sort(m_TransparentRenderQueue.begin(), m_TransparentRenderQueue.end(),
[this](RenderableModel *a, RenderableModel *b) -> bool
{
return glm::length2(m_Camera->GetPosition() - a->GetPosition()) > glm::length2(m_Camera->GetPosition() - b->GetPosition());
});
while (!m_TransparentRenderQueue.empty()) {
RenderableModel *current = m_TransparentRenderQueue.front();
m_GLCache->SetBlend(true);
m_GLCache->SetBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
SetupModelMatrix(current, shader, pass);
current->Draw(shader, pass);
m_TransparentRenderQueue.pop_front();
}
}
// TODO: Currently only supports two levels for hierarchical transformations
// Make it work with any number of levels
void ModelRenderer::SetupModelMatrix(RenderableModel *renderable, Shader *shader, RenderPassType pass) {
glm::mat4 model(1);
glm::mat4 translate = glm::translate(glm::mat4(1.0f), renderable->GetPosition());
glm::mat4 rotate = glm::toMat4(renderable->GetOrientation());
glm::mat4 scale = glm::scale(glm::mat4(1.0f), renderable->GetScale());
if (renderable->GetParent()) {
// Only apply scale locally
model = glm::translate(glm::mat4(1.0f), renderable->GetParent()->GetPosition()) * glm::toMat4(renderable->GetParent()->GetOrientation()) * translate * rotate * scale;
}
else {
model = translate * rotate * scale;
}
shader->SetUniform("model", model);
if (pass == MaterialRequired) {
glm::mat3 normalMatrix = glm::mat3(glm::transpose(glm::inverse(model)));
shader->SetUniform("normalMatrix", normalMatrix);
}
}
}
|
/*
Arduino-MAX30100 oximetry / heart rate integrated sensor library
Copyright (C) 2016 OXullo Intersecans <x@brainrapers.org>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MAX30100_BEATDETECTOR_H
#define MAX30100_BEATDETECTOR_H
#include <stdint.h>
#define BEATDETECTOR_INIT_HOLDOFF 2000 // in ms, how long to wait before counting
#define BEATDETECTOR_MASKING_HOLDOFF 200 // in ms, non-retriggerable window after beat detection
#define BEATDETECTOR_BPFILTER_ALPHA 0.6 // EMA factor for the beat period value
#define BEATDETECTOR_MIN_THRESHOLD 20 // minimum threshold (filtered) value
#define BEATDETECTOR_MAX_THRESHOLD 800 // maximum threshold (filtered) value
#define BEATDETECTOR_STEP_RESILIENCY 30 // maximum negative jump that triggers the beat edge
#define BEATDETECTOR_THRESHOLD_FALLOFF_TARGET 0.3 // thr chasing factor of the max value when beat
#define BEATDETECTOR_THRESHOLD_DECAY_FACTOR 0.99 // thr chasing factor when no beat
#define BEATDETECTOR_INVALID_READOUT_DELAY 2000 // in ms, no-beat time to cause a reset
#define BEATDETECTOR_SAMPLES_PERIOD 10 // in ms, 1/Fs
typedef enum BeatDetectorState {
BEATDETECTOR_STATE_INIT,
BEATDETECTOR_STATE_WAITING,
BEATDETECTOR_STATE_FOLLOWING_SLOPE,
BEATDETECTOR_STATE_MAYBE_DETECTED,
BEATDETECTOR_STATE_MASKING
} BeatDetectorState;
class BeatDetector
{
public:
BeatDetector();
bool addSample(float sample);
float getRate();
float getCurrentThreshold();
private:
bool checkForBeat(float value);
void decreaseThreshold();
BeatDetectorState state;
float threshold;
float beatPeriod;
float lastMaxValue;
uint32_t tsLastBeat;
};
#endif
|
/****************************************************************************
** Meta object code from reading C++ file 'tablewidget.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.13.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <memory>
#include "../../LabOfWork/tablewidget.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'tablewidget.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.13.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_TableWidget_t {
QByteArrayData data[10];
char stringdata0[184];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_TableWidget_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_TableWidget_t qt_meta_stringdata_TableWidget = {
{
QT_MOC_LITERAL(0, 0, 11), // "TableWidget"
QT_MOC_LITERAL(1, 12, 24), // "WindowTable_InMainWindow"
QT_MOC_LITERAL(2, 37, 0), // ""
QT_MOC_LITERAL(3, 38, 27), // "WindowTable_InPictureWindow"
QT_MOC_LITERAL(4, 66, 20), // "ClickedPictureWindow"
QT_MOC_LITERAL(5, 87, 17), // "ClickedMainWindow"
QT_MOC_LITERAL(6, 105, 15), // "OpenTableWindow"
QT_MOC_LITERAL(7, 121, 18), // "ClickedTableButton"
QT_MOC_LITERAL(8, 140, 19), // "ClickedDeleteButton"
QT_MOC_LITERAL(9, 160, 23) // "ClickedCalculatorButton"
},
"TableWidget\0WindowTable_InMainWindow\0"
"\0WindowTable_InPictureWindow\0"
"ClickedPictureWindow\0ClickedMainWindow\0"
"OpenTableWindow\0ClickedTableButton\0"
"ClickedDeleteButton\0ClickedCalculatorButton"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_TableWidget[] = {
// content:
8, // revision
0, // classname
0, 0, // classinfo
8, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
2, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 54, 2, 0x06 /* Public */,
3, 0, 55, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
4, 0, 56, 2, 0x0a /* Public */,
5, 0, 57, 2, 0x0a /* Public */,
6, 0, 58, 2, 0x0a /* Public */,
7, 0, 59, 2, 0x0a /* Public */,
8, 0, 60, 2, 0x0a /* Public */,
9, 0, 61, 2, 0x0a /* Public */,
// signals: parameters
QMetaType::Void,
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void TableWidget::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
auto *_t = static_cast<TableWidget *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->WindowTable_InMainWindow(); break;
case 1: _t->WindowTable_InPictureWindow(); break;
case 2: _t->ClickedPictureWindow(); break;
case 3: _t->ClickedMainWindow(); break;
case 4: _t->OpenTableWindow(); break;
case 5: _t->ClickedTableButton(); break;
case 6: _t->ClickedDeleteButton(); break;
case 7: _t->ClickedCalculatorButton(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
using _t = void (TableWidget::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&TableWidget::WindowTable_InMainWindow)) {
*result = 0;
return;
}
}
{
using _t = void (TableWidget::*)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&TableWidget::WindowTable_InPictureWindow)) {
*result = 1;
return;
}
}
}
Q_UNUSED(_a);
}
QT_INIT_METAOBJECT const QMetaObject TableWidget::staticMetaObject = { {
&QWidget::staticMetaObject,
qt_meta_stringdata_TableWidget.data,
qt_meta_data_TableWidget,
qt_static_metacall,
nullptr,
nullptr
} };
const QMetaObject *TableWidget::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *TableWidget::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_TableWidget.stringdata0))
return static_cast<void*>(this);
return QWidget::qt_metacast(_clname);
}
int TableWidget::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 8)
qt_static_metacall(this, _c, _id, _a);
_id -= 8;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 8)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 8;
}
return _id;
}
// SIGNAL 0
void TableWidget::WindowTable_InMainWindow()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
// SIGNAL 1
void TableWidget::WindowTable_InPictureWindow()
{
QMetaObject::activate(this, &staticMetaObject, 1, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
#ifndef _bullet_h_
#define _bullet_h_
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <Glut/glut.h>
#include <OpenGL/glext.h>
#include "vector.h"
#include <math.h>
class bullet {
public:
vector position, velocity;
float size;
bullet(vector pos, vector vel, float s);
void update(float, vector);
void drawBullet(GLuint texture);
};
#endif
|
//10449 - Traffic
//Dept. ICE, NSTU-11 Batch
#include<bits/stdc++.h>
using namespace std;
#define INF 99999999
//#define INF 1<<28
#define ll long long
#define SZ 100009
#define MX 100000000
#define sfint(a) scanf("%d",&a)
#define sfint2(a,b) scanf("%d%d",&a,&b)
#define sfint3(a,b,c) scanf("%d%d%d",&a,&b,&c)
#define forlp0(i,n) for(int i=0;i<n;i++)
#define forlp1(i,n) for(int i=1;i<=n;i++)
#define forlpa(i,a,n) for(int i=a;i<=n;i++)
#define rvforlp(i,n) for(int i=n-1;i>=0;i--)
typedef pair<int,int> PII;
#define SIZE 500005
struct edge{
int u,v,w;
};
vector<edge>E;
int dist[500];
int busy[500];
void bellmanford(int source,int n){
forlp0(i,n+1)
dist[i]=INF;
dist[source]=0;
int size=E.size();
forlp0(i,n-1){
forlp0(j,size){
if(dist[E[j].v] > dist[E[j].u]+E[j].w && dist[E[j].u]!=INF){
dist[E[j].v] = dist[E[j].u]+E[j].w;
}
}
}
forlp0(j,size){
if(dist[E[j].v] > dist[E[j].u]+E[j].w && dist[E[j].u]!=INF){
dist[E[j].v] = -INF;
}
}
}
int main()
{
int testCase=1;
int n;
while(scanf("%d", &n) == 1){
memset(dist,0,sizeof dist);
memset(busy,0,sizeof busy);
vector<edge>e; swap(e,E);
int m,q,dest;
forlp1(j,n){
sfint(busy[j]);
}
sfint(m);
forlp1(j,m){
int source,dest;
sfint2(source,dest);
edge test;
test.u=source;
test.v=dest;
test.w=((busy[dest]-busy[source])*(busy[dest]-busy[source])*(busy[dest]-busy[source]));
E.push_back(test);
}
sfint(q);
printf("Set #%d\n",testCase++);
bellmanford(1,n);
forlp1(j,q){
sfint(dest);
if(dest <= 0 || dest > n || dist[dest]<3 || dist[dest]==INF)
printf("?\n");
else
printf("%d\n",dist[dest]);
}
}
return 0;
}
|
#pragma once
#include <SFML/Graphics.hpp>
#include <vector>
#include "Block.hh"
class PointsDrawer: public Block
{
sf::RenderWindow* window;
public:
Input<std::vector<sf::Vector2f> >* in_points;
Input<sf::Vector2u>* in_size;
protected:
virtual void Compute() override;
public:
PointsDrawer(std::string _name);
};
|
#include <iostream>
using namespace std;
#include "solution.h"
int main() {
vector<char> cvec1 = {'h', 'e', 'l', 'l', 'o'};
vector<char> cvec2 = {'H', 'a', 'n', 'n', 'a', 'h'};
Solution sol;
sol.reverseString(cvec1);
sol.reverseString(cvec2);
for (auto c : cvec1) {
cout << c << " ";
}
cout << endl;
for (auto c : cvec2) {
cout << c << " ";
}
cout << endl;
return 0;
}
|
/* Sweep
by BARRAGAN <http://barraganstudio.com>
This example code is in the public domain.
modified 8 Nov 2013
by Scott Fitzgerald
http://arduino.cc/en/Tutorial/Sweep
*/
#include <Servo.h>
Servo myservoL; // create servo object to control a servo
// twelve servo objects can be created on most boards
Servo myservoR;
int pos = 0; // variable to store the servo position
//________SERIAL
char inData[80];
byte index = 0;
String message;
int posServoL;
int posServoR;
void setup()
{
posServoL = 110;
posServoR = 105;
myservoR.attach(9); //Bleu
myservoL.attach(10); //Vert
myservoL.write(posServoL);
myservoR.write(posServoR);
Serial.begin(9600);
}
void loop()
{
message = "";
while(Serial.available() > 0){
char aChar = Serial.read();
//______________________PARSING DATA_________________________
if(aChar == '\n'){
for(int i = 0;i<index;i++){
message += inData[i];
}
Serial.flush();
//Serial.println(message);//debug
int separatorIndex = message.indexOf('_');
int secondSeparatorIndex = message.indexOf('_', separatorIndex+1);
//Data not correct
if(separatorIndex == -1){
//Serial.println("Wrong data format");
//Correct data format
}if(separatorIndex != -1 && secondSeparatorIndex ==-1){
//Serial.println("1 motor instruction");
//Correct data format
String firstValue = message.substring(0, separatorIndex);
String secondValue = message.substring(separatorIndex+1);
int motorValue = firstValue.toInt();
int rotationValue = secondValue.toInt();
if(rotationValue >= 0 && rotationValue <= 180){
if(motorValue == 0){
posServoL = rotationValue;
//myservoL.write(rotationValue);
}else if(motorValue == 1){
posServoR = rotationValue;
//myservoR.write(rotationValue);
}
}
}if(separatorIndex != -1 && secondSeparatorIndex !=-1){
//Serial.println("2 motor instruction");
//Correct data format
String firstValue = message.substring(0, separatorIndex);
String secondValue = message.substring(separatorIndex+1);
String thirdValue = message.substring(secondSeparatorIndex+1);
int motorValue = firstValue.toInt();
int rotationValueL = secondValue.toInt();
int rotationValueR = thirdValue.toInt();
if(rotationValueL >= 0 && rotationValueL <= 180 && rotationValueR >= 0 && rotationValueR <= 180){
if(motorValue == 2){
posServoL = rotationValueL;
posServoR = rotationValueR;
//myservoL.write(rotationValueL);
//myservoR.write(rotationValueR);
}
}
}else{
}
index = 0;
inData[index] = NULL;
//______________________READING DATA_________________________
}else{
//Serial.println("..");
inData[index] = aChar;
index++;
inData[index] = '\0'; // Keep the string NULL terminated
}
//____________________________________________________________
}
myservoL.write(posServoL);
myservoR.write(posServoR);
delay(100);
}
|
#ifndef __DBMANAGER_H__
#define __DBMANAGER__
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
// For posix::time
#include <boost/date_time/gregorian/gregorian.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
// For cdb
#include <cdb.h>
#include <fcntl.h>
using namespace std;
namespace screenDNS {
// Implement 1_Writer, N_Readers using shared_mutex.
// See later if we need to implement Singleton
class DBManager {
public:
// Constructor
DBManager();
//
void writeDB(std::string log_content);
// Pass structure using a structure reference
bool readDB(struct cdb &cdb);
private:
// Share mutex to synchronize access Read/Write to DB
mutable boost::shared_mutex rw_mutex;
// DB here is conceptually modelled as a string, which is supposed to be the content of LOG
struct cdb c; // Pointer to content of DB in memory
bool initialized; // To signal if c is already populated or not
};
}
#endif /* __DBMANAGER_H__ */
|
#include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
typedef vector<vi> vvi;
typedef vector<ii> vii;
typedef vector<bool> vb;
typedef vector<vb> vvb;
typedef set<int> si;
typedef map<string, int> msi;
typedef greater<int> gt;
typedef priority_queue<int, vector<int>, gt> minq;
typedef long long ll;
const ll INF = 1e18L + 1;
//clang++ -std=c++11 -stdlib=libc++
ll gcd(ll a, ll b) { return b?gcd(b,a%b):a;}
ll lcm(ll a, ll b) { return a/gcd(a,b)*b;}
int main() {
int a,b; cin>>a>>b;
cout << lcm(a,b) << endl;
return 0;
}
|
// github.com/andy489
// https://www.hackerrank.com/contests/practice-3-sda/challenges/strawberries-sda
#include <cstdio>
using namespace std;
const int mxN = 100005;
long long n, q, x, l, r, m, A[mxN];
int main() {
scanf("%lld", &n);
int i(0);
for (; i < n; ++i) {
scanf("%lld", &A[i]);
A[i] += (i > 0 ? A[i - 1] : 0);
}
scanf("%lld", &q);
while (q--) {
scanf("%lld", &x);
l = 0;
r = n - 1;
while (l != r) {
m = (l + r) / 2;
if (A[m] < x)
l = m + 1;
else
r = m;
}
printf("%lld\n", l + 1);
}
return 0;
}
|
#include <sstream>
#include <string>
#include "Mesh.h"
Mesh::Mesh(){
//vector<Vector3> vertice;
//vector<Vector2> uvs;
//vector<Vector3> normals;
//vector<string> groups;
maxOrder = 0 ;
}
Face::Face(string source){
string temp("") ;
cout << "[Face] " << source << " " << endl ;
for(int j = 0 ; j<source.length() ; j++){
stringstream ss ;
string character = source.substr(j,1);
if(character.compare(0,1," ")!=0){
ss << temp << character ;
temp = ss.str();
}else{
rawFaces.push_back(temp);
cout << "[vertex] " << temp << endl ;
ss.clear();
temp = "" ;
}
};
//the last token
rawFaces.push_back(temp);
cout << "[vertex] " << temp << endl ;
temp = "" ;
}
void Mesh::append(string element){
if(element.compare(0, 2, "g ") == 0){
string elementValue = element.substr(2, element.length()-2);
groups.push_back(elementValue) ;
//cout << "[group] " << elementValue << endl;
} else if(element.compare(0, 2, "v ") == 0){
string elementValue = element.substr(2, element.length()-2);
stringstream ss ;
ss << elementValue << endl;
float x,y,z;
ss >> x >> y >> z ;
vertices.push_back(Vector3(x,y,z));
//cout << "[vertex] " << x << " " << y << " " << z << endl;
} else if(element.compare(0, 3, "vt ") == 0){
string elementValue = element.substr(3, element.length()-3);
stringstream ss ;
ss << elementValue << endl;
float u,v;
ss >> u >> v ;
uvs.push_back(Vector2(u,v));
//cout << "[uv] " << elementValue << endl;
}else if(element.compare(0, 3, "vn ") == 0){
string elementValue = element.substr(3, element.length()-3);
stringstream ss ;
ss << elementValue << endl;
float x,y,z;
ss >> x >> y >> z ;
normals.push_back(Vector3(x,y,z));
//cout << "[normal] " << elementValue << endl;
}else if(element.compare(0, 2, "f ") == 0){
string elementValue = element.substr(2, element.length()-2);
Face f(elementValue) ;
if(f.rawFaces.size()>maxOrder){
cout << "[face] " << f.rawFaces.size() << " " << endl;
maxOrder = f.rawFaces.size() ;
}
faces.push_back(f);
//cout << "[face] " << i++ << endl;
}else if(element.compare(0, 2, "s ") == 0){
string elementValue = element.substr(2, element.length()-2);
//cout << "[?] " << elementValue << endl;
}else if(element.compare(0, 7, "usemtl ") == 0){
string elementValue = element.substr(7, element.length()-7);
//cout << "[material] " << elementValue << endl;
}else if(element.compare(0, 7, "mtllib ") == 0){
string elementValue = element.substr(7, element.length()-7);
//cout << "[mtlib] " << elementValue << endl;
}else if(element.compare(0, 2, "# ") == 0){
string elementValue = element.substr(2, element.length()-2);
cout << "[comment] " << elementValue << endl;
}else if(element.length() == 0){
//cout << "[empty] " << endl;
}
else{
cout << "[unknown] '" << element << "'" << endl;
}
}
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#define ll long long
using namespace __gnu_pbds;
using namespace std;
typedef tree<int, null_type, less<int>, rb_tree_tag,
tree_order_statistics_node_update>
indexed_set;
typedef tuple<ll, ll, ll> tp;
typedef pair<ll, ll> pr;
const ll MOD = 1000000007;
const ll INF = 1e18;
template <typename T> void print(const T &t) {
std::copy(t.cbegin(), t.cend(),
std::ostream_iterator<typename T::value_type>(std::cout, " "));
cout << endl;
}
template <typename T> void print2d(const T &t) {
std::for_each(t.cbegin(), t.cend(), print<typename T::value_type>);
}
void setIO(string s) { // the argument is the filename without the extension
freopen((s + ".in").c_str(), "r", stdin);
freopen((s + ".out").c_str(), "w", stdout);
}
struct Cow{
ll x;
ll y;
ll id;
};
vector<Cow> E;
vector<Cow> N;
bool cmpE(Cow &a, Cow &b){
if(a.x == b.x){
return a.y < b.y;
}
return a.x < b.x;
}
bool cmpN(Cow &a, Cow &b){
if(a.y == b.y){
return a.x < b.x;
}
return a.y < b.y;
}
int main() {
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
ll n; cin >> n;
for(ll i = 0; i < n; i++){
string dir;
ll x, y;
cin >> dir >> x >> y;
if(dir == "E"){
E.push_back({x, y, i + 1});
} else{
N.push_back({x, y, i + 1});
}
}
sort(E.begin(), E.end(), cmpN);
sort(N.begin(), N.end(), cmpE);
vector<bool> stop(2501);
vector<ll> blame(2501);
for(ll i = 0; i < E.size(); i++){
for(ll j = 0; j < N.size(); j++){
if(!stop[E[i].id] && !stop[N[j].id] && E[i].x <= N[j].x && E[i].y >= N[j].y){
ll diffx = N[j].x - E[i].x;
ll diffy = E[i].y - N[j].y;
if(diffx < diffy){
stop[N[j].id] = true;
blame[E[i].id] += 1 + blame[N[j].id];
} else if(diffy < diffx){
stop[E[i].id] = true;
blame[N[j].id] += 1 + blame[E[i].id];
}
}
}
}
for(ll i = 1; i <= n; i++){
cout << blame[i] << endl;
}
}
|
#pragma once
#include <vector>
#include "Linear.h"
#include "Simplex.h"
#include "Function.h"
class ZoitendijkMethod {
using xn_t = std::vector<double>;
public:
ZoitendijkMethod(Function const& function, size_t dim, double lamda = 0.5);
void set_limitaions(Limitations const& limitations, std::vector<Function> const& grads);
void set_function(Function const& objective_function);
void calculate();
~ZoitendijkMethod();
private:
void init_first_approximation();
double limitation_value(size_t index, xn_t const& x) const;
xn_t solve_subtask(xn_t const& x, std::vector<size_t> const& almost_active);
bool is_in_area(xn_t const& x) const;
double find_next_alpha(xn_t const& xk, double eta_k, xn_t const& s_k);
static double dot_product(xn_t const& x, xn_t const& y);
static void scale(xn_t& vec, double mult);
static xn_t add(xn_t const& x, xn_t const& y);
std::vector<size_t> build_almost_active(xn_t const& x);
double delta_null_active(xn_t const& x);
size_t dim;
xn_t x0;
Function objective_function;
Limitations limitations;
std::vector<Function> gradients;
double lamda;
double delta;
};
|
#include <iostream>
#include <string>
#include "evaluator.h"
int main()
{
std::cout << "Calculate something!\n";
std::string str;
while(getline(std::cin, str))
{
Evaluator<double> e(str);
std::cout << e.GetValue() << std::endl;
}
return 0;
}
|
#include "ModifierSlot.h"
ModifierSlot::ModifierSlot(void)
{
Frequency = 60;
secondsSinceLastUpdate = 0;
}
ModifierSlot::ModifierSlot(Modifier* m, float freq)
{
MainModifier = m;
Frequency = freq;
secondsSinceLastUpdate = 0;
}
ModifierSlot::~ModifierSlot(void)
{
}
void ModifierSlot::Update(ParticleCollection* collection, float delta)
{
secondsSinceLastUpdate += delta;
if (secondsSinceLastUpdate >= (1.0f / Frequency))
{
MainModifier->Update(collection, secondsSinceLastUpdate);
secondsSinceLastUpdate = 0.0f;
}
}
|
// Manager Milestone - ItemManager Interface
// ItemManager.cpp
// Chris Szalwinski
// v1.0 - 16/11/2015
#include <iostream>
#include <vector>
#include "ItemManager.h"
void ItemManager::push_back(Item&& item){
items.push_back(std::move(item));
}
std::vector<Item>::iterator ItemManager::begin(){
return items.begin();
}
std::vector<Item>::iterator ItemManager::end(){
return items.end();
}
const std::vector<Item>::const_iterator ItemManager::cbegin() const{
return items.begin();
}
const std::vector<Item>::const_iterator ItemManager::cend() const{
return items.end();
}
void ItemManager::display(std::ostream& os, bool desc) const{
for (const Item& item : items)
item.display(os, desc);
}
|
#pragma once
/* Faster Interface Windows
*/
#include "../Main.h"
#include "../Singleton.h"
#include "GenericPatcher.h"
class CPatcher_FasterInterfaceWindows : public IGenericPatcher {
public:
CPatcher_FasterInterfaceWindows();
bool ReadINI(void);
bool WriteINI(void);
private:
// Hook functions
// Variables for hook functions
};
typedef Singleton<CPatcher_FasterInterfaceWindows> SngPatcher_FasterInterfaceWindows;
|
#include "stringdecomposition.h"
StringDecomposition::StringDecomposition(char in[])
{
this->length=strlen(in);
// this->in=new char[length];
this->out=new int[length];
this->in=in;
// for(int i=0;i<length;i++){
// this->in[i]=in[i];
// }
this->length_out=0;
}
StringDecomposition::~StringDecomposition(){
delete []in;
in=NULL;
delete []out;
out=NULL;
}
void StringDecomposition::calculate(){
int n=0;
for(int i=0;i<length;i++){
if(in[i]>='0'&&in[i]<='9'){
n++;
if(i==length-1){
if(n>1){
int sum=0;
for(int j=i-n+1;j<=i;j++){
sum=sum*10+int(in[j]-48);
}
out[length_out]=sum;
length_out++;
n=0;
}
}
}
else {
if(n>1){
int sum=0;
for(int j=i-n;j<i;j++){
sum=sum*10+int(in[j]-48);
}
out[length_out]=sum;
length_out++;
n=0;
}
n=0;
}
}
}
int *StringDecomposition::get(){
return this->out;
}
int StringDecomposition::getlength(){
return this->length_out;
}
|
//インクルードファイル指定
#include <opencv2/opencv.hpp>
//静的リンクライブラリの指定
//#include <opencv2/opencv_lib.hpp>
//名前空間の指定
#include<stdio.h>
#include<cv.h>
#include<highgui.h>
#include<string>
#include<fstream>
#include<iostream>
#define HEAD_CUT 1.7
//#include<opencv2/core/core.hpp>
int toBinary(char *file_name);
void resize(char *img_name,int size);
void cut(char *img_name);
void toStringFile();
void mergeData(char *output_name);
std::string Replace(std::string str,std::string from_str,std::string to_str);
int main(int argc,char *argv[]){
if(argc!=3){
printf("Please input start number and end number !\n");
exit(1);
}
int start = atoi(argv[1]);
int end = atoi(argv[2]);
printf("%d %d\n",start,end);
for(int i=start;i<=end;i++){
char file_name[256];
sprintf(file_name,"BINGO_%d.jpg",i);
toBinary(file_name);
resize("Binary.jpg",6);
cut("Binary.jpg");
toStringFile();
mergeData("merge_data");
}
}
int toBinary(char *file_name)
{
IplImage *src_img = 0, *dst_img;
IplImage *src_img_gray = 0;
IplImage *tmp_img1, *tmp_img2, *tmp_img3;
// (1)画像を読み込む
//if (argc >= 2)
src_img = cvLoadImage (file_name, CV_LOAD_IMAGE_COLOR);
if (src_img == 0)
return -1;
tmp_img1 = cvCreateImage (cvGetSize (src_img), IPL_DEPTH_8U, 1);
tmp_img2 = cvCreateImage (cvGetSize (src_img), IPL_DEPTH_8U, 1);
tmp_img3 = cvCreateImage (cvGetSize (src_img), IPL_DEPTH_8U, 1);
src_img_gray = cvCreateImage (cvGetSize (src_img), IPL_DEPTH_8U, 1);
cvCvtColor (src_img, src_img_gray, CV_BGR2GRAY);
dst_img = cvCloneImage (src_img);
// (2)ガウシアンフィルタで平滑化を行う
cvSmooth (src_img_gray, src_img_gray, CV_GAUSSIAN, 5);
// (3)二値化:cvThreshold
cvThreshold (src_img_gray, tmp_img1, 60, 255, CV_THRESH_BINARY);
// (4)二値化:cvAdaptiveThreshold
//cvAdaptiveThreshold (src_img_gray, tmp_img2, 255, CV_ADAPTIVE_THRESH_MEAN_C, CV_THRESH_BINARY, 11, 10);
// (5)二つの二値化画像の論理積
//cvAnd (tmp_img1, tmp_img2, tmp_img3);
//cvCvtColor (tmp_img3, dst_img, CV_GRAY2BGR);
// (6)元画像と二値画像の論理積
//cvSmooth (src_img, src_img, CV_GAUSSIAN, 11);
//cvAnd (dst_img, src_img, dst_img);
cvSaveImage("Binary.jpg",tmp_img1);
// (7)画像を表示する
//cvNamedWindow ("Threshold", CV_WINDOW_AUTOSIZE);
//cvShowImage ("Threshold", tmp_img1);
//cvNamedWindow ("AdaptiveThreshold", CV_WINDOW_AUTOSIZE);
//cvShowImage ("AdaptiveThreshold", tmp_img2);
//cvNamedWindow ("Image", CV_WINDOW_AUTOSIZE);
//cvShowImage ("Image", dst_img);
//cvWaitKey (0);
//cvDestroyWindow ("Threshold");
//cvDestroyWindow ("AdaptiveThreshold");
//cvDestroyWindow ("Image");
//終了処理
cvReleaseImage (&src_img);
cvReleaseImage (&dst_img);
cvReleaseImage (&src_img_gray);
cvReleaseImage (&tmp_img1);
cvReleaseImage (&tmp_img2);
cvReleaseImage (&tmp_img3);
return 0;
}
//#include<opencv2/core/core.hpp>
//画像サイズの変更
void resize(char *img_name,int size){
IplImage *src_img,*resize_img;
src_img = cvLoadImage (img_name, CV_LOAD_IMAGE_ANYDEPTH | CV_LOAD_IMAGE_ANYCOLOR);
if(src_img==0){
printf("Not found %s !\n",img_name);
exit(0);
}
resize_img = cvCreateImage (cvSize (src_img->width * size, src_img->height * size), src_img->depth, src_img->nChannels);
cvResize(src_img,resize_img,CV_INTER_NN);
cvSaveImage(img_name,resize_img);
}
//画像カット
void cut(char *img_name){
IplImage* src_img = 0;
IplImage* cut_img=0;
int w,h,h_nohead;
src_img = cvLoadImage(img_name);
if(!src_img){
printf("Not reading %s !\n",img_name);
exit(0);
}
w=src_img->width;
h=src_img->height;
h_nohead = h - h/8*HEAD_CUT; //頭の部分を抜いた画像の高さ
char save_name[10];
//頭の部分だけを抜き出し
cut_img = cvCloneImage(src_img);
cvSetImageROI(cut_img,cvRect(cut_img->width/2-cut_img->width/16,0,w/HEAD_CUT,h/20*HEAD_CUT));
sprintf(save_name,"cut%d.jpg",1);
cvSaveImage(save_name,cut_img);
//ビンゴの本体部分の抜き出し
for(int i=0;i<5;i++){
cut_img = cvCloneImage(src_img);
cvSetImageROI(cut_img,cvRect(0,h/8*HEAD_CUT+h_nohead/5*i,w,h_nohead/5));
sprintf(save_name,"cut%d.jpg",i+2);
cvSaveImage(save_name,cut_img);
}
}
//切り取った画像をテキストデータへ
void toStringFile(){
char command[255];
for(int i=0;i<7;i++){
sprintf(command,"tesseract cut%d.jpg data%d -psm 7 tesseract.conf",i,i);
system(command);
}
}
//テキストデータを統一
void mergeData(char *output_name){
std::ifstream ifs;
std::ofstream ofs(output_name,std::ios::app);
std::string temp;
std::string out_str,ID;
char file_name[128];
ifs.open("data1.txt");
if(!ifs){
printf("File Open Error !\n");
}
//カードID
ifs >> out_str;
ID=out_str;
out_str+="\t";
ifs.close();
//ビンゴのデータ本体
for(int i=0;i<5;i++){
sprintf(file_name,"data%d.txt",i+2);
ifs.open(file_name);
getline(ifs,temp);
temp += " ";
out_str += temp;
ifs.close();
}
std::string str=Replace(out_str," ",",");
//str+=","+ID;
// ofs << out_str<<"\n";
ofs << str<<"\n";
ofs.close();
}
//文字列置き換え
std::string Replace(std::string str,std::string from_str,std::string to_str){
std::string::size_type Pos(str.find(from_str));
while(Pos != std::string::npos){
str.replace(Pos,from_str.length(),to_str);
Pos = str.find(from_str, Pos + to_str.length());
}
if(str.length()-1==str.find_last_of(to_str)){
str=str.erase(str.find_last_of(to_str));
}
return str;
}
|
/*
* transform_modes.h
*
* Created on: Dec 5, 2017
* Author: glenn
*/
#ifndef SRC_MODEL_TRANSFORM_MODES_H_
#define SRC_MODEL_TRANSFORM_MODES_H_
#include "transform.h"
#include "Types_6D_Modes.h"
#include "DeviceProtein.h"
#include "Protein.h"
namespace as{
/**
* @brief: to change from the receptor system to the ligand system
* the translational and rotational DOF have to be "inverted".
* This function returns an inverted DOF such that it points to the receptor in the ligandsystem
*
*/
template<typename REAL>
const DOF_6D_Modes<REAL> invertDOF( DOF_6D_Modes<REAL> ligandDOF)
{
DOF_6D_Modes<REAL> invertedDOF;
Vec3<REAL> ang(0.0);
invertedDOF._6D.ang=ligandDOF._6D.ang;
invertedDOF._6D.pos=ligandDOF._6D.pos.inv() ;
const RotMat<REAL> rotMat=euler2rotmat(ligandDOF._6D.ang.x, ligandDOF._6D.ang.y, ligandDOF._6D.ang.z).getInv();
invertedDOF._6D.pos=rotMat*invertedDOF._6D.pos ;
std::copy( ligandDOF.modesRec, ligandDOF.modesRec+MODES_MAX_NUMBER,
invertedDOF.modesRec);
std::copy(ligandDOF.modesLig, ligandDOF.modesLig+MODES_MAX_NUMBER,
invertedDOF.modesLig);
return invertedDOF;
}
/**
* @brief: In addition to the normal transform function rotate_translate_deform
* also applies mode deformation to the coodinates.
* Note that the deformed coordinates are also returned.
* The deformed but not translated coordinates are important to evaluate the
* NLForces between the receptor and the ligand
*
*/
template<typename REAL, typename DOF_T>
__inline__ void h_deform( DOF_T const& dof, Protein<REAL> const* protein, unsigned idx_protein, unsigned idx_atom, Vec3<REAL> & posAtom,REAL* buffer_defoX,
REAL* buffer_defoY,
REAL* buffer_defoZ,
typename std::enable_if<std::is_same< DOF_T, DOF_6D_Modes<REAL> >::value, void>::type* dummy = 0)
{
unsigned numModes = protein->numModes();
REAL const * dlig;
if ( idx_protein == 0){
dlig = dof.modesRec;
}
else{
dlig = dof.modesLig;
}
for(int mode=0;mode<numModes;mode++){
posAtom.x += dlig[mode] * protein->xModes()[idx_atom*numModes+mode];
posAtom.y += dlig[mode] * protein->yModes()[idx_atom*numModes+mode];
posAtom.z += dlig[mode] * protein->zModes()[idx_atom*numModes+mode];
}
buffer_defoX[idx_atom] = posAtom.x;
buffer_defoY[idx_atom] = posAtom.y;
buffer_defoZ[idx_atom] = posAtom.z;
}
template<typename REAL, typename DOF_T>
__inline__ void h_deform( DOF_T const &dof, Protein<REAL> const* protein, unsigned idx_protein, unsigned idx_atom, Vec3<REAL> & posAtom,REAL* buffer_defoX,
REAL* buffer_defoY,
REAL* buffer_defoZ,
typename std::enable_if<std::is_same< DOF_T, DOF_6D<REAL> >::value, void>::type* dummy = 0)
{}
template<typename REAL, typename DOF_T>
__inline__ void h_rotate_translate( DOF_T const&dof, Vec3<REAL> & posAtom, unsigned const type_protein,
typename std::enable_if<std::is_same< DOF_T, DOF_6D_Modes<REAL> >::value, void>::type* dummy = 0)
{
RotMat<REAL> rotMat = euler2rotmat(dof._6D.ang.x, dof._6D.ang.y, dof._6D.ang.z);
Vec3<REAL> translation = dof._6D.pos;
if ( type_protein == 0)
{
rotMat = rotMat.getInv();
translation = rotMat * translation.inv();
}
posAtom = rotMat*posAtom;
posAtom += translation;
}
template<typename REAL, typename DOF_T>
__inline__ void h_rotate_translate( DOF_T &dof, Vec3<REAL> & posAtom, unsigned const type_protein,
typename std::enable_if<std::is_same< DOF_T, DOF_6D<REAL> >::value, void>::type* dummy = 0)
{
RotMat<REAL> rotMat = euler2rotmat(dof.ang.x, dof.ang.y, dof.ang.z);
if( type_protein == 0){
rotMat = rotMat.getInv();
}
posAtom = rotMat*posAtom;
posAtom += dof.pos;
}
template< typename REAL, typename DOF_T>
void h_DOFPos(
Protein<REAL> const* protein,
DOF_T const& dof,
unsigned const type_protein,
REAL* buffer_defoX,
REAL* buffer_defoY,
REAL* buffer_defoZ,
REAL* buffer_trafoX,
REAL* buffer_trafoY,
REAL* buffer_trafoZ
){
REAL const* x = protein->xPos();
REAL const* y = protein->yPos();
REAL const* z = protein->zPos();
for ( unsigned idx_atom = 0; idx_atom < protein->numAtoms(); ++idx_atom ){
Vec3<REAL> posAtom(x[idx_atom], y[idx_atom], z[idx_atom]);
h_deform( dof, protein, type_protein, idx_atom, posAtom, buffer_defoX,
buffer_defoY,
buffer_defoZ);
h_rotate_translate( dof, posAtom, type_protein);
buffer_trafoX[idx_atom] = posAtom.x;
buffer_trafoY[idx_atom] = posAtom.y;
buffer_trafoZ[idx_atom] = posAtom.z;
}
}
/*
*
* only applies mode deformation to an array of coordinates. Not used anymore.
*/
/*
* This function rotates an incomming array of type REAl.
* USECASE: since the forces action on the receptor are evaluated in the ligandframe,
* they have to be rotated back into the global/receptor system which is what this function does
*/
template<typename REAL>
void rotate_forces(
Vec3<REAL> const& ang,
unsigned const& numAtoms,
REAL* forceX,
REAL* forceY,
REAL* forceZ
)
{
const RotMat<REAL> rotMat = euler2rotmat(ang.x, ang.y, ang.z);
Vec3<REAL> center(0.0f) ;
for (unsigned i = 0; i < numAtoms; ++i) {
Vec3<REAL> forceAtom(forceX[i], forceY[i], forceZ[i]);
forceAtom = rotMat*forceAtom;
forceX[i] = forceAtom.x;
forceY[i] = forceAtom.y;
forceZ[i] = forceAtom.z;
}
}
#ifdef CUDA
template <typename REAL, typename DOF_T>
__device__ __forceinline__ void deform(
DOF_T const& dof, Vec3<REAL> & posAtom, d_Protein<REAL> const& protein, unsigned const idxAtom, unsigned const idx_protein, unsigned const bufIdx,
REAL& buffer_defoX, REAL& buffer_defoY, REAL& buffer_defoZ,
typename std::enable_if<std::is_same< DOF_T, DOF_6D_Modes<REAL> >::value, void>::type* dummy = 0 )
{
REAL const * dlig;
if ( idx_protein == 0){
dlig = dof.modesRec;
}
else{
dlig = dof.modesLig;
}
unsigned const numModes = protein.numModes;
for(int mode=0; mode < numModes; mode++){
posAtom.x += dlig[mode] * protein.xModes[idxAtom*numModes+mode];
posAtom.y += dlig[mode] * protein.yModes[idxAtom*numModes+mode];
posAtom.z += dlig[mode] * protein.zModes[idxAtom*numModes+mode];
}
buffer_defoX = posAtom.x;
buffer_defoY = posAtom.y;
buffer_defoZ = posAtom.z;
}
template <typename REAL, typename DOF_T>
__device__ __forceinline__ void deform(
DOF_T const& dof, Vec3<REAL> & posAtom, d_Protein<REAL> const& protein, unsigned const idxAtom, unsigned const idx_protein, unsigned const bufIdx,
REAL& buffer_defoX, REAL& buffer_defoY, REAL& buffer_defoZ,
typename std::enable_if<std::is_same< DOF_T, DOF_6D<REAL> >::value, void>::type* dummy = 0 )
{
}
template <typename REAL, typename DOF_T>
__device__ __forceinline__ void translate_rotate( DOF_T const& dof, Vec3<REAL> & posAtom, unsigned const type_protein,
typename std::enable_if<std::is_same< DOF_T, DOF_6D_Modes<REAL> >::value, void>::type* dummy = 0 )
{
RotMat<REAL> rotMat = euler2rotmat(dof._6D.ang.x, dof._6D.ang.y, dof._6D.ang.z);
Vec3<REAL> translation = dof._6D.pos;
if ( type_protein == 0)
{
rotMat = rotMat.getInv();
translation = rotMat * translation.inv();
}
posAtom = rotMat*posAtom;
posAtom += translation;
}
template <typename REAL, typename DOF_T>
__device__ __forceinline__ void translate_rotate( DOF_T const& dof, Vec3<REAL> & posAtom , unsigned const type_protein,
typename std::enable_if<std::is_same< DOF_T, DOF_6D<REAL> >::value, void>::type* dummy = 0 )
{
RotMat<REAL> rotMat = euler2rotmat(dof.ang.x, dof.ang.y, dof.ang.z);
Vec3<REAL> translation = dof.pos;
if ( type_protein == 0 ){
rotMat = rotMat.getInv();
translation = rotMat * translation.inv();
}
posAtom = rotMat*posAtom;
posAtom += translation;
}
template<typename REAL, typename DOF_T >
__device__ __forceinline__ void d_DOFPos_device(
d_Protein<REAL> const& protein,
DOF_T const & dof,
unsigned const idx,
unsigned const type_protein,
REAL& buffer_defoX, REAL& buffer_defoY, REAL& buffer_defoZ,
REAL& buffer_trafoX, REAL& buffer_trafoY, REAL& buffer_trafoZ
)
{
/* calculate element index that is to be prcessed */
const unsigned int num_atoms = protein.numAtoms;
/* load DOF from global memory */
unsigned atomIdx = idx % num_atoms;
Vec3<REAL> posAtom( protein.xPos[atomIdx],
protein.yPos[atomIdx],
protein.zPos[atomIdx]);
deform< REAL, DOF_T>( dof, posAtom, protein, atomIdx, type_protein, idx, buffer_defoX, buffer_defoY, buffer_defoZ);
translate_rotate< REAL, DOF_T>( dof, posAtom, type_protein );
buffer_trafoX = posAtom.x;
buffer_trafoY = posAtom.y;
buffer_trafoZ = posAtom.z;
}
template<typename REAL>
void d_rotateForces(
unsigned blockSize,
unsigned gridSize,
const cudaStream_t &stream,
REAL* xForce,
REAL* yForce,
REAL* zForce,
DOF_6D_Modes<REAL>* dofs,
unsigned numAtoms,
unsigned numDOFs
);
#endif
}
#endif /* TRANSFORM_MODES_H_ */
|
//Define what controls to send to KSP
//check if it is time to send a control packet
void send_control_packet() {
now = millis();
controlTime = now - controlTimeOld;
if (controlTime > CONTROLREFRESH) {
controlTimeOld = now;
define_control_packet();
motorfader(); //call motorfader if button pressed
}
}
//Main controls uses enum above, e.g. MainControls(SAS,true);
void MainControls(byte n, boolean s) {
if (s)
CPacket.MainControls |= (1 << n); // forces nth bit of x to be 1. all other bits left alone.
else
CPacket.MainControls &= ~(1 << n); // forces nth bit of x to be 0. all other bits left alone.
}
//Control groups (action groups) uses an integer to refer to a custom action group, e.g. ControlGroup(5,true);
void ControlGroups(byte n, boolean s) {
if (s)
CPacket.ControlGroup |= (1 << n); // forces nth bit of x to be 1. all other bits left alone.
else
CPacket.ControlGroup &= ~(1 << n); // forces nth bit of x to be 0. all other bits left alone.
}
//SAS mode uses enum above, e.g. setSASMode(SMPrograde);
void setSASMode(byte m) {
CPacket.NavballSASMode &= B11110000;
CPacket.NavballSASMode += m;
}
//Navball mode uses enum above, e.g. setNavBallMode(NAVBallSURFACE);
void setNavballMode(byte m) {
CPacket.NavballSASMode &= B00001111;
CPacket.NavballSASMode += m << 4;
}
void define_control_packet() {
if (Connected) {
//here we define what controls to send when which pins are manipulate
//toggle switches
if(!digitalRead(pSAS)){MainControls(SAS, true);} else {MainControls(SAS, false);}
if(!digitalRead(pRCS)){MainControls(RCS, true);} else {MainControls(RCS, false);}
if(digitalRead(pABORT)){MainControls(ABORT, true);} else {MainControls(ABORT, false);}
//momentary stage button
if(debouncerStage.pressed() && digitalRead(pARM)){MainControls(STAGE, true);} else {MainControls(STAGE, false);}
//toggle buttons
if(debouncerLights.pressed()){MainControls(LIGHTS, !lights_on);}
if(debouncerGears.pressed()){MainControls(GEARS, !gears_on);}
if(debouncerBrakes.pressed()){MainControls(BRAKES, !brakes_on);}
if(debouncerA1.pressed()){ControlGroups(1, !action1_on);}
if(debouncerA2.pressed()){ControlGroups(2, !action2_on);}
if(debouncerA3.pressed()){ControlGroups(3, !action3_on);}
if(debouncerA4.pressed()){ControlGroups(4, !action4_on);}
if(debouncerA5.pressed()){ControlGroups(5, !action5_on);}
if(debouncerA6.pressed()){ControlGroups(6, !action6_on);}
if(debouncerLadder.pressed()){ControlGroups(7, !ladder_on);}
if(debouncerChutes.pressed()){ControlGroups(8, !chutes_on);}
if(debouncerSolar.pressed()){ControlGroups(9, !solar_on);}
//check flymode
if((digitalRead(pprecision)) and (!digitalRead(pmodeswitch))){
flymode = 0;} // rocket mode
else if((digitalRead(pprecision)) and (digitalRead(pmodeswitch))){
flymode = 1;} // plane mode
else if((!digitalRead(pprecision)) and (!digitalRead(pmodeswitch))){
flymode = 2;} // rocket mode + precision
else if((!digitalRead(pprecision)) and (digitalRead(pmodeswitch))){
flymode = 3;} // plane mode + precision
else {flymode = 0;}
int deadzone = 25;
int deadzonethrottle = 10;
switch(flymode){
case 0:
CPacket.Throttle = constrain(map(analogRead(pTHROTTLE),1023-deadzonethrottle,0+deadzonethrottle,0,1000),0,1000);
CPacket.WheelThrottle = constrain(map(analogRead(pTHROTTLE),1023-deadzonethrottle,0+deadzonethrottle,0,1000),0,1000);
if(analogRead(pRX) >= 512+deadzone){CPacket.Yaw = constrain(map(analogRead(pRX),512+deadzone,1023,0,1000),0,1000);
CPacket.WheelSteer = constrain(map(analogRead(pRX),1023,512+deadzone,-1000,0),-1000,0);}
else if(analogRead(pRX) <= 512-deadzone){CPacket.Yaw = constrain(map(analogRead(pRX),0,512-deadzone,-1000,0),-1000,0);
CPacket.WheelSteer = constrain(map(analogRead(pRX),512-deadzone,0,0,1000),0,1000);}
else {CPacket.Yaw = 0;
CPacket.WheelSteer = 0;}
if(analogRead(pRY) >= 512+deadzone){CPacket.Pitch = constrain(map(analogRead(pRY),512+deadzone,1023,0,1000),0,1000);}
else if(analogRead(pRY) <= 512-deadzone){CPacket.Pitch = constrain(map(analogRead(pRY),0,512-deadzone,-1000,0),-1000,0);}
else {CPacket.Pitch = 0;}
if(analogRead(pRZ) >= 512+deadzone){CPacket.Roll = constrain(map(analogRead(pRZ),512+deadzone,1023,0,1000),0,1000);}
else if(analogRead(pRZ) <= 512-deadzone){CPacket.Roll = constrain(map(analogRead(pRZ),0,512-deadzone,-1000,0),-1000,0);}
else {CPacket.Roll = 0;}
if(analogRead(pTX) >= 512+deadzone){CPacket.TX = constrain(map(analogRead(pTX),1023,512+deadzone,-1000,0),-1000,0);}
else if(analogRead(pTX) <= 512-deadzone){CPacket.TX = constrain(map(analogRead(pTX),512-deadzone,0,0,1000),0,1000);}
else {CPacket.TX = 0;}
if(analogRead(pTY) >= 512+deadzone){CPacket.TY = constrain(map(analogRead(pTY),1023,512+deadzone,-1000,0),-1000,0);}
else if(analogRead(pTY) <= 512-deadzone){CPacket.TY = constrain(map(analogRead(pTY),512-deadzone,0,0,1000),0,1000);}
else {CPacket.TY = 0;}
if(analogRead(pTZ) >= 512+deadzone){CPacket.TZ = constrain(map(analogRead(pTZ),1023,512+deadzone,-1000,0),-1000,0);}
else if(analogRead(pTZ) <= 512-deadzone){CPacket.TZ = constrain(map(analogRead(pTZ),512-deadzone,0,0,1000),0,1000);}
else {CPacket.TZ = 0;}
break;
case 1:
CPacket.Throttle = constrain(map(analogRead(pTHROTTLE),1023-deadzonethrottle,0+deadzonethrottle,0,1000),0,1000);
CPacket.WheelThrottle = constrain(map(analogRead(pTHROTTLE),1023-deadzonethrottle,0+deadzonethrottle,0,1000),0,1000);
if(analogRead(pRX) >= 512+deadzone){CPacket.Roll = constrain(map(analogRead(pRX),512+deadzone,1023,0,1000),0,1000);}
else if(analogRead(pRX) <= 512-deadzone){CPacket.Roll = constrain(map(analogRead(pRX),0,512-deadzone,-1000,0),-1000,0);}
else {CPacket.Roll = 0;}
if(analogRead(pRY) >= 512+deadzone){CPacket.Pitch = constrain(map(analogRead(pRY),512+deadzone,1023,0,1000),0,1000);}
else if(analogRead(pRY) <= 512-deadzone){CPacket.Pitch = constrain(map(analogRead(pRY),0,512-deadzone,-1000,0),-1000,0);}
else {CPacket.Pitch = 0;}
if(analogRead(pRZ) >= 512+deadzone){CPacket.Yaw = constrain(map(analogRead(pRZ),512+deadzone,1023,0,1000),0,1000);
CPacket.WheelSteer = constrain(map(analogRead(pRZ),1023,512+deadzone,-1000,0),-1000,0);}
else if(analogRead(pRZ) <= 512-deadzone){CPacket.Yaw = constrain(map(analogRead(pRZ),0,512-deadzone,-1000,0),-1000,0);
CPacket.WheelSteer = constrain(map(analogRead(pRZ),512-deadzone,0,0,1000),0,1000);}
else {CPacket.Yaw = 0;
CPacket.WheelSteer = 0;}
if(analogRead(pTX) >= 512+deadzone){CPacket.TX = constrain(map(analogRead(pTX),1023,512+deadzone,-1000,0),-1000,0);}
else if(analogRead(pTX) <= 512-deadzone){CPacket.TX = constrain(map(analogRead(pTX),512-deadzone,0,0,1000),0,1000);}
else {CPacket.TX = 0;}
if(analogRead(pTY) >= 512+deadzone){CPacket.TY = constrain(map(analogRead(pTY),1023,512+deadzone,-1000,0),-1000,0);}
else if(analogRead(pTY) <= 512-deadzone){CPacket.TY = constrain(map(analogRead(pTY),512-deadzone,0,0,1000),0,1000);}
else {CPacket.TY = 0;}
if(analogRead(pTZ) >= 512+deadzone){CPacket.TZ = constrain(map(analogRead(pTZ),1023,512+deadzone,-1000,0),-1000,0);}
else if(analogRead(pTZ) <= 512-deadzone){CPacket.TZ = constrain(map(analogRead(pTZ),512-deadzone,0,0,1000),0,1000);}
else {CPacket.TZ = 0;}
break;
case 2:
CPacket.Throttle = constrain(map(analogRead(pTHROTTLE),1023-deadzonethrottle,0+deadzonethrottle,0,1000),0,1000);
CPacket.WheelThrottle = constrain(map(analogRead(pTHROTTLE),1023-deadzonethrottle,0+deadzonethrottle,0,1000),0,1000);
if(analogRead(pRX) >= 512+deadzone){CPacket.Yaw = constrain(map(analogRead(pRX),512+deadzone,1023,0,500),0,500);
CPacket.WheelSteer = constrain(map(analogRead(pRX),1023,512+deadzone,-500,0),-500,0);}
else if(analogRead(pRX) <= 512-deadzone){CPacket.Yaw = constrain(map(analogRead(pRX),0,512-deadzone,-500,0),-500,0);
CPacket.WheelSteer = constrain(map(analogRead(pRX),512-deadzone,0,0,500),0,500);}
else {CPacket.Yaw = 0;
CPacket.WheelSteer = 0;}
if(analogRead(pRY) >= 512+deadzone){CPacket.Pitch = constrain(map(analogRead(pRY),512+deadzone,1023,0,500),0,500);}
else if(analogRead(pRY) <= 512-deadzone){CPacket.Pitch = constrain(map(analogRead(pRY),0,512-deadzone,-500,0),-500,0);}
else {CPacket.Pitch = 0;}
if(analogRead(pRZ) >= 512+deadzone){CPacket.Roll = constrain(map(analogRead(pRZ),512+deadzone,1023,0,500),0,500);}
else if(analogRead(pRZ) <= 512-deadzone){CPacket.Roll = constrain(map(analogRead(pRZ),0,512-deadzone,-500,0),-500,0);}
else {CPacket.Roll = 0;}
if(analogRead(pTX) >= 512+deadzone){CPacket.TX = constrain(map(analogRead(pTX),1023,512+deadzone,-500,0),-500,0);}
else if(analogRead(pTX) <= 512-deadzone){CPacket.TX = constrain(map(analogRead(pTX),512-deadzone,0,0,500),0,500);}
else {CPacket.TX = 0;}
if(analogRead(pTY) >= 512+deadzone){CPacket.TY = constrain(map(analogRead(pTY),1023,512+deadzone,-500,0),-500,0);}
else if(analogRead(pTY) <= 512-deadzone){CPacket.TY = constrain(map(analogRead(pTY),512-deadzone,0,0,500),0,500);}
else {CPacket.TY = 0;}
if(analogRead(pTZ) >= 512+deadzone){CPacket.TZ = constrain(map(analogRead(pTZ),1023,512+deadzone,-500,0),-500,0);}
else if(analogRead(pTZ) <= 512-deadzone){CPacket.TZ = constrain(map(analogRead(pTZ),512-deadzone,0,0,500),0,500);}
else {CPacket.TZ = 0;}
break;
case 3:
CPacket.Throttle = constrain(map(analogRead(pTHROTTLE),1023-deadzonethrottle,0+deadzonethrottle,0,1000),0,1000);
CPacket.WheelThrottle = constrain(map(analogRead(pTHROTTLE),1023-deadzonethrottle,0+deadzonethrottle,0,1000),0,1000);
if(analogRead(pRX) >= 512+deadzone){CPacket.Roll = constrain(map(analogRead(pRX),512+deadzone,1023,0,500),0,500);}
else if(analogRead(pRX) <= 512-deadzone){CPacket.Roll = constrain(map(analogRead(pRX),0,512-deadzone,-500,0),-500,0);}
else {CPacket.Roll = 0;}
if(analogRead(pRY) >= 512+deadzone){CPacket.Pitch = constrain(map(analogRead(pRY),512+deadzone,1023,0,500),0,500);}
else if(analogRead(pRY) <= 512-deadzone){CPacket.Pitch = constrain(map(analogRead(pRY),0,512-deadzone,-500,0),-500,0);}
else {CPacket.Pitch = 0;}
if(analogRead(pRZ) >= 512+deadzone){CPacket.Yaw = constrain(map(analogRead(pRZ),512+deadzone,1023,0,500),0,500);
CPacket.WheelSteer = constrain(map(analogRead(pRZ),1023,512+deadzone,-500,0),-500,0);}
else if(analogRead(pRZ) <= 512-deadzone){CPacket.Yaw = constrain(map(analogRead(pRZ),0,512-deadzone,-500,0),-500,0);
CPacket.WheelSteer = constrain(map(analogRead(pRZ),512-deadzone,0,0,500),0,500);}
else {CPacket.Yaw = 0;
CPacket.WheelSteer = 0;}
if(analogRead(pTX) >= 512+deadzone){CPacket.TX = constrain(map(analogRead(pTX),1023,512+deadzone,-500,0),-500,0);}
else if(analogRead(pTX) <= 512-deadzone){CPacket.TX = constrain(map(analogRead(pTX),512-deadzone,0,0,500),0,500);}
else {CPacket.TX = 0;}
if(analogRead(pTY) >= 512+deadzone){CPacket.TY = constrain(map(analogRead(pTY),1023,512+deadzone,-500,0),-500,0);}
else if(analogRead(pTY) <= 512-deadzone){CPacket.TY = constrain(map(analogRead(pTY),512-deadzone,0,0,500),0,500);}
else {CPacket.TY = 0;}
if(analogRead(pTZ) >= 512+deadzone){CPacket.TZ = constrain(map(analogRead(pTZ),1023,512+deadzone,-500,0),-500,0);}
else if(analogRead(pTZ) <= 512-deadzone){CPacket.TZ = constrain(map(analogRead(pTZ),512-deadzone,0,0,500),0,500);}
else {CPacket.TZ = 0;}
break;
}
//send the control packet to the KSPSerialIO plugin
KSPBoardSendData(details(CPacket));
}
}
void motorfader() {
if(!digitalRead(maxthrottle)){
throttletarget = 0;
digitalWrite(motoron, HIGH);
}
else if(!digitalRead(minthrottle)){
throttletarget = 1020;
digitalWrite(motoron, HIGH);
}
else {
throttletarget = pTHROTTLE;
digitalWrite(motoron, LOW);
}
if (analogRead(pTHROTTLE) > (throttletarget + theThreshold) ) {
analogWrite(motordown, 0);
analogWrite(motorup, 255);
}
else if (analogRead(pTHROTTLE) < (throttletarget - theThreshold) ) {
analogWrite(motordown, 255);
analogWrite(motorup, 0);
}
else {
analogWrite(motordown, 0);
analogWrite(motorup, 0);
}
}
|
#include <MaxMatrix.h>
const byte DATA1 = 11; // 資料輸入線
const byte CS1= 10; // 晶片選擇線
const byte CLK1 = 9;// 時脈線
const byte DATA2 = 11; // 資料輸入線
const byte CS2= 10; // 晶片選擇線
const byte CLK2 = 9; // 時脈線
const byte maxInUse = 6; // 代表串連兩個MAX7219模組
MaxMatrix m1(DATA1, CS1, CLK1, maxInUse);
//MaxMatrix m2(DATA2, CS2, CLK2, maxInUse);
long long int light_data1[] = {0, 0, 0, 0, 0, 0, 0, 0};
long long int light_data2[] = {0, 0, 0, 0, 0, 0, 0, 0};
short LED_R2[16] = {3, 7, 2, 4, 0, 5, 1, 6, 27, 31, 26, 28, 24, 29, 25, 30};
short LED_G2[16] = {14, 8, 10, 11, 22, 21, 20, 19, 38, 32, 34, 35, 46, 45, 44, 43};
short LED_B2[16] = {9, 13, 12, 15, 17, 16, 18, 23, 33, 37, 36, 39, 41, 40, 42, 47};
short LED_R1[16] = {27, 31, 26, 28, 24, 29, 25, 30, 3, 7, 2, 4, 0, 5, 1, 6};
short LED_G1[16] = {33, 32, 34, 35, 41, 40, 42, 43, 9, 8, 10, 11, 22, 16, 18, 19};
short LED_B1[16] = {38, 37, 36, 39, 46, 45, 44, 47, 14, 13, 12, 15, 17, 21, 20, 23};
void reset1(){
for (int i=0;i<8;i++){
light_data1[i] = (long long int)0;
}
}
void reset2(){
for (int i=0;i<8;i++){
light_data2[i] = (long long int)0;
}
}
void set_color1(int LED_NUM, int R, int G, int B){
for (int i=0;i<R;i++){
light_data1[i] |= ((long long int)1 << LED_R1[LED_NUM]);
}
for (int i=0;i<G;i++){
light_data1[i] |= ((long long int)1 << LED_G1[LED_NUM]);
}
for (int i=0;i<B;i++){
light_data1[i] |= ((long long int)1 << LED_B1[LED_NUM]);
}
}
void set_color2(int LED_NUM, int R, int G, int B){
for (int i=0;i<R;i++){
light_data2[i] |= ((long long int)1 << LED_R2[LED_NUM]);
}
for (int i=0;i<G;i++){
light_data2[i] |= ((long long int)1 << LED_G2[LED_NUM]);
}
for (int i=0;i<B;i++){
light_data2[i] |= ((long long int)1 << LED_B2[LED_NUM]);
}
}
void show1(){
for (int i=0;i<6;i++){
byte ttt[] = {8, 8, 0, 0, 0, 0, 0, 0, 0, 0};
for (int j=0;j<8;j++){
ttt[j+2] = (light_data1[j] >> (i*8));
//Serial.print(ttt[j+2]);
//Serial.print(" ");
}
//Serial.println();
m1.writeSprite(i*8, 0, ttt);
}
}
void show2(){
for (int i=0;i<6;i++){
byte ttt[] = {8, 8, 0, 0, 0, 0, 0, 0, 0, 0};
for (int j=0;j<8;j++){
ttt[j+2] = (light_data2[j] >> (i*8));
//Serial.print(ttt[j+2]);
//Serial.print(" ");
}
//Serial.println();
//m2.writeSprite(i*8, 0, ttt);
}
}
void setup() {
// put your setup code here, to run once:
m1.init();
//m2.init();
m1.setIntensity(20);
//m2.setIntensity(20);
//delay(1000);
pinMode(13, OUTPUT);
Serial.begin(9600);
}
void loop() {
m1.init();
for (int i=0;i<16;i++){
set_color1(i, 6, 0, 0);
show1();
delay(50);
reset1();
}
for (int i=0;i<16;i++){
set_color1(i, 0, 6, 0);
show1();
delay(50);
reset1();
}
for (int i=0;i<16;i++){
set_color1(i, 0, 0, 6);
show1();
delay(50);
reset1();
}
for (int i=0;i<16;i++){
set_color1(i, i%3, i%6, i%4);
show1();
delay(50);
}
for (int i=0;i<16;i++){
set_color1(i, i%6, i%4, i%3);
show1();
delay(50);
}
reset1();
for (int j=8;j>0;j--){
for (int i=0;i<16;i++){
set_color1(i, j, j, j);
}
show1();
reset1();
delay(50);
}
reset1();
for (int j = 1;j<9;j++){
for (int i=0;i<16;i++){
set_color1(i, j, 0, 0);
}
show1();
delay(50);
reset1();
}
for (int j = 8;j > 0;j--){
for (int i=0;i<16;i++){
set_color1(i, j, 0, 0);
}
show1();
delay(50);
reset1();
}
for (int j = 1;j<9;j++){
for (int i=0;i<16;i++){
set_color1(i, 0, j, 0);
}
show1();
delay(50);
reset1();
}
for (int j = 8;j > 0;j--){
for (int i=0;i<16;i++){
set_color1(i, 0, j, 0);
}
show1();
delay(50);
reset1();
}
for (int j = 1;j<9;j++){
for (int i=0;i<16;i++){
set_color1(i, 0, 0, j);
}
show1();
delay(50);
reset1();
}
for (int j = 8;j > 0;j--){
for (int i=0;i<16;i++){
set_color1(i, 0, 0, j);
}
show1();
delay(50);
reset1();
}
}
|
/**
* $Source: /backup/cvsroot/project/pnids/zdk/zls/zvm/CGlobalVariableRegisterEntry.cpp,v $
*
* $Date: 2001/11/14 18:29:37 $
*
* $Revision: 1.3 $
*
* $Name: $
*
* $Author: zls $
*
* Copyright(C) since 1998 by Albert Zheng - 郑立松, All Rights Reserved.
*
* lisong.zheng@gmail.com
*
* $State: Exp $
*/
#include <zls/zvm/CGlobalVariableRegisterEntry.hpp>
#include <zls/zvm/IDynamicLoadableModule.hpp>
ZLS_BEGIN_NAMESPACE(zvm)
const std::string & CGlobalVariableRegisterEntry::GetSourceFileName() const
{ return _pciOwnerModule->GetSourceFileName(); }
const std::string & CGlobalVariableRegisterEntry::GetObjectFileName() const
{ return _pciOwnerModule->GetObjectFileName(); }
CGlobalVariableRegisterEntry::CGlobalVariableRegisterEntry(
const std::string & rstringTypeSignature,
IDynamicLoadableModule * pciOwnerModule)
: _stringTypeSignature(rstringTypeSignature),
_pciOwnerModule(pciOwnerModule),
_ciVariableSlot(rstringTypeSignature)
//< May throw zfc::EOutOfMemory
{ }
ZLS_END_NAMESPACE
|
// C++ for the Windows Runtime vv1.0.170303.6
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
#include "Windows.Services.TargetedContent.1.h"
#include "Windows.Storage.Streams.1.h"
#include "Windows.Storage.Streams.2.h"
WINRT_EXPORT namespace winrt {
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
#define WINRT_GENERIC_e2fcc7c1_3bfc_5a0b_b2b0_72e769d1cb7e
template <> struct __declspec(uuid("e2fcc7c1-3bfc-5a0b-b2b0-72e769d1cb7e")) __declspec(novtable) IIterable<hstring> : impl_IIterable<hstring> {};
#endif
#ifndef WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
#define WINRT_GENERIC_2f13c006_a03a_5f69_b090_75a43e33423e
template <> struct __declspec(uuid("2f13c006-a03a-5f69-b090-75a43e33423e")) __declspec(novtable) IVectorView<hstring> : impl_IVectorView<hstring> {};
#endif
#ifndef WINRT_GENERIC_b0d63b78_78ad_5e31_b6d8_e32a0e16c447
#define WINRT_GENERIC_b0d63b78_78ad_5e31_b6d8_e32a0e16c447
template <> struct __declspec(uuid("b0d63b78-78ad-5e31-b6d8-e32a0e16c447")) __declspec(novtable) IIterable<Windows::Foundation::Uri> : impl_IIterable<Windows::Foundation::Uri> {};
#endif
#ifndef WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
#define WINRT_GENERIC_98b9acc1_4b56_532e_ac73_03d5291cca90
template <> struct __declspec(uuid("98b9acc1-4b56-532e-ac73-03d5291cca90")) __declspec(novtable) IVector<hstring> : impl_IVector<hstring> {};
#endif
#ifndef WINRT_GENERIC_ac7f26f2_feb7_5b2a_8ac4_345bc62caede
#define WINRT_GENERIC_ac7f26f2_feb7_5b2a_8ac4_345bc62caede
template <> struct __declspec(uuid("ac7f26f2-feb7-5b2a-8ac4-345bc62caede")) __declspec(novtable) IMapView<hstring, hstring> : impl_IMapView<hstring, hstring> {};
#endif
#ifndef WINRT_GENERIC_f6d1f700_49c2_52ae_8154_826f9908773c
#define WINRT_GENERIC_f6d1f700_49c2_52ae_8154_826f9908773c
template <> struct __declspec(uuid("f6d1f700-49c2-52ae-8154-826f9908773c")) __declspec(novtable) IMap<hstring, hstring> : impl_IMap<hstring, hstring> {};
#endif
#ifndef WINRT_GENERIC_60310303_49c5_52e6_abc6_a9b36eccc716
#define WINRT_GENERIC_60310303_49c5_52e6_abc6_a9b36eccc716
template <> struct __declspec(uuid("60310303-49c5-52e6-abc6-a9b36eccc716")) __declspec(novtable) IKeyValuePair<hstring, hstring> : impl_IKeyValuePair<hstring, hstring> {};
#endif
#ifndef WINRT_GENERIC_4b8385bd_a2cd_5ff1_bf74_7ea580423e50
#define WINRT_GENERIC_4b8385bd_a2cd_5ff1_bf74_7ea580423e50
template <> struct __declspec(uuid("4b8385bd-a2cd-5ff1-bf74-7ea580423e50")) __declspec(novtable) IVectorView<Windows::Foundation::Uri> : impl_IVectorView<Windows::Foundation::Uri> {};
#endif
#ifndef WINRT_GENERIC_0d82bd8d_fe62_5d67_a7b9_7886dd75bc4e
#define WINRT_GENERIC_0d82bd8d_fe62_5d67_a7b9_7886dd75bc4e
template <> struct __declspec(uuid("0d82bd8d-fe62-5d67-a7b9-7886dd75bc4e")) __declspec(novtable) IVector<Windows::Foundation::Uri> : impl_IVector<Windows::Foundation::Uri> {};
#endif
#ifndef WINRT_GENERIC_f452d23c_bf05_5f3e_88e7_d17a6716b911
#define WINRT_GENERIC_f452d23c_bf05_5f3e_88e7_d17a6716b911
template <> struct __declspec(uuid("f452d23c-bf05-5f3e-88e7-d17a6716b911")) __declspec(novtable) IVector<double> : impl_IVector<double> {};
#endif
#ifndef WINRT_GENERIC_c738964e_9c64_5bce_b5ce_61e9a282ec4a
#define WINRT_GENERIC_c738964e_9c64_5bce_b5ce_61e9a282ec4a
template <> struct __declspec(uuid("c738964e-9c64-5bce-b5ce-61e9a282ec4a")) __declspec(novtable) IIterable<double> : impl_IIterable<double> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_46f16f4b_8ec1_5c4f_b1f5_a7e7acd63366
#define WINRT_GENERIC_46f16f4b_8ec1_5c4f_b1f5_a7e7acd63366
template <> struct __declspec(uuid("46f16f4b-8ec1-5c4f-b1f5-a7e7acd63366")) __declspec(novtable) IAsyncOperation<Windows::Services::TargetedContent::TargetedContentSubscription> : impl_IAsyncOperation<Windows::Services::TargetedContent::TargetedContentSubscription> {};
#endif
#ifndef WINRT_GENERIC_e757e0fc_0136_5f63_97b8_6a96b8d0601e
#define WINRT_GENERIC_e757e0fc_0136_5f63_97b8_6a96b8d0601e
template <> struct __declspec(uuid("e757e0fc-0136-5f63-97b8-6a96b8d0601e")) __declspec(novtable) IAsyncOperation<Windows::Services::TargetedContent::TargetedContentContainer> : impl_IAsyncOperation<Windows::Services::TargetedContent::TargetedContentContainer> {};
#endif
#ifndef WINRT_GENERIC_ef11d751_9d56_580d_8a9f_51ae7e8036e3
#define WINRT_GENERIC_ef11d751_9d56_580d_8a9f_51ae7e8036e3
template <> struct __declspec(uuid("ef11d751-9d56-580d-8a9f-51ae7e8036e3")) __declspec(novtable) TypedEventHandler<Windows::Services::TargetedContent::TargetedContentSubscription, Windows::Services::TargetedContent::TargetedContentChangedEventArgs> : impl_TypedEventHandler<Windows::Services::TargetedContent::TargetedContentSubscription, Windows::Services::TargetedContent::TargetedContentChangedEventArgs> {};
#endif
#ifndef WINRT_GENERIC_99929904_138a_59ac_a11a_fe0042f0fd50
#define WINRT_GENERIC_99929904_138a_59ac_a11a_fe0042f0fd50
template <> struct __declspec(uuid("99929904-138a-59ac-a11a-fe0042f0fd50")) __declspec(novtable) TypedEventHandler<Windows::Services::TargetedContent::TargetedContentSubscription, Windows::Services::TargetedContent::TargetedContentAvailabilityChangedEventArgs> : impl_TypedEventHandler<Windows::Services::TargetedContent::TargetedContentSubscription, Windows::Services::TargetedContent::TargetedContentAvailabilityChangedEventArgs> {};
#endif
#ifndef WINRT_GENERIC_c4d5acbe_f65b_5fa4_9242_d2860de85d52
#define WINRT_GENERIC_c4d5acbe_f65b_5fa4_9242_d2860de85d52
template <> struct __declspec(uuid("c4d5acbe-f65b-5fa4-9242-d2860de85d52")) __declspec(novtable) TypedEventHandler<Windows::Services::TargetedContent::TargetedContentSubscription, Windows::Services::TargetedContent::TargetedContentStateChangedEventArgs> : impl_TypedEventHandler<Windows::Services::TargetedContent::TargetedContentSubscription, Windows::Services::TargetedContent::TargetedContentStateChangedEventArgs> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_19a87e94_ab75_574f_a226_8726a0d8eb3e
#define WINRT_GENERIC_19a87e94_ab75_574f_a226_8726a0d8eb3e
template <> struct __declspec(uuid("19a87e94-ab75-574f-a226-8726a0d8eb3e")) __declspec(novtable) IMapView<hstring, Windows::Services::TargetedContent::TargetedContentValue> : impl_IMapView<hstring, Windows::Services::TargetedContent::TargetedContentValue> {};
#endif
#ifndef WINRT_GENERIC_cea4c859_8736_5c75_bb83_a686bf7f7c6f
#define WINRT_GENERIC_cea4c859_8736_5c75_bb83_a686bf7f7c6f
template <> struct __declspec(uuid("cea4c859-8736-5c75-bb83-a686bf7f7c6f")) __declspec(novtable) IVectorView<Windows::Services::TargetedContent::TargetedContentCollection> : impl_IVectorView<Windows::Services::TargetedContent::TargetedContentCollection> {};
#endif
#ifndef WINRT_GENERIC_31e3ed33_8554_5496_86a4_d78392204c8f
#define WINRT_GENERIC_31e3ed33_8554_5496_86a4_d78392204c8f
template <> struct __declspec(uuid("31e3ed33-8554-5496-86a4-d78392204c8f")) __declspec(novtable) IVectorView<Windows::Services::TargetedContent::TargetedContentItem> : impl_IVectorView<Windows::Services::TargetedContent::TargetedContentItem> {};
#endif
#ifndef WINRT_GENERIC_af7586a8_6b21_5f61_bff1_1b682293ad96
#define WINRT_GENERIC_af7586a8_6b21_5f61_bff1_1b682293ad96
template <> struct __declspec(uuid("af7586a8-6b21-5f61-bff1-1b682293ad96")) __declspec(novtable) IVectorView<double> : impl_IVectorView<double> {};
#endif
#ifndef WINRT_GENERIC_243a09cb_6f40_56af_a442_fe81431fbef5
#define WINRT_GENERIC_243a09cb_6f40_56af_a442_fe81431fbef5
template <> struct __declspec(uuid("243a09cb-6f40-56af-a442-fe81431fbef5")) __declspec(novtable) IVectorView<bool> : impl_IVectorView<bool> {};
#endif
#ifndef WINRT_GENERIC_ec0d80cb_9a87_5f0b_b6df_2c09b6310177
#define WINRT_GENERIC_ec0d80cb_9a87_5f0b_b6df_2c09b6310177
template <> struct __declspec(uuid("ec0d80cb-9a87-5f0b-b6df-2c09b6310177")) __declspec(novtable) IVectorView<Windows::Services::TargetedContent::TargetedContentFile> : impl_IVectorView<Windows::Services::TargetedContent::TargetedContentFile> {};
#endif
#ifndef WINRT_GENERIC_f55ac7c6_168d_5010_84cf_36bf451ede38
#define WINRT_GENERIC_f55ac7c6_168d_5010_84cf_36bf451ede38
template <> struct __declspec(uuid("f55ac7c6-168d-5010-84cf-36bf451ede38")) __declspec(novtable) IVectorView<Windows::Services::TargetedContent::TargetedContentImage> : impl_IVectorView<Windows::Services::TargetedContent::TargetedContentImage> {};
#endif
#ifndef WINRT_GENERIC_4299bd84_e44e_5fcb_a465_e1bd434a317c
#define WINRT_GENERIC_4299bd84_e44e_5fcb_a465_e1bd434a317c
template <> struct __declspec(uuid("4299bd84-e44e-5fcb-a465-e1bd434a317c")) __declspec(novtable) IVectorView<Windows::Services::TargetedContent::TargetedContentAction> : impl_IVectorView<Windows::Services::TargetedContent::TargetedContentAction> {};
#endif
#ifndef WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
#define WINRT_GENERIC_8c304ebb_6615_50a4_8829_879ecd443236
template <> struct __declspec(uuid("8c304ebb-6615-50a4-8829-879ecd443236")) __declspec(novtable) IIterator<hstring> : impl_IIterator<hstring> {};
#endif
#ifndef WINRT_GENERIC_1c157d0f_5efe_5cec_bbd6_0c6ce9af07a5
#define WINRT_GENERIC_1c157d0f_5efe_5cec_bbd6_0c6ce9af07a5
template <> struct __declspec(uuid("1c157d0f-5efe-5cec-bbd6-0c6ce9af07a5")) __declspec(novtable) IIterator<Windows::Foundation::Uri> : impl_IIterator<Windows::Foundation::Uri> {};
#endif
#ifndef WINRT_GENERIC_638a2cf4_f474_5318_9055_141cb909ac4b
#define WINRT_GENERIC_638a2cf4_f474_5318_9055_141cb909ac4b
template <> struct __declspec(uuid("638a2cf4-f474-5318-9055-141cb909ac4b")) __declspec(novtable) IIterator<double> : impl_IIterator<double> {};
#endif
}
namespace ABI::Windows::Foundation {
#ifndef WINRT_GENERIC_e4188c71_5a8e_57ec_b0de_1d314fb3e2cf
#define WINRT_GENERIC_e4188c71_5a8e_57ec_b0de_1d314fb3e2cf
template <> struct __declspec(uuid("e4188c71-5a8e-57ec-b0de-1d314fb3e2cf")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Services::TargetedContent::TargetedContentSubscription> : impl_AsyncOperationCompletedHandler<Windows::Services::TargetedContent::TargetedContentSubscription> {};
#endif
#ifndef WINRT_GENERIC_8fc6bc2a_26ce_50b5_97bb_fcc80ca0871d
#define WINRT_GENERIC_8fc6bc2a_26ce_50b5_97bb_fcc80ca0871d
template <> struct __declspec(uuid("8fc6bc2a-26ce-50b5-97bb-fcc80ca0871d")) __declspec(novtable) AsyncOperationCompletedHandler<Windows::Services::TargetedContent::TargetedContentContainer> : impl_AsyncOperationCompletedHandler<Windows::Services::TargetedContent::TargetedContentContainer> {};
#endif
}
namespace ABI::Windows::Foundation::Collections {
#ifndef WINRT_GENERIC_35cf9903_ade5_565d_a011_be3173d09215
#define WINRT_GENERIC_35cf9903_ade5_565d_a011_be3173d09215
template <> struct __declspec(uuid("35cf9903-ade5-565d-a011-be3173d09215")) __declspec(novtable) IKeyValuePair<hstring, Windows::Services::TargetedContent::TargetedContentValue> : impl_IKeyValuePair<hstring, Windows::Services::TargetedContent::TargetedContentValue> {};
#endif
#ifndef WINRT_GENERIC_f24d969d_ba69_5e26_b3ab_9c94f9bd8747
#define WINRT_GENERIC_f24d969d_ba69_5e26_b3ab_9c94f9bd8747
template <> struct __declspec(uuid("f24d969d-ba69-5e26-b3ab-9c94f9bd8747")) __declspec(novtable) IMap<hstring, Windows::Services::TargetedContent::TargetedContentValue> : impl_IMap<hstring, Windows::Services::TargetedContent::TargetedContentValue> {};
#endif
#ifndef WINRT_GENERIC_efa7e21b_562c_5fcc_82bd_0ceebd9d9c61
#define WINRT_GENERIC_efa7e21b_562c_5fcc_82bd_0ceebd9d9c61
template <> struct __declspec(uuid("efa7e21b-562c-5fcc-82bd-0ceebd9d9c61")) __declspec(novtable) IVector<Windows::Services::TargetedContent::TargetedContentCollection> : impl_IVector<Windows::Services::TargetedContent::TargetedContentCollection> {};
#endif
#ifndef WINRT_GENERIC_6093b8fd_6d5d_53cd_b497_7b4540f10857
#define WINRT_GENERIC_6093b8fd_6d5d_53cd_b497_7b4540f10857
template <> struct __declspec(uuid("6093b8fd-6d5d-53cd-b497-7b4540f10857")) __declspec(novtable) IIterator<Windows::Services::TargetedContent::TargetedContentCollection> : impl_IIterator<Windows::Services::TargetedContent::TargetedContentCollection> {};
#endif
#ifndef WINRT_GENERIC_2049f813_37ee_5158_9996_709859f0ce49
#define WINRT_GENERIC_2049f813_37ee_5158_9996_709859f0ce49
template <> struct __declspec(uuid("2049f813-37ee-5158-9996-709859f0ce49")) __declspec(novtable) IIterable<Windows::Services::TargetedContent::TargetedContentCollection> : impl_IIterable<Windows::Services::TargetedContent::TargetedContentCollection> {};
#endif
#ifndef WINRT_GENERIC_827bf6cf_4301_5b2a_a3bd_09edb0417241
#define WINRT_GENERIC_827bf6cf_4301_5b2a_a3bd_09edb0417241
template <> struct __declspec(uuid("827bf6cf-4301-5b2a-a3bd-09edb0417241")) __declspec(novtable) IVector<Windows::Services::TargetedContent::TargetedContentItem> : impl_IVector<Windows::Services::TargetedContent::TargetedContentItem> {};
#endif
#ifndef WINRT_GENERIC_50109d8e_f711_5076_8309_e4e230ef7e85
#define WINRT_GENERIC_50109d8e_f711_5076_8309_e4e230ef7e85
template <> struct __declspec(uuid("50109d8e-f711-5076-8309-e4e230ef7e85")) __declspec(novtable) IIterator<Windows::Services::TargetedContent::TargetedContentItem> : impl_IIterator<Windows::Services::TargetedContent::TargetedContentItem> {};
#endif
#ifndef WINRT_GENERIC_03f38fb6_54e6_5bf1_913b_9510fec8be1f
#define WINRT_GENERIC_03f38fb6_54e6_5bf1_913b_9510fec8be1f
template <> struct __declspec(uuid("03f38fb6-54e6-5bf1-913b-9510fec8be1f")) __declspec(novtable) IIterable<Windows::Services::TargetedContent::TargetedContentItem> : impl_IIterable<Windows::Services::TargetedContent::TargetedContentItem> {};
#endif
#ifndef WINRT_GENERIC_6180171d_2ed8_5e24_8a55_01ecb1009eb2
#define WINRT_GENERIC_6180171d_2ed8_5e24_8a55_01ecb1009eb2
template <> struct __declspec(uuid("6180171d-2ed8-5e24-8a55-01ecb1009eb2")) __declspec(novtable) IVector<bool> : impl_IVector<bool> {};
#endif
#ifndef WINRT_GENERIC_740a0296_a535_572a_bf0b_17c18ff71fe6
#define WINRT_GENERIC_740a0296_a535_572a_bf0b_17c18ff71fe6
template <> struct __declspec(uuid("740a0296-a535-572a-bf0b-17c18ff71fe6")) __declspec(novtable) IIterator<bool> : impl_IIterator<bool> {};
#endif
#ifndef WINRT_GENERIC_30160817_1d7d_54e9_99db_d7636266a476
#define WINRT_GENERIC_30160817_1d7d_54e9_99db_d7636266a476
template <> struct __declspec(uuid("30160817-1d7d-54e9-99db-d7636266a476")) __declspec(novtable) IIterable<bool> : impl_IIterable<bool> {};
#endif
#ifndef WINRT_GENERIC_aede9a39_ffa7_5885_8cc5_46d7e05230a4
#define WINRT_GENERIC_aede9a39_ffa7_5885_8cc5_46d7e05230a4
template <> struct __declspec(uuid("aede9a39-ffa7-5885-8cc5-46d7e05230a4")) __declspec(novtable) IVector<Windows::Services::TargetedContent::TargetedContentFile> : impl_IVector<Windows::Services::TargetedContent::TargetedContentFile> {};
#endif
#ifndef WINRT_GENERIC_6a957f20_ed25_5019_90e7_9890d4f912f2
#define WINRT_GENERIC_6a957f20_ed25_5019_90e7_9890d4f912f2
template <> struct __declspec(uuid("6a957f20-ed25-5019-90e7-9890d4f912f2")) __declspec(novtable) IIterator<Windows::Services::TargetedContent::TargetedContentFile> : impl_IIterator<Windows::Services::TargetedContent::TargetedContentFile> {};
#endif
#ifndef WINRT_GENERIC_5f65d649_ccbd_5728_a85b_d3ff92fca962
#define WINRT_GENERIC_5f65d649_ccbd_5728_a85b_d3ff92fca962
template <> struct __declspec(uuid("5f65d649-ccbd-5728-a85b-d3ff92fca962")) __declspec(novtable) IIterable<Windows::Services::TargetedContent::TargetedContentFile> : impl_IIterable<Windows::Services::TargetedContent::TargetedContentFile> {};
#endif
#ifndef WINRT_GENERIC_b967c042_f7b9_538d_a427_c102c22a6501
#define WINRT_GENERIC_b967c042_f7b9_538d_a427_c102c22a6501
template <> struct __declspec(uuid("b967c042-f7b9-538d-a427-c102c22a6501")) __declspec(novtable) IVector<Windows::Services::TargetedContent::TargetedContentImage> : impl_IVector<Windows::Services::TargetedContent::TargetedContentImage> {};
#endif
#ifndef WINRT_GENERIC_a807b298_9e2f_5673_bcf6_1e35feba0647
#define WINRT_GENERIC_a807b298_9e2f_5673_bcf6_1e35feba0647
template <> struct __declspec(uuid("a807b298-9e2f-5673-bcf6-1e35feba0647")) __declspec(novtable) IIterator<Windows::Services::TargetedContent::TargetedContentImage> : impl_IIterator<Windows::Services::TargetedContent::TargetedContentImage> {};
#endif
#ifndef WINRT_GENERIC_efadb6bf_af18_5af9_a509_19881bc586f5
#define WINRT_GENERIC_efadb6bf_af18_5af9_a509_19881bc586f5
template <> struct __declspec(uuid("efadb6bf-af18-5af9-a509-19881bc586f5")) __declspec(novtable) IIterable<Windows::Services::TargetedContent::TargetedContentImage> : impl_IIterable<Windows::Services::TargetedContent::TargetedContentImage> {};
#endif
#ifndef WINRT_GENERIC_f3ad0d23_dd06_51c5_8fe4_8d030d5c093a
#define WINRT_GENERIC_f3ad0d23_dd06_51c5_8fe4_8d030d5c093a
template <> struct __declspec(uuid("f3ad0d23-dd06-51c5-8fe4-8d030d5c093a")) __declspec(novtable) IVector<Windows::Services::TargetedContent::TargetedContentAction> : impl_IVector<Windows::Services::TargetedContent::TargetedContentAction> {};
#endif
#ifndef WINRT_GENERIC_79656935_5813_5aa6_8e69_627a0d85088f
#define WINRT_GENERIC_79656935_5813_5aa6_8e69_627a0d85088f
template <> struct __declspec(uuid("79656935-5813-5aa6-8e69-627a0d85088f")) __declspec(novtable) IIterator<Windows::Services::TargetedContent::TargetedContentAction> : impl_IIterator<Windows::Services::TargetedContent::TargetedContentAction> {};
#endif
#ifndef WINRT_GENERIC_cf05b497_3afd_5d00_859e_9fbd1a36d576
#define WINRT_GENERIC_cf05b497_3afd_5d00_859e_9fbd1a36d576
template <> struct __declspec(uuid("cf05b497-3afd-5d00-859e-9fbd1a36d576")) __declspec(novtable) IIterable<Windows::Services::TargetedContent::TargetedContentAction> : impl_IIterable<Windows::Services::TargetedContent::TargetedContentAction> {};
#endif
#ifndef WINRT_GENERIC_e9bdaaf0_cbf6_5c72_be90_29cbf3a1319b
#define WINRT_GENERIC_e9bdaaf0_cbf6_5c72_be90_29cbf3a1319b
template <> struct __declspec(uuid("e9bdaaf0-cbf6-5c72-be90-29cbf3a1319b")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> {};
#endif
#ifndef WINRT_GENERIC_05eb86f1_7140_5517_b88d_cbaebe57e6b1
#define WINRT_GENERIC_05eb86f1_7140_5517_b88d_cbaebe57e6b1
template <> struct __declspec(uuid("05eb86f1-7140-5517-b88d-cbaebe57e6b1")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, hstring>> {};
#endif
#ifndef WINRT_GENERIC_b97e682b_6e0a_5eea_b70b_25795b28e937
#define WINRT_GENERIC_b97e682b_6e0a_5eea_b70b_25795b28e937
template <> struct __declspec(uuid("b97e682b-6e0a-5eea-b70b-25795b28e937")) __declspec(novtable) IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Services::TargetedContent::TargetedContentValue>> : impl_IIterator<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Services::TargetedContent::TargetedContentValue>> {};
#endif
#ifndef WINRT_GENERIC_45a020d8_fe49_5720_950b_3cceab655531
#define WINRT_GENERIC_45a020d8_fe49_5720_950b_3cceab655531
template <> struct __declspec(uuid("45a020d8-fe49-5720-950b-3cceab655531")) __declspec(novtable) IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Services::TargetedContent::TargetedContentValue>> : impl_IIterable<Windows::Foundation::Collections::IKeyValuePair<hstring, Windows::Services::TargetedContent::TargetedContentValue>> {};
#endif
}
namespace Windows::Services::TargetedContent {
struct ITargetedContentAction :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentAction>
{
ITargetedContentAction(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentAvailabilityChangedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentAvailabilityChangedEventArgs>
{
ITargetedContentAvailabilityChangedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentChangedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentChangedEventArgs>
{
ITargetedContentChangedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentCollection :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentCollection>
{
ITargetedContentCollection(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentContainer :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentContainer>
{
ITargetedContentContainer(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentContainerStatics :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentContainerStatics>
{
ITargetedContentContainerStatics(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentImage :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentImage>,
impl::require<ITargetedContentImage, Windows::Storage::Streams::IRandomAccessStreamReference>
{
ITargetedContentImage(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentItem :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentItem>
{
ITargetedContentItem(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentItemState :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentItemState>
{
ITargetedContentItemState(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentObject :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentObject>
{
ITargetedContentObject(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentStateChangedEventArgs :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentStateChangedEventArgs>
{
ITargetedContentStateChangedEventArgs(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentSubscription :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentSubscription>
{
ITargetedContentSubscription(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentSubscriptionOptions :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentSubscriptionOptions>
{
ITargetedContentSubscriptionOptions(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentSubscriptionStatics :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentSubscriptionStatics>
{
ITargetedContentSubscriptionStatics(std::nullptr_t = nullptr) noexcept {}
};
struct ITargetedContentValue :
Windows::Foundation::IInspectable,
impl::consume<ITargetedContentValue>
{
ITargetedContentValue(std::nullptr_t = nullptr) noexcept {}
};
}
}
|
#include "stdafx.h"
#include "misc.h"
#include "scan.h"
#include "LineFeatureSet.h"
#include "FeatureCreationParam.h"
#include "DebugTrace.h"
#include "assert.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
extern CFeatureCreationParam FeatureCreationParam;
///////////////////////////////////////////////////////////////////////////////
/*
** Calculates a line in the form (n1, n2) * (x, y) + c = 0,
** so that the leastsquare sum of the corresponding scan points
** is minimized.
** sp is an array of scan points, num specifies the number of scan points,
** n1, n2 and c are the result values.
*/
bool RegressionLine(const CScanPoint *sp, long num, CLineBase& ln);
/*
** Calculates variance of distance from a set of scan points
** given in (sp, num) to a line given in (n1, n2, c).
*/
float LineDeviation(CScanPoint *sp, long num, CLineBase& lb);
int MinPointsOnLine(float r, float fMinPointsOnLineRatio)
{
int n = (int)(fMinPointsOnLineRatio / r);
if (n < 20)
n = 20;
return n;
}
///////////////////////////////////////////////////////////////////////////////
// “CLineFeatureSet”类的实现。
//
// 构造函数。
//
CLineFeatureSet::CLineFeatureSet(int nNum)
{
Clear();
m_rect.Clear();
}
//
// “拷贝”构造函数。
//
CLineFeatureSet::CLineFeatureSet(const CLineFeatureSet& Obj, bool bFilterDisabled)
{
Clear();
for (int i = 0; i < (int)Obj.size(); i++)
{
// 根据需要,滤除那些被禁止的项
if (bFilterDisabled && !Obj.at(i)->IsEnabled())
continue;
CLineFeature* p = Obj.at(i)->Duplicate();
if (p == NULL)
assert(false);
else
push_back(p);
}
m_Param = Obj.m_Param; // 直线生成参数
m_pstScanner = Obj.m_pstScanner; // 激光头参考姿态
UpdateCoveringRect();
}
//
// 在析构函数中释放所有已分配的内存。
//
CLineFeatureSet::~CLineFeatureSet()
{
Clear();
}
//
// 重载“=”操作符。
//
void CLineFeatureSet::operator = (const CLineFeatureSet& Obj)
{
Clear();
m_rect = Obj.GetCoveringRect();
m_Param = Obj.m_Param; // 直线生成参数
m_pstScanner = Obj.m_pstScanner; // 激光头参考姿态
for (int i = 0; i < (int)Obj.size(); i++)
{
CLineFeature* p = Obj.at(i)->Duplicate();
if (p == NULL)
assert(false);
else
push_back(p);
}
}
//
// 根据直线特征类型分配空间。
//
CLineFeature* CLineFeatureSet::NewLineFeature(int nSubType)
{
switch (nSubType)
{
case GENERIC_LINE_FEATURE:
return new CLineFeature;
case SINGLE_SIDED_LINE_FEATURE:
// return new CSingleSidedLineFeature;
default:
return NULL;
}
}
//
// 设置直线性特征生成参数。
//
void CLineFeatureSet::SetCreationParam(CLineFeatureCreationParam* pParam)
{
if (pParam != NULL)
m_Param = *pParam;
}
//
// 根据所提供的扫描到的直线数组生成直线特征集合。
//
// 注意:所有直线数组均必须为本地测量到的直线数据(即观测姿态为(0, 0, 0))
//
bool CLineFeatureSet::CreateFromLocalLines(int nNum, CLineFeature* pLineData)
{
Clear();
// 直线数据必须提供
if (pLineData == NULL)
return false;
for (int i = 0; i < nNum; i++)
{
CLineFeature* p = pLineData[i].Duplicate();
if (p == NULL)
assert(false);
else
push_back(p);
}
// 设置直线特征的观测方向
SetDetectPosture(CPosture(0, 0, 0));
// 计算边界值
UpdateCoveringRect();
return true;
}
//
// 设置扫检测到这些直线特征时的激光头姿态,以便计算各条直线特征的观测方向。
//
void CLineFeatureSet::SetDetectPosture(const CPosture& pstDetect)
{
for (int i = 0; i < (int)size(); i++)
at(i)->SetDetectPosture(pstDetect);
}
//
// 从一个扫描集中抽取其有所有直线段。
//
bool CLineFeatureSet::CreateFromScan(const CScan& scan)
{
Clear();
const float fac = 5.0;
const float div = 1.0 / fac;
// 点云不能为空
if (scan.m_nCount == 0)
return false;
m_pstScanner = scan.m_poseScanner;
CScanPoint* sp = scan.m_pPoints;
sp[0].m_nLineID = -1;
long i, start = 0;
float last_dist = 0.0;
for (i = 1; i < scan.m_nCount; i++)
{
// 计算当前点到上一点之间的距离
float d = sp[i-1].DistanceTo(sp[i]);
// 距离至少取10mm
float dist = MAX(d, 0.01f);
float rel = last_dist / dist;
// 先假定该点所对应的直线不存在
sp[i].m_nLineID = -1;
// 当前点的极径
float r = sp[i].r;
// 直线段所含点的最小数量
int nMinPointsOnLine = MinPointsOnLine(r, m_Param.nMinPointsOnLine);
// 判断两点间距离是否过大
bool bPointsDistTooBig = (dist > m_Param.fMaxDistPointToPoint * r);
// 判断扫描点是否太不均匀(距离差距过大)
bool bPointsDistChangeTooMuch = (i > start + 1 && (rel > fac || rel < div));
// 如果点间距离太大,或者点间距离变化过块(不均匀)
if (bPointsDistTooBig || bPointsDistChangeTooMuch)
{
// 如果这一段里面点的数量够一个线段,尝试分裂出一条新线段
if (i - start >= m_Param.nMinPointsOnLine)
SplitPoints(sp, start, i - 1);
// 调整下一段的起始点位置
start = i;
}
// 计算近两个距离的均值
if (i <= start + 1)
last_dist = dist;
else
last_dist = (last_dist + dist) / 2;
}
// 直线段所含点的最小数量
float r = sp[i].r;
int nMinPointsOnLine = MinPointsOnLine(r, m_Param.nMinPointsOnLine);
// 如果从start到i点所含的点的数量够一个最小线段所需的数量,尝试分裂出一条直线
if (i - start >= nMinPointsOnLine)
SplitPoints(sp, start, i - 1);
// 合并共线的直线特征
LineScanMergeLines(&((CScan&)scan), NULL);
// 删除那些扫描角太小的直线特征
RemoveBadLines(m_pstScanner, scan);
for (i = 0; i < (int)size(); i++)
{
at(i)->m_nId = i+1;
at(i)->ComputeParam();
// 附加上范围
CRange range(0, at(i)->Length());
at(i)->m_Ranges.push_back(range);
}
// 设置直线特征的观测方向
SetDetectPosture(m_pstScanner);
// 计算边界值
UpdateCoveringRect();
return true;
}
//
// 删除那些扫描角不佳的直线特征。
//
void CLineFeatureSet::RemoveBadLines(const CPosture& pstScanner, const CScan& scan)
{
CPnt ptScanner = m_pstScanner;
for (int i = 0; i < (int)size(); i++)
{
CLineFeature* pLineFeature = at(i);
// 取直线特征的中点
CPnt ptMid = pLineFeature->GetMidpoint();
// 构造扫描线
CLine ln1(ptScanner, ptMid);
// 计算直线特征与扫描线之间的夹角
CAngle angDiff = ln1.AngleToUndirectionalLine(*pLineFeature);
float fAngDiff = angDiff.m_fRad;
if (angDiff > PI / 2)
fAngDiff = PI - fAngDiff;
// 如果这个夹角小于指定的门限值,则认为此直线特征不合格
bool bBad = fAngDiff < m_Param.fMinScanToLineAngle;
// 如果夹角合格,下面核对点间距离
if (!bBad)
{
float fDistLimit = (float)(m_Param.fMaxDistPointToPoint * ln1.Length() / sin(fAngDiff));
CScanPoint* sp = scan.m_pPoints;
for (long j = pLineFeature->m_lStart; j < pLineFeature->m_lEnd - 1; j++)
{
// 取得相邻的两个扫描点
CPnt pt1 = sp[j].GetPntObject();
CPnt pt2 = sp[j + 1].GetPntObject();
// 计算这两个点在直线特征上的投影点
CPnt ptFoot1, ptFoot2;
pLineFeature->DistanceToPoint(false, pt1, NULL, &ptFoot1);
pLineFeature->DistanceToPoint(false, pt2, NULL, &ptFoot2);
// 计算两个投影点之间的距离
float d = ptFoot1.DistanceTo(ptFoot2);
// 如果两个相邻扫描点之间的距离大于极限值,说明此直线特征不合格
if (d > fDistLimit)
{
bBad = true;
break;
}
}
}
// 删除不合格的直线特征
if (bBad)
{
delete at(i);
erase(begin() + i);
i--;
}
}
}
//
// 根据当前姿态、最大扫描半径和直线模型来生成直线特征集合。
//
bool CLineFeatureSet::CreateFromWorldLines(CPosture& pst, float fMaxRange, int nNumOfLines,
CLine* pLines)
{
Clear();
// 构造一个“范围圆”
CCircle RangeCircle(pst.GetPntObject(), fMaxRange);
// 用这个圆截取各条直线,得到的直线将被加入到直线特征集合中
int nResultCount = 0;
CLineFeature* pNewLine = new CLineFeature;
for (int i = 0; i < nNumOfLines; i++)
{
// 如果有剪切到长度大于300mm的线段
if (RangeCircle.CutLine(pLines[i], *pNewLine) && (pNewLine->Length() > 300)) // 0.3米,单位有误!!
{
push_back(pNewLine);
}
}
// 通过设置观测姿态来计算各直线特征的有效朝向
SetDetectPosture(pst);
// 更改特征数量(此举将导致存储空间中有多余未用的部分)
// m_nCount = nResultCount;
// 计算边界值
UpdateCoveringRect();
return true;
}
//
// 清除对象内的所有的直线。
//
void CLineFeatureSet::Clear()
{
for (int i = 0; i < (int)size(); i++)
delete at(i);
clear();
m_rect.Clear();
}
//
// 分配内存并复制当前对象内容,返回新复制的对象指针。
//
CLineFeatureSet* CLineFeatureSet::Duplicate()
{
// 为新副本的各直线段分配空间
CLineFeatureSet *copy = new CLineFeatureSet;
if (copy == NULL)
return NULL;
*copy = *this;
return copy;
}
//
// 将此另一个直线段集并入此直线段集中。
//
bool CLineFeatureSet::Merge(const CLineFeatureSet& LineScan)
{
for (int i = 0; i < (int)LineScan.size(); i++)
{
CLineFeature* p = LineScan.at(i)->Duplicate();
if (p == NULL)
return false;
else
{
push_back(p);
m_rect += *p;
}
}
return true;
}
//
// 增加一个直线特征。
// (目前此函数效率很低,需要频繁释放/分配内存,将来改进)
//
bool CLineFeatureSet::Add(const CLineFeature& LineFeature)
{
CLineFeature* p = LineFeature.Duplicate();
if (p == NULL)
return false;
else
{
push_back(p);
m_rect += *p;
}
return true;
}
//
// 通过合并共线的线段来简化此直线段集合。
//
// 说明:当两条无重叠区域但共线的线段之间的最小距离小于fMaxGapBetweenLines时,
// 可以将这两条线段进行合并(即认为断续区很小,可以忽略)。
//
bool CLineFeatureSet::Simplify(float fMaxGapBetweenLines)
{
bool bChange;
int i, j;
// 先生成一个线段集的附本,并为每个线段标明是否“启用”
CLineFeatureSet* pScan1 = Duplicate();
bool* pUse = new bool[size()];
do {
// 先标明所有项都应启用
for (i = 0; i < (int)pScan1->size(); i++)
pUse[i] = true;
// 再将pScan1复制一份(得到pScan2),作为比较之用
CLineFeatureSet* pScan2 = pScan1->Duplicate();
bChange = false;
// 尝试对所有的线段进行逐项合并
for (i = 0; i < (int)pScan1->size(); i++)
{
// 跳过那些已标明“不启用”的线段
if (!pUse[i])
continue;
for (j = i + 1; j < (int)pScan1->size(); j++)
{
// if (!pUse[j])
// continue;
// 如果合并成功,则标明第二个线段为“不启用”
if (pScan1->at(i)->ColinearMerge(*pScan1->at(j), m_Param.fMaxLineMergeAngle,
m_Param.fMaxLineMergeDist, fMaxGapBetweenLines))
{
pUse[j] = false;
bChange = true;
}
else if (pScan1->at(j)->ColinearMerge(*pScan1->at(i), m_Param.fMaxLineMergeAngle,
m_Param.fMaxLineMergeDist, fMaxGapBetweenLines))
{
pUse[i] = false;
bChange = true;
}
}
}
// 将带有“空洞”的数组进行“挤压”,使之成为紧凑排列的数组(即所有成员都是启用的)
for (int j = pScan1->size() - 1; j >= 0; j--)
{
if (!pUse[j])
{
delete pScan1->at(j);
pScan1->erase(pScan1->begin() + j);
}
}
delete pScan2; // 释放pScan2
} while (bChange); // 一直处理到不能再合并
Clear();
*this = *pScan1;
delete pScan1;
delete []pUse;
return true;
}
//
// 在集合中找到所有共线的特征,并进行分组记录。
// 返回值:最大的组号。
//
int CLineFeatureSet::FindColinearGroups(float fMaxAngDiff, float fMaxDistDiff)
{
// 先将所有分组标志置为-1
for (int i = 0; i < (int)size(); i++)
{
CLineFeature* pLine = at(i);
pLine->m_nId = -1;
}
// 下面对所有直线段按照共线情况进行分组
int nNextGroupId = 0;
for (int i = 0; i < (int)size(); i++)
{
// 取第一个直线特征
CLineFeature* pLine1 = at(i);
// 跳过已分组的特征
// if (Line1.m_nGroupId >= 0)
if (pLine1->m_nId >= 0)
continue;
else
pLine1->m_nId = nNextGroupId++;
//Line1.m_nGroupId = nNextGroupId++;
for (int j = i + 1; j < (int)size(); j++)
{
// 取第二个直线特征
CLineFeature* pLine2 = at(j);
// 跳过已分组的特征
// if (Line2.m_nGroupId >= 0)
if (pLine2->m_nId >= 0)
continue;
// 如果两个特征共线,标明为同一组
if (pLine1->IsColinearWith(*pLine2, fMaxAngDiff, fMaxDistDiff))
pLine2->m_nId = pLine1->m_nId;
// Line2.m_nGroupId = Line1.m_nGroupId;
}
}
return nNextGroupId;
}
//
// 针对共线的特征,通过多段线的描述方式进行合并。
//
bool CLineFeatureSet::ColinearSimplify(float fMaxAngDiff, float fMaxDistDiff)
{
// 先按照是否共线进行分组
int nMaxGroupId = FindColinearGroups(fMaxAngDiff, fMaxDistDiff);
// 以多段线的方式重新描述所有特征
CLineFeatureSet setNew;
for (int i = 0; i < nMaxGroupId; i++)
{
// 建立一个临时集合
CLineFeatureSet temp;
// 查找所有分组标识为i的特征,并将它们加入到临时集合中
for (int j = 0; j < (int)size(); j++)
{
CLineFeature* pLine = at(j);
// 找到所有属于第i组的特征
// if (Line.m_nGroupId == i)
if (pLine->m_nId == i)
temp.Add(*pLine);
}
// 对此临时集合进行优化处理
temp.ColinearRectify();
// 结果加入到新集合中
setNew.Merge(temp);
}
*this = setNew;
return true;
}
//
// 优化共线特征组。
//
CLineFeatureSet* CLineFeatureSet::Optimize()
{
CLineFeatureSet* pNew = Duplicate();
pNew->ColinearSimplify(CAngle::ToRadian(5), 0.08f);
return pNew;
}
//
// 对所有特征进行共线调理。
//
bool CLineFeatureSet::ColinearRectify()
{
if (size() < 2)
return true;
// 分配直线段数组空间
CLine* pLines = new CLine[size()];
for (int i = 0; i < (int)size(); i++)
pLines[i] = *at(i);
// 生成等价多段线
CMultiSegLine MultiLine;
MultiLine.Create(pLines, size());
// 生成唯一一个特征
CLineFeature Feature;
Feature.Create(MultiLine);
// Feature.m_nGroupId = at(0).m_nGroupId;
Feature.m_nId = at(0)->m_nId;
// 清除集合内容,再把这唯一一个特征加入集合中
Clear();
Add(Feature);
delete[]pLines;
return true;
}
//
// 删除指定的线段。
//
bool CLineFeatureSet::DeleteAt(int nIdx)
{
if (nIdx >= (int)size() - 1 || nIdx < 0)
return false;
delete at(nIdx);
erase(begin() + nIdx);
UpdateCoveringRect();
return true;
}
//
// 计算所有直线段的总长度。
//
float CLineFeatureSet::TotalLength()
{
float fSum = 0;
for (long i = 0; i < (int)size(); i++)
fSum += at(i)->m_fTotalLen;
return fSum;
}
//
// 计算点云中各点距离指定直线(n1*x + n2*y + c = 0)距离最远的距离。
//
// 说明:点(x0, y0)到直线(n1*x + n2*y + c = 0)距离公式为:
// d = abs(n1*x0 + n2*y0 + c)/sqrt(n1*n1 + n2*n2)
//
// 返回值:
// 返回: 距离最远点的序号
// pMaxDist: 指向最远距离值的指针
//
float FindMaxDist(const CScanPoint *sp, long num, CLineBase& ln, long* pMaxDistIdx)
{
if (pMaxDistIdx != NULL)
*pMaxDistIdx = 0;
float fMaxDist = 0;
for (long i = 0; i < num; i++)
{
// 计算点到直线的距离
float d = ln.DistanceToPoint(sp[i]);
// 始终保持最大距离值
if (d > fMaxDist)
{
fMaxDist = d; // 更新最远距离值
if (pMaxDistIdx != NULL)
*pMaxDistIdx = i; // 最远距离点所对应的序号
}
}
return fMaxDist;
}
//
// 分析一下是否可以找到一个距离线段的端点更近的“好”断点,这样可以针对平行的墙面提高直线提取效果。
// 注意:
// 点(x0, y0)到直线 n1*x +n2*y + c = 0 的距离公式为:
// d = abs(n1 * x0 + n2 * y0 + c)/sqrt(n1*n1 + n2*n2)
//
static long RefineBreakPoint(const CScanPoint *sp, long num, long brk, CLineBase& lb)
{
// 取得当前断点坐标
CPnt pt(sp[brk]);
// 计算该断点到直线的距离
float fMaxDist = lb.DistanceToPoint(pt);
// 计算“最短距离1”- 比上面的距离近15个点
float fMinD1 = fMaxDist - MAX_SIGMA / 2.0;
// 计算“最短距离2”- 为断点处距离的80%
float fMinD2 = fMaxDist * 0.8;
// 取上面两个距离的较大值
float fMinD = MAX(fMinD1, fMinD2);
long end = num - 1;
// 计算该断点到起点的距离
float fStartD = pt.DistanceTo(sp[0]);
// 计算该断点到终点的距离
float fEndD = pt.DistanceTo(sp[end]);
// 如果离起点较近
if (fStartD < fEndD)
{
// 看看从起点到该断点处有没有距离直线偏离大于要求的“最小距离”的点
for (long i = 1; i < brk; i++)
if (lb.DistanceToPoint(sp[i]) > fMinD)
return i;
}
// 如果离终点较近
else
{
// 看看从终点到该断点处有没有距离直线偏离更大的点
for (long i = end - 1; i > brk; i--)
if (lb.DistanceToPoint(sp[0]) > fMinD)
return i;
}
return brk;
}
//
// 判断扫描点的连线是否来回弯曲,不够平直。
//
static bool IsZigZag(const CScanPoint *sp, long num, long brk, CLineBase& lb)
{
static const float eps = 0.01;
long i;
long lNegCount = 0; // 负向距离点计数
long lPosCount = 0; // 正向距离点计数
// 先分析起点到断点之间的所有点
for (i = 0; i < brk; i++)
{
// 计算点到直线的距离
float val = lb.DistanceToPoint(sp[i]); //sp[i].x * n1 + sp[i].y * n2 + c;
// 计算那些距离直线偏离较大的点的数量(分正向偏离和负向偏离两种情况)
if (val < -eps)
lNegCount++;
else if (val > eps)
lPosCount++;
}
// 如正向偏离、负向偏离读数值中的一方比另一方的2倍还大,可认为是“弯弯曲曲”
if ((lNegCount >= 3 && lNegCount > 2 * lPosCount) || (lPosCount >= 3 && lPosCount > 2 * lNegCount))
return true;
// 重新计数
lNegCount = lPosCount = 0;
// 再分析断点到终点之间的所有点,原理同上
for (i = brk + 1; i < num; i++)
{
// 计算点到直线的距离
float val = lb.DistanceToPoint(sp[i]); //sp[i].x * n1 + sp[i].y * n2 + c;
// 计算那些距离直线偏离较大的点的数量(分正向偏离和负向偏离两种情况)
if (val < -eps)
lNegCount++;
else if (val > eps)
lPosCount++;
}
// 如正向偏离、负向偏离读数值中的一方比另一方的2倍还大,可认为是“弯弯曲曲”
if ((lNegCount >= 3 && lNegCount > 2 * lPosCount) || (lPosCount >= 3 && lPosCount > 2 * lNegCount))
return true;
return false;
}
//
// 对位于指定序号的扫描点中的直线进行优化,找到准确的起点和终点。
// 注意:如此找到的直线段其实有可能还需要进行再次分裂,进而提取出多个直线段。
//
// 返回值:
// true - 优化成功,得到了新的lStart, lEnd值
// false - 这个区间的扫描点提取不出有效的直线
//
bool RefineLineBetween(CScanPoint* sp, long& lStart, long& lEnd, float& sigma2, CLineFeatureCreationParam* pParam)
{
const float max_sigma2 = MAX_SIGMA * MAX_SIGMA;
const float thresh1 = max_sigma2 / 2.0; // 门限值1
long num_points = lEnd + 1 - lStart;
// 构造成当前直线
CPnt ptStart(sp[lStart]), ptEnd(sp[lEnd]);
CLine ln(ptStart, ptEnd);
// 现在需要确定所有这些点所处直线的标准参数(n1, n2, c)
if (!RegressionLine(sp + lStart, num_points, ln))
return false;
// 确定该直线的起始点(沿正方向顺序查找)
long i;
for (i = lStart; i < lEnd; i++)
{
float val = ln.DistanceToPoint(sp[i]);
val = val * val;
sigma2 += val;
if (val < thresh1)
break; // 该点已很靠近直线,找到起始点
}
long lNewStart = i; // 起始点序号
// 当前起始点的极径
float r = sp[lNewStart].r;
int nMinPointsOnLine = MinPointsOnLine(r, pParam->nMinPointsOnLine);
// 确定该直线的终止点(沿反方向逆序查找)
for (i = lEnd; i > lNewStart; i--)
{
float val = ln.DistanceToPoint(sp[i]);
val = val * val;
sigma2 += val;
if (val < thresh1)
break; // 该点已很靠近直线,找到终止点
}
long lNewEnd = i; // 终止点序号
// 如果所包含的点太少,则无法组成线段
if (lNewEnd + 1 - lNewStart < nMinPointsOnLine - 2)
return false;
return true;
}
//
// 将指定的扫描点分裂并抽取出直线段。
//
void CLineFeatureSet::SplitPoints(CScanPoint *sp, long lStart, long lEnd)
{
bool refine_break_point = true;
long num_points = lEnd + 1 - lStart;
// 构造成当前直线
CPnt ptStart(sp[lStart]), ptEnd(sp[lEnd]);
CLine ln(ptStart, ptEnd);
// 判断直线长度是否太短
if (ln.Length() < m_Param.fMinLineLength)
return; // 太短
// 从lStart点开始,计算出到直线(n1*x + n2*y + c = 0)最远点的序号,并求出该最远距离(存于fMaxDist中)
long lMaxDistIdx;
float fMaxDist = FindMaxDist(&sp[lStart], num_points, ln, &lMaxDistIdx);
long brk = lStart + lMaxDistIdx;
// 如果上面求得的最远距离大于最大允许距离,则直线需要分裂
bool bSplit = (fMaxDist > m_Param.fMaxDistPointToLine);
// 如果该直线不必分裂
if (!bSplit)
{
const float max_sigma2 = MAX_SIGMA * MAX_SIGMA;
const float thresh2 = max_sigma2 * 16.0; // 门限值2
long lNewStart = lStart, lNewEnd = lEnd;
float sigma2 = 0;
// 如果所包含的点太少,则无法组成线段,需要彻底分裂
if (!RefineLineBetween(sp, lNewStart, lNewEnd, sigma2, &m_Param))
bSplit = true;
else
{
// 试图在剩下的段中找到一个新的距离较远的断点
long newbrk = -1;
for (long i = lNewStart + 1; i < lNewEnd; i++)
{
float val = ln.DistanceToPoint(sp[i]);
val = val * val;
sigma2 += val;
if (val > thresh2 && newbrk < 0)
newbrk = i;
}
sigma2 /= num_points;
if (sigma2 > max_sigma2)
bSplit = true;
// 如果继续可分
else if (newbrk >= 0)
{
brk = newbrk;
refine_break_point = false;
bSplit = true;
}
// 否则,不可能再分了
else
{
// 增加一条线段
long new_num = lNewEnd + 1 - lNewStart;
if (num_points - new_num > 3)
RegressionLine(&sp[lNewStart], new_num, ln);
// 当前起始点的极径
float r = sp[lNewStart].r;
int nMinPointsOnLine = MinPointsOnLine(r, m_Param.nMinPointsOnLine);
// 如果位于lNewStart之前的点的数量也够一条线段,应对那些点也进行分裂
if (lNewStart + 1 - lStart >= nMinPointsOnLine)
SplitPoints(sp, lStart, lNewStart);
CPnt ptStart1(sp[lNewStart]), ptEnd1(sp[lNewEnd]);
CLine ln1(ptStart1, ptEnd1);
// 计算线段长度
float fDist = ln1.Length();
float fSigmaRatio = sqrt(sigma2) / fDist;
// 如果线段的长度超过“最小长度”,且平均距离误差小于指定门限,可确认找到一个有效线段
if (fDist >= m_Param.fMinLineLength && fSigmaRatio < MAX_SIGMA_RATIO)
{
// 将这些处于该直线上的点标记上直线的序号
for (long i = lNewStart; i <= lNewEnd; i++)
sp[i].m_nLineID = (int)size();
CLineFeature* pLine = new CLineFeature(ptStart1, ptEnd1);
pLine->m_lStart = lNewStart;
pLine->m_lEnd = lNewEnd;
pLine->m_fSigma2 = sigma2;
push_back(pLine);
}
// 如果位于lNewEnd之后的点的数量也够一条线段,应对那些点也进行分裂
if (lEnd + 1 - lNewEnd >= nMinPointsOnLine)
SplitPoints(sp, lNewEnd, lEnd);
}
}
}
// 如果需要进一步分裂
if (bSplit)
{
if (refine_break_point)
{
brk = lStart + RefineBreakPoint(&sp[lStart], lEnd + 1 - lStart, brk - lStart, ln);
}
// 当前极径
float r = sp[lStart].r;
int nMinPointsOnLine = MinPointsOnLine(r, m_Param.nMinPointsOnLine);
// 如果从起始点到断点处还有较多点,则这一段需要继续分裂
if (brk + 1 - lStart >= nMinPointsOnLine)
SplitPoints(sp, lStart, brk);
// 如果从断点到起始点处还有较多点,则这一段需要继续分裂
if (lEnd + 1 - brk >= nMinPointsOnLine)
SplitPoints(sp, brk, lEnd);
}
}
///////////////////////////////////////////////////////////////////////////////
#define LINE_MERGE_MAX_SIGMA2 (25.0 * 25.0)
#define LINE_MERGE_MAX_SIGMA2_FAC 2.0
#define MIN_COS_ALPHA cos(DEG2RAD(30.0))
//
// 对指定的点云段进行线性回归直线拟合。
// 说明:
// sp - 点云数组缓冲区指针
// num - 点的数量
//
bool RegressionLine(const CScanPoint *sp, long num, CLineBase& lb)
{
float xm = 0.0, ym = 0.0, xxm = 0.0, yym = 0.0, xym = 0.0;
float a, dx, dy;
long i;
if (num <= 1)
return false;
for (i = 0; i < num; i++)
{
float x = sp[i].x;
float y = sp[i].y;
xm += x;
ym += y;
xxm += x*x;
yym += y*y;
xym += x*y;
}
a = 0.5f * atan2((float)(-2.0*(xym - xm*ym / num)), (float)(yym - ym*ym / num - xxm + xm*xm / num));
float n1 = cos(a);
float n2 = sin(a);
dx = sp[num - 1].x - sp[0].x;
dy = sp[num - 1].y - sp[0].y;
if (dx * n2 - dy * n1 > 0.0)
{
n1 = -n1;
n2 = -n2;
}
float c = -(n1 * xm + n2 * ym) / num;
lb.DirectCreate(n1, n2, c);
return true;
}
float LineDeviation(CScanPoint *sp, long num, CLineBase& lb)
{
float sum = 0.0, sigma2;
long i;
for (i = 0; i < num; i++)
{
float val = lb.DistanceToPoint(sp[i]);
sum += val * val;
}
sigma2 = sum / (float)num;
return sigma2;
}
//
// 将那些共线且相连的线段合并。
//
void CLineFeatureSet::LineScanMergeLines(CScan *scan, long *lineNum)
{
static const float fac = 1.0;
long i, j;
if (scan == NULL)
return;
CScanPoint* tmp = (CScanPoint *)SSmalloc(scan->m_nCount * sizeof(scan->m_pPoints[0]));
if (tmp == NULL)
return;
CScanPoint* sp = scan->m_pPoints;
long totalLines = size(); //m_nCount;
bool change = true;
while (change)
{
change = false;
// 将所有的直线段两两对比,看是否共线且相连
for (i = 0; i < (int)size() - 1; i++)
for (j = i + 1; j < (int)size(); j++)
{
// 依次取得两条线段
CLineFeature *ln1 = at(i);
CLineFeature *ln2 = at(j);
// 计算两条直线的夹角?
float cosa = ln1->a * ln2->a + ln1->b * ln2->b;
float d1, d2, lambda1, lambda2;
long num1, num2, k, l, l1, l2;
float n1, n2, c;
float x1, y1, x2, y2;
float val, dist, appdist, sigma2, maxSigma2;
if (cosa < MIN_COS_ALPHA)
continue;
// 如果线段1的长度小于直线2,则将两条线段对换(结果是:线段1不短于线段2)
if (ln1->m_fTotalLen < ln2->m_fTotalLen)
{
CLineFeature *h = ln1;
ln1 = ln2;
ln2 = h;
}
d1 = ln1->DistanceToPoint(false, ln2->m_ptStart, &lambda1);
d2 = ln1->DistanceToPoint(false, ln2->m_ptEnd, &lambda2);
if (d1 > fac * m_Param.fMaxDistPointToLine)
continue;
if (d2 > fac * m_Param.fMaxDistPointToLine)
continue;
if ((lambda1 < 0.0 || lambda1 > 1.0) && (lambda2 < 0.0 || lambda2 > 1.0))
continue;
k = 0;
l1 = ln1->m_lStart;
l2 = ln2->m_lStart;
n1 = ln1->a;
n2 = ln1->b;
while (l1 <= ln1->m_lEnd && l2 <= ln2->m_lEnd)
{
float x1 = sp[l1].x * n2 - sp[l1].y * n1;
float x2 = sp[l2].x * n2 - sp[l2].y * n1;
if (x1 > x2)
tmp[k++] = sp[l1++];
else
tmp[k++] = sp[l2++];
}
while (l1 <= ln1->m_lEnd)
tmp[k++] = sp[l1++];
while (l2 <= ln2->m_lEnd)
tmp[k++] = sp[l2++];
CLineBase lb;
if (!RegressionLine(tmp, k, lb))
continue;
n1 = lb.a;
n2 = lb.b;
c = lb.c;
maxSigma2 = LINE_MERGE_MAX_SIGMA2_FAC * (ln1->m_fSigma2 + ln2->m_fSigma2);
maxSigma2 = MIN(maxSigma2, LINE_MERGE_MAX_SIGMA2);
if ((lambda1 >= 0.0 && 1.0 - lambda1 > lambda2 - 1.0) || (lambda2 <= 1.0 && lambda2 > -lambda1))
maxSigma2 *= 20.0;
else
{
// 计算扫描点序列tmp到直线lb最远的一点(在序号brk处)
long brk;
FindMaxDist(tmp, k, lb, &brk);
brk = RefineBreakPoint(tmp, k, brk, lb);
// 如果直线段是“歪歪扭扭”的
if (IsZigZag(tmp, k, brk, lb))
continue;
}
num1 = ln1->m_lEnd + 1 - ln1->m_lStart;
sigma2 = LineDeviation(&sp[ln1->m_lStart], num1, lb);
if (sigma2 > maxSigma2)
continue;
num2 = ln2->m_lEnd + 1 - ln2->m_lStart;
sigma2 = LineDeviation(&sp[ln2->m_lStart], num2, lb);
if (sigma2 > maxSigma2)
continue;
sigma2 = LineDeviation(tmp, k, lb);
if (sigma2 > maxSigma2)
continue;
// 将两条线段合并
if (ln1->m_lStart > ln2->m_lStart)
{
CLineFeature *h = ln1;
ln1 = ln2;
ln2 = h;
l = 0;
}
if (ln1->m_lEnd + 1 < ln2->m_lStart)
{
long num2 = ln2->m_lEnd + 1 - ln2->m_lStart;
long src = ln1->m_lEnd + 1;
long dst = src + num2;
long size0 = ln2->m_lStart - src;
memmove(&sp[dst], &sp[src], size0 * sizeof(*sp));
for (l = 0; l < (long)size(); l++)
{
CLineFeature *ln3 = at(l);
if (ln3->m_lStart >= ln1->m_lEnd && ln3->m_lEnd <= ln2->m_lStart)
{
if (ln3->m_lStart == ln1->m_lEnd)
ln3->m_lStart++;
if (ln3->m_lEnd == ln2->m_lStart)
ln3->m_lEnd--;
ln3->m_lStart += num2;
ln3->m_lEnd += num2;
}
}
ln2->m_lStart = src;
ln2->m_lEnd = src + num2 - 1;
}
x1 = tmp[0].x;
y1 = tmp[0].y;
x2 = tmp[k - 1].x;
y2 = tmp[k - 1].y;
val = c + n1 * x1 + n2 * y1;
x1 -= val * n1;
y1 -= val * n2;
val = c + n1 * x2 + n2 * y2;
x2 -= val * n1;
y2 -= val * n2;
dist = _hypot(x2 - x1, y2 - y1);
if (dist < 0.01f)
continue;
k = ln2->m_lEnd + 1 - ln1->m_lStart;
appdist = dist / (float)k;
ln1->m_lEnd = ln2->m_lEnd;
ln1->m_ptStart.x = x1;
ln1->m_ptStart.y = y1;
ln1->m_ptEnd.x = x2;
ln1->m_ptEnd.y = y2;
ln1->m_fTotalLen = dist;
ln1->a = n1;
ln1->b = n2;
ln1->c = c;
ln1->m_fSigma2 = sigma2;
if (ln1 != at(i))
*at(i) = *ln1;
memcpy(&sp[ln1->m_lStart], tmp, k * sizeof(*sp)); // 此处改变了原来的扫描点????
delete at(j);
erase(begin() + j);
change = true;
j--;
}
}
// 更新各点对应的直线段编号
for (long i = 0; i < (long)size(); i++)
{
CLineFeature *ln = at(i);
for (long j = ln->m_lStart; j <= ln->m_lEnd; j++)
{
long old = sp[j].m_nLineID;
if (lineNum != NULL && old >= 0 && old < totalLines)
lineNum[old] = i;
sp[j].m_nLineID = i;
}
}
SSfree(tmp);
}
///////////////////////////////////////////////////////////////////////////////
//
// 去掉所有长度短于minLineLength的直线。
//
void CLineFeatureSet::LengthFilter(float minLineLength)
{
for (int i = size() - 1; i >= 0; i--)
if (at(i)->m_fTotalLen < minLineLength)
{
delete at(i);
erase(begin() + i);
}
}
//
// 判断直线扫描集是否包含指定的点。
//
bool CLineFeatureSet::ContainScanPoint(const CScanPoint& sp)
{
for (int i = 0; i < (int)size(); i++)
{
if (at(i)->DistanceToPoint(true, sp) < 50)
return true;
}
return false;
}
//
// 移除位于指定区域内的线段。
//
void CLineFeatureSet::RemoveWithin(const CRectangle& r)
{
for (int j = size() - 1; j >= 0; j--)
{
if (r.Contain(*at(j)))
{
delete at(j);
erase(begin() + j);
}
}
}
//
// 将特征进行平移。
//
void CLineFeatureSet::Move(float fX, float fY)
{
for (int i = 0; i < (int)size(); i++)
at(i)->Move(fX, fY);
}
//
// 将特征进行旋转。
//
void CLineFeatureSet::Rotate(CAngle ang, CPnt ptCenter)
{
for (int i = 0; i < (int)size(); i++)
at(i)->Rotate(ang, ptCenter);
}
//
// 选中/取消选中指定的线段。
//
void CLineFeatureSet::Select(int nIdx, bool bOn)
{
if (nIdx < 0)
{
for (int i = 0; i < (int)size(); i++)
at(i)->Select(bOn);
}
else
at(nIdx)->Select(bOn);
}
//
// 从文本文件装入直线特征集合。
// 返回值:
// < 0 : 读取失败
// >= 0: 读取的特征数量
//
int CLineFeatureSet::LoadText(FILE* fp)
{
Clear();
// 先读入直线数量
int nCount;
if (fscanf(fp, "%d\n", &nCount) != 1 || nCount < 0)
return -1;
// 依次读入各直线特征
for (int i = 0; i < nCount; i++)
{
// 读入直线类型
int nSubType;
if (fscanf(fp, "%d\t", &nSubType) != 1)
return -1;
// 根据类型分配空间
CLineFeature* pFeature = NewLineFeature(nSubType);
if (pFeature == NULL)
return -1;
// 根据类型读入直线特征数据
if (pFeature->LoadText(fp) < 0)
return -1;
push_back(pFeature);
}
UpdateCoveringRect();
return true;
}
//
// 将直线特征集合存到文本文件。
//
int CLineFeatureSet::SaveText(FILE* fp)
{
// 先写直线数量
int nCount = (int)size();
fprintf(fp, "%d\n", nCount);
// 依次写入各直线特征
for (int i = 0; i < nCount; i++)
at(i)->SaveText(fp);
return nCount;
}
//
// 从二进制文件装入直线特征集合。
//
int CLineFeatureSet::LoadBinary(FILE* fp)
{
Clear();
// 先读入直线数量
int nCount;
if (fread(&nCount, sizeof(int), 1, fp) != 1 || nCount < 0)
return -1;
// 依次读入各直线特征
for (int i = 0; i < nCount; i++)
{
// 读入直线类型
int nSubType;
if (fread(&nSubType, sizeof(int), 1, fp) != 1)
return -1;
// 根据类型分配空间
CLineFeature* pFeature = NewLineFeature(nSubType);
if (pFeature == NULL)
return -1;
// 根据类型读入直线特征数据
if (!pFeature->LoadText(fp))
return -1;
push_back(pFeature);
}
UpdateCoveringRect();
return nCount;
}
//
// 将直线特征集合存到二进制文件。
//
int CLineFeatureSet::SaveBinary(FILE* fp)
{
// 先写直线数量
int nCount = (int)size();
if (!fwrite(&nCount, sizeof(int), 1, fp) != 1)
return -1;
// 依次写入各直线特征
for (int i = 0; i < nCount; i++)
if (at(i)->SaveBinary(fp) < 0)
return -1;
return nCount;
}
//
// 重新计算边界值。
//
void CLineFeatureSet::UpdateCoveringRect()
{
m_rect.Clear();
for (int i = 0; i < (int)size(); i++)
m_rect += *at(i);
}
//
// 根据直线特征集合生成角点集合。
//
int CLineFeatureSet::CreateCornerPoints(vector<CPointFeature>& ptCorners)
{
// 下面生成所有两两相交直线的交点集合,作为“角点特征”
ptCorners.clear();
for (int i = 0; i < (int)size() - 1; i++)
{
CLineFeature* pLine1 = at(i);
if (pLine1->Length() < MIN_LINE_LEN)
continue;
for (int j = i + 1; j < (int)size(); j++)
{
CLineFeature* pLine2 = at(j);
if (pLine2->Length() < MIN_LINE_LEN)
continue;
// 计算两条直线的差角
CAngle angDiff = pLine1->SlantAngle() - pLine2->SlantAngle();
if ((angDiff > MIN_CORNER_ANGLE && angDiff < (PI - MIN_CORNER_ANGLE)) ||
(angDiff >(PI + MIN_CORNER_ANGLE) && angDiff < (2 * PI - MIN_CORNER_ANGLE)))
{
float x, y;
bool bOnLine1 = false;
bool bOnLine2 = false;
// 计算两条直线段的交点,并判断交点是否在两条线段上
if (pLine1->Intersect(*pLine2, &x, &y, &bOnLine1, &bOnLine2))
{
CPointFeature pt;
pt.x = x;
pt.y = y;
pt.m_nType = 1; // 角点类型
pt.m_nParam[0] = pLine1->m_nId; // 直线1的ID号
pt.m_nParam[1] = pLine2->m_nId; // 直线2的ID号
#if 0
pt.m_fParam[0] = pLine1->SlantAngle().m_fRad; // 直线1的倾角
pt.m_fParam[1] = pLine2->SlantAngle().m_fRad; // 直线2的倾角
#endif
float fDist;
// 如果交点不在直线1上
if (!bOnLine1)
{
pLine1->FindNearPoint(pt, &fDist);
float fLen1 = pLine1->Length();
// 对于很短的直线特征,要求延长长度不能超过直线特征自身的长度
if (fLen1 < MIN_LINE_LEN * 3)
{
if (fDist > fLen1)
continue;
}
// 对于一般长度的直线特征,延长长度不能超过规定的固定长度(MAX_HIDDEN_LINE_LEN)
else if (fDist > MAX_HIDDEN_LINE_LEN)
continue;
}
// 如果交点不在直线2上
if (!bOnLine2)
{
pLine2->FindNearPoint(pt, &fDist);
float fLen2 = pLine2->Length();
// 对于很短的直线特征,要求延长长度不能超过直线特征自身的长度
if (fLen2 < MIN_LINE_LEN * 3)
{
if (fDist > fLen2)
continue;
}
// 对于一般长度的直线特征,延长长度不能超过规定的固定长度(MAX_HIDDEN_LINE_LEN)
else if (fDist > MAX_HIDDEN_LINE_LEN)
continue;
}
// 如果该点与先前加入的点太近,则不将它加入
if (/*!PointTooCloseToSomeCorner(pt, ptCorners)*/1)
ptCorners.push_back(pt);
}
}
}
}
return (int)ptCorners.size();
}
//
// 判断给定的点是否与某个角点距离过近。
//
bool CLineFeatureSet::PointTooCloseToSomeCorner(CPnt& pt, vector<CPnt>& ptCorners)
{
bool bTooClose = false;
for (vector<CPnt>::iterator iter = ptCorners.begin(); iter != ptCorners.end(); iter++)
{
CPnt& pti = iter->GetPntObject();
if (pt.DistanceTo(pti) < 200)
{
bTooClose = true;
break;
}
}
return bTooClose;
}
//
// 从二进制文件中装入用户编辑数据。
//
bool CLineFeatureSet::LoadUserData(FILE* fp)
{
int n;
for (int i = 0; i < (int)size(); i++)
{
if (fread(&n, sizeof(int), 1, fp) != 1)
return false;
// 数据为0时特征使能
at(i)->Enable(n == 0);
}
return true;
}
//
// 将用户编辑数据保存到二进制文件中。
//
bool CLineFeatureSet::SaveUserData(FILE* fp)
{
int n;
for (int i = 0; i < (int)size(); i++)
{
// 特征使能时置0
n = !(at(i)->IsEnabled());
if (fwrite(&n, sizeof(int), 1, fp) != 1)
return false;
}
return true;
}
//
// 从另外一个LineFeatureSet复制其用户使能设置。
//
bool CLineFeatureSet::CopyUserData(const CLineFeatureSet& another)
{
if (another.size() != size())
return false;
for (int i = 0; i < (int)size(); i++)
{
bool bEnabled = another.at(i)->IsEnabled();
at(i)->Enable(bEnabled);
}
return true;
}
//
// 将直线集合转换到局部坐标系中,转换后的原点姿态落到指定的姿态处。
//
void CLineFeatureSet::Transform(CPosture& pstLocal)
{
// 建立坐标变换
CTransform trans(pstLocal);
// 进行直线的坐标变换
for (int i = 0; i < (int)size(); i++)
{
// 先取得直线段的两个端点
CPnt pt1 = at(i)->m_ptStart;
CPnt pt2 = at(i)->m_ptEnd;
// 将两个端点依次变换到局部坐标系下
CPnt ptLocal1 = trans.GetLocalPoint(pt1);
CPnt ptLocal2 = trans.GetLocalPoint(pt2);
// 生成变换后的直线段
at(i)->Create(ptLocal1, ptLocal2);
}
// 调整边界值
UpdateCoveringRect();
}
//
// 将直线集合转换到世界坐标系中,转换后原来的原点姿态需要到达指定的姿态。
//
void CLineFeatureSet::InvTransform(CPosture& pstOrigin)
{
// 建立坐标变换
CTransform trans(pstOrigin);
// 进行直线的坐标变换
for (int i = 0; i < (int)size(); i++)
{
// 先取得直线段的两个端点
CPnt pt1 = at(i)->m_ptStart;
CPnt pt2 = at(i)->m_ptEnd;
// 将两个端点依次变换到世界坐标系下
CPnt ptWorld1 = trans.GetWorldPoint(pt1);
CPnt ptWorld2 = trans.GetWorldPoint(pt2);
vector<CRange> ranges = at(i)->m_Ranges;
// 生成变换后的直线段
at(i)->Create(ptWorld1, ptWorld2);
at(i)->m_Ranges = ranges;
}
// 调整边界值
UpdateCoveringRect();
}
//
// 以给定的点为中心,以指定的范围为半径,截取出一个特征子集。
//
bool CLineFeatureSet::GetSubset(CPnt& ptCenter, float fRange, CLineFeatureSet& Subset)
{
Subset.Clear();
// 依次判断所有直线特征是否应放入子集中
for (int i = 0; i < (int)size(); i++)
{
bool bSelect = false;
CLineFeature* pFeature = at(i);
float fDist1 = pFeature->m_ptStart.DistanceTo(ptCenter); // 直线起点到中心点的距离
float fDist2 = pFeature->m_ptEnd.DistanceTo(ptCenter); // 直线终点到中心点的距离
// 如果直线的两个端点中有一个位于圆内,选择它进子集
if (fDist1 < fRange || fDist2 < fRange)
bSelect = true;
else
{
float fLambda;
CPnt ptFoot;
// 计算直线到中心点的距离,并获得垂足点坐标
pFeature->DistanceToPoint(false, ptCenter, &fLambda, &ptFoot);
// 如果垂足点在线段以内,并且垂足点也在圆内,选择它进子集
if (fLambda >= 0 && fLambda <= 1 && ptFoot.DistanceTo(ptCenter) < fRange)
bSelect = true;
}
if (bSelect)
Subset.Add(*pFeature);
}
return true;
}
#define Q_MIN_LINE_LEN 0.3f
#define Q_MIN_INC_ANGLE TO_RADIAN(45) // 最小夹角45度
#define Q_MAX_INC_ANGLE TO_RADIAN(135) // 最大夹角135度
//
// 针对当前的直线特征集合,分离出“较好的直线特征集合”和“角点特征集合”。
//
bool CLineFeatureSet::SeperateFeatures(CLineFeatureSet& GoodLineFeatureSet, CPointFeatureSet& CornerFeatureSet)
{
GoodLineFeatureSet.Clear();
CornerFeatureSet.Clear();
for (int i = 0;i < (int)size(); i++)
{
CLineFeature* p = at(i);
// 如果该直线段够长,直接将其加入“合格直线特征集合”中
if (p->Length() > Q_MIN_LINE_LEN)
{
GoodLineFeatureSet.Add(*p);
continue;
}
// 如果是短直线
CPnt pt;
// 跟前一条直线进行比较,看是否能构成角点
if (i > 0)
{
CLineFeature* p1 = at(i - 1);
// 如果能构成角点,则添加此角点
if (p1->Length() > Q_MIN_LINE_LEN && p->MakeCorner(*p1, Q_MIN_INC_ANGLE, Q_MAX_INC_ANGLE, 0.03f, pt))
{
CPointFeature* pFeature = new CPointFeature;
pFeature->SetSubType(CORNER_FEATURE);
pFeature->SetCenterPoint(pt);
CornerFeatureSet += pFeature;
}
}
else if (i < (int)size() - 1)
{
CLineFeature* p1 = at(i + 1);
// 如果能构成角点,则添加此角点
if (p1->Length() > Q_MIN_LINE_LEN && p->MakeCorner(*p1, Q_MIN_INC_ANGLE, Q_MAX_INC_ANGLE, 0.03f, pt))
{
CPointFeature* pFeature = new CPointFeature;
pFeature->SetSubType(CORNER_FEATURE);
pFeature->SetCenterPoint(pt);
CornerFeatureSet += pFeature;
}
}
}
return true;
}
//
// 进行坐标正变换。
//
void CLineFeatureSet::Transform(const CFrame& frame)
{
for (int i = 0; i < (int)size(); i++)
at(i)->Transform(frame);
m_pstScanner.Transform(frame);
UpdateCoveringRect();
}
//
// 进行坐标逆变换。
//
void CLineFeatureSet::InvTransform(const CFrame& frame)
{
for (int i = 0; i < (int)size(); i++)
at(i)->InvTransform(frame);
m_pstScanner.InvTransform(frame);
UpdateCoveringRect();
}
#ifdef _MFC_VER
void CLineFeatureSet::Dump()
{
// TRACE("Dumping Line Scan (%d lines):\n", size());
for (int i = 0; i < (int)size(); i++)
{
DebugTrace(_T("Line #%d:\t%.2f\t%.2f\t\t%.2f\t%.2f\n"), i,
at(i)->m_ptStart.x, at(i)->m_ptStart.y,
at(i)->m_ptEnd.x, at(i)->m_ptEnd.y);
}
DebugTrace(_T("\n"));
}
//
// 绘制直线特征集合。
//
void CLineFeatureSet::Plot(CScreenReference& ScrnRef, CDC* pDC, COLORREF crColor, COLORREF crSelected,
int nPointSize, bool bShowActiveSide, bool bShowId, bool bShowRefPoint, int nShowDisabled)
{
for (int i = 0; i < (int)size(); i++)
{
at(i)->SetIntParam(0, (int)bShowActiveSide);
at(i)->SetIntParam(1, (int)bShowId);
at(i)->SetIntParam(2, (int)bShowRefPoint);
at(i)->Plot(ScrnRef, pDC, crColor, crSelected, nPointSize, nShowDisabled);
}
}
//
// 判断一个给定点是否触碰到某一条直线特征(用于屏幕上直线触碰判断)。
// 返回值:
// -1:给定点没有触碰到任何直线特征。
//
int CLineFeatureSet::PointHit(const CPnt& pt, float fDistGate)
{
// 逐个对所有直线特征进行判断
for (int i = 0; i < (int)size(); i++)
{
if (at(i)->PointHit(pt, fDistGate))
return i;
}
return -1;
}
#endif
|
/*
* =====================================================================================
*
* Filename: InsertionSort.hpp
*
* Description:
*
* Version: 1.0
* Created: 09/16/2013 03:33:55 PM
* Revision: none
* Compiler: gcc
*
* Author: Shuai YUAN (galoisplusplus), yszheda@gmail.com
* Organization:
*
* =====================================================================================
*/
#ifndef INSERTIONSORT_HPP
#define INSERTIONSORT_HPP
#include <vector>
#include <functional>
template <typename T>
void InsertionSort( std::vector<T>& elems );
template <typename T, typename Comparator>
void InsertionSort( std::vector<T>& elems, Comparator comp );
template <typename T, typename Comparator>
void InsertionSort( std::vector<T>& elems, Comparator comp )
{
int elem_num = elems.size();
T tmp;
for (int i = 1; i < elem_num; ++i)
{
tmp = elems[i];
int j;
for (j = i; j > 0 && comp(tmp, elems[j-1]) ; --j)
{
// shift if elems[j-1] > tmp
elems[j-1] = elems[j];
}
elems[j] = tmp;
}
}
template <typename T>
void InsertionSort( std::vector<T>& elems )
{
InsertionSort( elems, std::less<T>() );
}
#endif /* INSERTIONSORT_HPP */
|
#include <type_traits>
#include <functional>
#include <algorithm>
#include <memory>
#include <atomic>
#include <future>
#include <vector>
#include <deque>
#include <mutex>
#include "thread_pool.h"
namespace internal {
thread_local std::size_t ThreadPool::m_my_index;
thread_local ThreadPool::work_queue_type * ThreadPool::m_my_queue;
ThreadPool::ThreadPool() : m_done(false), m_num_tasks(0), m_thread_joiner(m_workers) {
std::size_t num_threads = std::max(std::thread::hardware_concurrency(), 3U);
--num_threads;
try {
// Create per thread queues prior to creating threads
for (std::size_t i = 0; i < num_threads; ++i) {
m_thread_queues.push_back(std::shared_ptr<work_queue_type>(new work_queue_type));
}
// Create working threads
m_workers.resize(num_threads);
for (std::size_t i = 0; i < num_threads; ++i) {
m_workers[i] = std::thread(&ThreadPool::do_work, this, i);
}
} catch (...) {
m_done = true;
throw;
}
}
ThreadPool::~ThreadPool() {
m_done = true;
}
bool ThreadPool::pop_task_from_my_queue(task_type & task) {
return m_my_queue && m_my_queue->try_pop(task);
}
bool ThreadPool::pop_task_from_main_queue(task_type & task) {
return m_main_queue.try_pop(task);
}
bool ThreadPool::pop_task_from_other_queue(task_type & task) {
for (std::size_t i = (m_my_index + 1) % m_thread_queues.size(); i != m_my_index; i = (i + 1) % m_thread_queues.size()) {
if (m_thread_queues[i]->try_steal(task)) {
return true;
}
}
return false;
}
bool ThreadPool::empty() const {
return m_num_tasks == 0;
}
bool ThreadPool::run_pending_tasks() {
task_type task;
if (pop_task_from_my_queue(task) || pop_task_from_main_queue(task) || pop_task_from_other_queue(task)) {
task();
--m_num_tasks;
return true;
}
return false;
}
void ThreadPool::do_work(std::size_t thread_index) {
m_my_index = thread_index;
m_my_queue = m_thread_queues[m_my_index].get();
while (!m_done) {
run_pending_tasks();
}
}
} // namespace internal
|
//All functionality and structs pertaining to explosion emitters go in this file
float4 OutputExplosionPosition(float3 position, float3 velocity, float3 acceleration, float age, float interval, float3 controlPoint)
{
float segments = 20;
float iteration = age / segments;
for(int i = 0; i < segments; i++)
{
position = position + velocity * iteration + interval * acceleration * pow(iteration, 2);
velocity = velocity + acceleration * iteration;
acceleration = acceleration * (position - controlPoint);
}
return float4(position, 1.0f);
}
|
/*
Title: ACM Brakelight Controller
Description: Main code for brakelight ACM
v 1.0
Last Revision Date: 06.04.2019
Created by Simon Nylund on 05.04.2019
Copyright © 2019 Align Racing UiA. All rights reserved.
*/
//Libraries
#include <Arduino.h>
#include <SPI.h>
#include <mcp2515.h>
#include "AllSettings.h"
MCP2515 mcp2515(7);
struct can_frame canMsg;
int breakpressurepercent = 0;
bool lightsON = false;
void setup() {
SPI.begin();
//Debug led setup
pinMode(rled, OUTPUT);
pinMode(gled, OUTPUT);
pinMode(bled, OUTPUT);
digitalWrite(rled, HIGH);
digitalWrite(gled, HIGH);
digitalWrite(bled, HIGH);
//CAN setup
mcp2515.reset();
mcp2515.setBitrate(CAN_1000KBPS);
mcp2515.setNormalMode();
//Brakelight setup
pinMode(breaklightout, OUTPUT);
digitalWrite(breaklightout, LOW);
}
void loop() {
if (mcp2515.readMessage(&canMsg) == MCP2515::ERROR_OK) {
if(canMsg.can_id = breakPressureCANID){ //Henter ut data fra riktig CAN melding
breakPressure1 = canMsg.data[0]; //Trykk i bremsekrets 1 (35 bar)
breakPressure2 = canMsg.data[1]; //Trykk i bremsekrets 2 (100 bar)
}
if (breakPressure1 > pressureThresholdOn || breakPressure2 > pressureThresholdOn ) { //Skrur på bremselyset hvis den går forbi bremsethreshold (Vedien 0-255)
lightsON = true;
}
else if (breakPressure1 < pressureThresholdOff || breakPressure2 < pressureThresholdOff ) { //Skrur på bremselyset hvis den går forbi bremsethreshold (Vedien 0-255)
lightsON = false;
}
if (lightsON){ //skru på
digitalWrite(rled, LOW); //Debug led blir rød
digitalWrite(breaklightout, HIGH); //Bremselyset lyser
}
else{ //skru av
digitalWrite(rled, HIGH); //Debug led blir rød
digitalWrite(breaklightout, LOW); //Bremselyset lyser
}
}
}
|
#include "graphics\Singularity.Graphics.h"
namespace Singularity
{
namespace Graphics
{
class IndexBuffer : public Singularity::Object
{
DECLARE_OBJECT_TYPE
private:
#pragma region Variables
unsigned m_iStart;
unsigned m_iLength;
void* m_pBuffer;
InternalIndexBuffer* m_pInternal;
#pragma endregion
public:
#pragma region Properties
unsigned Get_Length() { return this->m_iLength; }
#pragma endregion
#pragma region Constructors and Finalizers
IndexBuffer(unsigned length);
~IndexBuffer();
#pragma endregion
#pragma region Methods
void SetData(void* data);
void* GetData(bool force = false);
#pragma endregion
friend class Singularity::Graphics::Devices::DrawingContext;
friend class Singularity::Graphics::Devices::DeferredDrawingContext;
};
}
}
|
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
int key;
cin>>key;
int r=n-1,l=0;
int mid;
while(r>=l){
mid=(l+r)/2;
if(a[mid]==key){
cout<<mid;
return 0;
}
if(a[mid]>key)
r=mid-1;
else
l=mid+1;
}
}
|
#include "Circuit.h"
/*Constructor which takes sampleRate as an arguement and initialises the sampling period to 1./sampleRate */
Circuit::Circuit(double _sampleRate) :samplePeriod(1. / _sampleRate) {
//Set the sampleRate of the circuit to input _sampleRate
sampleRate = _sampleRate;
std::cout << "Circuit Created with SR: " << sampleRate << std::endl;
//Initialise Default circuit values
initialiseValues();
//Initialise controllable paramaters
setParams(FUZZ_DEFAULT, VOL_DEFAULT);
//Perform initial setup of the circuit
setupCircuit();
//initialise the zipper value smoothing coefficient
kCoeff = exp(-2.0 * PI * (ZIP_SMOOTH / sampleRate));
}
void Circuit::initialiseValues() {
//BJT Values
forwardGain = 70;
forwardGain2 = 103.52; //originally 110
reverseGain = 9.98; //originally 2.0
thermalVoltage = 25.8e-3;
saturationCurrent = 1.9767e-5; //originally 1e-14
//Potentiometer base resistances
volPotRes = 500e3;
fuzzPotRes = 1e3;
//Resistors Values
r1 = 33e3;
r2 = 8.2e3;
r3 = 470;
r4 = 2 * volPotRes;
r5 = 2 * volPotRes;
r6 = 100e3;
r7 = 2 * fuzzPotRes;
r8 = 2 * fuzzPotRes;
//Capacitors Values
c1 = 2.2e-6;
c2 = 20e-6;
c3 = 10e-9;
//Initialise the psi values
psi << 1 / forwardGain2, 1 / reverseGain, 0, 0,
1, -(reverseGain + 1) / reverseGain, 0, 0,
0, 0, 1 / forwardGain, 1 / reverseGain,
0, 0, 1, -(reverseGain + 1) / reverseGain;
//Initialise the phi values
phi << 1, 0, 0, 0,
1, -1, 0, 0,
0, 0, 1, 0,
0, 0, 1, -1;
}
/* Initial setup of default circuit values and parameters*/
void Circuit::setupCircuit() {
/* Setup */
//Populate circuit matrices
populateComponentMatrices();
//Initialise the incident matrices
initialiseIncidentMatrices();
//Populate the constant system matrix
populateConstantSystemMatrix();
//Populate the constant statespace terms
populateConstantStateSpaceTerms();
//Initialise the system matrices
refreshFullCircuit();
//initialise the zipper values
aStore22 = stateSpaceA(1, 1);
cStore13 = stateSpaceC(0, 2);
cStore23 = stateSpaceC(1, 2);
kStore33 = stateSpaceK(2, 2);
kStore34 = stateSpaceK(2, 3);
kStore44 = stateSpaceK(3, 3);
}
/* Initial setup of circuit matrices.
Set up the constant elements then refresh the variable elements*/
void Circuit::populateComponentMatrices() {
//prep the resistor values for input into the diagonal matrix
resMatrix << 1 / r1, 1 / r2, 1 / r3, 1 / r4, 1 / r5, 1 / r6, 1 / r7, 1 / r8;
//prep the capacitor values for input into diagonal matrix
capMatrix << c1, c2, c3;
capMatrix = (2 * capMatrix) / samplePeriod;
//Convert the matrices to diagonal matrices
diagResMatrix = resMatrix.asDiagonal();
diagCapMatrix = capMatrix.asDiagonal();
//Refresh the potentiometerMatrices
refreshPotentiometerMatrices();
}
/*One time setup of incident matrices, this is performed in the constructor and sets up the incident matrices*/
void Circuit::initialiseIncidentMatrices() {
//The incident matrix for the resistors
incidentResistors <<
0, 0, -1, 1, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -1, 1, 0, 0, 0, 0,
0, 0, 0, 1, 0, -1, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 1, -1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 1, 0, 0, 0, 0, -1, 0, 0, 0,
0, 0, 0, 0, 0, 0, 1, -1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0;
//The incident matrix for the potentiometers
incidentPot <<
0, 0, 0, 0, 0, 0, 0, 0, 1, -1,
0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
0, 0, 0, 0, 0, 0, 1, -1, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0;
//The incident matrix for the Capacitors
incidentCapacitors <<
1, -1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1, 0, 0,
0, 0, 0, 0, 0, 1, 0, 0, -1, 0;
//The incident matrix for Voltage
incidentVoltage <<
1, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, -1, 0, 0, 0, 0, 0, 0;
//The incident matrix for the nonlinearities
incidentNonlinearities <<
0, -1, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, -1, 0, 0, 0, 0, 0, 0, 0,
0, 0, -1, 0, 0, 0, 1, 0, 0, 0,
0, 0, 0, 0, -1, 0, 1, 0, 0, 0;
//The incident matrix for the output
incidentOutput <<
0, 0, 0, 0, 0, 0, 0, 0, 0, 1;
}
/* Refresh all variable matrices in the system when fuzz or vol changes*/
void Circuit::refreshFullCircuit() {
refreshPotentiometerMatrices();
refreshStateSpace();
refreshNonlinearFunctions();
}
/*Function to populate the circuit matrices*/
void Circuit::refreshPotentiometerMatrices() {
//Update the resistor values
volPotVar1 = (2 * (1 - vol)*volPotRes) / (2 - (1 - vol));
volPotVar2 = (2 * vol*volPotRes) / (2 - vol);
fuzzPotVar1 = (2 * (1 - fuzz)*fuzzPotRes) / (2 - (1 - fuzz));
fuzzPotVar2 = (2 * fuzz*fuzzPotRes) / (2 - fuzz);
//populate the potentiometer matrix
potMatrix << volPotVar1, volPotVar2, fuzzPotVar1, fuzzPotVar2;
//Diagonalise the matrix
diagPotMatrix = potMatrix.asDiagonal();
}
/* Function used to populate the constant elements of system matrix, call when fuzz or vol is changed, called by refresh() */
void Circuit::populateConstantSystemMatrix() {
//Update the matrix systemRes with the resistor element of the system Matrix
systemRes = (incidentResistors.transpose())*diagResMatrix*incidentResistors;
//Update the matrix systemCap with the capacitor element of the system Matrix
systemCap = (incidentCapacitors.transpose())*diagCapMatrix*incidentCapacitors;
//Construct system matrix
systemMatrix.block(0, 0, numNodes, numNodes) = systemRes + systemCap; //sets the first 10x10 top left matrix to be the sum of systemRes and systemCap matrices
systemMatrix.block(0, numNodes, numNodes, numInputs) = incidentVoltage.transpose(); //sets the 10x2 matrix starting at (0,10) equal to the transpose of incidentVoltage matrix
systemMatrix.block(numNodes, 0, numInputs, numNodes) = incidentVoltage; //sets the 2x10 matrix starting at (10,0) equal to the incidentVoltage matrix
systemMatrix.block(numNodes, numNodes, numInputs, numInputs).setZero(); //sets the last 2x2 matrix in the bottom right corner to 0
}
//Populate Constant StateSpace
//Function used to populate the constant elements of the state space matrices
void Circuit::populateConstantStateSpaceTerms() {
/* Padded matrices used in state space term calculations*/
//Padded Potentiometer Matrix
padPot.block(0, 0, numPot, numNodes) = incidentPot;
padPot.block(0, numNodes, numPot, numInputs).setZero();
//Padded Capacitor Matrix
padC.block(0, 0, numCap, numNodes) = incidentCapacitors;
padC.block(0, numNodes, numCap, numInputs).setZero();
//Padded NonLinearity Matrix
padNL.block(0, 0, numNonLin, numNodes) = incidentNonlinearities;
padNL.block(0, numNodes, numNonLin, numInputs).setZero();
//Padded output Matrix
padO.block(0, 0, numOutputs, numNodes) = incidentOutput;
padO.block(0, numNodes, numOutputs, numInputs).setZero();
//Padded identity matrix
padI.block(0, 0, numInputs, numNodes).setZero();
padI.block(0, numNodes, numInputs, numInputs).setIdentity();
/*Populate the constant terms*/
//Q = [N_V zeros(nv,nu)]*(S0\([N_V zeros(nv,nu)].'));
stateSpaceQ = padPot * systemMatrix.partialPivLu().solve(padPot.transpose());
//Ux = [N_X zeros(nx,nu)]*(S0\([N_V zeros(nv,nu)].'));
stateSpaceUx = padC * systemMatrix.partialPivLu().solve(padPot.transpose());
//Uo = [N_O zeros(1,nu)]*(S0\([N_V zeros(nv,nu)].'));
stateSpaceUo = padO * systemMatrix.partialPivLu().solve(padPot.transpose());
//Un = [N_N zeros(nn,nu)]*(S0\([N_V zeros(nv,nu)].'));
stateSpaceUn = padNL * systemMatrix.partialPivLu().solve(padPot.transpose());
//Uu = [zeros(nu,ns) eye(nu)]*(S0\([N_V zeros(nv,nu)].'));
stateSpaceUu = padI * systemMatrix.partialPivLu().solve(padPot.transpose());
//A0 = 2*G_X*[N_X zeros(nx,nu)]*(S0\[N_X zeros(nx, nu)].')- eye(nx);
stateSpaceA0 = 2 * diagCapMatrix*padC*systemMatrix.partialPivLu().solve(padC.transpose()) - Eigen::MatrixXd::Identity(numCap, numCap); //populate
//B0 = 2*G_X*[N_X zeros(nx,nu)]*(S0\[zeros(nu,ns) eye(nu)].');
stateSpaceB0 = 2 * diagCapMatrix*padC*systemMatrix.partialPivLu().solve(padI.transpose()); //populate
//C0 = 2*G_X*[N_X zeros(nx,nu)]*(S0\[N_N zeros(nn,nu)].');
stateSpaceC0 = 2 * diagCapMatrix*padC*systemMatrix.partialPivLu().solve(padNL.transpose()); //populate
//D0 = [N_O zeros(1,nu)]*(S0\[N_X zeros(nx,nu)].');
stateSpaceD0 = padO*systemMatrix.partialPivLu().solve(padC.transpose()); //populate
//E0 = [N_O zeros(1,nu)]*(S0\[zeros(2,10) eye(2)].');
stateSpaceE0 = padO*systemMatrix.partialPivLu().solve(padI.transpose()); //populate
//F0 = [N_O zeros(1,nu)]*(S0\[N_N zeros(nn,nu)].');
stateSpaceF0 = padO*systemMatrix.partialPivLu().solve(padNL.transpose()); //populate
//G0 = [N_N zeros(nn,nu)]*(S0\[N_X zeros(nx,nu)].');
stateSpaceG0 = padNL*systemMatrix.partialPivLu().solve(padC.transpose()); //populate
//H0 = [N_N zeros(nn,nu)]*(S0\[zeros(nu,ns) eye(nu)].');
stateSpaceH0 = padNL*systemMatrix.partialPivLu().solve(padI.transpose()); //populate
//K0 = [N_N zeros(nn,nu)]*(S0\[N_N zeros(nn,nu)].');
stateSpaceK0 = padNL*systemMatrix.partialPivLu().solve(padNL.transpose()); //populate
}
/* Function used to refrseh the final state space terms, combines the variable elements with the constant terms, called by refresh()*/
void Circuit::refreshStateSpace() {
/*Refresh the final statespace terms*/
//A = A0 - 2*G_X*Ux*((R_V+Q)\(Ux.'));
stateSpaceA = stateSpaceA0 - (2 * diagCapMatrix*stateSpaceUx*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUx.transpose())));
//B = B0 - 2*G_X*Ux*((R_V+Q)\(Uu.'));
stateSpaceB = stateSpaceB0 - (2 * diagCapMatrix*stateSpaceUx*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUu.transpose())));
//C = -(C0 - 2 * G_X*Ux*((R_V + Q)\(Un.')));
stateSpaceC = -(stateSpaceC0 - (2 * diagCapMatrix*stateSpaceUx*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUn.transpose()))));
//D = D0 - Uo*((R_V + Q)\(Ux.'));
stateSpaceD = stateSpaceD0 - stateSpaceUo*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUx.transpose()));
//E = E0 - Uo*((R_V+Q)\(Uu.'));
stateSpaceE = stateSpaceE0 - stateSpaceUo*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUu.transpose()));
//F = -(F0 - Uo*((R_V+Q)\(Un.')));
stateSpaceF = -(stateSpaceF0 - stateSpaceUo*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUn.transpose())));
//G = G0 - Un*((R_V+Q)\(Ux.'));
stateSpaceG = stateSpaceG0 - stateSpaceUn*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUx.transpose()));
//H = H0 - Un*((R_V+Q)\(Uu.'));
stateSpaceH = stateSpaceH0 - stateSpaceUn*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUu.transpose()));
//K = -(K0 - Un*((R_V+Q)\(Un.')));
stateSpaceK = -(stateSpaceK0 - stateSpaceUn*((diagPotMatrix + stateSpaceQ).partialPivLu().solve(stateSpaceUn.transpose())));
updateZipperTargets();
}
//Update the target values for the zipper matrices
void Circuit::updateZipperTargets() {
//Set the target values for the zipper causing elements
aTarget22 = stateSpaceA(1, 1);
cTarget13 = stateSpaceC(0, 2);
cTarget23 = stateSpaceC(1, 2);
kTarget33 = stateSpaceK(2, 2);
kTarget34 = stateSpaceK(2, 3);
kTarget44 = stateSpaceK(3, 3);
}
//Update the values of the zipper matrices with smoothed values every sample
void Circuit::updateZipperMatrices() {
aStore22 = aTarget22*(1. - kCoeff) + aStore22*kCoeff;
stateSpaceA(1, 1) = aStore22;
cStore13 = cTarget13*(1. - kCoeff) + cStore13*kCoeff;
stateSpaceC(0, 2) = cStore13;
cStore23 = cTarget23*(1. - kCoeff) + cStore23*kCoeff;
stateSpaceC(1, 2) = cStore23;
kStore33 = kTarget33*(1. - kCoeff) + kStore33*kCoeff;
stateSpaceK(2, 2) = kStore33;
kStore34 = kTarget34*(1. - kCoeff) + kStore34*kCoeff;
stateSpaceK(2, 3) = kStore34;
stateSpaceK(3, 2) = kStore34;
kStore44 = kTarget44*(1. - kCoeff) + kStore44*kCoeff;
stateSpaceK(3, 3) = kStore44;
//update the nonlinear functions with new K values
refreshNonlinearFunctions();
}
/* Function used to refresh the nonlinear function matrices, called by refresh() */
void Circuit::refreshNonlinearFunctions() {
//Input the Kd values
alteredStateSpaceK = -stateSpaceK*psi;
//Input the M values
nonLinEquationMatrix = alteredStateSpaceK.inverse()*phi.inverse();
}
/* Create a setter for the Fuzz parameter, when input is outside the allowable range 0 > fuzzVal > 1 */
void Circuit::setFuzz(double _fuzz) {
//Checks value is within allowable upper range, if the value is greater than 1-0.001 = 0.999 then default to 0.999
if (_fuzz > CTRL_MAX - CTRL_INCREMENT)
{
//Defaults value to MAX - INCREMENT and prints a message
std::cout << "Fuzz greater than range, defaulted to " << CTRL_MAX - CTRL_INCREMENT << std::endl;
fuzz = CTRL_MAX - CTRL_INCREMENT;
}
//Checks value is within allowable lower range, if the valuse is less than 0.0 + 0.001 = 0.001 then default to 0.001
else if (_fuzz < CTRL_MIN + CTRL_INCREMENT)
{
//Defaults value to Min and prints a message
std::cout << "Fuzz less than range, defaulted to " << CTRL_MIN + CTRL_INCREMENT << std::endl;
fuzz = CTRL_MIN + CTRL_INCREMENT;
}
else
{
//0 <_fuzz < 1 set fuzz to the arguement
fuzz = _fuzz;
}
}
/* Returns the current value for the fuzz setting */
double Circuit::getFuzz()
{
return fuzz;
}
/* Create a setter for the Vol parameter, when input is outside the allowable range 0 > volVal > 1, default to 0.4 */
void Circuit::setVol(double _vol) {
//Checks value is within allowable upper range, if the value is greater than 1-0.001 = 0.999 then default to 0.999
if (_vol > CTRL_MAX - CTRL_INCREMENT)
{
//Defaults value to MAX - INCREMENT and prints a message
std::cout << "Vol greater than range, defaulted to " << CTRL_MAX - CTRL_INCREMENT << std::endl;
vol = CTRL_MAX - CTRL_INCREMENT;
}
//Checks value is within allowable lower range, if the valuse is less than 0.0 + 0.001 = 0.001 then default to 0.001
else if (_vol < CTRL_MIN + CTRL_INCREMENT)
{
//Defaults value to Min + Increment and prints a message
std::cout << "Vol less than range, defaulted to " << CTRL_MIN + CTRL_INCREMENT << std::endl;
vol = CTRL_MIN + CTRL_INCREMENT;
}
else
{
//0 <_vol < 1 set fuzz to the arguement
vol = _vol;
}
}
/* Returns the current value for the vol setting*/
double Circuit::getVol()
{
return vol;
}
//Method to set the fuzz and vol params to the arguement vals and then refresh the system.
void Circuit::setParams(double _fuzzVal, double _volVal) {
setFuzz(_fuzzVal);
setVol(_volVal);
refreshPotentiometerMatrices();
refreshStateSpace();
//refreshNonlinearFunctions();
}
/* Returns the circuit saturation current IS */
double Circuit::getSaturationCurrent()
{
return saturationCurrent;
}
/* Returns the circuit thermal voltage VT*/
double Circuit::getThermalVoltage()
{
return thermalVoltage;
}
/*Sets samplerate to new samplerate and refreshes the circuit matrices*/
void Circuit::setCircuitSampleRate(double _sampleRate)
{
sampleRate = _sampleRate;
samplePeriod = 1. / sampleRate;
setupCircuit();
}
double Circuit::getCircuitSampleRate() {
return sampleRate;
}
/*Default Destructor */
Circuit::~Circuit() {
//Cleanup
std::cout << "Circuit Destroyed" << std::endl;
}
|
#ifndef __TARGET_H__
#define __TARGET_H__
class Target
{
public:
virtual int twoTime(int number) = 0;
virtual int halfTime(int number) = 0;
};
#endif // __TARGET_H__
|
#include<iostream>
#include<string>
using namespace std;
// string的构造函数
// string 是c++风格的字符串,而本质上是一个类
// 内部封装了很多成员方法:查找find,拷贝copy,删除delete等
// //string的构造函数
// 1.string(); //创建一个空的字符串
// 2.string(const char *s); //使用字符串s初始化
// 3.string(const string& str); //使用一个string对象初始化一个string对象
// 4.string(int n,char c); //使用n个字符c初始化
void test01()
{
string s1 = "hellow world";//默认构造
cout<<"s1: "<<s1<<endl;
const char * str = "hellow world";
string s2(str);
cout<<"s2: "<<s2<<endl;
string s3(s2);
cout<<"s3: "<<s3<<endl;
string s4(10,'a');
cout<<"s4: "<<s4<<endl;
}
int main()
{
test01();
return 0;
}
|
#include "frmserver.h"
#include "ui_frmserver.h"
frmServer::frmServer(QWidget *parent)
: QDialog(parent),
ui(new Ui::frmServer)
{
ui->setupUi(this);
this->setWindowTitle(ui->lab_Title->text());
this->InitForm();
server = new TCPTransmitServer(this);
server->startServer(8888);
//如果与客户端成功连接,会触发QTcpServer::newConnection()信号
//connect(server, &QTcpServer::newConnection, this, &frmMain::acceptConnection);
connect(server, &TCPTransmitServer::connectedSignal, this, &frmServer::clientConnected);
connect(server, &TCPTransmitServer::receiveFinishedSignal, this, &frmServer::transmitFinshed);
connect(server, &TCPTransmitServer::receiveMessageSignal, this, &frmServer::updateTransmitStatus);
connect(server, &TCPTransmitServer::receiveFileNameSignal, this, &frmServer::updateReceiveFileName);
connect(server, &TCPTransmitServer::receiveFileSizeSignal, this, &frmServer::setTransmitProgress);
connect(server, &TCPTransmitServer::receiveDataSignal, this, &frmServer::updateTransmitProgress);
connect(server, &TCPTransmitServer::sendFileSizeSignal, this, &frmServer::setTransmitProgress);
connect(server, &TCPTransmitServer::bytesWrittenSignal, this, &frmServer::updateTransmitProgress);
connect(server, &TCPTransmitServer::sendMessageSignal, this, &frmServer::updateTransmitStatus);
connect(server, &TCPTransmitServer::sendFinishedSignal, this, &frmServer::transmitFinshed);
connect(ui->btnExit, &QPushButton::clicked, this, &frmServer::close);
}
frmServer::~frmServer()
{
delete ui;
server->deleteLater();
}
void frmServer::InitForm()
{
transmitBytes = 0;
transmitBlockNumber = 0;
transmitMaxBytes = 0;
ui->txtSendFile->setText(tr("请选择文件"));
ui->txtReceiveFile->setText(tr("等待接收文件"));
ui->txtTransmitStatus->setText((tr("等待连接")));
ui->txtTransmitStatus_1->setText((tr("尚未连接")));
ui->pbTransmitProgress->setRange(0, 100);
ui->pbTransmitProgress->setValue(0);
ui->btnSelect->setEnabled(false);
ui->btnSend->setEnabled(false);
}
void frmServer::clientConnected(QString ip, quint16 port)
{
updateConnectStatus(ip, port);
ui->pbTransmitProgress->setValue(0);
ui->btnSelect->setEnabled(true);
}
void frmServer::on_btnSelect_clicked()
{
QString filePath = QFileDialog::getOpenFileName(this, tr("选择文件"), QCoreApplication::applicationDirPath(), tr("所有文件 (*.*)"));
file.setFileName(filePath);
ui->txtSendFile->setText(file.fileName());
ui->pbTransmitProgress->setRange(0, 100);
ui->pbTransmitProgress->setValue(0);
ui->btnSend->setEnabled(true);
}
void frmServer::on_btnSend_clicked()
{
transmitBytes = 0;
transmitBlockNumber = 0;
transmitMaxBytes = 0;
server->SendFile(file.fileName());
}
void frmServer::updateTransmitProgress(qint64 size)
{
transmitBlockNumber++;
transmitBytes += size;
ui->pbTransmitProgress->setValue(transmitBytes);
QString msg = tr("已传输数据包:%1个 当前数据包大小:%2字节 已传输字节:%3 总共字节:%4")
.arg(transmitBlockNumber)
.arg(size)
.arg(transmitBytes)
.arg(transmitMaxBytes);
ui->txtTransmitStatus->setText(msg);
qApp->processEvents(); //及时刷新界面
}
void frmServer::updateTransmitStatus(QString msg)
{
qDebug() << tr("服务器端Server:") << msg;
ui->txtTransmitStatus_1->setText(msg);
}
void frmServer::setTransmitProgress(qint64 size)
{
transmitBytes = 0;
transmitBlockNumber = 0;
transmitMaxBytes = size;
ui->pbTransmitProgress->setRange(0, size - 1);
ui->pbTransmitProgress->setValue(0);
}
void frmServer::transmitFinshed()
{
ui->pbTransmitProgress->setRange(0, 100);
ui->pbTransmitProgress->setValue(100);
ui->txtTransmitStatus_1->setText(tr("文件传输完成"));
}
void frmServer::updateReceiveFileName(QString name)
{
ui->pbTransmitProgress->setRange(0, 100);
ui->pbTransmitProgress->setValue(100);
ui->txtReceiveFile->setText(name);
}
void frmServer::updateConnectStatus(QString ip, quint16 port)
{
ui->txtTransmitStatus->setText(QString(tr("与客户端[%1:%2]成功连接")).arg(ip).arg(port));
}
|
/****************************************
*
* INSERT-PROJECT-NAME-HERE - INSERT-GENERIC-NAME-HERE
* Copyright (C) 2019 Victor Tran
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* *************************************/
#include "focuspointer.h"
#include <QApplication>
#include <QPointer>
#include <QPainter>
#include <QTimer>
#include <QAbstractItemView>
#include <the-libs_global.h>
#include <tvariantanimation.h>
#include "focusbarrier.h"
#include "musicengine.h"
struct FocusPointerPrivate {
FocusPointer* instance = nullptr;
QPointer<QWidget> activeWidget;
QList<QPointer<QWidget>> filteredWidgets;
bool automatic = false;
bool enabled = false;
tVariantAnimation* colourPulse;
void ensureInstance() {
if (instance == nullptr) instance = new FocusPointer();
}
};
FocusPointerPrivate* FocusPointer::d = new FocusPointerPrivate();
void FocusPointer::enableFocusPointer()
{
d->ensureInstance();
d->enabled = true;
}
void FocusPointer::disableFocusPointer()
{
d->ensureInstance();
d->instance->hide();
d->enabled = false;
}
void FocusPointer::enableAutomaticFocusPointer()
{
d->ensureInstance();
d->automatic = true;
}
void FocusPointer::disableAutomaticFocusPointer()
{
d->ensureInstance();
d->automatic = false;
}
bool FocusPointer::isEnabled()
{
return d->enabled;
}
FocusPointer::FocusPointer() : QWidget(nullptr)
{
this->setAttribute(Qt::WA_TransparentForMouseEvents);
connect(static_cast<QApplication*>(QApplication::instance()), &QApplication::focusChanged, this, [=](QWidget* old, QWidget* now) {
if (!d->activeWidget.isNull()) {
disconnect(d->activeWidget, nullptr, this, nullptr);
d->activeWidget->removeEventFilter(this);
for (QPointer<QWidget> w : d->filteredWidgets) {
if (!w.isNull()) {
disconnect(w, nullptr, this, nullptr);
w->removeEventFilter(this);
}
}
}
d->activeWidget = now;
if (d->activeWidget.isNull()) {
d->instance->hide();
} else {
this->setFocusProxy(d->activeWidget);
d->activeWidget->installEventFilter(this);
QWidget* parent = d->activeWidget->parentWidget();
while (parent != nullptr) {
parent->installEventFilter(this);
d->filteredWidgets.append(QPointer<QWidget>(parent));
parent = parent->parentWidget();
}
QAbstractItemView* listView = qobject_cast<QAbstractItemView*>(d->activeWidget);
if (listView) {
connect(listView->selectionModel(), &QItemSelectionModel::selectionChanged, this, [=] {
MusicEngine::playSoundEffect(MusicEngine::FocusChanged);
QTimer::singleShot(0, this, &FocusPointer::updateFocusedWidget);
});
}
if (d->enabled) {
if (qobject_cast<FocusBarrier*>(d->activeWidget) == nullptr && qobject_cast<FocusBarrier*>(old) == nullptr) {
MusicEngine::playSoundEffect(MusicEngine::FocusChanged);
}
}
this->updateFocusedWidget();
}
});
QApplication::instance()->installEventFilter(this);
this->resize(SC_DPI_T(QSize(32, 32), QSize));
// QColor mainCol = QApplication::palette().color(QPalette::Highlight);
d->colourPulse = new tVariantAnimation();
d->colourPulse->setForceAnimation(true);
d->colourPulse->setStartValue(QColor(0, 100, 255));
d->colourPulse->setEndValue(QColor(0, 200, 255));
// d->colourPulse->setStartValue(mainCol.darker());
// d->colourPulse->setEndValue(mainCol.lighter());
d->colourPulse->setDuration(500);
connect(d->colourPulse, &tVariantAnimation::valueChanged, this, [=] {
this->update();
});
connect(d->colourPulse, &tVariantAnimation::finished, this, [=] {
if (d->colourPulse->direction() == tVariantAnimation::Forward) {
d->colourPulse->setDirection(tVariantAnimation::Backward);
} else {
d->colourPulse->setDirection(tVariantAnimation::Forward);
}
d->colourPulse->start();
});
d->colourPulse->start();
this->hide();
}
void FocusPointer::updateFocusedWidget()
{
if (d->activeWidget.isNull() || d->activeWidget->window() == nullptr) {
this->setParent(nullptr);
d->instance->hide();
} else {
QWidget* parentWindow = d->activeWidget->window();
if (d->enabled) d->instance->show();
this->setParent(parentWindow);
QRect geometry;
QAbstractItemView* listView = qobject_cast<QAbstractItemView*>(d->activeWidget);
if (listView) {
QModelIndex index = listView->currentIndex();
if (index.isValid()) {
geometry = listView->visualRect(index);
geometry.moveTopLeft(listView->viewport()->mapTo(parentWindow, geometry.topLeft()));
geometry.adjust(SC_DPI(-5), SC_DPI(-5), SC_DPI(5), SC_DPI(5));
}
}
if (geometry.isNull()) {
geometry.setSize(d->activeWidget->size() + SC_DPI_T(QSize(10, 10), QSize));
geometry.moveTopLeft(d->activeWidget->mapTo(parentWindow, SC_DPI_T(QPoint(-5, -5), QPoint)));
}
this->setGeometry(geometry);
this->raise();
}
}
void FocusPointer::paintEvent(QPaintEvent*event)
{
QPainter painter(this);
// painter.setBrush(QColor(0, 0, 0, 127));
// painter.setPen(Qt::transparent);
// painter.setBrush(Qt::transparent);
// painter.setPen(QPen(QColor(255, 255, 255), SC_DPI(5), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
// painter.setPen(QPen(QColor(0, 150, 255), SC_DPI(10), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
// painter.drawRect(5, 5, this->width() + 10, this->height() + 10);
painter.setBrush(d->colourPulse->currentValue().value<QColor>());
painter.setPen(Qt::transparent);
painter.drawRect(0, 0, this->width(), SC_DPI(5));
painter.drawRect(0, 0, SC_DPI(5), this->height());
painter.drawRect(0, this->height() - SC_DPI(5), this->width(), SC_DPI(5));
painter.drawRect(this->width() - SC_DPI(5), 0, SC_DPI(5), this->height());
// QPolygon pol;
// pol.append(QPoint(0, 0));
// pol.append(QPoint(this->width(), this->height() / 2));
// pol.append(QPoint(this->width() / 2, this->height() / 2));
// pol.append(QPoint(this->width() / 2, this->height()));
// pol.append(QPoint(0, 0));
// painter.setPen(Qt::black);
// painter.setBrush(Qt::white);
// painter.drawPolygon(pol);
}
bool FocusPointer::eventFilter(QObject*watched, QEvent*event)
{
if (d->automatic) {
if (event->type() == QEvent::MouseMove) {
this->disableFocusPointer();
} else if (event->type() == QEvent::KeyPress) {
this->enableFocusPointer();
}
}
if (event->type() == QEvent::Resize || event->type() == QEvent::Move) {
if (watched == d->activeWidget) {
updateFocusedWidget();
}
if (event->type() == QEvent::Move && d->filteredWidgets.contains(QPointer<QWidget>(qobject_cast<QWidget*>(watched)))) {
updateFocusedWidget();
}
}
return false;
}
|
/* Copyright 2017-2018 All Rights Reserved.
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* [Contact]
* Gyeonghwan Hong (redcarrottt@gmail.com)
*
* Licensed under the Apache License, Version 2.0(the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "SwitchTestRunner.h"
#include "../common/inc/ChildProcess.h"
#include "../configs/PathConfig.h"
using namespace sc;
#include <string>
#include <thread>
int main(int argc, char **argv) {
/* Parse arguments */
if (argc != 3 && argc != 4) {
printf("[Usage] %s <user-side throughput (B/s)> <# iterations>\n", argv[0]);
return -1;
}
int throughput = atoi(argv[1]);
int iterations = atoi(argv[2]);
SwitchTestRunner *test_runner;
if(throughput <= 0) {
printf("Invalid throughput!: %d\n", throughput);
return -1;
} else if(iterations <= 0) {
printf("Invalid # iterations!: %d\n", iterations);
return -1;
}
test_runner = SwitchTestRunner::test_runner(throughput, iterations);
if (test_runner == NULL) {
return -2;
}
test_runner->start();
return 0;
}
|
#include "RectangleT4.h"
RectangleT4::RectangleT4(float L, float r, float u, float d) :Quad(L, r, u, d) {}
float RectangleT4::Area()
{
float a;
a = GetLeft() * GetRight();
return a;
}
float RectangleT4::Perimeter()
{
float p;
p = GetLeft() + GetRight();
p *= 2;
return p;
}
RectangleT4::~RectangleT4() {}
|
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 1, ans = 0, num = 0; //a存储输入数据,ans为最终得分,num为连跳方块中心次数
while (cin >> a && a != 0) //数据输入还没完成且a!=0
if (a == 1) { //如果a==1
ans += a; //加上1分
num = 0; //连跳方块中心次数归零
} else if (a == 2) //a==2
ans += 2 * (++num); //递增连跳方块中心次数,得分为该次数乘2
cout << ans;
return 0;
}
|
#include <stdio.h>
int main(){
int t;
scanf("%d", &t);
int num[t];
for (int i = 0; i < t; i++){
scanf("%d", &num[i]);
getchar();
}
for(int i = 0; i < t; i++){
printf("Case #%d: ", i + 1);
if (num[i] % 11 == 0 && num[i] % 7 != 0){
printf("Eleven\n");
}
if (num[i] % 7 == 0 && num[i] % 11 != 0){
printf("Seven\n");
}
if (num[i] % 7 == 0 && num[i] % 11 == 0){
printf("ElevenSeven\n");
}
if (num[i] % 7 != 0 && num[i] % 11 != 0){
printf("%d\n", num[i]);
}
}
return 0;
}
|
class CfgUnitInsignia {
#include "script_component.hpp"
// // Alpha first platoon
// //MACRO_UNITINSIGNIA(Alpha Co. 1st platoon,Alpha_1);
// //MACRO_UNITINSIGNIA(Alpha Co. 1st platoon - Alpha Squad,Alpha_1_A);
// //MACRO_UNITINSIGNIA(Alpha Co. 1st platoon - Bravo Squad,Alpha_1_B);
// MACRO_UNITINSIGNIA(Alpha Co. 1st platoon - Charlie Squad,Alpha_1_C);
// //MACRO_UNITINSIGNIA(Alpha Co. 1st platoon - Delta Squad,Alpha_1_D);
// // Alpha second platoon
// MACRO_UNITINSIGNIA(Alpha Co. 2nd platoon,Alpha_2);
// MACRO_UNITINSIGNIA(Alpha Co. 2nd platoon - Alpha Squad,Alpha_2_A);
// MACRO_UNITINSIGNIA(Alpha Co. 2nd platoon - Bravo Squad,Alpha_2_B);
// MACRO_UNITINSIGNIA(Alpha Co. 2nd platoon - Charlie Squad,Alpha_2_C);
// //MACRO_UNITINSIGNIA(Alpha Co. 2nd platoon - Delta Squad,Alpha_2_D);
// // Bravo first platoon
// //MACRO_UNITINSIGNIA(Bravo Co. 1st platoon,Bravo_1);
// //MACRO_UNITINSIGNIA(Bravo Co. 1st platoon - Alpha Squad,Bravo_1_A);
// //MACRO_UNITINSIGNIA(Bravo Co. 1st platoon - Bravo Squad,Bravo_1_B);
// //MACRO_UNITINSIGNIA(Bravo Co. 1st platoon - Charlie Squad,Bravo_1_C);
// //MACRO_UNITINSIGNIA(Bravo Co. 1st platoon - Delta Squad,Bravo_1_D);
// // Bravo second platoon
// MACRO_UNITINSIGNIA(Bravo Co. 2nd platoon,Bravo_2);
// MACRO_UNITINSIGNIA(Bravo Co. 2nd platoon - 1st Squad,Bravo_2_1);
// //MACRO_UNITINSIGNIA(Bravo Co. 2nd platoon - 2nd Squad,Bravo_2_2);
// //MACRO_UNITINSIGNIA(Bravo Co. 2nd platoon - 3rd Squad,Bravo_2_3);
// //MACRO_UNITINSIGNIA(Bravo Co. 2nd platoon - 4th Squad,Bravo_2_4);
// // Charlie first platoon
// MACRO_UNITINSIGNIA(Charlie Co. 1st platoon,Charlie_1);
// MACRO_UNITINSIGNIA(Charlie Co. 1st platoon - 1st Squad,Charlie_1_1);
// MACRO_UNITINSIGNIA(Charlie Co. 1st platoon - 2nd Squad,Charlie_1_2);
// MACRO_UNITINSIGNIA(Charlie Co. 1st platoon - 3rd Squad,Charlie_1_3);
// MACRO_UNITINSIGNIA(Charlie Co. 1st platoon - 4th Squad,Charlie_1_4);
// // Charlie second platoon
// MACRO_UNITINSIGNIA(Charlie Co. 2nd platoon,Charlie_2);
// MACRO_UNITINSIGNIA(Charlie Co. 2nd platoon - 1st Squad,Charlie_2_1);
// //MACRO_UNITINSIGNIA(Charlie Co. 2nd platoon - 2nd Squad,Charlie_2_2);
// //MACRO_UNITINSIGNIA(Charlie Co. 2nd platoon - 3rd Squad,Charlie_2_3);
// //MACRO_UNITINSIGNIA(Charlie Co. 2nd platoon - 4th Squad,Charlie_2_4);
// // Other Insignias
// MACRO_UNITINSIGNIA(Yellow and Black,Custom_Cav_7);
// MACRO_UNITINSIGNIA(Yellow and Black (M81),Custom_Cav_7_m81);
// MACRO_UNITINSIGNIA(Yellow and Black (OCP),Custom_Cav_7_ocp);
// // Specialized
// MACRO_UNITINSIGNIA(CAG,Specialized_Airborne);
// MACRO_UNITINSIGNIA(CLS,Specialized_CLS);
// MACRO_UNITINSIGNIA(RANGER,Specialized_Ranger);
// MACRO_UNITINSIGNIA(Follow Me,Specialized_FollowMe);
};
|
//Copyright 2015-2016 Tomas Mikalauskas. All rights reserved.
#include <stdafx.h>
#include <TywLib\math\GLXMath.h>
#include <TywLib\geometry\VertData.h>
#include <TywLib\geometry\JointTransform.h>
//Renderer Includes
#include "OpenGL\BufferObject.h"
#include "OpenGL\Texture2D.h"
#include "ThirdParty\FreeType\FreetypeLoad.h"
#include "Font.h"
/*
=======================================
Font::Font
=======================================
*/
Font::Font():vao(0), vbo(0), data(nullptr), buffer(nullptr) {
try {
data = TYW_NEW GlyphData();
buffer = TYW_NEW VertexBuffer();
}
catch (...) {
//Engine::getInstance().Sys_Printf("ERROR: Font::Font(): could not allocate data for VBuffer and GlyphData \n");
}
}
/*
=======================================
Font::CreateFont
=======================================
*/
void Font::CreateFontGL(const char* strTypeface, int point_size, int dpi) {
if (!data->LoadGlyph(strTypeface, point_size, dpi)) {
//Engine::getInstance().Sys_Printf("%s \n", data->getLog().c_str());
return;
}
buffer->AllocateBufferObject(nullptr, sizeof(drawVert)*6, enumBuffer::DYNAMIC_DRAW);
}
/*
=======================================
Font::InitializeChars
=======================================
*/
void Font::InitializeChars(char* source) {
if (!data->InitiliazeChars(source)) {
//Engine::getInstance().Sys_Error("%s \n", data->getLog().c_str());
//Engine::getInstance().Sys_DebugPrintf("ERROR: Font::InitializeChars: returned false \n");
}
size_t size = strlen(source);
for (int i = 0; i < size; i++) {
Data temp = data->getChar(source[i]);
if (temp.bitmap_buffer != nullptr && temp.c == source[i]) {
Texture2D texture;
texture.GenerateTexture(temp.bitmap_buffer, temp.bitmap_width, temp.bitmap_rows, texFormat::GLX_RED);
glyphs.insert(std::unordered_map<char, GLuint>::value_type(source[i], texture.getId()));
}
else {
//Engine::getInstance().Sys_Error("ERROR: Could not find char %c\n", source[i]);
}
}
//I do not need anymore glyph buffer data, so I delete it
data->ReleaseBuffer();
}
/*
=======================================
Font::DisplayText()
=======================================
*/
void Font::DisplayText(float x, float y, float ws, float hs, const char* text)
{
buffer->EnableVAO();
buffer->EnableVBO();
size_t size = strlen(text);
for (int i = 0; i < size; i++) {
if (text[i] == ' ') {
x += 32*ws;
continue;
}
Data currentGlyph = data->getChar(text[i]);
#ifndef TYW_DEBUG
if (currentGlyph.c != text[i]) {
//Engine::getInstance().Sys_Error("ERROR: Could not find char %c \n", text[i]);
return;
}
#endif
float vx = x + currentGlyph.bitmap_left * ws;
float vy = y + currentGlyph.bitmap_top * hs;
float w = currentGlyph.bitmap_width * ws;
float h = currentGlyph.bitmap_rows * hs;
drawVert data[6] =
{
{ glx::vec3<float>(vx,vy, 1), glx::vec3<float>(0,0,0), glx::vec2<float>(0,0) },
{ glx::vec3<float>(vx,vy-h, 1), glx::vec3<float>(0,0,0), glx::vec2<float>(0,1) },
{ glx::vec3<float>(vx+w,vy, 1), glx::vec3<float>(0,0,0), glx::vec2<float>(1,0) },
{ glx::vec3<float>(vx+w,vy, 1), glx::vec3<float>(0,0,0), glx::vec2<float>(1,0) },
{ glx::vec3<float>(vx,vy-h, 1), glx::vec3<float>(0,0,0), glx::vec2<float>(0,1) },
{ glx::vec3<float>(vx+w,vy-h,1), glx::vec3<float>(0,0,0), glx::vec2<float>(1,1) }
};
glBindTexture(GL_TEXTURE_2D, glyphs.at(text[i])); //Bind texture
buffer->Update(data, sizeof(drawVert)*6);
glDrawArrays(GL_TRIANGLES, 0, 6);
// increment position /
x += (currentGlyph.advance.x >> 6) * ws;
y += (currentGlyph.advance.y >> 6) * hs;
}
buffer->DisableVAO();
}
/*
=======================================
Font::Release()
=======================================
*/
bool Font::Release() {
if (!data->Release()) {
//Engine::getInstance().Sys_DebugPrintf("ERROR: Font::Release: Glyph data could not be released\n");
return false;
}
glyphs.clear();
SAFE_DELETE(data);
SAFE_DELETE(buffer);
return true;
}
/*
=============================
~Font
=============================
*/
Font::~Font() {
//Release();
}
|
/*
Copyright (c) 2005-2023, University of Oxford.
All rights reserved.
University of Oxford means the Chancellor, Masters and Scholars of the
University of Oxford, having an administrative office at Wellington
Square, Oxford OX1 2JD, UK.
This file is part of Chaste.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the University of Oxford nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ABSTRACTOUTPUTMODIFIER_HPP_
#define ABSTRACTOUTPUTMODIFIER_HPP_
#include "ChasteSerialization.hpp"
#include <boost/serialization/string.hpp>
#include "ClassIsAbstract.hpp"
#include <string>
#include "AbstractTetrahedralMesh.hpp"
/**
* A plug-in class for on-the-fly output. This is designed so that a user can insert something in
* order to monitor the progress of a simulation or to produce "post processed" output during the simulation.
*/
class AbstractOutputModifier
{
private:
/** For testing */
friend class TestMonodomainProblem;
/** Needed for serialization. */
friend class boost::serialization::access;
/**
* Archive this modifier. Just calls the base class version.
*
* @param archive the archive
* @param version the current version of this class
*/
template<class Archive>
void serialize(Archive & archive, const unsigned int version)
{
archive & mFilename;
archive & mFlushTime;
}
protected:
/** Constructor that does nothing, for archiving */
AbstractOutputModifier()
: mFilename(), mFlushTime(0.0)
{}
std::string mFilename; /**<The file which is eventually produced by this modifier*/
/** Simulation time period between flushes to disk */
double mFlushTime;
public:
/**
* Standard construction method contains only the name of the file which this simulation modifier should produce.
*
* Note that construction occurs before the Solve() loop and probably before initialisation. This means that it
* will not be possible to view certain data (e.g the mesh) at the time of construction
*
* Note the problem passes parameters in a non-templated fashion in order to keep the interface as lightweight as
* possible.
* @param rFilename The file which is eventually produced by this modifier
* @param flushTime The (simulation) time between flushing the file to disk. Default (0) means don't flush.
*
*/
AbstractOutputModifier(const std::string& rFilename, double flushTime=0.0)
: mFilename(rFilename),
mFlushTime(flushTime)
{}
/**
* Destructor should be overridden when necessary
*/
virtual ~AbstractOutputModifier()
{
}
/**
* Initialise the modifier (open a file or make some memory) when the solve loop is starting
*
* Note the problem passes parameters in a non-templated fashion in order to keep the interface as lightweight as
* possible. That is, it might have been slicker to pass in the mesh but that would require multiple templates.
* @param pVectorFactory The vector factory which is associated with the calling problem's mesh
* @param rNodePermutation The permutation associated with the calling problem's mesh (when running with parallel partitioning)
*/
virtual void InitialiseAtStart(DistributedVectorFactory* pVectorFactory, const std::vector<unsigned>& rNodePermutation)=0;
/**
* Finalise the modifier (close a file or dump the calculation to disk)
*/
virtual void FinaliseAtEnd()=0;
/**
* Process a solution time-step (dump a small line to file or compute the latest activation times)
* @param time The current simulation time
* @param solution A working copy of the solution at the current time-step. This is the PETSc vector which is distributed across the processes.
* @param problemDim The calling problem dimension. Used here to avoid probing the size of the solution vector
*/
virtual void ProcessSolutionAtTimeStep(double time, Vec solution, unsigned problemDim)=0;
};
CLASS_IS_ABSTRACT(AbstractOutputModifier)
#endif /* ABSTRACTOUTPUTMODIFIER_HPP_ */
|
/*************************************************************************
> File Name: observable.cpp
> Author: Jason
> Mail: jie-email@jie-trancender.org
> Created Time: 2017年03月27日 星期一 20时42分54秒
************************************************************************/
#include <iostream>
using namespace std;
class Observable
{
public:
void register(weak_ptr<Observer> x);
void notifyObservers();
private:
mutable std::mutex mutex_;
std::vector<std::weak_ptr<Observer>> observers_;
typedef std::vector<std::weak_ptr<Observer>>::iterator Iterator;
};
void Observable::notifyObservers()
{
std::lock_guard<std::mutex> lock(mutex_);
Iterator it = observers_begin();
while (it != observers_.end())
{
std::shared_ptr<Observer> obj(it->lock());
if (obj)
{
obj->update();
++it;
}
else
{
it = observers_.erase(it);
}
}
}
int main(int argc, char* argv[])
{
}
|
#ifndef TINYENGINE_LTE_IFONT_H_
#define TINYENGINE_LTE_IFONT_H_
#pragma once
#include <string>
#include "../LTE_Types.h"
#include "../LTE_Utils.h"
template <class T>
class LTE_IFont {
public:
LTE_IFont() {}
LTE_IFont(const LTE_IFont&) = delete;
LTE_IFont(const std::string& path, int ptsize) { LTE_Unused(path, ptsize); }
virtual ~LTE_IFont() {}
virtual void Load(const std::string& path, int ptsize) = 0;
virtual void Draw(const char *text, int x, int y, uint8_t r, uint8_t g, uint8_t b, uint8_t a) const = 0;
virtual void SetStyle(const LTE_FontStyle& style) = 0;
virtual T GetNative() const = 0;
};
#endif
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.