blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
b6fca1d6a4d9d5f222f8d1188724115b04a987df
8a0e989d4b64a9ea50da0048465e28435d3cc68d
/476A.cpp
34b41b9b4780b757bf82e8d5e81c47b4246c9bf2
[]
no_license
VinuB-Dev/codeforce-solutions
8c89ebacf2963a3bfa0e9e6259e759880cc5b8c3
c676fa631655286da2de91d825114fb0800cdf7f
refs/heads/master
2023-06-26T22:10:22.751475
2020-10-06T01:32:06
2020-10-06T01:32:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
275
cpp
#include <iostream> using namespace std; int main(int argc, char const *argv[]) { int n,m,a; cin>>n>>m; if(m>n) { cout<<-1; return 0; } if(n%2==0) a=n/2; else a=n/2+1; while(a%m!=0) { a++; } cout<<a; return 0; }
[ "noreply@github.com" ]
noreply@github.com
9add55ee2203eaa50c1169e3c229d5a7a55cd208
49b979e617619251a4d8df4c92ded34dde460aeb
/tmp/fastIO.cpp
faf40a4ebeea9eb5825d0edcda439f286ab02b3a
[]
no_license
boook64/codebook
ad340438cec5983afc18bb8cfad787075d3c88dd
cb25cfd7ca0ec426e872b80fd426f38515c0b124
refs/heads/master
2023-01-09T23:39:38.840631
2020-11-05T16:28:29
2020-11-05T16:28:29
310,356,223
0
0
null
null
null
null
UTF-8
C++
false
false
792
cpp
/* no negative number */ inline int rit(){ int f=0; char c; do{ c=getchar(); }while(c<'0' || c>'9'); do{ f=f*10+c-'0'; c=getchar(); }while(c>='0' && c<='9'); return f; } inline void out(int x) { if (x > 9) { out(x / 10); } putchar(x % 10 + '0'); } /* with negative number */ inline int rit(){ int f=0,key=1; char c; do{ c=getchar(); if(c=='-') key=-1; }while(c<'0' || c>'9'); do{ f=f*10+c-'0'; c=getchar(); }while(c>='0' && c<='9'); return f*key; } inline void out2(int x) { if (x > 9) { out2(x / 10); } putchar(x % 10 + '0'); } inline void out(int x) { if (x < 0) { putchar('-'); out2(-x); } else { out2(x); } }
[ "boook64@gmail.com" ]
boook64@gmail.com
979f350185bc04d4bd510d98cac2fdfee2913cd0
6b0ca4ece69cb52c30228395d8201137028605eb
/cpp/1001-10000/1681-1690/Delivering Boxes from Storage to Ports.cpp
a540380d9022e31922d64fc951afc7211e140c01
[ "MIT" ]
permissive
gzc/leetcode
d8245071199e1b6321856ba0ddbdef5acfb5b2ac
1a604df1e86c9775b8db364bfb3a5462ed96e9d0
refs/heads/master
2022-02-04T00:12:19.448204
2022-01-30T03:08:14
2022-01-30T03:08:14
32,258,529
178
68
MIT
2021-03-28T16:50:18
2015-03-15T12:04:59
C++
UTF-8
C++
false
false
1,076
cpp
class Solution { public: int boxDelivering(vector<vector<int>>& boxes, int portsCount, int maxBoxes, int maxWeight) { int n = boxes.size(); vector<int> dp(n+1, INT_MAX); dp[0] = 0; int weight = 0; int trips = 2; int left = 0; for (int right = 0; right < n; right++) { weight += boxes[right][1]; // If current box is different than previous one, need to make one more trip. if (right > 0 && boxes[right][0] != boxes[right-1][0]) { trips++; } while ((right - left) >= maxBoxes || weight > maxWeight || (left < right && dp[left] == dp[left+1])) { weight -= boxes[left][1]; if (boxes[left][0] != boxes[left+1][0]) { trips--; } left++; } dp[right+1] = dp[left] + trips; } return dp.back(); } };
[ "noreply@github.com" ]
noreply@github.com
4b18b4242919d51abaccaddc3c3e9ba4536bef20
084a35363e65931de8b3772c91753bf449c88c19
/ICP PROJECT/Source.cpp
9fbf08bcad3b237f6dffdbb74ea1d14c8d4f29c2
[]
no_license
Muhammad-Kamran967/Car-Management-
e2257df299e97447a392d88f742be98ecf7f3c90
3937c10c3cb45c4617b74604cb6c86b405ac779c
refs/heads/master
2022-11-29T00:15:28.514754
2020-07-07T16:54:36
2020-07-07T16:54:36
277,873,485
0
0
null
null
null
null
UTF-8
C++
false
false
3,119
cpp
#include<iostream> #include<string> using namespace std; struct car { string make; string model; string color; string speed; string direction; }; void printcurrentcar(car z) { cout << "colour:______" << z.color; cout << endl << "make:_______" << z.make; cout << endl << "Direction:_______" << z.direction; cout << endl << "model:_______" << z.model; cout << endl << "speed:_______" << z.speed; cout << endl << "_______\n"; } unsigned int Getcolour(void) { int colour; cout << "Enter a color(1 to 4)" << endl; cin >> colour; switch (colour) { case 1: cout << "Red\n"; break; case 2: cout << "Blue\n"; break; case 3: cout << "White\n"; break; case 4: cout << "Black\n"; break; default: cout << "invalid\n"; return false; } return true; } void Setcolou(unsigned int val = 1) { int m_colour; if ((val > 4) || (val < 1)) { cout << "Error assigning colours use num 1-4 only\n"; } else { m_colour = val; } } unsigned int Getmake(void) { int make; cout << "Enter a make number(1to4)" << endl; cin >> make; switch (make) { case 1: cout << "Ford\n"; break; case 2: cout << "Honda civic\n"; break; case 3: cout << "Toyta\n"; break; case 4: cout << "Pontiac\n"; break; default: cout << "invalid\n"; return false; } return true; } void Setmake(unsigned int val = 1) { unsigned int make; if ((val > 4) || (val < 1)) { cout << "Error assigning make use num 1-4 only\n"; } else { make = val; } } unsigned int Getmodel(void) { unsigned int model; cout << "Enter a model from (1 to 4)" << endl; cin >> model; switch (model) { case 1: cout << "Range rover\n"; break; case 2: cout << "land crouser\n"; break; case 3: cout << "Car\n"; break; case 4: cout << "Super bike\n"; break; default: cout << "invalid\n"; return false; } return true; } void Setmodel(unsigned int val = 1) { unsigned int model; if ((val > 4) || (val < 1)) { cout << "Error assigning model use num 1-4 only\n"; } else { model = val; } } unsigned int Getspeed(void) { unsigned int speed; cout << "Enter a speed" << endl; cin >> speed; cout << speed << "km/h" << endl; return true; } void Setspeed(unsigned int val = 1) { unsigned int speed; if (val > 200) { cout << "to fast(max speed:200km/h)\n"; } else { speed = val; } } unsigned int GetDirection(void) { unsigned int direction; cout << "Enter a Direction(1 to 4)" << endl; cin >> direction; switch (direction) { case 1: cout << "North\n"; break; case 2: cout << "East\n"; break; case 3: cout << "South\n"; break; case 4: cout << "West\n"; break; default: cout << "invalid\n"; return false; } return true; } void Setdirection(unsigned int val = 1) { unsigned int direction; direction = val; } void ChangeDirection(unsigned int val = 1) { int tempDirection = val; if (tempDirection > 4) { tempDirection -= 4; } else if (tempDirection < 1) { tempDirection += 4; } } int main() { car k; printcurrentcar(k); Getcolour(); Getmake(); Getmodel(); Getspeed(); GetDirection(); system("Pause"); return 0; }
[ "60073088+Xamran@users.noreply.github.com" ]
60073088+Xamran@users.noreply.github.com
ee4be8ca3abf8fae0521eeac8df3ad5fb13057cb
f3501d59eaf1846e18e35883084d0d91dfc5edaa
/Elektronik/Arduino/Archiv/EUW/sketch_sep01a/sketch_sep01a.ino
bf890a488b445496e226cfe22def4b4687122a4e
[]
no_license
0Kraft/EuW
49658ab2aac242eec728893d8ac826143a8e62da
498cfc301bdfdba6d9513a310f3cf63a82e1c26d
refs/heads/master
2021-09-21T16:33:31.353628
2018-08-28T16:14:51
2018-08-28T16:14:51
104,867,388
0
0
null
null
null
null
UTF-8
C++
false
false
1,466
ino
int inA1 = 2; // input 1 of the stepper int inA2 = 4; // input 2 of the stepper int inB1 = 6; // input 3 of the stepper int inB2 = 7; // input 4 of the stepper int stepDelay = 5; // Delay between steps in milliseconds void setup() { pinMode(inA1, OUTPUT); pinMode(inA2, OUTPUT); pinMode(inB1, OUTPUT); pinMode(inB2, OUTPUT); } void step1() { digitalWrite(inA1, LOW); digitalWrite(inA2, HIGH); digitalWrite(inB1, HIGH); digitalWrite(inB2, LOW); delay(stepDelay); } void step2() { digitalWrite(inA1, LOW); digitalWrite(inA2, HIGH); digitalWrite(inB1, LOW); digitalWrite(inB2, HIGH); delay(stepDelay); } void step3() { digitalWrite(inA1, HIGH); digitalWrite(inA2, LOW); digitalWrite(inB1, LOW); digitalWrite(inB2, HIGH); delay(stepDelay); } void step4() { digitalWrite(inA1, HIGH); digitalWrite(inA2, LOW); digitalWrite(inB1, HIGH); digitalWrite(inB2, LOW); delay(stepDelay); } void stopMotor() { digitalWrite(inA1, LOW); digitalWrite(inA2, LOW); digitalWrite(inB1, LOW); digitalWrite(inB2, LOW); } // the loop routine runs over and over again forever: void loop() { for (int i=0; i<=75; i++){ step1(); step2(); step3(); step4(); } stopMotor(); delay(10000); for (int i=0; i<=75; i++){ step3(); step2(); step1(); step4(); } stopMotor(); delay(10000); }
[ "doktorsuarez@gmx.de" ]
doktorsuarez@gmx.de
da0a15e1ba6b311b8f477f2ecc65a860a3123eaa
fd112107b91ed380566a9a59cf9396d2e3dcd457
/Face.cpp
7f3c50377c67dc440dfc60b7d1f7cf6c0307a3dd
[]
no_license
lapidarioz/STEF
3a612df60b0778ae67680b5ee77e6a8111d6f2a0
585e72dd5cba08a50892819b6526664c72d35235
refs/heads/master
2021-01-22T10:59:48.242685
2017-01-05T17:47:52
2017-01-05T17:47:52
36,267,377
3
0
null
null
null
null
UTF-8
C++
false
false
16,433
cpp
#include <stdio.h> #include <GL/glut.h> #include <sstream>> #include <string> #include "Face.h" int expres=0; Face::Face(GLint altura, GLint largura, GLint etinia, Grafo g) { //pFile = fopen ("OutrasFaces.txt","w"); this->altura = altura; this->largura = largura; //(altura/Antropometria::alturaCabeca) //desenha = new Desenha(altura, largura, 2.7); desenha = new Desenha(altura, largura, 4); medidas = new Medidas(); antropometria = new Antropometria(altura, largura, etinia, g); movimentos = new Movimentos(altura, largura); } Face::~Face() { fclose (pFile); delete desenha; delete medidas; delete antropometria; delete movimentos; } void Face::inicilizaArraysCurvas() { //sobrancelha antropometria->getSombrancelhaEsquerda(se); antropometria->getSombrancelhaDireita(sd); //olho antropometria->getOlhoEsquerdoCima(oec); antropometria->getOlhoEsquerdoBaixo(oeb); antropometria->getOlhoDireitoCima(odc); antropometria->getOlhoDireitoBaixo(odb); //nariz antropometria->getNarizEsquerda(ne); antropometria->getNarizDireita(nd); //boca antropometria->getLabioSuperiorCima(lsc); antropometria->getLabioSuperiorBaixo(lsb); antropometria->getLabioInferiorCima(lic); antropometria->getLabioInferiorBaixo(lib); //rugas olho antropometria->getRugasOlhoEsquerdoCima(roec); antropometria->getRugasOlhoEsquerdoMeio(roem); antropometria->getRugasOlhoEsquerdoBaixo(roeb); antropometria->getRugasOlhoDireitoCima(rodc); antropometria->getRugasOlhoDireitoMeio(rodm); antropometria->getRugasOlhoDireitoBaixo(rodb); //palpebras antropometria->getPalpebraEsquerda(pe); antropometria->getPalpebraDireita(pd); //contorno antropometria->getContornoEsquerdoCima(cec); // antropometria->getContornoQueixo(queixo); // antropometria->getContornoEsquerdoBaixo(ceb); //antropometria->getContornoDireitoCima(cdc); antropometria->getContornoDireitoBaixo(cdb); //rugas testa antropometria->getRugaTestaCima(rtc); antropometria->getRugaTestaMeio(rtm); antropometria->getRugaTestaBaixo(rtb); //rugas centro testa antropometria->getRugaCentroTestaCima(rctc); antropometria->getRugaCentroTestaMeio(rctm); antropometria->getRugaCentroTestaBaixo(rctb); //pupilas antropometria->getPupilaEsquerda(pue); antropometria->getPupilaDireita(pud); pupilaR = antropometria->getRaioPupila(); // antropometria->getRugaInteriorSobrancelhaEsquerda(rsie); antropometria->getRugaInteriorSobrancelhaCentro(rsic); antropometria->getRugaInteriorSobrancelhaDireita(rsid); // antropometria->getRugaSobrancelhaNarizCima(rsnc); antropometria->getRugaSobrancelhaNarizMeio(rsnm); antropometria->getRugaSobrancelhaNarizBaixo(rsnb); // antropometria->getRugaNarizEsquerdaCima(rnec); antropometria->getRugaNarizEsquerdaBaixo(rneb); antropometria->getRugaNarizDireitaCima(rndc); antropometria->getRugaNarizDireitaBaixo(rndb); // antropometria->getRugaBochechaEsquerda(rbe); antropometria->getRugaBochechaDireita(rbd); // antropometria->getNasolabialEsquerda(nle); antropometria->getNasolabialDireita(nld); // antropometria->getNasolabialInternaEsquerda(nlie); antropometria->getNasolabialInternaDireita(nlid); } void Face::desenhaSobrancelhaEsquerda() { imprimePontos("Sobrancelha esquerda", se, 8); //desenha->desenhaCurva(se, 8); } void Face::desenhaSobrancelhaDireita() { imprimePontos("Sobrancelha direita", sd, 8); //desenha->desenhaCurva(sd, 8); } void Face::desenhaOlhoEsquerdoCima() { imprimePontos("Olho esquerdo cima", oec, 4); //desenha->desenhaCurva(oec, 4); } void Face::desenhaOlhoEsquerdoBaixo() { imprimePontos("Olho esquerdo baixo", oeb, 4); //desenha->desenhaCurva(oeb, 4); } void Face::desenhaOlhoDireitoCima() { imprimePontos("Olho direito cima", odc, 4); //desenha->desenhaCurva(odc, 4); } void Face::desenhaOlhoDireitoBaixo() { imprimePontos("Olho direito baixo", odb, 4); //desenha->desenhaCurva(odb, 4); } void Face::desenhaNarizEsquerda() { imprimePontos("Nariz esquerda", ne, 6); //desenha->desenhaCurva(ne, 6); } void Face::desenhaNarizDireita() { imprimePontos("Nariz direita", nd, 6); //desenha->desenhaCurva(nd, 6); } void Face::desenhaLabioSuperiorCima() { imprimePontos("Boca cima", lsc, 4); //desenha->desenhaCurva(lsc, 4); } void Face::desenhaLabioSuperiorBaixo() { imprimePontos("Boca meio cima", lsb, 4); //desenha->desenhaCurva(lsb, 4); } void Face::desenhaLabioInferiorCima() { imprimePontos("Boca meio baixo", lic, 4); //desenha->desenhaCurva(lic, 4); } void Face::desenhaLabioInferiorBaixo() { imprimePontos("Boca baixo", lib, 4); //desenha->desenhaCurva(lib, 4); } void Face::desenhaRugasOlhoEsquerdo() { imprimePontos("rugas olho esquerdo cima", roec, 4); //desenha->desenhaCurva(roec, 4); imprimePontos("rugas olho esquerdo meio", roem, 4); //desenha->desenhaCurva(roem, 4); imprimePontos("rugas olho esquerdo baixo", roeb, 4); //desenha->desenhaCurva(roeb, 4); } void Face::desenhaRugasOlhoDireito() { imprimePontos("rugas olho direito cima", rodc, 4); //desenha->desenhaCurva(rodc, 4); imprimePontos("rugas olho direito meio", rodm, 4); //desenha->desenhaCurva(rodm, 4); imprimePontos("rugas olho direito baixo", rodb, 4); //desenha->desenhaCurva(rodb, 4); } void Face::desenhaPalpebraEsquerda() { imprimePontos("Palpebra esquerda", pe, 4); //desenha->desenhaCurva(pe, 4); } void Face::desenhaPalpebraDireita() { imprimePontos("Palpebra direita", pd, 4); //desenha->desenhaCurva(pd, 4); } void Face::desenhaContornoEsquerdo() { imprimePontos("Contorno cima", cec, 7); //desenha->desenhaCurva(cec, 4); imprimePontos("Contorno esquerdo baixo", ceb, 4); //desenha->desenhaCurva(ceb, 4); imprimePontos("Contorno queixo", queixo, 3); } void Face::desenhaContornoDireito() { //imprimePontos("Contorno direito cima", cdc, 7); //desenha->desenhaCurva(cdc, 4); imprimePontos("Contorno direito baixo", cdb, 4); //desenha->desenhaCurva(cdb, 4); } void Face::desenhaRugaTestaCima() { imprimePontos("Ruga testa cima", rtc, 8); //desenha->desenhaCurva(rtc, 8); } void Face::desenhaRugaTestaMeio() { imprimePontos("Ruga testa meio", rtm, 8); //desenha->desenhaCurva(rtm, 8); } void Face::desenhaRugaTestaBaixo() { imprimePontos("Ruga testa baixo", rtb, 8); //desenha->desenhaCurva(rtb, 8); } void Face::desenhaRugaCentroTestaCima() { imprimePontos("Ruga testa centro cima", rctc, 4); //desenha->desenhaCurva(rctc, 4); } void Face::desenhaRugaCentroTestaMeio() { imprimePontos("Ruga testa centro meio", rctm, 4); //desenha->desenhaCurva(rctm, 4); } void Face::desenhaRugaCentroTestaBaixo() { imprimePontos("Ruga testa centro centro baixo", rctb, 4); //desenha->desenhaCurva(rctb, 4); } void Face::desenhaPupilaEsquerda() { imprimePontos("wPupila esquerda", pue, 1); //desenha->desenhaCirculo(pue, pupilaR); } void Face::desenhaPupilaDireita() { imprimePontos("wPupila direita", pud, 1); //desenha->desenhaCirculo(pud, pupilaR); } void Face::desenhaRugasCantoInternoSobrancelhaEsquerda() { imprimePontos("Ruga Canto Interno Sobrancelha Esquerda", rsie, 4); //desenha->desenhaCurva(rsie, 4); } void Face::desenhaRugasCantoInternoSobrancelhaCentro() { imprimePontos("Ruga Canto Interno Sobrancelha Centro", rsic, 4); //desenha->desenhaCurva(rsic, 4); } void Face::desenhaRugasCantoInternoSobrancelhaBaixo() { imprimePontos("Ruga Canto Interno Sobrancelha Direita", rsid, 4); //desenha->desenhaCurva(rsid, 4); } void Face::desenhaRugasNarizSuperiorCima() { imprimePontos("Ruga Nariz Superior Cima", rsnc, 4); //desenha->desenhaCurva(rsnc, 4); } void Face::desenhaRugasNarizSuperiorMeio() { imprimePontos("Ruga Nariz Superior meio", rsnm, 4); //desenha->desenhaCurva(rsnm, 4); } void Face::desenhaRugasNarizSuperiorBaixo() { imprimePontos("Ruga Nariz Superior baixo", rsnb, 4); //desenha->desenhaCurva(rsnb, 4); } void Face::desenhaRugasNarizInferiorEsquerda() { imprimePontos("Ruga Nariz Inferior Esquerda baixo", rneb, 4); //desenha->desenhaCurva(rneb, 4); imprimePontos("Ruga Nariz Inferior Esquerda cima", rnec, 4); //desenha->desenhaCurva(rnec, 4); } void Face::desenhaRugasNarizInferiorDireita() { imprimePontos("Ruga Nariz Inferior direita baixo", rndb, 4); //desenha->desenhaCurva(rndb, 4); imprimePontos("Ruga Nariz Inferior direita cima", rndc, 4); //desenha->desenhaCurva(rndc, 4); } void Face::desenhaRugasBochechasEsquerda() { imprimePontos("Ruga Bochecha Esquerda", rbe, 8); //desenha->desenhaCurva(rbe, 8); } void Face::desenhaRugasBochechasDireita() { imprimePontos("Ruga Bochecha Direita", rbd, 8); //desenha->desenhaCurva(rbd, 8); } void Face::desenhaNazolabialEsquerda() { imprimePontos("Naso Labial Esquerda", nle, 4); //desenha->desenhaCurva(nle, 4); } void Face::desenhaNazolabialDireita() { imprimePontos("Naso Labial Direita", nld, 4); //desenha->desenhaCurva(nld, 4); } void Face::desenhaNazolabialInternoEsquerda() { imprimePontos("Naso Labial interno Esquerda", nlie, 4); //desenha->desenhaCurva(nlie, 4); } void Face::desenhaNazolabialInternoDireita() { imprimePontos("Naso Labial interno Direita", nlid, 4); //desenha->desenhaCurva(nlid, 4); } void Face::desenhaNazolabial() { desenhaNazolabialEsquerda(); desenhaNazolabialDireita(); desenhaNazolabialInternoEsquerda(); desenhaNazolabialInternoDireita(); } void Face::desenhaPupilas() { desenhaPupilaEsquerda(); desenhaPupilaDireita(); } void Face::desenhaRugasTesta(GLfloat espessura) { desenha->alteraEspessuraLinha(espessura * Desenha::espessuraPadrao); desenhaRugaTestaCima(); desenhaRugaTestaMeio(); desenhaRugaTestaBaixo(); desenha->alteraEspessuraLinha(Desenha::espessuraPadrao); } void Face::desenhaRugasCentroTesta(GLfloat espessura) { desenha->alteraEspessuraLinha(espessura * Desenha::espessuraPadrao); desenhaRugaCentroTestaCima(); desenhaRugaCentroTestaMeio(); desenhaRugaCentroTestaBaixo(); desenha->alteraEspessuraLinha(Desenha::espessuraPadrao); } void Face::desenhaContorno() { desenhaContornoEsquerdo(); desenhaContornoDireito(); } void Face::desenhaPalpebras() { desenhaPalpebraEsquerda(); desenhaPalpebraDireita(); } void Face::desenhaRugasOlhos(GLfloat espessura) { desenha->alteraEspessuraLinha(espessura * Desenha::espessuraPadrao); desenhaRugasOlhoEsquerdo(); desenhaRugasOlhoDireito(); desenha->alteraEspessuraLinha(Desenha::espessuraPadrao); } void Face::desenhaSobrancelha() { desenhaSobrancelhaEsquerda(); desenhaSobrancelhaDireita(); } void Face::desenhaOlhoEsquerdo() { desenhaOlhoEsquerdoCima(); desenhaOlhoEsquerdoBaixo(); } void Face::desenhaOlhoDireito() { desenhaOlhoDireitoCima(); desenhaOlhoDireitoBaixo(); } void Face::desenhaOlho() { desenhaOlhoEsquerdo(); desenhaOlhoDireito(); } void Face::desenhaNariz() { desenhaNarizEsquerda(); desenhaNarizDireita(); } void Face::desenhaRugasNarizInferior() { desenhaRugasNarizInferiorEsquerda(); desenhaRugasNarizInferiorDireita(); } void Face::desenhaRugasNarizSuperior() { desenhaRugasNarizSuperiorCima(); desenhaRugasNarizSuperiorMeio(); desenhaRugasNarizSuperiorBaixo(); } void Face::desenhaRugasCantoInternoSobrancelha(GLfloat espessura) { desenha->alteraEspessuraLinha(espessura * Desenha::espessuraPadrao); desenhaRugasCantoInternoSobrancelhaEsquerda(); //desenhaRugasCantoInternoSobrancelhaCentro(); desenhaRugasCantoInternoSobrancelhaBaixo(); desenha->alteraEspessuraLinha(Desenha::espessuraPadrao); } void Face::desenhaRugasNariz(GLfloat espessura) { desenha->alteraEspessuraLinha(espessura * Desenha::espessuraPadrao); desenhaRugasNarizSuperior(); desenhaRugasNarizInferior(); desenha->alteraEspessuraLinha(Desenha::espessuraPadrao); } void Face::desenhaRugasBochecha(GLfloat espessura) { desenha->alteraEspessuraLinha(espessura * Desenha::espessuraPadrao); desenhaRugasBochechasDireita(); desenhaRugasBochechasEsquerda(); desenha->alteraEspessuraLinha(Desenha::espessuraPadrao); } void Face::desenhaBoca() { desenhaLabioSuperiorCima(); desenhaLabioSuperiorBaixo(); desenhaLabioInferiorCima(); desenhaLabioInferiorBaixo(); } void Face::desenhaFace() { desenhaSobrancelha(); desenhaOlho(); desenhaNariz(); desenhaBoca(); desenhaPalpebras(); desenhaContorno(); desenhaPupilas(); } int n = 0; void Face::desenhaFace(GLint expressao, GLfloat qtdExpressao) { pFile = fopen("FaceMov.txt", "w"); glClear(GL_COLOR_BUFFER_BIT); inicilizaArraysCurvas(); switch (expressao) { case expressaoNeutra: neutra(); break; case expressaoSatisfcao: satisfacao(qtdExpressao); expres=1; break; case expressaoTriteza: tristeza(qtdExpressao); expres=2; break; case expressaoSurpresa: surpresa(qtdExpressao); break; case expressaoMedo: medo(qtdExpressao); break; case expressaoAversao: aversao(qtdExpressao); break; case expressaoRaiva: raiva(qtdExpressao); break; case expressaoDesprezo: desprezo(qtdExpressao); break; } desenhaFace(); glFlush(); glutSwapBuffers(); //printf("\n###########################################################\n"); n++; fclose (pFile); if (n == 2) { n = 0; } } void Face::imprimePontos(const char* contexto, GLfloat pontos[][3], GLint nPontos) { fprintf(pFile, "Curva %s:{\n", contexto); GLint i; for (i = 0; i < nPontos; i++) { fprintf(pFile, "(%f, %f)\n", pontos[i][0], pontos[i][1]); } fprintf(pFile, "}\n"); // printf(">>>>>>>contexto:+%s", contexto); } void Face::satisfacao(GLfloat intensidade) { movimentos->au12LipCornerPuller(lsc, lsb, lic, lib, intensidade); movimentos->au6CheekRaiserLidCompressor(oeb, oec, odb, odc, pe, pd, roec, roem, roeb, rodc, rodm, rodb, intensidade); //movimentos->movAlpha(lsc, lsb, lic, lib, oeb, oec, odb, odc, pe, pd, roec, //roem, roeb, rodc, rodm, rodb, intensidade,expres); desenhaRugasOlhos(intensidade); } void Face::tristeza(GLfloat intensidade) { //movimentos->movAlpha(lsc, lsb, lic, lib, oeb, oec, odb, odc, pe, pd, roec, // roem, roeb, rodc, rodm, rodb, intensidade,expres); movimentos->au1au4(se, sd, oec, odc, rctc, rctm, rctb, intensidade); desenhaRugasCentroTesta(intensidade); movimentos->au15LipCornerDepresor(lsc, lsb, lic, lib, intensidade); desenhaRugasCantoInternoSobrancelha(intensidade); GLfloat aux[7][3]; antropometria->getAuxiliares(aux); //desenha->desenhaPontosAzul(aux, 7); imprimePontos("Auxiliares", aux, 2); //FAZER AU11 } void Face::neutra() { GLfloat aux[7][3]; antropometria->getAuxiliares(aux); //desenha->desenhaPontosAzul(aux, 7); imprimePontos("Auxiliares", aux, 2); //desenhaControno(); } void Face::surpresa(GLfloat intensidade) { movimentos->au1au2(se, sd, oec, odc, rtc, rtm, rtb, rctc, rctm, rctb, intensidade); desenhaRugasTesta(intensidade); movimentos->au5UpperLidRaiser(oeb, oec, odb, odc, pe, pd, 0.8 * intensidade); movimentos->au26JawDrop(lsc, lsb, lic, lib, intensidade); } void Face::medo(GLfloat intensidade) { movimentos->au1au2au4(se, sd, oec, odc, rtc, rtm, rtb, rctc, rctm, rctb, intensidade); movimentos->au5UpperLidRaiser(oeb, oec, odb, odc, pe, pd, intensidade); movimentos->au26JawDrop(lsc, lsb, lic, lib, 0.8 * intensidade); movimentos->au20LipStretcher(lsc, lsb, lic, lib, intensidade); desenhaRugasCantoInternoSobrancelha(intensidade); } void Face::aversao(GLfloat intensidade) { movimentos->au9NoseWrinkler(ne, nd, lsc, lsb, intensidade); movimentos->au15LipCornerDepresor(lsc, lsb, lic, lib, 0.1 * intensidade); movimentos->au16au25LowerLipDepressor(lsc, lsb, lic, lib, intensidade); desenhaRugasNariz(intensidade); desenhaRugasBochecha(intensidade); } void Face::raiva(GLfloat intensidade) { movimentos->au4BrowLowerer(se, sd, oec, odc, intensidade); movimentos->au5UpperLidRaiser(oeb, oec, odb, odc, pe, pd, intensidade); movimentos->au7LidTightener(oeb, oec, odb, odc, pe, pd, 0.4 * intensidade); movimentos->au23LipTightener(lsc, lsb, lic, lib, intensidade); desenhaRugasCantoInternoSobrancelha(intensidade); desenhaNazolabial(); } void Face::desprezo(GLfloat intensidade) { desenhaContorno(); }
[ "rafael1testa@gmail.com" ]
rafael1testa@gmail.com
37f621bccdea492677ceaab4a14e14bfd240db1c
9b4e471ad6ed2a76269456f5c8e237d2c301e2ec
/stringhelper.cpp
bbb035197a0012aeb98202939c89a01f604455d2
[]
no_license
PontiacGTX/SqlServerSampleQT
fe803986c386f3531cf4a8211c7e706aebbf8d91
35b8ed8d9f1b98859e8e356c60455cf8d2bf97f2
refs/heads/master
2023-02-18T14:41:11.361889
2021-01-15T19:10:28
2021-01-15T19:10:28
330,000,434
0
0
null
null
null
null
UTF-8
C++
false
false
893
cpp
#include "stringhelper.h" StringHelper::StringHelper() { } StringHelper::StringHelper( std::string const& text) { this->input = text; } size_t StringHelper::GetIndex(size_t elementCount,const std::string str,std::string val) { size_t elementFoundAt=0; size_t counter = 0; while(counter!=elementCount) { if((elementFoundAt = str.find(val,elementFoundAt))!=0) { counter++; } } return elementFoundAt; } std::string StringHelper::GetConnectionString(std::string serverName, std::string dbName) { std::string server = input.substr(0,7) + serverName + ";"; size_t index = GetIndex(1,input,";"); std::string Database = input.substr(index,9) + dbName; index = GetIndex(2,input,";"); std::string remaining = input.substr(index,input.length() - index); return (result = server + Database + remaining) ; }
[ "pontiacsunfiregt@gmail.com" ]
pontiacsunfiregt@gmail.com
f0e1f3841cb3ffb610bc938485e54257f8e9c3f9
bfa20f2a33304f9f5db3d9671109ddc6e9cfe7f2
/src/studio/studio_sessions_vm.hpp
c77d218e0ca137837964a344b6ccfc71d1d6aa11
[ "MIT" ]
permissive
JonnyWalker81/mx3
6a701b43cdc1482825e8c115145d7237a3e1d576
381652b5fa14866f6596625e1a56213fb536f073
refs/heads/master
2021-01-18T03:53:30.801915
2015-10-23T05:44:29
2015-10-23T05:44:29
44,085,743
0
0
null
2015-10-12T05:24:32
2015-10-12T05:24:31
null
UTF-8
C++
false
false
954
hpp
// // Created by Jonathan Rothberg on 10/22/15. // #ifndef MX3_STUDIO_SESSIONS_VM_HPP #define MX3_STUDIO_SESSIONS_VM_HPP #include <optional/optional.hpp> #include "studio_session_cell.hpp" #import "studio_sessions_vm.hpp" #include "http.hpp" #include "studio_client.hpp" class studio_sessions_vm : public mx3_gen::StudioSessionsVm, public std::enable_shared_from_this<studio_sessions_vm> { public: studio_sessions_vm(const std::shared_ptr<studio_client>& pClient, const std::shared_ptr<mx3_gen::StudioSessionsObserver> & observer); virtual void getSessions(); virtual std::experimental::optional<mx3_gen::StudioSessionCell> getSession(int32_t index); virtual int32_t getSessionCount(); private: std::weak_ptr<studio_client> _studioClient; std::vector<mx3_gen::SessionsDto> m_oSessions; const std::shared_ptr<mx3_gen::StudioSessionsObserver> _observer; }; #endif //MX3_STUDIO_SESSIONS_VM_HPP
[ "%%GITEMAIL%%" ]
%%GITEMAIL%%
d587d3c820ab0652e20ac53a52a98338168298d1
f90f6861f9a62ccdbec9cf0707f2ccb438375713
/fengche/fengche.cpp
f8b5b304d5c59a216a199b87cb669129ae46a409
[]
no_license
zzwwqq/CPlusProgram
01124861e271cd6d79ca9852e1dcc11ef13ef680
8176a994fb2aad1e5bcb906b2488a1f7d5c69b17
refs/heads/master
2021-08-27T22:21:17.000252
2017-12-10T14:20:03
2017-12-10T14:20:03
null
0
0
null
null
null
null
GB18030
C++
false
false
5,696
cpp
#include <windows.h> #include<stdio.h> #define DIVISIONS 5 #include <math.h> #define Pi 3.1415926 #define R 50 //风车半径 #define NUM 3 //子窗口个数 int nMaxNum = 20; //nMaxNum记录了叶片循环一周中绘图的次数. LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ; LRESULT CALLBACK ChildWndProc(HWND, UINT, WPARAM, LPARAM) ; TCHAR szChildClass[] = TEXT ("ChildWindow") ; int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow) { static TCHAR szAppName[] = TEXT ("Checker3") ; HWND hwnd ; MSG msg ; WNDCLASS wndclass ; wndclass.style = CS_HREDRAW | CS_VREDRAW ; wndclass.lpfnWndProc = WndProc ; wndclass.cbClsExtra = 0 ; wndclass.cbWndExtra = 0 ; wndclass.hInstance = hInstance ; wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION) ; wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ; wndclass.hbrBackground = CreateSolidBrush(RGB(255,255,0));//(HBRUSH) GetStockObject (WHITE_BRUSH) ; wndclass.lpszMenuName = NULL ; wndclass.lpszClassName = szAppName ; if (!RegisterClass (&wndclass)) { MessageBox ( NULL, TEXT ("Program requires Windows NT!"),szAppName, MB_ICONERROR) ; return 0 ; } wndclass.lpfnWndProc = ChildWndProc ; wndclass.cbWndExtra = 2*sizeof (long) ; wndclass.hbrBackground = (HBRUSH) GetStockObject (NULL_BRUSH) ;//设子窗口的背景为透明 wndclass.lpszClassName = szChildClass ; RegisterClass (&wndclass) ; //注册子窗口类型 hwnd = CreateWindow (szAppName, TEXT ("主窗口与子窗口"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL) ; ShowWindow (hwnd, iCmdShow) ; UpdateWindow (hwnd) ; while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg) ; DispatchMessage (&msg) ; } return msg.wParam ; } //主窗口消息处理函数. LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam,LPARAM lParam) { static HWND hwndChild[NUM] ; static int cxBlock, cyBlock; static POINT ps; int i; switch (message) { case WM_CREATE : for( i = 0; i < NUM; i++) { hwndChild[i] = CreateWindow (szChildClass, NULL, WS_CHILDWINDOW | WS_VISIBLE/* | WS_SYSMENU| WS_CAPTION*/ , 0, 0, 0, 0, hwnd, (HMENU)i, //子窗口的ID值 (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE), NULL) ; SetWindowLong(hwndChild[i],0,i); //设定窗口第一个附加信息-窗口序号 SetWindowLong(hwndChild[i],4,0); //设定窗口第二个附加信息-窗口风车转动次数 SetTimer(hwndChild[i],i,(i+1)*30,0); } return 0 ; case WM_SIZE : //将子窗口按合适的尺寸和位置置于主窗口中 cxBlock = LOWORD (lParam) / 2 ; cyBlock = HIWORD (lParam) / 2 ; for( i=0; i<NUM;i++) MoveWindow ( hwndChild[i],R+i*(2*R+20), cyBlock-R,2*R, 2*R, TRUE) ; return 0 ; case WM_LBUTTONDOWN : MessageBeep (0) ; return 0 ; case WM_DESTROY : PostQuitMessage (0) ; return 0 ; } return DefWindowProc (hwnd, message, wParam, lParam) ; } //子窗口消息处理函数. long WINAPI ChildWndProc(HWND hWnd,UINT iMessage,UINT wParam,LONG lParam) { HDC hDC; //定义设备环境句柄. HBRUSH hBrush; //定义画刷句柄 HPEN hPen; //定义画笔句柄 PAINTSTRUCT PtStr; //定义包含绘图信息的结构体变量 int nCentreX,nCentreY; //定义3个叶片的圆心的坐标. int nNum; //当前的序数. double fAngle; switch(iMessage) { case WM_CREATE: break; case WM_LBUTTONDOWN: KillTimer(hWnd,GetWindowLong(hWnd,0)); break; case WM_PAINT: //处理绘图消息. nNum = GetWindowLong (hWnd, 4); hDC=BeginPaint(hWnd,&PtStr); //获得设备环境指针. SetMapMode(hDC,MM_ANISOTROPIC); //设置映射模式. SetViewportOrgEx(hDC,R,R,NULL); //设置视口原点坐标为(300,200).物理单位. //绘制外圆。 hPen = (HPEN)GetStockObject(BLACK_PEN); SelectObject(hDC,hPen); Ellipse(hDC,-R,-R,R,R); //绘制风车的叶片。 hBrush = CreateSolidBrush(RGB(255,0,0)); //画红色的叶片. SelectObject(hDC,hBrush); fAngle = 2*Pi/nMaxNum*nNum; //计算叶片角度 nCentreX = (int)(R/2*cos(fAngle)); nCentreY = (int)(R/2*sin(fAngle)); Pie(hDC,nCentreX-R/2,nCentreY-R/2, nCentreX+R/2,nCentreY+R/2, (int)(nCentreX+R/2*cos(fAngle)),(int)(nCentreY+R/2*sin(fAngle)), (int)(nCentreX+R/2*cos(fAngle+Pi)),(int)(nCentreY+R/2*sin(fAngle+Pi))); hBrush = CreateSolidBrush(RGB(255,255,0)); //画天蓝色的叶片. SelectObject(hDC,hBrush); nCentreX = (int)(R/2*cos(fAngle+2*Pi/3)); nCentreY = (int)(R/2*sin(fAngle+2*Pi/3)); Pie(hDC,nCentreX-R/2,nCentreY-R/2, nCentreX+R/2,nCentreY+R/2, (int)(nCentreX+R/2*cos(fAngle+2*Pi/3)),(int)(nCentreY+R/2*sin(fAngle+2*Pi/3)), (int)(nCentreX+R/2*cos(fAngle+Pi+2*Pi/3)),(int)(nCentreY+R/2*sin(fAngle+Pi+2*Pi/3))); hBrush = CreateSolidBrush(RGB(0,255,255)); //画黄色的叶片. SelectObject(hDC,hBrush); nCentreX = (int)(R/2*cos(fAngle+4*Pi/3)); nCentreY = (int)(R/2*sin(fAngle+4*Pi/3)); Pie(hDC,nCentreX-R/2,nCentreY-R/2, nCentreX+R/2,nCentreY+R/2, (int)(nCentreX+R/2*cos(fAngle+4*Pi/3)),(int)(nCentreY+R/2*sin(fAngle+4*Pi/3)), (int)(nCentreX+R/2*cos(fAngle+Pi+4*Pi/3)),(int)(nCentreY+R/2*sin(fAngle+Pi+4*Pi/3))); EndPaint(hWnd,&PtStr); //释放环境指针。 nNum++; //当前序数加1. SetWindowLong(hWnd,4,nNum); //将该窗口风车的转动次数存于窗口附加信息中 return 0; case WM_TIMER: InvalidateRect(hWnd,NULL,1); //重绘窗口区域. break; case WM_DESTROY: //关闭窗口. PostQuitMessage(0); return 0; default: return(DefWindowProc(hWnd,iMessage,wParam,lParam)); } return DefWindowProc (hWnd, iMessage, wParam, lParam) ; }
[ "1107717335@qq.com" ]
1107717335@qq.com
6a414890f867975c9547f67aaeb62e20f4f9b77e
f1fb4de1f2decb833031349ed642b101830a056f
/Graphics/GraphicsEngineD3D12/src/DeviceContextD3D12Impl.cpp
513f29071de296852da1f52fd21e67a9366346db
[ "Apache-2.0" ]
permissive
whztt07/DiligentCore
b2cb02bc6320716272986e1554f176fea94f9e39
18d59732724500f094510cece80afd83e3256282
refs/heads/master
2020-03-17T05:42:34.536763
2018-04-01T20:03:19
2018-04-01T20:03:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
40,726
cpp
/* Copyright 2015-2018 Egor Yusov * * 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 * * 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 OF ANY PROPRIETARY RIGHTS. * * In no event and under no legal theory, whether in tort (including negligence), * contract, or otherwise, unless required by applicable law (such as deliberate * and grossly negligent acts) or agreed to in writing, shall any Contributor be * liable for any damages, including any direct, indirect, special, incidental, * or consequential damages of any character arising as a result of this License or * out of the use or inability to use the software (including but not limited to damages * for loss of goodwill, work stoppage, computer failure or malfunction, or any and * all other commercial damages or losses), even if such Contributor has been advised * of the possibility of such damages. */ #include "pch.h" #include "RenderDeviceD3D12Impl.h" #include "DeviceContextD3D12Impl.h" #include "SwapChainD3D12.h" #include "PipelineStateD3D12Impl.h" #include "CommandContext.h" #include "TextureD3D12Impl.h" #include "BufferD3D12Impl.h" #include "D3D12TypeConversions.h" #include "d3dx12_win.h" #include "DynamicUploadHeap.h" #include "CommandListD3D12Impl.h" #include "DXGITypeConversions.h" namespace Diligent { DeviceContextD3D12Impl::DeviceContextD3D12Impl( IReferenceCounters *pRefCounters, RenderDeviceD3D12Impl *pDeviceD3D12Impl, bool bIsDeferred, const EngineD3D12Attribs &Attribs, Uint32 ContextId) : TDeviceContextBase(pRefCounters, pDeviceD3D12Impl, bIsDeferred), m_pUploadHeap(pDeviceD3D12Impl->RequestUploadHeap() ), m_NumCommandsInCurCtx(0), m_NumCommandsToFlush(bIsDeferred ? std::numeric_limits<decltype(m_NumCommandsToFlush)>::max() : Attribs.NumCommandsToFlushCmdList), m_pCurrCmdCtx(pDeviceD3D12Impl->AllocateCommandContext()), m_CommittedIBFormat(VT_UNDEFINED), m_CommittedD3D12IndexDataStartOffset(0), m_MipsGenerator(pDeviceD3D12Impl->GetD3D12Device()), m_CmdListAllocator(GetRawAllocator(), sizeof(CommandListD3D12Impl), 64 ), m_ContextId(ContextId) { auto *pd3d12Device = pDeviceD3D12Impl->GetD3D12Device(); D3D12_COMMAND_SIGNATURE_DESC CmdSignatureDesc = {}; D3D12_INDIRECT_ARGUMENT_DESC IndirectArg = {}; CmdSignatureDesc.NodeMask = 0; CmdSignatureDesc.NumArgumentDescs = 1; CmdSignatureDesc.pArgumentDescs = &IndirectArg; CmdSignatureDesc.ByteStride = sizeof(UINT)*4; IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW; auto hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDrawIndirectSignature), reinterpret_cast<void**>(static_cast<ID3D12CommandSignature**>(&m_pDrawIndirectSignature)) ); CHECK_D3D_RESULT_THROW(hr, "Failed to create indirect draw command signature"); CmdSignatureDesc.ByteStride = sizeof(UINT)*5; IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED; hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDrawIndexedIndirectSignature), reinterpret_cast<void**>(static_cast<ID3D12CommandSignature**>(&m_pDrawIndexedIndirectSignature)) ); CHECK_D3D_RESULT_THROW(hr, "Failed to create draw indexed indirect command signature"); CmdSignatureDesc.ByteStride = sizeof(UINT)*3; IndirectArg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; hr = pd3d12Device->CreateCommandSignature(&CmdSignatureDesc, nullptr, __uuidof(m_pDispatchIndirectSignature), reinterpret_cast<void**>(static_cast<ID3D12CommandSignature**>(&m_pDispatchIndirectSignature)) ); CHECK_D3D_RESULT_THROW(hr, "Failed to create dispatch indirect command signature"); } DeviceContextD3D12Impl::~DeviceContextD3D12Impl() { if(m_bIsDeferred) ValidatedCast<RenderDeviceD3D12Impl>(m_pDevice.RawPtr())->DisposeCommandContext(m_pCurrCmdCtx); else { if (m_NumCommandsInCurCtx != 0) LOG_WARNING_MESSAGE("Flusing outstanding commands from the device context being destroyed. This may result in D3D12 synchronization errors"); Flush(false); } } IMPLEMENT_QUERY_INTERFACE( DeviceContextD3D12Impl, IID_DeviceContextD3D12, TDeviceContextBase ) void DeviceContextD3D12Impl::SetPipelineState(IPipelineState *pPipelineState) { // Never flush deferred context! if (!m_bIsDeferred && m_NumCommandsInCurCtx >= m_NumCommandsToFlush) { Flush(true); } auto *pPipelineStateD3D12 = ValidatedCast<PipelineStateD3D12Impl>(pPipelineState); const auto &PSODesc = pPipelineStateD3D12->GetDesc(); bool CommitStates = false; bool CommitScissor = false; if(!m_pPipelineState) { // If no pipeline state is bound, we are working with the fresh command // list. We have to commit the states set in the context that are not // committed by the draw command (render targets, viewports, scissor rects, etc.) CommitStates = true; } else { const auto& OldPSODesc = m_pPipelineState->GetDesc(); // Commit all graphics states when switching from compute pipeline // This is necessary because if the command list had been flushed // and the first PSO set on the command list was a compute pipeline, // the states would otherwise never be committed (since m_pPipelineState != nullptr) CommitStates = OldPSODesc.IsComputePipeline; // We also need to update scissor rect if ScissorEnable state has changed CommitScissor = OldPSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable != PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable; } TDeviceContextBase::SetPipelineState( pPipelineState ); auto *pCmdCtx = RequestCmdContext(); auto *pd3d12PSO = pPipelineStateD3D12->GetD3D12PipelineState(); if (PSODesc.IsComputePipeline) { pCmdCtx->AsComputeContext().SetPipelineState(pd3d12PSO); } else { auto &GraphicsCtx = pCmdCtx->AsGraphicsContext(); GraphicsCtx.SetPipelineState(pd3d12PSO); if(CommitStates) { GraphicsCtx.SetStencilRef(m_StencilRef); GraphicsCtx.SetBlendFactor(m_BlendFactors); CommitRenderTargets(); CommitViewports(); } if(CommitStates || CommitScissor) { CommitScissorRects(GraphicsCtx, PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable); } } m_pCommittedResourceCache = nullptr; } void DeviceContextD3D12Impl::TransitionShaderResources(IPipelineState *pPipelineState, IShaderResourceBinding *pShaderResourceBinding) { VERIFY_EXPR(pPipelineState != nullptr); auto *pCtx = RequestCmdContext(); auto *pPipelineStateD3D12 = ValidatedCast<PipelineStateD3D12Impl>(pPipelineState); pPipelineStateD3D12->CommitAndTransitionShaderResources(pShaderResourceBinding, *pCtx, false, true); } void DeviceContextD3D12Impl::CommitShaderResources(IShaderResourceBinding *pShaderResourceBinding, Uint32 Flags) { if (!DeviceContextBase::CommitShaderResources<PipelineStateD3D12Impl>(pShaderResourceBinding, Flags, 0 /*Dummy*/)) return; auto *pCtx = RequestCmdContext(); auto *pPipelineStateD3D12 = ValidatedCast<PipelineStateD3D12Impl>(m_pPipelineState.RawPtr()); m_pCommittedResourceCache = pPipelineStateD3D12->CommitAndTransitionShaderResources(pShaderResourceBinding, *pCtx, true, (Flags & COMMIT_SHADER_RESOURCES_FLAG_TRANSITION_RESOURCES)!=0); } void DeviceContextD3D12Impl::SetStencilRef(Uint32 StencilRef) { if (TDeviceContextBase::SetStencilRef(StencilRef, 0)) { RequestCmdContext()->AsGraphicsContext().SetStencilRef( m_StencilRef ); } } void DeviceContextD3D12Impl::SetBlendFactors(const float* pBlendFactors) { if (TDeviceContextBase::SetBlendFactors(m_BlendFactors, 0)) { RequestCmdContext()->AsGraphicsContext().SetBlendFactor( m_BlendFactors ); } } void DeviceContextD3D12Impl::CommitD3D12IndexBuffer(VALUE_TYPE IndexType) { VERIFY( m_pIndexBuffer != nullptr, "Index buffer is not set up for indexed draw command" ); D3D12_INDEX_BUFFER_VIEW IBView; BufferD3D12Impl *pBuffD3D12 = static_cast<BufferD3D12Impl *>(m_pIndexBuffer.RawPtr()); IBView.BufferLocation = pBuffD3D12->GetGPUAddress(m_ContextId) + m_IndexDataStartOffset; if( IndexType == VT_UINT32 ) IBView.Format = DXGI_FORMAT_R32_UINT; else if( IndexType == VT_UINT16 ) IBView.Format = DXGI_FORMAT_R16_UINT; else { UNEXPECTED( "Unsupported index format. Only R16_UINT and R32_UINT are allowed." ); } // Note that for a dynamic buffer, what we use here is the size of the buffer itself, not the upload heap buffer! IBView.SizeInBytes = pBuffD3D12->GetDesc().uiSizeInBytes - m_IndexDataStartOffset; // Device context keeps strong reference to bound index buffer. // When the buffer is unbound, the reference to the D3D12 resource // is added to the context. There is no need to add reference here //auto &GraphicsCtx = RequestCmdContext()->AsGraphicsContext(); //auto *pd3d12Resource = pBuffD3D12->GetD3D12Buffer(); //GraphicsCtx.AddReferencedObject(pd3d12Resource); bool IsDynamic = pBuffD3D12->GetDesc().Usage == USAGE_DYNAMIC; #ifdef _DEBUG if(IsDynamic) pBuffD3D12->DbgVerifyDynamicAllocation(m_ContextId); #endif auto &GraphicsCtx = RequestCmdContext()->AsGraphicsContext(); // Resource transitioning must always be performed! GraphicsCtx.TransitionResource(pBuffD3D12, D3D12_RESOURCE_STATE_INDEX_BUFFER, true); size_t BuffDataStartByteOffset; auto *pd3d12Buff = pBuffD3D12->GetD3D12Buffer(BuffDataStartByteOffset, m_ContextId); if( IsDynamic || m_CommittedD3D12IndexBuffer != pd3d12Buff || m_CommittedIBFormat != IndexType || m_CommittedD3D12IndexDataStartOffset != m_IndexDataStartOffset + BuffDataStartByteOffset) { m_CommittedD3D12IndexBuffer = pd3d12Buff; m_CommittedIBFormat = IndexType; m_CommittedD3D12IndexDataStartOffset = m_IndexDataStartOffset + static_cast<Uint32>(BuffDataStartByteOffset); GraphicsCtx.SetIndexBuffer( IBView ); } // GPU virtual address of a dynamic index buffer can change every time // a draw command is invoked m_bCommittedD3D12IBUpToDate = !IsDynamic; } void DeviceContextD3D12Impl::TransitionD3D12VertexBuffers(GraphicsContext &GraphCtx) { for( UINT Buff = 0; Buff < m_NumVertexStreams; ++Buff ) { auto &CurrStream = m_VertexStreams[Buff]; VERIFY( CurrStream.pBuffer, "Attempting to bind a null buffer for rendering" ); auto *pBufferD3D12 = static_cast<BufferD3D12Impl*>(CurrStream.pBuffer.RawPtr()); if(!pBufferD3D12->CheckAllStates(D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER)) GraphCtx.TransitionResource(pBufferD3D12, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); } } void DeviceContextD3D12Impl::CommitD3D12VertexBuffers(GraphicsContext &GraphCtx) { auto *pPipelineStateD3D12 = ValidatedCast<PipelineStateD3D12Impl>(m_pPipelineState.RawPtr()); // Do not initialize array with zeroes for performance reasons D3D12_VERTEX_BUFFER_VIEW VBViews[MaxBufferSlots];// = {} VERIFY( m_NumVertexStreams <= MaxBufferSlots, "Too many buffers are being set" ); const auto *TightStrides = pPipelineStateD3D12->GetTightStrides(); bool DynamicBufferPresent = false; for( UINT Buff = 0; Buff < m_NumVertexStreams; ++Buff ) { auto &CurrStream = m_VertexStreams[Buff]; auto &VBView = VBViews[Buff]; VERIFY( CurrStream.pBuffer, "Attempting to bind a null buffer for rendering" ); auto *pBufferD3D12 = static_cast<BufferD3D12Impl*>(CurrStream.pBuffer.RawPtr()); if (pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) { DynamicBufferPresent = true; #ifdef _DEBUG pBufferD3D12->DbgVerifyDynamicAllocation(m_ContextId); #endif } GraphCtx.TransitionResource(pBufferD3D12, D3D12_RESOURCE_STATE_VERTEX_AND_CONSTANT_BUFFER); // Device context keeps strong references to all vertex buffers. // When a buffer is unbound, a reference to D3D12 resource is added to the context, // so there is no need to reference the resource here //GraphicsCtx.AddReferencedObject(pd3d12Resource); VBView.BufferLocation = pBufferD3D12->GetGPUAddress(m_ContextId) + CurrStream.Offset; VBView.StrideInBytes = CurrStream.Stride ? CurrStream.Stride : TightStrides[Buff]; // Note that for a dynamic buffer, what we use here is the size of the buffer itself, not the upload heap buffer! VBView.SizeInBytes = pBufferD3D12->GetDesc().uiSizeInBytes - CurrStream.Offset; } GraphCtx.FlushResourceBarriers(); GraphCtx.SetVertexBuffers( 0, m_NumVertexStreams, VBViews ); // GPU virtual address of a dynamic vertex buffer can change every time // a draw command is invoked m_bCommittedD3D12VBsUpToDate = !DynamicBufferPresent; } void DeviceContextD3D12Impl::Draw( DrawAttribs &DrawAttribs ) { #ifdef _DEBUG if (!m_pPipelineState) { LOG_ERROR("No pipeline state is bound"); return; } if (m_pPipelineState->GetDesc().IsComputePipeline) { LOG_ERROR("No graphics pipeline state is bound"); return; } #endif auto &GraphCtx = RequestCmdContext()->AsGraphicsContext(); if( DrawAttribs.IsIndexed ) { if( m_CommittedIBFormat != DrawAttribs.IndexType ) m_bCommittedD3D12IBUpToDate = false; if(m_bCommittedD3D12IBUpToDate) { BufferD3D12Impl *pBuffD3D12 = static_cast<BufferD3D12Impl *>(m_pIndexBuffer.RawPtr()); if(!pBuffD3D12->CheckAllStates(D3D12_RESOURCE_STATE_INDEX_BUFFER)) GraphCtx.TransitionResource(pBuffD3D12, D3D12_RESOURCE_STATE_INDEX_BUFFER, true); } else CommitD3D12IndexBuffer(DrawAttribs.IndexType); } auto *pPipelineStateD3D12 = ValidatedCast<PipelineStateD3D12Impl>(m_pPipelineState.RawPtr()); auto D3D12Topology = TopologyToD3D12Topology( DrawAttribs.Topology ); GraphCtx.SetPrimitiveTopology(D3D12Topology); if(m_bCommittedD3D12VBsUpToDate) TransitionD3D12VertexBuffers(GraphCtx); else CommitD3D12VertexBuffers(GraphCtx); GraphCtx.SetRootSignature( pPipelineStateD3D12->GetD3D12RootSignature() ); if(m_pCommittedResourceCache != nullptr) { pPipelineStateD3D12->GetRootSignature().CommitRootViews(*m_pCommittedResourceCache, GraphCtx, false, m_ContextId); } #ifdef _DEBUG else { if( pPipelineStateD3D12->dbgContainsShaderResources() ) LOG_ERROR_MESSAGE("Pipeline state \"", pPipelineStateD3D12->GetDesc().Name, "\" contains shader resources, but IDeviceContext::CommitShaderResources() was not called" ); } #endif if( DrawAttribs.IsIndirect ) { if( auto *pBufferD3D12 = ValidatedCast<BufferD3D12Impl>(DrawAttribs.pIndirectDrawAttribs) ) { #ifdef _DEBUG if(pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) pBufferD3D12->DbgVerifyDynamicAllocation(m_ContextId); #endif GraphCtx.TransitionResource(pBufferD3D12, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); size_t BuffDataStartByteOffset; ID3D12Resource *pd3d12ArgsBuff = pBufferD3D12->GetD3D12Buffer(BuffDataStartByteOffset, m_ContextId); GraphCtx.ExecuteIndirect(DrawAttribs.IsIndexed ? m_pDrawIndexedIndirectSignature : m_pDrawIndirectSignature, pd3d12ArgsBuff, DrawAttribs.IndirectDrawArgsOffset + BuffDataStartByteOffset); } else { LOG_ERROR_MESSAGE("Valid pIndirectDrawAttribs must be provided for indirect draw command"); } } else { if( DrawAttribs.IsIndexed ) GraphCtx.DrawIndexed(DrawAttribs.NumIndices, DrawAttribs.NumInstances, DrawAttribs.FirstIndexLocation, DrawAttribs.BaseVertex, DrawAttribs.FirstInstanceLocation); else GraphCtx.Draw(DrawAttribs.NumVertices, DrawAttribs.NumInstances, DrawAttribs.StartVertexLocation, DrawAttribs.FirstInstanceLocation ); } ++m_NumCommandsInCurCtx; } void DeviceContextD3D12Impl::DispatchCompute( const DispatchComputeAttribs &DispatchAttrs ) { #ifdef _DEBUG if (!m_pPipelineState) { LOG_ERROR("No pipeline state is bound"); return; } if (!m_pPipelineState->GetDesc().IsComputePipeline) { LOG_ERROR("No compute pipeline state is bound"); return; } #endif auto *pPipelineStateD3D12 = ValidatedCast<PipelineStateD3D12Impl>(m_pPipelineState.RawPtr()); auto &ComputeCtx = RequestCmdContext()->AsComputeContext(); ComputeCtx.SetRootSignature( pPipelineStateD3D12->GetD3D12RootSignature() ); if(m_pCommittedResourceCache != nullptr) { pPipelineStateD3D12->GetRootSignature().CommitRootViews(*m_pCommittedResourceCache, ComputeCtx, true, m_ContextId); } #ifdef _DEBUG else { if( pPipelineStateD3D12->dbgContainsShaderResources() ) LOG_ERROR_MESSAGE("Pipeline state \"", pPipelineStateD3D12->GetDesc().Name, "\" contains shader resources, but IDeviceContext::CommitShaderResources() was not called" ); } #endif if( DispatchAttrs.pIndirectDispatchAttribs ) { if( auto *pBufferD3D12 = ValidatedCast<BufferD3D12Impl>(DispatchAttrs.pIndirectDispatchAttribs) ) { #ifdef _DEBUG if(pBufferD3D12->GetDesc().Usage == USAGE_DYNAMIC) pBufferD3D12->DbgVerifyDynamicAllocation(m_ContextId); #endif ComputeCtx.TransitionResource(pBufferD3D12, D3D12_RESOURCE_STATE_INDIRECT_ARGUMENT); size_t BuffDataStartByteOffset; ID3D12Resource *pd3d12ArgsBuff = pBufferD3D12->GetD3D12Buffer(BuffDataStartByteOffset, m_ContextId); ComputeCtx.ExecuteIndirect(m_pDispatchIndirectSignature, pd3d12ArgsBuff, DispatchAttrs.DispatchArgsByteOffset + BuffDataStartByteOffset); } else { LOG_ERROR_MESSAGE("Valid pIndirectDrawAttribs must be provided for indirect dispatch command"); } } else ComputeCtx.Dispatch(DispatchAttrs.ThreadGroupCountX, DispatchAttrs.ThreadGroupCountY, DispatchAttrs.ThreadGroupCountZ); ++m_NumCommandsInCurCtx; } void DeviceContextD3D12Impl::ClearDepthStencil( ITextureView *pView, Uint32 ClearFlags, float fDepth, Uint8 Stencil ) { ITextureViewD3D12 *pDSVD3D12 = nullptr; if( pView != nullptr ) { pDSVD3D12 = ValidatedCast<ITextureViewD3D12>(pView); #ifdef _DEBUG const auto& ViewDesc = pDSVD3D12->GetDesc(); VERIFY( ViewDesc.ViewType == TEXTURE_VIEW_DEPTH_STENCIL, "Incorrect view type: depth stencil is expected" ); #endif } else { if (m_pSwapChain) { pDSVD3D12 = ValidatedCast<ISwapChainD3D12>(m_pSwapChain.RawPtr())->GetDepthBufferDSV(); } else { LOG_ERROR("Failed to clear default depth stencil buffer: swap chain is not initialized in the device context"); return; } } D3D12_CLEAR_FLAGS d3d12ClearFlags = (D3D12_CLEAR_FLAGS)0; if( ClearFlags & CLEAR_DEPTH_FLAG ) d3d12ClearFlags |= D3D12_CLEAR_FLAG_DEPTH; if( ClearFlags & CLEAR_STENCIL_FLAG ) d3d12ClearFlags |= D3D12_CLEAR_FLAG_STENCIL; // The full extent of the resource view is always cleared. // Viewport and scissor settings are not applied?? RequestCmdContext()->AsGraphicsContext().ClearDepthStencil( pDSVD3D12, d3d12ClearFlags, fDepth, Stencil ); ++m_NumCommandsInCurCtx; } void DeviceContextD3D12Impl::ClearRenderTarget( ITextureView *pView, const float *RGBA ) { ITextureViewD3D12 *pd3d12RTV = nullptr; if( pView != nullptr ) { #ifdef _DEBUG const auto& ViewDesc = pView->GetDesc(); VERIFY( ViewDesc.ViewType == TEXTURE_VIEW_RENDER_TARGET, "Incorrect view type: render target is expected" ); #endif pd3d12RTV = ValidatedCast<ITextureViewD3D12>(pView); } else { if (m_pSwapChain) { pd3d12RTV = ValidatedCast<ISwapChainD3D12>(m_pSwapChain.RawPtr())->GetCurrentBackBufferRTV(); } else { LOG_ERROR("Failed to clear default render target: swap chain is not initialized in the device context"); return; } } static constexpr float Zero[4] = { 0.f, 0.f, 0.f, 0.f }; if( RGBA == nullptr ) RGBA = Zero; // The full extent of the resource view is always cleared. // Viewport and scissor settings are not applied?? RequestCmdContext()->AsGraphicsContext().ClearRenderTarget( pd3d12RTV, RGBA ); ++m_NumCommandsInCurCtx; } void DeviceContextD3D12Impl::Flush(bool RequestNewCmdCtx) { auto pDeviceD3D12Impl = ValidatedCast<RenderDeviceD3D12Impl>(m_pDevice.RawPtr()); if( m_pCurrCmdCtx ) { VERIFY(!m_bIsDeferred, "Deferred contexts cannot execute command lists directly"); if (m_NumCommandsInCurCtx != 0) { m_pCurrCmdCtx->FlushResourceBarriers(); pDeviceD3D12Impl->CloseAndExecuteCommandContext(m_pCurrCmdCtx, true); } else pDeviceD3D12Impl->DisposeCommandContext(m_pCurrCmdCtx); } m_pCurrCmdCtx = RequestNewCmdCtx ? pDeviceD3D12Impl->AllocateCommandContext() : nullptr; m_NumCommandsInCurCtx = 0; m_CommittedD3D12IndexBuffer = nullptr; m_CommittedD3D12IndexDataStartOffset = 0; m_CommittedIBFormat = VT_UNDEFINED; m_bCommittedD3D12VBsUpToDate = false; m_bCommittedD3D12IBUpToDate = false; m_pPipelineState.Release(); } void DeviceContextD3D12Impl::Flush() { VERIFY(!m_bIsDeferred, "Flush() should only be called for immediate contexts"); Flush(true); } void DeviceContextD3D12Impl::SetVertexBuffers( Uint32 StartSlot, Uint32 NumBuffersSet, IBuffer **ppBuffers, Uint32 *pStrides, Uint32 *pOffsets, Uint32 Flags ) { TDeviceContextBase::SetVertexBuffers( StartSlot, NumBuffersSet, ppBuffers, pStrides, pOffsets, Flags ); m_bCommittedD3D12VBsUpToDate = false; } void DeviceContextD3D12Impl::InvalidateState() { if (m_NumCommandsInCurCtx != 0) LOG_WARNING_MESSAGE("Invalidating context that has outstanding commands in it. Call Flush() to submit commands for execution"); TDeviceContextBase::InvalidateState(); m_CommittedD3D12IndexBuffer = nullptr; m_CommittedD3D12IndexDataStartOffset = 0; m_CommittedIBFormat = VT_UNDEFINED; m_bCommittedD3D12VBsUpToDate = false; m_bCommittedD3D12IBUpToDate = false; } void DeviceContextD3D12Impl::SetIndexBuffer( IBuffer *pIndexBuffer, Uint32 ByteOffset ) { TDeviceContextBase::SetIndexBuffer( pIndexBuffer, ByteOffset ); m_bCommittedD3D12IBUpToDate = false; } void DeviceContextD3D12Impl::CommitViewports() { constexpr Uint32 MaxViewports = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; D3D12_VIEWPORT d3d12Viewports[MaxViewports]; // Do not waste time initializing array to zero for( Uint32 vp = 0; vp < m_NumViewports; ++vp ) { d3d12Viewports[vp].TopLeftX = m_Viewports[vp].TopLeftX; d3d12Viewports[vp].TopLeftY = m_Viewports[vp].TopLeftY; d3d12Viewports[vp].Width = m_Viewports[vp].Width; d3d12Viewports[vp].Height = m_Viewports[vp].Height; d3d12Viewports[vp].MinDepth = m_Viewports[vp].MinDepth; d3d12Viewports[vp].MaxDepth = m_Viewports[vp].MaxDepth; } // All viewports must be set atomically as one operation. // Any viewports not defined by the call are disabled. RequestCmdContext()->AsGraphicsContext().SetViewports( m_NumViewports, d3d12Viewports ); } void DeviceContextD3D12Impl::SetViewports( Uint32 NumViewports, const Viewport *pViewports, Uint32 RTWidth, Uint32 RTHeight ) { constexpr Uint32 MaxViewports = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; VERIFY( NumViewports < MaxViewports, "Too many viewports are being set" ); NumViewports = std::min( NumViewports, MaxViewports ); TDeviceContextBase::SetViewports( NumViewports, pViewports, RTWidth, RTHeight ); VERIFY( NumViewports == m_NumViewports, "Unexpected number of viewports" ); CommitViewports(); } constexpr LONG MaxD3D12TexDim = D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION; constexpr Uint32 MaxD3D12ScissorRects = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; static constexpr RECT MaxD3D12TexSizeRects[D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE] = { { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim }, { 0,0, MaxD3D12TexDim,MaxD3D12TexDim } }; void DeviceContextD3D12Impl::CommitScissorRects(GraphicsContext &GraphCtx, bool ScissorEnable) { if (ScissorEnable) { // Commit currently set scissor rectangles D3D12_RECT d3d12ScissorRects[MaxD3D12ScissorRects]; // Do not waste time initializing array with zeroes for (Uint32 sr = 0; sr < m_NumScissorRects; ++sr) { d3d12ScissorRects[sr].left = m_ScissorRects[sr].left; d3d12ScissorRects[sr].top = m_ScissorRects[sr].top; d3d12ScissorRects[sr].right = m_ScissorRects[sr].right; d3d12ScissorRects[sr].bottom = m_ScissorRects[sr].bottom; } GraphCtx.SetScissorRects(m_NumScissorRects, d3d12ScissorRects); } else { // Disable scissor rectangles static_assert(_countof(MaxD3D12TexSizeRects) == MaxD3D12ScissorRects, "Unexpected array size"); GraphCtx.SetScissorRects(MaxD3D12ScissorRects, MaxD3D12TexSizeRects); } } void DeviceContextD3D12Impl::SetScissorRects( Uint32 NumRects, const Rect *pRects, Uint32 RTWidth, Uint32 RTHeight ) { const Uint32 MaxScissorRects = D3D12_VIEWPORT_AND_SCISSORRECT_OBJECT_COUNT_PER_PIPELINE; VERIFY( NumRects < MaxScissorRects, "Too many scissor rects are being set" ); NumRects = std::min( NumRects, MaxScissorRects ); TDeviceContextBase::SetScissorRects(NumRects, pRects, RTWidth, RTHeight); // Only commit scissor rects if scissor test is enabled in the rasterizer state. // If scissor is currently disabled, or no PSO is bound, scissor rects will be committed by // the SetPipelineState() when a PSO with enabled scissor test is set. if( m_pPipelineState ) { const auto &PSODesc = m_pPipelineState->GetDesc(); if(!PSODesc.IsComputePipeline && PSODesc.GraphicsPipeline.RasterizerDesc.ScissorEnable) { VERIFY(NumRects == m_NumScissorRects, "Unexpected number of scissor rects"); auto &Ctx = RequestCmdContext()->AsGraphicsContext(); CommitScissorRects(Ctx, true); } } } void DeviceContextD3D12Impl::CommitRenderTargets() { const Uint32 MaxD3D12RTs = D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; Uint32 NumRenderTargets = m_NumBoundRenderTargets; VERIFY( NumRenderTargets <= MaxD3D12RTs, "D3D12 only allows 8 simultaneous render targets" ); NumRenderTargets = std::min( MaxD3D12RTs, NumRenderTargets ); ITextureViewD3D12 *ppRTVs[MaxD3D12RTs]; // Do not initialize with zeroes! ITextureViewD3D12 *pDSV = nullptr; if( m_IsDefaultFramebufferBound ) { if (m_pSwapChain) { NumRenderTargets = 1; auto *pSwapChainD3D12 = ValidatedCast<ISwapChainD3D12>(m_pSwapChain.RawPtr()); ppRTVs[0] = pSwapChainD3D12->GetCurrentBackBufferRTV(); pDSV = pSwapChainD3D12->GetDepthBufferDSV(); } else { LOG_WARNING_MESSAGE("Failed to bind default render targets and depth-stencil buffer: swap chain is not initialized in the device context"); return; } } else { for( Uint32 rt = 0; rt < NumRenderTargets; ++rt ) ppRTVs[rt] = ValidatedCast<ITextureViewD3D12>(m_pBoundRenderTargets[rt].RawPtr()); pDSV = ValidatedCast<ITextureViewD3D12>(m_pBoundDepthStencil.RawPtr()); } RequestCmdContext()->AsGraphicsContext().SetRenderTargets(NumRenderTargets, ppRTVs, pDSV); } void DeviceContextD3D12Impl::SetRenderTargets( Uint32 NumRenderTargets, ITextureView *ppRenderTargets[], ITextureView *pDepthStencil ) { if( TDeviceContextBase::SetRenderTargets( NumRenderTargets, ppRenderTargets, pDepthStencil ) ) { CommitRenderTargets(); // Set the viewport to match the render target size SetViewports(1, nullptr, 0, 0); } } DynamicAllocation DeviceContextD3D12Impl::AllocateDynamicSpace(size_t NumBytes) { return m_pUploadHeap->Allocate(NumBytes); } void DeviceContextD3D12Impl::UpdateBufferRegion(class BufferD3D12Impl *pBuffD3D12, DynamicAllocation& Allocation, Uint64 DstOffset, Uint64 NumBytes) { auto pCmdCtx = RequestCmdContext(); VERIFY_EXPR( static_cast<size_t>(NumBytes) == NumBytes ); pCmdCtx->TransitionResource(pBuffD3D12, D3D12_RESOURCE_STATE_COPY_DEST, true); size_t DstBuffDataStartByteOffset; auto *pd3d12Buff = pBuffD3D12->GetD3D12Buffer(DstBuffDataStartByteOffset, m_ContextId); VERIFY(DstBuffDataStartByteOffset == 0, "Dst buffer must not be suballocated"); pCmdCtx->GetCommandList()->CopyBufferRegion( pd3d12Buff, DstOffset + DstBuffDataStartByteOffset, Allocation.pBuffer, Allocation.Offset, NumBytes); ++m_NumCommandsInCurCtx; } void DeviceContextD3D12Impl::UpdateBufferRegion(BufferD3D12Impl *pBuffD3D12, const void *pData, Uint64 DstOffset, Uint64 NumBytes) { VERIFY(pBuffD3D12->GetDesc().Usage != USAGE_DYNAMIC, "Dynamic buffers must be updated via Map()"); VERIFY_EXPR( static_cast<size_t>(NumBytes) == NumBytes ); auto TmpSpace = m_pUploadHeap->Allocate(static_cast<size_t>(NumBytes)); memcpy(TmpSpace.CPUAddress, pData, static_cast<size_t>(NumBytes)); UpdateBufferRegion(pBuffD3D12, TmpSpace, DstOffset, NumBytes); } void DeviceContextD3D12Impl::CopyBufferRegion(BufferD3D12Impl *pSrcBuffD3D12, BufferD3D12Impl *pDstBuffD3D12, Uint64 SrcOffset, Uint64 DstOffset, Uint64 NumBytes) { VERIFY(pDstBuffD3D12->GetDesc().Usage != USAGE_DYNAMIC, "Dynamic buffers cannot be copy destinations"); auto pCmdCtx = RequestCmdContext(); pCmdCtx->TransitionResource(pSrcBuffD3D12, D3D12_RESOURCE_STATE_COPY_SOURCE); pCmdCtx->TransitionResource(pDstBuffD3D12, D3D12_RESOURCE_STATE_COPY_DEST, true); size_t DstDataStartByteOffset; auto *pd3d12DstBuff = pDstBuffD3D12->GetD3D12Buffer(DstDataStartByteOffset, m_ContextId); VERIFY(DstDataStartByteOffset == 0, "Dst buffer must not be suballocated"); size_t SrcDataStartByteOffset; auto *pd3d12SrcBuff = pSrcBuffD3D12->GetD3D12Buffer(SrcDataStartByteOffset, m_ContextId); pCmdCtx->GetCommandList()->CopyBufferRegion( pd3d12DstBuff, DstOffset + DstDataStartByteOffset, pd3d12SrcBuff, SrcOffset+SrcDataStartByteOffset, NumBytes); ++m_NumCommandsInCurCtx; } void DeviceContextD3D12Impl::CopyTextureRegion(TextureD3D12Impl *pSrcTexture, Uint32 SrcSubResIndex, const D3D12_BOX *pD3D12SrcBox, TextureD3D12Impl *pDstTexture, Uint32 DstSubResIndex, Uint32 DstX, Uint32 DstY, Uint32 DstZ) { auto pCmdCtx = RequestCmdContext(); pCmdCtx->TransitionResource(pSrcTexture, D3D12_RESOURCE_STATE_COPY_SOURCE); pCmdCtx->TransitionResource(pDstTexture, D3D12_RESOURCE_STATE_COPY_DEST, true); D3D12_TEXTURE_COPY_LOCATION DstLocation = {}, SrcLocation = {}; DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; DstLocation.pResource = pDstTexture->GetD3D12Resource(); DstLocation.SubresourceIndex = DstSubResIndex; SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; SrcLocation.pResource = pSrcTexture->GetD3D12Resource(); SrcLocation.SubresourceIndex = SrcSubResIndex; pCmdCtx->GetCommandList()->CopyTextureRegion( &DstLocation, DstX, DstY, DstZ, &SrcLocation, pD3D12SrcBox); ++m_NumCommandsInCurCtx; } void DeviceContextD3D12Impl::CopyTextureRegion(IBuffer *pSrcBuffer, Uint32 SrcStride, Uint32 SrcDepthStride, class TextureD3D12Impl *pTextureD3D12, Uint32 DstSubResIndex, const Box &DstBox) { auto *pBufferD3D12 = ValidatedCast<BufferD3D12Impl>(pSrcBuffer); const auto& TexDesc = pTextureD3D12->GetDesc(); VERIFY(pBufferD3D12->GetState() == D3D12_RESOURCE_STATE_GENERIC_READ, "Staging buffer is expected to always be in D3D12_RESOURCE_STATE_GENERIC_READ state"); auto *pCmdCtx = RequestCmdContext(); auto *pCmdList = pCmdCtx->GetCommandList(); auto TextureState = pTextureD3D12->GetState(); D3D12_RESOURCE_BARRIER BarrierDesc; BarrierDesc.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; BarrierDesc.Transition.pResource = pTextureD3D12->GetD3D12Resource(); BarrierDesc.Transition.Subresource = DstSubResIndex; BarrierDesc.Transition.StateBefore = TextureState; BarrierDesc.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; BarrierDesc.Flags = D3D12_RESOURCE_BARRIER_FLAG_NONE; bool StateTransitionRequired = (TextureState & D3D12_RESOURCE_STATE_COPY_DEST) != D3D12_RESOURCE_STATE_COPY_DEST; if (StateTransitionRequired) pCmdList->ResourceBarrier(1, &BarrierDesc); D3D12_TEXTURE_COPY_LOCATION DstLocation; DstLocation.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; DstLocation.pResource = pTextureD3D12->GetD3D12Resource(); DstLocation.SubresourceIndex = static_cast<UINT>(DstSubResIndex); D3D12_TEXTURE_COPY_LOCATION SrcLocation; SrcLocation.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; SrcLocation.pResource = pBufferD3D12->GetD3D12Resource(); D3D12_PLACED_SUBRESOURCE_FOOTPRINT &Footpring = SrcLocation.PlacedFootprint; Footpring.Offset = 0; Footpring.Footprint.Width = static_cast<UINT>(DstBox.MaxX - DstBox.MinX); Footpring.Footprint.Height = static_cast<UINT>(DstBox.MaxY - DstBox.MinY); Footpring.Footprint.Depth = static_cast<UINT>(DstBox.MaxZ - DstBox.MinZ); // Depth cannot be 0 Footpring.Footprint.Format = TexFormatToDXGI_Format(TexDesc.Format); Footpring.Footprint.RowPitch = static_cast<UINT>(SrcStride); VERIFY(Footpring.Footprint.RowPitch * Footpring.Footprint.Height * Footpring.Footprint.Depth <= pBufferD3D12->GetDesc().uiSizeInBytes, "Buffer is not large enough"); VERIFY(SrcDepthStride == 0 || static_cast<UINT>(SrcDepthStride) == Footpring.Footprint.RowPitch * Footpring.Footprint.Height, "Depth stride must be equal to the size 2D level"); D3D12_BOX D3D12SrcBox; D3D12SrcBox.left = 0; D3D12SrcBox.right = Footpring.Footprint.Width; D3D12SrcBox.top = 0; D3D12SrcBox.bottom = Footpring.Footprint.Height; D3D12SrcBox.front = 0; D3D12SrcBox.back = Footpring.Footprint.Depth; pCmdCtx->GetCommandList()->CopyTextureRegion( &DstLocation, static_cast<UINT>( DstBox.MinX ), static_cast<UINT>( DstBox.MinY ), static_cast<UINT>( DstBox.MinZ ), &SrcLocation, &D3D12SrcBox); ++m_NumCommandsInCurCtx; if (StateTransitionRequired) { std::swap(BarrierDesc.Transition.StateBefore, BarrierDesc.Transition.StateAfter); pCmdList->ResourceBarrier(1, &BarrierDesc); } } void DeviceContextD3D12Impl::GenerateMips(TextureViewD3D12Impl *pTexView) { auto *pCtx = RequestCmdContext(); m_MipsGenerator.GenerateMips(ValidatedCast<RenderDeviceD3D12Impl>(m_pDevice.RawPtr()), pTexView, *pCtx); ++m_NumCommandsInCurCtx; } void DeviceContextD3D12Impl::FinishCommandList(class ICommandList **ppCommandList) { CommandListD3D12Impl *pCmdListD3D12( NEW_RC_OBJ(m_CmdListAllocator, "CommandListD3D12Impl instance", CommandListD3D12Impl) (m_pDevice, m_pCurrCmdCtx) ); pCmdListD3D12->QueryInterface( IID_CommandList, reinterpret_cast<IObject**>(ppCommandList) ); m_pCurrCmdCtx = nullptr; Flush(true); InvalidateState(); } void DeviceContextD3D12Impl::ExecuteCommandList(class ICommandList *pCommandList) { if (m_bIsDeferred) { LOG_ERROR("Only immediate context can execute command list"); return; } // First execute commands in this context Flush(true); InvalidateState(); CommandListD3D12Impl* pCmdListD3D12 = ValidatedCast<CommandListD3D12Impl>(pCommandList); ValidatedCast<RenderDeviceD3D12Impl>(m_pDevice.RawPtr())->CloseAndExecuteCommandContext(pCmdListD3D12->Close(), true); } void DeviceContextD3D12Impl::TransitionTextureState(ITexture *pTexture, D3D12_RESOURCE_STATES State) { VERIFY_EXPR(pTexture != nullptr); auto *pCmdCtx = RequestCmdContext(); pCmdCtx->TransitionResource(ValidatedCast<ITextureD3D12>(pTexture), State); } void DeviceContextD3D12Impl::TransitionBufferState(IBuffer *pBuffer, D3D12_RESOURCE_STATES State) { VERIFY_EXPR(pBuffer != nullptr); auto *pCmdCtx = RequestCmdContext(); pCmdCtx->TransitionResource(ValidatedCast<IBufferD3D12>(pBuffer), State); } }
[ "egor.yusov@gmail.com" ]
egor.yusov@gmail.com
50f3c4a35979f5e0731fc0718a9e74e2def4c0bc
e15e033b5a31812087758f1db957165961c1526f
/include/Layout.h
a193d50e481c612e5b84985e188e12524d37339d
[ "MIT" ]
permissive
Groszek97/carpglib
9f734baf339dd8b343ad39da6ca099baa767fe0c
435e611d0e137710770628c89ab64a96abc0524a
refs/heads/master
2023-03-04T07:54:25.450445
2021-02-15T17:48:39
2021-02-15T18:41:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,784
h
#pragma once //----------------------------------------------------------------------------- #include "Control.h" //----------------------------------------------------------------------------- struct AreaLayout { friend class LayoutLoader; enum class Mode { None, Color, BorderColor, Image, Item }; Mode mode; Color color; union { struct { Color border_color; int width; }; struct { Texture* tex; Box2d region; Color background_color; }; }; Int2 size; AreaLayout() : mode(Mode::None) {} explicit AreaLayout(Color color) : mode(Mode::Color), color(color) {} AreaLayout(Color color, Color border_color, int width = 1) : mode(Mode::BorderColor), color(color), border_color(border_color), width(width) {} explicit AreaLayout(Texture* tex, Color color = Color::White) : mode(Mode::Image), tex(tex), color(color), background_color(Color::None), region(0, 0, 1, 1) { SetFromArea(nullptr); } AreaLayout(Texture* tex, const Box2d& region) : mode(Mode::Image), tex(tex), color(Color::White), background_color(Color::White), region(region) {} AreaLayout(Texture* tex, const Rect& area) : mode(Mode::Image), tex(tex), color(Color::White), background_color(Color::None) { SetFromArea(&area); } AreaLayout(Texture* tex, int corner, int size, Color color = Color::White) : mode(Mode::Item), tex(tex), size(corner, size), color(color) {} AreaLayout(const AreaLayout& l) : mode(l.mode), color(l.color), size(l.size) { memcpy(&tex, &l.tex, sizeof(Texture*) + sizeof(Box2d) + sizeof(Color)); } AreaLayout& operator = (const AreaLayout& l) { mode = l.mode; color = l.color; size = l.size; memcpy(&tex, &l.tex, sizeof(Texture*) + sizeof(Box2d) + sizeof(Color)); return *this; } private: void SetFromArea(const Rect* area); }; //----------------------------------------------------------------------------- namespace layout { struct Control { }; struct Gui : public Control { TexturePtr cursor[CURSOR_MAX]; }; } //----------------------------------------------------------------------------- class Layout { friend class LayoutLoader; public: Layout(Gui* gui); ~Layout(); layout::Control* Get(const type_info& type); template<typename T> T* Get() { return static_cast<T*>(Get(typeid(T))); } private: Gui* gui; std::unordered_map<std::type_index, layout::Control*> types; }; //----------------------------------------------------------------------------- template<typename T> class LayoutControl { friend class Gui; public: LayoutControl() : layout(Control::gui->GetLayout()->Get<T>()) {} T* GetLayout() const { return layout; } void SetLayout(T* layout) { if(layout) this->layout = layout; else this->layout = Control::gui->GetLayout()->Get<T>(); } protected: T* layout; };
[ "tomash4my@gmail.com" ]
tomash4my@gmail.com
63b92cdb3a532b06b29ceda0a0c1d0f9f5b56aa8
28cd7ed72e8e62d492ea7f2b1b67280e572ec8ff
/chrome/browser/android/compositor/layer/tab_layer.cc
687c86159c47189af2d80d389342681f77caf898
[ "BSD-3-Clause" ]
permissive
zjkdragon/chromium
e38f511bd32065ab32310ab45ea2b5638cc84761
22884a52a77e3947f0f9327a81220d9016ca240f
refs/heads/master
2022-11-08T20:44:02.950873
2020-07-02T14:11:47
2020-07-02T14:11:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,343
cc
// Copyright 2014 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 "chrome/browser/android/compositor/layer/tab_layer.h" #include <vector> #include "base/i18n/rtl.h" #include "cc/layers/layer.h" #include "cc/layers/layer_collections.h" #include "cc/layers/nine_patch_layer.h" #include "cc/layers/solid_color_layer.h" #include "cc/layers/ui_resource_layer.h" #include "cc/resources/scoped_ui_resource.h" #include "chrome/browser/android/compositor/decoration_title.h" #include "chrome/browser/android/compositor/layer/content_layer.h" #include "chrome/browser/android/compositor/layer/tabgroup_content_layer.h" #include "chrome/browser/android/compositor/layer/toolbar_layer.h" #include "chrome/browser/android/compositor/layer_title_cache.h" #include "chrome/browser/android/compositor/tab_content_manager.h" #include "ui/android/resources/nine_patch_resource.h" #include "ui/android/resources/resource_manager.h" #include "ui/base/l10n/l10n_util_android.h" #include "ui/gfx/geometry/insets_f.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/transform.h" namespace android { // static scoped_refptr<TabLayer> TabLayer::Create( bool incognito, ui::ResourceManager* resource_manager, LayerTitleCache* layer_title_cache, TabContentManager* tab_content_manager) { return base::WrapRefCounted(new TabLayer( incognito, resource_manager, layer_title_cache, tab_content_manager)); } // static void TabLayer::ComputePaddingPositions(const gfx::Size& content_size, const gfx::Size& desired_size, gfx::Rect* side_padding_rect, gfx::Rect* bottom_padding_rect) { if (content_size.width() < desired_size.width()) { side_padding_rect->set_x(content_size.width()); side_padding_rect->set_width(desired_size.width() - content_size.width()); // Restrict the side padding height to avoid overdrawing when both the side // and bottom padding are used. side_padding_rect->set_height(std::min(content_size.height(), desired_size.height())); } if (content_size.height() < desired_size.height()) { bottom_padding_rect->set_y(content_size.height()); // The side padding height is restricted to the min of bounds.height() and // desired_bounds.height(), so it will not extend all the way to the bottom // of the desired_bounds. The width of the bottom padding is set at // desired_bounds.width() so that there is not a hole where the side padding // stops. bottom_padding_rect->set_width(desired_size.width()); bottom_padding_rect->set_height( desired_size.height() - content_size.height()); } } static void PositionPadding(scoped_refptr<cc::SolidColorLayer> padding_layer, gfx::Rect padding_rect, float content_scale, float alpha, gfx::PointF content_position, gfx::RectF descaled_local_content_area) { if (padding_rect.IsEmpty()) { padding_layer->SetHideLayerAndSubtree(true); return; } padding_layer->SetHideLayerAndSubtree(false); padding_layer->SetBounds(padding_rect.size()); padding_layer->SetOpacity(alpha); gfx::Transform transform; transform.Scale(content_scale, content_scale); transform.Translate(padding_rect.x() + content_position.x(), padding_rect.y() + content_position.y()); transform.Translate(descaled_local_content_area.x(), descaled_local_content_area.y()); padding_layer->SetTransformOrigin(gfx::Point3F(0.f, 0.f, 0.f)); padding_layer->SetTransform(transform); } void TabLayer::SetProperties(int id, const std::vector<int>& ids, bool can_use_live_layer, int toolbar_resource_id, int close_button_resource_id, int shadow_resource_id, int contour_resource_id, int back_logo_resource_id, int border_resource_id, int border_inner_shadow_resource_id, int default_background_color, int back_logo_color, bool close_button_on_right, float x, float y, float width, float height, float shadow_x, float shadow_y, float shadow_width, float shadow_height, float pivot_x, float pivot_y, float rotation_x, float rotation_y, float alpha, float border_alpha, float border_inner_shadow_alpha, float contour_alpha, float shadow_alpha, float close_alpha, float border_scale, float saturation, float brightness, float close_btn_width, float close_btn_asset_size, float static_to_view_blend, float content_width, float content_height, float view_width, float view_height, bool show_toolbar, int default_theme_color, int toolbar_background_color, int close_button_color, bool anonymize_toolbar, bool show_tab_title, int toolbar_textbox_resource_id, int toolbar_textbox_background_color, float toolbar_textbox_alpha, float toolbar_alpha, float content_offset, float side_border_scale, bool inset_border) { if (alpha <= 0) { layer_->SetHideLayerAndSubtree(true); return; } layer_->SetHideLayerAndSubtree(false); // Grab required resources ui::NinePatchResource* border_resource = ui::NinePatchResource::From(resource_manager_->GetStaticResourceWithTint( border_resource_id, default_theme_color)); ui::NinePatchResource* border_inner_shadow_resource = ui::NinePatchResource::From(resource_manager_->GetResource( ui::ANDROID_RESOURCE_TYPE_STATIC, border_inner_shadow_resource_id)); ui::NinePatchResource* shadow_resource = ui::NinePatchResource::From(resource_manager_->GetResource( ui::ANDROID_RESOURCE_TYPE_STATIC, shadow_resource_id)); ui::NinePatchResource* contour_resource = ui::NinePatchResource::From(resource_manager_->GetResource( ui::ANDROID_RESOURCE_TYPE_STATIC, contour_resource_id)); ui::Resource* close_btn_resource = resource_manager_->GetStaticResourceWithTint(close_button_resource_id, close_button_color); ui::Resource* back_logo_resource = nullptr; DecorationTitle* title_layer = nullptr; //---------------------------------------------------------------------------- // Handle Border Scaling (Upscale/Downscale everything until final scaling) //---------------------------------------------------------------------------- width /= border_scale; height /= border_scale; shadow_x /= border_scale; shadow_y /= border_scale; shadow_width /= border_scale; shadow_height /= border_scale; //---------------------------------------------------------------------------- // Precalculate Helper Values //---------------------------------------------------------------------------- const gfx::RectF border_padding(border_resource->padding()); const gfx::RectF border_inner_shadow_padding( border_inner_shadow_resource->padding()); const gfx::RectF shadow_padding(shadow_resource->padding()); const gfx::RectF contour_padding(contour_resource->padding()); const bool back_visible = cos(rotation_x * SK_ScalarPI / 180.0f) < 0 || cos(rotation_y * SK_ScalarPI / 180.0f) < 0; const float content_scale = width / content_width; gfx::RectF content_area(0.f, 0.f, content_width, content_height); gfx::RectF scaled_local_content_area(shadow_x, shadow_y, shadow_width, shadow_height); gfx::RectF descaled_local_content_area( scaled_local_content_area.x() / content_scale, scaled_local_content_area.y() / content_scale, scaled_local_content_area.width() / content_scale, scaled_local_content_area.height() / content_scale); const gfx::Size shadow_padding_size( shadow_resource->size().width() - shadow_padding.width(), shadow_resource->size().height() - shadow_padding.height()); const gfx::Size border_padding_size( border_resource->size().width() - border_padding.width(), border_resource->size().height() - border_padding.height()); const gfx::Size border_inner_shadow_padding_size( border_inner_shadow_resource->size().width() - border_inner_shadow_padding.width(), border_inner_shadow_resource->size().height() - border_inner_shadow_padding.height()); const gfx::Size contour_padding_size( contour_resource->size().width() - contour_padding.width(), contour_resource->size().height() - contour_padding.height()); const float close_btn_effective_width = close_btn_width * close_alpha; //-------------------------------------------------------------------------- // Update Resource Ids For Layers That Impact Layout //-------------------------------------------------------------------------- // TODO(kkimlabs): Tab switcher doesn't show the progress bar. toolbar_layer_->PushResource( toolbar_resource_id, toolbar_background_color, anonymize_toolbar, toolbar_textbox_background_color, toolbar_textbox_resource_id, toolbar_textbox_alpha, view_height, content_offset, false, false); toolbar_layer_->UpdateProgressBar(0, 0, 0, 0, 0, 0, 0, 0, 0, 0); float toolbar_impact_height = 0; if (show_toolbar && !back_visible) toolbar_impact_height = content_offset; //---------------------------------------------------------------------------- // Compute Alpha and Visibility //---------------------------------------------------------------------------- border_alpha *= alpha; contour_alpha *= alpha; shadow_alpha *= alpha; close_alpha *= alpha; toolbar_alpha *= alpha; if (back_visible) { border_alpha = 0.f; border_inner_shadow_alpha = 0.f; } bool border_visible = border_alpha > 0.f; bool border_inner_shadow_visible = border_inner_shadow_alpha > 0.f; bool contour_visible = border_alpha < contour_alpha && contour_alpha > 0.f; bool shadow_visible = shadow_alpha > 0.f && border_alpha > 0.f; //---------------------------------------------------------------------------- // Compute Layer Sizes //---------------------------------------------------------------------------- gfx::Size shadow_size(width + shadow_padding_size.width() * side_border_scale, height + shadow_padding_size.height()); gfx::Size border_size(width + border_padding_size.width() * side_border_scale, height + border_padding_size.height()); gfx::Size border_inner_shadow_size( width + border_inner_shadow_padding_size.width(), height + border_inner_shadow_padding_size.height()); gfx::Size contour_size( width + contour_padding_size.width() * side_border_scale, height + contour_padding_size.height()); gfx::Size close_button_size(close_btn_width, border_padding.y()); gfx::Size title_size(width - close_btn_effective_width, border_padding.y()); gfx::Size back_logo_size; // TODO(clholgat): Figure out why the back logo is null sometimes. if (back_visible) { back_logo_resource = resource_manager_->GetResource(ui::ANDROID_RESOURCE_TYPE_STATIC, back_logo_resource_id); if (back_logo_resource) back_logo_size = back_logo_resource->size(); } // Store this size at a point as it might go negative during the inset // calculations. gfx::Point desired_content_size_pt( descaled_local_content_area.width(), descaled_local_content_area.height() - toolbar_impact_height); // Shrink the toolbar layer so we properly clip if it's offset. gfx::Size toolbar_size(toolbar_layer_->layer()->bounds().width(), toolbar_layer_->layer()->bounds().height()); //---------------------------------------------------------------------------- // Compute Layer Positions //---------------------------------------------------------------------------- gfx::PointF shadow_position(-shadow_padding.x() * side_border_scale, -shadow_padding.y()); gfx::PointF border_position(-border_padding.x() * side_border_scale, -border_padding.y()); gfx::PointF border_inner_shadow_position(-border_inner_shadow_padding.x(), -border_inner_shadow_padding.y()); gfx::PointF contour_position(-contour_padding.x() * side_border_scale, -contour_padding.y()); gfx::PointF toolbar_position( 0.f, toolbar_layer_->layer()->bounds().height() - toolbar_size.height()); gfx::PointF content_position(0.f, toolbar_impact_height); gfx::PointF back_logo_position( ((descaled_local_content_area.width() - back_logo_->bounds().width()) * content_scale) / 2.0f, ((descaled_local_content_area.height() - back_logo_->bounds().height()) * content_scale) / 2.0f); gfx::PointF close_button_position; gfx::PointF title_position; close_button_position.set_y(-border_padding.y()); title_position.set_y(-border_padding.y()); if (close_button_on_right) close_button_position.set_x(width - close_button_size.width()); else title_position.set_x(close_btn_effective_width); //---------------------------------------------------------------------------- // Center Specific Assets in the Rects //---------------------------------------------------------------------------- close_button_position.Offset( (close_button_size.width() - close_btn_asset_size) / 2.f, (close_button_size.height() - close_btn_asset_size) / 2.f); close_button_size.SetSize(close_btn_asset_size, close_btn_asset_size); //---------------------------------------------------------------------------- // Handle Insetting the Top Border Component //---------------------------------------------------------------------------- if (inset_border) { float inset_diff = inset_border ? border_padding.y() : 0.f; descaled_local_content_area.set_height( descaled_local_content_area.height() - inset_diff); scaled_local_content_area.set_height(scaled_local_content_area.height() - inset_diff * content_scale); shadow_size.set_height(shadow_size.height() - inset_diff); border_size.set_height(border_size.height() - inset_diff); border_inner_shadow_size.set_height(border_inner_shadow_size.height() - inset_diff); contour_size.set_height(contour_size.height() - inset_diff); shadow_position.set_y(shadow_position.y() + inset_diff); border_position.set_y(border_position.y() + inset_diff); border_inner_shadow_position.set_y(border_inner_shadow_position.y() + inset_diff); contour_position.set_y(contour_position.y() + inset_diff); close_button_position.set_y(close_button_position.y() + inset_diff); title_position.set_y(title_position.y() + inset_diff); // Scaled eventually, so have to descale the size difference first. toolbar_position.set_y(toolbar_position.y() + inset_diff / content_scale); content_position.set_y(content_position.y() + inset_diff / content_scale); desired_content_size_pt.set_y(desired_content_size_pt.y() - inset_diff / content_scale); } const bool inset_toolbar = !inset_border; if (!inset_toolbar) { float inset_diff = toolbar_impact_height; toolbar_position.set_y(toolbar_position.y() - inset_diff); content_position.set_y(content_position.y() - inset_diff); desired_content_size_pt.set_y(desired_content_size_pt.y() + inset_diff); } // Finally build the sizes that might have calculations that go negative. gfx::Size desired_content_size(desired_content_size_pt.x(), desired_content_size_pt.y()); //---------------------------------------------------------------------------- // Calculate Content Visibility //---------------------------------------------------------------------------- // Check if the rect we are drawing is larger than the content rect. bool content_visible = desired_content_size.GetArea() > 0.f; // TODO(dtrainor): Improve these calculations to prune these layers out. bool title_visible = border_alpha > 0.f && !back_visible && show_tab_title; bool close_btn_visible = title_visible; bool toolbar_visible = show_toolbar && toolbar_alpha > 0.f && !back_visible; //---------------------------------------------------------------------------- // Fix jaggies //---------------------------------------------------------------------------- border_position.Offset(0.5f, 0.5f); border_inner_shadow_position.Offset(0.5f, 0.5f); shadow_position.Offset(0.5f, 0.5f); contour_position.Offset(0.5f, 0.5f); title_position.Offset(0.5f, 0.5f); close_button_position.Offset(0.5f, 0.5f); toolbar_position.Offset(0.5f, 0.5f); border_size.Enlarge(-1.f, -1.f); border_inner_shadow_size.Enlarge(-1.f, -1.f); shadow_size.Enlarge(-1.f, -1.f); //---------------------------------------------------------------------------- // Update Resource Ids //---------------------------------------------------------------------------- shadow_->SetUIResourceId(shadow_resource->ui_resource()->id()); shadow_->SetBorder(shadow_resource->Border(shadow_size)); shadow_->SetAperture(shadow_resource->aperture()); contour_shadow_->SetUIResourceId(contour_resource->ui_resource()->id()); contour_shadow_->SetBorder(contour_resource->Border(contour_size)); contour_shadow_->SetAperture(contour_resource->aperture()); front_border_->SetUIResourceId(border_resource->ui_resource()->id()); front_border_->SetAperture(border_resource->aperture()); front_border_->SetBorder(border_resource->Border( border_size, gfx::InsetsF(1.f, side_border_scale, 1.f, side_border_scale))); front_border_inner_shadow_->SetUIResourceId( border_inner_shadow_resource->ui_resource()->id()); front_border_inner_shadow_->SetAperture( border_inner_shadow_resource->aperture()); front_border_inner_shadow_->SetBorder(border_inner_shadow_resource->Border( border_inner_shadow_size)); side_padding_->SetBackgroundColor(back_visible ? back_logo_color : default_background_color); bottom_padding_->SetBackgroundColor(back_visible ? back_logo_color : default_background_color); if (title_visible && layer_title_cache_) title_layer = layer_title_cache_->GetTitleLayer(id); SetTitle(title_layer); close_button_->SetUIResourceId(close_btn_resource->ui_resource()->id()); if (!back_visible) { gfx::Rect rounded_descaled_content_area( round(descaled_local_content_area.x()), round(descaled_local_content_area.y()), round(desired_content_size.width()), round(desired_content_size.height())); SetContentProperties( id, ids, can_use_live_layer, static_to_view_blend, true, alpha, saturation, true, rounded_descaled_content_area, border_inner_shadow_resource, border_inner_shadow_alpha); } else if (back_logo_resource) { back_logo_->SetUIResourceId(back_logo_resource->ui_resource()->id()); } //---------------------------------------------------------------------------- // Push Size, Position, Alpha and Transformations to Layers //---------------------------------------------------------------------------- shadow_->SetHideLayerAndSubtree(!shadow_visible); if (shadow_visible) { shadow_->SetPosition(shadow_position); shadow_->SetBounds(shadow_size); shadow_->SetOpacity(shadow_alpha); } contour_shadow_->SetHideLayerAndSubtree(!contour_visible); if (contour_visible) { contour_shadow_->SetPosition(contour_position); contour_shadow_->SetBounds(contour_size); contour_shadow_->SetOpacity(contour_alpha); } front_border_->SetHideLayerAndSubtree(!border_visible); if (border_visible) { front_border_->SetPosition(border_position); front_border_->SetBounds(border_size); front_border_->SetOpacity(border_alpha); front_border_->SetNearestNeighbor(toolbar_visible); } front_border_inner_shadow_->SetHideLayerAndSubtree( !border_inner_shadow_visible); if (border_inner_shadow_visible) { front_border_inner_shadow_->SetPosition(border_inner_shadow_position); front_border_inner_shadow_->SetBounds(border_inner_shadow_size); front_border_inner_shadow_->SetOpacity(border_inner_shadow_alpha); } toolbar_layer_->layer()->SetHideLayerAndSubtree(!toolbar_visible); if (toolbar_visible) { // toolbar_ Transform gfx::Transform transform; transform.Scale(content_scale, content_scale); transform.Translate(toolbar_position.x(), toolbar_position.y()); toolbar_layer_->layer()->SetTransformOrigin(gfx::Point3F(0.f, 0.f, 0.f)); toolbar_layer_->layer()->SetTransform(transform); toolbar_layer_->SetOpacity(toolbar_alpha); toolbar_layer_->layer()->SetMasksToBounds( toolbar_layer_->layer()->bounds() != toolbar_size); toolbar_layer_->layer()->SetBounds(toolbar_size); } if (title_layer) { gfx::PointF vertically_centered_position( title_position.x(), title_position.y() + (title_size.height() - title_layer->size().height()) / 2.f); title_->SetPosition(vertically_centered_position); title_layer->setBounds(title_size); title_layer->setOpacity(border_alpha); } close_button_->SetHideLayerAndSubtree(!close_btn_visible); if (close_btn_visible) { close_button_->SetPosition(close_button_position); close_button_->SetBounds(close_button_size); // Non-linear alpha looks better. close_button_->SetOpacity(close_alpha * close_alpha * border_alpha); } if (content_visible) { { // content_ and back_logo_ Transforms gfx::Transform transform; transform.Scale(content_scale, content_scale); transform.Translate(content_position.x(), content_position.y()); transform.Translate(descaled_local_content_area.x(), descaled_local_content_area.y()); content_->layer()->SetHideLayerAndSubtree(back_visible); back_logo_->SetHideLayerAndSubtree(!back_visible); if (!back_visible) { content_->layer()->SetTransformOrigin(gfx::Point3F(0.f, 0.f, 0.f)); content_->layer()->SetTransform(transform); } else { back_logo_->SetPosition(back_logo_position); back_logo_->SetBounds(back_logo_size); back_logo_->SetTransformOrigin(gfx::Point3F(0.f, 0.f, 0.f)); back_logo_->SetTransform(transform); // TODO: Set back logo alpha on leaf. } } { // padding_ Transform gfx::Size content_bounds; if (!back_visible) content_bounds = content_->ComputeSize(id); gfx::Rect side_padding_rect; gfx::Rect bottom_padding_rect; if (content_bounds.width() == 0 || content_bounds.height() == 0) { // If content_ has 0 width or height, use the side padding to fill // the desired_content_size. side_padding_rect.set_size(desired_content_size); } else { ComputePaddingPositions(content_bounds, desired_content_size, &side_padding_rect, &bottom_padding_rect); } PositionPadding(side_padding_, side_padding_rect, content_scale, alpha, content_position, descaled_local_content_area); PositionPadding(bottom_padding_, bottom_padding_rect, content_scale, alpha, content_position, descaled_local_content_area); } } else { back_logo_->SetHideLayerAndSubtree(true); side_padding_->SetHideLayerAndSubtree(true); bottom_padding_->SetHideLayerAndSubtree(true); content_->layer()->SetHideLayerAndSubtree(true); } { // Global Transform gfx::PointF pivot_origin(pivot_y, pivot_x); gfx::Transform transform; if (rotation_x != 0 || rotation_y != 0) { // Apply screen perspective if there are rotations. transform.Translate(content_width / 2, content_height / 2); transform.ApplyPerspectiveDepth( content_width > content_height ? content_width : content_height); transform.Translate(-content_width / 2, -content_height / 2); // Translate to correct position on the screen transform.Translate(x, y); // Apply pivot rotations transform.Translate(pivot_origin.x(), pivot_origin.y()); transform.RotateAboutYAxis(rotation_y); transform.RotateAboutXAxis(-rotation_x); transform.Translate(-pivot_origin.x(), -pivot_origin.y()); } else { // Translate to correct position on the screen transform.Translate(x, y); } transform.Scale(border_scale, border_scale); layer_->SetTransform(transform); } // Only applies the brightness filter if the value has changed and is less // than 1. if (brightness != brightness_) { brightness_ = brightness; cc::FilterOperations filters; if (brightness_ < 1.f) filters.Append(cc::FilterOperation::CreateBrightnessFilter(brightness_)); layer_->SetFilters(filters); } } scoped_refptr<cc::Layer> TabLayer::layer() { return layer_; } TabLayer::TabLayer(bool incognito, ui::ResourceManager* resource_manager, LayerTitleCache* layer_title_cache, TabContentManager* tab_content_manager) : incognito_(incognito), resource_manager_(resource_manager), tab_content_manager_(tab_content_manager), layer_title_cache_(layer_title_cache), layer_(cc::Layer::Create()), toolbar_layer_(ToolbarLayer::Create(resource_manager)), title_(cc::Layer::Create()), content_(ContentLayer::Create(tab_content_manager)), side_padding_(cc::SolidColorLayer::Create()), bottom_padding_(cc::SolidColorLayer::Create()), close_button_(cc::UIResourceLayer::Create()), front_border_(cc::NinePatchLayer::Create()), front_border_inner_shadow_(cc::NinePatchLayer::Create()), contour_shadow_(cc::NinePatchLayer::Create()), shadow_(cc::NinePatchLayer::Create()), back_logo_(cc::UIResourceLayer::Create()), brightness_(1.f) { layer_->AddChild(shadow_); layer_->AddChild(contour_shadow_); layer_->AddChild(side_padding_); layer_->AddChild(bottom_padding_); layer_->AddChild(content_->layer()); layer_->AddChild(back_logo_); layer_->AddChild(front_border_inner_shadow_); layer_->AddChild(front_border_); layer_->AddChild(title_.get()); layer_->AddChild(close_button_); layer_->AddChild(toolbar_layer_->layer()); contour_shadow_->SetIsDrawable(true); side_padding_->SetIsDrawable(true); bottom_padding_->SetIsDrawable(true); front_border_->SetIsDrawable(true); front_border_inner_shadow_->SetIsDrawable(true); shadow_->SetIsDrawable(true); close_button_->SetIsDrawable(true); back_logo_->SetIsDrawable(true); front_border_->SetFillCenter(false); } TabLayer::~TabLayer() { } void TabLayer::SetTitle(DecorationTitle* title) { scoped_refptr<cc::Layer> layer = title ? title->layer() : nullptr; if (!layer.get()) { title_->RemoveAllChildren(); } else { const cc::LayerList& children = title_->children(); if (children.size() == 0 || children[0]->id() != layer->id()) { title_->RemoveAllChildren(); title_->AddChild(layer); } } if (title) title->SetUIResourceIds(); } void TabLayer::SetContentProperties( int id, const std::vector<int>& tab_ids, bool can_use_live_layer, float static_to_view_blend, bool should_override_content_alpha, float content_alpha_override, float saturation, bool should_clip, const gfx::Rect& clip, ui::NinePatchResource* inner_shadow_resource, float inner_shadow_alpha) { if (tab_ids.size() == 0) { content_->SetProperties(id, can_use_live_layer, static_to_view_blend, should_override_content_alpha, content_alpha_override, saturation, should_clip, clip); } else { scoped_refptr<TabGroupContentLayer> tabgroup_content_layer = TabGroupContentLayer::Create(tab_content_manager_); layer_->ReplaceChild(content_->layer().get(), tabgroup_content_layer->layer()); content_ = tabgroup_content_layer; tabgroup_content_layer->SetProperties( id, tab_ids, can_use_live_layer, static_to_view_blend, should_override_content_alpha, content_alpha_override, saturation, should_clip, clip, inner_shadow_resource, inner_shadow_alpha); front_border_inner_shadow_->SetIsDrawable(false); } } } // namespace android
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
415119511a0ee2dd4a524afa6b3285477119751e
7ea7161be9b23dfcb1a694f28702e62a414985d7
/tests/json.cpp
a0517dcfb991f0c6f897a7cb18dbe805b5db11a1
[]
no_license
veracioux/siau-devlib
a7afc597833cf4a21f6871411b2c92392798c595
fc136996da3b116ca8ba99d628f4ae3fe48cada9
refs/heads/master
2023-08-22T18:16:01.210590
2021-09-23T23:00:04
2021-09-23T23:00:04
338,467,212
0
0
null
null
null
null
UTF-8
C++
false
false
6,063
cpp
#include <QtTest/QtTest> #include "json.h" #include <QByteArray> #include <QDir> #include <QFile> #include <QJsonObject> #include <iostream> #include <limits> #include <unistd.h> using namespace Devlib; namespace Devlib { extern QJsonObject jsonObjectFromFile(const QString&); } class TestJson : public QObject { Q_OBJECT ValueSpec specFromFile(const QString& path) { auto obj = jsonObjectFromFile(path); return jsonParseValueSpec(obj); } private slots: void testValueSpecEmpty() { auto spec = specFromFile("valuespec/empty.json"); QVERIFY(spec.isVoid()); QVERIFY(spec.getValueRange().isEmpty()); QVERIFY(spec.getUnit().isEmpty()); } void testValueSpecBool() { auto spec = specFromFile("valuespec/bool.json"); QVERIFY(spec.isBool()); QVERIFY(spec.getValueRange().isEmpty()); } void testValueSpecFloat() { auto spec = specFromFile("valuespec/float.json"); QVERIFY(spec.isFloat()); QCOMPARE(spec.getMinFloat(), 0.3f); QCOMPARE(spec.getMaxFloat(), 2.3f); } void testValueSpecCustomEnum() { auto spec = specFromFile("valuespec/enum.json"); QVERIFY(spec.isCustomEnum()); QCOMPARE(spec.getValueType(), "Status"); QCOMPARE(spec.getValueRange(), (QStringList{"On", "Off"})); } void testValueSpecFloat_OnlyType() { auto spec = specFromFile("valuespec/float_only_type.json"); QVERIFY(spec.isFloat()); QVERIFY(qIsNaN(spec.getMinFloat())); QVERIFY(qIsNaN(spec.getMaxFloat())); } void testValueSpecInt() { auto spec = specFromFile("valuespec/int.json"); QVERIFY(spec.isInt()); QCOMPARE(spec.getMinInt(), -4); QCOMPARE(spec.getMaxInt(), 10); QCOMPARE(spec.getUnit(), "%"); } void testValueSpecInt_OnlyType() { auto spec = specFromFile("valuespec/int_only_type.json"); QVERIFY(spec.isInt()); QCOMPARE(spec.getMinInt(), std::numeric_limits<int>::min()); QCOMPARE(spec.getMaxInt(), std::numeric_limits<int>::max()); QVERIFY(spec.getUnit().isEmpty()); } void testValueSpecWrongAttributeTypes() { QJsonObject obj = jsonObjectFromFile("valuespec/wrong_attributes.json"); foreach (const QString& attr, obj.keys()) { QVERIFY_EXCEPTION_THROWN( jsonParseValueSpec(obj.value(attr).toObject()), std::runtime_error); } } void testValueSpecIntegrated() { auto spec = specFromFile("function/single.json"); QVERIFY(spec.isFloat()); QCOMPARE(spec.getMinFloat(), 0); QCOMPARE(spec.getMaxFloat(), 100); QCOMPARE(spec.getUnit(), "%"); } void testData() { auto obj = jsonObjectFromFile("data/data.json"); Data* data = jsonParseData(obj); QCOMPARE(data->getName(), "AnInt"); QCOMPARE(data->getFriendlyName(), "An integer"); ValueSpec spec = data->getValueSpec(); QVERIFY(spec.isInt()); QCOMPARE(spec.getValueRange(), (QStringList{ "-5", "40" })); QCOMPARE(spec.getUnit(), "%"); delete data; } void testSingleFunction() { auto obj = jsonObjectFromFile("function/single.json"); SingleFunction* function = jsonParseFunction(obj); QCOMPARE(function->getName(), "setBrightness"); QCOMPARE(function->getFriendlyName(), "Set Brightness"); ValueSpec spec = function->getValueSpec(); QVERIFY(spec.isFloat()); QCOMPARE(spec.getValueRange(), (QStringList{ "0", "100" })); QCOMPARE(spec.getUnit(), "%"); delete function; } void testMultiFunction() { auto obj = jsonObjectFromFile("function/multi.json"); QJsonArray multiFunction = obj["function"].toArray(); MultiFunction *mfun = jsonParseFunction(multiFunction); auto sfunList = mfun->getSingleFunctions(); QCOMPARE(sfunList.size(), 2); SingleFunction *sfun1 = sfunList[0], *sfun2 = sfunList[1]; QCOMPARE(sfun1->getName(), "turnOn"); QVERIFY(sfun1->getValueSpec().isVoid()); QCOMPARE(sfun2->getName(), "turnOff"); QVERIFY(sfun2->getValueSpec().isVoid()); } void testDevice() { Device device = jsonParseDevice("device/device.json"); QCOMPARE(device.getName(), "TestDevice"); QCOMPARE(device.getVendorId(), "ETF"); QCOMPARE(device.getModel(), "Model-X"); QCOMPARE(device["deviceType"], "Generic"); // TODO QList<Function*> functions = device.getFunctions(); QVERIFY(functions.length() == 2); QVERIFY(functions[0]->isSingleFunction()); SingleFunction* sfun = dynamic_cast<SingleFunction*>(functions[0]); QVERIFY(sfun != nullptr); QCOMPARE(sfun->getName(), "setBrightness"); QCOMPARE(sfun->getFriendlyName(), "Set Brightness"); auto valueSpec = sfun->getValueSpec(); QVERIFY(valueSpec.isFloat()); QCOMPARE(valueSpec.getValueRange(), (QStringList{ "0", "100" })); QCOMPARE(valueSpec.getUnit(), "%"); MultiFunction* mfun = dynamic_cast<MultiFunction*>(functions[1]); SingleFunction *sfun1 = mfun->getSingleFunctions()[0], *sfun2 = mfun->getSingleFunctions()[1]; QVERIFY(mfun != nullptr); QCOMPARE(sfun1->getName(), "turnOn"); QVERIFY(sfun1->getValueSpec().isVoid()); QCOMPARE(sfun2->getName(), "turnOff"); QVERIFY(sfun2->getValueSpec().isVoid()); QList<Data*> data = device.getData(); QVERIFY(data.length() == 1); QCOMPARE(data[0]->getName(), "getBrightness"); QCOMPARE(data[0]->getFriendlyName(), "Brightness"); valueSpec = data[0]->getValueSpec(); QVERIFY(valueSpec.isInt()); QCOMPARE(valueSpec.getValueRange(), (QStringList{ "-5", "40" })); QCOMPARE(valueSpec.getUnit(), "%"); } }; QTEST_MAIN(TestJson) #include "json.moc"
[ "harisgusic.dev@gmail.com" ]
harisgusic.dev@gmail.com
d0ff6e3b4e4cea763048beea9bb822c91b72edec
9934512da4a541a3e6654dd3a71512df9a9bfe14
/SRAAM6/tvc.cpp
413b8e8cc56eed7f0a8e9aabbb6e8f75a6e59de9
[]
no_license
missiondesignsolutions/CADAC
a534eda151c6d8d3afba8e5d48d60201a2a591ff
8aa2f73e551554a48abeac5416d1ec3a34ae660f
refs/heads/main
2023-05-01T04:32:40.710534
2021-05-24T07:44:03
2021-05-24T07:44:03
370,660,263
3
1
null
2021-05-25T10:55:36
2021-05-25T10:55:36
null
UTF-8
C++
false
false
8,180
cpp
/////////////////////////////////////////////////////////////////////////////// //FILE: 'tvc.cpp' //Contains 'tvc' module of class 'Missile' // //030608 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// #include "class_hierarchy.hpp" /////////////////////////////////////////////////////////////////////////////// //Definition of TVC (thrust vector control) module-variables //Member function of class 'Missile' //Module-variable locations are assigned to missile[700-749] // // mtvc=0 No TVC // =1 No dynamics // =2 TVC Second order dynamics with rate limiting // =3 same as 2 but with inline TVC gain // //030608 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// void Missile::def_tvc() { //Definition and initialization of module-variables missile[700].init("mtvc","int",0,"=0:no TVC;=1:no dyn;=2:scnd order;=3:2+gain","tvc","data",""); missile[702].init("tvclimx",0,"Nozzle deflection limiter - deg","tvc","data",""); missile[704].init("dtvclimx",0,"Nozzle deflection rate limiter - deg/s","tvc","data",""); missile[705].init("wntvc",0,"Natural frequency of TVC - rad/s","tvc","data",""); missile[706].init("zettvc",0,"Damping of TVC - ND","tvc","data",""); missile[707].init("factgtvc",0,"Factor for TVC gain - ND","tvc","data",""); missile[708].init("gtvc",0,"TVC nozzle deflection gain - ND","tvc","data,diag",""); missile[709].init("parm",0,"Propulsion moment arm from vehicle nose - m","tvc","data",""); missile[710].init("FPB",0,0,0,"Thrust force in body axes - N","tvc","out",""); missile[711].init("FMPB",0,0,0,"Thrust moment in body axes - Nm","tvc","out",""); missile[712].init("etax",0,"Nozzle pitch deflection - deg","tvc","diag","plot"); missile[713].init("zetx",0,"Nozzle yaw deflection - deg","tvc","diag","plot"); missile[714].init("etacx",0,"Commanded nozzle pitch deflection - deg","tvc","diag","plot"); missile[715].init("zetcx",0,"Commanded nozzle yaw deflection - deg","tvc","diag","plot"); missile[730].init("etasd",0,"Pitch nozzle derivative - rad/s","tvc","state",""); missile[731].init("zetad",0,"Yaw nozzle derivative - rad/s","tvc","state",""); missile[734].init("etas",0,"Pitch nozzle deflection - rad","tvc","state",""); missile[735].init("zeta",0,"Yaw nozzle deflection - rad","tvc","state",""); missile[738].init("detasd",0,"Pitch nozzle rate derivative - rad/s^2","tvc","state",""); missile[739].init("dzetad",0,"Yaw nozzle rate derivative - rad/s^2","tvc","state",""); missile[742].init("detas",0,"Pitch nozzle rate - rad/s","tvc","state","plot"); missile[743].init("dzeta",0,"Yaw nozzle rate - rad/s","tvc","state","plot"); } /////////////////////////////////////////////////////////////////////////////// //Actuator module //Member function of class 'Missile' // mtvc=0 No TVC // =1 No dynamics // =2 TVC Second order dynamics with rate limiting // =3 same as 2 but with inline TVC gain // // This subroutine performs the following functions: // (1) Converts from control commands to nozzle deflections // (2) Calls nozzle dynamic subroutine // //030608 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// void Missile::tvc(double int_step) { //local variables double eta(0),zet(0); //local module-variables Matrix FPB(3,1); Matrix FMPB(3,1); double etax(0),zetx(0); double etacx(0),zetcx(0); //localizing module-variables //input data int mtvc=missile[700].integer(); double factgtvc=missile[707].real(); double gtvc=missile[708].real(); double parm=missile[709].real(); //input from other modules double time=flat6[0].real(); double thrust=missile[63].real(); double xcg=missile[70].real(); double dqcx=missile[520].real(); double drcx=missile[521].real(); double pdynmc=flat6[57].real(); //------------------------------------------------------------------------- //return if no tvc if(mtvc==0) return; //variable nozzle reduction gain (low q, high gain) if(mtvc==3){ if(pdynmc>1e5) gtvc=0; else gtvc=(-5.e-6*pdynmc+0.5)*(factgtvc+1); } //reduction of nozzle deflection command double etac=gtvc*dqcx*RAD; double zetc=gtvc*drcx*RAD; //no nozzle dynamics if(mtvc==1){ eta=etac; zet=zetc; } //calling second order nozzle dynamics if(mtvc>=2) tvc_scnd(eta,zet,etac,zetc,int_step); //thrust forces in body axes double seta=sin(eta); double ceta=cos(eta); double czet=cos(zet); double szet=sin(zet); FPB[0]=ceta*czet*thrust; FPB[1]=ceta*szet*thrust; FPB[2]=-seta*thrust; //thrust moments in body axes double arm=parm-xcg; FMPB[0]=0; FMPB[1]=arm*FPB[2]; FMPB[2]=-arm*FPB[1]; //output etax=eta*DEG; zetx=zet*DEG; //diagnostic etacx=etac*DEG; zetcx=zetc*DEG; //------------------------------------------------------------------------- //loading module-variables //output to other modules missile[710].gets_vec(FPB); missile[711].gets_vec(FMPB); //diagnostics missile[712].gets(etax); missile[713].gets(zetx); missile[714].gets(etax); missile[715].gets(zetx); } /////////////////////////////////////////////////////////////////////////////// //Second order TVC //Member function of class 'Missile' // This subroutine performs the following functions: // (1) Models second order lags of pitch and yaw deflections // (2) Limits nozzle deflections // (3) Limits nozzle deflection rates // //Return output // eta=Nozzle pitch deflection - rad // zet=Nozzle yaw deflection - rad // Argument Input: // etac=Nozzle pitch command - rad // zetc=Nozzle yaw command - rad // //030608 Created by Peter H Zipfel /////////////////////////////////////////////////////////////////////////////// void Missile::tvc_scnd(double &eta,double &zet,double etac,double zetc,double int_step) { //localizing module-variables //input data double tvclimx=missile[702].real(); double dtvclimx=missile[704].real(); double wntvc=missile[705].real(); double zettvc=missile[706].real(); //input from other modules double time=flat6[0].real(); //state variables double etasd=missile[730].real(); double zetad=missile[731].real(); double etas=missile[734].real(); double zeta=missile[735].real(); double detasd=missile[738].real(); double dzetad=missile[739].real(); double detas=missile[742].real(); double dzeta=missile[743].real(); //------------------------------------------------------------------------- //pitch nozzle dynamics //limiting position and the nozzle rate derivative if(fabs(etas)>tvclimx*RAD){ etas=tvclimx*RAD*sign(etas); if(etas*detas>0.)detas=0.; } //limiting nozzle rate int iflag=0; if(fabs(detas)>dtvclimx*RAD){ iflag=1; detas=dtvclimx*RAD*sign(detas); } //state integration double etasd_new=detas; etas=integrate(etasd_new,etasd,etas,int_step); etasd=etasd_new; double eetas=etac-etas; double detasd_new=wntvc*wntvc*eetas-2.*zettvc*wntvc*etasd; detas=integrate(detasd_new,detasd,detas,int_step); detasd=detasd_new; //setting nozzle rate derivative to zero if rate is limited if(iflag&&detas*detasd>0.) detasd=0.; eta=etas; //yaw nozzle dynamics //limiting position and the nozzle rate derivative if(fabs(zeta)>tvclimx*RAD){ zeta=tvclimx*RAD*sign(zeta); if(zeta*dzeta>0.)dzeta=0.; } //limiting nozzle rate iflag=0; if(fabs(dzeta)>dtvclimx*RAD){ iflag=1; dzeta=dtvclimx*RAD*sign(dzeta); } //state integration double zetad_new=dzeta; zeta=integrate(zetad_new,zetad,zeta,int_step); zetad=zetad_new; double ezeta=zetc-zeta; double dzetad_new=wntvc*wntvc*ezeta-2.*zettvc*wntvc*zetad; dzeta=integrate(dzetad_new,dzetad,dzeta,int_step); dzetad=dzetad_new; //setting nozzle rate derivative to zero if rate is limited if(iflag&&dzeta*dzetad>0.) dzetad=0.; zet=zeta; //------------------------------------------------------------------------- //loading module-variables //state variables missile[730].gets(etasd); missile[731].gets(zetad); missile[734].gets(etas); missile[735].gets(zeta); missile[738].gets(detasd); missile[739].gets(dzetad); missile[742].gets(detas); missile[743].gets(dzeta); }
[ "rads2995@gmail.com" ]
rads2995@gmail.com
4ec50b0e70c55b96383ed909a59007f5156142e5
66deb611781cae17567efc4fd3717426d7df5e85
/pcmanager/src/import/kxe_improve_publish/scom/scom/scomdef.h
283f2e03842ae5ee167b9af487846f9aac188173
[ "Apache-2.0" ]
permissive
heguoxing98/knoss-pcmanager
4671548e14b8b080f2d3a9f678327b06bf9660c9
283ca2e3b671caa85590b0f80da2440a3fab7205
refs/heads/master
2023-03-19T02:11:01.833194
2020-01-03T01:45:24
2020-01-03T01:45:24
504,422,245
1
0
null
2022-06-17T06:40:03
2022-06-17T06:40:02
null
GB18030
C++
false
false
5,553
h
/******************************************************************** * CreatedOn: 2005-8-16 15:41 * FileName: SCOMDef.h * CreatedBy: qiuruifeng <qiuruifeng@kingsoft.net> * $LastChangedDate$ * $LastChangedRevision$ * $LastChangedBy$ * $HeadURL$ * Purpose: *********************************************************************/ #ifndef SCOMDEF_H #define SCOMDEF_H #include <cassert> #include "SCOMError.h" #include "Threads.h" #include "SCOMMsgAssert.h" #include "../../kxecommon/kxecommon.h" #ifdef WIN32 #pragma warning(disable: 4244) //disable warning C4244: conversion from 'int' to //'unsigned char', possible loss of data #if MSCVER >= 1400 #include <GuidDef.h> #endif #endif #ifndef WIN32 #define APIENTRY __stdcall typedef void* HANDLE; typedef void* HMODULE; typedef unsigned long DWORD; typedef unsigned long ULONG; typedef const char * LPCSTR; typedef long BOOL; const BOOL TRUE = 1; const BOOL FALSE = 0; typedef struct _GUID { unsigned long Data1; unsigned short Data2; unsigned short Data3; unsigned char Data4[ 8 ]; } GUID; #endif #define SCOMLIB_VERSION 1 //配置文件格式错误 #define E_CONFIGFILEFORMAT_ERROR (long)0x81000001L //读出配置文件错误 #define E_CONFIGFILEREAD_ERROR (long)0x81000002L //写入配置文件错误 #define E_CONFIGFILEWRITE_ERROR (long)0x81000003L //找不到组件 #define E_SCOM_NOT_FOUND (long)0x81000004L //没有定位文件 #define E_SCOM_NO_LOCATE_FILE (long)0x81000005L //没有初始化 #define E_SCOM_NOTINIT (long)0x81000006L #define COMPONENT_PROP_STARTUP 1 typedef GUID _KSGUID; typedef GUID KSGUID; typedef long KSRESULT; typedef KSGUID KSIID; typedef KSGUID KSCLSID; typedef HMODULE HSCOMMODULE; #define KS_DEFINE_GUID_NULL \ { 0x00000000, 0x0000, 0x0000, \ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} } #define KS_DEFINE_GUID_NULL_STR "00000000-0000-0000-0000-000000000000" typedef struct _CLASSINFO { KSCLSID m_CLSID; const char *m_pszProgID; DWORD m_dwProperty; }CLASSINFO; typedef KSRESULT (__stdcall _SCOM_CREATORFUNC)(const KSIID &iid, void **ppv); typedef struct _KMODULEINFO { KSCLSID m_CLSID; _SCOM_CREATORFUNC *m_pfnCreateInstance; const char *m_pszProgID; DWORD m_dwProperty; }KMODULEINFO; ////////////////////////////////////////////////////////////////////////// typedef KSRESULT (__stdcall _SCOM_KSDLLGETCLASSOBJECT)(const KSCLSID& clsid, const KSIID &riid , void **ppv); typedef KSRESULT (__stdcall _SCOM_KSDLLGETCLASSCOUNT)(int &nReturnSize); typedef KSRESULT (__stdcall _SCOM_KSDLLGETCLASSINFO)(CLASSINFO *ClassInfo, int nInSize); typedef KSRESULT (__stdcall _SCOM_KSDLLCANUNLOADNOW)(void); ////////////////////////////////////////////////////////////////////////// #define RGUID const KSGUID& #define KS_ASSERT(exp) assert(exp) #define KS_DEFINE_GETIID(_iid) public:\ static const KSIID& GetIID() {static const KSIID iid = _iid; return iid;} #define KS_DEFINE_GETCLSID(_clsid) public:\ static const KSCLSID& GetCLSID() {static const KSCLSID clsid = _clsid; return clsid;} ////////////////////////////////////////////////////////////////////////// #ifdef WIN32 #define KS_IIDOF(_interface) __uuidof(_interface) #else #define KS_IIDOF(_interface) _interface::GetIID() #endif #define KS_CLSIDOF(_component) _component::GetCLSID() //引用计数类 #ifdef WIN32 class KSRefCnt { public: KSRefCnt() : m_lValue(0) {} KSRefCnt(long lValue) : m_lValue(lValue) {} long operator++() { return InterlockedIncrement(&m_lValue); } long operator--() { return InterlockedDecrement(&m_lValue); } long operator=(long lValue) { return (m_lValue = lValue); } operator long() const { return m_lValue; } private: long operator++(int); long operator--(int); long m_lValue; }; #else //可考虑使用SGI stl提供的原子操作 class KSRefCnt { public: KSRefCnt() : m_lValue(0) {} KSRefCnt(long lValue) : m_lValue(lValue) {} long operator++() { KSAutoLockGuard guard(m_mutex); return ++m_lValue; } long operator--() { KSAutoLockGuard guard(m_mutex); return --m_lValue; } long operator=(long lValue) { return (m_lValue = lValue); } operator long() const { return m_lValue; } private: long operator++(int); long operator--(int); long m_lValue; KSAutoLockGuard::ThreadMutex m_mutex; }; #endif template<long lRefInitCnt> class KSRefCnt_WithArgument : public KSRefCnt { public: KSRefCnt_WithArgument():KSRefCnt(lRefInitCnt) { } }; ////////////////////////////////////////////////////////////////////////// #ifndef WIN32 inline bool IsEqualGUID(KSGUID rguid1, KSGUID rguid2) { return !memcmp(&rguid1, &rguid2, sizeof(KSGUID)); } #define IsEqualIID(riid1, riid2) IsEqualGUID(riid1, riid2) #define IsEqualCLSID(rclsid1, rclsid2) IsEqualGUID(rclsid1, rclsid2) inline bool operator==(const KSGUID& guidOne, const KSGUID& guidOther) { return !memcmp(&guidOne,&guidOther,sizeof(KSGUID)); } inline bool operator!=(const KSGUID& guidOne, const KSGUID& guidOther) { return !(guidOne == guidOther); } #endif inline bool InlineIsLessGUID(RGUID rguid1, RGUID rguid2) { int nRet = memcmp(&rguid1, &rguid2, sizeof(KSGUID)); return (nRet < 0) ? true : false; } inline bool operator<(RGUID rguid1, RGUID rguid2) { return InlineIsLessGUID(rguid1, rguid2); } #endif //SCOMDEF_H
[ "dreamsxin@qq.com" ]
dreamsxin@qq.com
36893e85193b05a7e8ced7fdf5089f6223b579fc
777d616740f8e2bad93fb60b7b78b5f276558416
/nnls-chroma-0.2.1_v2/NNLSChroma.cpp
06169e40ea82f56bf8627dfd6c3bf9630929c81b
[]
no_license
kg1994/SURA-PROJECT
9cb11e6f65bd99b0d42df1b7a0d274244b4754a8
6e104ab2d5a851e208baad56c0b8c5f8edc78077
refs/heads/master
2021-01-17T15:52:50.256743
2014-06-26T16:09:03
2014-06-26T16:09:03
21,210,599
1
0
null
null
null
null
UTF-8
C++
false
false
19,790
cpp
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* NNLS-Chroma / Chordino Audio feature extraction plugins for chromagram and chord estimation. Centre for Digital Music, Queen Mary University of London. This file copyright 2008-2010 Matthias Mauch and QMUL. 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 2 of the License, or (at your option) any later version. See the file COPYING included with this distribution for more information. */ #include "NNLSChroma.h" #include "chromamethods.h" #include <cstdlib> #include <fstream> #include <cmath> #include <algorithm> const bool debug_on = false; NNLSChroma::NNLSChroma(float inputSampleRate) : NNLSBase(inputSampleRate) { if (debug_on) cerr << "--> NNLSChroma" << endl; } NNLSChroma::~NNLSChroma() { if (debug_on) cerr << "--> ~NNLSChroma" << endl; } string NNLSChroma::getIdentifier() const { if (debug_on) cerr << "--> getIdentifier" << endl; return "nnls-chroma"; } string NNLSChroma::getName() const { if (debug_on) cerr << "--> getName" << endl; return "NNLS Chroma"; } string NNLSChroma::getDescription() const { if (debug_on) cerr << "--> getDescription" << endl; return "This plugin provides a number of features derived from a DFT-based log-frequency amplitude spectrum: some variants of the log-frequency spectrum, including a semitone spectrum derived from approximate transcription using the NNLS algorithm; and based on this semitone spectrum, different chroma features."; } NNLSChroma::OutputList NNLSChroma::getOutputDescriptors() const { if (debug_on) cerr << "--> getOutputDescriptors" << endl; OutputList list; // Make chroma names for the binNames property vector<string> chromanames; vector<string> bothchromanames; for (int iNote = 0; iNote < 24; iNote++) { bothchromanames.push_back(notenames[iNote]); if (iNote < 12) { chromanames.push_back(notenames[iNote+12]); } } int index = 0; OutputDescriptor d1; d1.identifier = "logfreqspec"; d1.name = "Log-Frequency Spectrum"; d1.description = "A Log-Frequency Spectrum (constant Q) that is obtained by cosine filter mapping."; d1.unit = ""; d1.hasFixedBinCount = true; d1.binCount = nNote; d1.hasKnownExtents = false; d1.isQuantized = false; d1.sampleType = OutputDescriptor::FixedSampleRate; d1.hasDuration = false; d1.sampleRate = (m_stepSize == 0) ? m_inputSampleRate/2048 : m_inputSampleRate/m_stepSize; list.push_back(d1); m_outputLogSpec = index++; OutputDescriptor d2; d2.identifier = "tunedlogfreqspec"; d2.name = "Tuned Log-Frequency Spectrum"; d2.description = "A Log-Frequency Spectrum (constant Q) that is obtained by cosine filter mapping, then its tuned using the estimated tuning frequency."; d2.unit = ""; d2.hasFixedBinCount = true; d2.binCount = nNote; d2.hasKnownExtents = false; d2.isQuantized = false; d2.sampleType = OutputDescriptor::FixedSampleRate; d2.hasDuration = false; d2.sampleRate = (m_stepSize == 0) ? m_inputSampleRate/2048 : m_inputSampleRate/m_stepSize; list.push_back(d2); m_outputTunedSpec = index++; OutputDescriptor d3; d3.identifier = "semitonespectrum"; d3.name = "Semitone Spectrum"; d3.description = "A semitone-spaced log-frequency spectrum derived from the third-of-a-semitone-spaced tuned log-frequency spectrum."; d3.unit = ""; d3.hasFixedBinCount = true; d3.binCount = 84; d3.hasKnownExtents = false; d3.isQuantized = false; d3.sampleType = OutputDescriptor::FixedSampleRate; d3.hasDuration = false; d3.sampleRate = (m_stepSize == 0) ? m_inputSampleRate/2048 : m_inputSampleRate/m_stepSize; list.push_back(d3); m_outputSemiSpec = index++; OutputDescriptor d4; d4.identifier = "chroma"; d4.name = "Chromagram"; d4.description = "Tuning-adjusted chromagram from NNLS approximate transcription, with an emphasis on the medium note range."; d4.unit = ""; d4.hasFixedBinCount = true; d4.binCount = 12; d4.binNames = chromanames; d4.hasKnownExtents = false; d4.isQuantized = false; d4.sampleType = OutputDescriptor::FixedSampleRate; d4.hasDuration = false; d4.sampleRate = (m_stepSize == 0) ? m_inputSampleRate/2048 : m_inputSampleRate/m_stepSize; list.push_back(d4); m_outputChroma = index++; OutputDescriptor d5; d5.identifier = "basschroma"; d5.name = "Bass Chromagram"; d5.description = "Tuning-adjusted bass chromagram from NNLS approximate transcription, with an emphasis on the bass note range."; d5.unit = ""; d5.hasFixedBinCount = true; d5.binCount = 12; d5.binNames = chromanames; d5.hasKnownExtents = false; d5.isQuantized = false; d5.sampleType = OutputDescriptor::FixedSampleRate; d5.hasDuration = false; d5.sampleRate = (m_stepSize == 0) ? m_inputSampleRate/2048 : m_inputSampleRate/m_stepSize; list.push_back(d5); m_outputBassChroma = index++; OutputDescriptor d6; d6.identifier = "bothchroma"; d6.name = "Chromagram and Bass Chromagram"; d6.description = "Tuning-adjusted chromagram and bass chromagram (stacked on top of each other) from NNLS approximate transcription."; d6.unit = ""; d6.hasFixedBinCount = true; d6.binCount = 24; d6.binNames = bothchromanames; d6.hasKnownExtents = false; d6.isQuantized = false; d6.sampleType = OutputDescriptor::FixedSampleRate; d6.hasDuration = false; d6.sampleRate = (m_stepSize == 0) ? m_inputSampleRate/2048 : m_inputSampleRate/m_stepSize; list.push_back(d6); m_outputBothChroma = index++; OutputDescriptor d7; d7.identifier = "consonance"; d7.name = "Consonance estimate."; d7.description = "A simple consonance value based on the convolution of a consonance profile with the semitone spectrum."; d7.unit = ""; d7.hasFixedBinCount = true; d7.binCount = 1; d7.hasKnownExtents = false; d7.isQuantized = false; d7.sampleType = OutputDescriptor::FixedSampleRate; d7.hasDuration = false; d7.sampleRate = (m_stepSize == 0) ? m_inputSampleRate/2048 : m_inputSampleRate/m_stepSize; list.push_back(d7); m_outputConsonance = index++; return list; } bool NNLSChroma::initialise(size_t channels, size_t stepSize, size_t blockSize) { if (debug_on) { cerr << "--> initialise"; } if (!NNLSBase::initialise(channels, stepSize, blockSize)) { return false; } return true; } void NNLSChroma::reset() { if (debug_on) cerr << "--> reset"; NNLSBase::reset(); } NNLSChroma::FeatureSet NNLSChroma::process(const float *const *inputBuffers, Vamp::RealTime timestamp) { if (debug_on) cerr << "--> process" << endl; NNLSBase::baseProcess(inputBuffers, timestamp); FeatureSet fs; fs[m_outputLogSpec].push_back(m_logSpectrum[m_logSpectrum.size()-1]); return fs; } NNLSChroma::FeatureSet NNLSChroma::getRemainingFeatures() { static const int nConsonance = 24; float consonancepattern[nConsonance] = {0,-1,-1,1,1,1,-1,1,1,1,-1,-1,1,-1,-1,1,1,1,-1,1,1,1,-1,-1}; float consonancemean = 0; for (int i = 0; i< nConsonance; ++i) { consonancemean += consonancepattern[i]/nConsonance; } cerr << "consonancemean = " << consonancemean << endl; for (int i = 0; i< nConsonance; ++i) { consonancepattern[i] -= consonancemean; } if (debug_on) cerr << "--> getRemainingFeatures" << endl; FeatureSet fsOut; if (m_logSpectrum.size() == 0) return fsOut; // /** Calculate Tuning calculate tuning from (using the angle of the complex number defined by the cumulative mean real and imag values) **/ float meanTuningImag = 0; float meanTuningReal = 0; for (int iBPS = 0; iBPS < nBPS; ++iBPS) { meanTuningReal += m_meanTunings[iBPS] * cosvalues[iBPS]; meanTuningImag += m_meanTunings[iBPS] * sinvalues[iBPS]; } float cumulativetuning = 440 * pow(2,atan2(meanTuningImag, meanTuningReal)/(24*M_PI)); float normalisedtuning = atan2(meanTuningImag, meanTuningReal)/(2*M_PI); int intShift = floor(normalisedtuning * 3); float floatShift = normalisedtuning * 3 - intShift; // floatShift is a really bad name for this char buffer0 [50]; sprintf(buffer0, "estimated tuning: %0.1f Hz", cumulativetuning); // cerr << "normalisedtuning: " << normalisedtuning << '\n'; /** Tune Log-Frequency Spectrogram calculate a tuned log-frequency spectrogram (f2): use the tuning estimated above (kinda f0) to perform linear interpolation on the existing log-frequency spectrogram (kinda f1). **/ cerr << endl << "[NNLS Chroma Plugin] Tuning Log-Frequency Spectrogram ... "; float tempValue = 0; float dbThreshold = 0; // relative to the background spectrum float thresh = pow(10,dbThreshold/20); // cerr << "tune local ? " << m_tuneLocal << endl; int count = 0; for (FeatureList::iterator i = m_logSpectrum.begin(); i != m_logSpectrum.end(); ++i) { Feature f1 = *i; Feature f2; // tuned log-frequency spectrum f2.hasTimestamp = true; f2.timestamp = f1.timestamp; f2.values.push_back(0.0); f2.values.push_back(0.0); // set lower edge to zero if (m_tuneLocal) { intShift = floor(m_localTuning[count] * 3); floatShift = m_localTuning[count] * 3 - intShift; // floatShift is a really bad name for this } // cerr << intShift << " " << floatShift << endl; for (unsigned k = 2; k < f1.values.size() - 3; ++k) { // interpolate all inner bins tempValue = f1.values[k + intShift] * (1-floatShift) + f1.values[k+intShift+1] * floatShift; f2.values.push_back(tempValue); } f2.values.push_back(0.0); f2.values.push_back(0.0); f2.values.push_back(0.0); // upper edge vector<float> runningmean = SpecialConvolution(f2.values,hw); vector<float> runningstd; for (int i = 0; i < nNote; i++) { // first step: squared values into vector (variance) runningstd.push_back((f2.values[i] - runningmean[i]) * (f2.values[i] - runningmean[i])); } runningstd = SpecialConvolution(runningstd,hw); // second step convolve for (int i = 0; i < nNote; i++) { runningstd[i] = sqrt(runningstd[i]); // square root to finally have running std if (runningstd[i] > 0) { // f2.values[i] = (f2.values[i] / runningmean[i]) > thresh ? // (f2.values[i] - runningmean[i]) / pow(runningstd[i],m_whitening) : 0; f2.values[i] = (f2.values[i] - runningmean[i]) > 0 ? (f2.values[i] - runningmean[i]) / pow(runningstd[i],m_whitening) : 0; } if (f2.values[i] < 0) { cerr << "ERROR: negative value in logfreq spectrum" << endl; } } fsOut[m_outputTunedSpec].push_back(f2); count++; } cerr << "done." << endl; /** Semitone spectrum and chromagrams Semitone-spaced log-frequency spectrum derived from the tuned log-freq spectrum above. the spectrum is inferred using a non-negative least squares algorithm. Three different kinds of chromagram are calculated, "treble", "bass", and "both" (which means bass and treble stacked onto each other). **/ if (m_useNNLS == 0) { cerr << "[NNLS Chroma Plugin] Mapping to semitone spectrum and chroma ... "; } else { cerr << "[NNLS Chroma Plugin] Performing NNLS and mapping to chroma ... "; } vector<float> oldchroma = vector<float>(12,0); vector<float> oldbasschroma = vector<float>(12,0); count = 0; for (FeatureList::iterator it = fsOut[m_outputTunedSpec].begin(); it != fsOut[m_outputTunedSpec].end(); ++it) { Feature f2 = *it; // logfreq spectrum Feature f3; // semitone spectrum Feature f4; // treble chromagram Feature f5; // bass chromagram Feature f6; // treble and bass chromagram Feature consonance; f3.hasTimestamp = true; f3.timestamp = f2.timestamp; f4.hasTimestamp = true; f4.timestamp = f2.timestamp; f5.hasTimestamp = true; f5.timestamp = f2.timestamp; f6.hasTimestamp = true; f6.timestamp = f2.timestamp; consonance.hasTimestamp = true; consonance.timestamp = f2.timestamp; float b[nNote]; bool some_b_greater_zero = false; float sumb = 0; for (int i = 0; i < nNote; i++) { // b[i] = m_dict[(nNote * count + i) % (nNote * 84)]; b[i] = f2.values[i]; sumb += b[i]; if (b[i] > 0) { some_b_greater_zero = true; } } // here's where the non-negative least squares algorithm calculates the note activation x vector<float> chroma = vector<float>(12, 0); vector<float> basschroma = vector<float>(12, 0); float currval; unsigned iSemitone = 0; if (some_b_greater_zero) { if (m_useNNLS == 0) { for (unsigned iNote = nBPS/2 + 2; iNote < nNote - nBPS/2; iNote += nBPS) { currval = 0; for (int iBPS = -nBPS/2; iBPS < nBPS/2+1; ++iBPS) { currval += b[iNote + iBPS] * (1-abs(iBPS*1.0/(nBPS/2+1))); } f3.values.push_back(currval); chroma[iSemitone % 12] += currval * treblewindow[iSemitone]; basschroma[iSemitone % 12] += currval * basswindow[iSemitone]; iSemitone++; } } else { float x[84+1000]; for (int i = 1; i < 1084; ++i) x[i] = 1.0; vector<int> signifIndex; int index=0; sumb /= 84.0; for (unsigned iNote = nBPS/2 + 2; iNote < nNote - nBPS/2; iNote += nBPS) { float currval = 0; for (int iBPS = -nBPS/2; iBPS < nBPS/2+1; ++iBPS) { currval += b[iNote + iBPS]; } if (currval > 0) signifIndex.push_back(index); f3.values.push_back(0); // fill the values, change later index++; } float rnorm; float w[84+1000]; float zz[84+1000]; int indx[84+1000]; int mode; int dictsize = nNote*signifIndex.size(); // cerr << "dictsize is " << dictsize << "and values size" << f3.values.size()<< endl; float *curr_dict = new float[dictsize]; for (int iNote = 0; iNote < (int)signifIndex.size(); ++iNote) { for (int iBin = 0; iBin < nNote; iBin++) { curr_dict[iNote * nNote + iBin] = 1.0 * m_dict[signifIndex[iNote] * nNote + iBin]; } } nnls(curr_dict, nNote, nNote, signifIndex.size(), b, x, &rnorm, w, zz, indx, &mode); delete [] curr_dict; for (int iNote = 0; iNote < (int)signifIndex.size(); ++iNote) { f3.values[signifIndex[iNote]] = x[iNote]; // cerr << mode << endl; chroma[signifIndex[iNote] % 12] += x[iNote] * treblewindow[signifIndex[iNote]]; basschroma[signifIndex[iNote] % 12] += x[iNote] * basswindow[signifIndex[iNote]]; } } } else { for (int i = 0; i < 84; ++i) f3.values.push_back(0); } float notesum = 0; consonance.values.push_back(0); for (int iSemitone = 0; iSemitone < 84-24; ++iSemitone) { notesum += f3.values[iSemitone] * f3.values[iSemitone] * treblewindow[iSemitone] * treblewindow[iSemitone]; float tempconsonance = 0; for (int jSemitone = 1; jSemitone < 24; ++jSemitone) { tempconsonance += f3.values[iSemitone+jSemitone] * (consonancepattern[jSemitone]) * treblewindow[iSemitone+jSemitone]; } consonance.values[0] += (f3.values[iSemitone] * tempconsonance * treblewindow[iSemitone]); } if (notesum > 0) consonance.values[0] /= notesum; f4.values = chroma; f5.values = basschroma; chroma.insert(chroma.begin(), basschroma.begin(), basschroma.end()); // just stack the both chromas f6.values = chroma; if (m_doNormalizeChroma > 0) { vector<float> chromanorm = vector<float>(3,0); switch (int(m_doNormalizeChroma)) { case 0: // should never end up here break; case 1: chromanorm[0] = *max_element(f4.values.begin(), f4.values.end()); chromanorm[1] = *max_element(f5.values.begin(), f5.values.end()); chromanorm[2] = max(chromanorm[0], chromanorm[1]); break; case 2: for (vector<float>::iterator it = f4.values.begin(); it != f4.values.end(); ++it) { chromanorm[0] += *it; } for (vector<float>::iterator it = f5.values.begin(); it != f5.values.end(); ++it) { chromanorm[1] += *it; } for (vector<float>::iterator it = f6.values.begin(); it != f6.values.end(); ++it) { chromanorm[2] += *it; } break; case 3: for (vector<float>::iterator it = f4.values.begin(); it != f4.values.end(); ++it) { chromanorm[0] += pow(*it,2); } chromanorm[0] = sqrt(chromanorm[0]); for (vector<float>::iterator it = f5.values.begin(); it != f5.values.end(); ++it) { chromanorm[1] += pow(*it,2); } chromanorm[1] = sqrt(chromanorm[1]); for (vector<float>::iterator it = f6.values.begin(); it != f6.values.end(); ++it) { chromanorm[2] += pow(*it,2); } chromanorm[2] = sqrt(chromanorm[2]); break; } if (chromanorm[0] > 0) { for (size_t i = 0; i < f4.values.size(); i++) { f4.values[i] /= chromanorm[0]; } } if (chromanorm[1] > 0) { for (size_t i = 0; i < f5.values.size(); i++) { f5.values[i] /= chromanorm[1]; } } if (chromanorm[2] > 0) { for (size_t i = 0; i < f6.values.size(); i++) { f6.values[i] /= chromanorm[2]; } } } fsOut[m_outputSemiSpec].push_back(f3); fsOut[m_outputChroma].push_back(f4); fsOut[m_outputBassChroma].push_back(f5); fsOut[m_outputBothChroma].push_back(f6); fsOut[m_outputConsonance].push_back(consonance); count++; } cerr << "done." << endl; return fsOut; }
[ "khushboogupta0911@gmail.com" ]
khushboogupta0911@gmail.com
26d8245f08ccc2a383eb2d39a0bb19621255f2b4
6b368c3b8d4cccb7c30463109e2c59633f23ffde
/src/loaders/RomLoader.h
8a231135dae701ca77e43bf9a380e02d7d9ea846
[]
no_license
lesharris/chipbit
a6d843f298d72f6606814205b0895b4d52a0c610
d306aecd191a6724faf9aa16bb9b57e55ff9daa7
refs/heads/master
2023-01-06T17:57:27.701399
2020-11-15T06:48:13
2020-11-15T06:48:13
291,652,930
0
0
null
null
null
null
UTF-8
C++
false
false
197
h
#pragma once #include <string> #include <memory> #include <vector> namespace Chipbit { class RomLoader { public: static std::vector<unsigned char> load(const std::string& romPath); }; }
[ "les@lesharris.com" ]
les@lesharris.com
2cdafa167e46c4a21928c67f6898ad4b371093db
98be777926b78b77a49166febd3f822e2e8860d0
/ULog/include/ULog/CXX/SpinLock.hpp
fd00cc6714626eef3c250872ea64f93c3e6987b2
[ "MIT" ]
permissive
yang123vc/ULog
1201cee2c9f5c78b782e2780b9e8122fb7e1a05d
ef1a77046ed1ba4aa66a160df57442ee56cf2c19
refs/heads/master
2021-01-22T07:27:30.576325
2017-01-11T18:46:52
2017-01-11T18:46:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,735
hpp
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2016 Jean-David Gadina - www.xs-labs.com * * 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. ******************************************************************************/ /*! * @header SpinLock.hpp * @copyright (c) 2016, Jean-David Gadina - www.xs-labs.com */ #ifndef ULOG_CXX_SPINLOCK_H #define ULOG_CXX_SPINLOCK_H #include <ULog/Base.h> #include <cstdint> namespace ULog { typedef volatile int32_t SpinLock; ULOG_EXPORT void SpinLockLock( SpinLock * lock ); ULOG_EXPORT void SpinLockUnlock( SpinLock * lock ); } #endif /* ULOG_CXX_SPINLOCK_H */
[ "macmade@xs-labs.com" ]
macmade@xs-labs.com
c3d74fa1ac312bde678d92b98a6b01312dc9d724
b6ab5a3ff4402ed085557cd5ff354ab2ead6e6f8
/codechef/HELLO.cpp
8a386d1fe711069edc9e85aed58e1c28d5e8d240
[]
no_license
sahiljajodia01/Competitive-Programming
e51587110640663aa32f220feddf6ab10f17c445
7ae9b45654aff513bceb0fc058a67ca49273a369
refs/heads/master
2021-07-17T08:23:24.143156
2020-06-05T11:34:14
2020-06-05T11:34:14
163,054,750
0
1
null
2019-10-31T05:36:35
2018-12-25T06:48:39
C++
UTF-8
C++
false
false
128
cpp
#include <iostream> #include <bits/stdc++.h> using namespace std; int main(int argc, char *argv[]) { cout << "Hello World!"; }
[ "sahil.jajodia@gmail.com" ]
sahil.jajodia@gmail.com
ee7c5a5c6472d6842a477c35d54e5b2cee913072
1635ac92bc976b124a5e1472d1d25ebfad5b0cb3
/src/Array.cpp
2e8e1d01d047e8f091c0e1fe3cb73a898ca3f4cc
[]
no_license
v4r05/stnfd.algs
6f198b1173a8bda44e2d4dff4a7d6a671a6c3c62
0038bc03d16d5f39d5ed5120517dfb2f1e8557c2
refs/heads/master
2021-01-20T19:27:06.828550
2016-08-07T18:22:05
2016-08-07T18:22:05
65,123,523
0
0
null
null
null
null
UTF-8
C++
false
false
5,430
cpp
// // MSI_Array.cpp // MSI // // Created by lykanthrop on 2016.07.17. // // #include "Array.h" #include <fstream> Array::Array() { } Array::Array(int* ptr, int sz) { size = sz; array_ptr = new int[size]; for(int i=0;i<size;++i) { array_ptr[i] = ptr[i]; } arraySorted_ptr = new int[size]; } Array::~Array() { if(array_ptr!=(int*)0) { delete[] array_ptr; } if(arraySorted_ptr!=(int*)0) { delete[] arraySorted_ptr; } } int Array::loadArrayFromFile(std::string filename) { printf("Loading File\n"); int out = -1; std::ifstream file(filename,std::fstream::in); if(file.is_open()) { printf("File Open\n"); std::string gluk; while(std::getline(file,gluk)) { size++; } printf("Size: %i\n",size); array_ptr = new int[size]; arraySorted_ptr = new int[size]; file.clear(); file.seekg(0); int i = 0; int value; while(std::getline(file,gluk)) { printf("Array %i\n",std::stoi(gluk)); value = std::stoi(gluk); array_ptr[i] = value; arraySorted_ptr[i] = value; i++; } file.close(); out = 0; } return out; } void Array::printSorted() { for(int i=0;i<size;++i) { printf("INDEX %i : %i\n",i,arraySorted_ptr[i]); } } void Array::sort(sortType tp) { switch (tp) { case Array::sortType::quickfst: quickSort(Array::pivotSelection::fst); break; case Array::sortType::quickmed: quickSort(Array::pivotSelection::med); break; case Array::sortType::quicklst: quickSort(Array::pivotSelection::lst); break; default: mergeSort(); break; } } void Array::mergeSort() { if(size>0) { int* bufferArray = new int[size]; for(int i=0;i<size;++i) { arraySorted_ptr[i] = array_ptr[i]; bufferArray[i] = array_ptr[i]; } printf("Sorting Array.\n"); merge_sort_recursion(0, size-1, bufferArray); delete[] bufferArray; } } void Array::quickSort(Array::pivotSelection psl) { if(size>0) { for(int i=0;i<size;++i) { arraySorted_ptr[i] = array_ptr[i]; } printf("Sorting Array.\n"); qsComparisons = 0; quick_sort_recursion(0,size-1,psl); } } unsigned long int Array::getInversions(){ return msInversions; } unsigned long int Array::getComparisons(){ return qsComparisons; } void Array::merge_sort_recursion(int l, int r, int* buffer) { printf("Sorting from %i to %i\n",l,r); if(r>l) { int length = (r - l)/2; printf("Dividing %i -> %i : %i -> %i\n",l,l+length,l+length+1,r); merge_sort_recursion(l,l+length,buffer); merge_sort_recursion(l+length+1,r,buffer); merge_sorting(l,l+length,l+length+1,r,buffer); } else { printf("Nothing to Do\n"); } } void Array::merge_sorting(int li, int lj, int ri, int rj, int* buffer) { printf("Merging right: %i -> %i left %i -> %i\n",li,lj,ri,rj); int index = li; int indexl = li; int indexr = ri; while(indexl<=lj && indexr<=rj) { if(buffer[indexl]<=buffer[indexr]) { arraySorted_ptr[index] = buffer[indexl]; indexl++; } else { arraySorted_ptr[index] = buffer[indexr]; indexr++; msInversions+=(lj-indexl+1); } index++; } for(int i=indexl;i<=lj;++i) { arraySorted_ptr[index] = buffer[i]; index++; } for(int i=indexr;i<=rj;++i) { arraySorted_ptr[index] = buffer[i]; index++; } for(int i=li;i<=rj;++i) { buffer[i] = arraySorted_ptr[i]; } } void Array::quick_sort_recursion(int li, int ri, pivotSelection ps) { if(li<ri) { int idx = quick_sorting(li,ri,ps); quick_sort_recursion(li,idx-1,ps); quick_sort_recursion(idx+1,ri,ps); } } int Array::quick_sorting(int li, int ri, pivotSelection ps) { printf("Quick Sorting from %i to %i\n",li,ri); int pivotIdx = li; int currentIdx = li+1; int swapValue = 0; int i = 0; switch (ps) { case Array::pivotSelection::med: printf("Sorting MED\n"); i = (ri+li)/2; if((arraySorted_ptr[ri]<arraySorted_ptr[li] && arraySorted_ptr[ri]>arraySorted_ptr[i]) || (arraySorted_ptr[ri]>arraySorted_ptr[li] && arraySorted_ptr[ri]<arraySorted_ptr[i])) { swapValue = arraySorted_ptr[pivotIdx]; arraySorted_ptr[pivotIdx] = arraySorted_ptr[ri]; arraySorted_ptr[ri] = swapValue; } else if((arraySorted_ptr[i]<arraySorted_ptr[ri] && arraySorted_ptr[i]>arraySorted_ptr[li]) || (arraySorted_ptr[i]>arraySorted_ptr[ri] && arraySorted_ptr[i]<arraySorted_ptr[li])) { swapValue = arraySorted_ptr[pivotIdx]; arraySorted_ptr[pivotIdx] = arraySorted_ptr[i]; arraySorted_ptr[i] = swapValue; } break; case Array::pivotSelection::lst: printf("Sorting LST\n"); swapValue = arraySorted_ptr[pivotIdx]; arraySorted_ptr[pivotIdx] = arraySorted_ptr[ri]; arraySorted_ptr[ri] = swapValue; break; default: printf("Sorting FST\n"); break; } int pivotValue = arraySorted_ptr[pivotIdx]; printf("Pivot Value: %i\n",pivotValue); while(currentIdx<=ri) { if(arraySorted_ptr[currentIdx]<pivotValue) { printf("Swaping\n"); swapValue = arraySorted_ptr[pivotIdx+1]; arraySorted_ptr[pivotIdx+1] = arraySorted_ptr[currentIdx]; arraySorted_ptr[currentIdx] = swapValue; ++pivotIdx; } ++currentIdx; } if(pivotIdx>li) { arraySorted_ptr[li] = arraySorted_ptr[pivotIdx]; arraySorted_ptr[pivotIdx] = pivotValue; } qsComparisons+=ri-li; printf("Comparisons: %lu\n",qsComparisons); printf("Pivot Index: %i\n",pivotIdx); return pivotIdx; }
[ "lykanthropen@gmail.com" ]
lykanthropen@gmail.com
81a85ce8e3c5fe92c7468e5385f990577f4b211e
bb0e0de2ad0fa385b87347efdb04c654e8453e99
/sensors/photon-dht-sensor.ino
e63f05da8d0bbab6a1cffa1274290296d6260b55
[]
no_license
jhaip/lovelace
7fd02302f8890d28c2385fde53257f14029c98a4
6de16c6472d5fcac6aa414bc130680261a3c92c2
refs/heads/master
2021-06-25T19:11:06.315318
2020-10-12T21:54:50
2020-10-12T21:54:50
141,215,908
0
0
null
2019-06-21T03:45:30
2018-07-17T01:46:13
C++
UTF-8
C++
false
false
3,866
ino
// This #include statement was automatically added by the Particle IDE. #include <HttpClient.h> // This #include statement was automatically added by the Particle IDE. #include <Adafruit_DHT.h> #include "Adafruit_DHT.h" // Example testing sketch for various DHT humidity/temperature sensors // Written by ladyada, public domain #define DHTPIN 2 // what pin we're connected to // Uncomment whatever type you're using! //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302) //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Connect pin 1 (on the left) of the sensor to +5V // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 4 (on the right) of the sensor to GROUND // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor DHT dht(DHTPIN, DHTTYPE); HttpClient http; // Headers currently need to be set at init, useful for API keys etc. http_header_t headers[] = { { "Content-Type", "application/json" }, { "Accept" , "application/json" }, { "Accept" , "*/*"}, { NULL, NULL } // NOTE: Always terminate headers will NULL }; http_request_t request; http_response_t response; String myID = System.deviceID(); void retract() { char str[150]; sprintf(str, "facts=\"Photon %s\" says the humidity is $ and temp is $", (const char*)myID); sprintf(str, "{\"facts\":\"\\\"Photon %s\\\" says the humidity is $ and temp is $\"}", (const char*)myID); // Particle.publish("retract", str, PRIVATE); // request.hostname = "requestbin.fullcontact.com"; // "10.0.0.162"; request.ip = {192, 168, 1, 34}; // {52, 222, 150, 205}; request.port = 3000; request.path = "/retract"; // "/18fjmkf1"; request.body = str; Serial.println(request.body); http.post(request, response, headers); Serial.print("Application>\tResponse status: "); Serial.println(response.status); } void publishValueMessage(float humidity, float temp) { char str[150]; // sprintf(str, "facts=\"Photon %s\" says the humidity is %f and temp is %f", (const char*)myID, humidity, temp); sprintf(str, "{\"facts\":\"\\\"Photon %s\\\" says the humidity is %f and temp is %f\"}", (const char*)myID, humidity, temp); // Serial.println(str); // Particle.publish("assert", str, PRIVATE); // request.hostname = NULL; // "10.0.0.162"; request.ip = {192, 168, 1, 34}; request.port = 3000; request.path = "/assert"; request.body = str; Serial.println(request.body); http.post(request, response, headers); Serial.print("Application>\tResponse status: "); Serial.println(response.status); } void setup() { Serial.begin(9600); Serial.println("DHTxx test!"); dht.begin(); } void loop() { // Wait a few seconds between measurements. delay(2000); // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a // very slow sensor) float h = dht.getHumidity(); // Read temperature as Celsius float t = dht.getTempCelcius(); // Read temperature as Farenheit float f = dht.getTempFarenheit(); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t) || isnan(f)) { Serial.println("Failed to read from DHT sensor!"); return; } // Compute heat index // Must send in temp in Fahrenheit! float hi = dht.getHeatIndex(); float dp = dht.getDewPoint(); float k = dht.getTempKelvin(); Serial.print("Humid: "); Serial.print(h); Serial.print("% - "); Serial.print("Temp: "); Serial.print(t); Serial.print("*C "); Serial.print(f); Serial.print("*F "); Serial.print(k); Serial.print("*K - "); Serial.print("DewP: "); Serial.print(dp); Serial.print("*C - "); Serial.print("HeatI: "); Serial.print(hi); Serial.println("*C"); Serial.println(Time.timeStr()); retract(); publishValueMessage(h, t); }
[ "haipjacob@gmail.com" ]
haipjacob@gmail.com
3b58242d17450d62324bcc5a9428650fa0620d0f
84ce74493e41edcbc4d31312fdab5a611efc0568
/src/Vendor/Parsers/JsonParser.h
0394b8ab1431958b46105a2ac46904d84154640b
[]
no_license
moriorgames/bfai-vendor
f116ca1e12acb1b83ba430a640403aeac449e466
7364a577a4952eb8e5fd199cf60661adf075ac8e
refs/heads/master
2021-04-30T13:00:06.935887
2018-03-21T05:49:05
2018-03-21T05:49:05
121,285,231
0
0
null
null
null
null
UTF-8
C++
false
false
669
h
#ifndef MORIOR_GAMES_VENDOR_PARSERS_JSON_PARSER_H #define MORIOR_GAMES_VENDOR_PARSERS_JSON_PARSER_H #include <string> #include <vector> #include "json/document.h" namespace MoriorGames { using namespace rapidjson; class JsonParser { public: JsonParser(std::string json); protected: Document document; int getInt(const rapidjson::Value &data, std::string key); long int getInt64(const rapidjson::Value &data, std::string key); double getDouble(const rapidjson::Value &data, std::string key); std::string getString(const rapidjson::Value &data, std::string key); bool getBool(const rapidjson::Value &data, std::string key); }; } #endif
[ "moriorgames@gmail.com" ]
moriorgames@gmail.com
f195e79d0d074e6a4869d484cb9001159d8ed30b
5a669e48840a7ec299bf8b382c1c781c3406bb5f
/src/materials/material.hh
3b7e85f7e8bb4d7aaefbb2ff72ca2fffbfe1916a
[]
no_license
MedericCar/pathtracer
dfa3835fbd695977f752ffa20b3e407622dae66c
6e014a6fb9116773fe5518d8a317e72ecbb8ee08
refs/heads/main
2023-04-07T05:15:39.728411
2021-04-19T14:13:46
2021-04-19T14:13:46
342,172,808
1
0
null
null
null
null
UTF-8
C++
false
false
1,287
hh
#pragma once #include <memory> #include "../utils/color.hh" #include "../utils/vector.hh" namespace isim { class Material { public: Material(); Material(Rgb _ka , Rgb _kd, Rgb _ks, float _ns, Rgb _ke, float _ni, Rgb _kt, float _roughness); virtual Vector3 sample(const Vector3& wo, const Vector3& n) const; virtual Rgb eval_bsdf(const Vector3& wo, const Vector3& wi, const Vector3& n) const = 0; virtual float pdf(const Vector3& wo, const Vector3& wi, const Vector3& n) const; virtual Rgb sample_f(const Vector3& wo, const Vector3& n, Vector3* wi, float* pdf) const; Rgb ka_; // ambient Rgb kd_; // diffusivity Rgb ks_; // specularity float ns_; // specular exponent Rgb ke_; // emissive Rgb kt_; // transmittance float ni_t_; // index of refraction inside material float ni_i_ = 1.f; // index of refraction outside material (air) float roughness_ = 1.f; // roughness (as defined in related BSDFs) float pdf_constant_ = 1.0f / (2.0f * M_PI); // hemisphere sampling }; }
[ "carriatmederic@gmail.com" ]
carriatmederic@gmail.com
fc15be8fe1f7f1ac99b2baf469b83a6eff264d70
081138564d7d668e1853c85757f270ecebbcc3e3
/ncfighter.cpp
8d1c8dc9ab44a617263bda1ee3e31389fa636537
[]
no_license
blxsheep/POSN_2018
54c37fd0aeab5b4d4a86d73922c9025e178e8217
5a05e4d7d42bca709436a8896c9bbd12e1c3c2de
refs/heads/main
2023-04-18T10:04:13.035250
2021-04-26T16:02:12
2021-04-26T16:02:12
361,807,461
0
0
null
null
null
null
UTF-8
C++
false
false
1,229
cpp
// Never Give up. May be clutch shot threes make you win. #include<bits/stdc++.h> using namespace std; typedef pair<int,int> PII; vector<PII> g[100100]; int mid,mark[100100],ch; int dfs(int u,int color){ if(mark[u]==color) return 0; if(mark[u]!=0 && mark[u]!=color) return 1; mark[u]=color; for(int i=0;i<g[u].size();i++){ //if index that to go > mid it not important to create graph . // to reduce the big O. if(g[u][i].second>mid) continue; if(dfs(g[u][i].first,3-color)==1) return 1; } return 0; } int a,b,i,s,r,l; int main(){ // Bipartite graph + Binary Search; scanf("%d %d",&a,&b); for(i=1;i<=b;i++){ scanf("%d %d",&r,&s); //link each other and keep index too; g[r].push_back(make_pair(s,i)); g[s].push_back(make_pair(r,i)); } l=1,r=b; while(l<r){ mid=(l+r)/2; memset(mark,0,sizeof mark); for(i=1,ch=0;i<=a;i++){ if(mark[i]==0){ if(dfs(i,1)==1){ ch=1; //it not bipatite here; break; } } } if(ch) r=mid; else l=mid+1; } printf("%d\n",l); return 0; } /* 6 8 3 4 1 2 5 6 1 6 1 3 4 5 2 4 2 6 */
[ "noreply@github.com" ]
noreply@github.com
f197282277977155a3cdeed6af4b08be360ca71a
117761fd24cb1ab05d581e88304beec24143e680
/lore/printable.hpp
3178461cd75dd386acac77c8c42fca7e3f8e5c14
[]
no_license
NineDayGame/NineDayGame
0d944bb1a17dfc1200331e32f2fcaa2fe422d8b4
2a30ed7a02a99d7789f54ed5848598a6f8d7c00d
refs/heads/master
2021-01-01T18:55:06.919599
2011-02-28T05:40:26
2011-02-28T05:40:26
1,386,782
4
1
null
null
null
null
UTF-8
C++
false
false
213
hpp
#ifndef PRINTABLE_HPP #define PRINTABLE_HPP #include <boost/shared_ptr.hpp> class Printable { public: typedef boost::shared_ptr<Printable> ShPtr; virtual void print(const std::string output) = 0; }; #endif
[ "foxryan@gmail.com" ]
foxryan@gmail.com
bcc49cdba7b1baf361818ab6c9d1bb1b2726a0a4
47a485fe6b512aee8ba7ccd03a97f744936801a9
/HR/maximum_product_subarry.cpp
50ae702d115f1bdd501dfc1a712fdbdafa16bbd4
[]
no_license
yuyashiraki/CTCI
9e641557cf5a9d9629d2edc665b9d089e648881f
ddc2384314894d3a1536fa2b179f14ebfd2a4df3
refs/heads/master
2021-04-27T11:33:30.568159
2018-10-01T01:02:55
2018-10-01T01:02:55
122,563,481
0
0
null
null
null
null
UTF-8
C++
false
false
1,257
cpp
class Solution { public: // Genius Answer // Time O(n) Space O(1) int maxProduct(vector<int>& nums) { int r = nums[0]; for (int i = 1; imax = r, imin = r; i < n; i++) { if (A[i] < 0) { swap(imax, imin); } imax = max(A[i], imax * A[i]); imin = min(A[i], imin * A[i]); r = max(r, imax); } return r; } // Time O(N) Space O(N) int maxProduct(vector<int>& nums) { if (!nums.size()) return 0; if (nums.size() == 1) return nums[0]; vector<long long> products; int n = nums.size(); long long ans = INT_MIN, neg_min; for (int i = 0; i < n; i++) { if (0 == i || 0 == products[i - 1]) { products.push_back(nums[i]); neg_min = INT_MIN; } else { products.push_back(products[i - 1] * nums[i]); } ans = max(ans, products[i]); if (products[i] < 0) { if (INT_MIN != neg_min) { ans = max(ans, products[i] / neg_min); } neg_min = max(neg_min, products[i]); } } return (int) ans; } };
[ "yshiraki.japan@gmail.com" ]
yshiraki.japan@gmail.com
78e73ad577b72ee9e8b4598e92d96602043ed7a8
349fe789ab1e4e46aae6812cf60ada9423c0b632
/Forms/SprNumTel/UFormaElementaSprNumTelImpl.h
f0c466ce3c57513056812c58e50869c414025639
[]
no_license
presscad/ERP
a6acdaeb97b3a53f776677c3a585ca860d4de980
18ecc6c8664ed7fc3f01397d587cce91fc3ac78b
refs/heads/master
2020-08-22T05:24:15.449666
2019-07-12T12:59:13
2019-07-12T12:59:13
216,326,440
1
0
null
2019-10-20T07:52:26
2019-10-20T07:52:26
null
UTF-8
C++
false
false
1,506
h
#ifndef UFormaElementaSprNumTelImplH #define UFormaElementaSprNumTelImplH #include "IFormaElementaSprNumTel.h" #include "UFormaElementaSprNumTel.h" //--------------------------------------------------------------- class __declspec(uuid("{152FB88D-D75C-4570-84E5-D89EDA3687BC}"))TFormaElementaSprNumTelImpl : public IFormaElementaSprNumTel, IkanCallBack { public: TFormaElementaSprNumTelImpl(); ~TFormaElementaSprNumTelImpl(); TFormaElementaSprNumTel * Object; int NumRefs; bool flDeleteObject; void DeleteImpl(void); //IUnknown virtual int kanQueryInterface(REFIID id_interface,void ** ppv); virtual int kanAddRef(void); virtual int kanRelease(void); //IMainInterface virtual int get_CodeError(void); virtual void set_CodeError(int CodeError); virtual UnicodeString get_TextError(void); virtual void set_TextError(UnicodeString TextError); virtual int Init(IkanUnknown * i_main_object, IkanUnknown * i_owner_object); virtual int Done(void); //IkanCallBack virtual int kanExternalEvent(IkanUnknown * pUnk, REFIID id_object,int type_event, int number_procedure_end); //IFormaElementaSprNumTel virtual IDMSprNumTel * get_DM(void); virtual void set_DM(IDMSprNumTel * DM); virtual bool get_Vibor(void); virtual void set_Vibor(bool Vibor); virtual int get_NumberProcVibor(void); virtual void set_NumberProcVibor(int NumberProcVibor); }; #define CLSID_TFormaElementaSprNumTelImpl __uuidof(TFormaElementaSprNumTelImpl) #endif
[ "sasha@kaserv.ru" ]
sasha@kaserv.ru
379f24d23034c0f77f00c815eef468352e0ef1b5
75053084247157c8857e1ead4ada643de3e2c3fe
/mainwindow.cpp
1f253ed1dc826b5185a777b2b3605b14eba79bde
[ "MIT" ]
permissive
netbeen/UncleZhou_UI
e5ad50115630339e3189cc7660ab5193efbb75a7
69ad47d1b6d41a63984e6448ef412afc1481bb89
refs/heads/master
2016-09-16T04:21:19.424444
2016-01-01T09:27:07
2016-01-01T09:27:07
42,807,549
2
0
null
null
null
null
UTF-8
C++
false
false
13,609
cpp
#include "mainwindow.h" #include <QApplication> #include <QGridLayout> #include <QWidget> #include <QLabel> #include <QMenuBar> #include <QToolBar> #include <QStatusBar> #include <QAction> #include <QFileDialog> #include <QDebug> #include <QMessageBox> #include "newimagedialog.h" #include "util.h" #include "imageeditwindow.h" #include "QFileInfo" /** * @brief MainWindow::MainWindow * @brief mainwindow的构造函数 * @param parent 是qt widget的父指针 * @return 没有返回值 */ MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { this->initWindowLayout(); this->initAction(); QIcon icon(":/image/open.png"); //设置程序图标 this->setWindowIcon(icon); this->fileMenu = this->menuBar()->addMenu("&File"); this->fileMenu->addAction(this->loadSourceImageAction); this->helpMenu = this->menuBar()->addMenu("&Help"); this->helpMenu->addAction(this->aboutAction); this->menuBar()->setStyleSheet(" QMenuBar{background-color: #333337; padding-left: 5px;}QMenuBar::item {background-color: #333337; padding:2px; margin:6px 10px 0px 0px;} QMenuBar::item:selected {background: #3e3e40;} QMenuBar::item:pressed {background: #1b1b1c;}"); QToolBar* toolbar = this->addToolBar("Standard Tool Bar"); toolbar->addAction(this->loadSourceImageAction); //QStatusBar* statusBar = this->statusBar(); } /** * @brief MainWindow::initAction * @brief 用于mainwindow的action的定义、connect、插入 * @param 没有参数 * @return 没有返回值 */ void MainWindow::initAction(){ this->loadSourceImageAction = new QAction(QIcon(":/image/open.png"),"&Load Source Image",this); QObject::connect(this->loadSourceImageAction, &QAction::triggered, this, &MainWindow::loadSourceImage); this->viewSourceImageAction = new QAction(QIcon(":/image/open.png"),"&View Source Image",this); QObject::connect(this->viewSourceImageAction, &QAction::triggered, this, &MainWindow::viewSourceImage); this->viewSourceImageAction->setEnabled(false); this->editSourceGuidanceAction = new QAction(QIcon(":/image/open.png"),"&Edit Source Guidance",this); QObject::connect(this->editSourceGuidanceAction, &QAction::triggered, this, &MainWindow::editSourceGuidance); this->editSourceGuidanceAction->setEnabled(false); this->viewTargetGuidanceAction = new QAction(QIcon(":/image/open.png"),"&View Target Guidance",this); QObject::connect(this->viewTargetGuidanceAction, &QAction::triggered, this, &MainWindow::viewTargetGuidance); this->viewTargetGuidanceAction->setEnabled(false); this->createNewTargetGuidanceAction = new QAction(QIcon(":/image/open.png"),"&Create New Guidance",this); QObject::connect(this->createNewTargetGuidanceAction, &QAction::triggered, this, &MainWindow::newImage); this->editTargetGuidanceAction = new QAction(QIcon(":/image/open.png"),"&Edit Target Guidance",this); QObject::connect(this->editTargetGuidanceAction, &QAction::triggered, this, &MainWindow::editTargetGuidance); this->editTargetGuidanceAction->setEnabled(false); this->aboutAction = new QAction(QIcon(":/image/open.png"),"&About",this); QObject::connect(this->aboutAction, &QAction::triggered, this, &MainWindow::about); //Action 插入段 this->sourceImageWidget->addAction(this->viewSourceImageAction); //左上角的view this->sourceImageWidget->addAction(this->loadSourceImageAction); //左上角的load this->sourceGuidanceWidget->addAction(new QAction("&View",this)); this->sourceGuidanceWidget->addAction(this->editSourceGuidanceAction); this->targetGuidanceWidget->addAction(this->viewTargetGuidanceAction); this->targetGuidanceWidget->addAction(this->createNewTargetGuidanceAction); this->targetGuidanceWidget->addAction(this->editTargetGuidanceAction); } /** * @brief MainWindow::loadSourceImage * @brief load image的action的入口函数,用于载入一个原图,并显示在左上角,顺带初始化右上角的source guidance(同等大小的白图)。 * @param 没有参数 * @return 没有返回值 */ void MainWindow::loadSourceImage(){ QFileDialog* fileDialog = new QFileDialog(this, tr("Open image File"), ".", tr("Image files(*.png *.jpg *.JPG)")); fileDialog->setFileMode(QFileDialog::ExistingFiles); fileDialog->setViewMode(QFileDialog::Detail); if (fileDialog->exec() == QDialog::Accepted) //成功选择一个png图片 { this->sourceImage =new QImage(fileDialog->selectedFiles().first()); //读入图片 QString filename; //取出完整文件名 for(int i = 1; ;i++){ QString section = fileDialog->selectedFiles().first().section('/',i,i); if(section.size() == 0){ break; }else{ filename = section; } } QString filenameWithoutSuffix = filename.section('.',0,0); QFileInfo dirNameInfo = QFileInfo(filenameWithoutSuffix); //判断当前目录下,以该文件命名的文件夹是否存在 if(dirNameInfo.isDir() == false){ QDir().mkdir(filenameWithoutSuffix); //新建文件夹 }else{ QImage preSavedImage = QImage(filenameWithoutSuffix+"/sourceImage.png"); if(*this->sourceImage != preSavedImage){ //同名但图像不同,删除目录下所有文件 QDir dir(filenameWithoutSuffix); QFileInfoList fileList = dir.entryInfoList(); foreach (QFileInfo fi, fileList) { if(fi.isFile() == true){ dir.remove(fi.fileName()); } } } } Util::dirName = filenameWithoutSuffix; //给静态类赋值,保存目录名称 this->sourceImage->save((Util::dirName+"/sourceImage.png").toUtf8().data()); this->sourceImageFrame->setStyleSheet("background-image: url("+Util::dirName+"/sourceImage.png);background-position:center center;background-repeat: no-repeat"); this->sourceGuidance = new QImage(this->sourceImage->width(), this->sourceImage->height(), QImage::Format_RGB888); //新建一个同等大小的空图像 this->sourceGuidance->fill(QColor(255,255,255)); //填充白色 for(QString elem : Util::guidanceChannel){ this->sourceGuidance->save(Util::dirName+"/sourceGuidance"+elem+".png"); } this->sourceGuidance->save((Util::dirName+"/multiLabelClassificationResult.png").toUtf8().data()); this->sourceGuidanceFrame->setStyleSheet("background-image: url("+Util::dirName+"/sourceGuidanceLabelChannel.png);background-position:center center;background-repeat: no-repeat"); //显示在右上角 this->sourceImageWidgetStackedLayout->setCurrentIndex(1); this->sourceGuidanceWidgetStackedLayout->setCurrentIndex(1); this->viewSourceImageAction->setEnabled(true); this->viewSourceImageAction->setEnabled(true); this->editSourceGuidanceAction->setEnabled(true); } } MainWindow::~MainWindow() { } /** * @brief MainWindow::initWindowLayout * @brief 用于管理mainwindow的窗口设置、layout布局、内部控件声明及摆放 * @param 没有参数 * @return 没有返回值 */ void MainWindow::initWindowLayout(){ this->setWindowState(Qt::WindowMaximized); //设置窗口最大化 this->setStyleSheet("background-color: #333337; color: #f1f1f1;"); //设置窗口样式(酷黑) QWidget* centerWidget = new QWidget(this); //声明widget并设置为窗口的中央widget(这样才能设置layout) this->setCentralWidget(centerWidget); QGridLayout* gridLayout = new QGridLayout(centerWidget); //在中央widget开启网格布局 centerWidget->setLayout(gridLayout); this->sourceImageWidget = new QWidget(centerWidget); //左上角widget声明:放置source image this->sourceImageWidget->setStyleSheet("background-color: #696969;"); gridLayout->addWidget(sourceImageWidget,0,0); this->sourceGuidanceWidget = new QWidget(centerWidget); //右上角label声明:放置source guidance this->sourceGuidanceWidget->setStyleSheet("background-color: #696969;"); gridLayout->addWidget(this->sourceGuidanceWidget,0,1); this->targetGuidanceWidget = new QWidget(centerWidget); // 左下角label声明:放置target guidance this->targetGuidanceWidget->setStyleSheet("background-color: #696969;"); gridLayout->addWidget(this->targetGuidanceWidget,1,0); this->targetImageWidget = new QWidget(centerWidget); //右下角widget声明:放置target image this->targetImageWidget->setStyleSheet("background-color: #696969;"); gridLayout->addWidget(targetImageWidget,1,1); this->sourceImageWidget->setContextMenuPolicy(Qt::ActionsContextMenu); //激活右键菜单策略 this->sourceGuidanceWidget->setContextMenuPolicy(Qt::ActionsContextMenu); //激活右键菜单策略 this->targetGuidanceWidget->setContextMenuPolicy(Qt::ActionsContextMenu); //激活右键菜单策略 this->targetImageWidget->setContextMenuPolicy(Qt::ActionsContextMenu); //激活右键菜单策略 this->sourceImageWidgetStackedLayout = new QStackedLayout(this->sourceImageWidget); this->sourceImageWidget->setLayout(this->sourceImageWidgetStackedLayout); this->sourceImageFrame = new QFrame(this->sourceImageWidget); QLabel* hintLabel1 = new QLabel("Source Image Area", this->sourceImageWidget); hintLabel1->setStyleSheet("font-size : 40px"); hintLabel1->setAlignment(Qt::AlignCenter); this->sourceImageWidgetStackedLayout->addWidget(hintLabel1); this->sourceImageWidgetStackedLayout->addWidget(this->sourceImageFrame); this->sourceGuidanceWidgetStackedLayout = new QStackedLayout(this->sourceGuidanceWidget); //在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变 this->sourceGuidanceWidget->setLayout(this->sourceGuidanceWidgetStackedLayout); this->sourceGuidanceFrame = new QFrame(this->sourceGuidanceWidget); QLabel* hintLabel2 = new QLabel("Source Guidance Area", this->sourceGuidanceWidget); hintLabel2->setStyleSheet("font-size : 40px"); hintLabel2->setAlignment(Qt::AlignCenter); this->sourceGuidanceWidgetStackedLayout->addWidget(hintLabel2); this->sourceGuidanceWidgetStackedLayout->addWidget(this->sourceGuidanceFrame); this->targetGuidanceWidgetStackedLayout = new QStackedLayout(this->targetGuidanceWidget); //在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变 this->targetGuidanceWidget->setLayout(this->targetGuidanceWidgetStackedLayout); this->targetGuidanceFrame = new QFrame(this->targetGuidanceWidget); QLabel* hintLabel3 = new QLabel("Target Guidance Area", this->targetGuidanceWidget); hintLabel3->setStyleSheet("font-size : 40px"); hintLabel3->setAlignment(Qt::AlignCenter); this->targetGuidanceWidgetStackedLayout->addWidget(hintLabel3); this->targetGuidanceWidgetStackedLayout->addWidget(this->targetGuidanceFrame); this->targetImageWidgetStackedLayout = new QStackedLayout(this->targetImageWidget); //在label内建一个layout放置一个Frame,可以保证右键菜单的背景不受改变 this->targetImageWidget->setLayout(this->targetImageWidgetStackedLayout); this->targetImageFrame = new QFrame(this->targetImageWidget); QLabel* hintLabel4 = new QLabel("Target Image Area", this->targetImageWidget); hintLabel4->setStyleSheet("font-size : 40px"); hintLabel4->setAlignment(Qt::AlignCenter); this->targetImageWidgetStackedLayout->addWidget(hintLabel4); this->targetImageWidgetStackedLayout->addWidget(this->targetImageFrame); this->targetImageWidget->addAction(new QAction("&View",this)); } /** * @brief MainWindow::newImage * @brief mainwindow中点击新建导引图片的action * @param 没有参数 * @return 没有返回值 */ void MainWindow::newImage(){ NewImageDialog* newImageDialog = new NewImageDialog(); if(newImageDialog->exec() == QDialog::Accepted){ this->targetGuidanceFrame->setStyleSheet("background-image: url("+Util::dirName+"/targetGuidanceLabelChannel.png);background-position:center center;background-repeat: no-repeat"); //显示在右上角 } this->targetGuidanceWidgetStackedLayout->setCurrentIndex(1); this->viewTargetGuidanceAction->setEnabled(true); this->editTargetGuidanceAction->setEnabled(true); } void MainWindow::editSourceGuidance(){ ImageEditWindow* imageEditWindow = new ImageEditWindow(config::sourceGuidance, config::editable, this); imageEditWindow->show(); } void MainWindow::viewSourceImage(){ ImageEditWindow* imageEditWindow = new ImageEditWindow(config::sourceImage, config::readOnly, this); imageEditWindow->show(); } void MainWindow::about() { QMessageBox::about(this, tr("About Uncle Zhou UI"), tr("<p><b>Uncle Zhou UI</b></p>" "Open sourced under the <b>MIT</b> license.<br/>" "Copyright (c) 2015 NetBeen<br/>" "netbeen.cn@gmail.com")); } void MainWindow::editTargetGuidance(){ ImageEditWindow* imageEditWindow = new ImageEditWindow(config::targetGuidance, config::editable, this); imageEditWindow->show(); } void MainWindow::viewTargetGuidance(){ ImageEditWindow* imageEditWindow = new ImageEditWindow(config::targetGuidance, config::readOnly, this); imageEditWindow->show(); }
[ "netbeen.cn@gmail.com" ]
netbeen.cn@gmail.com
783a8274bf79fd24ed89f31067b545c6a52e5caa
5bc07dbbdcda1a772de18a36432086a4c09299a9
/TXCloudRoom/UI/MemberItemView.cpp
4666932949938277959faff48de33c7d351c2e97
[]
no_license
shengang1978/webexe_exe_source
f37715405b0e822c779cd00496765f34285981bb
716e85310449db720558eea7e2d6dbf803824e56
refs/heads/master
2020-04-06T17:00:01.144573
2018-09-29T10:52:45
2018-09-29T10:52:45
157,642,349
0
1
null
2018-11-15T02:46:19
2018-11-15T02:46:18
null
UTF-8
C++
false
false
909
cpp
#include "MemberItemView.h" MemberItemView::MemberItemView(MemberPanel* panel, const MemberItem& members, QWidget *parent) : QWidget(parent) , m_panel(panel) { m_ui.setupUi(this); if (members.role == MasterPusherRole) { m_ui.label_icon->setStyleSheet("image :url(:/RoomService/teacher.png)"); QString labelStyle = R"( background: none; color: #0063ff; font: 10pt "Microsoft YaHei"; )"; m_ui.label_nick->setStyleSheet(labelStyle); } else { m_ui.label_icon->setStyleSheet("image :url(:/RoomService/student.png)"); QString labelStyle = R"( background: none; color: #333333; font: 10pt "Microsoft YaHei"; )"; m_ui.label_nick->setStyleSheet(labelStyle); } m_ui.label_nick->setText(members.userName.c_str()); if (!members.status.empty()) { m_ui.label_status->setStyleSheet("image :url(:/RoomService/speaker.png)"); } } MemberItemView::~MemberItemView() { }
[ "xuanyiyan@tencent.com" ]
xuanyiyan@tencent.com
ee27c389f08049d92d10311eaa230114703c106c
0b63fa8325233e25478b76d0b4a9a6ee3070056d
/src/appleseed.studio/utility/scrollareapanhandler.h
97d94c04c836b8618978dbc5020ec310424184a9
[ "MIT" ]
permissive
hipopotamo-hipotalamo/appleseed
e8c61ccec64baf01b6aeb3cde4dd3031d37ece17
eaf07e3e602218a35711e7495ac633ce210c6078
refs/heads/master
2020-12-07T02:39:27.454003
2013-10-29T13:10:59
2013-10-29T13:10:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,352
h
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // // 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. // #ifndef APPLESEED_STUDIO_UTILITY_SCROLLAREAPANHANDLER_H #define APPLESEED_STUDIO_UTILITY_SCROLLAREAPANHANDLER_H // Qt headers. #include <QObject> #include <QPoint> // Forward declarations. class QEvent; class QMouseEvent; class QScrollArea; namespace appleseed { namespace studio { class ScrollAreaPanHandler : public QObject { Q_OBJECT public: explicit ScrollAreaPanHandler(QScrollArea* scroll_area); ~ScrollAreaPanHandler(); private: QScrollArea* m_scroll_area; bool m_is_dragging; QPoint m_initial_mouse_position; int m_initial_hbar_value; int m_initial_vbar_value; virtual bool eventFilter(QObject* object, QEvent* event); bool handle_mouse_button_press_event(QMouseEvent* event); bool handle_mouse_button_release_event(QMouseEvent* event); bool handle_mouse_move_event(QMouseEvent* event); }; } // namespace studio } // namespace appleseed #endif // !APPLESEED_STUDIO_UTILITY_SCROLLAREAPANHANDLER_H
[ "beaune@aist.enst.fr" ]
beaune@aist.enst.fr
a59be69046cc867ca5805efe886a71f894d623f6
9bc4f3d5f57e643491543a6ce935c00e2d4665a0
/tipono.cpp
34008c680a3ecf685964f63563946f2cabb78933
[]
no_license
jeanhardzz/TAD-Arvores
8d8ae5e1f0f404688acda52249552ea9280ba4ef
44ecd1c0fa68a062a3767a8ec0ed3c7cfba528a9
refs/heads/master
2022-12-13T23:17:57.190282
2020-09-10T19:30:45
2020-09-10T19:30:45
293,819,491
1
0
null
null
null
null
UTF-8
C++
false
false
88
cpp
#include "tipono.h" TipoNo::TipoNo(){ item.SetChave(-1); esq = 0; dir = 0; }
[ "jean.lk@hotmail.com" ]
jean.lk@hotmail.com
8cd07b35cb221b0a8729171627ee1d8ec148364d
33a44642c3ca8c08554fe4e107918be505cf9a4f
/virtuanessrc097/NES/Mapper/Mapper003.cpp
54f0532b0a13d3c752db286c4862e4c9cf92f492
[]
no_license
yyl-20020115/vn-097
0b77e7b1fc77d1a79fc57413261c0046af1448c3
faa0f2658e0952c3ae5b9953466bb16032f75cbc
refs/heads/master
2021-07-11T02:48:10.260128
2017-10-13T21:34:02
2017-10-13T21:34:02
106,718,956
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,297
cpp
////////////////////////////////////////////////////////////////////////// // Mapper003 CNROM // ////////////////////////////////////////////////////////////////////////// void Mapper003::Reset() { switch( PROM_16K_SIZE ) { case 1: // 16K only SetPROM_16K_Bank( 4, 0 ); //$8000 <- Bank 0 (8K Page 4 <-Bank 0;8K Page 5 <-Bank 1) SetPROM_16K_Bank( 6, 0 ); //$C000 <- Bank 0 (8K Page 6 <-Bank 0;8K Page 7 <-Bank 1) break; case 2: // 32K SetPROM_32K_Bank( 0 ); //$8000 <- Bank 0 (8K Page 4,5,6,7 <- Bank 0*4+0,0*4+1,0*4+2,0*4+3) break; } // nes->SetRenderMethod( NES::TILE_RENDER ); DWORD crc = nes->rom->GetPROM_CRC(); if( crc == 0x2b72fe7e ) { // Ganso Saiyuuki - Super Monkey Dai Bouken(J) nes->SetRenderMethod( NES::TILE_RENDER ); nes->ppu->SetExtNameTableMode( TRUE ); } // if( crc == 0xE44D95B5 ) { // ‚Ђ݂‚— // } } #if 0 void Mapper003::WriteLow( WORD addr, BYTE data ) { if( patch ) { Mapper::WriteLow( addr, data ); } else { if( nes->rom->IsSAVERAM() ) { Mapper::WriteLow( addr, data ); } else { if( addr >= 0x4800 ) { SetVROM_8K_Bank( data & 0x03 ); } } } } #endif void Mapper003::Write( WORD addr, BYTE data ) { SetVROM_8K_Bank( data ); //VROM Bank Number = data }
[ "yyl_20050115@hotmail.com" ]
yyl_20050115@hotmail.com
fabfaa1484f6db5468d804b3dbb429ad72ff276d
f4f8ddc1eb63cec391f4478876dab09f82b8bd89
/src/net/TgLongPoll.cpp
91bf058dcff8631c51c5cfd5c2403776baa6de63
[ "MIT" ]
permissive
Omrigan/tgbot-cpp
b1268473cdc64c60470be5db10bcb95296e2c21e
142b526311431ded4022f349a52fd109d88c9ca3
refs/heads/master
2021-09-08T14:22:41.725786
2018-03-10T13:27:20
2018-03-10T13:27:20
124,658,251
0
1
MIT
2018-03-10T13:29:31
2018-03-10T13:29:31
null
UTF-8
C++
false
false
1,661
cpp
/* * Copyright (c) 2015 Oleg Morozenkov * * 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 "tgbot/net/TgLongPoll.h" namespace TgBot { TgLongPoll::TgLongPoll(const Api* api, const EventHandler* eventHandler) : _api(api), _eventHandler(eventHandler) { } TgLongPoll::TgLongPoll(const Bot& bot) : TgLongPoll(&bot.getApi(), &bot.getEventHandler()) { } void TgLongPoll::start() { std::vector<Update::Ptr> updates = _api->getUpdates(_lastUpdateId, 100, 60); for (Update::Ptr& item : updates) { if (item->updateId >= _lastUpdateId) { _lastUpdateId = item->updateId + 1; } _eventHandler->handleUpdate(item); } } }
[ "omorozenkov@gmail.com" ]
omorozenkov@gmail.com
44208ca363fb843de67454724820e8ef2ed4cfd7
df7cd8ef6bc16aef31de7e878aa64a33632c8f1d
/fp2Tester.cpp
85bb23ca632379a56069b461c6cf95a62a6b53ed
[]
no_license
k1tam/hospital-patient-system
e2afc395830535caaaf7cef0d400a103a892929f
3563d58c67ba5395fc250a49f4f1b5ecfb192241
refs/heads/main
2023-08-05T09:39:18.018155
2021-09-14T04:18:00
2021-09-14T04:18:00
406,221,439
0
0
null
null
null
null
UTF-8
C++
false
false
947
cpp
// Final Project Tester // file: fp2Tester.cpp // Version: 1.0 // Date: 2021-06-23 // Author: Fardad // Description: // This file tests the Final project // overall functionality ///////////////////////////////////////////// #include <iostream> #include <fstream> #include "PreTriage.h" #include "utils.h" using namespace sdds; using namespace std; void displayFile(const char* fname) { ifstream fin(fname); char ch; cout << endl << "****** Content of file: \"" << fname << "\":" << endl; while (fin.get(ch)) cout << ch; cout << "***************************************************" << endl << endl; } void copyFile(const char* des, const char* src) { ifstream s(src); ofstream d(des); char ch = 0; while (s.get(ch) && d << ch); } int main() { sdds::debug = true; copyFile("smalldata.csv", "smalldata.csv.bak"); PreTriage P("smalldata.csv"); P.run(); return 0; }
[ "noreply@github.com" ]
noreply@github.com
6badc68f8bcb9e97f1a5e6789561b2ebc3471aec
8efac62c1a7a75c0d22e93ccf874364adc743dca
/K_Concatenation.cpp
4f29856eb46d57adb1bd0cccef326aab4cd6926e
[]
no_license
me190003017/Dp_Questions
afdab1cc48e025669e39018f41f3dc7e55769f47
20be412c6742c493473c49976bd0e298f9b9f595
refs/heads/master
2023-03-27T23:02:55.958788
2021-04-05T04:40:05
2021-04-05T04:40:05
354,719,334
1
0
null
null
null
null
UTF-8
C++
false
false
993
cpp
#include<bits/stdc++.h> using namespace std; int kadans(int arr[],int n){ int overall_sum=arr[0]; int current_sum=arr[0]; for(int i=1;i<n;i++){ if(current_sum<0){ current_sum=arr[i]; }else{ current_sum+=arr[i]; } if(current_sum>overall_sum){ overall_sum=current_sum; } } return overall_sum; } int kadansofTwo(int arr[],int n){ int newarr[2*n]; for(int i=0;i<n;i++){ newarr[i]=arr[i]; } for(int i=0;i<n;i++){ newarr[n+i]=arr[i]; } return kadans(newarr,2*n); } void solve(){ int n; cin>>n; int arr[n]; int sum=0; for(int i=0;i<n;i++){ cin>>arr[i]; sum+=arr[i]; } int k; cin>>k; if(k==1){ cout<<kadans(arr,n)<<endl; }else if(sum<0){ cout<<kadansofTwo(arr,n)<<endl; }else{ cout<<kadansofTwo(arr,n)+(k-2)*sum<<endl; } } int main(){ solve(); return 0; }
[ "bhupendrasingh62435@gmail.com" ]
bhupendrasingh62435@gmail.com
157e32639c86ea4b3f32c2c282608a465dcb9f4b
315420052d5e39cff75b2c977d959b0138a49bfc
/Leetcode/Prepare-Google/Leetcode 139.Word Break.cpp
f8f271abf175c6d339ab11e2f30c5b4473e0c44f
[]
no_license
seawood/Leetcode-JianzhiOffer
ff46474b3146a7c50a5a117b6e4aa2becd8ec761
ec4c9510582ef0bddc88a3d070042a21771360a3
refs/heads/master
2022-02-23T17:33:56.792847
2019-09-24T03:48:11
2019-09-24T03:48:11
123,068,470
1
1
null
null
null
null
UTF-8
C++
false
false
1,102
cpp
//Leetcode 139. Word Break //类似背包问题的写法 bool wordBreak(string s, vector<string>& wordDict) { int len = wordDict.size(), s_len = s.size(); if(s_len == 0 || len == 0) return false; vector<bool> record(s_len+1, false); record[0] = true; for(int i = 0; i < len; ++i){ for(int j = 0; j <= s_len; ++j){ for(int k = 0; k <= i; ++k){ int word_len = wordDict[k].size(); if(j >= word_len && record[j-word_len] == true && wordDict[k] == s.substr(j-word_len, word_len)) record[j] = true; } } } return record[s_len]; } bool wordBreak(string s, vector<string>& wordDict) { int len = s.size(); vector<bool> mark(len+1, false); mark[0] = true; for (int i = 1; i <= len; i++) { for (int j = i - 1; j >= 0; j--) { if (mark[j] && find(wordDict.begin(), wordDict.end(), s.substr(j, i - j)) != wordDict.end()) { mark[i] = true; break; } } } return mark[len]; }
[ "xyynku@163.com" ]
xyynku@163.com
532bc68b2651bed02cdb297cd093575f306dc9ec
61b6e7a70537962343b97063d4f9bf340ea63b7b
/Lib/LLVMJIT/EmitExceptions.cpp
e151b64f500bf296a8247c819c9f1d5b5aa5f14f
[ "BSD-3-Clause" ]
permissive
glycerine/wasm-jit-prototype
eaf077d7f29ccb0587c791f972b7be3cbfb524a8
93151f787838642db16bdb02fbdc17c029824f3f
refs/heads/master
2023-08-07T06:08:51.000234
2019-10-10T09:49:23
2019-10-10T09:49:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,185
cpp
#include <stddef.h> #include <memory> #include <vector> #include "EmitFunctionContext.h" #include "EmitModuleContext.h" #include "LLVMJITPrivate.h" #include "WAVM/IR/Module.h" #include "WAVM/IR/Operators.h" #include "WAVM/IR/Types.h" #include "WAVM/IR/Value.h" #include "WAVM/Inline/Assert.h" #include "WAVM/Inline/BasicTypes.h" #include "WAVM/Platform/Signal.h" #include "WAVM/RuntimeABI/RuntimeABI.h" PUSH_DISABLE_WARNINGS_FOR_LLVM_HEADERS #include <llvm/ADT/APInt.h> #include <llvm/IR/Argument.h> #include <llvm/IR/BasicBlock.h> #include <llvm/IR/Constant.h> #include <llvm/IR/Constants.h> #include <llvm/IR/DerivedTypes.h> #include <llvm/IR/Function.h> #include <llvm/IR/GlobalValue.h> #include <llvm/IR/GlobalVariable.h> #include <llvm/IR/IRBuilder.h> #include <llvm/IR/Instructions.h> #include <llvm/IR/Intrinsics.h> #include <llvm/IR/Type.h> #include <llvm/IR/Value.h> POP_DISABLE_WARNINGS_FOR_LLVM_HEADERS using namespace WAVM; using namespace WAVM::IR; using namespace WAVM::LLVMJIT; using namespace WAVM::Runtime; static llvm::Function* getCXABeginCatchFunction(EmitModuleContext& moduleContext) { if(!moduleContext.cxaBeginCatchFunction) { LLVMContext& llvmContext = moduleContext.llvmContext; moduleContext.cxaBeginCatchFunction = llvm::Function::Create( llvm::FunctionType::get(llvmContext.i8PtrType, {llvmContext.i8PtrType}, false), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "__cxa_begin_catch", moduleContext.llvmModule); } return moduleContext.cxaBeginCatchFunction; } static llvm::Function* getCXAEndCatchFunction(EmitModuleContext& moduleContext) { if(!moduleContext.cxaEndCatchFunction) { LLVMContext& llvmContext = moduleContext.llvmContext; moduleContext.cxaEndCatchFunction = llvm::Function::Create( llvm::FunctionType::get(llvm::Type::getVoidTy(llvmContext), false), llvm::GlobalValue::LinkageTypes::ExternalLinkage, "__cxa_end_catch", moduleContext.llvmModule); } return moduleContext.cxaEndCatchFunction; } void EmitFunctionContext::endTryWithoutCatch() { WAVM_ASSERT(tryStack.size()); tryStack.pop_back(); endTryCatch(); } void EmitFunctionContext::endTryCatch() { WAVM_ASSERT(catchStack.size()); CatchContext& catchContext = catchStack.back(); exitCatch(); // If an end instruction terminates a sequence of catch clauses, terminate the chain of // handler type ID tests by rethrowing the exception if its type ID didn't match any of the // handlers. llvm::BasicBlock* savedInsertionPoint = irBuilder.GetInsertBlock(); irBuilder.SetInsertPoint(catchContext.nextHandlerBlock); emitRuntimeIntrinsic( "throwException", FunctionType(TypeTuple{}, TypeTuple{inferValueType<Iptr>()}), {irBuilder.CreatePtrToInt(catchContext.exceptionPointer, llvmContext.iptrType)}); irBuilder.CreateUnreachable(); irBuilder.SetInsertPoint(savedInsertionPoint); catchStack.pop_back(); } void EmitFunctionContext::exitCatch() { ControlContext& currentContext = controlStack.back(); WAVM_ASSERT(currentContext.type == ControlContext::Type::catch_); WAVM_ASSERT(catchStack.size()); CatchContext& catchContext = catchStack.back(); if(currentContext.isReachable) { // Destroy the exception caught by the previous catch clause. emitRuntimeIntrinsic( "destroyException", FunctionType(TypeTuple{}, TypeTuple{inferValueType<Iptr>()}), {irBuilder.CreatePtrToInt(catchContext.exceptionPointer, llvmContext.iptrType)}); } } llvm::BasicBlock* EmitFunctionContext::getInnermostUnwindToBlock() { if(tryStack.size()) { return tryStack.back().unwindToBlock; } else { return nullptr; } } void EmitFunctionContext::try_(ControlStructureImm imm) { auto originalInsertBlock = irBuilder.GetInsertBlock(); if(moduleContext.useWindowsSEH) { // Insert an alloca for the exception pointer at the beginning of the function. irBuilder.SetInsertPoint(&function->getEntryBlock(), function->getEntryBlock().getFirstInsertionPt()); llvm::Value* exceptionPointerAlloca = irBuilder.CreateAlloca(llvmContext.i8PtrType, nullptr, "exceptionPointer"); // Create a BasicBlock with a CatchSwitch instruction to use as the unwind target. auto catchSwitchBlock = llvm::BasicBlock::Create(llvmContext, "catchSwitch", function); irBuilder.SetInsertPoint(catchSwitchBlock); auto catchSwitchInst = irBuilder.CreateCatchSwitch(llvm::ConstantTokenNone::get(llvmContext), nullptr, 1); // Create a block+catchpad that the catchswitch will transfer control if the exception type // info matches a WAVM runtime exception. auto catchPadBlock = llvm::BasicBlock::Create(llvmContext, "catchPad", function); catchSwitchInst->addHandler(catchPadBlock); irBuilder.SetInsertPoint(catchPadBlock); auto catchPadInst = irBuilder.CreateCatchPad(catchSwitchInst, {moduleContext.runtimeExceptionTypeInfo, emitLiteral(llvmContext, I32(0)), exceptionPointerAlloca}); // Create a catchret that immediately returns from the catch "funclet" to a new non-funclet // basic block. auto catchBlock = llvm::BasicBlock::Create(llvmContext, "catch", function); irBuilder.CreateCatchRet(catchPadInst, catchBlock); irBuilder.SetInsertPoint(catchBlock); // Load the exception pointer from the alloca that the catchpad wrote it to. auto exceptionPointer = loadFromUntypedPointer(exceptionPointerAlloca, llvmContext.i8PtrType); // Load the exception type ID. auto exceptionTypeId = loadFromUntypedPointer( irBuilder.CreateInBoundsGEP( exceptionPointer, {emitLiteral(llvmContext, Uptr(offsetof(Exception, typeId)))}), llvmContext.iptrType); tryStack.push_back(TryContext{catchSwitchBlock}); catchStack.push_back( CatchContext{catchSwitchInst, nullptr, exceptionPointer, catchBlock, exceptionTypeId}); } else { // Create a BasicBlock with a LandingPad instruction to use as the unwind target. auto landingPadBlock = llvm::BasicBlock::Create(llvmContext, "landingPad", function); irBuilder.SetInsertPoint(landingPadBlock); auto landingPadInst = irBuilder.CreateLandingPad( llvm::StructType::get(llvmContext, {llvmContext.i8PtrType, llvmContext.i32Type}), 1); landingPadInst->addClause(moduleContext.runtimeExceptionTypeInfo); // Call __cxa_begin_catch to get the exception pointer. auto exceptionPointer = irBuilder.CreateCall(getCXABeginCatchFunction(moduleContext), {irBuilder.CreateExtractValue(landingPadInst, {0})}); // Call __cxa_end_catch immediately to free memory used to throw the exception. irBuilder.CreateCall(getCXAEndCatchFunction(moduleContext)); // Load the exception type ID. auto exceptionTypeId = loadFromUntypedPointer( irBuilder.CreateInBoundsGEP( exceptionPointer, {emitLiteral(llvmContext, Uptr(offsetof(Exception, typeId)))}), llvmContext.iptrType); tryStack.push_back(TryContext{landingPadBlock}); catchStack.push_back(CatchContext{ nullptr, landingPadInst, exceptionPointer, landingPadBlock, exceptionTypeId}); } irBuilder.SetInsertPoint(originalInsertBlock); // Create an end try+phi for the try result. FunctionType blockType = resolveBlockType(irModule, imm.type); auto endBlock = llvm::BasicBlock::Create(llvmContext, "tryEnd", function); auto endPHIs = createPHIs(endBlock, blockType.results()); // Pop the try arguments. llvm::Value** tryArgs = (llvm::Value**)alloca(sizeof(llvm::Value*) * blockType.params().size()); popMultiple(tryArgs, blockType.params().size()); // Push a control context that ends at the end block/phi. pushControlStack(ControlContext::Type::try_, blockType.results(), endBlock, endPHIs); // Push a branch target for the end block/phi. pushBranchTarget(blockType.results(), endBlock, endPHIs); // Repush the try arguments. pushMultiple(tryArgs, blockType.params().size()); } void EmitFunctionContext::catch_(ExceptionTypeImm imm) { WAVM_ASSERT(controlStack.size()); WAVM_ASSERT(catchStack.size()); ControlContext& controlContext = controlStack.back(); CatchContext& catchContext = catchStack.back(); WAVM_ASSERT(controlContext.type == ControlContext::Type::try_ || controlContext.type == ControlContext::Type::catch_); if(controlContext.type == ControlContext::Type::try_) { WAVM_ASSERT(tryStack.size()); tryStack.pop_back(); } else { exitCatch(); } branchToEndOfControlContext(); // Look up the exception type instance to be caught WAVM_ASSERT(imm.exceptionTypeIndex < moduleContext.exceptionTypeIds.size()); const IR::ExceptionType catchType = irModule.exceptionTypes.getType(imm.exceptionTypeIndex); llvm::Constant* catchTypeId = moduleContext.exceptionTypeIds[imm.exceptionTypeIndex]; irBuilder.SetInsertPoint(catchContext.nextHandlerBlock); auto isExceptionType = irBuilder.CreateICmpEQ(catchContext.exceptionTypeId, catchTypeId); auto catchBlock = llvm::BasicBlock::Create(llvmContext, "catch", function); auto unhandledBlock = llvm::BasicBlock::Create(llvmContext, "unhandled", function); irBuilder.CreateCondBr(isExceptionType, catchBlock, unhandledBlock); catchContext.nextHandlerBlock = unhandledBlock; irBuilder.SetInsertPoint(catchBlock); // Push the exception arguments on the stack. for(Uptr argumentIndex = 0; argumentIndex < catchType.params.size(); ++argumentIndex) { const ValueType parameters = catchType.params[argumentIndex]; const Uptr argOffset = offsetof(Exception, arguments) + (catchType.params.size() - argumentIndex - 1) * sizeof(Exception::arguments[0]); auto argument = loadFromUntypedPointer( irBuilder.CreateInBoundsGEP(catchContext.exceptionPointer, {emitLiteral(llvmContext, argOffset)}), asLLVMType(llvmContext, parameters), sizeof(Exception::arguments[0])); push(argument); } // Change the top of the control stack to a catch clause. controlContext.type = ControlContext::Type::catch_; controlContext.isReachable = true; } void EmitFunctionContext::catch_all(NoImm) { WAVM_ASSERT(controlStack.size()); WAVM_ASSERT(catchStack.size()); ControlContext& controlContext = controlStack.back(); CatchContext& catchContext = catchStack.back(); WAVM_ASSERT(controlContext.type == ControlContext::Type::try_ || controlContext.type == ControlContext::Type::catch_); if(controlContext.type == ControlContext::Type::try_) { WAVM_ASSERT(tryStack.size()); tryStack.pop_back(); } else { exitCatch(); } branchToEndOfControlContext(); irBuilder.SetInsertPoint(catchContext.nextHandlerBlock); auto isUserExceptionType = irBuilder.CreateICmpNE( loadFromUntypedPointer( irBuilder.CreateInBoundsGEP( catchContext.exceptionPointer, {emitLiteral(llvmContext, Uptr(offsetof(Exception, isUserException)))}), llvmContext.i8Type), llvm::ConstantInt::get(llvmContext.i8Type, llvm::APInt(8, 0, false))); auto catchBlock = llvm::BasicBlock::Create(llvmContext, "catch", function); auto unhandledBlock = llvm::BasicBlock::Create(llvmContext, "unhandled", function); irBuilder.CreateCondBr(isUserExceptionType, catchBlock, unhandledBlock); catchContext.nextHandlerBlock = unhandledBlock; irBuilder.SetInsertPoint(catchBlock); // Change the top of the control stack to a catch clause. controlContext.type = ControlContext::Type::catch_; controlContext.isReachable = true; } void EmitFunctionContext::throw_(ExceptionTypeImm imm) { const IR::ExceptionType& exceptionType = irModule.exceptionTypes.getType(imm.exceptionTypeIndex); const Uptr numArgs = exceptionType.params.size(); const Uptr numArgBytes = numArgs * sizeof(UntaggedValue); auto argBaseAddress = irBuilder.CreateAlloca(llvmContext.i8Type, emitLiteral(llvmContext, numArgBytes)); argBaseAddress->setAlignment(sizeof(UntaggedValue)); for(Uptr argIndex = 0; argIndex < exceptionType.params.size(); ++argIndex) { auto elementValue = pop(); storeToUntypedPointer( elementValue, irBuilder.CreatePointerCast( irBuilder.CreateInBoundsGEP( argBaseAddress, {emitLiteral(llvmContext, (numArgs - argIndex - 1) * sizeof(UntaggedValue))}), elementValue->getType()->getPointerTo()), sizeof(UntaggedValue)); } llvm::Value* exceptionTypeId = moduleContext.exceptionTypeIds[imm.exceptionTypeIndex]; llvm::Value* argsPointerAsInt = irBuilder.CreatePtrToInt(argBaseAddress, llvmContext.iptrType); llvm::Value* exceptionPointer = emitRuntimeIntrinsic( "createException", FunctionType(TypeTuple{inferValueType<Iptr>()}, TypeTuple{inferValueType<Iptr>(), inferValueType<Iptr>(), ValueType::i32}), {exceptionTypeId, argsPointerAsInt, emitLiteral(llvmContext, I32(1))})[0]; emitRuntimeIntrinsic("throwException", FunctionType(TypeTuple{}, TypeTuple{inferValueType<Iptr>()}), {irBuilder.CreatePtrToInt(exceptionPointer, llvmContext.iptrType)}); irBuilder.CreateUnreachable(); enterUnreachable(); } void EmitFunctionContext::rethrow(RethrowImm imm) { WAVM_ASSERT(imm.catchDepth < catchStack.size()); CatchContext& catchContext = catchStack[catchStack.size() - imm.catchDepth - 1]; emitRuntimeIntrinsic( "throwException", FunctionType(TypeTuple{}, TypeTuple{inferValueType<Iptr>()}), {irBuilder.CreatePtrToInt(catchContext.exceptionPointer, llvmContext.iptrType)}); irBuilder.CreateUnreachable(); enterUnreachable(); }
[ "andrew@scheidecker.net" ]
andrew@scheidecker.net
9046203aa8b5efa548c4a6f7b37955ac4de6f03b
f6ab96101246c8764dc16073cbea72a188a0dc1a
/volume105/10566 - Crossed Ladders.cpp
689840e0eead4d7a2e1e64840baf9e773b0b5775
[]
no_license
nealwu/UVa
c87ddc8a0bf07a9bd9cadbf88b7389790bc321cb
10ddd83a00271b0c9c259506aa17d03075850f60
refs/heads/master
2020-09-07T18:52:19.352699
2019-05-01T09:41:55
2019-05-01T09:41:55
220,883,015
3
2
null
2019-11-11T02:14:54
2019-11-11T02:14:54
null
UTF-8
C++
false
false
512
cpp
#include <stdio.h> #include <math.h> #define eps 1e-5 int main() { double c, x, y; while(scanf("%lf %lf %lf", &x, &y, &c) == 3) { double l = 0, r = x < y ? x : y, d, tc; while(1) { d = (l+r)/2; tc = sqrt(y*y-d*d)*sqrt(x*x-d*d)/(sqrt(y*y-d*d)+sqrt(x*x-d*d)); if(fabs(tc-c) <= eps) break; if(tc > c) l = d; else r = d; } printf("%.3lf\n", d); } return 0; }
[ "morris821028@gmail.com" ]
morris821028@gmail.com
f77a35dee628ed82c709fb991a86e1a308881147
2ba4693bf7441ac8a56a7d5750acd036191b4b21
/MainOld.cpp
e661e35bc1a4befc9a5f1145b8ea530b65f7d933
[]
no_license
ShanoToni/PhysicsAnimation
5c2339507d90f9b5abe0da41bacd7b554bf5c37f
f1a7db5cff7bcb31ef2e47ed8595979bbbb1a370
refs/heads/master
2021-08-28T17:01:39.684173
2017-12-12T21:17:07
2017-12-12T21:17:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,884
cpp
#if 0 #include "Particle.h" #include "Application.h" #include "Shader.h" #include <random> // Std. Includes #include <string> #include <time.h> #include <array> // Other Libs #include "SOIL2/SOIL2.h" /* Vectors and Arrays */ glm::vec3 cpoint = glm::vec3(-6.0f, 0.0f, -6.0f); glm::vec3 size = glm::vec3(12.0f, 12.0f, 12.0f); /* FORCES */ /* void createHooks(std::array<Particle, 5>p) { std::array<Hook, 4>hooks; for (int i=0;i<4;i++) { hooks[i] = Hook( 10.0f, 1.0f, .5f); } } */ void addCollision(Particle &p) { for (int i = 0; i < 3; i++) { if (p.getTranslate()[3][i] < cpoint[i] + 0.1f || p.getTranslate()[3][i] > size[i] + cpoint[i] - 0.1f) { p.getVel()[i] *= -1.f; } if (p.getPos()[i] < cpoint[i] + 0.1f) { p.getPos()[i] = cpoint[i] + 0.1f; } if (p.getPos()[i] > size[i] + cpoint[i] - 0.1f) { p.getPos()[i] = size[i] + cpoint[i] - 0.1f; } } } void createParticles(std::array<Particle,5>&p, Force *g, Force *drag) { float gap = 1.0f; for(int i=0;i<5;i++) { p[i].translate(glm::vec3(1.0f+gap, 10.0f, 0.0f)); p[i].scale(glm::vec3(3.f, 3.f, 3.f)); p[i].setVel(glm::vec3(0.0f, 1.0f, .0f)); p[i].getMesh().setShader(Shader("resources/shaders/core.vert", "resources/shaders/core_blue.frag")); gap ++; if (i > 0) { p[i].addForce(g); p[i].addForce(drag); } } } /* void addForces(std::array<Particle, 5>&p,std::array<Hook,4>hooks) {} */ void setAcceleration(std::array<Particle, 5>&p) { for (int i = 1; i < p.size(); i++) { p[i].setAcc(p[i].applyForces(p[i].getPos(), p[i].getVel())); } } void setVelocitySI(std::array<Particle, 5>&p, const float time) { for (int i = 1;i<5;i++) { p[i].getVel() = p[i].getVel() + time*p[i].getAcc(); p[i].setPos(p[i].getPos() + time*(p[i].getVel())); } } void renderParticles(std::array<Particle, 5>&p,Application app) { for(int i =0; i < 5; i++) { app.draw(p[i].getMesh()); } } int main() { // create application Application app = Application::Application(); app.initRender(); Application::camera.setCameraPosition(glm::vec3(0.0f, 5.0f, 20.0f)); // create ground plane Mesh plane = Mesh::Mesh(); // scale it up x5 plane.scale(glm::vec3(20.0f, 5.0f, 20.0f)); plane.setShader(Shader("resources/shaders/core.vert", "resources/shaders/core.frag")); Gravity g = Gravity(); Drag drag = Drag(); std::array<Hook, 4> hooks; float ks = 10.0f; float kd = 3.0f; for (auto &hook : hooks) { hook = Hook(ks, kd , 0.05f); } std::array<Hook, 4> bhooks; for (auto &hook : bhooks) { hook = Hook(ks, kd, 0.05f); ks*=0.6f; } std::array<Particle, 5> particles; createParticles(particles , &g , &drag); for (int i = 0; i<hooks.size(); i++) { hooks[i].setBodies(&particles[i], &particles[i + 1]); } for (int i = bhooks.size()-1; i>=0; i--) { bhooks[i].setBodies(&particles[i+1], &particles[i]); } particles[1].addForce(&hooks[0]); particles[2].addForce(&hooks[1]); particles[3].addForce(&hooks[2]); particles[4].addForce(&hooks[3]); particles[1].addForce(&bhooks[1]); particles[2].addForce(&bhooks[2]); particles[3].addForce(&bhooks[3]); // new time const float dt = 0.01f; float accumulator = 0.0f; GLfloat currentTime = (GLfloat)glfwGetTime(); // Game loop while (!glfwWindowShouldClose(app.getWindow())) { //New frame time GLfloat newTime = (GLfloat)glfwGetTime(); GLfloat frameTime = newTime - currentTime; currentTime = newTime; accumulator += frameTime; app.doMovement(dt); addCollision(particles[1]); addCollision(particles[2]); addCollision(particles[3]); addCollision(particles[4]); setAcceleration(particles); while (accumulator >= dt) { setVelocitySI(particles, dt); accumulator -= dt; } // clear buffer app.clear(); app.draw(plane); renderParticles(particles, app); app.display(); } app.terminate(); return EXIT_SUCCESS; } #endif
[ "anton_b_mitkov@abv.bg" ]
anton_b_mitkov@abv.bg
426ac38d0d281e2ee41f80f64b58fab1d87b8d3a
125c36549274f18c7795982ae8d3afe5e0698dd7
/template/lis.cpp
b892627184a759fc4e82d930409ef4da74c0965c
[]
no_license
callmebg/luogu
518d75ef6b1f60d735f7fb45e074959fd5e7ce10
cde510c7ae01810188f1442512e9fa2166b17a91
refs/heads/master
2020-04-11T02:01:35.222429
2018-12-12T04:44:35
2018-12-12T04:44:35
161,433,125
53
0
null
null
null
null
UTF-8
C++
false
false
476
cpp
#include<cstdio> #include<iostream> #include<algorithm> using namespace std; const int N = 100008; int to[N],n; int t,tow[N]; int dl[N],en; int main() { int a,b; int *p; scanf("%d",&n); for(a=1;a<=n;a++) scanf("%d",&t),to[t]=a; for(a=1;a<=n;a++) scanf("%d",&t),tow[a]=to[t]; dl[1]=tow[1]; en=1; for(a=2;a<=n;a++) { p=lower_bound(dl+1,dl+1+en,tow[a]); if(p==dl+1+en) dl[++en]=tow[a]; else *p=tow[a]; } printf("%d",en); return 0; }
[ "noreply@github.com" ]
noreply@github.com
6081915c0cfdd991159c3662660626b55b0454ac
1db694c43ba7044acf28e4883d0d35213bad3311
/DuiLib/Core/UIBase.cpp
0f651fcd4be3b57811a60fe7701fb8c3af14a47f
[]
no_license
shanrenshushu/monitor
0e6af131f41a211006dfd7a88a0f4c41edeb9661
7982228bc9d8e9c06ba343cb47c91cfd114a2f96
refs/heads/master
2021-06-23T12:09:47.493441
2020-10-22T08:31:11
2020-10-22T08:31:11
130,328,989
0
2
null
null
null
null
GB18030
C++
false
false
15,306
cpp
#include "StdAfx.h" #ifdef _DEBUG #include <shlwapi.h> #pragma comment(lib, "shlwapi.lib") #endif namespace DuiLib { ///////////////////////////////////////////////////////////////////////////////////// // // void UILIB_API DUI__Trace(LPCTSTR pstrFormat, ...) { #ifdef _DEBUG TCHAR szBuffer[300] = { 0 }; va_list args; va_start(args, pstrFormat); ::wvnsprintf(szBuffer, lengthof(szBuffer) - 2, pstrFormat, args); _tcscat(szBuffer, _T("\n")); va_end(args); ::OutputDebugString(szBuffer); #endif } LPCTSTR DUI__TraceMsg(UINT uMsg) { #define MSGDEF(x) if(uMsg==x) return _T(#x) MSGDEF(WM_SETCURSOR); MSGDEF(WM_NCHITTEST); MSGDEF(WM_NCPAINT); MSGDEF(WM_PAINT); MSGDEF(WM_ERASEBKGND); MSGDEF(WM_NCMOUSEMOVE); MSGDEF(WM_MOUSEMOVE); MSGDEF(WM_MOUSELEAVE); MSGDEF(WM_MOUSEHOVER); MSGDEF(WM_NOTIFY); MSGDEF(WM_COMMAND); MSGDEF(WM_MEASUREITEM); MSGDEF(WM_DRAWITEM); MSGDEF(WM_LBUTTONDOWN); MSGDEF(WM_LBUTTONUP); MSGDEF(WM_LBUTTONDBLCLK); MSGDEF(WM_RBUTTONDOWN); MSGDEF(WM_RBUTTONUP); MSGDEF(WM_RBUTTONDBLCLK); MSGDEF(WM_SETFOCUS); MSGDEF(WM_KILLFOCUS); MSGDEF(WM_MOVE); MSGDEF(WM_SIZE); MSGDEF(WM_SIZING); MSGDEF(WM_MOVING); MSGDEF(WM_GETMINMAXINFO); MSGDEF(WM_CAPTURECHANGED); MSGDEF(WM_WINDOWPOSCHANGED); MSGDEF(WM_WINDOWPOSCHANGING); MSGDEF(WM_NCCALCSIZE); MSGDEF(WM_NCCREATE); MSGDEF(WM_NCDESTROY); MSGDEF(WM_TIMER); MSGDEF(WM_KEYDOWN); MSGDEF(WM_KEYUP); MSGDEF(WM_CHAR); MSGDEF(WM_SYSKEYDOWN); MSGDEF(WM_SYSKEYUP); MSGDEF(WM_SYSCOMMAND); MSGDEF(WM_SYSCHAR); MSGDEF(WM_VSCROLL); MSGDEF(WM_HSCROLL); MSGDEF(WM_CHAR); MSGDEF(WM_SHOWWINDOW); MSGDEF(WM_PARENTNOTIFY); MSGDEF(WM_CREATE); MSGDEF(WM_NCACTIVATE); MSGDEF(WM_ACTIVATE); MSGDEF(WM_ACTIVATEAPP); MSGDEF(WM_CLOSE); MSGDEF(WM_DESTROY); MSGDEF(WM_GETICON); MSGDEF(WM_GETTEXT); MSGDEF(WM_GETTEXTLENGTH); static TCHAR szMsg[10]; ::wsprintf(szMsg, _T("0x%04X"), uMsg); return szMsg; } ///////////////////////////////////////////////////////////////////////////////////// // // ////////////////////////////////////////////////////////////////////////// // DUI_BASE_BEGIN_MESSAGE_MAP(CNotifyPump) DUI_END_MESSAGE_MAP() static const DUI_MSGMAP_ENTRY* DuiFindMessageEntry(const DUI_MSGMAP_ENTRY* lpEntry,TNotifyUI& msg ) { CDuiString sMsgType = msg.sType; CDuiString sCtrlName = msg.pSender->GetName(); const DUI_MSGMAP_ENTRY* pMsgTypeEntry = NULL; while (lpEntry->nSig != DuiSig_end) { if(lpEntry->sMsgType==sMsgType) { if(!lpEntry->sCtrlName.IsEmpty()) { if(lpEntry->sCtrlName==sCtrlName) { return lpEntry; } } else { pMsgTypeEntry = lpEntry; } } lpEntry++; } return pMsgTypeEntry; } bool CNotifyPump::AddVirtualWnd(CDuiString strName,CNotifyPump* pObject) { if( m_VirtualWndMap.Find(strName) == NULL ) { m_VirtualWndMap.Insert(strName.GetData(),(LPVOID)pObject); return true; } return false; } bool CNotifyPump::RemoveVirtualWnd(CDuiString strName) { if( m_VirtualWndMap.Find(strName) != NULL ) { m_VirtualWndMap.Remove(strName); return true; } return false; } bool CNotifyPump::LoopDispatch(TNotifyUI& msg) { const DUI_MSGMAP_ENTRY* lpEntry = NULL; const DUI_MSGMAP* pMessageMap = NULL; #ifndef UILIB_STATIC for(pMessageMap = GetMessageMap(); pMessageMap!=NULL; pMessageMap = (*pMessageMap->pfnGetBaseMap)()) #else for(pMessageMap = GetMessageMap(); pMessageMap!=NULL; pMessageMap = pMessageMap->pBaseMap) #endif { #ifndef UILIB_STATIC ASSERT(pMessageMap != (*pMessageMap->pfnGetBaseMap)()); #else ASSERT(pMessageMap != pMessageMap->pBaseMap); #endif if ((lpEntry = DuiFindMessageEntry(pMessageMap->lpEntries,msg)) != NULL) { goto LDispatch; } } return false; LDispatch: union DuiMessageMapFunctions mmf; mmf.pfn = lpEntry->pfn; bool bRet = false; int nSig; nSig = lpEntry->nSig; switch (nSig) { default: ASSERT(FALSE); break; case DuiSig_lwl: (this->*mmf.pfn_Notify_lwl)(msg.wParam,msg.lParam); bRet = true; break; case DuiSig_vn: (this->*mmf.pfn_Notify_vn)(msg); bRet = true; break; } return bRet; } void CNotifyPump::NotifyPump(TNotifyUI& msg) { ///遍历虚拟窗口 if( !msg.sVirtualWnd.IsEmpty() ){ for( int i = 0; i< m_VirtualWndMap.GetSize(); i++ ) { if( LPCTSTR key = m_VirtualWndMap.GetAt(i) ) { if( _tcsicmp(key, msg.sVirtualWnd.GetData()) == 0 ){ CNotifyPump* pObject = static_cast<CNotifyPump*>(m_VirtualWndMap.Find(key, false)); if( pObject && pObject->LoopDispatch(msg) ) return; } } } } /// //遍历主窗口 LoopDispatch( msg ); } ////////////////////////////////////////////////////////////////////////// /// CWindowWnd::CWindowWnd() : m_hWnd(NULL), m_OldWndProc(::DefWindowProc), m_bSubclassed(false) { } CWindowWnd::~CWindowWnd() { } HWND CWindowWnd::GetHWND() const { return m_hWnd; } UINT CWindowWnd::GetClassStyle() const { return 0; } LPCTSTR CWindowWnd::GetSuperClassName() const { return NULL; } CWindowWnd::operator HWND() const { return m_hWnd; } HWND CWindowWnd::CreateDuiWindow( HWND hwndParent, LPCTSTR pstrWindowName,DWORD dwStyle /*=0*/, DWORD dwExStyle /*=0*/ ) { return Create(hwndParent,pstrWindowName,dwStyle,dwExStyle,0,0,0,0,NULL); } HWND CWindowWnd::Create(HWND hwndParent, LPCTSTR pstrName, DWORD dwStyle, DWORD dwExStyle, const RECT rc, HMENU hMenu) { return Create(hwndParent, pstrName, dwStyle, dwExStyle, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, hMenu); } HWND CWindowWnd::Create(HWND hwndParent, LPCTSTR pstrName, DWORD dwStyle, DWORD dwExStyle, int x, int y, int cx, int cy, HMENU hMenu) { if( GetSuperClassName() != NULL && !RegisterSuperclass() ) return NULL; if( GetSuperClassName() == NULL && !RegisterWindowClass() ) return NULL; m_hWnd = ::CreateWindowEx(dwExStyle, GetWindowClassName(), pstrName, dwStyle, x, y, cx, cy, hwndParent, hMenu, CPaintManagerUI::GetInstance(), this); ASSERT(m_hWnd!=NULL); return m_hWnd; } HWND CWindowWnd::Subclass(HWND hWnd) { ASSERT(::IsWindow(hWnd)); ASSERT(m_hWnd==NULL); m_OldWndProc = SubclassWindow(hWnd, __WndProc); if( m_OldWndProc == NULL ) return NULL; m_bSubclassed = true; m_hWnd = hWnd; ::SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LPARAM>(this)); return m_hWnd; } void CWindowWnd::Unsubclass() { ASSERT(::IsWindow(m_hWnd)); if( !::IsWindow(m_hWnd) ) return; if( !m_bSubclassed ) return; SubclassWindow(m_hWnd, m_OldWndProc); m_OldWndProc = ::DefWindowProc; m_bSubclassed = false; } void CWindowWnd::ShowWindow(bool bShow /*= true*/, bool bTakeFocus /*= false*/) { ASSERT(::IsWindow(m_hWnd)); if( !::IsWindow(m_hWnd) ) return; ::ShowWindow(m_hWnd, bShow ? (bTakeFocus ? SW_SHOWNORMAL : SW_SHOWNOACTIVATE) : SW_HIDE); } UINT CWindowWnd::ShowModal() { ASSERT(::IsWindow(m_hWnd)); UINT nRet = 0; HWND hWndParent = GetWindowOwner(m_hWnd); ::ShowWindow(m_hWnd, SW_SHOWNORMAL); ::EnableWindow(hWndParent, FALSE); MSG msg = { 0 }; while( ::IsWindow(m_hWnd) && ::GetMessage(&msg, NULL, 0, 0) ) { if( msg.message == WM_CLOSE && msg.hwnd == m_hWnd ) { nRet = msg.wParam; ::EnableWindow(hWndParent, TRUE); ::SetFocus(hWndParent); } if( !CPaintManagerUI::TranslateMessage(&msg) ) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } if( msg.message == WM_QUIT ) break; } ::EnableWindow(hWndParent, TRUE); ::SetFocus(hWndParent); if( msg.message == WM_QUIT ) ::PostQuitMessage(msg.wParam); return nRet; } void CWindowWnd::Close(UINT nRet) { ASSERT(::IsWindow(m_hWnd)); if( !::IsWindow(m_hWnd) ) return; PostMessage(WM_CLOSE, (WPARAM)nRet, 0L); } void CWindowWnd::CenterWindow() { ASSERT(::IsWindow(m_hWnd)); ASSERT((GetWindowStyle(m_hWnd)&WS_CHILD)==0); RECT rcDlg = { 0 }; ::GetWindowRect(m_hWnd, &rcDlg); RECT rcArea = { 0 }; RECT rcCenter = { 0 }; HWND hWnd=*this; HWND hWndParent = ::GetParent(m_hWnd); HWND hWndCenter = ::GetWindowOwner(m_hWnd); if (hWndCenter!=NULL) hWnd=hWndCenter; // 处理多显示器模式下屏幕居中 MONITORINFO oMonitor = {}; oMonitor.cbSize = sizeof(oMonitor); ::GetMonitorInfo(::MonitorFromWindow(hWnd, MONITOR_DEFAULTTONEAREST), &oMonitor); rcArea = oMonitor.rcWork; if( hWndCenter == NULL ) rcCenter = rcArea; else ::GetWindowRect(hWndCenter, &rcCenter); int DlgWidth = rcDlg.right - rcDlg.left; int DlgHeight = rcDlg.bottom - rcDlg.top; // Find dialog's upper left based on rcCenter int xLeft = (rcCenter.left + rcCenter.right) / 2 - DlgWidth / 2; int yTop = (rcCenter.top + rcCenter.bottom) / 2 - DlgHeight / 2; // The dialog is outside the screen, move it inside if( xLeft < rcArea.left ) xLeft = rcArea.left; else if( xLeft + DlgWidth > rcArea.right ) xLeft = rcArea.right - DlgWidth; if( yTop < rcArea.top ) yTop = rcArea.top; else if( yTop + DlgHeight > rcArea.bottom ) yTop = rcArea.bottom - DlgHeight; ::SetWindowPos(m_hWnd, NULL, xLeft, yTop, -1, -1, SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE); } void CWindowWnd::SetIcon(UINT nRes) { HICON hIcon = (HICON)::LoadImage(CPaintManagerUI::GetInstance(), MAKEINTRESOURCE(nRes), IMAGE_ICON, ::GetSystemMetrics(SM_CXICON), ::GetSystemMetrics(SM_CYICON), LR_DEFAULTCOLOR); ASSERT(hIcon); ::SendMessage(m_hWnd, WM_SETICON, (WPARAM) TRUE, (LPARAM) hIcon); hIcon = (HICON)::LoadImage(CPaintManagerUI::GetInstance(), MAKEINTRESOURCE(nRes), IMAGE_ICON, ::GetSystemMetrics(SM_CXSMICON), ::GetSystemMetrics(SM_CYSMICON), LR_DEFAULTCOLOR); ASSERT(hIcon); ::SendMessage(m_hWnd, WM_SETICON, (WPARAM) FALSE, (LPARAM) hIcon); } bool CWindowWnd::RegisterWindowClass() { WNDCLASS wc = { 0 }; wc.style = GetClassStyle(); wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hIcon = NULL; wc.lpfnWndProc = CWindowWnd::__WndProc; wc.hInstance = CPaintManagerUI::GetInstance(); wc.hCursor = ::LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = GetWindowClassName(); ATOM ret = ::RegisterClass(&wc); ASSERT(ret!=NULL || ::GetLastError()==ERROR_CLASS_ALREADY_EXISTS); return ret != NULL || ::GetLastError() == ERROR_CLASS_ALREADY_EXISTS; } bool CWindowWnd::RegisterSuperclass() { // Get the class information from an existing // window so we can subclass it later on... WNDCLASSEX wc = { 0 }; wc.cbSize = sizeof(WNDCLASSEX); if( !::GetClassInfoEx(NULL, GetSuperClassName(), &wc) ) { if( !::GetClassInfoEx(CPaintManagerUI::GetInstance(), GetSuperClassName(), &wc) ) { ASSERT(!"Unable to locate window class"); return NULL; } } m_OldWndProc = wc.lpfnWndProc; wc.lpfnWndProc = CWindowWnd::__ControlProc; wc.hInstance = CPaintManagerUI::GetInstance(); wc.lpszClassName = GetWindowClassName(); ATOM ret = ::RegisterClassEx(&wc); ASSERT(ret!=NULL || ::GetLastError()==ERROR_CLASS_ALREADY_EXISTS); return ret != NULL || ::GetLastError() == ERROR_CLASS_ALREADY_EXISTS; } LRESULT CALLBACK CWindowWnd::__WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CWindowWnd* pThis = NULL; if( uMsg == WM_NCCREATE ) { LPCREATESTRUCT lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam); pThis = static_cast<CWindowWnd*>(lpcs->lpCreateParams); pThis->m_hWnd = hWnd; ::SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LPARAM>(pThis)); } else { pThis = reinterpret_cast<CWindowWnd*>(::GetWindowLongPtr(hWnd, GWLP_USERDATA)); if( uMsg == WM_NCDESTROY && pThis != NULL ) { LRESULT lRes = ::CallWindowProc(pThis->m_OldWndProc, hWnd, uMsg, wParam, lParam); ::SetWindowLongPtr(pThis->m_hWnd, GWLP_USERDATA, 0L); if( pThis->m_bSubclassed ) pThis->Unsubclass(); pThis->m_hWnd = NULL; pThis->OnFinalMessage(hWnd); return lRes; } } if( pThis != NULL ) { return pThis->HandleMessage(uMsg, wParam, lParam); } else { return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } } LRESULT CALLBACK CWindowWnd::__ControlProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { CWindowWnd* pThis = NULL; if( uMsg == WM_NCCREATE ) { LPCREATESTRUCT lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam); pThis = static_cast<CWindowWnd*>(lpcs->lpCreateParams); ::SetProp(hWnd, _T("WndX"), (HANDLE) pThis); pThis->m_hWnd = hWnd; } else { pThis = reinterpret_cast<CWindowWnd*>(::GetProp(hWnd, _T("WndX"))); if( uMsg == WM_NCDESTROY && pThis != NULL ) { LRESULT lRes = ::CallWindowProc(pThis->m_OldWndProc, hWnd, uMsg, wParam, lParam); if( pThis->m_bSubclassed ) pThis->Unsubclass(); ::SetProp(hWnd, _T("WndX"), NULL); pThis->m_hWnd = NULL; pThis->OnFinalMessage(hWnd); return lRes; } } if( pThis != NULL) { return pThis->HandleMessage(uMsg, wParam, lParam); } else { return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } } LRESULT CWindowWnd::SendMessage(UINT uMsg, WPARAM wParam /*= 0*/, LPARAM lParam /*= 0*/) { ASSERT(::IsWindow(m_hWnd)); return ::SendMessage(m_hWnd, uMsg, wParam, lParam); } LRESULT CWindowWnd::PostMessage(UINT uMsg, WPARAM wParam /*= 0*/, LPARAM lParam /*= 0*/) { ASSERT(::IsWindow(m_hWnd)); return ::PostMessage(m_hWnd, uMsg, wParam, lParam); } void CWindowWnd::ResizeClient(int cx /*= -1*/, int cy /*= -1*/) { ASSERT(::IsWindow(m_hWnd)); RECT rc = { 0 }; if( !::GetClientRect(m_hWnd, &rc) ) return; if( cx != -1 ) rc.right = cx; if( cy != -1 ) rc.bottom = cy; if( !::AdjustWindowRectEx(&rc, GetWindowStyle(m_hWnd), (!(GetWindowStyle(m_hWnd) & WS_CHILD) && (::GetMenu(m_hWnd) != NULL)), GetWindowExStyle(m_hWnd)) ) return; ::SetWindowPos(m_hWnd, NULL, 0, 0, rc.right - rc.left, rc.bottom - rc.top, SWP_NOZORDER | SWP_NOMOVE | SWP_NOACTIVATE); } LRESULT CWindowWnd::HandleMessage(UINT uMsg, WPARAM wParam, LPARAM lParam) { return ::CallWindowProc(m_OldWndProc, m_hWnd, uMsg, wParam, lParam); } void CWindowWnd::OnFinalMessage(HWND /*hWnd*/) { } void CWindowWnd::FullScreen() { ::GetClientRect(m_hWnd,&m_RestoreRect); CPoint point; ::ClientToScreen(m_hWnd,&point); m_RestoreRect.left=point.x; m_RestoreRect.top=point.y; m_RestoreRect.right+=point.x; m_RestoreRect.bottom+=point.y; MONITORINFO oMonitor = {}; oMonitor.cbSize = sizeof(oMonitor); ::GetMonitorInfo(::MonitorFromWindow(*this, MONITOR_DEFAULTTONEAREST), &oMonitor); CDuiRect rcWork = oMonitor.rcWork; ::SetWindowPos( m_hWnd, NULL, rcWork.left, rcWork.top, rcWork.GetWidth(), rcWork.GetHeight(), SWP_SHOWWINDOW | SWP_NOZORDER ); } void CWindowWnd::RestoreScreen() { ::SetWindowPos( m_hWnd, NULL, m_RestoreRect.left, m_RestoreRect.top, m_RestoreRect.GetWidth(), m_RestoreRect.GetHeight(), SWP_SHOWWINDOW | SWP_NOZORDER ); } } // namespace DuiLib
[ "1393105176@qq.com" ]
1393105176@qq.com
7422c081793b4cf3cd544d36794cb98abff06663
3dfa415d1ff295e86fedcc63a381d024b9c5dccc
/src/Generator.h
95bf6cd2331b96f69c98d5275a6bf1474e1f33cd
[]
no_license
Grzegorz-00/MCP_Parzen
93b427dbc5b5a04571d1c523e1841f2b43ab5233
02c25df6ee0d1de5f8dadeef25a5abbbf5abeb39
refs/heads/master
2016-08-12T22:06:46.345426
2016-02-15T18:16:55
2016-02-15T18:16:55
47,970,326
0
0
null
null
null
null
UTF-8
C++
false
false
443
h
#ifndef GENERATOR_H_ #define GENERATOR_H_ #include <cstdlib> #include <ctime> #include <random> #include <iostream> #include "Data.h" #include <cmath> class Generator { private: static float getGauss(float x, float mean, float variance); public: static void generateDoubleGauss(Data* data); static void generateTripleGauss(Data* data); static float orginalDoubleGauss(float x); static float orginalTripleGauss(float x); }; #endif
[ "grzegorz00new@gmail.com" ]
grzegorz00new@gmail.com
22799db770289a0866ba40947221857e41c17a4d
0d9c9a225825f5cdc74ec35189ef4fdc818672d9
/programing/Dialog2.cpp
12fbf40d9765e23fc328a0f1c3426073cc24541e
[]
no_license
Claireywp/Visual-C-MFC
ca7e2dfee7bfa92ea3d74774485f46550679c43e
b5065ad3551399e443dd00a9daafed89ecb3ec61
refs/heads/master
2021-05-07T23:11:20.395100
2017-10-18T13:28:03
2017-10-18T13:28:03
107,412,436
0
0
null
null
null
null
UTF-8
C++
false
false
2,223
cpp
// Dialog2.cpp : implementation file // #include "stdafx.h" #include "stu.h" #include "Dialog2.h" #include "Dialog1.h" #include "Dialog3.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif extern CString strTemp; extern CString strTemp1; extern CString strTemp2; extern CString strTemp3; extern CString strTemp4; extern CString aaaa; extern CString strTemp5; extern CString strTemp6; CString bbb; ///////////////////////////////////////////////////////////////////////////// // CDialog2 dialog CDialog2::CDialog2(CWnd* pParent /*=NULL*/) : CDialog(CDialog2::IDD, pParent) { //{{AFX_DATA_INIT(CDialog2) m_nAge = _T(""); //}}AFX_DATA_INIT } void CDialog2::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDialog2) DDX_Control(pDX, IDC_XL, m_XL); DDX_Control(pDX, IDC_Adress, m_Ad); DDX_Control(pDX, IDC_Mz, m_Mz); DDX_Control(pDX, IDC_Ah, m_Ah); DDX_Control(pDX, IDC_Sex, m_Sex); DDX_Control(pDX, IDC_Name, m_Name); DDX_Control(pDX, IDC_Age, m_Age); DDX_Text(pDX, IDC_Age, m_nAge); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDialog2, CDialog) //{{AFX_MSG_MAP(CDialog2) ON_BN_CLICKED(IDC_BUTTON2, OnButton2) ON_BN_CLICKED(IDC_BUTTON3, OnButton3) ON_BN_CLICKED(IDC_BUTTON1, OnButton1) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDialog2 message handlers void CDialog2::OnOK() { // TODO: Add extra validation here m_Age.SetWindowText (strTemp) ; m_Sex.SetWindowText(strTemp2); m_Name.SetWindowText(strTemp1); // CString hoob; //hoob=strTemp3+" "+strTemp4; m_Ah.SetWindowText(strTemp3); // m_Ah.SetWindowText(strTemp4); m_Mz.SetWindowText(aaaa); m_XL.SetWindowText(strTemp6); m_Ad.SetWindowText(strTemp5); } void CDialog2::OnButton2() { // TODO: Add your control notification handler code here CDialog::OnOK(); } void CDialog2::OnButton3() { // TODO: Add your control notification handler code here CDialog1 dlg; dlg.DoModal (); } void CDialog2::OnButton1() { // TODO: Add your control notification handler code here CDialog3 dlg; m_Name.GetWindowText(bbb); dlg.m_ndeit2=bbb; dlg.DoModal(); CDialog::OnOK(); }
[ "1377877512ywp@sina.com" ]
1377877512ywp@sina.com
ebd065672c2ec36793e4020534560c854b69d8bc
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/third_party/pdfium/core/fxcrt/cfx_retain_ptr_unittest.cpp
4e74e52768fa1e19237261b3c4193600bafe2441
[ "BSD-3-Clause", "Apache-2.0", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT" ]
permissive
webosce/chromium53
f8e745e91363586aee9620c609aacf15b3261540
9171447efcf0bb393d41d1dc877c7c13c46d8e38
refs/heads/webosce
2020-03-26T23:08:14.416858
2018-08-23T08:35:17
2018-09-20T14:25:18
145,513,343
0
2
Apache-2.0
2019-08-21T22:44:55
2018-08-21T05:52:31
null
UTF-8
C++
false
false
5,814
cpp
// Copyright 2016 PDFium 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 "core/fxcrt/include/cfx_retain_ptr.h" #include <utility> #include "testing/fx_string_testhelpers.h" #include "testing/gtest/include/gtest/gtest.h" namespace { class PseudoRetainable { public: PseudoRetainable() : retain_count_(0), release_count_(0) {} void Retain() { ++retain_count_; } void Release() { ++release_count_; } int retain_count() const { return retain_count_; } int release_count() const { return release_count_; } private: int retain_count_; int release_count_; }; } // namespace TEST(fxcrt, RetainPtrNull) { CFX_RetainPtr<PseudoRetainable> ptr; EXPECT_EQ(nullptr, ptr.Get()); } TEST(fxcrt, RetainPtrNormal) { PseudoRetainable obj; { CFX_RetainPtr<PseudoRetainable> ptr(&obj); EXPECT_EQ(&obj, ptr.Get()); EXPECT_EQ(1, obj.retain_count()); EXPECT_EQ(0, obj.release_count()); } EXPECT_EQ(1, obj.retain_count()); EXPECT_EQ(1, obj.release_count()); } TEST(fxcrt, RetainPtrCopyCtor) { PseudoRetainable obj; { CFX_RetainPtr<PseudoRetainable> ptr1(&obj); { CFX_RetainPtr<PseudoRetainable> ptr2(ptr1); EXPECT_EQ(2, obj.retain_count()); EXPECT_EQ(0, obj.release_count()); } EXPECT_EQ(2, obj.retain_count()); EXPECT_EQ(1, obj.release_count()); } EXPECT_EQ(2, obj.retain_count()); EXPECT_EQ(2, obj.release_count()); } TEST(fxcrt, RetainPtrMoveCtor) { PseudoRetainable obj; { CFX_RetainPtr<PseudoRetainable> ptr1(&obj); { CFX_RetainPtr<PseudoRetainable> ptr2(std::move(ptr1)); EXPECT_EQ(1, obj.retain_count()); EXPECT_EQ(0, obj.release_count()); } EXPECT_EQ(1, obj.retain_count()); EXPECT_EQ(1, obj.release_count()); } EXPECT_EQ(1, obj.retain_count()); EXPECT_EQ(1, obj.release_count()); } TEST(fxcrt, RetainPtrResetNull) { PseudoRetainable obj; { CFX_RetainPtr<PseudoRetainable> ptr(&obj); ptr.Reset(); EXPECT_EQ(1, obj.retain_count()); EXPECT_EQ(1, obj.release_count()); } EXPECT_EQ(1, obj.retain_count()); EXPECT_EQ(1, obj.release_count()); } TEST(fxcrt, RetainPtrReset) { PseudoRetainable obj1; PseudoRetainable obj2; { CFX_RetainPtr<PseudoRetainable> ptr(&obj1); ptr.Reset(&obj2); EXPECT_EQ(1, obj1.retain_count()); EXPECT_EQ(1, obj1.release_count()); EXPECT_EQ(1, obj2.retain_count()); EXPECT_EQ(0, obj2.release_count()); } EXPECT_EQ(1, obj1.retain_count()); EXPECT_EQ(1, obj1.release_count()); EXPECT_EQ(1, obj2.retain_count()); EXPECT_EQ(1, obj2.release_count()); } TEST(fxcrt, RetainPtrSwap) { PseudoRetainable obj1; PseudoRetainable obj2; { CFX_RetainPtr<PseudoRetainable> ptr1(&obj1); { CFX_RetainPtr<PseudoRetainable> ptr2(&obj2); ptr1.Swap(ptr2); EXPECT_EQ(1, obj1.retain_count()); EXPECT_EQ(0, obj1.release_count()); EXPECT_EQ(1, obj2.retain_count()); EXPECT_EQ(0, obj2.release_count()); } EXPECT_EQ(1, obj1.retain_count()); EXPECT_EQ(1, obj1.release_count()); EXPECT_EQ(1, obj2.retain_count()); EXPECT_EQ(0, obj2.release_count()); } EXPECT_EQ(1, obj1.retain_count()); EXPECT_EQ(1, obj1.release_count()); EXPECT_EQ(1, obj2.retain_count()); EXPECT_EQ(1, obj2.release_count()); } TEST(fxcrt, RetainPtrSwapNull) { PseudoRetainable obj1; { CFX_RetainPtr<PseudoRetainable> ptr1(&obj1); { CFX_RetainPtr<PseudoRetainable> ptr2; ptr1.Swap(ptr2); EXPECT_FALSE(ptr1); EXPECT_TRUE(ptr2); EXPECT_EQ(1, obj1.retain_count()); EXPECT_EQ(0, obj1.release_count()); } EXPECT_EQ(1, obj1.retain_count()); EXPECT_EQ(1, obj1.release_count()); } EXPECT_EQ(1, obj1.retain_count()); EXPECT_EQ(1, obj1.release_count()); } TEST(fxcrt, RetainPtrAssign) { PseudoRetainable obj; { CFX_RetainPtr<PseudoRetainable> ptr(&obj); { CFX_RetainPtr<PseudoRetainable> ptr2; ptr2 = ptr; EXPECT_EQ(2, obj.retain_count()); EXPECT_EQ(0, obj.release_count()); } EXPECT_EQ(2, obj.retain_count()); EXPECT_EQ(1, obj.release_count()); } EXPECT_EQ(2, obj.retain_count()); EXPECT_EQ(2, obj.release_count()); } TEST(fxcrt, RetainPtrEquals) { PseudoRetainable obj1; PseudoRetainable obj2; CFX_RetainPtr<PseudoRetainable> null_ptr1; CFX_RetainPtr<PseudoRetainable> obj1_ptr1(&obj1); CFX_RetainPtr<PseudoRetainable> obj2_ptr1(&obj2); { CFX_RetainPtr<PseudoRetainable> null_ptr2; EXPECT_TRUE(null_ptr1 == null_ptr2); CFX_RetainPtr<PseudoRetainable> obj1_ptr2(&obj1); EXPECT_TRUE(obj1_ptr1 == obj1_ptr2); CFX_RetainPtr<PseudoRetainable> obj2_ptr2(&obj2); EXPECT_TRUE(obj2_ptr1 == obj2_ptr2); } EXPECT_FALSE(null_ptr1 == obj1_ptr1); EXPECT_FALSE(null_ptr1 == obj2_ptr1); EXPECT_FALSE(obj1_ptr1 == obj2_ptr1); } TEST(fxcrt, RetainPtrNotEquals) { PseudoRetainable obj1; PseudoRetainable obj2; CFX_RetainPtr<PseudoRetainable> null_ptr1; CFX_RetainPtr<PseudoRetainable> obj1_ptr1(&obj1); CFX_RetainPtr<PseudoRetainable> obj2_ptr1(&obj2); { CFX_RetainPtr<PseudoRetainable> null_ptr2; CFX_RetainPtr<PseudoRetainable> obj1_ptr2(&obj1); CFX_RetainPtr<PseudoRetainable> obj2_ptr2(&obj2); EXPECT_FALSE(null_ptr1 != null_ptr2); EXPECT_FALSE(obj1_ptr1 != obj1_ptr2); EXPECT_FALSE(obj2_ptr1 != obj2_ptr2); } EXPECT_TRUE(null_ptr1 != obj1_ptr1); EXPECT_TRUE(null_ptr1 != obj2_ptr1); EXPECT_TRUE(obj1_ptr1 != obj2_ptr1); } TEST(fxcrt, RetainPtrBool) { PseudoRetainable obj1; CFX_RetainPtr<PseudoRetainable> null_ptr; CFX_RetainPtr<PseudoRetainable> obj1_ptr(&obj1); bool null_bool = null_ptr; bool obj1_bool = obj1_ptr; EXPECT_FALSE(null_bool); EXPECT_TRUE(obj1_bool); }
[ "changhyeok.bae@lge.com" ]
changhyeok.bae@lge.com
2292b1e4eaca056bf069022529919bf60cbc1d53
45193c63e2eeff53046acd781dedb10434b8b94d
/include/yaul/tml/if_fwd.hpp
7faab0c9dc547c31fa11bae4e635ee3e7d298ab2
[ "BSL-1.0" ]
permissive
ptomulik/yaul-tml
b3d39274f9c8b75f9fc2da05404f18f2a80b190b
2b8bf3f88742996bd8199375678cdebd6e3206d9
refs/heads/master
2021-01-22T13:41:47.026647
2015-03-16T15:10:10
2015-03-16T15:10:10
31,795,386
0
0
null
null
null
null
UTF-8
C++
false
false
850
hpp
// Copyright (C) 2014, Pawel Tomulik <ptomulik@meil.pw.edu.pl> // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // yaul/tml/if_fwd.hpp /** // doc: yaul/tml/if_fwd.hpp {{{ * \file yaul/tml/if_fwd.hpp * \brief Forward declarations for \ref yaul/tml/if.hpp */ // }}} #ifndef YAUL_TML_IF_FWD_HPP #define YAUL_TML_IF_FWD_HPP namespace yaul { namespace tml { template <class C, class T1, class T2> struct if_; } } // end namespace yaul::tml #include <yaul/tml/bool_fwd.hpp> namespace yaul { namespace tml { template <bool c, class T1, class T2> using if_c = if_<bool_<c>,T1,T2>; } } // end namespace yaul::tml #endif /* YAUL_TML_IF_FWD_HPP */ // vim: set expandtab tabstop=2 shiftwidth=2: // vim: set foldmethod=marker foldcolumn=4:
[ "ptomulik@meil.pw.edu.pl" ]
ptomulik@meil.pw.edu.pl
61b3468fcb30aa9039a601c593e9144ddaca4653
2c148e207664a55a5809a3436cbbd23b447bf7fb
/src/net/quic/core/quic_control_frame_manager.h
a70ce0e6a570275fa866b8966de1f00a65c93e41
[ "BSD-3-Clause" ]
permissive
nuzumglobal/Elastos.Trinity.Alpha.Android
2bae061d281ba764d544990f2e1b2419b8e1e6b2
4c6dad6b1f24d43cadb162fb1dbec4798a8c05f3
refs/heads/master
2020-05-21T17:30:46.563321
2018-09-03T05:16:16
2018-09-03T05:16:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,688
h
// Copyright (c) 2017 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. #ifndef NET_QUIC_CORE_QUIC_CONTROL_FRAME_MANAGER_H_ #define NET_QUIC_CORE_QUIC_CONTROL_FRAME_MANAGER_H_ #include "net/quic/core/frames/quic_frame.h" #include "net/quic/platform/api/quic_containers.h" #include "net/quic/platform/api/quic_string.h" namespace net { class QuicSession; namespace test { class QuicControlFrameManagerPeer; } // namespace test // Control frame manager contains a list of sent control frames with valid // control frame IDs. Control frames without valid control frame IDs include: // (1) non-retransmittable frames (e.g., ACK_FRAME, PADDING_FRAME, // STOP_WAITING_FRAME, etc.), (2) CONNECTION_CLOSE and IETF Quic // APPLICATION_CLOSE frames. // New control frames are added to the tail of the list when they are added to // the generator. Control frames are removed from the head of the list when they // get acked. Control frame manager also keeps track of lost control frames // which need to be retransmitted. class QUIC_EXPORT_PRIVATE QuicControlFrameManager { public: explicit QuicControlFrameManager(QuicSession* session); QuicControlFrameManager(const QuicControlFrameManager& other) = delete; QuicControlFrameManager(QuicControlFrameManager&& other) = delete; ~QuicControlFrameManager(); // Tries to send a WINDOW_UPDATE_FRAME. Buffers the frame if it cannot be sent // immediately. void WriteOrBufferRstStream(QuicControlFrameId id, QuicRstStreamErrorCode error, QuicStreamOffset bytes_written); // Tries to send a GOAWAY_FRAME. Buffers the frame if it cannot be sent // immediately. void WriteOrBufferGoAway(QuicErrorCode error, QuicStreamId last_good_stream_id, const QuicString& reason); // Tries to send a WINDOW_UPDATE_FRAME. Buffers the frame if it cannot be sent // immediately. void WriteOrBufferWindowUpdate(QuicStreamId id, QuicStreamOffset byte_offset); // Tries to send a BLOCKED_FRAME. Buffers the frame if it cannot be sent // immediately. void WriteOrBufferBlocked(QuicStreamId id); // Sends a PING_FRAME. void WritePing(); // Called when |frame| gets acked. Returns true if |frame| gets acked for the // first time, return false otherwise. bool OnControlFrameAcked(const QuicFrame& frame); // Called when |frame| is considered as lost. void OnControlFrameLost(const QuicFrame& frame); // Called by the session when the connection becomes writable. void OnCanWrite(); // Retransmit |frame| if it is still outstanding. Returns false if the frame // does not get retransmitted because the connection is blocked. Otherwise, // returns true. bool RetransmitControlFrame(const QuicFrame& frame); // Returns true if |frame| is outstanding and waiting to be acked. Returns // false otherwise. bool IsControlFrameOutstanding(const QuicFrame& frame) const; // Returns true if there is any lost control frames waiting to be // retransmitted. bool HasPendingRetransmission() const; // Returns true if there are any lost or new control frames waiting to be // sent. bool WillingToWrite() const; private: friend class test::QuicControlFrameManagerPeer; // Tries to write buffered control frames to the peer. void WriteBufferedFrames(); // Called when |frame| is sent for the first time or gets retransmitted. void OnControlFrameSent(const QuicFrame& frame); // Writes pending retransmissions if any. void WritePendingRetransmission(); // Retrieves the next pending retransmission. This must only be called when // there are pending retransmissions. QuicFrame NextPendingRetransmission() const; // Returns true if there are buffered frames waiting to be sent for the first // time. bool HasBufferedFrames() const; QuicDeque<QuicFrame> control_frames_; // Id of latest saved control frame. 0 if no control frame has been saved. QuicControlFrameId last_control_frame_id_; // The control frame at the 0th index of control_frames_. QuicControlFrameId least_unacked_; // ID of the least unsent control frame. QuicControlFrameId least_unsent_; // TODO(fayang): switch to linked_hash_set when chromium supports it. The bool // is not used here. // Lost control frames waiting to be retransmitted. QuicLinkedHashMap<QuicControlFrameId, bool> pending_retransmissions_; // Pointer to the owning QuicSession object. QuicSession* session_; }; } // namespace net #endif // NET_QUIC_CORE_QUIC_CONTROL_FRAME_MANAGER_H_
[ "jiawang.yu@spreadtrum.com" ]
jiawang.yu@spreadtrum.com
8d2644f6372dbc44472b1494c843d7424adca4e1
f43e0439caac176e8c843677b142bdb2e94f0aea
/src/actions/single_action/trap_class.h
ff7bbd8c4d9d56be4c24d559ec7b5bda81029fa5
[]
no_license
etano/simpimc
78034b3caf7905231ef537df3c92035f93928b04
943fb6e3ec399b1f7b9ea075a447806f4522a6fd
refs/heads/master
2020-06-01T07:36:03.448913
2017-01-03T18:16:07
2017-01-03T18:16:07
1,943,220
9
2
null
2016-02-25T12:49:30
2011-06-23T18:13:08
C++
UTF-8
C++
false
false
2,477
h
#ifndef SIMPIMC_ACTIONS_TRAP_CLASS_H_ #define SIMPIMC_ACTIONS_TRAP_CLASS_H_ #include "single_action_class.h" /// Harmonic well action class class Trap : public SingleAction { private: double omega; ///< Harmonic frequency of the trap double cofactor_a; ///< Constant from 4th order expansion of the action double cofactor_b; ///< Constant from 4th order expansion of the beta derivative of the action public: /// Constructor calls Init Trap(Path &path, Input &in, IO &out) : SingleAction(path, in, out) { omega = in.GetAttribute<double>("omega"); out.Write("/Actions/" + name + "/omega", omega); cofactor_a = 0.5 * path.GetTau() * omega * omega * (1. + path.GetTau() * path.GetTau() * omega * omega / 12.); cofactor_b = 0.5 * omega * omega * (1. + 3. * path.GetTau() * path.GetTau() * omega * omega / 12.); } /// Returns the beta derivative of the action for the whole path virtual double DActionDBeta() { double tot = 0.; #pragma omp parallel for collapse(2) reduction(+ : tot) for (uint32_t p_i = 0; p_i < species->GetNPart(); p_i += 1) { for (uint32_t b_i = 0; b_i < species->GetNBead(); b_i += 1) { tot += dot(species->GetBead(p_i, b_i)->GetR(), species->GetBead(p_i, b_i)->GetR()); } } return cofactor_b * tot; } /// Returns the value of the action between time slices b0 and b1 for a vector of particles virtual double GetAction(const uint32_t b0, const uint32_t b1, const std::vector<std::pair<std::shared_ptr<Species>, uint32_t>> &particles, const uint32_t level) { if (level > max_level) return 0.; bool check = false; for (uint32_t p = 0; p < particles.size(); ++p) { if (particles[p].first == species) { check = true; break; } } if (!check) return 0.; uint32_t skip = 1 << level; double tot = 0.; for (uint32_t p = 0; p < particles.size(); ++p) { uint32_t p_i = particles[p].second; for (uint32_t b_i = b0; b_i < b1; b_i += skip) { tot += dot(species->GetBead(p_i, b_i)->GetR(), species->GetBead(p_i, b_i)->GetR()); } } return cofactor_a * skip * tot; } /// Write information about the action virtual void Write() {} }; #endif // SIMPIMC_ACTIONS_TRAP_CLASS_H_
[ "ethan.w.brown@gmail.com" ]
ethan.w.brown@gmail.com
cf44cca880eb57579b17efdd08068773151f026c
315dfe415bf99f9380bd678d70c35d19a5dceac6
/tests/ArticulationPointsTest.cpp
4b5548a9a5527fe112b489e1af7fbf154c4b5859
[]
no_license
froasio/MiscellaneousAlgorithms
00680c4f56433474c74418c3619781159266f229
d897c5feb1cfbf8dc1bafb3ebc8b1778a81315ba
refs/heads/master
2021-06-17T02:44:49.529215
2017-06-07T00:54:48
2017-06-07T00:54:48
68,478,654
1
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
#include "CppUTest/TestHarness.h" #include <cmath> #include "Digraph.h" #include "ArticulationPoints.h" TEST_GROUP(articulationPointsTest) { void setup() { } void teardown() { } }; TEST(articulationPointsTest, testArticulationPointsAlgorithm) { ifstream input("tests/graph_D.txt"); Graph g(input); ArticulationPoints ap(g); vector<int> aps = ap.getArticulationPoints(); vector<int> expectedAps = {2,3}; for(size_t i = 0; i < aps.size(); i++) { CHECK_EQUAL(expectedAps[i], aps[i]); } }
[ "federoasio@gmail.com" ]
federoasio@gmail.com
17dde00c522d619e9db26dcc3e7c5a0cdf368f9a
aff4b07ca4f11ab1f093da838c38faa72503d16d
/src_cpp/elf/utils/reflection.h
c30b1443e6d5941a6cef4a99b9e88a6126aa772d
[ "BSD-3-Clause" ]
permissive
qucheng/ELF-1
fb518d7c7af9d397161e167a5e9f8b42d0e1cddb
c7045787ae15abf36e08c68101bdeb192391a484
refs/heads/master
2020-03-17T16:11:50.162302
2019-01-22T22:34:16
2019-01-22T22:34:16
133,739,305
1
0
null
2018-05-17T00:55:22
2018-05-17T00:55:22
null
UTF-8
C++
false
false
4,855
h
#pragma once #include "member_check.h" /* Example usage * class Visitor { public: template <typename T> void visit(const std::string &name, const T& v, const std::string& help) const { std::cout << name << ", " << v << ", help: " << help << std::endl; } }; DEF_STRUCT(Options) DEF_FIELD(int, id, 0, "The id"); DEF_FIELD(std::string, name, "", "The name"); DEF_FIELD(float, salary, 0.0, "The salary"); DEF_END int main() { Options options; Visitor visitor; options.id = 2; options.name = "Smith"; options.salary = 2.5; options.apply(visitor); return 0; } * */ template <int I> class Idx { public: static constexpr int value = I; using prev_type = Idx<I - 1>; using next_type = Idx<I + 1>; }; template <typename C, typename I, int line_number> static constexpr int __NextCounter() { if constexpr (std::is_same<decltype(C::__identifier(I{})), int>::value) { return I::value; } else { return __NextCounter<C, Idx<I::value + 1>, line_number>(); } } #define _INIT(class_name) \ using __curr_type = class_name; \ static constexpr bool __reflection = true; \ template <typename I> \ static constexpr int __identifier(I); \ static constexpr bool __identifier(Idx<0>); \ template <typename Visit> \ void __apply(const Visit&, Idx<0>) const {} \ template <typename Visit> \ void __applyMutable(const Visit&, Idx<0>) {} \ template <typename Visit> \ static void __applyStatic(const Visit&, Idx<0>) {} #define DEF_STRUCT(class_name) \ struct class_name { \ _INIT(class_name) #define _MEMBER_FUNCS(name, help, idx_name) \ static constexpr int idx_name = \ __NextCounter<__curr_type, Idx<0>, __LINE__>(); \ static constexpr bool __identifier(Idx<idx_name>); \ template <typename Visit> \ void __apply(Visit& v, Idx<idx_name>) const { \ v.template visit(#name, name, help); \ __apply(v, Idx<idx_name - 1>{}); \ } \ template <typename Visit> \ void __applyMutable(Visit& v, Idx<idx_name>) { \ v.template visit(#name, name, help); \ __applyMutable(v, Idx<idx_name - 1>{}); \ } #define _STATIC_FUNCS(name, def, help, idx_name) \ template <typename Visit> \ static void __applyStatic(Visit& v, Idx<idx_name>) { \ v.template visit(#name, def, help); \ __applyStatic(v, Idx<idx_name - 1>{}); \ } #define _STATIC_FUNCS_NODEFAULT(type, name, help, idx_name) \ template <typename Visit> \ static void __applyStatic(Visit& v, Idx<idx_name>) { \ v.template visit(#name, type(), help); \ __applyStatic(v, Idx<idx_name - 1>{}); \ } #define CONCAT_(x, y) x##y #define CONCAT(x, y) CONCAT_(x, y) #define DEF_FIELD(type, name, def, help) \ DEF_FIELD_IMPL(type, name, def, help, CONCAT(__idx, name)) #define DEF_FIELD_IMPL(type, name, def, help, idx_name) \ type name = def; \ _MEMBER_FUNCS(name, help, idx_name) \ _STATIC_FUNCS(name, def, help, idx_name) #define DEF_FIELD_NODEFAULT(type, name, help) \ DEF_FIELD_NODEFAULT_IMPL(type, name, help, CONCAT(__idx, name)) #define DEF_FIELD_NODEFAULT_IMPL(type, name, help, idx_name) \ type name; \ _MEMBER_FUNCS(name, help, idx_name) \ _STATIC_FUNCS_NODEFAULT(type, name, help, idx_name) #define DEF_END \ static constexpr const int __final_idx = \ __NextCounter<__curr_type, Idx<0>, __LINE__>(); \ template <typename Visit> \ void apply(Visit& v) const { \ __apply(v, Idx<__final_idx - 1>{}); \ } \ template <typename Visit> \ void applyMutable(Visit& v) { \ __applyMutable(v, Idx<__final_idx - 1>{}); \ } \ template <typename Visit> \ static void applyStatic(Visit& v) { \ __applyStatic(v, Idx<__final_idx - 1>{}); \ } \ } \ ; namespace elf { namespace reflection { MEMBER_CHECK(__reflection) template <typename T> using has_reflection = has___reflection<T>; } // namespace reflection } // namespace elf
[ "yuandong.tian@gmail.com" ]
yuandong.tian@gmail.com
eaa2f7f005a3323e7ac7e277ef817d94fea42af4
436d5cde84d3ec4bd16c0b663c7fdc68db02a723
/ch10/ex10_11.cpp
eff5d49ce9ac68192dd63d54330ed02c9e4afcf1
[]
no_license
focus000/cppprimer
31f0cadd1ee69f20a6a2a20fc62ddfa0c5341b83
c901b55da35922a96857a108d25213fa37121b33
refs/heads/master
2020-09-13T04:56:55.130773
2020-05-09T09:23:00
2020-05-09T09:23:00
222,660,434
0
0
null
null
null
null
UTF-8
C++
false
false
804
cpp
#include <iostream> #include <vector> #include <string> #include <algorithm> using std::cout; using std::endl; using std::vector; using std::sort; using std::string; using std::unique; auto elimDups(vector<string> &vecstr) { sort(vecstr.begin(), vecstr.end()); auto end_unique = unique(vecstr.begin(), vecstr.end()); vecstr.erase(end_unique, vecstr.cend()); for (auto &&i : vecstr) { cout << i << " "; } cout << endl; } inline bool isShorter (string const &s1, string const &s2) { return s1.size() < s2.size(); } int main() { vector<string> vstr{"1234", "1234", "1234", "Hi", "alan", "wang"}; elimDups(vstr); std::stable_sort(vstr.begin(), vstr.end(), isShorter); for (auto &&i : vstr) { cout << i << " "; } cout << endl; }
[ "hanszimmerme@gmail.com" ]
hanszimmerme@gmail.com
bbcc4908defba71467cb3ec3e0a877977c2ce73e
da50a03667b54a8100a397a8c78be5078fe6f70e
/Game/Material.h
ecb32a4172e4ff00616b0aef2fd317692daf8bbf
[ "MIT" ]
permissive
roooodcastro/gamedev-coursework
33a618d3e72e1b29855cf866737e45a9c9961c21
a4bfdbd8f68cb641c0025ec70270b0a17e2e237d
refs/heads/master
2021-01-19T16:57:52.660664
2014-05-13T21:27:27
2014-05-13T21:27:27
16,929,092
1
0
null
null
null
null
UTF-8
C++
false
false
2,819
h
/* * Author: TheCPlusPlusGuy (http://www.youtube.com/user/thecplusplusguy) and Rodrigo Castro Azevedo * * Description: This class reads a .mtl file (Wavefront obj material file) and stores its attributes. * The material described here should be used with the models to correctly render them, using different * textures and light properties, etc. * * Note: This class cannot correctly load materials which contain more than one texture map. It will * only load the texture map associated with the diffuse light (map_Kd) */ #pragma once #include <cstdlib> #include <vector> #include <string> #include <algorithm> #include <functional> #include <cctype> #include <locale> #include <fstream> #include <cstdio> #include <iostream> #include "Vector2.h" #include "Vector3.h" #include "Texture.h" class Material { public: Material(void); Material(const Material &copy); Material(const char* name, float alpha, float ns, float ni, Vector3 &diffuse, Vector3 &ambient, Vector3 &specular, int illum, Texture &texture); ~Material(void); /* * This function loads materials from a .mtl file. It returns a vector because * a material file can define more than one material. */ static std::vector<Material*> loadMaterialsFromFile(const char *filename); /* * Checks if a .mtl file defines a material with the name specified */ static bool fileHasMaterial(const char *filename, const char *materialName); /* General getters and setters */ void setName(std::string &name) { this->name = name; } std::string getName() { return name; } void setDiffuse(Vector3 &diffuse) { *(this->diffuse) = diffuse; } Vector3 getDiffuse() { return *diffuse; } void setAmbient(Vector3 &ambient) { *(this->ambient) = ambient; } Vector3 getAmbient() { return *ambient; } void setSpecular(Vector3 &specular) { *(this->specular) = specular; } Vector3 getSpecular() { return *specular; } void setTexture(Texture &texture); Texture *getTexture() { return texture; } void setAlpha(float alpha) { this->alpha = alpha; } float getAlpha() { return alpha; } void setNs(float ns) { this->ns = ns; } float getNs() { return ns; } void setNi(float ni) { this->ni = ni; } float getNi() { return ni; } void setIllum(int illum) { this->illum = illum; } int getIllum() { return illum; } Material &operator=(const Material &other); protected: std::string name; // Name of this material float alpha; // Transparency of this material float ns; // Weight of the specular light (the bigger the shinier) float ni; // Optical Density (Index of Refraction), not used Vector3 *specular; // Colour of the specular light Vector3 *ambient; // Colour of the ambient light Vector3 *diffuse; // Colour of the diffuse light int illum; // Illumination model, not used Texture *texture; // The texture used for this material };
[ "rodrigocastro@id.uff.br" ]
rodrigocastro@id.uff.br
0fd0594571760eef07360374589549427298bded
88885e8e59855530c09ac930ae57914cbe4fe0f8
/Source/xs_source/FeatureCollectionImpl.cpp
20b8f29b2829f109793c90030ef6437da4ba55da
[]
no_license
klainqin/LandXmlSDK
8767c46c36b2257d388e50a25e64956c7c6ed020
ca52863d66d172b00835f66cef636790e668a52f
refs/heads/master
2021-01-10T08:30:45.007060
2015-11-25T10:20:13
2015-11-25T10:20:13
46,108,934
2
0
null
null
null
null
UTF-8
C++
false
false
551
cpp
#include "stdafx.h" #include "LXTypes.h" #include "LXTypesTmpl.inl" #include "FeatureCollectionImpl.h" namespace LX { FeatureCollection* createFeatureCollectionObject (DocumentImpl* pDocument) { FeatureCollection* pCollection = new FeatureCollectionImpl(pDocument); if (!pCollection) throw Exception(Exception::kUnableToAllocateMemory, L"Unable to allocate member"); return pCollection; } FeatureCollectionImpl::FeatureCollectionImpl (DocumentImpl* pDocument) { m_pDoc = pDocument; } }; // namespace : LX
[ "qink@shac02q6273g8wn.ads.autodesk.com" ]
qink@shac02q6273g8wn.ads.autodesk.com
4cd371042627c63405ca9b3b36d0cbb643567cf5
de9c0b5cb2cbed88ca0c009b62f3e93cb58a2020
/Expression.h
e56f0d3a038376e778370eeeb7bb53d89d260028
[]
no_license
OzTamir/CalC
c14df13a05f1b546612bc3c95ec943e2db08d5ef
7c4ca37a2ca2881d96530d56f1f3ce111f0b7b3c
refs/heads/master
2020-12-24T16:41:43.110979
2016-02-28T11:43:47
2016-02-28T11:43:47
52,711,031
0
0
null
null
null
null
UTF-8
C++
false
false
534
h
// // Created by Oz Tamir on 28/02/2016. // #ifndef CALC_EXPRESSION_H #define CALC_EXPRESSION_H #include <string> #include "Number.h" #include "Operator.h" class Expression : public Number { public: Expression(std::string stringValue); Expression(Number *lval, Number *rval, Operator *op); void evaluate(); Number* GetNumberValue(); Operator* GetOpValue(); bool isNumber(); private: Number *lval; Number *rval; Operator *op; Number *value; bool isNum; }; #endif //CALC_EXPRESSION_H
[ "TheOzTamir@gmail.com" ]
TheOzTamir@gmail.com
481e479c3e0d92d1638af4c08bbce06f30c55cd0
5ba0aca053f01d45f36058a542f51fdfd3b2745c
/GOSIMv2.0/GOSIM.cpp
6515526e25b66af3c2272ca79fec099e14d2fab2
[]
no_license
ZhouChuanyou/GOSIM_MPSAlgorithm
600e7c24eed65ad75a4afdb9b6e3310bdb48228c
b39dc58735bb5d16fb8b461aff7369ee9b32ca14
refs/heads/main
2023-01-02T23:01:44.041680
2020-10-18T00:09:25
2020-10-18T00:09:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,181
cpp
#include "GOSIM.h" #include "stdio.h" #include <algorithm> GOSIM::GOSIM() {} GOSIM::GOSIM(int varnum, int patx, int paty, int patz, int searchiter, int scale_num, vector<int> emiters, bool categorical, bool is3d, bool iscon, bool histmatch, int categorynum, vector<float> cdweight, string varianame, string outprefix, int factorx, int factory, int factorz, int simgridx, int simgridy, int simgridz, string ti_filename, string conda_filename, float low, float high) { VarNum = varnum; category_num = categorynum; // set the pattern size patternSizex = patx; patternSizey = paty; patternSizez = patz; Search_iterations = searchiter; // the iteration number for pattern search //the iteration number for each scale scales = scale_num; EM_iterations = emiters; IsCategorical = categorical; // is it categorical data? Is3D = is3d; HistMatch = histmatch; // does it need any highlight of some features? IsConditional = iscon; w = cdweight; variable_name = varianame; output_prefix = outprefix; resizefactorx = factorx; resizefactory = factory; resizefactorz = factorz; //calculate half of the pattern size halfPatSizex = patternSizex/2; halfPatSizey = patternSizey/2; halfPatSizez = patternSizez/2; TI = LoadData(ti_filename); ConData = LoadData(conda_filename); Real = CreateGrid(simgridx, simgridy, simgridz, VarNum, low, high); } Grid *GOSIM::CreateGrid(int length, int width, int height, int varnum, float low, float high) { Grid *newgrid = new Grid(length, width, height, varnum); for (int v = 0; v < varnum; ++v) for (int z = 0; z < height; ++z) for (int y = 0; y < width; ++y) for (int x = 0; x < length; ++x) { (*newgrid)(x, y, z, v) = randomFloat(low, high); } return newgrid; } void GOSIM::GOSIM_run(Grid *ti, Grid *real, int scale, int real_num) { currentscale = scale; int resizex = 1; int resizey = 1; int resizez = 1; for (int i = 0; i < scale-1; ++i) { resizex *= resizefactorx; resizey *= resizefactory; resizez *= resizefactorz; } Grid *condata = Relocation(ConData, resizex, resizey, resizez); minvalue_ti = find_min(ti); maxvalue_ti = find_max(ti); minvalue_real = find_min(real); maxvalue_real = find_max(real); //EM-iterations for (int i = 0; i < EM_iterations[scales - scale]; ++i) { printf("."); fflush(stdout); Grid *errmap = PatternSearch(ti, real, condata); //E-step:search for the most similar patterns GridUpdate(ti, real, errmap);//M-step:update the realization } //k-means for transforming continuous variables to categorical variables if (scale == 1) { if (IsCategorical) { Classify(real, category_num, 1); vector<float> indicators; indicators.push_back((*real)(0, 0, 0, 0)); for (int z = 0; z < real->height; ++z) { for (int y = 0; y < real->width; ++y) { for (int x = 0; x < real->length; ++x) { int i = 0; while (i < indicators.size()) { if ((*real)(x, y, z, 0) == indicators[i]) break; else ++i; } if (i == indicators.size()) indicators.push_back((*real)(x, y, z, 0)); if (indicators.size() >= category_num) break; } } } sort(indicators.begin(), indicators.end()); for (int z = 0; z < real->height; ++z) { for (int y = 0; y < real->width; ++y) { for (int x = 0; x < real->length; ++x) { for (int i = 0; i < indicators.size(); ++i) { if ((*real)(x, y, z, 0) == indicators[i]) (*real)(x, y, z, 0) = i; } } } } } Real = real; Reals.push_back(Real); } printf("\n"); } float GOSIM::find_min(Grid *grid) { float minvalue = (*grid)(0,0,0,0); for (int z = 0; z < grid->height; ++z) { for (int y = 0; y < grid->width; ++y) { for (int x = 0; x < grid->length; ++x) { float temp = (*grid)(x, y, z, 0); minvalue = min(temp, minvalue); } } } return minvalue; } float GOSIM::find_max(Grid *grid) { float maxvalue = (*grid)(0,0,0,0); for (int z = 0; z < grid->height; ++z) { for (int y = 0; y < grid->width; ++y) { for (int x = 0; x < grid->length; ++x) { float temp = (*grid)(x, y, z, 0); maxvalue = max(temp, maxvalue); } } } return maxvalue; }
[ "noreply@github.com" ]
noreply@github.com
48bc21d5df81bd030b97b46f81f9da586cf232e0
47ebc922fd0b70df2a51dda7b532068c6feb1cc9
/src/swm.cpp
ec7f8ad05a73086c294e5dc29abd3c8954a15174
[]
no_license
samjay/SQAT_7_segment_anim-1
d9b553353125a3f174302d46cdd0e870d74c6439
667cf76bbdbc3d77b345ddafd8d1c7ca9d2e6ba9
refs/heads/master
2021-01-11T04:02:13.029781
2016-10-18T07:55:55
2016-10-18T07:55:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
682
cpp
/* * switchmatrix.c * * Created on: Jun 6, 2016 * Author: timppa */ #include "chip.h" #include "swm.h" int SWM_init(LPC_SYSCTL_T* pLPC_SYSCON, LPC_SWM_T* pLPC_SWM) { if ( !pLPC_SYSCON || !pLPC_SWM ){ return SWM_RC_PARAM_ERROR; } // Enable SWM clock pLPC_SYSCON->SYSAHBCLKCTRL |= (1<<7); // SDA in PI0_10 pLPC_SWM->PINASSIGN[7] = 0x0AFFFFFF; // (p. 130) // SCL in PI0_11 pLPC_SWM->PINASSIGN[8] = 0xFFFFFF0B; // (p. 131) // Configure fixed-pin functions // These are default values -- could be changed pLPC_SWM->PINENABLE0 = 0xffffffb3UL; // (p. 132) // Disable SWM clock - power saving pLPC_SYSCON->SYSAHBCLKCTRL &= (~(1<<7)); return SWM_RC_OK; }
[ "ratytimo@gmail.com" ]
ratytimo@gmail.com
9b050e11f38521cf62ff06568049c814e6d65b10
92e238fee6b02207842489b76085ad767169d974
/tests/TestBuffer.cpp
de0039b8a7d441572ec5fd8289123b37d753ef8a
[ "MIT" ]
permissive
CIBC-Internal/cpm-var-buffer
0d96a8ba93fe90e8c539e09cf41bd861932be20d
a0ef955fa10a18d4261e19f289f476184380142b
refs/heads/master
2021-01-18T06:56:54.196792
2014-12-04T22:41:41
2014-12-04T22:41:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,566
cpp
#include <var-buffer/VarBuffer.hpp> #include <bserialize/BSerialize.hpp> #include <gtest/gtest.h> #include <memory> #include <cstring> namespace varbuff = CPM_VAR_BUFFER_NS; namespace { TEST(VarBuffer, BasicSerialization) { varbuff::VarBuffer vb; // Proceed close to 1024 limit. const size_t emptySize = 1020; char empty[emptySize]; std::memset(empty, 0, emptySize); vb.writeBytes(empty, emptySize); // After this write, we are at 1024. uint32_t v1 = 3; double v2 = 5.483; float v3 = 8293.09; int32_t v4 = -323; uint16_t v5 = 8924; std::string v6 = "This is a test string."; uint8_t v7 = 98; vb.write(v1); // Continue writing. vb.write(v2); vb.write(v3); vb.write(v4); vb.writeNullTermString("Blah!"); vb.write(v5); vb.write(v6); vb.write(v7); // Now take the buffer and stuff it into BSerialize CPM_BSERIALIZE_NS::BSerialize sin(vb.getBuffer(), vb.getBufferSize()); sin.readBytes(emptySize); EXPECT_EQ(v1, sin.read<uint32_t>()); EXPECT_EQ(v2, sin.read<double>()); EXPECT_EQ(v3, sin.read<float>()); EXPECT_EQ(v4, sin.read<int32_t>()); EXPECT_EQ(std::string("Blah!"), std::string(sin.readNullTermString())); EXPECT_EQ(v5, sin.read<uint16_t>()); EXPECT_EQ(v6, sin.read<std::string>()); EXPECT_EQ(v7, sin.read<uint8_t>()); } TEST(VarBuffer, TestPreallocatedSize) { varbuff::VarBuffer vb(5000); EXPECT_EQ(5000, vb.getAllocatedSize()); // Proceed close to 1024 limit. const size_t emptySize = 1020; char empty[emptySize]; std::memset(empty, 0, emptySize); vb.writeBytes(empty, emptySize); // After this write, we are at 1024. uint32_t v1 = 3; double v2 = 5.483; float v3 = 8293.09; int32_t v4 = -323; uint16_t v5 = 8924; std::string v6 = "This is a test string."; uint8_t v7 = 98; vb.write(v1); // Continue writing. vb.write(v2); vb.write(v3); vb.write(v4); vb.writeNullTermString("Blah!"); vb.write(v5); vb.write(v6); vb.write(v7); // Now take the buffer and stuff it into BSerialize CPM_BSERIALIZE_NS::BSerialize sin(vb.getBuffer(), vb.getBufferSize()); sin.readBytes(emptySize); EXPECT_EQ(v1, sin.read<uint32_t>()); EXPECT_EQ(v2, sin.read<double>()); EXPECT_EQ(v3, sin.read<float>()); EXPECT_EQ(v4, sin.read<int32_t>()); EXPECT_EQ(std::string("Blah!"), std::string(sin.readNullTermString())); EXPECT_EQ(v5, sin.read<uint16_t>()); EXPECT_EQ(v6, sin.read<std::string>()); EXPECT_EQ(v7, sin.read<uint8_t>()); // Check to ensure that we are still at size 5000. EXPECT_EQ(5000, vb.getAllocatedSize()); } }
[ "jhughes@sci.utah.edu" ]
jhughes@sci.utah.edu
788edf99ba79ce48dab09f44951824b0a917f564
52fcad769c3f201d1b3682537129411aabe632db
/main.cpp
3d5b0c0479502ad29190dcfcc82718c3da16c91b
[]
no_license
MarcinML/simple_database
8114fbb6088a233fe811390d6cf0d693971cfff7
5d718bf79d88504d223b53098e98c23bfd27e144
refs/heads/master
2020-03-22T21:14:37.539721
2018-07-16T08:23:41
2018-07-16T08:23:41
140,669,568
0
0
null
2018-07-12T06:17:00
2018-07-12T06:17:00
null
UTF-8
C++
false
false
328
cpp
#include <iostream> #include "Student.h" int main() { Student s; s.addNewStudent("John", "Doe", 12345); s.addNewStudent("Karolina", "Karolinska", 54321); s.searchByIndexNumber(54321); s.deleteStudentByIndexNumber(54321); s.searchByIndexNumber(54321); s.searchByIndexNumber(12345); return 0; }
[ "marcinliszcz@gmail.com" ]
marcinliszcz@gmail.com
a19b0e398a1ddcf71bf319146d252d1004528c7c
736278662af8207210f0eb9422d7f875544fbbcb
/longint.h
57c62f302c571bc94d95dba65d32a37b630203d8
[]
no_license
Tonyyytran/Dequeue
17b68b83ddfb6256f96467be6a4ca908efa0fb3b
8ffaafe8b2668d57f74691a44591c2333c12f87d
refs/heads/master
2022-11-25T20:49:25.301117
2020-07-23T00:47:30
2020-07-23T00:47:30
281,802,044
0
0
null
null
null
null
UTF-8
C++
false
false
2,109
h
// // Created by Tony Tran on 12/8/19. // #ifndef LONGINT_H #define LONGINT_H #include <iostream> #include "deque.h" using namespace std; class LongInt { friend istream &operator>>(istream &in, LongInt &rhs ); // overloaded instream for LongInt friend ostream &operator<<( ostream &out, const LongInt &rhs ); // overloaded outstream for LongInt public: Deque<char> digits; LongInt(); // Defualt constructor LongInt( const string str ); // Single parameter string constructor LongInt( const LongInt &rhs ); // Copy constructor ~LongInt( ); // Destructor LongInt operator+( const LongInt &rhs ) const; // overloaded operators add for LongInt LongInt operator-( const LongInt &rhs ) const; // overloaded operators subtract for LongInt LongInt& operator=( const LongInt &rhs ); // overloaded operators assignment for LongInt bool operator< ( const LongInt & rhs ) const; // overloaded operators less than for LongInt bool operator<=( const LongInt & rhs ) const; // overloaded operators less than or equal to for LongInt bool operator> ( const LongInt & rhs ) const; // overloaded operators greater than for LongInt bool operator>=( const LongInt & rhs ) const; // overloaded operators greater than or equal to for LongInt bool operator==( const LongInt & rhs ) const; // overloaded operators equal to for LongInt bool operator!=( const LongInt & rhs ) const; // overloaded operators not equal to for LongInt int compareList (const LongInt & rhs ) const; // helper methods : finds if this LongInt is smaller, larger, or equal independent of negativity int getBackInt () const; // returns the back of longInt as integer instead of char private: bool negative; void remove0s( ); // Removes zeros in the front of the integer }; #include "longint.cpp" #endif
[ "37555343+Tonyyytran@users.noreply.github.com" ]
37555343+Tonyyytran@users.noreply.github.com
1c4950fe9c953bd2658ad77cac3a6c9165d0f1ed
36579e820f5c07cd1fe796abc777f23f32efeb10
/src/content/renderer/mus/renderer_window_tree_client.cc
6e55fdf7f5ffada88326a13f6c840b2deba94cc9
[ "BSD-3-Clause" ]
permissive
sokolovp/BraveMining
089ea9940ee6e6cb8108b106198e66c62049d27b
7040cdee80f6f7176bea0e92f8f3435abce3e0ae
refs/heads/master
2020-03-20T00:52:22.001918
2018-06-12T11:33:31
2018-06-12T11:33:31
137,058,944
0
1
null
null
null
null
UTF-8
C++
false
false
13,503
cc
// Copyright 2017 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 "content/renderer/mus/renderer_window_tree_client.h" #include <map> #include "base/command_line.h" #include "base/lazy_instance.h" #include "cc/base/switches.h" #include "components/viz/client/client_layer_tree_frame_sink.h" #include "components/viz/client/hit_test_data_provider.h" #include "components/viz/client/hit_test_data_provider_draw_quad.h" #include "components/viz/client/local_surface_id_provider.h" #include "components/viz/common/features.h" #include "content/renderer/mus/mus_embedded_frame.h" #include "content/renderer/mus/mus_embedded_frame_delegate.h" #include "content/renderer/render_frame_proxy.h" #include "ui/base/ui_base_features.h" namespace content { namespace { using ConnectionMap = std::map<int, RendererWindowTreeClient*>; base::LazyInstance<ConnectionMap>::Leaky g_connections = LAZY_INSTANCE_INITIALIZER; } // namespace // static void RendererWindowTreeClient::CreateIfNecessary(int routing_id) { if (!features::IsMusEnabled() || Get(routing_id)) return; RendererWindowTreeClient* connection = new RendererWindowTreeClient(routing_id); g_connections.Get().insert(std::make_pair(routing_id, connection)); } // static void RendererWindowTreeClient::Destroy(int routing_id) { delete Get(routing_id); } // static RendererWindowTreeClient* RendererWindowTreeClient::Get(int routing_id) { auto it = g_connections.Get().find(routing_id); if (it != g_connections.Get().end()) return it->second; return nullptr; } void RendererWindowTreeClient::Bind( ui::mojom::WindowTreeClientRequest request, mojom::RenderWidgetWindowTreeClientRequest render_widget_window_tree_client_request) { // Bind() may be called multiple times. binding_.Close(); render_widget_window_tree_client_binding_.Close(); binding_.Bind(std::move(request)); render_widget_window_tree_client_binding_.Bind( std::move(render_widget_window_tree_client_request)); } std::unique_ptr<MusEmbeddedFrame> RendererWindowTreeClient::OnRenderFrameProxyCreated( RenderFrameProxy* render_frame_proxy) { auto iter = pending_frames_.find(render_frame_proxy->routing_id()); if (iter == pending_frames_.end()) return nullptr; const base::UnguessableToken token = iter->second; pending_frames_.erase(iter); return CreateMusEmbeddedFrame(render_frame_proxy, token); } void RendererWindowTreeClient::SetVisible(bool visible) { if (visible_ == visible) return; visible_ = visible; if (tree_) { tree_->SetWindowVisibility(GetAndAdvanceNextChangeId(), root_window_id_, visible); } } void RendererWindowTreeClient::RequestLayerTreeFrameSink( scoped_refptr<viz::ContextProvider> context_provider, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, const LayerTreeFrameSinkCallback& callback) { DCHECK(pending_layer_tree_frame_sink_callback_.is_null()); if (tree_) { RequestLayerTreeFrameSinkInternal(std::move(context_provider), gpu_memory_buffer_manager, callback); return; } pending_context_provider_ = std::move(context_provider); pending_gpu_memory_buffer_manager_ = gpu_memory_buffer_manager; pending_layer_tree_frame_sink_callback_ = callback; } std::unique_ptr<MusEmbeddedFrame> RendererWindowTreeClient::CreateMusEmbeddedFrame( MusEmbeddedFrameDelegate* delegate, const base::UnguessableToken& token) { std::unique_ptr<MusEmbeddedFrame> frame = base::WrapUnique<MusEmbeddedFrame>( new MusEmbeddedFrame(this, delegate, ++next_window_id_, token)); embedded_frames_.insert(frame.get()); return frame; } RendererWindowTreeClient::RendererWindowTreeClient(int routing_id) : routing_id_(routing_id), binding_(this), render_widget_window_tree_client_binding_(this) {} RendererWindowTreeClient::~RendererWindowTreeClient() { g_connections.Get().erase(routing_id_); DCHECK(embedded_frames_.empty()); } void RendererWindowTreeClient::RequestLayerTreeFrameSinkInternal( scoped_refptr<viz::ContextProvider> context_provider, gpu::GpuMemoryBufferManager* gpu_memory_buffer_manager, const LayerTreeFrameSinkCallback& callback) { viz::mojom::CompositorFrameSinkPtrInfo sink_info; viz::mojom::CompositorFrameSinkRequest sink_request = mojo::MakeRequest(&sink_info); viz::mojom::CompositorFrameSinkClientPtr client; viz::mojom::CompositorFrameSinkClientRequest client_request = mojo::MakeRequest(&client); viz::ClientLayerTreeFrameSink::InitParams params; params.gpu_memory_buffer_manager = gpu_memory_buffer_manager; params.pipes.compositor_frame_sink_info = std::move(sink_info); params.pipes.client_request = std::move(client_request); params.local_surface_id_provider = std::make_unique<viz::DefaultLocalSurfaceIdProvider>(); params.enable_surface_synchronization = true; if (features::IsVizHitTestingDrawQuadEnabled()) { params.hit_test_data_provider = std::make_unique<viz::HitTestDataProviderDrawQuad>( true /* should_ask_for_child_region */); } auto frame_sink = std::make_unique<viz::ClientLayerTreeFrameSink>( std::move(context_provider), nullptr /* worker_context_provider */, &params); tree_->AttachCompositorFrameSink(root_window_id_, std::move(sink_request), std::move(client)); callback.Run(std::move(frame_sink)); } void RendererWindowTreeClient::OnEmbeddedFrameDestroyed( MusEmbeddedFrame* frame) { embedded_frames_.erase(embedded_frames_.find(frame)); } void RendererWindowTreeClient::Embed(uint32_t frame_routing_id, const base::UnguessableToken& token) { RenderFrameProxy* render_frame_proxy = RenderFrameProxy::FromRoutingID(frame_routing_id); if (!render_frame_proxy) { pending_frames_[frame_routing_id] = token; return; } render_frame_proxy->SetMusEmbeddedFrame( CreateMusEmbeddedFrame(render_frame_proxy, token)); } void RendererWindowTreeClient::DestroyFrame(uint32_t frame_routing_id) { pending_frames_.erase(frame_routing_id); } void RendererWindowTreeClient::OnEmbed( ui::mojom::WindowDataPtr root, ui::mojom::WindowTreePtr tree, int64_t display_id, ui::Id focused_window_id, bool drawn, const base::Optional<viz::LocalSurfaceId>& local_surface_id) { const bool is_reembed = tree_.is_bound(); if (is_reembed) { for (MusEmbeddedFrame* frame : embedded_frames_) frame->OnTreeWillChange(); } root_window_id_ = root->window_id; tree_ = std::move(tree); tree_->SetWindowVisibility(GetAndAdvanceNextChangeId(), root_window_id_, visible_); if (!is_reembed) { for (MusEmbeddedFrame* frame : embedded_frames_) frame->OnTreeAvailable(); } if (!pending_layer_tree_frame_sink_callback_.is_null()) { RequestLayerTreeFrameSinkInternal(std::move(pending_context_provider_), pending_gpu_memory_buffer_manager_, pending_layer_tree_frame_sink_callback_); pending_context_provider_ = nullptr; pending_gpu_memory_buffer_manager_ = nullptr; pending_layer_tree_frame_sink_callback_.Reset(); } } void RendererWindowTreeClient::OnEmbeddedAppDisconnected(ui::Id window_id) { // TODO(sad): Embedded mus-client (oopif) is gone. Figure out what to do. } void RendererWindowTreeClient::OnUnembed(ui::Id window_id) { // At this point all operations will fail. We don't delete this as it would // mean all consumers have to null check (as would MusEmbeddedFrames). } void RendererWindowTreeClient::OnCaptureChanged(ui::Id new_capture_window_id, ui::Id old_capture_window_id) {} void RendererWindowTreeClient::OnFrameSinkIdAllocated( ui::Id window_id, const viz::FrameSinkId& frame_sink_id) { // When mus is not hosting viz FrameSinkIds come from the browser, so we // ignore them here. if (!base::FeatureList::IsEnabled(features::kMash)) return; for (MusEmbeddedFrame* embedded_frame : embedded_frames_) { if (embedded_frame->window_id_ == window_id) { embedded_frame->delegate_->OnMusEmbeddedFrameSinkIdAllocated( frame_sink_id); return; } } } void RendererWindowTreeClient::OnTopLevelCreated( uint32_t change_id, ui::mojom::WindowDataPtr data, int64_t display_id, bool drawn, const base::Optional<viz::LocalSurfaceId>& local_surface_id) { NOTREACHED(); } void RendererWindowTreeClient::OnWindowBoundsChanged( ui::Id window_id, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, const base::Optional<viz::LocalSurfaceId>& local_surface_id) {} void RendererWindowTreeClient::OnWindowTransformChanged( ui::Id window_id, const gfx::Transform& old_transform, const gfx::Transform& new_transform) {} void RendererWindowTreeClient::OnClientAreaChanged( ui::Id window_id, const gfx::Insets& new_client_area, const std::vector<gfx::Rect>& new_additional_client_areas) {} void RendererWindowTreeClient::OnTransientWindowAdded( ui::Id window_id, ui::Id transient_window_id) {} void RendererWindowTreeClient::OnTransientWindowRemoved( ui::Id window_id, ui::Id transient_window_id) {} void RendererWindowTreeClient::OnWindowHierarchyChanged( ui::Id window_id, ui::Id old_parent_id, ui::Id new_parent_id, std::vector<ui::mojom::WindowDataPtr> windows) {} void RendererWindowTreeClient::OnWindowReordered( ui::Id window_id, ui::Id relative_window_id, ui::mojom::OrderDirection direction) {} void RendererWindowTreeClient::OnWindowDeleted(ui::Id window_id) { // See comments on OnUnembed() for why we do nothing here. } void RendererWindowTreeClient::OnWindowVisibilityChanged(ui::Id window_id, bool visible) {} void RendererWindowTreeClient::OnWindowOpacityChanged(ui::Id window_id, float old_opacity, float new_opacity) {} void RendererWindowTreeClient::OnWindowParentDrawnStateChanged(ui::Id window_id, bool drawn) {} void RendererWindowTreeClient::OnWindowSharedPropertyChanged( ui::Id window_id, const std::string& name, const base::Optional<std::vector<uint8_t>>& new_data) {} void RendererWindowTreeClient::OnWindowInputEvent( uint32_t event_id, ui::Id window_id, int64_t display_id, ui::Id display_root_window_id, const gfx::PointF& event_location_in_screen_pixel_layout, std::unique_ptr<ui::Event> event, bool matches_pointer_watcher) { NOTREACHED(); } void RendererWindowTreeClient::OnPointerEventObserved( std::unique_ptr<ui::Event> event, ui::Id window_id, int64_t display_id) { NOTREACHED(); } void RendererWindowTreeClient::OnWindowFocused(ui::Id focused_window_id) {} void RendererWindowTreeClient::OnWindowCursorChanged(ui::Id window_id, ui::CursorData cursor) {} void RendererWindowTreeClient::OnWindowSurfaceChanged( ui::Id window_id, const viz::SurfaceInfo& surface_info) { DCHECK(base::FeatureList::IsEnabled(features::kMash)); for (MusEmbeddedFrame* embedded_frame : embedded_frames_) { if (embedded_frame->window_id_ == window_id) { embedded_frame->delegate_->OnMusEmbeddedFrameSurfaceChanged(surface_info); return; } } } void RendererWindowTreeClient::OnDragDropStart( const std::unordered_map<std::string, std::vector<uint8_t>>& mime_data) {} void RendererWindowTreeClient::OnDragEnter( ui::Id window_id, uint32_t event_flags, const gfx::Point& position, uint32_t effect_bitmask, const OnDragEnterCallback& callback) {} void RendererWindowTreeClient::OnDragOver(ui::Id window_id, uint32_t event_flags, const gfx::Point& position, uint32_t effect_bitmask, const OnDragOverCallback& callback) {} void RendererWindowTreeClient::OnDragLeave(ui::Id window_id) {} void RendererWindowTreeClient::OnCompleteDrop( ui::Id window_id, uint32_t event_flags, const gfx::Point& position, uint32_t effect_bitmask, const OnCompleteDropCallback& callback) {} void RendererWindowTreeClient::OnPerformDragDropCompleted( uint32_t change_id, bool success, uint32_t action_taken) {} void RendererWindowTreeClient::OnDragDropDone() {} void RendererWindowTreeClient::OnChangeCompleted(uint32_t change_id, bool success) { // Don't DCHECK success, as it's possible we'll try to do some operations // after unembedded, which means all operations will fail. Additionally // setting the window visibility may fail for the root frame (the browser // controls the visibility of the root frame). } void RendererWindowTreeClient::RequestClose(ui::Id window_id) {} void RendererWindowTreeClient::GetWindowManager( mojo::AssociatedInterfaceRequest<ui::mojom::WindowManager> internal) { NOTREACHED(); } } // namespace content
[ "sokolov.p@gmail.com" ]
sokolov.p@gmail.com
afc65e4d5f038865eaac8a3a505a3f544dc0aa9b
bcbc8e608e386227de04eda8f3aa5e9a892613d3
/src/gpu/graphite/compute/VelloComputeSteps.cpp
24ba31976f6c9bd8589d4df2566cb1864617c971
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
jei-mayol/skia
fd91b0383a852bfef936f1a4fee4c34b20384486
aa208c8a2d60b087ef74d35737b037cfe85a4fc4
refs/heads/master
2023-09-02T01:11:31.240779
2023-08-22T16:56:00
2023-08-22T22:00:26
201,937,654
0
0
null
2019-08-12T13:38:19
2019-08-12T13:38:18
null
UTF-8
C++
false
false
23,207
cpp
/* * Copyright 2023 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/graphite/compute/VelloComputeSteps.h" namespace skgpu::graphite { std::string_view VelloStageName(vello_cpp::ShaderStage stage) { auto name = vello_cpp::shader(stage).name(); return {name.data(), name.length()}; } WorkgroupSize VelloStageLocalSize(vello_cpp::ShaderStage stage) { auto wgSize = vello_cpp::shader(stage).workgroup_size(); return WorkgroupSize(wgSize.x, wgSize.y, wgSize.z); } skia_private::TArray<ComputeStep::WorkgroupBufferDesc> VelloWorkgroupBuffers( vello_cpp::ShaderStage stage) { auto wgBuffers = vello_cpp::shader(stage).workgroup_buffers(); skia_private::TArray<ComputeStep::WorkgroupBufferDesc> result; if (!wgBuffers.empty()) { result.reserve(wgBuffers.size()); for (const auto& desc : wgBuffers) { result.push_back({desc.size_in_bytes, desc.index}); } } return result; } std::string_view VelloNativeShaderSource(vello_cpp::ShaderStage stage, ComputeStep::NativeShaderFormat format) { using NativeFormat = ComputeStep::NativeShaderFormat; const auto& shader = vello_cpp::shader(stage); ::rust::Str source; switch (format) { #ifdef SK_DAWN case NativeFormat::kWGSL: source = shader.wgsl(); break; #endif #ifdef SK_METAL case NativeFormat::kMSL: source = shader.msl(); break; #endif default: return std::string_view(); } return {source.data(), source.length()}; } // PathtagReduce VelloPathtagReduceStep::VelloPathtagReduceStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kMapped, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kMapped, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PathtagReduceOutput, }, }) {} // PathtagScanSmall VelloPathtagScanSmallStep::VelloPathtagScanSmallStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PathtagReduceOutput, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_TagMonoid, }, }) {} // PathtagReduce2 VelloPathtagReduce2Step::VelloPathtagReduce2Step() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_LargePathtagReduceFirstPassOutput, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_LargePathtagReduceSecondPassOutput, }, }) {} // PathtagScan1 VelloPathtagScan1Step::VelloPathtagScan1Step() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_LargePathtagReduceFirstPassOutput, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_LargePathtagReduceSecondPassOutput, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_LargePathtagScanFirstPassOutput, }, }) {} // PathtagScanLarge VelloPathtagScanLargeStep::VelloPathtagScanLargeStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_LargePathtagScanFirstPassOutput, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_TagMonoid, }, }) {} // BboxClear VelloBboxClearStep::VelloBboxClearStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PathBBoxes, }, }) {} // Pathseg VelloPathsegStep::VelloPathsegStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_TagMonoid, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PathBBoxes, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Cubics, }, }) {} // DrawReduce VelloDrawReduceStep::VelloDrawReduceStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_DrawReduceOutput, }, }) {} // DrawLeaf VelloDrawLeafStep::VelloDrawLeafStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_DrawReduceOutput, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PathBBoxes, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_DrawMonoid, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_InfoBinData, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipInput, }, }) {} // ClipReduce VelloClipReduceStep::VelloClipReduceStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipInput, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PathBBoxes, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipBicyclic, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipElement, }, }) {} // ClipLeaf VelloClipLeafStep::VelloClipLeafStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipInput, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PathBBoxes, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipBicyclic, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipElement, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_DrawMonoid, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipBBoxes, }, }) {} // Binning VelloBinningStep::VelloBinningStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_DrawMonoid, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PathBBoxes, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ClipBBoxes, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_DrawBBoxes, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kClear, /*slot=*/kVelloSlot_BumpAlloc, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_InfoBinData, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_BinHeader, }, }) {} // TileAlloc VelloTileAllocStep::VelloTileAllocStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_DrawBBoxes, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_BumpAlloc, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Path, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Tile, }, }) {} // PathCoarseFull VelloPathCoarseFullStep::VelloPathCoarseFullStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Cubics, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Path, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_BumpAlloc, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Tile, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Segments, }, }) {} // Backdrop VelloBackdropStep::VelloBackdropStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Tile, }, }) {} // BackdropDyn VelloBackdropDynStep::VelloBackdropDynStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Path, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Tile, }, }) {} // Coarse VelloCoarseStep::VelloCoarseStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Scene, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_DrawMonoid, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_BinHeader, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_InfoBinData, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Path, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Tile, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_BumpAlloc, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PTCL, }, }) {} // Fine VelloFineStep::VelloFineStep() : VelloStep( /*resources=*/{ { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ConfigUniform, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_Segments, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_PTCL, }, { /*type=*/ResourceType::kStorageBuffer, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_InfoBinData, }, { /*type=*/ResourceType::kStorageTexture, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_OutputImage, }, { /*type=*/ResourceType::kTexture, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_GradientImage, }, { /*type=*/ResourceType::kTexture, /*flow=*/DataFlow::kShared, /*policy=*/ResourcePolicy::kNone, /*slot=*/kVelloSlot_ImageAtlas, }, }) {} } // namespace skgpu::graphite
[ "skcq-be@skia-corp.google.com.iam.gserviceaccount.com" ]
skcq-be@skia-corp.google.com.iam.gserviceaccount.com
81c8e3af3e1351649561242a2ab04e672bb2ad81
2479189775312ea0903300738c434c19a0fb3dcf
/src/pNodeZip/NZ_MOOSApp.h
e6219b842274e26dc8c58a35a46f503d8d5a64b0
[]
no_license
ucsb-coast-lab/moos-ivp-ucsb
fff18148334dc506fe5f33d24d4dd95f90cc0b3a
327ebd5e70e6cc50c644ba474cfcf6cb09dad805
refs/heads/master
2023-06-11T06:26:36.893350
2021-07-01T21:17:10
2021-07-01T21:17:10
28,889,859
1
1
null
2019-06-26T18:12:20
2015-01-07T00:10:45
C++
UTF-8
C++
false
false
676
h
#include <iostream> #include "MOOS/libMOOS/MOOSLib.h" #include <string> #include "MBUtils.h" #include "MOOSGeodesy.h" class NZ_MOOSApp : public CMOOSApp { public: NZ_MOOSApp(); virtual ~NZ_MOOSApp() {}; bool Iterate(); bool OnConnectToServer(); bool OnDisconnectFromServer(); bool OnStartUp(); bool OnNewMail(MOOSMSG_LIST &NewMail); protected: void RegisterVariables(); bool ReportZip(); bool ReportUnZip(); protected: std::string nodeReportVar; std::string node_report; std::string zipReportVar; std::string zip_report; bool zipping; int count; int index; CMOOSGeodesy geodesy; double latOrigin; double lonOrigin; };
[ "pi@9284e19a-42a1-4dfb-bd8f-f680e431a953" ]
pi@9284e19a-42a1-4dfb-bd8f-f680e431a953
f53a0c1081b11239a432baf9755847d52565ff34
d2de6f54bae55578f9d6f6d621b1892efe7eb076
/gluecodium/src/test/resources/smoke/nesting/output/dart/ffi/ffi_smoke_OuterClass.cpp
d8fc3ee3370c4bedc589a099e6c42da1d3116c76
[ "Apache-2.0" ]
permissive
heremaps/gluecodium
812f4b8a6a0f01979d6902b5e0cfe003a5b82347
92e6a514dc8bdb786ad949f79df249da277c6e88
refs/heads/master
2023-08-24T19:34:55.818503
2023-08-24T06:02:15
2023-08-24T06:02:15
139,735,719
172
17
Apache-2.0
2023-09-01T11:49:28
2018-07-04T14:55:33
Dart
UTF-8
C++
false
false
9,017
cpp
#include "ffi_smoke_OuterClass.h" #include "ConversionBase.h" #include "InstanceCache.h" #include "FinalizerData.h" #include "CallbacksQueue.h" #include "IsolateContext.h" #include "ProxyCache.h" #include "gluecodium/TypeRepository.h" #include "smoke/OuterClass.h" #include <memory> #include <string> #include <memory> #include <new> class smoke_OuterClass_InnerInterface_Proxy : public smoke::OuterClass::InnerInterface { public: smoke_OuterClass_InnerInterface_Proxy(uint64_t token, int32_t isolate_id, Dart_Handle dart_handle, FfiOpaqueHandle f0) : token(token), isolate_id(isolate_id), dart_persistent_handle(Dart_NewPersistentHandle_DL(dart_handle)), f0(f0) { library_cache_dart_handle_by_raw_pointer(this, isolate_id, dart_handle); } ~smoke_OuterClass_InnerInterface_Proxy() { gluecodium::ffi::remove_cached_proxy(token, isolate_id, "smoke_OuterClass_InnerInterface"); auto raw_pointer_local = this; auto isolate_id_local = isolate_id; auto dart_persistent_handle_local = dart_persistent_handle; auto deleter = [raw_pointer_local, isolate_id_local, dart_persistent_handle_local]() { library_uncache_dart_handle_by_raw_pointer(raw_pointer_local, isolate_id_local); Dart_DeletePersistentHandle_DL(dart_persistent_handle_local); }; if (gluecodium::ffi::IsolateContext::is_current(isolate_id)) { deleter(); } else { gluecodium::ffi::cbqm.enqueueCallback(isolate_id, deleter); } } smoke_OuterClass_InnerInterface_Proxy(const smoke_OuterClass_InnerInterface_Proxy&) = delete; smoke_OuterClass_InnerInterface_Proxy& operator=(const smoke_OuterClass_InnerInterface_Proxy&) = delete; std::string foo(const std::string& input) override { FfiOpaqueHandle _result_handle; dispatch([&]() { (*reinterpret_cast<bool (*)(Dart_Handle, FfiOpaqueHandle, FfiOpaqueHandle*)>(f0))(Dart_HandleFromPersistent_DL(dart_persistent_handle), gluecodium::ffi::Conversion<std::string>::toFfi(input), &_result_handle ); }); auto _result = gluecodium::ffi::Conversion<std::string>::toCpp(_result_handle); delete reinterpret_cast<std::string*>(_result_handle); return _result; } private: const uint64_t token; const int32_t isolate_id; const Dart_PersistentHandle dart_persistent_handle; const FfiOpaqueHandle f0; inline void dispatch(std::function<void()>&& callback) const { gluecodium::ffi::IsolateContext::is_current(isolate_id) ? callback() : gluecodium::ffi::cbqm.enqueueCallback(isolate_id, std::move(callback)).wait(); } }; #ifdef __cplusplus extern "C" { #endif FfiOpaqueHandle library_smoke_OuterClass_foo__String(FfiOpaqueHandle _self, int32_t _isolate_id, FfiOpaqueHandle input) { gluecodium::ffi::IsolateContext _isolate_context(_isolate_id); return gluecodium::ffi::Conversion<std::string>::toFfi( (*gluecodium::ffi::Conversion<std::shared_ptr<smoke::OuterClass>>::toCpp(_self)).foo( gluecodium::ffi::Conversion<std::string>::toCpp(input) ) ); } FfiOpaqueHandle library_smoke_OuterClass_InnerClass_foo__String(FfiOpaqueHandle _self, int32_t _isolate_id, FfiOpaqueHandle input) { gluecodium::ffi::IsolateContext _isolate_context(_isolate_id); return gluecodium::ffi::Conversion<std::string>::toFfi( (*gluecodium::ffi::Conversion<std::shared_ptr<smoke::OuterClass::InnerClass>>::toCpp(_self)).foo( gluecodium::ffi::Conversion<std::string>::toCpp(input) ) ); } FfiOpaqueHandle library_smoke_OuterClass_InnerInterface_foo__String(FfiOpaqueHandle _self, int32_t _isolate_id, FfiOpaqueHandle input) { gluecodium::ffi::IsolateContext _isolate_context(_isolate_id); return gluecodium::ffi::Conversion<std::string>::toFfi( (*gluecodium::ffi::Conversion<std::shared_ptr<smoke::OuterClass::InnerInterface>>::toCpp(_self)).foo( gluecodium::ffi::Conversion<std::string>::toCpp(input) ) ); } // "Private" finalizer, not exposed to be callable from Dart. void library_smoke_OuterClass_finalizer(FfiOpaqueHandle handle, int32_t isolate_id) { auto ptr_ptr = reinterpret_cast<std::shared_ptr<smoke::OuterClass>*>(handle); library_uncache_dart_handle_by_raw_pointer(ptr_ptr->get(), isolate_id); library_smoke_OuterClass_release_handle(handle); } void library_smoke_OuterClass_register_finalizer(FfiOpaqueHandle ffi_handle, int32_t isolate_id, Dart_Handle dart_handle) { FinalizerData* data = new (std::nothrow) FinalizerData{ffi_handle, isolate_id, &library_smoke_OuterClass_finalizer}; Dart_NewFinalizableHandle_DL(dart_handle, data, sizeof data, &library_execute_finalizer); } FfiOpaqueHandle library_smoke_OuterClass_copy_handle(FfiOpaqueHandle handle) { return reinterpret_cast<FfiOpaqueHandle>( new (std::nothrow) std::shared_ptr<smoke::OuterClass>( *reinterpret_cast<std::shared_ptr<smoke::OuterClass>*>(handle) ) ); } void library_smoke_OuterClass_release_handle(FfiOpaqueHandle handle) { delete reinterpret_cast<std::shared_ptr<smoke::OuterClass>*>(handle); } // "Private" finalizer, not exposed to be callable from Dart. void library_smoke_OuterClass_InnerClass_finalizer(FfiOpaqueHandle handle, int32_t isolate_id) { auto ptr_ptr = reinterpret_cast<std::shared_ptr<smoke::OuterClass::InnerClass>*>(handle); library_uncache_dart_handle_by_raw_pointer(ptr_ptr->get(), isolate_id); library_smoke_OuterClass_InnerClass_release_handle(handle); } void library_smoke_OuterClass_InnerClass_register_finalizer(FfiOpaqueHandle ffi_handle, int32_t isolate_id, Dart_Handle dart_handle) { FinalizerData* data = new (std::nothrow) FinalizerData{ffi_handle, isolate_id, &library_smoke_OuterClass_InnerClass_finalizer}; Dart_NewFinalizableHandle_DL(dart_handle, data, sizeof data, &library_execute_finalizer); } FfiOpaqueHandle library_smoke_OuterClass_InnerClass_copy_handle(FfiOpaqueHandle handle) { return reinterpret_cast<FfiOpaqueHandle>( new (std::nothrow) std::shared_ptr<smoke::OuterClass::InnerClass>( *reinterpret_cast<std::shared_ptr<smoke::OuterClass::InnerClass>*>(handle) ) ); } void library_smoke_OuterClass_InnerClass_release_handle(FfiOpaqueHandle handle) { delete reinterpret_cast<std::shared_ptr<smoke::OuterClass::InnerClass>*>(handle); } // "Private" finalizer, not exposed to be callable from Dart. void library_smoke_OuterClass_InnerInterface_finalizer(FfiOpaqueHandle handle, int32_t isolate_id) { auto ptr_ptr = reinterpret_cast<std::shared_ptr<smoke::OuterClass::InnerInterface>*>(handle); library_uncache_dart_handle_by_raw_pointer(ptr_ptr->get(), isolate_id); library_smoke_OuterClass_InnerInterface_release_handle(handle); } void library_smoke_OuterClass_InnerInterface_register_finalizer(FfiOpaqueHandle ffi_handle, int32_t isolate_id, Dart_Handle dart_handle) { FinalizerData* data = new (std::nothrow) FinalizerData{ffi_handle, isolate_id, &library_smoke_OuterClass_InnerInterface_finalizer}; Dart_NewFinalizableHandle_DL(dart_handle, data, sizeof data, &library_execute_finalizer); } FfiOpaqueHandle library_smoke_OuterClass_InnerInterface_copy_handle(FfiOpaqueHandle handle) { return reinterpret_cast<FfiOpaqueHandle>( new (std::nothrow) std::shared_ptr<smoke::OuterClass::InnerInterface>( *reinterpret_cast<std::shared_ptr<smoke::OuterClass::InnerInterface>*>(handle) ) ); } void library_smoke_OuterClass_InnerInterface_release_handle(FfiOpaqueHandle handle) { delete reinterpret_cast<std::shared_ptr<smoke::OuterClass::InnerInterface>*>(handle); } FfiOpaqueHandle library_smoke_OuterClass_InnerInterface_create_proxy(uint64_t token, int32_t isolate_id, Dart_Handle dart_handle, FfiOpaqueHandle f0) { auto cached_proxy = gluecodium::ffi::get_cached_proxy<smoke_OuterClass_InnerInterface_Proxy>(token, isolate_id, "smoke_OuterClass_InnerInterface"); std::shared_ptr<smoke_OuterClass_InnerInterface_Proxy>* proxy_ptr; if (cached_proxy) { proxy_ptr = new (std::nothrow) std::shared_ptr<smoke_OuterClass_InnerInterface_Proxy>(cached_proxy); } else { proxy_ptr = new (std::nothrow) std::shared_ptr<smoke_OuterClass_InnerInterface_Proxy>( new (std::nothrow) smoke_OuterClass_InnerInterface_Proxy(token, isolate_id, dart_handle, f0) ); gluecodium::ffi::cache_proxy(token, isolate_id, "smoke_OuterClass_InnerInterface", *proxy_ptr); } return reinterpret_cast<FfiOpaqueHandle>(proxy_ptr); } FfiOpaqueHandle library_smoke_OuterClass_InnerInterface_get_type_id(FfiOpaqueHandle handle) { const auto& type_id = ::gluecodium::get_type_repository().get_id(reinterpret_cast<std::shared_ptr<smoke::OuterClass::InnerInterface>*>(handle)->get()); return reinterpret_cast<FfiOpaqueHandle>(new (std::nothrow) std::string(type_id)); } #ifdef __cplusplus } #endif
[ "noreply@github.com" ]
noreply@github.com
d56a0686a6b2df981bda8947a60fa8446a113795
421a832c2d7747f4b0612f22debd4e523e4a8e24
/FROGGER/MOVING.CPP
fdccc4ecbf8bffe98440a384551442e6e37d5a9e
[ "MIT" ]
permissive
AllenCompSci/FLOPPYGLORY
85e712a7af64ab4e72a93fdbb6d0759f6565ae49
ef08a690f237f0b8e711dc234607828375ae0a72
refs/heads/master
2021-01-20T01:19:51.330189
2018-03-18T03:11:34
2018-03-18T03:11:34
89,257,274
2
0
null
null
null
null
UTF-8
C++
false
false
1,157
cpp
//Comment //Nick Vankemseke //Shell //5th //Library sec #include <iostream.h> #include <iomanip.h> #include <conio.h> #include <apstring.h> #include <apvector.h> #include <fstream.h> #include <graphics.h> #include <dos.h> #include <alloc.h> //const sec //structs //Global Variable Section char Ans; int GrDriver, GrMode, ErrorCode; int A,B,C,D,E,F,I; char Key; unsigned int Size; void far *P; //Prototypes void gr_start(int&,int&,int&); //Main Section void main() { do{ clrscr(); gr_start(GrDriver,GrMode,ErrorCode); A=150; B=100; circle(A,B,50); I=0; do{ if(kbhit()) {Key=getch(); if(Key==80) B++; if(Key==72) B--; if(Key==77) A++; if(Key== 75) A--; cleardevice(); setcolor(15); circle(A,B,50);} }while(Key!=27); cout<<"Re-run? (Y/N)"<<endl; cin>>Ans; }while(Ans=='Y'||Ans=='y'); }//End Main //Create functions here void gr_start(int&GrDriver, int&GrMode, int&ErrorCode) {GrDriver=VGA; GrMode=VGAHI; initgraph(&GrDriver, &GrMode, "C:\\TC\\BGI"); if(ErrorCode!=grOk) {clrscr(); cout<<"Error:"<<ErrorCode; getch(); exit(1);}}
[ "Weston1998Reed@gmail.com" ]
Weston1998Reed@gmail.com
4c30a8cd93e239f070d51fe363a1a35b4c845d35
fb7efe44f4d9f30d623f880d0eb620f3a81f0fbd
/content/public/browser/devtools_manager_delegate.h
1136340bc132453e736d730b3ec4166597fd0aef
[ "BSD-3-Clause" ]
permissive
wzyy2/chromium-browser
2644b0daf58f8b3caee8a6c09a2b448b2dfe059c
eb905f00a0f7e141e8d6c89be8fb26192a88c4b7
refs/heads/master
2022-11-23T20:25:08.120045
2018-01-16T06:41:26
2018-01-16T06:41:26
117,618,467
3
2
BSD-3-Clause
2022-11-20T22:03:57
2018-01-16T02:09:10
null
UTF-8
C++
false
false
3,283
h
// Copyright 2014 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. #ifndef CONTENT_PUBLIC_BROWSER_DEVTOOLS_MANAGER_DELEGATE_H_ #define CONTENT_PUBLIC_BROWSER_DEVTOOLS_MANAGER_DELEGATE_H_ #include <memory> #include <string> #include "base/memory/ref_counted.h" #include "content/common/content_export.h" #include "content/public/browser/devtools_agent_host.h" #include "url/gurl.h" namespace base { class DictionaryValue; } namespace content { class WebContents; class CONTENT_EXPORT DevToolsManagerDelegate { public: // Opens the inspector for |agent_host|. virtual void Inspect(DevToolsAgentHost* agent_host); // Returns DevToolsAgentHost type to use for given |web_contents| target. virtual std::string GetTargetType(WebContents* web_contents); // Returns DevToolsAgentHost title to use for given |web_contents| target. virtual std::string GetTargetTitle(WebContents* web_contents); // Returns DevToolsAgentHost title to use for given |web_contents| target. virtual std::string GetTargetDescription(WebContents* web_contents); // Returns all targets embedder would like to report as debuggable // remotely. virtual DevToolsAgentHost::List RemoteDebuggingTargets(); // Creates new inspectable target given the |url|. virtual scoped_refptr<DevToolsAgentHost> CreateNewTarget(const GURL& url); // Called when a new session is created/destroyed. Note that |session_id| is // globally unique. virtual void SessionCreated(content::DevToolsAgentHost* agent_host, int session_id); virtual void SessionDestroyed(content::DevToolsAgentHost* agent_host, int session_id); // Returns true if the command has been handled, false otherwise. virtual bool HandleCommand(DevToolsAgentHost* agent_host, int session_id, base::DictionaryValue* command); using CommandCallback = base::Callback<void(std::unique_ptr<base::DictionaryValue> response)>; virtual bool HandleAsyncCommand(DevToolsAgentHost* agent_host, int session_id, base::DictionaryValue* command, const CommandCallback& callback); // Should return discovery page HTML that should list available tabs // and provide attach links. virtual std::string GetDiscoveryPageHTML(); // Returns frontend resource data by |path|. virtual std::string GetFrontendResource(const std::string& path); // Makes browser target easily discoverable for remote debugging. // This should only return true when remote debugging endpoint is not // accessible by the web (for example in Chrome for Android where it is // exposed via UNIX named socket) or when content/ embedder is built for // running in the controlled environment (for example a special build for // the Lab testing). If you want to return true here, please get security // clearance from the devtools owners. virtual bool IsBrowserTargetDiscoverable(); virtual ~DevToolsManagerDelegate(); }; } // namespace content #endif // CONTENT_PUBLIC_BROWSER_DEVTOOLS_MANAGER_DELEGATE_H_
[ "jacob-chen@iotwrt.com" ]
jacob-chen@iotwrt.com
54018d9e4142b7df7fafb2a6101e5d219e5b96cb
17f2b0d89da6f1400b72fef83f12263fa59d0dd0
/Simple/main.cpp
ba04efeeb39002ae638e4e2b56f675500b167b6a
[]
no_license
sammcd4/Simple
dfde6de37e0cc8730888aaca2824315179e392b0
5ac49cc66cc5d863e0476b82317fba1cb6597015
refs/heads/master
2021-01-09T11:15:36.083399
2020-02-23T01:45:17
2020-02-23T01:45:17
242,278,967
0
0
null
null
null
null
UTF-8
C++
false
false
301
cpp
// // main.cpp // Simple // // Created by Sam McDonald on 1/31/20. // Copyright © 2020 Sam McDonald. All rights reserved. // #include "quadratic.h" #include "types.h" using namespace std; int main(int argc, const char * argv[]) { arrays(); //runQuadraticSolver(); return 0; }
[ "samuel.jacob.mcdonald@gmail.com" ]
samuel.jacob.mcdonald@gmail.com
95a2eb38f73e537e0332fdfea8981d0dc96648de
2dc9ab0ec71fd31900173fb15a6f2c85753180c4
/components/feed/core/v2/protocol_translator_unittest.cc
592bebe3028bcfe1a8f6d0d2ce0f92fbaa987502
[ "BSD-3-Clause" ]
permissive
Forilan/chromium
ec337c30d23c22d11fbdf814a40b9b4c26000d78
562b20b68672e7831054ec8f160d5f7ae940eae4
refs/heads/master
2023-02-28T02:43:17.744240
2020-05-12T02:23:44
2020-05-12T02:23:44
231,539,724
0
0
BSD-3-Clause
2020-05-12T02:23:45
2020-01-03T07:52:37
null
UTF-8
C++
false
false
9,560
cc
// Copyright 2020 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 "components/feed/core/v2/protocol_translator.h" #include <sstream> #include <string> #include "base/base_paths.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/path_service.h" #include "base/strings/string_number_conversions.h" #include "base/time/time.h" #include "components/feed/core/proto/v2/wire/feed_response.pb.h" #include "components/feed/core/proto/v2/wire/response.pb.h" #include "components/feed/core/v2/proto_util.h" #include "components/feed/core/v2/test/proto_printer.h" #include "testing/gtest/include/gtest/gtest.h" namespace feed { namespace { const char kResponsePbPath[] = "components/test/data/feed/response.binarypb"; const base::Time kCurrentTime = base::Time::UnixEpoch() + base::TimeDelta::FromDays(123); feedwire::Response TestWireResponse() { // Read and parse response.binarypb. base::FilePath response_file_path; CHECK(base::PathService::Get(base::DIR_SOURCE_ROOT, &response_file_path)); response_file_path = response_file_path.AppendASCII(kResponsePbPath); CHECK(base::PathExists(response_file_path)); std::string response_data; CHECK(base::ReadFileToString(response_file_path, &response_data)); feedwire::Response response; CHECK(response.ParseFromString(response_data)); return response; } feedwire::Response EmptyWireResponse() { feedwire::Response response; response.set_response_version(feedwire::Response::FEED_RESPONSE); return response; } // Helper to add some common params. RefreshResponseData TranslateWireResponse(feedwire::Response response) { return TranslateWireResponse( response, StreamModelUpdateRequest::Source::kNetworkUpdate, kCurrentTime); } } // namespace // TODO(iwells): Test failure cases. TEST(ProtocolTranslatorTest, NextPageToken) { feedwire::Response response = EmptyWireResponse(); feedwire::DataOperation* operation = response.mutable_feed_response()->add_data_operation(); operation->set_operation(feedwire::DataOperation::UPDATE_OR_APPEND); operation->mutable_metadata()->mutable_content_id()->set_id(1); operation->mutable_next_page_token() ->mutable_next_page_token() ->set_next_page_token("token"); RefreshResponseData translated = TranslateWireResponse(response); ASSERT_TRUE(translated.model_update_request); EXPECT_EQ(1ul, translated.model_update_request->stream_structures.size()); EXPECT_EQ("token", translated.model_update_request->stream_data.next_page_token()); } TEST(ProtocolTranslatorTest, TranslateRealResponse) { // Tests how proto translation works on a real response from the server. // // The response will periodically need to be updated as changes are made to // the server. Update testdata/response.textproto and then run // tools/generate_test_response_binarypb.sh. feedwire::Response response = TestWireResponse(); RefreshResponseData translated = TranslateWireResponse(response); ASSERT_TRUE(translated.model_update_request); ASSERT_TRUE(translated.request_schedule); EXPECT_EQ(kCurrentTime, translated.request_schedule->anchor_time); EXPECT_EQ(std::vector<base::TimeDelta>( {base::TimeDelta::FromSeconds(86308) + base::TimeDelta::FromNanoseconds(822963644)}), translated.request_schedule->refresh_offsets); std::stringstream ss; ss << *translated.model_update_request; const std::string want = R"(source: 0 stream_data: { last_added_time_millis: 10627200000 shared_state_id { content_domain: "render_data" } } content: { content_id { content_domain: "stories.f" type: 1 id: 3328940074512586021 } frame: "data2" } content: { content_id { content_domain: "stories.f" type: 1 id: 8191455549164721606 } frame: "data3" } content: { content_id { content_domain: "stories.f" type: 1 id: 10337142060535577025 } frame: "data4" } content: { content_id { content_domain: "stories.f" type: 1 id: 9467333465122011616 } frame: "data5" } content: { content_id { content_domain: "stories.f" type: 1 id: 10024917518268143371 } frame: "data6" } content: { content_id { content_domain: "stories.f" type: 1 id: 14956621708214864803 } frame: "data7" } content: { content_id { content_domain: "stories.f" type: 1 id: 2741853109953412745 } frame: "data8" } content: { content_id { content_domain: "stories.f" type: 1 id: 586433679892097787 } frame: "data9" } content: { content_id { content_domain: "stories.f" type: 1 id: 790985792726953756 } frame: "data10" } content: { content_id { content_domain: "stories.f" type: 1 id: 7324025093440047528 } frame: "data11" } shared_state: { content_id { content_domain: "render_data" } shared_state_data: "data1" } stream_structure: { operation: 1 } stream_structure: { operation: 2 content_id { content_domain: "root" } type: 1 } stream_structure: { operation: 2 content_id { content_domain: "render_data" } } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 3328940074512586021 } parent_id { content_domain: "content.f" type: 3 id: 14679492703605464401 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 14679492703605464401 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 8191455549164721606 } parent_id { content_domain: "content.f" type: 3 id: 16663153735812675251 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 16663153735812675251 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 10337142060535577025 } parent_id { content_domain: "content.f" type: 3 id: 15532023010474785878 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 15532023010474785878 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 9467333465122011616 } parent_id { content_domain: "content.f" type: 3 id: 10111267591181086437 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 10111267591181086437 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 10024917518268143371 } parent_id { content_domain: "content.f" type: 3 id: 6703713839373923610 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 6703713839373923610 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 14956621708214864803 } parent_id { content_domain: "content.f" type: 3 id: 12592500096310265284 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 12592500096310265284 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 2741853109953412745 } parent_id { content_domain: "content.f" type: 3 id: 1016582787945881825 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 1016582787945881825 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 586433679892097787 } parent_id { content_domain: "content.f" type: 3 id: 9506447424580769257 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 9506447424580769257 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 790985792726953756 } parent_id { content_domain: "content.f" type: 3 id: 17612738377810195843 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 17612738377810195843 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "stories.f" type: 1 id: 7324025093440047528 } parent_id { content_domain: "content.f" type: 3 id: 5093490247022575399 } type: 3 } stream_structure: { operation: 2 content_id { content_domain: "content.f" type: 3 id: 5093490247022575399 } parent_id { content_domain: "root" } type: 4 } stream_structure: { operation: 2 content_id { content_domain: "request_schedule" id: 300842786 } } max_structure_sequence_number: 0 )"; EXPECT_EQ(want, ss.str()); } } // namespace feed
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
d1dddd37c85f992bc247c47969b7d33df7e6ac8d
4e1289b60e89c20daba942735d18c36826b48622
/Jeepers Elvis!/add-on source/JE Defaults/AlphaMixer/SuperMix.cpp
4ee8713c0ccbca6d8f12038f05b33f64da41f24e
[ "MIT" ]
permissive
jwiggins/BeOS-Projects
ff20283f29baa4c865fc209412e46d32f81626d3
11ce1dd58bf9b5d97e4fac3e514cb5b15b31ea74
refs/heads/master
2021-01-20T12:21:24.154574
2018-09-25T20:29:43
2018-09-25T20:29:43
4,940,876
8
2
MIT
2018-09-25T20:28:17
2012-07-07T20:07:32
C++
UTF-8
C++
false
false
3,071
cpp
/* SuperMix.cpp 2000 John Wiggins */ #include "SuperMix.h" SuperMix::SuperMix() { alpha = 127; scaleX = 1.0f; scaleY = 1.0f; } SuperMix::~SuperMix() { // nichts } void SuperMix::Mix(BBitmap *back, BBitmap *fore, BBitmap *dst) { uint32 *dBits = (uint32 *)dst->Bits(); int32 rowlen = dst->BytesPerRow() / 4; int32 width = dst->Bounds().IntegerWidth(), height = dst->Bounds().IntegerHeight(); // if there are two sources if (fore != NULL) { BRect backRect = back->Bounds(), foreRect = fore->Bounds(); uint32 *fBits = (uint32 *)fore->Bits(), *bBits = (uint32 *)back->Bits(); int32 fRowlen = fore->BytesPerRow() / 4, bRowlen = back->BytesPerRow() / 4; uint32 fVal, bVal, val; uint32 fRed, fGreen, fBlue, bRed, bGreen, bBlue, red, green, blue; bool scale = false, bScale = false, fScale = false; // find out who needs to be scaled (if any) if (backRect.Width() < foreRect.Width() || backRect.Height() < foreRect.Height()) { scale = true; bScale = true; } else if (backRect.Width() > foreRect.Width() || backRect.Height() > foreRect.Height()) { scale = true; fScale = true; } // loop through the dst image for (int32 y = 0; y <= height; y++) { for (int32 x = 0; x <= width; x++) { // do we need to scale? if (scale) { // foreground is scaled if (fScale) { //fVal = fBits[(((int32)floor(y*scaleY))*fRowlen)+((int32)floor(x*scaleX))]; fVal = fBits[(((int32)(y*scaleY))*fRowlen)+((int32)(x*scaleX))]; bVal = bBits[(y*bRowlen)+x]; } else // background is scaled { //bVal = bBits[(((int32)floor(y*scaleY))*bRowlen)+((int32)floor(x*scaleX))]; bVal = bBits[(((int32)(y*scaleY))*bRowlen)+((int32)(x*scaleX))]; fVal = fBits[(y*fRowlen)+x]; } } else { fVal = fBits[(y*fRowlen)+x]; bVal = bBits[(y*bRowlen)+x]; } // foreground components fRed = (fVal>>16 & 0xff); fGreen = (fVal>>8 & 0xff); fBlue = (fVal & 0xff); // background components bRed = (bVal>>16 & 0xff); bGreen = (bVal>>8 & 0xff); bBlue = (bVal & 0xff); // blend // (http://www.gamedev.net/reference/articles/article817.asp) red = ((alpha*(fRed-bRed)) >> 8) + bRed; green = ((alpha*(fGreen-bGreen)) >> 8) + bGreen; blue = ((alpha*(fBlue-bBlue)) >> 8) + bBlue; // smoosh back together val = (uint32)( ((red<<16) | (green<<8) | blue) & 0x00ffffff); // assign dBits[(y*rowlen)+x] = val; } } } else // only one source { uint32 *bBits = (uint32 *)back->Bits(); int32 bRowlen = back->BytesPerRow() / 4; // copy back into dst // back and dst guaranteed to be the same size for (int32 y = 0; y <= height; y++) for (int32 x = 0; x <= width; x++) dBits[(y*rowlen)+x] = bBits[(y*bRowlen)+x]; } } void SuperMix::SetAlpha(uint8 alf) { //printf("SuperMix::SetAlpha()\n"); alpha = alf; } void SuperMix::SetScale(BRect & src, BRect & dst) { //printf("SuperMix::SetScale()\n"); scaleX = src.Width() / dst.Width(); scaleY = src.Height() / dst.Height(); }
[ "jwiggins@enthought.com" ]
jwiggins@enthought.com
99e6d24219bb6ca083b70715b768461887767bca
a09400aa22a27c7859030ec470b5ddee93e0fdf0
/stalkerrender/source/r5/Engine/XRayRSector.h
6d9dbf17ee3147684e3535a9b8885ab8018e9ee1
[]
no_license
BearIvan/Stalker
4f1af7a9d6fc5ed1597ff13bd4a34382e7fdaab1
c0008c5103049ce356793b37a9d5890a996eed23
refs/heads/master
2022-04-04T02:07:11.747666
2020-02-16T10:51:57
2020-02-16T10:51:57
160,668,112
1
1
null
null
null
null
UTF-8
C++
false
false
2,696
h
// Portal.h: interface for the CPortal class. // ////////////////////////////////////////////////////////////////////// #pragma once class CPortal; class CSector; struct _scissor : public Fbox2 { float depth; }; // Connector class CPortal : public IRender_Portal #ifdef DEBUG , public pureRender #endif { private: svector<Fvector,8> poly; CSector *pFace,*pBack; public: Fplane P; Fsphere S; u32 marker; BOOL bDualRender; void Setup (Fvector* V, bsize vcnt, CSector* face, CSector* back); svector<Fvector,8>& getPoly() { return poly; } CSector* Back() { return pBack; } CSector* Front() { return pFace; } CSector* getSector (CSector* pFrom) { return pFrom==pFace?pBack:pFace; } CSector* getSectorFacing (const Fvector& V) { if (P.classify(V)>0) return pFace; else return pBack; } CSector* getSectorBack (const Fvector& V) { if (P.classify(V)>0) return pBack; else return pFace; } float distance (const Fvector &V) { return XrMath::abs(P.classify(V)); } CPortal (); virtual ~CPortal (); #ifdef DEBUG virtual void OnRender (); #endif }; class XRayRenderVisual; // Main 'Sector' class class CSector : public IRender_Sector { protected: XRayRenderVisual* m_root; // whole geometry of that sector xr_vector<CPortal*> m_portals; public: xr_vector<CFrustum> r_frustums; xr_vector<_scissor> r_scissors; _scissor r_scissor_merged; u32 r_marker; public: // Main interface XRayRenderVisual* root () { return m_root; } void traverse (CFrustum& F, _scissor& R); void load (IReader& fs); CSector () { m_root = NULL; } virtual ~CSector ( ); }; class CPortalTraverser { public: enum { VQ_HOM = (1<<0), VQ_SSA = (1<<1), VQ_SCISSOR = (1<<2), VQ_FADE = (1<<3), // requires SSA to work }; public: u32 i_marker; // input u32 i_options; // input: culling options Fvector i_vBase; // input: "view" point Fmatrix i_mXFORM; // input: 4x4 xform Fmatrix i_mXFORM_01; // CSector* i_start; // input: starting point xr_vector<IRender_Sector*> r_sectors; // result xr_vector<std::pair<CPortal*, float> > f_portals; public: CPortalTraverser (); void initialize (); void destroy (); void traverse (IRender_Sector* start, CFrustum& F, Fvector& vBase, Fmatrix& mXFORM, u32 options); void fade_portal (CPortal* _p, float ssa); void fade_render (); #ifdef DEBUG void dbg_draw (); #endif }; extern CPortalTraverser GPortalTraverser ;
[ "i-sobolevskiy@mail.ru" ]
i-sobolevskiy@mail.ru
9fdec4b897521fa225b5adcafd00b0f1c932dbb8
aa1ea8570603cf8866dbb0773d0017a99ad973cb
/prueba4/mainwindow.h
c7cd475a57ac40c7b122a53deef13df95b182189
[]
no_license
hector31/Qt-projects
35835488f203ae2223a732eae35fa2b93ba9b622
b746210eebfa4e969934740647d93a7b559b35f0
refs/heads/master
2020-12-20T20:50:07.462772
2020-01-25T17:48:09
2020-01-25T17:48:09
236,205,817
0
0
null
null
null
null
UTF-8
C++
false
false
311
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
[ "noreply@github.com" ]
noreply@github.com
377c5d0041d850ebedd1f4624a9c37b0cf06d4b6
7f1f2d028a0faa297617a4e2070714891df11688
/ch16/1614funadap.cpp
dfec05b369959927d6ac46c14d9f1c033ddcc87d
[]
no_license
mallius/CppPrimerPlus
3487058a82d74ef0dd0c51b19c9f082b89c0c3f3
2a1ca08b4cdda542bb5cda35c8c5cfd903f969eb
refs/heads/master
2021-01-01T04:12:16.783696
2018-03-08T13:49:17
2018-03-08T13:49:17
58,808,717
0
0
null
null
null
null
UTF-8
C++
false
false
990
cpp
#include <iostream> #include <vector> #include <iterator> #include <algorithm> #include <functional> void Show(double); const int LIM = 5; int main(void) { using namespace std; double arr1[LIM] = {36,39,42,45,48}; double arr2[LIM] = {25,27,29,31,33}; vector<double> gr8(arr1, arr1+LIM); vector<double> m8(arr2, arr2 + LIM); cout.setf(ios_base::fixed); cout.precision(1); cout << "gr8:\t"; for_each(gr8.begin(), gr8.end(), Show); cout << endl; cout << "m8: \t"; for_each(m8.begin(), m8.end(), Show); cout << endl; vector<double> sum(LIM); transform(gr8.begin(), gr8.end(), m8.begin(), sum.begin(), plus<double>()); cout << "sum: \t"; for_each(sum.begin(), sum.end(), Show); cout << endl; vector<double> prod(LIM); transform(gr8.begin(), gr8.end(), prod.begin(), bind1st(multiplies<double>(), 2.5)); cout << "prod: \t"; for_each(prod.begin(), prod.end(), Show); cout << endl; return 0; } void Show(double v) { std::cout.width(6); std::cout << v << ' '; }
[ "mallius@qq.com" ]
mallius@qq.com
2e2f2fc2d8b0825d0f8452581780b2944e2da202
96fd3ba40491c75d8aab6dd419982518dcff25df
/game.cpp
d082b96417ad2f9c902de43ef92f7cbe6829318b
[]
no_license
amalstrom/monopoly
eff379a162603ba995e21b8ac6953dd99b2f6b10
f1e9299f54897066130547dc180680ee454b9aa7
refs/heads/master
2020-05-18T02:03:26.718690
2015-08-18T19:10:37
2015-08-18T19:10:37
40,992,261
1
0
null
null
null
null
UTF-8
C++
false
false
59,203
cpp
// // game.cpp // monopoly // // Created by Alec Malstrom on 7/21/15. // Copyright (c) 2015 Alec Malstrom. All rights reserved. // #include <iostream> #include <stdio.h> #include "game.h" using namespace std; void game_init ( Game *game ) { Board gameboard; board_init(gameboard); chance_init(game); community_init(game); vector<Player *> players; /* GET NUMBER OF PLAYERS */ string in_numPlayers; cout << "How many players will be playing?" << endl; getline(cin, in_numPlayers); int numPlayers; numPlayers = stoi(in_numPlayers); while (!valid_num_players(numPlayers)) { if (numPlayers < 1) { cout << "Then who's typing?\nThere must be at least 2 players. Try again:" << endl; } else if (numPlayers < 2) { cout << "Sorry, you can only play if you have friends.\nThere must be at least 2 players. Try again:" << endl; } else if (numPlayers > 8) { cout << "Whoa there!\nOnly 8 people can play at a time. Try again:" << endl; } getline(cin, in_numPlayers); } /* SELECT PLAYER TOKENS */ vector<Token> pieces = { WHEELBARROW, BATTLESHIP, RACECAR, THIMBLE, SHOE, DOG, TOPHAT, CAT }; for (int i = 0; i < numPlayers; i++) { game->jail_count.push_back(0); string choice; //lists choices and takes input cout << "Okay Player " << i+1 << ", you can play as "; if (pieces.size() > 1) { for (int i = 0; i < pieces.size()-1; i++) { cout << print_token(pieces[i]) << ", "; } cout << "or " << print_token(pieces[pieces.size()-1]) << ". Please enter your choice:" << endl; getline(cin, choice); } else { cout << print_token(pieces[0]) << ". Please enter your choice:" << endl; getline(cin, choice); } //ensures valid choice bool valid_choice = false; for (int j = 0; j < pieces.size(); j++) { if (string_token(choice) == pieces[j]) { valid_choice = true; break; } } //corrects if invalid while (!valid_choice) { cout << "Invalid Choice. Please enter your choice again:" << endl; getline(cin, choice); for (int j = 0; j < pieces.size(); j++) { if (string_token(choice) == pieces[j]) { valid_choice = true; break; } } } //initializes player and adds to vector Player *player = new Player(); player_init(player, string_token(choice)); Token choiceToken = string_token(choice); bool notFound = true; for (int i = 0; i < pieces.size(); i++) { if (pieces[i] == choiceToken) { notFound = false; } if (notFound == true) { continue; } pieces[i] = pieces[i+1]; } pieces.pop_back(); players.push_back(player); } game->board = gameboard; game->players = players; } void chance_init ( Game *game ) { game->chance.push_back("Make general repairs on all your property. For each house pay $25, for each hotel pay $100."); game->chance.push_back("Go to Jail. Go directly to Jail, do not pass Go, do not collect $200."); game->chance.push_back("Speeding fine $15."); game->chance.push_back("Advance to the nearest railroad. If unowned, you may buy it from the bank. If owned, pay owner twice the rental to which they are otherwise entitled."); game->chance.push_back("Advance to the nearest railroad. If unowned, you may buy it from the bank. If owned, pay owner twice the rental to which they are otherwise entitled."); game->chance.push_back("Advance to Boardwalk."); game->chance.push_back("Take a trip to Reading Railroad. If you pass Go, collect $200."); game->chance.push_back("You have been elected chairman of the board. Pay each player $50."); game->chance.push_back("Get out of Jail free. This card may be kept until needed or traded."); game->chance.push_back("Advance to St. Charles Place. If you pass go, collect $200."); game->chance.push_back("Advance to the nearest utility. If unowned, you may buy it from the bank. If owned, throw dice and pay owner ten times the amount thrown."); game->chance.push_back("Go back three spaces."); game->chance.push_back("Advance to Go. (Collect $200)"); game->chance.push_back("Advance to Illinois Avenue. If you pass Go, collect $200."); game->chance.push_back("Bank pays you dividend of $50."); game->chance.push_back("Your building loan matures. Collect $150."); } void community_init ( Game *game ) { game->community_chest.push_back("From sale of stock you get $50."); game->community_chest.push_back("School fees. Pay $50."); game->community_chest.push_back("You have won second prize in a beauty contest. Collect $10."); game->community_chest.push_back("You are assessed for street repairs: pay $40 per house and $115 per hotel you own."); game->community_chest.push_back("Hospital fees. Pay $100."); game->community_chest.push_back("Go to Jail. Go directly to Jail, do not pass Go, do not collect $200."); game->community_chest.push_back("You inherity $100."); game->community_chest.push_back("Receive $25 consultancy fee."); game->community_chest.push_back("Doctor's fees. Pay $50."); game->community_chest.push_back("It is your birthday. Collect $10 from every player."); game->community_chest.push_back("Get out of Jail free. This card may be kept until needed or traded."); game->community_chest.push_back("Holiday fund matures. Receive $100."); game->community_chest.push_back("Advance to Go. (Collect $200)"); game->community_chest.push_back("Bank error in your favor. Collect $200."); game->community_chest.push_back("Life insurance matures. Collect $100."); game->community_chest.push_back("Income tax refund. Collect $20."); } bool valid_num_players (int num) { if (num < 2) { return false; } else if (num >8) { return false; } else { return true; } } int roll () { int dice = (rand() % 6) + 1; return dice; } int determine_order (Game *game) { cout << "\nTo decide who goes first, each person will roll one of the die." << endl; vector<int> first_rolls; bool tie = true; int winner_index = 0; int winner_roll = 0; while (tie) { /* EVERYONE ROLLS */ for (int i = 0; i < game->players.size(); i++) { cout << print_token(game->players[i]->token) << ", type 'Roll' to roll the die." << endl; string trash; getline(cin, trash); if (trash == "Roll") { int result = roll(); cout << print_token(game->players[i]->token) << " got " << result << "!" << endl; first_rolls.push_back(result); } else { cout << "You're an idiot. We're counting that as 1." << endl; first_rolls.push_back(1); } } /* DETERMINES IF WINNER IS TIED */ tie = false; winner_index = -1; winner_roll = 0; for (int i = 0; i < first_rolls.size(); i++) { if (first_rolls[i] > winner_roll) { winner_index = i; winner_roll = first_rolls[i]; tie = false; } else if (first_rolls[i] == winner_roll) { tie = true; } } /* INSTRUCTIONS IF TIED */ if (tie) { cout << "For a tie, everyone has to roll again." << endl; while (first_rolls.size()) { first_rolls.pop_back(); } } } /* RETURNS THE WINNER'S INDEX */ return winner_index; } bool game_over ( Game *game ) { if (game->players.size() == 1) { return true; } return false; }; void list_positions ( Game *game ) { cout << "LOCATIONS: " << endl; for (int i = 0; i < game->players.size(); i++) { cout << print_token(game->players[i]->token) << " is on " << game->board.board[game->players[i]->location_index]->name << endl; } cout << endl; } void take_turn ( Game* game, int &current_index ) { bool active = true; bool doubs = true; list_positions(game); cout << print_token(game->players[current_index]->token) << " is starting its turn." << endl; while (active) { if ((!game->players[current_index]->free) && (doubs)) { in_jail(game, current_index); bool invalid_input = true; while (invalid_input) { string input; getline(cin, input); if ((input == "Roll for Doubles") && (game->jail_count[current_index] < 3)) { doubs = false; invalid_input = false; pair<int, int> dice_roll = roll_dice(game->players[current_index]->token); if (dice_roll.first == dice_roll.second) { cout << "Doubles!" << endl; get_out_of_jail(game, current_index, "Doubles"); move_token(game, current_index, game->players[current_index]->location_index, game->players[current_index]->location_index+dice_roll.first+dice_roll.second, dice_roll.first+dice_roll.second); } game->jail_count[current_index]++; if ((game->jail_count[current_index] == 3) && (!game->players[current_index]->free)) { get_out_of_jail(game, current_index, "Cash"); move_token(game, current_index, game->players[current_index]->location_index, game->players[current_index]->location_index+dice_roll.first+dice_roll.second, dice_roll.first+dice_roll.second); } continue; } else if ((input == "Use 'Get Out of Jail Free' Card") && (game->players[current_index]->cc_jail || game->players[current_index]->chance_jail)) { doubs = false; invalid_input = false; get_out_of_jail(game, current_index, "Card"); pair<int, int> dice_roll = roll_dice(game->players[current_index]->token); if (dice_roll.first == dice_roll.second) { doubs = true; cout << "Doubles!" << endl; } move_token(game, current_index, game->players[current_index]->location_index, game->players[current_index]->location_index+dice_roll.first+dice_roll.second, dice_roll.first+dice_roll.second); continue; } else if (input == "Post $50 Bail") { doubs = false; invalid_input = false; get_out_of_jail(game, current_index, "Cash"); pair<int, int> dice_roll = roll_dice(game->players[current_index]->token); if (dice_roll.first == dice_roll.second) { doubs = true; cout << "Doubles!" << endl; } move_token(game, current_index, game->players[current_index]->location_index, game->players[current_index]->location_index+dice_roll.first+dice_roll.second, dice_roll.first+dice_roll.second); continue; } else if (input == "Trade") { invalid_input = false; trade(game, current_index); continue; } else if (input == "Manage Properties") { invalid_input = false; manage_properties(game, current_index); continue; } else if (input == "List Accounts") { invalid_input = false; list_accounts(game); continue; } else if (input == "List Properties") { invalid_input = false; list_properties(game); continue; } else { cout << "Invalid Input. Please try again:" << endl; } } } if (doubs) { print_turn_options1(); } else { print_turn_options2(); } string input; getline(cin, input); if ((input == "Roll") && (doubs)) { doubs = false; pair<int, int> dice = roll_dice( game->players[current_index]->token ); if (dice.first == dice.second) { doubs = true; cout << "Doubles!" << endl; } move_token (game, current_index, game->players[current_index]->location_index, game->players[current_index]->location_index+dice.first+dice.second, dice.first+dice.second); } else if (input == "Trade") { trade (game, current_index); } else if (input == "Manage Properties") { manage_properties (game, current_index); } else if (input == "List Accounts") { list_accounts (game); } else if (input == "List Properties") { list_properties (game); } else if ((input == "End Turn") && (!doubs)) { end_turn(game, current_index); active = false; } else { cout << "Invalid input. Try again:" << endl; } } } void print_turn_options1 () { cout << "Options: " << endl; cout << "\tRoll" << endl; cout << "\tTrade" << endl; cout << "\tManage Properties" << endl; cout << "\tList Accounts" << endl; cout << "\tList Properties" << endl; cout << "Please select an option:" << endl; } void print_turn_options2 () { cout << "Options: " << endl; cout << "\tTrade" << endl; cout << "\tManage Properties" << endl; cout << "\tList Accounts" << endl; cout << "\tList Properties" << endl; cout << "\tEnd turn" << endl; cout << "Please select an option:" << endl; } pair<int, int> roll_dice ( Token current_token ) { int die1 = roll(); int die2 = roll(); cout << print_token(current_token) << " rolled a " << die1 << " and a " << die2 << endl; return make_pair(die1, die2); } void end_turn ( Game* game, int &current_index ) { cout << print_token(game->players[current_index]->token) << " has finished its turn.\n" << endl; current_index++; if (current_index == game->players.size()) { current_index = 0; } } void print_purchase_opts () { cout << "The property is for sale! Would you like to buy it? Enter 'Buy' or 'Pass'" << endl; } void buy_property ( Game *game, int &current_index ) { if (check_cash_flow(game->board.board[game->players[current_index]->location_index]->price, game->players[current_index]->cashOnHand)) { game->board.board[game->players[current_index]->location_index]->owner = game->players[current_index]; game->players[current_index]->ownership[game->players[current_index]->location_index] = true; game->players[current_index]->cashOnHand -= game->board.board[game->players[current_index]->location_index]->price; cout << print_token(game->players[current_index]->token) << " has bought " << game->board.board[game->players[current_index]->location_index]->name << " from the bank for $" << game->board.board[game->players[current_index]->location_index]->price << "." << endl; update_monopoly(game, game->board.board[game->players[current_index]->location_index]); } else { broke_player(game, current_index); } } void pass_property ( Game *game, int &current_index ) { cout << "Property was passed on. Nothing happens!" << endl; } void pay_rent ( Game *game, int &current_index, int dice_roll ) { if (check_cash_flow(get_rent(game, current_index, dice_roll), game->players[current_index]->cashOnHand)) { game->board.board[game->players[current_index]->location_index]->owner->cashOnHand += get_rent(game, current_index, dice_roll); game->players[current_index]->cashOnHand -= get_rent(game, current_index, dice_roll); cout << print_token(game->players[current_index]->token) << " paid " << print_token(game->board.board[game->players[current_index]->location_index]->owner->token) << " $" << get_rent(game, current_index, dice_roll) << " in rent." << endl; } else { broke_player(game, current_index); } } int get_rent( Game *game, int &current_index, int dice_roll ) { Space *temp = game->board.board[game->players[current_index]->location_index]; if (temp->color == RAILROAD) { if (temp->numHouses == 1) { return 25; } else if (temp->numHouses == 2) { return 50; } else if (temp->numHouses == 3) { return 100; } else if (temp->numHouses == 4) { return 200; } } else if (temp->color == UTILITY) { if (temp->numHouses == 1) { return 4*dice_roll; } else if (temp->numHouses == 2) { return 10*dice_roll; } } if (temp->monopoly) { if (temp->numHouses == 0) { return 2*temp->rent; } else if (temp->numHouses == 1) { return temp->rent1; } else if (temp->numHouses == 2) { return temp->rent2; } else if (temp->numHouses == 3) { return temp->rent3; } else if (temp->numHouses == 4) { return temp->rent4; } else if (temp->numHouses == 5) { return temp->rentH; } } else { return temp->rent; } return 0; } void update_monopoly ( Game *game, Space* recent_purchase ) { if (recent_purchase->color == BROWN) { if (game->board.board[1]->owner == game->board.board[3]->owner) { game->board.board[1]->monopoly = game->board.board[3]->monopoly = true; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == LIGHTBLUE) { if ((game->board.board[6]->owner == game->board.board[8]->owner) && (game->board.board[8]->owner == game->board.board[9]->owner)) { game->board.board[6]->monopoly = game->board.board[8]->monopoly = game->board.board[9]->monopoly = true; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == PINK) { if ((game->board.board[11]->owner == game->board.board[13]->owner) && (game->board.board[13]->owner == game->board.board[14]->owner)) { game->board.board[11]->monopoly = game->board.board[13]->monopoly = game->board.board[14]->monopoly = true; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == ORANGE) { if ((game->board.board[16]->owner == game->board.board[18]->owner) && (game->board.board[18]->owner == game->board.board[19]->owner)) { game->board.board[16]->monopoly = game->board.board[18]->monopoly = game->board.board[19]->monopoly = true; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == RED) { if ((game->board.board[21]->owner == game->board.board[23]->owner) && (game->board.board[23]->owner == game->board.board[24]->owner)) { game->board.board[21]->monopoly = game->board.board[23]->monopoly = game->board.board[24]->monopoly = true; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == YELLOW) { if ((game->board.board[26]->owner == game->board.board[27]->owner) && (game->board.board[27]->owner == game->board.board[29]->owner)) { game->board.board[26]->monopoly = game->board.board[27]->monopoly = game->board.board[29]->monopoly = true; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == GREEN) { if ((game->board.board[31]->owner == game->board.board[32]->owner) && (game->board.board[32]->owner == game->board.board[34]->owner)) { game->board.board[31]->monopoly = game->board.board[32]->monopoly = game->board.board[34]->monopoly = true; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == DARKBLUE) { if (game->board.board[37]->owner == game->board.board[39]->owner) { game->board.board[37]->monopoly = game->board.board[39]->monopoly = true; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == RAILROAD) { int num_rr = 0; if (recent_purchase->owner->ownership[5]) { num_rr++; } if (recent_purchase->owner->ownership[15]) { num_rr++; } if (recent_purchase->owner->ownership[25]) { num_rr++; } if (recent_purchase->owner->ownership[35]) { num_rr++; } if (recent_purchase->owner->ownership[5]) { game->board.board[5]->numHouses = num_rr; } if (recent_purchase->owner->ownership[15]) { game->board.board[15]->numHouses = num_rr; } if (recent_purchase->owner->ownership[25]) { game->board.board[25]->numHouses = num_rr; } if (recent_purchase->owner->ownership[35]) { game->board.board[35]->numHouses = num_rr; } if (num_rr == 4) { cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } } else if (recent_purchase->color == UTILITY) { if (game->board.board[12]->owner == game->board.board[28]->owner) { game->board.board[12]->numHouses = game->board.board[28]->numHouses = 2; cout << "YOU'VE COMPLETED A MONOPOLY!" << endl; } else { recent_purchase->numHouses = 1; } } } string draw_chance ( Game* game ) { string chance_card; if (game->community_chest.size() == 1) { chance_card = game->community_chest[0]; game->community_chest.pop_back(); for (int i = 0; i < game->community_discard.size(); i++) { game->community_chest.push_back(game->community_discard[game->community_discard.size()-1]); game->community_discard.pop_back(); } } else { int draw_num = rand(); draw_num = draw_num % game->chance.size(); chance_card = game->chance[draw_num]; for (int i = draw_num; i < game->chance.size()-1; i++) { game->chance[i] = game->chance[i+1]; } } game->chance.pop_back(); return chance_card; } void execute_chance ( Game* game, string chance_card, int current_index ) { if (chance_card == "Make general repairs on all your property. For each house pay $25, for each hotel pay $100.") { pay_for_buildings(game, current_index, 25, 100); game->chance_discard.push_back(chance_card); } else if (chance_card == "Go to Jail. Go directly to Jail, do not pass Go, do not collect $200.") { move_token(game, current_index, 40, 30, 0); game->chance_discard.push_back(chance_card); } else if (chance_card == "Speeding fine $15.") { game->players[current_index]->cashOnHand -= 15; game->chance_discard.push_back(chance_card); } else if (chance_card == "Advance to the nearest railroad. If unowned, you may buy it from the bank. If owned, pay owner twice the rental to which they are otherwise entitled.") { if (game->players[current_index]->location_index < 5) { game->players[current_index]->location_index = 5; } else if (game->players[current_index]->location_index < 15) { game->players[current_index]->location_index = 15; } else if (game->players[current_index]->location_index < 25) { game->players[current_index]->location_index = 25; } else if (game->players[current_index]->location_index < 35) { game->players[current_index]->location_index = 35; } else { game->players[current_index]->location_index = 5; game->players[current_index]->cashOnHand += 200; } if (game->board.board[game->players[current_index]->location_index]->owner == nullptr) { offer_property(game, current_index); } else { pay_twice_rent (game, current_index); } game->chance_discard.push_back(chance_card); } else if (chance_card == "Advance to Boardwalk.") { move_token(game, current_index, game->players[current_index]->location_index, 39, 0); game->chance_discard.push_back(chance_card); } else if (chance_card == "Take a trip to Reading Railroad. If you pass Go, collect $200.") { move_token(game, current_index, game->players[current_index]->location_index, 5, 0); game->chance_discard.push_back(chance_card); } else if (chance_card == "You have been elected chairman of the board. Pay each player $50.") { for (int i = 0; i < game->players.size(); i++) { if (i == current_index) { continue; } game->players[current_index]->cashOnHand -= 50; game->players[i]->cashOnHand += 50; } game->chance_discard.push_back(chance_card); } else if (chance_card == "Get out of Jail free. This card may be kept until needed or traded.") { game->players[current_index]->chance_jail = true; } else if (chance_card == "Advance to St. Charles Place. If you pass go, collect $200.") { move_token(game, current_index, game->players[current_index]->location_index, 11, 0); game->chance_discard.push_back(chance_card); } else if (chance_card == "Advance to the nearest utility. If unowned, you may buy it from the bank. If owned, throw dice and pay owner ten times the amount thrown.") { pair<int, int> dice = roll_dice( game->players[current_index]->token ); if (game->players[current_index]->location_index < 12) { move_token(game, current_index, game->players[current_index]->location_index, 12, dice.first+dice.second); } else if (game->players[current_index]->location_index < 28) { move_token(game, current_index, game->players[current_index]->location_index, 28, dice.first+dice.second); } else { move_token(game, current_index, game->players[current_index]->location_index, 12, dice.first+dice.second); } game->chance_discard.push_back(chance_card); } else if (chance_card == "Go back three spaces.") { move_token(game, current_index, game->players[current_index]->location_index, game->players[current_index]->location_index - 3, 0); game->chance_discard.push_back(chance_card); } else if (chance_card == "Advance to Go. (Collect $200)") { move_token(game, current_index, game->players[current_index]->location_index, 0, 0); game->chance_discard.push_back(chance_card); } else if (chance_card == "Advance to Illinois Avenue. If you pass Go, collect $200.") { move_token(game, current_index, game->players[current_index]->location_index, 24, 0); game->chance_discard.push_back(chance_card); } else if (chance_card == "Bank pays you dividend of $50.") { game->players[current_index]->cashOnHand += 50; game->chance_discard.push_back(chance_card); } else if ("Your building loan matures. Collect $150.") { game->players[current_index]->cashOnHand += 150; game->chance_discard.push_back(chance_card); } } void offer_property ( Game* game, int current_index ) { print_purchase_opts(); bool invalid_input = true; while (invalid_input) { string buyPass; getline(cin, buyPass); if (buyPass == "Buy") { buy_property(game, current_index); invalid_input = false; } else if (buyPass == "Pass") { pass_property(game, current_index); invalid_input = false; } else { cout << "Invalid input. Please try again:" << endl; } } } void pay_twice_rent ( Game* game, int current_index ) { game->board.board[game->players[current_index]->location_index]->owner->cashOnHand += 2* get_rent(game, current_index, 0); game->players[current_index]->cashOnHand -= 2* get_rent(game, current_index, 0); } void move_token ( Game *game, int current_index, int current_location, int new_location, int dice_roll ) { if (new_location > 39) { new_location -= 40; } if ((passes_go(current_location, new_location)) && game->players[current_index]->free){ pass_go(game, current_index); } game->players[current_index]->location_index = new_location; if (game->board.board[game->players[current_index]->location_index]->type == PROPERTY) { cout << print_token(game->players[current_index]->token) << " has moved to " << game->board.board[new_location]->name << endl; if (game->board.board[game->players[current_index]->location_index]->owner == nullptr) { offer_property(game, current_index); } else { if (game->board.board[game->players[current_index]->location_index]->owner == game->players[current_index]) { cout << print_token(game->players[current_index]->token) << " owns this property." << endl; } else { pay_rent(game, current_index, dice_roll); } } } else if (game->board.board[game->players[current_index]->location_index]->type == GO) { cout << print_token(game->players[current_index]->token) << " landed on Go and collected $200!" << endl; game->players[current_index]->cashOnHand += 200; } else if (game->board.board[game->players[current_index]->location_index]->type == JAIL) { cout << print_token(game->players[current_index]->token) << " landed on Jail but is just visiting!" << endl; } else if (game->board.board[game->players[current_index]->location_index]->type == FREEPARK) { cout << print_token(game->players[current_index]->token) << " landed on Free Parking!" << endl; } else if (game->board.board[game->players[current_index]->location_index]->type == GOTOJAIL) { cout << print_token(game->players[current_index]->token) << " was sent to Jail." << endl; game->players[current_index]->free = false; game->players[current_index]->location_index = 10; } else if (game->board.board[game->players[current_index]->location_index]->type == CHANCE) { cout << print_token(game->players[current_index]->token) << " landed on Chance!" << endl; string chance_card = draw_chance(game); cout << "Chance: " << chance_card << endl; execute_chance(game, chance_card, current_index); } else if (game->board.board[game->players[current_index]->location_index]->type == COMMUNITY) { cout << print_token(game->players[current_index]->token) << " landed on Community Chest!" << endl; string cc_card = draw_community(game); cout << "Community Chest: " << cc_card << endl; execute_community(game, cc_card, current_index); } else if (game->board.board[game->players[current_index]->location_index]->type == INCOME) { game->players[current_index]->cashOnHand -= 200; cout << print_token(game->players[current_index]->token) << " landed on Income Tax and paid $200 to the bank." << endl; } else if (game->board.board[game->players[current_index]->location_index]->type == LUXURY) { game->players[current_index]->cashOnHand -= 100; cout << print_token(game->players[current_index]->token) << " landed on Luxury Tax and paid $100 to the bank." << endl; } } void pass_go ( Game *game, int current_index ) { cout << print_token(game->players[current_index]->token) << " has passed Go and collected $200." << endl; game->players[current_index]->cashOnHand += 200; } void list_accounts ( Game *game ) { for (int i = 0; i < game->players.size(); i++) { cout << print_token(game->players[i]->token) << " has $" << game->players[i]->cashOnHand << endl; } cout << endl; } void list_properties ( Game *game ) { for (int i = 0; i < game->players.size(); i++) { cout << print_token(game->players[i]->token) << "'s Properties:" << endl; for (int j = 0; j < 40; j++) { if (game->players[i]->ownership[j]) { cout << "\t" << game->board.board[j]->name << endl; } } } cout << endl; } bool passes_go ( int current_location, int new_location ) { if ((new_location - current_location < 0) && (new_location != 0)) { return true; } else { return false; } } string draw_community ( Game *game ) { string cc_card; if (game->community_chest.size() == 1) { cc_card = game->community_chest[0]; game->community_chest.pop_back(); for (int i = 0; i < game->community_discard.size(); i++) { game->community_chest.push_back(game->community_discard[game->community_discard.size()-1]); game->community_discard.pop_back(); } } else { int draw_num = rand(); draw_num = draw_num % game->community_chest.size(); cc_card = game->community_chest[draw_num]; for (int i = draw_num; i < game->community_chest.size() - 1; i++) { game->community_chest[i] = game->community_chest[i+1]; } game->community_chest.pop_back(); } return cc_card; } void execute_community ( Game *game, string cc_card, int current_index ) { if (cc_card == "From sale of stock you get $50.") { game->players[current_index]->cashOnHand += 50; game->community_discard.push_back(cc_card); } else if (cc_card == "School fees. Pay $50.") { game->players[current_index]->cashOnHand -= 50; game->community_discard.push_back(cc_card); } else if (cc_card == "You have won second prize in a beauty contest. Collect $10.") { game->players[current_index]->cashOnHand += 10; game->community_discard.push_back(cc_card); } else if (cc_card == "You are assessed for street repairs: pay $40 per house and $115 per hotel you own.") { pay_for_buildings(game, current_index, 40, 115); game->community_discard.push_back(cc_card); } else if (cc_card == "Hospital fees. Pay $100.") { game->players[current_index]->cashOnHand -= 100; game->community_discard.push_back(cc_card); } else if (cc_card == "Go to Jail. Go directly to Jail, do not pass Go, do not collect $200.") { move_token(game, current_index, game->players[current_index]->location_index, 30, 0); game->community_discard.push_back(cc_card); } else if (cc_card == "You inherit $100.") { game->players[current_index]->cashOnHand += 100; game->community_discard.push_back(cc_card); } else if (cc_card == "Receive $25 consultancy fee.") { game->players[current_index]->cashOnHand += 25; game->community_discard.push_back(cc_card); } else if (cc_card == "Doctor's fees. Pay $50.") { game->players[current_index]->cashOnHand -= 50; game->community_discard.push_back(cc_card); } else if (cc_card == "It is your birthday. Collect $10 from every player.") { for (int i = 0; i < game->players.size(); i++) { if (i == current_index) { continue; } game->players[i]->cashOnHand -= 10; game->players[current_index] += 10; } game->community_discard.push_back(cc_card); } else if (cc_card == "Get out of Jail free. This card may be kept until needed or traded.") { game->players[current_index]->cc_jail = true; } else if (cc_card == "Holiday fund matures. Receive $100.") { game->players[current_index]->cashOnHand += 100; game->community_discard.push_back(cc_card); } else if (cc_card == "Advance to Go. (Collect $200)") { move_token(game, current_index, game->players[current_index]->location_index, 0, 0); game->community_discard.push_back(cc_card); } else if (cc_card == "Bank error in your favor. Collect $200.") { game->players[current_index]->cashOnHand += 200; game->community_discard.push_back(cc_card); } else if (cc_card == "Life insurance matures. Collect $100.") { game->players[current_index]->cashOnHand += 100; game->community_discard.push_back(cc_card); } else if (cc_card == "Income tax refund. Collect $20.") { game->players[current_index]->cashOnHand += 20; game->community_discard.push_back(cc_card); } } void pay_for_buildings ( Game *game, int current_index, int housePrice, int hotelPrice ) { int numHouses = 0; int numHotels = 0; for (int i = 0; i < 40; i++) { if (game->players[current_index]->ownership[i]) { if ((game->board.board[i]->color != RAILROAD) && (game->board.board[i]->color != UTILITY)) { if (game->board.board[i]->numHouses == 5) { numHotels++; } else { numHouses += game->board.board[i]->numHouses; } } } } int totalPrice = (numHouses*housePrice) + (numHotels*hotelPrice); game->players[current_index]->cashOnHand -= totalPrice; } void manage_properties ( Game *game, int current_index ) { print_manage_opts(); bool invalid_input = true; while (invalid_input) { string input; getline(cin, input); if (input == "Mortgage Properties") { invalid_input = false; mortgage(game, current_index); } else if (input == "Unmortgage Properties") { invalid_input = false; bool prop_listed = false; int unmortgage_index = 0; cout << "Properties that can be unmortgaged:" << endl; for (int i = 0; i < 40; i++) { if ((game->players[current_index]->ownership[i]) && (game->board.board[i]->mortgaged)) { prop_listed = true; cout << "\t" << game->board.board[i]->name << endl; } } if (prop_listed) { bool invalid_input2 = true; while (invalid_input2) { getline(cin, input); for (int i = 0; i < 40; i++) { if (input == game->board.board[i]->name) { invalid_input2 = false; unmortgage_index = i; break; } } if (unmortgage_index != 0) { unmortgage_property(game, unmortgage_index); } else { cout << "No such property! Try again: " << endl; } } } else { cout << "Sorry! No Properties to Unmortgage." << endl; } } else if (input == "Build Improvements") { invalid_input = false; int build_index = 0; cout << "Properties that can be built upon:" << endl; bool prop_listed = false; for (int i = 0; i < 40; i++) { if ((game->players[current_index]->ownership[i]) && (game->board.board[i]->monopoly)) { prop_listed = true; cout << "\t" << game->board.board[i]->name << endl; } } if (prop_listed) { bool invalid_input2 = true; while (invalid_input2) { getline(cin, input); for (int i = 0; i < 40; i++) { if (input == game->board.board[i]->name) { invalid_input2 = false; build_index = i; break; } } if (build_index != 0) { build_property(game, build_index); } else { cout << "No such property! Try again: " << endl; } } } } else if (input == "Cancel") { invalid_input = false; } else { cout << "Invalid Input. Please try again: " << endl; } } } void print_manage_opts() { cout << "Manage Properties:" << endl; cout << "\tMortgage Properties" << endl; cout << "\tUnmortgage Properties" << endl; cout << "\tBuild Improvements" << endl; cout << "\tCancel" << endl; cout << "Please Enter:" << endl; } void mortgage ( Game *game, int current_index ) { bool prop_listed = false; int mortgage_index = 0; string input; cout << "Properties that can be mortgaged:" << endl; for (int i = 0; i < 40; i++) { if ((game->players[current_index]->ownership[i]) && (!game->board.board[i]->mortgaged)) { prop_listed = true; cout << "\t" << game->board.board[i]->name << endl; } } if (prop_listed) { bool invalid_input2 = true; cout << "Please Select the Property to Mortgage:" << endl; while (invalid_input2) { getline(cin, input); for (int i = 0; i < 40; i++) { if (input == game->board.board[i]->name) { invalid_input2 = false; mortgage_index = i; break; } } } if (mortgage_index != 0) { mortgage_property(game, mortgage_index); } else { cout << "No such property! Try again: " << endl; } } else { cout << "Sorry! No Properties to Mortgage." << endl; } } void mortgage_property ( Game *game, int mortgage_index ) { game->board.board[mortgage_index]->mortgaged = true; game->board.board[mortgage_index]->owner->cashOnHand += game->board.board[mortgage_index]->price/2; } void unmortgage_property ( Game *game, int unmortgage_index ) { game->board.board[unmortgage_index]->mortgaged = false; game->board.board[unmortgage_index]->owner->cashOnHand -= game->board.board[unmortgage_index]->price/2; } void build_property( Game *game, int build_index ) { cout << "How many buildings would you like to build?" << endl; string st_input; getline(cin, st_input); int input = stoi(st_input); game->board.board[build_index]->numHouses += input; game->board.board[build_index]->owner->cashOnHand -= input*game->board.board[build_index]->houseCost; } void trade ( Game *game, int current_index ) { trade_companions (game, current_index); } void trade_companions ( Game *game, int current_index ) { cout << "Trade with:" << endl; for (int i = 0; i < game->players.size(); i++) { if (current_index == i) { continue; } cout << "\t" << print_token(game->players[i]->token) << endl; } cout << "Who do you want to trade with?" << endl; bool invalid_input = true; while(invalid_input) { string input; getline(cin, input); int trade_index = -1; for (int i = 0; i < game->players.size(); i++) { if (input == print_token(game->players[i]->token)) { invalid_input = false; trade_index = i; } } if (trade_index != -1) { initialize_trade (game, current_index, trade_index); } else { cout << "Invalid input. Try Again: " << endl; } } } void initialize_trade ( Game *game, int current_index, int trade_index ) { cout << "The properties you have:" << endl; for (int i = 0; i < 40; i++) { if (game->players[current_index]->ownership[i]) { cout << "\t" << game->board.board[i]->name << endl; } } cout << "You have $" << game->players[current_index]->cashOnHand; if (game->players[current_index]->cc_jail || game->players[current_index]->chance_jail) { if (game->players[current_index]->cc_jail && game->players[current_index]->chance_jail) { cout << "You also have 2 'Get out of Jail Free' Cards" << endl; } else { cout << "You also have 1 'Get out of Jail Free' Card" << endl; } } cout << "The properties " << print_token(game->players[trade_index]->token) << " has:" << endl; for (int i = 0; i < 40; i++) { if (game->players[trade_index]->ownership[i]) { cout << "\t" << game->board.board[i]->name << endl; } } cout << print_token(game->players[trade_index]->token) << " has $" << game->players[trade_index]->cashOnHand << endl; if (game->players[trade_index]->cc_jail || game->players[trade_index]->chance_jail) { if (game->players[trade_index]->cc_jail && game->players[trade_index]->chance_jail) { cout << print_token(game->players[trade_index]->token) << " also has 2 'Get out of Jail Free' Cards" << endl; } else { cout << print_token(game->players[trade_index]->token) << " also has 1 'Get out of Jail Free' Card" << endl; } } compose_trade(game, current_index, trade_index); } void compose_trade ( Game *game, int current_index, int trade_index ) { vector<Space *> take_prop; vector<Space *> offer_prop; int take_money = 0; int offer_money = 0; bool cc_take = false; bool cc_offer = false; bool chance_take = false; bool chance_offer = false; bool invalid_input = true; while (invalid_input) { cout << "Add Property from Opponent" << endl; cout << "Add Money from Opponent" << endl; cout << "Add 'Get out of Jail Free' Card from Opponent" << endl; cout << "Add Property to Offer" << endl; cout << "Add Money to Offer" << endl; cout << "Add 'Get out of Jail Free' Card to Offer" << endl; cout << "Make Offer" << endl; cout << "Cancel Offer" << endl; cout << "Please enter choice: " << endl; string input; getline(cin, input); if (input == "Add Property from Opponent") { cout << "Which property would you like to add?" << endl; bool invalid_input2 = true; while (invalid_input2) { getline(cin, input); for (int i = 0; i < 40; i++) { if (input == game->board.board[i]->name) { invalid_input2 = false; take_prop.push_back(game->board.board[i]); } } if (invalid_input2) { cout << "That property is not available for trade. Please try again:" << endl; } } } else if (input == "Add Money from Opponent") { cout << "How much money would you like?" << endl; string money_in; getline(cin, money_in); take_money = stoi(money_in); } else if (input == "Add 'Get out of Jail Free' Car from Opponent") { if (game->players[trade_index]->cc_jail || game->players[trade_index]->chance_jail) { if (game->players[trade_index]->cc_jail && game->players[trade_index]->chance_jail) { cc_take = true; } else if (game->players[trade_index]->cc_jail) { cc_take = true; } else { chance_take = true; } } else { cout << "Sorry! " << print_token(game->players[trade_index]->token) << " has no 'Get out of Jail Free' Cards." << endl; } } else if (input == "Add Property to Offer") { cout << "Which property would you like to add?" << endl; bool invalid_input2 = true; while (invalid_input2) { getline(cin, input); for (int i = 0; i < 40; i++) { if (input == game->board.board[i]->name) { invalid_input2 = false; offer_prop.push_back(game->board.board[i]); } } if (invalid_input2) { cout << "That property is not available for trade. Please try again:" << endl; } } } else if (input == "Add Money to Offer") { cout << "How much money would you like to offer?" << endl; string money_in; getline(cin, money_in); offer_money = stoi(money_in); } else if (input == "Add 'Get out of Jail Free' Card to Offer") { if (game->players[current_index]->cc_jail || game->players[current_index]->chance_jail) { if (game->players[current_index]->cc_jail && game->players[current_index]->chance_jail) { cc_offer = true; } else if (game->players[current_index]->cc_jail) { cc_offer = true; } else { chance_offer = true; } } else { cout << "Sorry! You do not have any 'Get out of Jail Free' Cards." << endl; } } else if (input == "Cancel Offer") { } else if (input == "Make Offer") { make_offer (game, current_index, trade_index, take_prop, offer_prop, take_money, offer_money, cc_take, cc_offer, chance_take, chance_offer); invalid_input = false; } else { cout << "Invalid input. Please try again: " << endl; } } } void make_offer ( Game *game, int current_index, int trade_index, vector<Space *> take_prop, vector<Space *> offer_prop, int take_money, int offer_money, bool cc_take, bool cc_offer, bool chance_take, bool chance_offer ) { cout << print_token(game->players[trade_index]->token) << ", " << print_token(game->players[current_index]->token) << " would like to trade with you." << endl; cout << print_token(game->players[current_index]->token) << " is offering: " << endl; for (int i = 0; i < offer_prop.size(); i++) { cout << "\t" << offer_prop[i]->name << endl; } if (offer_money) { cout << "\t$" << offer_money << endl; } if (cc_offer || chance_offer) { if (cc_offer && chance_offer) { cout << "\t2 'Get out of Jail Free' Cards." << endl; } else { cout << "\t1 'Get out of Jail Free' Card≥." << endl; } } cout << "And in return, you will give up:" << endl; for (int i = 0; i < take_prop.size(); i++) { cout << "\t" << take_prop[i]->name << endl; } if (take_money) { cout << "\t$" << take_money << endl; } if (cc_take || chance_take) { if (cc_take && chance_take) { cout << "\t2 'Get out of Jail Free' Cards." << endl; } else { cout << "\t1 'Get out of Jail Free' Card." << endl; } } string input; cout << print_token(game->players[trade_index]->token) << ", would you like to accept this trade? (Yes/No)" << endl; getline(cin, input); bool invalid_input = true; while (invalid_input) { if (input == "Yes") { invalid_input = false; execute_trade(game, current_index, trade_index, take_prop, offer_prop, take_money, offer_money, cc_take, cc_offer, chance_take, chance_offer); } else if (input == "No") { invalid_input = false; cout << "Sorry, " << print_token(game->players[current_index]->token) << " the deal is off!" << endl; } else { cout << "Invalid input. Please try again:" << endl; } } } void execute_trade ( Game *game, int current_index, int trade_index, vector<Space *> take_prop, vector<Space *> offer_prop, int take_money, int offer_money, bool cc_take, bool cc_offer, bool chance_take, bool chance_offer ) { cout << "Trade went through!" << endl; for (int i = 0; i < take_prop.size(); i++) { take_prop[i]->owner = game->players[current_index]; for (int j = 0; j < 40; j++) { if (game->board.board[j] == take_prop[i]) { game->players[current_index]->ownership[j] = true; game->players[trade_index]->ownership[j] = false; } } update_monopoly(game, take_prop[i]); } for (int i = 0; i < offer_prop.size(); i++) { offer_prop[i]->owner = game->players[trade_index]; for (int j = 0; j < 40; j++) { if (game->board.board[j] == offer_prop[i]) { game->players[current_index]->ownership[j] = false; game->players[trade_index]->ownership[j] = true; } } update_monopoly(game, offer_prop[i]); } game->players[current_index]->cashOnHand += take_money; game->players[trade_index]->cashOnHand -= take_money; game->players[current_index]->cashOnHand -= offer_money; game->players[trade_index]->cashOnHand += offer_money; if (cc_offer) { game->players[current_index]->cc_jail = false; game->players[trade_index]->cc_jail = true; } if (chance_offer) { game->players[current_index]->chance_jail = false; game->players[trade_index]->chance_jail = true; } if (cc_take) { game->players[current_index]->cc_jail = true; game->players[trade_index]->cc_jail = false; } if (chance_take) { game->players[current_index]->chance_jail = true; game->players[trade_index]->chance_jail = false; } } bool check_cash_flow ( int cost, int cash ) { if (cost <= cash) { return true; } else { return false; } } void broke_player ( Game *game, int current_index ) { print_broke_opts(); bool invalid_input = true; while (invalid_input) { string input; getline(cin, input); if (input == "Trade") { invalid_input = false; trade(game, current_index); buy_property(game, current_index); } else if (input == "Mortgage Properties") { invalid_input = false; mortgage(game, current_index); buy_property(game, current_index); } else if (input == "Pass on the Property") { invalid_input = false; cout << "Player passes. Nothing happens yet!" << endl; } else { cout << "Invalid Input. Please try again." << endl; } } } void print_broke_opts() { cout << "You do not have enough money. What would you like to do?" << endl; cout << "\tTrade" << endl; cout << "\tMortgage Properties" << endl; cout << "\tPass on the Property." << endl; } void get_out_of_jail ( Game *game, int current_index, string method ) { if (method == "Doubles") { cout << print_token(game->players[current_index]->token) << " rolled doubles and was released from Jail." << endl; game->players[current_index]->free = true; } else if (method == "Card") { cout << print_token(game->players[current_index]->token) << " used a 'Get Out of Jail Free' Card." << endl; game->players[current_index]->free = true; if (game->players[current_index]->cc_jail) { game->players[current_index]->cc_jail = false; game->community_discard.push_back("Get out of Jail free. This card may be kept until needed or traded."); } else { game->players[current_index]->chance_jail = false; game->chance_discard.push_back("Get out of Jail free. This card may be kept until needed or traded."); } } else if (method == "Cash") { cout << print_token(game->players[current_index]->token) << " paid $50 and was released from Jail." << endl; game->players[current_index]->cashOnHand -= 50; game->players[current_index]->free = true; } } void in_jail ( Game *game, int current_index ) { cout << print_token(game->players[current_index]->token) << " is in jail. Options: " << endl; if (game->jail_count[current_index] < 3) { cout << "\tRoll for Doubles" << endl; } if (game->players[current_index]->cc_jail || game->players[current_index]->chance_jail) { cout << "\tUse 'Get Out of Jail Free' Card" << endl; } cout << "\tPost $50 Bail" << endl; cout << "\tTrade" << endl; cout << "\tManage Properties" << endl; cout << "\tList Accounts" << endl; cout << "\tList Properties" << endl; cout << "Please select an option: " << endl; }
[ "alec@adsbrook.com" ]
alec@adsbrook.com
69b4893f859d4859052e665aa77b9b22c130dfda
06c8a96286ed7c48bfac023daa78cdd8ebfe4a84
/Recursão:Busca-Binária/pao_a_metro.cpp
c75b6e8a000a6ebf2f467fa6ed6b81ccf6eb74ec
[]
no_license
victorhmp/OBI-Prep
e75f027b14e9c51b8e91e9ea7bd8e6dcba15c751
f354354ee16514763cc15c03344f28f46f59b61c
refs/heads/master
2021-06-03T00:04:12.596429
2020-04-11T15:05:46
2020-04-11T15:05:46
143,054,938
10
2
null
2019-08-17T12:22:21
2018-07-31T18:55:02
C++
UTF-8
C++
false
false
671
cpp
// OBI 2007 - N1 Fase 2 // Busca binária iterativa // O (n log n) #include <bits/stdc++.h> using namespace std; #define MAXN 10010 int n, k, p, sand[MAXN]; int buscab(int maxi) { int ini = 0, fim = maxi, ans = 0; while (ini <= fim) { int mid = (ini + fim) / 2; int qtd = 0; for (int i = 0; i < k; i++) { qtd += sand[i] / mid; if (qtd >= n) { ans = max(mid, ans); ini = mid + 1; } } if (qtd < n) fim = mid - 1; } return ans; } int main() { scanf("%d %d", &n, &k); for (int i = 0; i < k; i++) { scanf("%d", &sand[i]); p = max(p, sand[i]); } printf("%d\n", buscab(p)); return 0; }
[ "victor2142@gmail.com" ]
victor2142@gmail.com
5042aab719ff02c7d33779989c2ed97963cb7e03
71501709864eff17c873abbb97ffabbeba4cb5e3
/llvm8.0.0/polly/lib/Transform/FlattenSchedule.cpp
52ff0b782879283a0f0c6ad4bf91951e807676f8
[ "NCSA" ]
permissive
LEA0317/LLVM-VideoCore4
d08ba6e6f26f7893709d3285bdbd67442b3e1651
7ae2304339760685e8b5556aacc7e9eee91de05c
refs/heads/master
2022-06-22T15:15:52.112867
2022-06-09T08:45:24
2022-06-09T08:45:24
189,765,789
1
0
NOASSERTION
2019-06-01T18:31:29
2019-06-01T18:31:29
null
UTF-8
C++
false
false
3,443
cpp
//===------ FlattenSchedule.cpp --------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // Try to reduce the number of scatter dimension. Useful to make isl_union_map // schedules more understandable. This is only intended for debugging and // unittests, not for production use. // //===----------------------------------------------------------------------===// #include "polly/FlattenSchedule.h" #include "polly/FlattenAlgo.h" #include "polly/ScopInfo.h" #include "polly/ScopPass.h" #include "polly/Support/ISLOStream.h" #include "polly/Support/ISLTools.h" #define DEBUG_TYPE "polly-flatten-schedule" using namespace polly; using namespace llvm; namespace { /// Print a schedule to @p OS. /// /// Prints the schedule for each statements on a new line. void printSchedule(raw_ostream &OS, const isl::union_map &Schedule, int indent) { for (isl::map Map : Schedule.get_map_list()) OS.indent(indent) << Map << "\n"; } /// Flatten the schedule stored in an polly::Scop. class FlattenSchedule : public ScopPass { private: FlattenSchedule(const FlattenSchedule &) = delete; const FlattenSchedule &operator=(const FlattenSchedule &) = delete; std::shared_ptr<isl_ctx> IslCtx; isl::union_map OldSchedule; public: static char ID; explicit FlattenSchedule() : ScopPass(ID) {} virtual void getAnalysisUsage(AnalysisUsage &AU) const override { AU.addRequiredTransitive<ScopInfoRegionPass>(); AU.setPreservesAll(); } virtual bool runOnScop(Scop &S) override { // Keep a reference to isl_ctx to ensure that it is not freed before we free // OldSchedule. IslCtx = S.getSharedIslCtx(); LLVM_DEBUG(dbgs() << "Going to flatten old schedule:\n"); OldSchedule = S.getSchedule(); LLVM_DEBUG(printSchedule(dbgs(), OldSchedule, 2)); auto Domains = S.getDomains(); auto RestrictedOldSchedule = OldSchedule.intersect_domain(Domains); LLVM_DEBUG(dbgs() << "Old schedule with domains:\n"); LLVM_DEBUG(printSchedule(dbgs(), RestrictedOldSchedule, 2)); auto NewSchedule = flattenSchedule(RestrictedOldSchedule); LLVM_DEBUG(dbgs() << "Flattened new schedule:\n"); LLVM_DEBUG(printSchedule(dbgs(), NewSchedule, 2)); NewSchedule = NewSchedule.gist_domain(Domains); LLVM_DEBUG(dbgs() << "Gisted, flattened new schedule:\n"); LLVM_DEBUG(printSchedule(dbgs(), NewSchedule, 2)); S.setSchedule(NewSchedule); return false; } virtual void printScop(raw_ostream &OS, Scop &S) const override { OS << "Schedule before flattening {\n"; printSchedule(OS, OldSchedule, 4); OS << "}\n\n"; OS << "Schedule after flattening {\n"; printSchedule(OS, S.getSchedule(), 4); OS << "}\n"; } virtual void releaseMemory() override { OldSchedule = nullptr; IslCtx.reset(); } }; char FlattenSchedule::ID; } // anonymous namespace Pass *polly::createFlattenSchedulePass() { return new FlattenSchedule(); } INITIALIZE_PASS_BEGIN(FlattenSchedule, "polly-flatten-schedule", "Polly - Flatten schedule", false, false) INITIALIZE_PASS_END(FlattenSchedule, "polly-flatten-schedule", "Polly - Flatten schedule", false, false)
[ "kontoshi0317@gmail.com" ]
kontoshi0317@gmail.com
359a69274db316535cf535579adecf88b2b16abd
179abc8c0df1a258f73c434c0d4c32a813c0ba2b
/examples/ex2.cpp
7a468b85ed7b3498e64acb3706ee5eb2285b6900
[]
no_license
FairyDevicesRD/libmimixfe
342d00a133a595138954197d0cb389d835f74605
b463e9b5b7fc1834471f4b030b19a93381a16a1c
refs/heads/master
2021-06-08T03:38:06.365899
2020-02-02T21:58:40
2020-02-02T21:58:40
110,138,704
11
6
null
2018-10-11T23:51:10
2017-11-09T16:23:19
C++
UTF-8
C++
false
false
3,993
cpp
/* * @file ex2.cpp * @brief 固定方向同時複数音源抽出サンプル * @author Copyright (C) 2017 Fairy Devices Inc. http://www.fairydevices.jp/ * @author Masato Fujino, created on: 2017/07/14 */ #include <iostream> #include <unistd.h> #include <syslog.h> #include <string> #include <sched.h> #include <signal.h> #include <iomanip> #include <unordered_map> #include "XFERecorder.h" #include "XFETypedef.h" volatile sig_atomic_t xfe_flag_ = 0; void xfe_sig_handler_(int signum){ xfe_flag_ = 1; } class UserData { public: FILE *file1_; FILE *file2_; FILE *file3_; FILE *file4_; std::unordered_map<int, FILE*> sourceIdToFile_; }; void recorderCallback( short* buffer, size_t buflen, mimixfe::SpeechState state, int sourceId, mimixfe::StreamInfo* info, size_t infolen, void* userdata) { UserData *p = reinterpret_cast<UserData*>(userdata); std::string s = ""; if(state == mimixfe::SpeechState::SpeechStart){ s = "Speech Start"; // 発話検出の際に、この sourceId がどの方向に該当するかを確認しテーブルに記録する if(info[0].utteranceDirection_.azimuth_ == 0){ p->sourceIdToFile_[sourceId] = p->file1_; }else if(info[0].utteranceDirection_.azimuth_ == 90){ p->sourceIdToFile_[sourceId] = p->file2_; }else if(info[0].utteranceDirection_.azimuth_ == 180){ p->sourceIdToFile_[sourceId] = p->file3_; }else if(info[0].utteranceDirection_.azimuth_ == 270){ p->sourceIdToFile_[sourceId] = p->file4_; } }else if(state == mimixfe::SpeechState::InSpeech){ s = "In Speech"; }else if(state == mimixfe::SpeechState::SpeechEnd){ s = "End of Speech"; } fwrite(buffer, sizeof(short), buflen, p->sourceIdToFile_[sourceId]); // 画面表示で確認 std::cout << "State: " << s << " ( ID = " << sourceId << " )" << std::endl; for(size_t i=0;i<infolen;++i){ std::cout << info[i].milliseconds_ << "[ms] " << std::fixed << std::setprecision(3) << info[i].rmsDbfs_ << "[dbFS] " << info[i].speechProbability_*100.0F << "[%] "; std::cout << sourceId << " ( " << info[i].numSoundSources_ << "/" << info[i].totalNumSoundSources_ << " )"; std::cout << " angle=" << info[i].direction_.angle_ << ", azimuth=" << info[i].direction_.azimuth_ << ", peak=" << info[i].spatialSpectralPeak_ << " ( matchedDir: azimuth = " << info[i].utteranceDirection_.azimuth_ << ", angle = " << info[i].utteranceDirection_.angle_ << std::endl; } } int main(int argc, char** argv) { if(signal(SIGINT, xfe_sig_handler_) == SIG_ERR){ return 1; } using namespace mimixfe; XFESourceConfig s; XFEECConfig e; XFEVADConfig v; XFEBeamformerConfig b; XFEStaticLocalizerConfig c({Direction(0, 90), Direction(90,90), Direction(180,90), Direction(270,90)}); XFEOutputConfig o; c.maxSimultaneousSpeakers_ = 2; UserData data; data.file1_ = fopen("/tmp/ex2_000.raw","w"); data.file2_ = fopen("/tmp/ex2_090.raw","w"); data.file3_ = fopen("/tmp/ex2_180.raw","w"); data.file4_ = fopen("/tmp/ex2_270.raw","w"); int return_status = 0; try{ XFERecorder rec(s,e,v,b,c,o,recorderCallback,reinterpret_cast<void*>(&data)); rec.setLogLevel(LOG_UPTO(LOG_DEBUG)); // デバッグレベルのログから出力する rec.start(); int countup = 0; int timeout = 120; while(rec.isActive()){ std::cout << countup++ << " / " << timeout << std::endl; if(countup == timeout){ rec.stop(); break; } if(xfe_flag_ == 1){ rec.stop(); break; } sleep(1); } return_status = rec.stop(); }catch(const XFERecorderError& e){ std::cerr << "XFE Recorder Exception: " << e.what() << "(" << e.errorno() << ")" << std::endl; }catch(const std::exception& e){ std::cerr << "Exception: " << e.what() << std::endl; } fclose(data.file1_); fclose(data.file2_); fclose(data.file3_); fclose(data.file4_); if(return_status != 0){ std::cerr << "Abort by error code = " << return_status << std::endl; }else{ std::cout << "Normally finished" << std::endl; } return return_status; }
[ "fujino@fairydevices.jp" ]
fujino@fairydevices.jp
249063331894094094f8c922a573f630b6e768c8
a9073f20deffa22b5eaba6916cf67fddb6412482
/ocv/cpp/5point/main.cpp
d679ceb355f0a0f8e20da2038a4883fc28d70edb
[ "BSD-2-Clause" ]
permissive
zhaowei11594/scripts
6e680afcb2fe41e544104af3957bf248c080d5da
70a5edd4c50f780b89ba2238caae79999a406429
refs/heads/master
2021-01-20T13:43:03.022966
2017-05-07T07:46:39
2017-05-07T07:46:39
90,516,713
0
0
null
2017-05-07T07:41:53
2017-05-07T07:41:53
null
UTF-8
C++
false
false
2,011
cpp
/* This my own implementation of the 5 point algorithm from the paper H. Li and R. Hartley, "Five-point motion estimation made easy", icpr, 2006 I do not use anything from their GPL code. */ #include <vector> #include <iostream> #include <assert.h> #include <opencv2/core/core.hpp> #include "5point.h" using namespace std; int main() { // x,y pairing double pts1[] = {0.4964 ,1.0577, 0.3650, -0.0919, -0.5412, 0.0159, -0.5239, 0.9467, 0.3467, 0.5301, 0.2797, 0.0012, -0.1986, 0.0460, -0.1622, 0.5347, 0.0796, 0.2379, -0.3946, 0.7969}; double pts2[] = {0.7570, 2.7340, 0.3961, 0.6981, -0.6014, 0.7110, -0.7385, 2.2712, 0.4177, 1.2132, 0.3052, 0.4835, -0.2171, 0.5057, -0.2059, 1.1583, 0.0946, 0.7013, -0.6236, 3.0253}; int num_pts = 5; //10; cv::Mat E; // essential matrix cv::Mat P; // 3x4 projection matrix int inliers; bool ret; // Do some timing test double start = cv::getTickCount(); for(int i=0; i < 1000; i++) { ret = Solve5PointEssential(pts1, pts2, num_pts, E, P, inliers); } double end = cv::getTickCount(); double elapse = (end - start)/cv::getTickFrequency(); double avg_time_us = (elapse/1000)*1000000; cout << "Average execution time: " << avg_time_us << " us" << endl; cout << endl; if(ret) { cout << "Success!" << endl; cout << endl; cout << "E = " << E << endl; cout << endl; cout << "P = " << P << endl; cout << endl; cout << "inliers = " << inliers << "/" << num_pts << endl; } else { cout << "Could not find a valid essential matrix" << endl; } return 0; }
[ "ra22341@ya.ru" ]
ra22341@ya.ru
064b9df2cabedd77baace8452fe5c46cd698659c
a93a4d591e55057f2d92287779a04fd38c4ac0fa
/src/Components/RenderHandler.cpp
fd75441c917fe40882cff6b3b3e0964cf824186f
[]
no_license
CURVATJB/Shooter2D_SFML
409c9d0801e900d7decbb0e0cbc7809fa288bec8
b81607ca3a30796b7b153be5cbbc300613b263ea
refs/heads/master
2023-04-29T04:33:53.884165
2021-05-24T12:26:56
2021-05-24T12:26:56
370,343,038
1
0
null
null
null
null
UTF-8
C++
false
false
3,879
cpp
#include "Components/RenderHandler.h" #include <SFML/Graphics/RenderWindow.hpp> #include "GameWindow.h" #include "Managers/FontManager.h" RenderHandler::RenderHandler(GameObject* parentGameObject, sf::Texture* tex, std::string key, int zIndex, bool isMovable,sf::Vector2f origin,float scale) : m_owner(parentGameObject) { AddSprite(tex, key, zIndex, isMovable,origin,scale); GameWindow::GetGameLevel()->AddObjectRendered(*this); } RenderHandler::RenderHandler(GameObject* parentGameObject, std::string userText, std::string key, int zIndex, sf::Vector2f pos, sf::Color color, int size) : m_owner(parentGameObject) { AddText(userText, key, zIndex, pos, color, size); GameWindow::GetGameLevel()->AddObjectRendered(*this); } RenderHandler::~RenderHandler() { for (auto element : m_renderedItems) { delete element; element = nullptr; } } void RenderHandler::Initialise(sf::Texture* tex, std::string key, int zIndex, bool isMovable,sf::Vector2f origin,float scale) { AddSprite(tex, key, zIndex, isMovable,origin,scale); GameWindow::GetGameLevel()->AddObjectRendered(*this); } void RenderHandler::Initialise(std::string userText, std::string key, int zIndex, sf::Vector2f pos, sf::Color color, int size) { AddText(userText, key, zIndex, pos, color, size); GameWindow::GetGameLevel()->AddObjectRendered(*this); } void RenderHandler::Reset() { for (auto* container : m_renderedItems) { delete container; } m_renderedItems.clear(); m_MovableSprites.clear(); GameWindow::GetGameLevel()->RemoveObjectRendered(*m_owner); } sf::Sprite* RenderHandler::AddSprite(sf::Texture* tex, std::string key, int zIndex, bool isMovable,sf::Vector2f origin,float scale) { auto* sprite = new sf::Sprite(*tex); auto* customSprite = new CustomContainer(std::move(key), zIndex, sprite); sprite->setOrigin(origin); sprite->setScale(sf::Vector2f(scale,scale)); m_renderedItems.push_back(customSprite); // Sort using comparator function std::sort(m_renderedItems.begin(), m_renderedItems.end(), Comparator); if (isMovable) { m_MovableSprites.push_back(sprite); } return sprite; } sf::Text* RenderHandler::AddText(std::string userText, std::string key, int zIndex, sf::Vector2f pos, sf::Color color, int size) { // Create a text sf::Text* text = new sf::Text(userText, *FontManager::GetFontPtr(FontManager::EnumFonts::Mandalorian)); text->setCharacterSize(size); text->setFillColor(color); text->setPosition(pos); auto* customText = new CustomContainer(std::move(key), zIndex, text); m_renderedItems.push_back(customText); std::sort(m_renderedItems.begin(), m_renderedItems.end(), Comparator); return text; } void RenderHandler::RenderUpdate() { //Utilisé pour le debug de collision, permet d'afficher les collisions des objets // if (m_owner->GetCollisionHandler()) // { // auto radius = m_owner->GetCollisionHandler()->m_radius; // sf::CircleShape circle(radius); // circle.setPosition(sf::Vector2f(m_owner->m_position.x - radius,m_owner->m_position.y - radius)); // circle.setFillColor(sf::Color::Green); // GameWindow::m_window->draw(circle); // // // // std::vector<sf::Vector2f> tmp; // m_owner->GetCollisionHandler()->GetPoints(tmp); // // sf::Vertex vertice[4] = // { // tmp[0], // tmp[1], // tmp[2], // tmp[3] // }; // // GameWindow::m_window->draw(vertice, 4, sf::Quads); // // sf::CircleShape center(3); // center.setPosition(sf::Vector2f(m_owner->m_position.x,m_owner->m_position.y)); // center.setFillColor(sf::Color::Magenta); // GameWindow::m_window->draw(center); // } for (auto* sprite : m_MovableSprites) { sprite->setRotation(m_owner->m_rotation); sprite->setPosition(m_owner->m_position); } for (auto* rendered : m_renderedItems) { GameWindow::m_window->draw(*rendered->m_drawableItem); } }
[ "jb.curvat@gmail.com" ]
jb.curvat@gmail.com
24f99f13a07e907f2730176efa338425b8921980
62e90bcf604cb1270897cb7516362c230c5af2b4
/src/data-structure/MaterialsEnumeration.hpp
9499074c23f24fc75748d86e281aaa02e368bf0b
[ "CC-BY-4.0" ]
permissive
inexorgame-obsolete/cube2-map-importer
076d49c8692ed5eb040d28a92b990a40240fb7ab
ad81b347e4adfcf176257fdd83d6f6163c9eb30f
refs/heads/master
2022-03-16T20:38:32.813558
2019-12-08T16:34:22
2019-12-08T16:34:22
224,916,255
2
1
null
null
null
null
UTF-8
C++
false
false
1,155
hpp
#pragma once namespace inexor { namespace cube2_map_importer { // Hardcoded texture numbers. enum { DEFAULT_SKY = 0, DEFAULT_GEOM }; // enum { MATF_INDEX_SHIFT = 0, MATF_VOLUME_SHIFT = 2, MATF_CLIP_SHIFT = 5, MATF_FLAG_SHIFT = 8, MATF_INDEX = 3 << MATF_INDEX_SHIFT, MATF_VOLUME = 7 << MATF_VOLUME_SHIFT, MATF_CLIP = 7 << MATF_CLIP_SHIFT, MATF_FLAGS = 0xFF << MATF_FLAG_SHIFT }; // Cube empty-space materials. enum { MAT_AIR = 0, // the default, fill the empty space with air MAT_WATER = 1 << MATF_VOLUME_SHIFT, // fill with water, showing waves at the surface MAT_LAVA = 2 << MATF_VOLUME_SHIFT, // fill with lava MAT_GLASS = 3 << MATF_VOLUME_SHIFT, // behaves like clip but is blended blueish MAT_NOCLIP = 1 << MATF_CLIP_SHIFT, // collisions always treat cube as empty MAT_CLIP = 2 << MATF_CLIP_SHIFT, // collisions always treat cube as solid MAT_GAMECLIP = 3 << MATF_CLIP_SHIFT, // game specific clip material MAT_DEATH = 1 << MATF_FLAG_SHIFT, // force player suicide MAT_ALPHA = 4 << MATF_FLAG_SHIFT // alpha blended }; }; };
[ "IAmNotHanni@users.noreply.github.com" ]
IAmNotHanni@users.noreply.github.com
c4e809b8c3c439ab999e8f25d33ab6ab537f6870
d9e96244515264268d6078650fa707f34d94ee7a
/Utility/StringUtils.cpp
9b5d5ab88c698475af5dc7d7443dbda1c89d875f
[ "MIT" ]
permissive
xlgames-inc/XLE
45c89537c10561e216367a2e3bcd7d1c92b1b039
69cc4f2aa4faf12ed15bb4291c6992c83597899c
refs/heads/master
2022-06-29T17:16:11.491925
2022-05-04T00:29:28
2022-05-04T00:29:28
29,281,799
396
102
null
2016-01-04T13:35:59
2015-01-15T05:07:55
C++
UTF-8
C++
false
false
46,134
cpp
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #define _SCL_SECURE_NO_WARNINGS #include "StringUtils.h" #include "MemoryUtils.h" #include "PtrUtils.h" // for AsPointer #include <string.h> #include <wchar.h> #include <locale> #include <assert.h> #include <errno.h> #include <math.h> #include <stdlib.h> #if OS_OSX #include <xlocale.h> #endif #if CLIBRARIES_ACTIVE == CLIBRARIES_MSVC #include <strsafe.h> #include <mbstring.h> #endif namespace Utility { static const uint8 __alphanum_table[] = { 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03, 0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x00,0x00,0x00,0x00,0x00, 0x00,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02, 0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, }; static const uint8 __hex_table[] = { 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, }; static const uint8 __lower_table[] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x5B,0x5C,0x5D,0x5E,0x5F, 0x60,0x61,0x62,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6A,0x6B,0x6C,0x6D,0x6E,0x6F, 0x70,0x71,0x72,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7A,0x7B,0x7C,0x7D,0x7E,0x7F, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF, }; static const uint8 __upper_table[] = { 0x00,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,0x0F, 0x10,0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F, 0x20,0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F, 0x30,0x31,0x32,0x33,0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,0x3C,0x3D,0x3E,0x3F, 0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x5B,0x5C,0x5D,0x5E,0x5F, 0x60,0x41,0x42,0x43,0x44,0x45,0x46,0x47,0x48,0x49,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F, 0x50,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5A,0x7B,0x7C,0x7D,0x7E,0x7F, 0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x8E,0x8F, 0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9D,0x9E,0x9F, 0xA0,0xA1,0xA2,0xA3,0xA4,0xA5,0xA6,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF, 0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB7,0xB8,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xBF, 0xC0,0xC1,0xC2,0xC3,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCB,0xCC,0xCD,0xCE,0xCF, 0xD0,0xD1,0xD2,0xD3,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDB,0xDC,0xDD,0xDE,0xDF, 0xE0,0xE1,0xE2,0xE3,0xE4,0xE5,0xE6,0xE7,0xE8,0xE9,0xEA,0xEB,0xEC,0xED,0xEE,0xEF, 0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF6,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFD,0xFE,0xFF, }; namespace { static Locale::Enum gLocale = Locale::KO; static const char* localeStr[Locale::Max] = { "ko", "zh_cn", "en_us", "ja", "zh_tw", "ru", "de", "fr" }; static const char* localeLanguage[Locale::Max] = { "korean", "chinese-simplified", "english", "japanese", "chinese-simplified", "russian", "german", "french" }; } void XlInitStringUtil(const char locale[]) { for (size_t i = 0; i < Locale::Max; ++i) { if (XlEqStringI(locale, localeStr[i])) { gLocale = (Locale::Enum)i; setlocale(LC_CTYPE, localeLanguage[i]); break; } } } Locale::Enum XlGetLocale() { return gLocale; } const char* XlGetLocaleString(Locale::Enum locale) { if (locale < Locale::KO || locale >= Locale::Max) { return localeStr[Locale::KO]; } return localeStr[locale]; } size_t XlStringSize(const char* str) { return strlen(str); } size_t XlStringSizeSafe(const char* str, const char* end) { const char* p; for (p = str; p < end && *p; ++p) continue; return p - str; } size_t XlStringSize(const ucs4* str) { return XlStringLen(str); } size_t XlStringSizeSafe(const ucs4* str, const ucs4* end) { const ucs4* p; for (p = str; p < end && *p; ++p) continue; return p - str; } inline bool IsUtfMultibyte(uint8 c) { return ((c & 0xc0) == 0x80); } inline bool CheckUtfMultibytes(size_t count, const char* s) { while (count && IsUtfMultibyte((uint8)*s)) { ++s; --count; } return (count == 0); } size_t XlStringLen(const char* s) { size_t l = 0; while (uint8 c = (uint8)*s) { int seq = XlCountUtfSequence(c); if (seq == 0) { break; } if (CheckUtfMultibytes(seq - 1, s + 1)) { ++l; s += seq; } else { break; } } return l; } size_t XlStringLen(const utf8* s) { return XlStringLen((const char*)s); } size_t XlStringSize(const utf8* s) { return XlStringSize((const char*)s); } size_t XlStringLen(const ucs4* str) { // TODO: enhance if (!str) return 0; const ucs4* e = str; while (*e++) ; return e - str - 1; } // count is buffer size in char void XlCopyString(char* dst, size_t count, const char* src) { #ifdef _MSC_VER StringCbCopyA(dst, count, src); #elif OSX strncpy(dst, src, count); dst[count - 1] = 0; #else if (!count) return; while (--count && (*dst++ = *src++)) ; *dst = 0; #endif } // count is buffer size in char void XlCopyNString(char* dst, size_t count, const char* src, size_t length) { if (!length) { if (count >= 1) dst[0] = '\0'; return; } ++length; if (length > count) { length = count; } XlCopyString(dst, length, src); } #pragma warning(disable:4706) // warning C4706: assignment within conditional expression void XlCopySafeUtf(char* dst, size_t size, const char* src) { if (!size) return; --size; // reserve null uint8 c; while ((c = (uint8)*src)) { int seq = XlCountUtfSequence(c); if (seq == 0) { break; } if (!CheckUtfMultibytes(seq - 1, src + 1)) { break; } size -= seq; if (size < 0) { break; } XlCopyMemory(dst, src, seq); dst += seq; src += seq; } *dst = 0; } void XlCopySafeUtfN(char* dst, size_t size, const char* src, const uint32 numSeq) { if (!size) return; --size; // reserve null uint8 c; uint32 n = 0; while ((c = (uint8)*src)) { if (n >= numSeq) { break; } int seq = XlCountUtfSequence(c); if (seq == 0) { break; } if (!CheckUtfMultibytes(seq - 1, src + 1)) { break; } size -= seq; if (size < 0) { break; } XlCopyMemory(dst, src, seq); dst += seq; src += seq; ++n; } *dst = 0; } void XlCopyString (utf8* dst, size_t size, const utf8* src) { XlCopyString((char*)dst, size, (const char*)src); } void XlCopyNString (utf8* dst, size_t count, const utf8*src, size_t length) { XlCopyNString((char*)dst, count, (const char*)src, length); } int XlCompareString (const utf8* x, const utf8* y) { return XlCompareString((const char*)x, (const char*)y); } int XlCompareStringI (const utf8* x, const utf8* y) { return XlCompareStringI((const char*)x, (const char*)y); } int XlComparePrefix (const utf8* x, const utf8* y, size_t size) { return XlComparePrefix((const char*)x, (const char*)y, size); } int XlComparePrefixI (const utf8* x, const utf8* y, size_t size) { return XlComparePrefixI((const char*)x, (const char*)y, size); } #if CLIBRARIES_ACTIVE == CLIBRARIES_MSVC #pragma warning(disable: 4995) void XlCopyString(wchar_t* dst, size_t size, const wchar_t* src) { wcscpy_s((wchar_t*)dst, size, (const wchar_t*)src); } void XlCopyNString(wchar_t* dst, size_t count, const wchar_t*src, size_t length) { wcsncpy_s((wchar_t*)dst, count, (const wchar_t*)src, length); } void XlCopyString(ucs2* dst, size_t count, const ucs2* src) { wcscpy_s((wchar_t*)dst, count, (const wchar_t*)src); } void XlCopyNString(ucs2* dst, size_t count, const ucs2*src, size_t length) { wcsncpy_s((wchar_t*)dst, count, (const wchar_t*)src, length); } void XlCatString(ucs2* dst, size_t size, const ucs2* src) { wcscat_s((wchar_t*)dst, size, (const wchar_t*)src); } void XlCatNString(ucs2* dst, size_t size, const ucs2* src, size_t length) { wcsncat_s((wchar_t*)dst, size, (const wchar_t*)src, length); } size_t XlStringSize(const ucs2* str) { return wcslen((const wchar_t*)str); } size_t XlStringLen(const ucs2* str) { return wcslen((const wchar_t*)str); } size_t XlCompareString(const ucs2* x, const ucs2* y) { return wcscmp((const wchar_t*)x, (const wchar_t*)y); } size_t XlCompareStringI(const ucs2* x, const ucs2* y) { return _wcsicmp((const wchar_t*)x, (const wchar_t*)y); } #endif // count is buffer size in ucs4 void XlCopyString(ucs4* dst, size_t count, const ucs4* src) { if (!count) return; if (!src) { *dst = 0; return; } while (--count && (*dst++ = *src++)) ; *dst = 0; } void XlCopyNString(ucs4* dst, size_t count, const ucs4*src, size_t length) { ++length; if (length > count) { length = count; } XlCopyString(dst, length, src); } void XlCatString(char* dst, size_t size, const char* src) { #ifdef _MSC_VER StringCbCatA(dst, size, src); #else for (size_t i = 0; i < size - 1; ++i) { if (dst[i] == 0) { for (; i < size - 1; ++i) { dst[i] = *src; if (*src == 0) return; src++; } break; } } dst[size - 1] = 0; #endif } void XlCatNString(char* dst, size_t size, const char* src, size_t length) { for (size_t i = 0; i < size - 1; ++i) { if (dst[i] == 0) { size_t c=0; for (; (i < size - 1); ++i, ++c) { if (c >= length) { dst[i] = '\0'; return; } dst[i] = *src; if (*src == 0) return; src++; } break; } } dst[size - 1] = 0; } void XlCatSafeUtf(char* dst, size_t size, const char* src) { for (size_t i = 0; i < size - 1; ++i) { if (dst[i] == 0) { XlCopySafeUtf(dst + i, size - i, src); break; } } } void XlCombineString(char dst[], size_t size, const char zero[], const char one[]) { if (!size) return; auto* dstEnd = &dst[size-1]; while (*zero && dst < dstEnd) { *dst = *zero; ++dst; ++zero; } while (*one && dst < dstEnd) { *dst = *one; ++dst; ++one; } assert(dst <= dstEnd); // it's ok to equal dstEnd here *dst = '\0'; } void XlCatString(ucs4* dst, size_t count, const ucs4* src) { for (size_t i = 0; i < count - 1; ++i) { if (dst[i] == 0) { for (; i < count - 1; ++i) { dst[i] = *src; if (*src == 0) return; src++; } break; } } dst[count - 1] = 0; } void XlCatString(char* dst, size_t size, char src) { for (size_t i = 0; i < size - 1; ++i) { if (dst[i] == 0) { dst[i] = src; dst[i+1] = 0; return; } } } void XlCatString(ucs2* dst, size_t size, ucs2 src) { for (size_t i = 0; i < size - 1; ++i) { if (dst[i] == 0) { dst[i] = src; dst[i+1] = 0; return; } } } void XlCatString(ucs4* dst, size_t count, ucs4 src) { for (size_t i = 0; i < count - 1; ++i) { if (dst[i] == 0) { dst[i] = src; dst[i+1] = 0; return; } } } int XlComparePrefix(const char* s1, const char* s2, size_t size) { return strncmp(s1, s2, size); } int XlComparePrefixI(const char* s1, const char* s2, size_t size) { #if CLIBRARIES_ACTIVE == CLIBRARIES_MSVC return _strnicmp(s1, s2, size); #else return strncasecmp(s1, s2, size); #endif } int XlComparePrefix(const ucs2* x, const ucs2* y, size_t len) { if (!len) return 0; while (--len && *x && *x == *y) { ++x; ++y; } return (int)(*x - *y); } int XlComparePrefixI(const ucs2* x, const ucs2* y, size_t len) { if (!len) return 0; while (--len && *x && XlToLower(*x) == XlToLower(*y)) { ++x; ++y; } return (int)(XlToLower(*x) - XlToLower(*y)); } int XlComparePrefix(const ucs4* x, const ucs4* y, size_t len) { if (!len) return 0; while (--len && *x && *x == *y) { ++x; ++y; } return (int)(*x - *y); } int XlComparePrefixI(const ucs4* x, const ucs4* y, size_t len) { if (!len) return 0; while (--len && *x && XlToLower(*x) == XlToLower(*y)) { ++x; ++y; } return (int)(XlToLower(*x) - XlToLower(*y)); } uint32 XlHashString(const char* x) { // case sensitive string hash const char* s = x; uint32 hash = 0; while (char c = *s++) { hash = (hash * 31) + c; } return hash; } uint32 XlHashString(const ucs4* x) { // case sensitive string hash const ucs4* s = x; uint32 hash = 0; while (ucs4 c = *s++) { hash = (hash * 31) + c; } return hash; } int XlCompareString(const char* x, const char* y) { return strcmp(x, y); } int XlCompareStringI(const char* x, const char* y) { #if CLIBRARIES_ACTIVE == CLIBRARIES_MSVC return _stricmp(x, y); #else return strcasecmp(x, y); #endif } int XlCompareString(const ucs4* x, const ucs4* y) { while (*x && *x == *y) { ++x; ++y; } return (int)(*x - *y); } int XlCompareStringI(const ucs4* x, const ucs4* y) { while (*x && XlToLower(*x) == XlToLower(*y)) { ++x; ++y; } return (int)(XlToLower(*x) - XlToLower(*y)); } const char* XlFindChar(const char* s, const char ch) { return strchr(s, ch); } char* XlFindChar(char* s, const char ch) { return strchr(s, ch); } const char* XlFindAnyChar(const char s[], const char delims[]) { for (const char* i = s; *i; ++i) { for (const char *d = delims; *d; ++d) { if (*i == *d) return i; } } return nullptr; } char* XlFindAnyChar(char s[], const char delims[]) { for (char* i = s; *i; ++i) { for (const char *d = delims; *d; ++d) { if (*i == *d) return i; } } return nullptr; } const char* XlFindNot(const char s[], const char delims[]) { for (const char* i = s; *i; ++i) { const char *d = delims; for (; *d; ++d) { if (*i == *d) break; } if (*d == '\0') return i; } return nullptr; } char* XlFindNot(char s[], const char delims[]) { for (char* i = s; *i; ++i) { const char *d = delims; for (; *d; ++d) { if (*i == *d) break; } if (*d == '\0') return i; } return nullptr; } const char* XlFindCharReverse(const char* s, char ch) { return strrchr(s, ch); } const char* XlFindString(const char* s, const char* x) { return strstr(s, x); } char* XlFindString(char* s, const char* x) { return strstr(s, x); } const char* XlFindStringI(const char* s, const char* x) { size_t sb = XlStringSize(s); size_t xb = XlStringSize(x); if (sb < xb) return 0; for (size_t i = 0; i <= sb - xb; ++i) { if (XlComparePrefixI(s + i, x, xb) == 0) { return s + i; } } return 0; } const char* XlFindStringSafe(const char* s, const char* x, size_t size) { size_t xb = XlStringSize(x); for (size_t i = 0; s[i] && i < size - xb; ++i) { if (XlComparePrefixI(s + i, x, xb) == 0) { return s + i; } } return 0; } const ucs4* XlFindString(const ucs4* s, const ucs4* x) { if (!*x) return s; const ucs4 *cs, *cx; while (*s) { cs = s; cx = x; while (*cs && *cx && !(*cs - *cx)) { cs++; cx++; } if (!*cx) return s; ++s; } return 0; } const ucs4* XlFindStringI(const ucs4* s, const ucs4* x) { if (!*x) return s; size_t sn = XlStringLen(s); size_t xn = XlStringLen(x); if (sn < xn) return 0; for (size_t i = 0; i <= sn - xn; ++i) { if (XlComparePrefixI(s + i, x, xn) == 0) { return s + i; } } return 0; } const ucs4* XlFindStringSafe(const ucs4* s, const ucs4* x, size_t len) { if (!*x) return s; size_t xn = XlStringLen(x); for (size_t i = 0; s[i] && i < len - xn; ++i) { if (XlComparePrefixI(s + i, x, xn) == 0) { return s + i; } } return 0; } template <class T> size_t tokenize_string(T* buf, size_t count, const T* delimiters, T** tokens, size_t numMaxToken) { assert(numMaxToken > 1); size_t numDelimeters = XlStringLen(delimiters); size_t numToken = 0; tokens[numToken++] = buf; for (size_t i = 0; i < count; ++i) { if (buf[i] == '\0') { break; } for (size_t j = 0; j < numDelimeters; ++j) { if (buf[i] == delimiters[j]) { buf[i] = '\0'; tokens[numToken++] = &buf[i + 1]; if (numToken == numMaxToken) { return numToken; } } } } return numToken; } size_t XlTokenizeString(char* buf, size_t count, const char* delimiters, char** tokens, size_t numMaxToken) { return tokenize_string<char>(buf, count, delimiters, tokens, numMaxToken); } size_t XlTokenizeString(ucs2* buf, size_t count, const ucs2* delimiters, ucs2** tokens, size_t numMaxToken) { return tokenize_string<ucs2>(buf, count, delimiters, tokens, numMaxToken); } char* XlStrTok(char* token, const char* delimit, char** context) { #if CLIBRARIES_ACTIVE == CLIBRARIES_MSVC return strtok_s(token, delimit, context); #else return strtok_r(token, delimit, context); #endif } int XlExtractInt(const char* buf, int* arr, size_t length) { assert(length > 1); size_t index = 0; const char* s = buf; while (*s && index < length) { bool hasDigit = false; int negative = 1; int result = 0; if (*s == '-') { negative = -1; ++s; } while (XlIsDigit(*s)) { result = (result * 10) + (*s - '0'); ++s; hasDigit = true; } if (hasDigit) { arr[index++] = negative * result; } else { ++s; } } return int(index); } template<typename CharType> StringSection<CharType>::StringSection(const std::basic_string<CharType>& str) : _start(AsPointer(str.cbegin())), _end(AsPointer(str.cend())) {} template class StringSection<char>; template class StringSection<utf8>; template class StringSection<ucs2>; template class StringSection<ucs4>; bool XlSafeAtoi(const char* str, int* n) { errno = 0; #if CLIBRARIES_ACTIVE == CLIBRARIES_MSVC *n = atoi(str); if (*n == MAX_INT32 || *n == MIN_INT32) { if (errno == ERANGE) { return false; } } #else char* end = const_cast<char*>(XlStringEnd(str)); long result = strtol(str, &end, 10); // GCC atoi doesn't handle ERANGE as expected... But! Sometimes strtol returns a 64 bit number, not a 32 bit number... trouble...? if (result == LONG_MAX || result == LONG_MIN) { if (errno == ERANGE) { return false; } } if (result > MAX_INT32 || result < MIN_INT32) { return false; } if (!end || *end != '\0') { return false; } *n = int(result); #endif if ((*n) == 0 && errno != 0) { return false; } return true; } bool XlSafeAtoi64(const char* str, int64* n) { errno = 0; #if CLIBRARIES_ACTIVE == CLIBRARIES_MSVC *n = _atoi64(str); #else char* end = const_cast<char*>(XlStringEnd(str)); *n = strtoll(str, &end, 10); #endif if (*n == MAX_INT64 || *n == MIN_INT64) { if (errno == ERANGE) { return false; } } if (*n == 0 && errno != 0) { return false; } return true; } const char* XlReplaceString(char* dst, size_t size, const char* src, const char* strOld, const char* strNew) { assert(size > 0); size_t strOldLen = XlStringSize(strOld); size_t strNewLen = XlStringSize(strNew); size_t count = 0; size_t remain = 0; const char* p = src; while (const char* find = XlFindString(p, strOld)) { ptrdiff_t copySize = find - p; if (copySize > 0) { remain = size - count; XlCopyNString(&dst[count], remain, p, copySize); if (copySize >= ptrdiff_t(remain)) { return dst; } count += copySize; } p = find + strOldLen; remain = size - count; XlCopyNString(&dst[count], remain, strNew, strNewLen); if (strNewLen >= remain) { return dst; } count += strNewLen; } if (count) { XlCopyNString(&dst[count], size - count, p, XlStringSize(p)); } else { XlCopyString(dst, size, src); } return dst; } // count is buffer size of dst, not the string size XL_UTILITY_API void XlCompactString(char* dst, size_t count, const char* src) { if (!count) return; if (!src) { *dst = 0; return; } char ch; while ( --count && (ch = *src++)) { if (!XlIsSpace(ch)) { *dst++ = ch; } } *dst = 0; } void XlCompactString(ucs4* dst, size_t count, const ucs4* src) { if (!count) return; if (!src) { *dst = 0; return; } ucs4 ch; while ( --count && (ch = *src++)) { if (!XlIsSpace(ch)) { *dst++ = ch; } } *dst = 0; } bool XlIsValidAscii(const char* str) { while (uint8 c = (uint8)*str++) { if (c >= 0x80) return false; } return true; } bool XlIsValidUtf8(const utf8* str, size_t count) { const auto* s = str; if (XlHasUtf8Bom(s)) s += 3; uint32 c; while ((count == size_t(-1) || size_t(s - str) < count) && (c = (uint8)*s++) != 0) { if (c < 0x80) { } else if (c == 0xc0 || c == 0xc1 || (c >= 0xf5 && c <= 0xff)) { return false; } else if (c < 0xe0) { if ((*s++ & 0xc0) != 0x80) return false; } else if (c < 0xf0) { if ((*s++ & 0xc0) != 0x80) return false; if ((*s++ & 0xc0) != 0x80) return false; } else { if ((*s++ & 0xc0) != 0x80) return false; if ((*s++ & 0xc0) != 0x80) return false; if ((*s++ & 0xc0) != 0x80) return false; } } return true; } bool XlHasUtf8Bom(const utf8* str) { return (uint8)str[0] == 0xef && (uint8)str[1] == 0xbb && (uint8)str[2] == 0xbf; } size_t XlGetOffset(const char* s, size_t index) { size_t l = 0; for (size_t i = 0; i < index; ++i) { uint32 c = (uint8)s[l]; if (!c) break; if (c < 0x80) { l += 1; } else if (c < 0xe0) { l += 2; } else if (c < 0xf0) { l += 3; } else if (c < 0xf8) { l += 4; //} else if (c < 0xfc) { // l += 5; //} else if (c < 0xfe) { // l += 6; } else { // 2009-02-25 umean, temporary disabled //assert(0); break; } } return l; } ucs4 XlGetChar(const char* str, size_t* size) { const uint8* s = (const uint8*)str; ucs4 c = 0; if (*s < 0x80) { c = *s; *size = 1; } else if (*s < 0xe0) { c = ((*s & 0x1f) << 6) | (*(s+1) & 0x3f); *size = 2; } else if (*s < 0xf0) { c = ((*s & 0x0f) << 12) | ((*(s+1) & 0x3f) << 6) | (*(s+2) & 0x3f); *size = 3; } else if (*s < 0xf8) { c = ((*s & 0x0f) << 18) | ((*(s+1) & 0x3f) << 12) | ((*(s+2) & 0x3f) << 6) | (*(s+3) & 0x3f); *size = 4; //} else if (*s < 0xfc) { // c = ((*s & 0x0f) << 24) | ((*(s+1) & 0x3f) << 18) | ((*(s+2) & 0x3f) << 12) | ((*(s+3) & 0x3f) << 6) | (*(s+4) & 0x3f); // *size = 5; //} else if (*s < 0xfe) { // c = ((*s & 0x0f) << 28) | ((*(s+1) & 0x3f) << 24) | ((*(s+2) & 0x3f) << 18) | ((*(s+3) & 0x3f) << 12) | ((*(s+4) & 0x3f) << 6) | (*(s+5) & 0x3f); // *size = 6; } else { assert(0); c = 0; *size = 0; } return c; } void XlGetChar(char* output, size_t count, const ucs4* uniStr, size_t* size) { const ucs4 uniChar = *uniStr; if (count < sizeof(ucs4)) { *size = 0; return; } if (uniChar < 0x80) { *output = (char)uniChar; } else if (uniChar < 0x800) { *output++ = 0xc0 | ((uniChar >> 6) & 0x1f); *output = 0x80 | (uniChar & 0x3f); } else if (uniChar < 0x10000) { *output++ = 0xe0 | ((uniChar >> 12) & 0x0f); *output++ = 0x80 | ((uniChar >> 6) & 0x3f); *output = 0x80 | (uniChar & 0x3f); } else if (uniChar < 0x110000) { *output++ = 0xf0 | ((uniChar >> 18) & 0x07); *output++ = 0x80 | ((uniChar >> 12) & 0x3f); *output++ = 0x80 | ((uniChar >> 6) & 0x3f); *output = 0x80 | (uniChar & 0x3f); } } // casing (null terminated string) const char* XlLowerCase(char* str) { char* c = str; while (*c) { *c = XlToLower(*c); ++c; } return str; } const ucs4* XlLowerCase(ucs4* str) { ucs4* c = str; while (*c) { *c = XlToLower(*c); ++c; } return str; } const char* XlUpperCase(char* str) { char* c = str; while (*c) { *c = XlToUpper(*c); ++c; } return str; } const ucs4* XlUpperCase(ucs4* str) { ucs4* c = str; while (*c) { *c = XlToUpper(*c); ++c; } return str; } size_t XlDecodeUrl(char* dst, size_t count, const char* encoded) { const char* s = encoded; char* d = dst; while (*s) { if (size_t(d - dst) >= size_t(count - 1)) { return size_t(-1); } if (*s == '+') { *d = ' '; ++d; ++s; } else if (*s == '%') { ++s; if (!*s || !*(s + 1)) { return size_t(-1); } if (*s >= '0' && *s <= '9') { *d = (*s - '0') << 4; } else if (*s >= 'A' && *s <= 'F') { *d = (*s - 'A' + 10) << 4; } else { return size_t(-1); } ++s; if (*s >= '0' && *s <= '9') { *d |= (*s - '0'); } else if (*s >= 'A' && *s <= 'F') { *d |= (*s - 'A' + 10); } else { return size_t(-1); } ++s; ++d; } else { *d = *s; ++d; ++s; } } *d = 0; return d - dst; } void XlSwapMemory(void* a, void* b, size_t size) { uint8 buf[256]; assert(size < 256); memcpy(buf, a, size); memcpy(a, b, size); memcpy(b, buf, size); } bool XlIsAlnum(char c) { return __alphanum_table[(uint8)c] != 0x00; } bool XlIsEngAlpha(char c) { return __alphanum_table[(uint8)c] > 0x01; } bool XlIsAlNumSpace(char c) { return (__alphanum_table[(uint8)c] != 0x00) || (c == ' '); } bool XlIsDigit(char c) { return __alphanum_table[(uint8)c] == 0x01; } bool XlIsDigit(utf8 c) { return __alphanum_table[c] == 0x01; } bool XlIsHex(char c) { return __hex_table[(uint8)c] != 0xFF; } bool XlIsLower(char c) { return __alphanum_table[(uint8)c] == 0x02; } bool XlIsUpper(char c) { return __alphanum_table[(uint8)c] == 0x03; } bool XlIsPrint(char c) { return (uint8)c >= ' '; } bool XlIsSpace(char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\v' || c == '\f'; } char XlToLower(char c) { return (char)__lower_table[(uint8)c]; } char XlToUpper(char c) { return (char)__upper_table[(uint8)c]; } wchar_t XlToLower(wchar_t c) { return std::tolower(c, std::locale()); } wchar_t XlToUpper(wchar_t c) { return std::toupper(c, std::locale()); } // remark_todo("remove branching!") ucs2 XlToLower(ucs2 c) { if (c <= 0x7F) { return (ucs2)__lower_table[(uint8)c]; } return c; } ucs2 XlToUpper(ucs2 c) { if (c <= 0x7F) { return (ucs2)__upper_table[(uint8)c]; } return c; } char* XlTrimRight(char* str) { size_t len = XlStringSize(str); if (len < 1) { return str; } char* pos = str + len - 1; while (pos >= str && XlIsSpace(*pos)) { --pos; } *(pos + 1) = 0; return str; } char* XlRemoveAllSpace(char* str) { std::basic_string<char> customstr; while (size_t offset = XlGetOffset(str, 1)) { if (offset == 1) { if (XlIsSpace(str[0]) == false) { customstr.push_back(str[0]); } } else { char tempChar[64]; memcpy(tempChar, str, offset); customstr += tempChar; } str += offset; } return (char*)customstr.c_str(); } struct UnicharEng { UnicharEng(ucs4 c_) : c(c_) {} union { struct { uint8 l1, l2, l3; char ascii; } e; ucs4 c; }; bool c0() const { return (c <= 0x7F); } bool c1() const { return (c > 0x7F) && (c <= 0xFF); } bool c01() const { return (c <= 0xFF); } bool c15() const { return (c <= 0x7FF); } }; bool XlIsDigit(ucs4 c) { UnicharEng eng(c); if (!eng.c0()) { return false; } return XlIsDigit((char) eng.e.l1); } bool XlIsAlpha(ucs4 c) { UnicharEng eng(c); if (eng.c0()) { // single byte ucs4 return XlIsEngAlpha((char) eng.e.l1); } if (eng.c15()) { // 2 byte ucs4 return (iswalpha((wchar_t)c) > 0); } return false; } bool XlIsEngAlpha(ucs4 c) { UnicharEng eng(c); if (eng.c0()) { // single byte ucs4 return XlIsEngAlpha((char) eng.e.l1); } return false; } bool XlIsUpper(ucs4 c) { UnicharEng eng(c); if (!eng.c15()) { // 3 - 4 byte ucs4 return false; } else if (eng.c0()) { // single byte ucs4 return XlIsUpper((char) eng.e.l1); } // 2byte ucs4 return (iswupper((wchar_t) c) != 0); } bool XlIsLower(ucs4 c) { UnicharEng eng(c); if (!eng.c15()) { // 3 - 4 byte ucs4 return false; } else if (eng.c0()) { // single byte ucs4 return XlIsLower((char) eng.e.l1); } // 2byte ucs4 return (iswlower((wchar_t) c) != 0); } bool XlIsSpace(ucs4 c) { UnicharEng eng(c); if (!eng.c0()) { return false; } return XlIsSpace((char) eng.e.l1); } ucs4 XlToLower(ucs4 c) { UnicharEng eng(c); if (!eng.c15()) { // 3 - 4 byte ucs4 return c; } if (eng.c0()) { // single byte ucs4 return (ucs4)XlToLower((char) eng.e.l1); } // 2byte ucs4 wchar_t ret = towlower((wchar_t) c); return (ucs4) ret; } ucs4 XlToUpper(ucs4 c) { UnicharEng eng(c); if (!eng.c15()) { // 3 - 4 byte ucs4 return c; } if (eng.c0()) { // single byte ucs4 return (ucs4)XlToUpper((char) eng.e.l1); } // 2byte ucs4 wchar_t ret = towupper((wchar_t) c); return (ucs4) ret; } int XlFromHex(char c) { if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); return c - '0'; } char XlToHex(int n) { uint32 u = (uint32)n; if (u < 10) return '0' + char(u); else return 'a' + char(u - 10); } /*static inline bool XlIsLocaleSyllable(int c, bool allowSpace) { if (c == 0x0020 && allowSpace) { return true; } switch (XlGetLocale()) { case LOCALE_ZH_CN: return c >= 0x4E00 && c <= 0x9FFF; case LOCALE_JA: return true; case LOCALE_RU: return (c >= 0x0400 && c <= 0x052F); default: return c >= 0xAC00 && c <= 0xD7AF; } }*/ static inline bool XlIsHangulSyllable(int c) { // see http://www.unicode.org/charts/PDF/UAC00.pdf return c >= 0xAC00 && c <= 0xD7AF; } static inline bool XlIsHangulSpace(int c) { return (c >= 0xAC00 && c <= 0xD7AF) || (c == 0x0020); } bool XlAtoBool(const char* str, const char** end_ptr) { if (XlEqString(str, "true")) { if (end_ptr) { *end_ptr += 4; } return true; } else if (XlEqString(str, "false")) { if (end_ptr) { *end_ptr += 5; } return false; } else { if (end_ptr) { *end_ptr += XlStringLen(str); } return false; } } #define RADIX_MIN 2 #define RADIX_MAX 16 template <typename T> // T: must be "signed" type! static inline T tpl_atoi(const char* buffer, const char** end_ptr, int radix) { const char* s = buffer; if (radix < RADIX_MIN || radix > RADIX_MAX) { return (T)0; } // Skip whitespace while (XlIsSpace(*s)) ++s; // Check for sign bool neg = false; if (radix == 10) { if ((neg = *s == '-') || *s == '+') { ++s; } } else if (radix == 16) { if (s[0] == '0' && __lower_table[s[1]] == 'x') { s += 2; } } // Accumulate digits T result = 0; while (*s && __hex_table[*s] != 255 && __hex_table[*s] < radix) { result = (result * radix) + __hex_table[*s]; ++s; } if (end_ptr) *end_ptr = s; return (neg) ? -result : result; } int XlAtoI32(const char* str, const char** end_ptr, int radix) { return tpl_atoi<int32>(str, end_ptr, radix); } int64 XlAtoI64(const char* str, const char** end_ptr, int radix) { return tpl_atoi<int64>(str, end_ptr, radix); } uint32 XlAtoUI32(const char* str, const char** end_ptr, int radix) { return (uint32)tpl_atoi<int32>(str, end_ptr, radix); } uint64 XlAtoUI64(const char* str, const char** end_ptr, int radix) { return (uint64)tpl_atoi<int64>(str, end_ptr, radix); } float XlAtoF32(const char* str, const char** end_ptr) { return (float)XlAtoF64(str, end_ptr); } double XlAtoF64(const char* str, const char** endptr) { const char* s = str; // Skip whitespace while (XlIsSpace(*s)) ++s; // Check for sign int neg_val; if ((neg_val = (*s == '-')) || *s == '+') { ++s; } // Accumulate digits, using exponent to track the number of digits in the // fraction, and also if there are more digits than can be represented. double result = 0.0; int exponent = 0; while (XlIsDigit(*s)) { if (result > DBL_MAX * 0.1) ++exponent; else result = (result * 10.0) + (*s - '0'); ++s; } if (*s == '.') { ++s; while (XlIsDigit(*s)) { --exponent; if (result > DBL_MAX * 0.1) ++exponent; else result = (result * 10.0) + (*s - '0'); ++s; } } // Check for exponent if (*s == 'e' || *s == 'E') { ++s; // Get exponent and add to previous value computed above int neg_exp; if ((neg_exp = (*s == '-')) || *s == '+') { ++s; } int n = 0; while (XlIsDigit(*s)) { n = n * 10 + (*s - '0'); ++s; } exponent += neg_exp ? -n : n; } if (endptr) *endptr = s; result *= pow(10.0, exponent); return neg_val ? -result : result; } static bool IsValidDimForI32(size_t dim, int radix) { switch(radix) { case 10: return dim > 11; // "-2147483648" longest possible. need 11 chars + null terminator case 16: return dim > 8; //expand when need. } return false; } static bool IsValidDimForI64(size_t dim, int radix) { switch(radix) { case 10: return dim > 20; // "-9223372036854775808" or "18446744073709551615" longest possible. need 20 chars + null terminator case 16: return dim > 16; //expand when need. } return false; } template <typename T> static inline char* tpl_itoa(T value, char* buf, int radix) { T i; char* p = buf; char* q = buf; if (radix < RADIX_MIN || radix > RADIX_MAX) { *buf = 0; return buf; } if (value == 0) { *p++ = '0'; *p = 0; return buf; } while (value > 0) { i = value % radix; if (i > 9) i += 39; *p++ = char('0' + i); value /= radix; } *p-- = 0; q = buf; while (p > q) { i = *q; *q++ = *p; *p-- = char(i); } return buf; } char* XlI32toA(int32 value, char* buffer, size_t dim, int radix) { if (dim < 12) { return 0; } if (radix == 10 && value < 0) { *buffer = '-'; tpl_itoa<uint32>((uint32)(-value), buffer + 1, 10); return buffer; } return tpl_itoa<uint32>((uint32)value, buffer, radix); } char* XlI64toA(int64 value, char* buffer, size_t dim, int radix) { if (dim < 65) { return 0; } if (radix == 10 && value < 0) { *buffer = '-'; tpl_itoa<uint64>((uint64)(-value), buffer + 1, 10); return buffer; } return tpl_itoa<uint64>(value, buffer, radix); } char* XlUI32toA(uint32 value, char* buffer, size_t dim, int radix) { if (!IsValidDimForI32(dim, radix)) { return 0; } return tpl_itoa<uint32>((uint32)value, buffer, radix); } char* XlUI64toA(uint64 value, char* buffer, size_t dim, int radix) { if (!IsValidDimForI64(dim, radix)) { return 0; } return tpl_itoa<uint64>(value, buffer, radix); } int XlI32toA_s(int32 value, char* buffer, size_t dim, int radix) { if (dim < 12) { return EINVAL; } if (radix == 10 && value < 0) { *buffer = '-'; tpl_itoa<uint32>((uint32)(-value), buffer + 1, 10); return 0; } tpl_itoa<uint32>((uint32)value, buffer, radix); return 0; } int XlI64toA_s(int64 value, char* buffer, size_t dim, int radix) { if (dim < 65) { return EINVAL; } if (radix == 10 && value < 0) { *buffer = '-'; tpl_itoa<uint64>((uint64)(-value), buffer + 1, 10); return 0; } tpl_itoa<uint64>(value, buffer, radix); return 0; } int XlUI32toA_s(uint32 value, char* buffer, size_t dim, int radix) { if (dim < 12) { return EINVAL; } tpl_itoa<uint32>((uint32)value, buffer, radix); return 0; } int XlUI64toA_s(uint64 value, char* buffer, size_t dim, int radix) { if (dim < 65) { return EINVAL; } tpl_itoa<uint64>(value, buffer, radix); return 0; } char* XlI32toA_ns(int32 value, char* buffer, int radix) { if (radix == 10 && value < 0) { *buffer = '-'; tpl_itoa<uint32>((uint32)(-value), buffer + 1, 10); return buffer; } return tpl_itoa<uint32>((uint32)value, buffer, radix); } char* XlI64toA_ns(int64 value, char* buffer, int radix) { if (radix == 10 && value < 0) { *buffer = '-'; tpl_itoa<uint64>((uint64)(-value), buffer + 1, 10); return buffer; } return tpl_itoa<uint64>((uint64)value, buffer, radix); } char* XlUI32toA_ns(uint32 value, char* buffer, int radix) { return tpl_itoa<uint32>((uint32)value, buffer, radix); } char* XlUI64toA_ns(uint64 value, char* buffer, int radix) { return tpl_itoa<uint64>(value, buffer, radix); } bool XlMatchWildcard(const char* str, const char* pat, bool nocase) { const char* s; const char* p; bool star = false; start: for (s = str, p = pat; *s; ++s, ++p) { switch (*p) { case '?': if (*s == '.') goto check; break; case '*': star = true; str = s, pat = p; if (!*++pat) return true; goto start; default: if (nocase) { if (__lower_table[*s] != __lower_table[*p]) goto check; } else { if (*s != *p) goto check; } break; } } if (*p == '*') { ++p; } return (!*p); check: if (!star) { return false; } str++; goto start; } bool XlToHexStr(const char* x, size_t xlen, char* y, size_t ylen) { static const char* hexchars = "0123456789abcdef"; if (ylen < 2 * xlen + 1) { return false; } for (size_t i = 0; i < xlen; i++) { *y++ = hexchars[(uint8)x[i] >> 4]; *y++ = hexchars[(uint8)x[i] & 0x0f]; } *y = '\0'; return true; } // limitations: without checking in/out length & input validity! bool XlHexStrToBin(const char* x, char* y) { const char* c = x; char b = 0; while (*c) { b = (__hex_table[(uint8)*c++]) << 4; if (*c == '\0') { return false; } b |= (__hex_table[(uint8)*c++]) & 0x0f; *y++ = b; } return true; } #if 0 size_t XlMultiToWide(ucs4* dst, size_t count, const utf8* src) { // Assume UTF-8, but check for byte-order-mark if (XlHasUtf8Bom(src)) src += 3; size_t i = 0; while (i < count-1) { uint32 c = (uint8)*src++; if (c == 0) break; ucs4 x; if (c < 0x80) { x = c; } else if (c < 0xe0) { x = c & 0x1f; x = (x << 6) | *src++ & 0x3f; } else if (c < 0xf0) { x = c & 0x0f; x = (x << 6) | *src++ & 0x3f; x = (x << 6) | *src++ & 0x3f; } else { x = c & 0x07; x = (x << 6) | *src++ & 0x3f; x = (x << 6) | *src++ & 0x3f; x = (x << 6) | *src++ & 0x3f; } dst[i++] = x; } dst[i++] = '\0'; return i; } size_t XlWideToMulti(utf8* dst, size_t count, const ucs4* src) { auto* p = dst; auto* end = dst + count - 1; ucs4 c; while (p < end && (c = *src++) != 0) { if (c < 0x80) { *p++ = (char)c; } else if (c < 0x800) { *p++ = 0xc0 | ((c >> 6) & 0x1f); if (p == end) break; *p++ = 0x80 | (c & 0x3f); } else if (c < 0x10000) { *p++ = 0xe0 | ((c >> 12) & 0x0f); if (p == end) break; *p++ = 0x80 | ((c >> 6) & 0x3f); if (p == end) break; *p++ = 0x80 | (c & 0x3f); } else if (c < 0x110000) { *p++ = 0xf0 | ((c >> 18) & 0x07); if (p == end) break; *p++ = 0x80 | ((c >> 12) & 0x3f); if (p == end) break; *p++ = 0x80 | ((c >> 6) & 0x3f); if (p == end) break; *p++ = 0x80 | (c & 0x3f); } } *p++ = 0; return p - dst; } #endif }
[ "djewsbury@xlgames.com" ]
djewsbury@xlgames.com
f6d2383928a07df18245b04424394cc2c57f1249
07306d96ba61d744cb54293d75ed2e9a09228916
/External/AutodeskNav/sdk/include/gwnavruntime/queries/utils/breadthfirstsearchtraversal.h
2d351524a94e3eeb90450b23746df04b0245b937
[]
no_license
D34Dspy/warz-client
e57783a7c8adab1654f347f389c1dace35b81158
5262ea65e0baaf3f37ffaede5f41c9b7eafee7c1
refs/heads/master
2023-03-17T00:56:46.602407
2015-12-20T16:43:00
2015-12-20T16:43:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,232
h
/* * Copyright 2013 Autodesk, Inc. All rights reserved. * Use of this software is subject to the terms of the Autodesk license agreement and any attachments or Appendices thereto provided at the time of installation or download, * or which otherwise accompanies this software in either electronic or hard copy form, or which is signed by you and accepted by Autodesk. */ // ---------- Primary contact: JUBA - secondary contact: NOBODY #ifndef Navigation_BreadthFirstSearchTraversal_H #define Navigation_BreadthFirstSearchTraversal_H #include "gwnavruntime/querysystem/workingmemcontainers/workingmemdeque.h" #include "gwnavruntime/querysystem/workingmemcontainers/workingmemarray.h" #include "gwnavruntime/querysystem/workingmemcontainers/trianglestatusingrid.h" #include "gwnavruntime/queries/utils/navmeshtraversalcommon.h" #include "gwnavruntime/queries/utils/queryutils.h" #include "gwnavruntime/navmesh/identifiers/navtriangleptr.h" namespace Kaim { class NavMeshElementBlob; /* Visitor is a class that must have following methods : Visit(const NavTrianglePtr& trianglePtr, const TriangleStatusInGrid& triangleStatus) bool IsSearchFinished(); bool ShouldVisitTriangle(const NavTrianglePtr& trianglePtr); bool ShouldVisitNeighborTriangle(const NavTrianglePtr& trianglePtr, KyUInt32 indexOfNeighborTriangle); NavTrianglePtr GetNeighborTriangle(const NavTrianglePtr& trianglePtr, KyUInt32 indexOfNeighborTriangle); */ template <class Visitor> class BreadthFirstSearchTraversal { KY_DEFINE_NEW_DELETE_OPERATORS(MemStat_Query) public : BreadthFirstSearchTraversal( QueryUtils& queryUtils, const CellBox& cellBox, Visitor& visitor) : m_activeData(queryUtils.m_database->GetActiveData()), m_visitor(&visitor), m_openNodes(queryUtils.GetWorkingMemory()), m_triangleStatus(queryUtils.GetWorkingMemory(), cellBox), m_visitedNodes(KY_NULL) {} void Clear() { m_openNodes.MakeEmpty(); m_triangleStatus.MakeEmpty(); } // the navTag of the startTriangle is not tested inline TraversalResult SetStartTriangle(const NavTriangleRawPtr& triangleRawPtr); TraversalResult AddTriangleIfNeverEncountered(const NavTriangleRawPtr& triangleRawPtr); TraversalResult Search(); KY_INLINE void SetVisitedNodeContainer(WorkingMemArray<NavTriangleRawPtr>* visitedNodes) { m_visitedNodes = visitedNodes; } public : ActiveData* m_activeData; Visitor* m_visitor; //< the visitor (= the "node analyser") WorkingMemDeque<NavTriangleRawPtr> m_openNodes; //< open nodes = nodes that are about to be analysed TriangleStatusInGrid m_triangleStatus; //< closed nodes = nodes that have been analysed WorkingMemArray<NavTriangleRawPtr>* m_visitedNodes; //< nodes that have been visited }; template <class Visitor> TraversalResult BreadthFirstSearchTraversal<Visitor>:: SetStartTriangle(const NavTriangleRawPtr& triangleRawPtr) { if (m_visitor->ShouldVisitTriangle(triangleRawPtr) == false) return TraversalResult_DONE; if (KY_FAILED(m_openNodes.PushBack(triangleRawPtr))) return TraversalResult_LACK_OF_MEMORY_FOR_OPEN_NODES; bool unused; if (m_triangleStatus.IsInitialized() && KY_SUCCEEDED(m_triangleStatus.OpenNodeIfNew(*m_activeData, triangleRawPtr, unused))) return TraversalResult_DONE; return TraversalResult_LACK_OF_MEMORY_FOR_CLOSED_NODES; } template <class Visitor> TraversalResult BreadthFirstSearchTraversal<Visitor>::Search() { bool doesStoreVisited = m_visitedNodes != KY_NULL; NavTriangleRawPtr currentTrianglerRawPtr; while (!m_openNodes.IsEmpty()) { m_openNodes.Front(currentTrianglerRawPtr); m_openNodes.PopFront(); m_visitor->Visit(currentTrianglerRawPtr, m_triangleStatus); if (doesStoreVisited) { if (KY_FAILED(m_visitedNodes->PushBack(currentTrianglerRawPtr))) return TraversalResult_LACK_OF_MEMORY_FOR_VISITED_NODES; } if (m_visitor->IsSearchFinished()) return TraversalResult_DONE; if (m_visitor->ShouldVisitNeighborTriangle(currentTrianglerRawPtr, 0)) { const TraversalResult rc = AddTriangleIfNeverEncountered(m_visitor->GetNeighborTriangle(currentTrianglerRawPtr, 0)); if (rc != TraversalResult_DONE) return rc; } if (m_visitor->ShouldVisitNeighborTriangle(currentTrianglerRawPtr, 1)) { const TraversalResult rc = AddTriangleIfNeverEncountered(m_visitor->GetNeighborTriangle(currentTrianglerRawPtr, 1)); if (rc != TraversalResult_DONE) return rc; } if (m_visitor->ShouldVisitNeighborTriangle(currentTrianglerRawPtr, 2)) { const TraversalResult rc = AddTriangleIfNeverEncountered(m_visitor->GetNeighborTriangle(currentTrianglerRawPtr, 2)); if (rc != TraversalResult_DONE) return rc; } } return TraversalResult_DONE; } template <class Visitor> TraversalResult BreadthFirstSearchTraversal<Visitor>::AddTriangleIfNeverEncountered(const NavTriangleRawPtr& triangleRawPtr) { bool nodeIsNew; if (KY_FAILED(m_triangleStatus.OpenNodeIfNew(*m_activeData, triangleRawPtr, nodeIsNew))) return TraversalResult_LACK_OF_MEMORY_FOR_CLOSED_NODES; if (nodeIsNew && KY_FAILED(m_openNodes.PushBack(triangleRawPtr))) return TraversalResult_LACK_OF_MEMORY_FOR_OPEN_NODES; return TraversalResult_DONE; } } #endif // Navigation_BreadthFirstSearchTraversal_H
[ "hasan@openkod.com" ]
hasan@openkod.com
6a7519daaaab3d37071a8543fa095e24df866bef
e17c43db9488f57cb835129fa954aa2edfdea8d5
/Extended/DetailedBuildings/VisualDamage/RQuadSectionDamageRegion.cpp
f2299bee5af9108b76c3e7e639ceee052758cac2
[]
no_license
claudioperez/Rts
6e5868ab8d05ea194a276b8059730dbe322653a7
3609161c34f19f1649b713b09ccef0c8795f8fe7
refs/heads/master
2022-11-06T15:57:39.794397
2020-06-27T23:00:11
2020-06-27T23:00:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,826
cpp
/********************************************************************* * * * This file is posted by Dr. Stevan Gavrilovic (steva44@hotmail.com) * * as a result of work performed in the research group of Professor * * Terje Haukaas (terje@civil.ubc.ca) at the University of British * * Columbia in Vancouver. The code is part of the computer program * * Rts, which is an extension of the computer program Rt developed by * * Dr. Mojtaba Mahsuli (mahsuli@sharif.edu) in the same group. * * * * The content of this file is the product of thesis-related work * * performed at the University of British Columbia (UBC). Therefore, * * the Rights and Ownership are held by UBC. * * * * Please be cautious when using this code. It is provided “as is” * * without warranty of any kind, express or implied. * * * * Contributors to this file: * * - Stevan Gavrilovic * * * *********************************************************************/ #include "RQuadSectionDamageRegion.h" #include "RSectionForceDeformation.h" #include "RRCFibreContainer.h" #include "RFiber.h" #include "RElement.h" RQuadSectionDamageRegion::RQuadSectionDamageRegion() : RFibreDamageRegion() { theElement = nullptr; theSection = nullptr; } RQuadSectionDamageRegion::~RQuadSectionDamageRegion() { } void RQuadSectionDamageRegion::reset(void) { fiberMap.clear(); quadrantI.reset(); quadrantII.reset(); quadrantIII.reset(); quadrantIV.reset(); } std::vector<RGenericFibreContainer*> RQuadSectionDamageRegion::getAllFibreContainers() { std::vector<RGenericFibreContainer*> allQuadrants{&quadrantI,&quadrantII,&quadrantIII,&quadrantIV}; return allQuadrants; } std::vector<RFiber*> RQuadSectionDamageRegion::getAllFibres(void) { auto allContainers = this->getAllFibreContainers(); auto numFib = this->numFibres(); std::vector<RFiber*> allFibres; allFibres.reserve(numFib); for(auto&& it : allContainers) { allFibres.insert(allFibres.end(), it->getAllFibres().begin(), it->getAllFibres().end()); } return allFibres; } int RQuadSectionDamageRegion::numFibres(void) { auto numI = quadrantI.numFibres(); auto numII = quadrantII.numFibres(); auto numIII = quadrantIII.numFibres(); auto numIV = quadrantIV.numFibres(); return numI + numII + numIII + numIV; }
[ "steva44@hotmail.com" ]
steva44@hotmail.com
a2cb4af5a0e7704b1e47c66f56194eca80b904a9
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_repos_function_236_curl-7.35.0.cpp
47e901ccefdbb0e9e10ea696c7c544218e877649
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,887
cpp
int main(void) { CURL *curl; CURLcode res; /* Minimalistic http request */ const char *request = "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n"; curl_socket_t sockfd; /* socket */ long sockextr; size_t iolen; curl_off_t nread; curl = curl_easy_init(); if(curl) { curl_easy_setopt(curl, CURLOPT_URL, "http://example.com"); /* Do not do the transfer - only connect to host */ curl_easy_setopt(curl, CURLOPT_CONNECT_ONLY, 1L); res = curl_easy_perform(curl); if(CURLE_OK != res) { printf("Error: %s\n", strerror(res)); return 1; } /* Extract the socket from the curl handle - we'll need it for waiting. * Note that this API takes a pointer to a 'long' while we use * curl_socket_t for sockets otherwise. */ res = curl_easy_getinfo(curl, CURLINFO_LASTSOCKET, &sockextr); if(CURLE_OK != res) { printf("Error: %s\n", curl_easy_strerror(res)); return 1; } sockfd = sockextr; /* wait for the socket to become ready for sending */ if(!wait_on_socket(sockfd, 0, 60000L)) { printf("Error: timeout.\n"); return 1; } puts("Sending request."); /* Send the request. Real applications should check the iolen * to see if all the request has been sent */ res = curl_easy_send(curl, request, strlen(request), &iolen); if(CURLE_OK != res) { printf("Error: %s\n", curl_easy_strerror(res)); return 1; } puts("Reading response."); /* read the response */ for(;;) { char buf[1024]; wait_on_socket(sockfd, 1, 60000L); res = curl_easy_recv(curl, buf, 1024, &iolen); if(CURLE_OK != res) break; nread = (curl_off_t)iolen; printf("Received %" CURL_FORMAT_CURL_OFF_T " bytes.\n", nread); } /* always cleanup */ curl_easy_cleanup(curl); } return 0; }
[ "993273596@qq.com" ]
993273596@qq.com
62254e42a3d1da2ab31bd5e92317fd96e4241434
216f5252a8df73f8547d6a6c831409c916bae3e5
/windows_embedded_compact_2013_2015M09/WINCE800/private/test/net/wireless/common/APController/server/telnetport_t.hpp
fe40cfecd1cd6b86c09af32b5b01c770ea7cd29c
[]
no_license
fanzcsoft/windows_embedded_compact_2013_2015M09
845fe834d84d3f0021047bc73d6cf9a75fabb74d
d04b71c517428ed2c73e94caf21a1582b34b18e3
refs/heads/master
2022-12-19T02:52:16.222712
2020-09-28T20:13:09
2020-09-28T20:13:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,963
hpp
// // Copyright (c) Microsoft Corporation. All rights reserved. // // // Use of this source code is subject to the terms of the Microsoft shared // source or premium shared source license agreement under which you licensed // this source code. If you did not accept the terms of the license agreement, // you are not authorized to use this source code. For the terms of the license, // please see the license agreement between you and Microsoft or, if applicable, // see the SOURCE.RTF on your install media or the root of your tools installation. // THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES. // // ---------------------------------------------------------------------------- // // Use of this source code is subject to the terms of the Microsoft end-user // license agreement (EULA) under which you licensed this SOFTWARE PRODUCT. // If you did not accept the terms of the EULA, you are not authorized to use // this source code. For a copy of the EULA, please see the LICENSE.RTF on your // install media. // // ---------------------------------------------------------------------------- // // Definitions and declarations for the TelnetPort_t class. // // ---------------------------------------------------------------------------- #ifndef _DEFINED_TelnetPort_t_ #define _DEFINED_TelnetPort_t_ #pragma once #include <APCUtils.hpp> #include <MemBuffer_t.hpp> #include <sync.hxx> namespace ce { namespace qa { // ---------------------------------------------------------------------------- // // Provides a contention-controlled interface to a telnet server. // Unless external synchronization is provided, each of these objects // should be used by a single thread at a time. // class TelnetHandle_t; class TelnetLines_t; class TelnetPort_t { private: // Copy and assignment are deliberately disabled: TelnetPort_t(const TelnetPort_t &src); TelnetPort_t &operator = (const TelnetPort_t &src); protected: // Current telnet-server connection: TelnetHandle_t *m_pHandle; // Special constructor for derived classes which need to create // a different handle type: TelnetPort_t( const TCHAR *pServerHost, DWORD ServerPort, TelnetHandle_t *(*CreateHandleFunc)(const TCHAR *, DWORD)); public: // Default telnet-server port number: static const DWORD DefaultTelnetPort = 23; // Default operation times: static const long DefaultConnectTimeMS = 10*1000; // 10 seconds static const long DefaultReadTimeMS = 2*1000; // 2 seconds static const long DefaultWriteTimeMS = 1*1000; // 1 second // Contructor and destructor: TelnetPort_t(const TCHAR *pServerHost, DWORD ServerPort); virtual ~TelnetPort_t(void); // Returns true if the port handle is valid: bool IsValid(void) const; // Gets the telnet-server address or port (default 23): const TCHAR * GetServerHost(void) const; DWORD GetServerPort(void) const; // Gets or sets the user-name: const TCHAR * GetUserName(void) const; void SetUserName(const TCHAR *Value); // Gets or sets the admin password: const TCHAR * GetPassword(void) const; void SetPassword(const TCHAR *Value); // Retrieves an object which can be locked to prevent other threads // from accessing this telnet-server: // Callers should lock this object before performing any I/O operations. ce::critical_section & GetLocker(void) const; // Connects and logs in to the telnet-server: DWORD Connect(long MaxWaitTimeMS = DefaultConnectTimeMS); // Closes the existing connection: void Disconnect(void); // Is the connection open? // Note that the connection will automatically be timed out after // a period with no activity. bool IsConnected(void) const; // Flushes the read/write buffers: void Flush(void); #if 0 // Writes a line to the server: DWORD WriteLine( const char *pFormat, ...); DWORD WriteLineV( const char *pFormat, va_list pArgList, long MaxWaitTimeMS = DefaultWriteTimeMS); DWORD WriteNewLine( long MaxWaitTimeMS = DefaultWriteTimeMS) { return WriteBlock("\r\n", 2, MaxWaitTimeMS); } // Writes an unformatted, "raw", block of data to the server: DWORD WriteBlock( const void *pBlock, int BlockChars, long MaxWaitTimeMS = DefaultWriteTimeMS); #endif // Sends the specified message (defaults to a newline) and waits for // the server to send the indicated prompt in return. // Returns ERROR_NOT_FOUND if the specified prompt wasn't forthcoming. DWORD SendExpect( const char *pExpect, int ExpectChars, const char *pExpectName, ce::string *pPromptBuffer = NULL, const char *pMessage = "", TelnetLines_t *pResponse = NULL, long MaxWaitTimeMS = DefaultReadTimeMS); }; // ---------------------------------------------------------------------------- // // Provides a mechanism for the telnet interface to return lines of // text retrieved from the telnet server. // class TelnetWords_t; class TelnetLines_t { protected: // Text retrieved from the server: MemBuffer_t m_Text; // List of separated lines: MemBuffer_t m_Lines; // Number words in the list: // Contains -1 if the text hasn't been parsed yet. int m_NumberLines; // Parses the text into lines and words: DWORD ParseLines(void); // The telnet interface is a friend: friend class TelnetHandle_t; public: // Constructor/destructor: TelnetLines_t(void) { Clear(); } virtual ~TelnetLines_t(void); // Clears the list of parsed words: void Clear(void) { m_Text.Clear(); m_Lines.Clear(); m_NumberLines = 0; } // Gets the unparsed text: // Note that this method and the following methods are incompatible. // When one of the following methods is called, it will parse the // text into lines and words. Hence, the unmodified text will no // longer be available for retrieval using this method. const char * GetText(void) const { return (const char *)(m_Text.GetShared()); } // Gets the number of lines in the text: // If necessary, parses the text first. int Size(void); // Gets the specified line as separated words: // If necessary, parses the text first. const TelnetWords_t & GetLine(int IX); }; // ---------------------------------------------------------------------------- // // Provides a mechanism for the telnet interface to return a parsed line // of text retrieved from the telnet server. // class TelnetWords_t { private: // List of separated words: static const int MaxWordsInLine = 16; char *m_Words[MaxWordsInLine]; // Number words in the list: int m_NumberWords; // Parses the words from a line of text: void ParseWords( char *&pText, const char *pTextEnd); // The telnet interface is a friend: friend class TelnetLines_t; public: // Gets the number of words in the line: int Size(void) const { return m_NumberWords; } // Retreves the individual words: const char * operator[](int IX) const { return m_Words[IX]; } // Re-merges the line of text into the specified buffer: const char * MergeLine(char *pBuffer, size_t BufferChars) const; }; }; }; #endif /* _DEFINED_TelnetPort_t_ */ // ----------------------------------------------------------------------------
[ "benjamin.barratt@icloud.com" ]
benjamin.barratt@icloud.com
e48cd83668b186706eaf76255eebbb499a554bf0
879681c994f1ca9c8d2c905a4e5064997ad25a27
/root-2.3.0/run/tutorials/multiphase/twoPhaseEulerFoam/RAS/bubbleColumn/46/nut.air
cbd36f7048c7d3dc776e8383d0f1ff76aeaa93ad
[]
no_license
MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu
3828272d989d45fb020e83f8426b849e75560c62
daeb870be81275e8a81f5cbac4ca1906a9bc69c0
refs/heads/master
2020-05-17T16:36:41.848261
2015-04-18T09:29:48
2015-04-18T09:29:48
34,159,882
1
0
null
null
null
null
UTF-8
C++
false
false
24,342
air
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2.3.0 | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "46"; object nut.air; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -1 0 0 0 0]; internalField nonuniform List<scalar> 1875 ( 2.04535e-05 2.17199e-05 2.37766e-05 2.56498e-05 2.7328e-05 2.87784e-05 3.00122e-05 3.10913e-05 3.20433e-05 3.29093e-05 3.3685e-05 3.43678e-05 3.4956e-05 3.54468e-05 3.58465e-05 3.59394e-05 3.5859e-05 3.54421e-05 3.45425e-05 3.32396e-05 3.15777e-05 2.96249e-05 2.73882e-05 2.48541e-05 2.21364e-05 2.14537e-05 2.51798e-05 2.82428e-05 3.03972e-05 3.1878e-05 3.28904e-05 3.35854e-05 3.40333e-05 3.42909e-05 3.45207e-05 3.46975e-05 3.48276e-05 3.50036e-05 3.52324e-05 3.55021e-05 3.57414e-05 3.59034e-05 3.58798e-05 3.55507e-05 3.46896e-05 3.32421e-05 3.11567e-05 2.83236e-05 2.45009e-05 1.98825e-05 2.82833e-05 3.2645e-05 3.57188e-05 3.75942e-05 3.86112e-05 3.90521e-05 3.91083e-05 3.89019e-05 3.85567e-05 3.81532e-05 3.7699e-05 3.72647e-05 3.69191e-05 3.66598e-05 3.64778e-05 3.63727e-05 3.62593e-05 3.60099e-05 3.55567e-05 3.4847e-05 3.35303e-05 3.17671e-05 2.94908e-05 2.67733e-05 2.42391e-05 3.70705e-05 4.08165e-05 4.25508e-05 4.31275e-05 4.30495e-05 4.25919e-05 4.19574e-05 4.12481e-05 4.05436e-05 3.9863e-05 3.92078e-05 3.85815e-05 3.80077e-05 3.75115e-05 3.71013e-05 3.6741e-05 3.63806e-05 3.59363e-05 3.53322e-05 3.45115e-05 3.32929e-05 3.17068e-05 2.97523e-05 2.7504e-05 2.52311e-05 6.1707e-05 5.02259e-05 4.71676e-05 4.64379e-05 4.53743e-05 4.41911e-05 4.30135e-05 4.19132e-05 4.09291e-05 4.00715e-05 3.93203e-05 3.86621e-05 3.80604e-05 3.74805e-05 3.69088e-05 3.64055e-05 3.58944e-05 3.53497e-05 3.46925e-05 3.38174e-05 3.26948e-05 3.13129e-05 2.9648e-05 2.78273e-05 2.59679e-05 7.13686e-05 5.47781e-05 5.01743e-05 4.82117e-05 4.61564e-05 4.42325e-05 4.25759e-05 4.11627e-05 4.00145e-05 3.91134e-05 3.83629e-05 3.77059e-05 3.7113e-05 3.65799e-05 3.60828e-05 3.55466e-05 3.50115e-05 3.45226e-05 3.38781e-05 3.30365e-05 3.20202e-05 3.08026e-05 2.94194e-05 2.79549e-05 2.65027e-05 7.77502e-05 5.50489e-05 5.18702e-05 4.88419e-05 4.59827e-05 4.34183e-05 4.12487e-05 3.96083e-05 3.83994e-05 3.75326e-05 3.68828e-05 3.63194e-05 3.58506e-05 3.54172e-05 3.5018e-05 3.4606e-05 3.41457e-05 3.36832e-05 3.30251e-05 3.22426e-05 3.13361e-05 3.02867e-05 2.91208e-05 2.79473e-05 2.67026e-05 8.49083e-05 5.76429e-05 5.30162e-05 4.88045e-05 4.512e-05 4.20424e-05 3.9621e-05 3.77628e-05 3.64445e-05 3.57092e-05 3.51174e-05 3.46255e-05 3.42768e-05 3.39838e-05 3.36822e-05 3.33549e-05 3.30443e-05 3.25429e-05 3.19039e-05 3.11581e-05 3.03188e-05 2.93782e-05 2.83598e-05 2.72869e-05 2.60541e-05 9.00144e-05 5.90739e-05 5.30066e-05 4.81082e-05 4.37724e-05 4.01821e-05 3.74401e-05 3.54143e-05 3.42594e-05 3.36015e-05 3.30396e-05 3.2707e-05 3.24834e-05 3.22816e-05 3.20229e-05 3.17328e-05 3.12676e-05 3.07141e-05 3.01064e-05 2.94202e-05 2.8646e-05 2.77586e-05 2.67958e-05 2.57242e-05 2.44566e-05 8.23369e-05 5.86145e-05 5.19866e-05 4.65808e-05 4.17984e-05 3.79341e-05 3.50185e-05 3.30121e-05 3.19135e-05 3.12776e-05 3.08611e-05 3.05222e-05 3.02222e-05 2.99244e-05 2.96163e-05 2.92324e-05 2.8801e-05 2.8303e-05 2.77266e-05 2.70773e-05 2.63583e-05 2.55391e-05 2.46434e-05 2.35814e-05 2.22784e-05 6.41082e-05 5.62378e-05 4.98785e-05 4.44672e-05 3.9662e-05 3.57678e-05 3.2893e-05 3.09422e-05 2.97317e-05 2.90512e-05 2.85886e-05 2.82407e-05 2.7952e-05 2.76515e-05 2.73012e-05 2.68961e-05 2.64393e-05 2.59287e-05 2.53616e-05 2.47347e-05 2.40389e-05 2.32894e-05 2.24403e-05 2.14111e-05 2.01083e-05 5.61886e-05 5.15225e-05 4.66517e-05 4.19405e-05 3.76062e-05 3.39838e-05 3.12882e-05 2.94868e-05 2.83948e-05 2.77474e-05 2.73272e-05 2.70146e-05 2.67393e-05 2.64498e-05 2.61334e-05 2.57692e-05 2.53359e-05 2.48198e-05 2.4216e-05 2.35267e-05 2.27545e-05 2.18999e-05 2.09495e-05 1.97956e-05 1.83829e-05 4.80187e-05 4.62026e-05 4.31605e-05 3.95562e-05 3.59546e-05 3.28217e-05 3.04732e-05 2.89563e-05 2.80689e-05 2.75662e-05 2.72648e-05 2.70385e-05 2.68263e-05 2.66161e-05 2.63474e-05 2.59986e-05 2.5558e-05 2.502e-05 2.43768e-05 2.36207e-05 2.27299e-05 2.17014e-05 2.05575e-05 1.92096e-05 1.77369e-05 4.19046e-05 4.17899e-05 4.01377e-05 3.75919e-05 3.47716e-05 3.22304e-05 3.03404e-05 2.91278e-05 2.84714e-05 2.81662e-05 2.80351e-05 2.79549e-05 2.78716e-05 2.77588e-05 2.7571e-05 2.72883e-05 2.68951e-05 2.63778e-05 2.57218e-05 2.49168e-05 2.39532e-05 2.2844e-05 2.15118e-05 1.99078e-05 1.83233e-05 3.76727e-05 3.84416e-05 3.77656e-05 3.60815e-05 3.39905e-05 3.20545e-05 3.05982e-05 2.97601e-05 2.93714e-05 2.92496e-05 2.92552e-05 2.9296e-05 2.93187e-05 2.92867e-05 2.91874e-05 2.89924e-05 2.86767e-05 2.82214e-05 2.76077e-05 2.68107e-05 2.58027e-05 2.45617e-05 2.30219e-05 2.10842e-05 1.90137e-05 3.46637e-05 3.58698e-05 3.58767e-05 3.49166e-05 3.35025e-05 3.21503e-05 3.12017e-05 3.06745e-05 3.04663e-05 3.04474e-05 3.05239e-05 3.0632e-05 3.07282e-05 3.07801e-05 3.07517e-05 3.0641e-05 3.04151e-05 3.00528e-05 2.95383e-05 2.88514e-05 2.796e-05 2.68177e-05 2.53535e-05 2.34125e-05 2.10231e-05 3.31685e-05 3.42899e-05 3.45845e-05 3.41268e-05 3.32778e-05 3.24365e-05 3.18458e-05 3.15389e-05 3.14513e-05 3.15025e-05 3.16278e-05 3.17788e-05 3.19206e-05 3.20248e-05 3.20601e-05 3.20015e-05 3.184e-05 3.15441e-05 3.10997e-05 3.04948e-05 2.97179e-05 2.87271e-05 2.74527e-05 2.58196e-05 2.37797e-05 3.17439e-05 3.29883e-05 3.3522e-05 3.34618e-05 3.30728e-05 3.26591e-05 3.23799e-05 3.22519e-05 3.22551e-05 3.23524e-05 3.25044e-05 3.26776e-05 3.28453e-05 3.29826e-05 3.30617e-05 3.30442e-05 3.29237e-05 3.26658e-05 3.22468e-05 3.16524e-05 3.08558e-05 2.98399e-05 2.86042e-05 2.71467e-05 2.53618e-05 3.09814e-05 3.20632e-05 3.27063e-05 3.29113e-05 3.28375e-05 3.27009e-05 3.26371e-05 3.26704e-05 3.27731e-05 3.2926e-05 3.31091e-05 3.33055e-05 3.34988e-05 3.36666e-05 3.37807e-05 3.38083e-05 3.37247e-05 3.34982e-05 3.30991e-05 3.25095e-05 3.17248e-05 3.07181e-05 2.94446e-05 2.79017e-05 2.60978e-05 3.09729e-05 3.15518e-05 3.2115e-05 3.24392e-05 3.25763e-05 3.2661e-05 3.27458e-05 3.28669e-05 3.30359e-05 3.3235e-05 3.34529e-05 3.36798e-05 3.39026e-05 3.41035e-05 3.42571e-05 3.433e-05 3.42906e-05 3.41124e-05 3.37638e-05 3.32381e-05 3.2511e-05 3.15327e-05 3.02383e-05 2.86429e-05 2.67953e-05 3.16596e-05 3.17839e-05 3.20449e-05 3.2268e-05 3.2412e-05 3.25412e-05 3.27005e-05 3.28954e-05 3.3112e-05 3.3347e-05 3.35951e-05 3.38505e-05 3.41032e-05 3.43361e-05 3.45249e-05 3.4638e-05 3.46394e-05 3.45037e-05 3.42081e-05 3.37322e-05 3.30487e-05 3.21073e-05 3.08315e-05 2.91934e-05 2.73229e-05 3.21977e-05 3.22412e-05 3.2311e-05 3.23861e-05 3.24594e-05 3.25397e-05 3.26631e-05 3.28403e-05 3.30593e-05 3.33085e-05 3.35787e-05 3.38632e-05 3.41549e-05 3.44379e-05 3.46798e-05 3.48548e-05 3.49221e-05 3.48542e-05 3.462e-05 3.41897e-05 3.35362e-05 3.26211e-05 3.13862e-05 2.97891e-05 2.8017e-05 3.28064e-05 3.28298e-05 3.28138e-05 3.27815e-05 3.27183e-05 3.26924e-05 3.27185e-05 3.28155e-05 3.29861e-05 3.32165e-05 3.34984e-05 3.38112e-05 3.41426e-05 3.44652e-05 3.47627e-05 3.50037e-05 3.51454e-05 3.51538e-05 3.5005e-05 3.46479e-05 3.40436e-05 3.31448e-05 3.18896e-05 3.02701e-05 2.84581e-05 3.3031e-05 3.317e-05 3.3219e-05 3.31811e-05 3.31207e-05 3.30066e-05 3.29186e-05 3.28838e-05 3.29419e-05 3.31083e-05 3.3352e-05 3.36691e-05 3.40408e-05 3.44082e-05 3.47755e-05 3.50869e-05 3.52997e-05 3.53726e-05 3.52871e-05 3.49715e-05 3.43994e-05 3.35398e-05 3.23368e-05 3.07615e-05 2.89935e-05 3.24704e-05 3.27722e-05 3.302e-05 3.30636e-05 3.30537e-05 3.30087e-05 3.29141e-05 3.28601e-05 3.28472e-05 3.29238e-05 3.31402e-05 3.34639e-05 3.38274e-05 3.42488e-05 3.46853e-05 3.50716e-05 3.53533e-05 3.5484e-05 3.54453e-05 3.51546e-05 3.45921e-05 3.37529e-05 3.26104e-05 3.11363e-05 2.95422e-05 3.00127e-05 3.07202e-05 3.13231e-05 3.18024e-05 3.21151e-05 3.23021e-05 3.23826e-05 3.23717e-05 3.23597e-05 3.24056e-05 3.25507e-05 3.28771e-05 3.33709e-05 3.38521e-05 3.44037e-05 3.48959e-05 3.52601e-05 3.54506e-05 3.54461e-05 3.51564e-05 3.45878e-05 3.37232e-05 3.2608e-05 3.12843e-05 2.99312e-05 2.51378e-05 2.67033e-05 2.79024e-05 2.88847e-05 2.97142e-05 3.03502e-05 3.08435e-05 3.12526e-05 3.14785e-05 3.1731e-05 3.1973e-05 3.23035e-05 3.26987e-05 3.32942e-05 3.39688e-05 3.45807e-05 3.50149e-05 3.52516e-05 3.52668e-05 3.49539e-05 3.43448e-05 3.34713e-05 3.23803e-05 3.11554e-05 2.9979e-05 2.06542e-05 2.25363e-05 2.407e-05 2.54138e-05 2.66101e-05 2.76698e-05 2.85376e-05 2.92514e-05 2.98503e-05 3.04015e-05 3.09244e-05 3.14983e-05 3.21052e-05 3.28041e-05 3.35334e-05 3.42087e-05 3.47082e-05 3.49257e-05 3.49269e-05 3.4566e-05 3.39058e-05 3.29879e-05 3.1877e-05 3.07084e-05 2.96606e-05 1.79026e-05 1.97827e-05 2.14477e-05 2.29579e-05 2.43385e-05 2.5596e-05 2.67081e-05 2.76426e-05 2.84453e-05 2.91754e-05 2.98867e-05 3.06231e-05 3.1415e-05 3.22529e-05 3.30762e-05 3.37834e-05 3.42846e-05 3.44652e-05 3.4397e-05 3.39669e-05 3.32289e-05 3.2246e-05 3.11016e-05 2.99439e-05 2.89657e-05 1.68042e-05 1.88709e-05 2.07614e-05 2.24237e-05 2.39025e-05 2.51756e-05 2.6278e-05 2.71904e-05 2.79935e-05 2.87282e-05 2.94493e-05 3.02175e-05 3.10595e-05 3.19138e-05 3.27129e-05 3.33782e-05 3.38132e-05 3.39255e-05 3.37432e-05 3.31886e-05 3.23337e-05 3.12628e-05 3.00693e-05 2.88968e-05 2.79331e-05 1.70458e-05 1.92965e-05 2.14058e-05 2.3164e-05 2.46291e-05 2.58364e-05 2.68512e-05 2.76715e-05 2.83451e-05 2.89407e-05 2.95545e-05 3.02525e-05 3.10225e-05 3.1798e-05 3.25001e-05 3.30366e-05 3.3319e-05 3.32743e-05 3.28888e-05 3.21805e-05 3.12069e-05 3.00541e-05 2.88145e-05 2.762e-05 2.66408e-05 1.83225e-05 2.08705e-05 2.31547e-05 2.48905e-05 2.6263e-05 2.73282e-05 2.81138e-05 2.86941e-05 2.91374e-05 2.95254e-05 2.99611e-05 3.05207e-05 3.11632e-05 3.17872e-05 3.22946e-05 3.26072e-05 3.26374e-05 3.23591e-05 3.1787e-05 3.09445e-05 2.98759e-05 2.86676e-05 2.74061e-05 2.62046e-05 2.51988e-05 2.05241e-05 2.30934e-05 2.5273e-05 2.69002e-05 2.80847e-05 2.89053e-05 2.94547e-05 2.97994e-05 3.00075e-05 3.01998e-05 3.048e-05 3.08662e-05 3.12935e-05 3.16791e-05 3.19433e-05 3.19779e-05 3.17541e-05 3.12644e-05 3.05187e-05 2.9551e-05 2.84126e-05 2.71863e-05 2.59476e-05 2.47844e-05 2.38055e-05 2.3209e-05 2.5516e-05 2.73813e-05 2.87204e-05 2.96267e-05 3.01922e-05 3.04938e-05 3.05987e-05 3.06188e-05 3.06571e-05 3.07867e-05 3.09937e-05 3.12097e-05 3.13566e-05 3.1349e-05 3.11158e-05 3.06581e-05 2.99717e-05 2.90842e-05 2.80328e-05 2.68696e-05 2.5667e-05 2.44911e-05 2.34313e-05 2.25574e-05 2.60488e-05 2.77457e-05 2.91526e-05 3.01424e-05 3.07608e-05 3.10648e-05 3.11322e-05 3.10379e-05 3.08744e-05 3.07836e-05 3.07614e-05 3.07929e-05 3.08214e-05 3.07273e-05 3.04557e-05 2.99967e-05 2.93446e-05 2.85153e-05 2.75404e-05 2.64543e-05 2.53137e-05 2.41691e-05 2.30828e-05 2.2147e-05 2.13803e-05 2.81883e-05 2.93694e-05 3.03877e-05 3.10822e-05 3.14496e-05 3.15348e-05 3.14241e-05 3.11667e-05 3.08658e-05 3.06532e-05 3.04865e-05 3.03518e-05 3.01214e-05 2.97951e-05 2.93252e-05 2.87017e-05 2.79271e-05 2.70233e-05 2.60213e-05 2.4952e-05 2.38703e-05 2.28119e-05 2.18349e-05 2.09885e-05 2.03124e-05 2.93197e-05 3.02561e-05 3.10456e-05 3.15497e-05 3.17334e-05 3.16928e-05 3.14396e-05 3.10751e-05 3.06614e-05 3.03262e-05 3.00013e-05 2.96409e-05 2.92491e-05 2.87696e-05 2.81792e-05 2.74703e-05 2.66507e-05 2.5739e-05 2.47578e-05 2.37494e-05 2.27434e-05 2.17742e-05 2.08733e-05 2.00552e-05 1.94182e-05 3.00284e-05 3.06885e-05 3.12747e-05 3.16404e-05 3.1723e-05 3.15983e-05 3.12638e-05 3.08135e-05 3.03113e-05 2.98148e-05 2.93581e-05 2.89212e-05 2.84537e-05 2.79186e-05 2.72994e-05 2.65908e-05 2.57996e-05 2.49453e-05 2.40446e-05 2.31239e-05 2.21737e-05 2.12025e-05 2.02073e-05 1.91704e-05 1.81313e-05 3.03332e-05 3.07766e-05 3.12216e-05 3.14925e-05 3.15267e-05 3.13693e-05 3.1013e-05 3.05192e-05 2.997e-05 2.94342e-05 2.89306e-05 2.84572e-05 2.79797e-05 2.74646e-05 2.68891e-05 2.62457e-05 2.55412e-05 2.47776e-05 2.39691e-05 2.31062e-05 2.21835e-05 2.12017e-05 2.01523e-05 1.8994e-05 1.77313e-05 3.01049e-05 3.0498e-05 3.09148e-05 3.11727e-05 3.12247e-05 3.10907e-05 3.07581e-05 3.02915e-05 2.97683e-05 2.92352e-05 2.87476e-05 2.831e-05 2.78843e-05 2.74354e-05 2.69392e-05 2.63914e-05 2.57993e-05 2.51436e-05 2.44391e-05 2.3646e-05 2.27652e-05 2.17916e-05 2.07116e-05 1.95014e-05 1.82095e-05 2.94445e-05 2.98742e-05 3.03521e-05 3.06798e-05 3.08088e-05 3.07432e-05 3.04807e-05 3.00815e-05 2.96164e-05 2.91496e-05 2.87397e-05 2.83877e-05 2.80472e-05 2.76853e-05 2.72874e-05 2.68525e-05 2.63749e-05 2.58311e-05 2.52255e-05 2.45207e-05 2.36852e-05 2.2728e-05 2.1639e-05 2.03807e-05 1.90029e-05 2.7996e-05 2.87732e-05 2.94697e-05 2.99467e-05 3.02079e-05 3.02709e-05 3.01362e-05 2.98552e-05 2.94932e-05 2.91126e-05 2.87803e-05 2.85117e-05 2.82688e-05 2.80199e-05 2.77452e-05 2.7433e-05 2.70682e-05 2.66315e-05 2.61223e-05 2.55049e-05 2.47545e-05 2.38671e-05 2.28226e-05 2.15639e-05 2.00765e-05 2.6792e-05 2.76115e-05 2.83833e-05 2.8979e-05 2.93943e-05 2.96245e-05 2.96558e-05 2.95279e-05 2.92913e-05 2.90307e-05 2.87997e-05 2.86462e-05 2.85144e-05 2.83714e-05 2.81981e-05 2.79849e-05 2.77207e-05 2.73796e-05 2.69512e-05 2.64299e-05 2.57984e-05 2.50448e-05 2.41431e-05 2.30553e-05 2.17154e-05 2.54805e-05 2.6199e-05 2.70013e-05 2.77224e-05 2.83283e-05 2.87694e-05 2.89949e-05 2.90648e-05 2.8998e-05 2.88552e-05 2.87233e-05 2.86584e-05 2.86322e-05 2.85987e-05 2.85283e-05 2.84074e-05 2.82232e-05 2.79597e-05 2.76031e-05 2.71505e-05 2.66012e-05 2.59672e-05 2.52174e-05 2.43576e-05 2.34071e-05 2.33857e-05 2.42552e-05 2.52475e-05 2.61635e-05 2.69922e-05 2.76563e-05 2.81105e-05 2.8363e-05 2.84965e-05 2.85216e-05 2.85024e-05 2.85174e-05 2.85746e-05 2.8647e-05 2.8683e-05 2.86596e-05 2.85597e-05 2.83666e-05 2.80695e-05 2.76678e-05 2.71598e-05 2.65456e-05 2.58229e-05 2.50125e-05 2.42037e-05 2.09813e-05 2.21003e-05 2.33173e-05 2.44287e-05 2.54443e-05 2.63014e-05 2.69647e-05 2.74204e-05 2.7722e-05 2.79307e-05 2.80698e-05 2.81944e-05 2.83541e-05 2.85087e-05 2.86538e-05 2.87433e-05 2.87358e-05 2.86171e-05 2.83786e-05 2.80194e-05 2.75386e-05 2.6934e-05 2.6192e-05 2.53295e-05 2.44656e-05 1.87647e-05 2.02405e-05 2.16179e-05 2.28452e-05 2.39393e-05 2.48735e-05 2.56439e-05 2.62522e-05 2.67123e-05 2.70917e-05 2.74025e-05 2.76737e-05 2.79468e-05 2.82328e-05 2.84915e-05 2.86791e-05 2.87645e-05 2.87308e-05 2.85473e-05 2.82254e-05 2.77648e-05 2.71637e-05 2.6422e-05 2.55379e-05 2.46611e-05 1.79731e-05 1.94552e-05 2.08349e-05 2.20002e-05 2.30421e-05 2.39281e-05 2.46765e-05 2.53102e-05 2.58448e-05 2.63086e-05 2.67182e-05 2.71051e-05 2.7485e-05 2.78778e-05 2.82504e-05 2.85391e-05 2.86993e-05 2.8721e-05 2.85914e-05 2.82984e-05 2.78497e-05 2.72456e-05 2.64985e-05 2.56168e-05 2.47257e-05 1.77096e-05 1.93676e-05 2.08432e-05 2.20618e-05 2.30378e-05 2.38203e-05 2.4428e-05 2.49368e-05 2.53828e-05 2.57946e-05 2.62027e-05 2.66661e-05 2.71423e-05 2.76285e-05 2.80522e-05 2.83881e-05 2.85944e-05 2.86387e-05 2.85375e-05 2.82682e-05 2.78379e-05 2.72501e-05 2.65153e-05 2.56877e-05 2.48362e-05 1.85077e-05 2.02962e-05 2.1819e-05 2.29757e-05 2.38199e-05 2.44472e-05 2.48764e-05 2.52013e-05 2.54914e-05 2.57949e-05 2.6158e-05 2.65926e-05 2.70647e-05 2.75178e-05 2.79445e-05 2.82802e-05 2.84848e-05 2.85366e-05 2.84484e-05 2.82041e-05 2.78028e-05 2.72479e-05 2.65531e-05 2.57958e-05 2.50176e-05 2.01345e-05 2.20863e-05 2.34957e-05 2.44514e-05 2.50537e-05 2.54213e-05 2.55894e-05 2.56834e-05 2.57984e-05 2.59968e-05 2.62918e-05 2.66624e-05 2.70901e-05 2.75285e-05 2.79206e-05 2.82258e-05 2.84144e-05 2.84735e-05 2.84003e-05 2.81917e-05 2.78387e-05 2.73424e-05 2.67131e-05 2.60325e-05 2.53169e-05 2.31491e-05 2.46069e-05 2.55004e-05 2.60516e-05 2.63437e-05 2.64328e-05 2.63918e-05 2.62982e-05 2.625e-05 2.63195e-05 2.65261e-05 2.68464e-05 2.7217e-05 2.7599e-05 2.79528e-05 2.82217e-05 2.84027e-05 2.84845e-05 2.84705e-05 2.83395e-05 2.80694e-05 2.76612e-05 2.71124e-05 2.65108e-05 2.58529e-05 2.61374e-05 2.68252e-05 2.72029e-05 2.73736e-05 2.73627e-05 2.72255e-05 2.7002e-05 2.68034e-05 2.66823e-05 2.66794e-05 2.68123e-05 2.7053e-05 2.73632e-05 2.76919e-05 2.80058e-05 2.82682e-05 2.85026e-05 2.86845e-05 2.87869e-05 2.87786e-05 2.86372e-05 2.83406e-05 2.78802e-05 2.73555e-05 2.67325e-05 2.80525e-05 2.83729e-05 2.84251e-05 2.8323e-05 2.80916e-05 2.77778e-05 2.74715e-05 2.71968e-05 2.704e-05 2.69957e-05 2.70671e-05 2.72444e-05 2.74992e-05 2.78063e-05 2.81509e-05 2.85e-05 2.88606e-05 2.91983e-05 2.94735e-05 2.964e-05 2.96613e-05 2.95118e-05 2.91628e-05 2.87191e-05 2.8139e-05 2.98116e-05 2.97127e-05 2.94381e-05 2.9085e-05 2.86487e-05 2.82123e-05 2.78227e-05 2.75179e-05 2.73294e-05 2.7274e-05 2.73298e-05 2.74814e-05 2.77304e-05 2.80828e-05 2.85066e-05 2.89951e-05 2.95454e-05 3.01195e-05 3.06522e-05 3.10619e-05 3.12917e-05 3.13147e-05 3.10852e-05 3.07207e-05 3.01729e-05 3.1426e-05 3.09316e-05 3.03834e-05 2.98145e-05 2.92173e-05 2.86691e-05 2.82195e-05 2.78913e-05 2.76876e-05 2.7622e-05 2.76717e-05 2.78497e-05 2.81573e-05 2.85885e-05 2.91568e-05 2.98693e-05 3.07095e-05 3.16132e-05 3.24712e-05 3.31798e-05 3.36658e-05 3.38779e-05 3.3773e-05 3.34769e-05 3.29349e-05 3.29631e-05 3.21904e-05 3.14551e-05 3.07497e-05 3.0047e-05 2.94265e-05 2.89435e-05 2.86062e-05 2.84107e-05 2.83311e-05 2.83971e-05 2.86211e-05 2.9017e-05 2.96055e-05 3.04106e-05 3.14399e-05 3.26496e-05 3.39326e-05 3.51584e-05 3.6197e-05 3.69507e-05 3.73561e-05 3.73707e-05 3.71296e-05 3.65774e-05 3.44663e-05 3.37269e-05 3.30084e-05 3.23165e-05 3.1635e-05 3.10312e-05 3.05345e-05 3.01523e-05 2.99268e-05 2.98632e-05 2.99793e-05 3.02986e-05 3.08557e-05 3.16873e-05 3.28089e-05 3.41949e-05 3.57688e-05 3.74136e-05 3.89782e-05 4.03113e-05 4.12992e-05 4.18816e-05 4.2015e-05 4.18286e-05 4.12665e-05 3.67308e-05 3.61183e-05 3.55384e-05 3.49979e-05 3.44599e-05 3.39671e-05 3.35516e-05 3.32495e-05 3.30874e-05 3.30947e-05 3.33125e-05 3.37835e-05 3.45443e-05 3.56157e-05 3.6997e-05 3.86507e-05 4.04938e-05 4.23841e-05 4.41776e-05 4.57141e-05 4.68697e-05 4.75877e-05 4.78253e-05 4.76914e-05 4.71261e-05 4.01834e-05 3.97256e-05 3.9414e-05 3.91816e-05 3.89552e-05 3.8753e-05 3.85861e-05 3.84848e-05 3.84885e-05 3.86451e-05 3.90071e-05 3.96243e-05 4.05339e-05 4.17552e-05 4.32778e-05 4.50538e-05 4.69925e-05 4.89754e-05 5.08545e-05 5.24788e-05 5.37268e-05 5.45415e-05 5.48829e-05 5.48264e-05 5.43019e-05 4.46737e-05 4.45357e-05 4.47172e-05 4.50128e-05 4.52844e-05 4.55116e-05 4.57003e-05 4.58895e-05 4.613e-05 4.648e-05 4.69982e-05 4.77369e-05 4.87324e-05 5.00003e-05 5.15296e-05 5.32768e-05 5.51511e-05 5.70661e-05 5.88931e-05 6.05017e-05 6.17865e-05 6.26895e-05 6.31741e-05 6.3274e-05 6.28989e-05 4.96101e-05 5.03035e-05 5.13401e-05 5.23944e-05 5.33167e-05 5.4067e-05 5.46683e-05 5.51763e-05 5.56578e-05 5.6182e-05 5.68134e-05 5.76066e-05 5.85981e-05 5.98009e-05 6.12088e-05 6.27908e-05 6.44884e-05 6.62222e-05 6.79081e-05 6.9447e-05 7.07596e-05 7.17943e-05 7.25127e-05 7.29045e-05 7.28415e-05 5.52263e-05 5.74242e-05 5.95082e-05 6.12786e-05 6.27312e-05 6.38967e-05 6.48218e-05 6.55748e-05 6.62317e-05 6.68657e-05 6.75418e-05 6.83145e-05 6.92189e-05 7.02692e-05 7.14634e-05 7.27861e-05 7.42268e-05 7.5734e-05 7.72518e-05 7.87242e-05 8.01085e-05 8.13766e-05 8.24846e-05 8.33742e-05 8.38274e-05 6.46709e-05 6.74168e-05 6.96998e-05 7.15591e-05 7.30752e-05 7.43067e-05 7.53084e-05 7.61381e-05 7.68542e-05 7.75133e-05 7.81673e-05 7.8859e-05 7.962e-05 8.04672e-05 8.14085e-05 8.24448e-05 8.35771e-05 8.48043e-05 8.61154e-05 8.75149e-05 8.90216e-05 9.0656e-05 9.24162e-05 9.42544e-05 9.58228e-05 7.84723e-05 7.95727e-05 8.0793e-05 8.20334e-05 8.32108e-05 8.42621e-05 8.51744e-05 8.59521e-05 8.66227e-05 8.72361e-05 8.78277e-05 8.84162e-05 8.90071e-05 8.96161e-05 9.0264e-05 9.09642e-05 9.17268e-05 9.25844e-05 9.35761e-05 9.47659e-05 9.62592e-05 9.8199e-05 0.000100797 0.00010429 0.000108454 9.03328e-05 8.9144e-05 8.94477e-05 9.03688e-05 9.14551e-05 9.25063e-05 9.34525e-05 9.42699e-05 9.49559e-05 9.55461e-05 9.6063e-05 9.65085e-05 9.68849e-05 9.72306e-05 9.75753e-05 9.79227e-05 9.82635e-05 9.86077e-05 9.90044e-05 9.95322e-05 0.000100344 0.000101728 0.000104238 0.000108792 0.000116134 8.76686e-05 9.03673e-05 9.32223e-05 9.57052e-05 9.76542e-05 9.91385e-05 0.00010031 0.000101308 0.000102096 0.000102688 0.000103114 0.00010335 0.000103436 0.000103533 0.000103634 0.00010373 0.000103689 0.000103445 0.000102999 0.000102359 0.000101555 0.000100736 0.000100305 0.000101191 0.000104993 7.46429e-05 8.90068e-05 9.72077e-05 0.000102093 0.000104813 0.000106299 0.000107169 0.00010824 0.000108977 0.000109472 0.000109746 0.000109714 0.000109269 0.00010934 0.00010924 0.000109393 0.000109147 0.000108488 0.000107405 0.000105819 0.0001036 0.000100327 9.53059e-05 8.69462e-05 7.27113e-05 0.000140972 0.000126314 0.000121735 0.000119826 0.000118818 0.000118304 0.000118099 0.000118325 0.000118558 0.000118774 0.000118852 0.00011871 0.000118285 0.000118052 0.000117912 0.000117941 0.000117614 0.000116966 0.000116125 0.000115164 0.000114261 0.00011353 0.000113517 0.000114561 0.000118728 0.000312891 0.000190444 0.000155767 0.000139615 0.000132352 0.00012899 0.000126825 0.000125088 0.000123902 0.000123596 0.000123785 0.000124457 0.000125203 0.000125367 0.000124885 0.000123754 0.000122446 0.000121539 0.000120943 0.000120919 0.000122797 0.000126887 0.000136488 0.000164649 0.000276392 0.00102179 0.000400327 0.000245804 0.000181812 0.000156119 0.00014646 0.000140564 0.000136643 0.000133796 0.000132305 0.00013185 0.000131928 0.000132632 0.000133084 0.000132804 0.00013161 0.0001297 0.00012838 0.000128204 0.000129105 0.000132552 0.000143293 0.00017512 0.00031204 0.00102452 0.000846088 0.000404358 0.00022676 0.000178009 0.000149414 0.000133054 0.000122478 0.000119302 0.000119701 0.000125916 0.000134883 0.000139821 0.000141495 0.000138458 0.00013097 0.000122399 0.000111415 0.000105975 0.000108953 0.000118858 0.000129806 0.000149434 0.000203954 0.000420321 0.00114763 0.000708361 0.000285133 0.000161271 0.000102773 7.59322e-05 6.205e-05 5.73268e-05 5.79982e-05 7.07678e-05 8.65747e-05 9.50961e-05 9.75581e-05 9.13624e-05 7.64317e-05 5.76936e-05 4.39835e-05 2.47831e-05 1.54207e-05 1.58141e-05 2.24532e-05 4.11772e-05 7.92945e-05 0.000181921 0.000345823 0.000586615 0.000332669 0.000182632 6.15148e-05 3.45787e-05 2.10637e-05 1.53762e-05 1.42238e-05 1.60112e-05 2.33298e-05 3.03749e-05 3.29844e-05 3.31075e-05 2.68517e-05 1.38967e-05 4.15681e-06 6.2309e-07 2.43053e-07 1.3973e-07 1.77062e-07 3.63865e-07 1.73323e-06 1.45166e-05 6.29232e-05 0.000217463 0.000313548 0.000132922 8.41436e-05 2.55298e-05 7.6787e-06 3.30829e-06 2.22859e-06 2.09758e-06 2.40926e-06 3.61939e-06 4.83921e-06 5.21063e-06 4.66371e-06 2.83714e-06 6.44257e-07 2.16272e-08 2.05807e-08 2.13047e-08 2.32058e-08 2.8265e-08 5.79473e-08 2.06513e-07 3.00599e-06 2.62691e-05 9.96468e-05 0.000141415 ) ; boundaryField { inlet { type calculated; value nonuniform List<scalar> 25 ( 2.0194e-08 2.01945e-08 2.01944e-08 2.0194e-08 2.01933e-08 2.01923e-08 2.01912e-08 2.01899e-08 2.01886e-08 2.01874e-08 2.01864e-08 2.01856e-08 2.0185e-08 2.01845e-08 2.01844e-08 2.01846e-08 2.0185e-08 2.01855e-08 2.0186e-08 2.01867e-08 2.01873e-08 2.01878e-08 2.01883e-08 2.01888e-08 2.01897e-08 ) ; } outlet { type calculated; value nonuniform List<scalar> 25 ( 0.000132885 8.41149e-05 2.55237e-05 7.68029e-06 3.30911e-06 2.22912e-06 2.0981e-06 2.41003e-06 3.62125e-06 4.84252e-06 5.21447e-06 4.66692e-06 2.83834e-06 6.44331e-07 1.88546e-08 1.88546e-08 1.88546e-08 1.88546e-08 1.88546e-08 1.88546e-08 1.88546e-08 1.88546e-08 2.62638e-05 9.96192e-05 0.000141383 ) ; } walls { type nutkWallFunction; Cmu 0.09; kappa 0.41; E 9.8; value uniform 1e-08; } defaultFaces { type empty; } } // ************************************************************************* //
[ "mizuha.watanabe@gmail.com" ]
mizuha.watanabe@gmail.com
9f51b3109c3af84fbeb693e37db516893d17a230
f7344a0fc96c07c777c13df261b796f49db5e445
/Cubo/headers/Shader.h
a4e7eafdb39cc69bfecc50ce873ba016864bd530
[ "MIT" ]
permissive
alencarrh/unisinos-computacao-grafica
e9e719b2d199c0b49fb223ba6c49f519dd094dd1
b7ea6b46956e47f695e4437fe254fd974a2b90de
refs/heads/master
2022-10-20T15:56:59.873806
2018-12-05T23:34:04
2018-12-06T11:39:33
145,136,103
0
0
MIT
2022-09-23T19:47:36
2018-08-17T15:18:11
C
UTF-8
C++
false
false
835
h
#ifndef SHADER_H #define SHADER_H #include <GL\glew.h> #include <GLFW\glfw3.h> #include <string> #include <fstream> #include <sstream> #include <iostream> class Shader { public: // the program ID unsigned int ID; // constructor reads and builds the shader Shader(const GLchar* vertexPath, const GLchar* fragmentPath); // use/activate the shader void use(); // utility uniform functions void setBool(const std::string& name, bool value) const; void setInt(const std::string& name, int value) const; void setFloat(const std::string& name, float value) const; void setMatrix4fv(const std::string& name, float matrix[]) const; void setMat4(const std::string& name, glm::mat4& mat) const; private: static void checkCompileErrors(unsigned int shader, std::string type); }; #endif
[ "alencarhentges@gmail.com" ]
alencarhentges@gmail.com
1572c27cda6847e3fa30aef4d0809cc2b508ab55
07ee17f9fb57c0ccc9e4fe2c18410bd3f3eeec34
/program/code/Door.cpp
ae95632f58319fa9ff305b182e2bfd90b7459729
[]
no_license
AlexHuck/TribesRebirth
1ea6ba27bc2af10527259d4d6cd4561a1793bccd
cf52c2e8c63f3da79e38cb3c153288d12003b123
refs/heads/master
2021-09-11T00:35:45.407177
2021-08-29T14:36:56
2021-08-29T14:36:56
226,741,338
0
0
null
2019-12-08T22:30:13
2019-12-08T22:30:12
null
UTF-8
C++
false
false
840
cpp
#include <door.h> #include <feardcl.h> #include <datablockmanager.h> #include <console.h> Door::Door() : MoveableBase() { } Door::~Door() { } int Door::getDatGroup() { return (DataBlockManager::DoorDataType); } IMPLEMENT_PERSISTENT_TAGS(Door, FOURCC('D', 'O', 'O', 'R'), DoorPersTag); Persistent::Base::Error Door::read(StreamIO &sio, int iVer, int iUsr) { return (Parent::read(sio, iVer, iUsr)); } Persistent::Base::Error Door::write(StreamIO &sio, int iVer, int iUsr) { return (Parent::write(sio, iVer, iUsr)); } void Door::onFirst() { if (const char *lpcszScript = scriptName("onClose")) { Console->executef(3, lpcszScript, scriptThis(), getId()); } } void Door::onLast() { if (const char *lpcszScript = scriptName("onOpen")) { Console->executef(3, lpcszScript, scriptThis(), getId()); } }
[ "altimormc@gmail.com" ]
altimormc@gmail.com
f529471a190818da5cc6df9d843dda7f370f8b7b
fab985c601e2d83966fc0230f3bc523272c6babe
/src/game_renderer.cpp
bcd1b97b7cbe04b4b851ae563b54e0486dd14907
[]
no_license
Desty-3000/Minestorm
bcb720a975b7d4ea7dde2702f0eaf0c1be96fa2f
407363859079d780ab40606fce79e67460c29610
refs/heads/main
2023-01-19T14:18:14.863904
2020-11-24T16:16:15
2020-11-24T16:16:15
315,663,422
0
0
null
null
null
null
UTF-8
C++
false
false
4,221
cpp
#include "game_renderer.h" #include "entity.h" #include "player.h" #include "projectile.h" #include "mines.h" #include <iostream> GameRenderer::GameRenderer() // Load ressources from files { m_mapBackground = LoadTexture("Assets/minestorm_background.png"); m_mapForground = LoadTexture("Assets/minestorm_forground.png"); m_tileset = LoadTexture("Assets/minestorm_sprite_atlas_mine_storm.png"); } GameRenderer::~GameRenderer() // Unload ressources { UnloadTexture(m_mapBackground); UnloadTexture(m_mapForground); UnloadTexture(m_tileset); } void GameRenderer::drawMap() { DrawTexture(m_mapBackground, 0, 0, WHITE); } void GameRenderer::drawBorder() { DrawTexture(m_mapForground, 0, 0, WHITE); } void GameRenderer::drawEntityDebug(Entity* entity) { Collider col = entity->m_collider; //Collisions Lines for (int i = 0; i < col.m_edges.size(); i++) { int y = i + 1; DrawLine((int)col.m_edges[i].x, (int)col.m_edges[i].y, (int)col.m_edges[y % col.m_edges.size()].x, (int)col.m_edges[y % col.m_edges.size()].y, (col.overlap ? RED : LIME)); DrawPixel((int)col.m_edges[i].x, (int)col.m_edges[i].y, GREEN); } //Center DrawPixel((int)col.center.x,(int) col.center.y, RED); //Direction line DrawLine((int)col.center.x, (int)col.center.y, (int)(col.center.x + (20 * entity->getDirection().x)) , (int)(col.center.y + (30 * entity->getDirection().y)), YELLOW); } void GameRenderer::drawEntity(Entity* entity) { int size = (int)entity->m_size; Rectangle tileRect = { (float)(1 + entity->m_sprite.tileColumn * 256.f),(float)entity->m_sprite.tileLine * 256.f, 256.f, 256.f}; Rectangle destRect = { entity->getCenter().x, entity->getCenter().y, 50.f * size, 50.f * size }; Vector2 origin = { 25.f * size, 25.f * size }; DrawTexturePro(m_tileset, tileRect, destRect, origin, entity->m_rotation, entity->m_sprite.color); } void GameRenderer::drawProjectile(Projectile* projectile) { Rectangle tileRect = { (float)projectile->m_sprite.tileColumn * 256.f, (float)projectile->m_sprite.tileLine * 256.f, 256, 256 }; Rectangle destRect = { projectile->getCenter().x, projectile->getCenter().y, 50.f, 50.f }; Vector2 origin = { 25.f, 25.f}; DrawTexturePro(m_tileset, tileRect, destRect, origin, 0, projectile->m_parent->m_spaceShip->m_sprite.color); } void GameRenderer::drawPlayerInfo(PlayerController* player, int padding) { for (int i = 0; i < player->m_spaceShip->getLife(); i++) { Rectangle tileRect = { 0, 0, 256, 256 }; Rectangle destRect {}; if(padding > 0) destRect = { 40.f + 30.f * i, 770.f, 60.f, 60.f}; else destRect = { 600.f - 30.f * i, 770.f, 60.f, 60.f }; //clignotement avec un modulo des familles sur l invicinbilite if (player->m_spaceShip->getInvicibilityTime() < 1.f || (int)(player->m_spaceShip->getInvicibilityTime() * 10.f) % 4 == 0) DrawTexturePro(m_tileset, tileRect, destRect, {25.f, 25.f}, 0, player->m_spaceShip->m_sprite.color); DrawText("Pause/Resume - [Space]", 200, 5, 20, LIME); } } void GameRenderer::drawSpawnPoint(EnemySpawnPoint* spawnPoint) { Rectangle tileRect = { 256, 0, 256, 256 }; Rectangle destRect = {spawnPoint->m_position.x, spawnPoint->m_position.y , 50.f, 50.f}; Vector2 origin = {25.f, 25.f}; DrawTexturePro(m_tileset, tileRect, destRect, origin, 0, RED); } void GameRenderer::drawScore(float2 position,int score) { DrawText("Score :", (int) position.x, (int)position.y, 20, LIME); std::string scoreS = std::to_string(score); DrawText(scoreS.c_str(), (int)position.x + 80, (int)position.y, 20, LIME); } void GameRenderer::drawMainMenu() { DrawText("Start New Game :", 150, 200, 40, RAYWHITE); DrawText("Singleplayer - [F]", 180, 300, 30, SKYBLUE); DrawText("Cooperation - [K]", 180, 350, 30, RED); DrawText("Quit - [Esc]", 255, 635, 20, DARKGRAY); } void GameRenderer::drawGameOver() { DrawText("GAME OVER", 190, 200, 40, RED); DrawText("Back to Main Menu - [Esc]", 180, 635, 20, DARKGRAY); } void GameRenderer::drawPauseMenu() { drawBorder(); DrawText("Game Paused", 190, 200, 40, RAYWHITE); DrawText("Back to Main Menu - [Esc]", 180, 635, 20, DARKGRAY); }
[ "noreply@github.com" ]
noreply@github.com
f210c18a6f23e96c936eb50dd86310dc54350c0d
1e4d0e370cefce365122d816ce56f54ba1f798c3
/Surgery.h
9b8854ab7a089b9e22b937843c5facac9186b57d
[]
no_license
sxj9880/hospitalStay
92973fa211c2b1d9297a4f169db0bde657871f5d
ba1f21e6cb1e80c4a3dc6f19658501d5e6af5de0
refs/heads/master
2016-08-09T04:24:40.757137
2016-03-28T02:13:20
2016-03-28T02:13:20
54,858,920
0
0
null
null
null
null
UTF-8
C++
false
false
192
h
#pragma once #ifndef SURGERY_H #define SURGERY_H class Surgery { private: int tonsillectomy; int foot; int knee; int shoulder; int appendectomy; public: Surgery(); }; #endif SURGERY_H
[ "sxj9880@sru.edu" ]
sxj9880@sru.edu
ea28bf645e1fbc110bd6e1dd28f8bee62b2d1026
5bd2afeded6a39311403641533f9a8798582b5c6
/codeforces/1096/G.cpp
499e6506af0e5de5e088bed3958340a33a2c4dba
[]
no_license
ShahjalalShohag/ProblemSolving
19109c35fc1a38b7a895dbc4d95cbb89385b895b
3df122f13808681506839f81b06d507ae7fc17e0
refs/heads/master
2023-02-06T09:28:43.118420
2019-01-06T11:09:00
2020-12-27T14:35:25
323,168,270
31
16
null
null
null
null
UTF-8
C++
false
false
8,859
cpp
//#pragma comment(linker, "/stack:200000000") //#pragma GCC optimize("Ofast") //#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native") //#pragma GCC optimize("unroll-loops") #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; using namespace std; #define ll long long #define ull unsigned long long #define ld long double #define pii pair<int,int> #define pll pair<ll,ll> #define vi vector<int> #define vll vector<ll> #define vc vector<char> #define vs vector<string> #define vpll vector<pll> #define vpii vector<pii> #define umap unordered_map #define uset unordered_set #define PQ priority_queue #define printa(a,L,R) for(int i=L;i<R;i++) cout<<a[i]<<(i==R-1?'\n':' ') #define printv(a) printa(a,0,a.size()) #define print2d(a,r,c) for(int i=0;i<r;i++) for(int j=0;j<c;j++) cout<<a[i][j]<<(j==c-1?'\n':' ') #define pb push_back #define eb emplace_back #define mt make_tuple #define fbo find_by_order #define ook order_of_key #define MP make_pair #define UB upper_bound #define LB lower_bound #define SQ(x) ((x)*(x)) #define issq(x) (((ll)(sqrt((x))))*((ll)(sqrt((x))))==(x)) #define F first #define S second #define mem(a,x) memset(a,x,sizeof(a)) #define inf 1e18 #define E 2.71828182845904523536 #define gamma 0.5772156649 #define nl "\n" #define lg(r,n) (int)(log2(n)/log2(r)) #define pf printf #define sf scanf #define sf1(a) scanf("%d",&a) #define sf2(a,b) scanf("%d %d",&a,&b) #define sf3(a,b,c) scanf("%d %d %d",&a,&b,&c) #define pf1(a) printf("%d\n",a); #define pf2(a,b) printf("%d %d\n",a,b) #define pf3(a,b,c) printf("%d %d %d\n",a,b,c) #define sf1ll(a) scanf("%lld",&a) #define sf2ll(a,b) scanf("%I64d %I64d",&a,&b) #define sf3ll(a,b,c) scanf("%I64d %I64d %I64d",&a,&b,&c) #define pf1ll(a) printf("%lld\n",a); #define pf2ll(a,b) printf("%I64d %I64d\n",a,b) #define pf3ll(a,b,c) printf("%I64d %I64d %I64d\n",a,b,c) #define _ccase printf("Case %lld: ",++cs) #define _case cout<<"Case "<<++cs<<": " #define by(x) [](const auto& a, const auto& b) { return a.x < b.x; } #define asche cerr<<"Ekhane asche\n"; #define rev(v) reverse(v.begin(),v.end()) #define srt(v) sort(v.begin(),v.end()) #define grtsrt(v) sort(v.begin(),v.end(),greater<ll>()) #define all(v) v.begin(),v.end() #define mnv(v) *min_element(v.begin(),v.end()) #define mxv(v) *max_element(v.begin(),v.end()) #define toint(a) atoi(a.c_str()) #define BeatMeScanf ios_base::sync_with_stdio(false) #define valid(tx,ty) (tx>=0&&tx<n&&ty>=0&&ty<m) #define one(x) __builtin_popcount(x) #define Unique(v) v.erase(unique(all(v)),v.end()) #define stree l=(n<<1),r=l+1,mid=b+(e-b)/2 #define fout(x) fixed<<setprecision(x) string tostr(int n) {stringstream rr;rr<<n;return rr.str();} inline void yes(){cout<<"YES\n";exit(0);} inline void no(){cout<<"NO\n";exit(0);} template <typename T> using o_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; //ll dx[]={1,0,-1,0,1,-1,-1,1}; //ll dy[]={0,1,0,-1,1,1,-1,-1}; //random_device rd; //mt19937 random(rd()); #define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); deb(_it, args); } void deb(istream_iterator<string> it) {} template<typename T, typename... Args> void deb(istream_iterator<string> it, T a, Args... args) { cerr << *it << " = " << a << endl; deb(++it, args...); } const int N=2e5+9; const ld eps=1e-9; const double PI = acos(-1); //ll gcd(ll a,ll b){while(b){ll x=a%b;a=b;b=x;}return a;} //ll lcm(ll a,ll b){return a/gcd(a,b)*b;} //ll qpow(ll n,ll k) {ll ans=1;assert(k>=0);n%=mod;while(k>0){if(k&1) ans=(ans*n)%mod;n=(n*n)%mod;k>>=1;}return ans%mod;} namespace ntt { struct num { double x,y; num() {x=y=0;} num(double x,double y):x(x),y(y){} }; inline num operator+(num a,num b) {return num(a.x+b.x,a.y+b.y);} inline num operator-(num a,num b) {return num(a.x-b.x,a.y-b.y);} inline num operator*(num a,num b) {return num(a.x*b.x-a.y*b.y,a.x*b.y+a.y*b.x);} inline num conj(num a) {return num(a.x,-a.y);} int base=1; vector<num> roots={{0,0},{1,0}}; vector<int> rev={0,1}; const double PI=acosl(-1.0); void ensure_base(int nbase) { if(nbase<=base) return; rev.resize(1<<nbase); for(int i=0;i<(1<<nbase);i++) rev[i]=(rev[i>>1]>>1)+((i&1)<<(nbase-1)); roots.resize(1<<nbase); while(base<nbase) { double angle=2*PI/(1<<(base+1)); for(int i=1<<(base-1);i<(1<<base);i++) { roots[i<<1]=roots[i]; double angle_i=angle*(2*i+1-(1<<base)); roots[(i<<1)+1]=num(cos(angle_i),sin(angle_i)); } base++; } } void fft(vector<num> &a,int n=-1) { if(n==-1) n=a.size(); assert((n&(n-1))==0); int zeros=__builtin_ctz(n); ensure_base(zeros); int shift=base-zeros; for(int i=0;i<n;i++) if(i<(rev[i]>>shift)) swap(a[i],a[rev[i]>>shift]); for(int k=1;k<n;k<<=1) { for(int i=0;i<n;i+=2*k) { for(int j=0;j<k;j++) { num z=a[i+j+k]*roots[j+k]; a[i+j+k]=a[i+j]-z; a[i+j]=a[i+j]+z; } } } } vector<num> fa,fb; vector<int> multiply(vector<int> &a, vector<int> &b) { int need=a.size()+b.size()-1; int nbase=0; while((1<<nbase)<need) nbase++; ensure_base(nbase); int sz=1<<nbase; if(sz>(int)fa.size()) fa.resize(sz); for(int i=0;i<sz;i++) { int x=(i<(int)a.size()?a[i]:0); int y=(i<(int)b.size()?b[i]:0); fa[i]=num(x,y); } fft(fa,sz); num r(0,-0.25/sz); for(int i=0;i<=(sz>>1);i++) { int j=(sz-i)&(sz-1); num z=(fa[j]*fa[j]-conj(fa[i]*fa[i]))*r; if(i!=j) fa[j]=(fa[i]*fa[i]-conj(fa[j]*fa[j]))*r; fa[i]=z; } fft(fa,sz); vector<int> res(need); for(int i=0;i<need;i++) res[i]=fa[i].x+0.5; return res; } vector<int> multiply(vector<int> &a,vector<int> &b,int m,int eq=0) { int need=a.size()+b.size()-1; int nbase=0; while((1<<nbase)<need) nbase++; ensure_base(nbase); int sz=1<<nbase; if(sz>(int)fa.size()) fa.resize(sz); for(int i=0;i<(int)a.size();i++) { int x=(a[i]%m+m)%m; fa[i]=num(x&((1<<15)-1),x>>15); } fill(fa.begin()+a.size(),fa.begin()+sz,num{0,0}); fft(fa,sz); if(sz>(int)fb.size()) fb.resize(sz); if(eq) copy(fa.begin(),fa.begin()+sz,fb.begin()); else { for(int i=0;i<(int)b.size();i++) { int x=(b[i]%m+m)%m; fb[i]=num(x&((1<<15)-1),x>>15); } fill(fb.begin()+b.size(),fb.begin()+sz,num{0,0}); fft(fb,sz); } double ratio=0.25/sz; num r2(0,-1),r3(ratio,0),r4(0,-ratio),r5(0,1); for(int i=0;i<=(sz>>1);i++) { int j=(sz-i)&(sz-1); num a1=(fa[i]+conj(fa[j])); num a2=(fa[i]-conj(fa[j]))*r2; num b1=(fb[i]+conj(fb[j]))*r3; num b2=(fb[i]-conj(fb[j]))*r4; if(i!=j) { num c1=(fa[j]+conj(fa[i])); num c2=(fa[j]-conj(fa[i]))*r2; num d1=(fb[j]+conj(fb[i]))*r3; num d2=(fb[j]-conj(fb[i]))*r4; fa[i]=c1*d1+c2*d2*r5; fb[i]=c1*d2+c2*d1; } fa[j]=a1*b1+a2*b2*r5; fb[j]=a1*b2+a2*b1; } fft(fa,sz);fft(fb,sz); vector<int> res(need); for(int i=0;i<need;i++) { ll aa=fa[i].x+0.5; ll bb=fb[i].x+0.5; ll cc=fa[i].y+0.5; res[i]=(aa+((bb%m)<<15)+((cc%m)<<30))%m; } return res; } vector<int> square(vector<int> &a,int m) { return multiply(a,a,m,1); } }; int mod; vi pow(vi& a,int p) { vi res; res.eb(1); while(p){ if(p&1) res=ntt::multiply(res,a,mod); a=ntt::square(a,mod); p>>=1; } return res; } int main() { BeatMeScanf; int i,j,k,n,m; mod=998244353; cin>>n>>k; vi a(10,0); while(k--){ cin>>m; a[m]=1; } vi ans=pow(a,n/2); int res=0; for(auto x:ans){ res=(res+1LL*x*x%mod)%mod; } cout<<res<<nl; return 0; }
[ "shahjalalshohag2014@gmail.com" ]
shahjalalshohag2014@gmail.com
10d745faf4cb335e95e7e4f5957f5916394b6a22
cd430695f2165855d4d9462557f8480896a234f0
/bluffcode/cfra.cpp
953e7d447df6a0271c96acf461e8a997ec70bc74
[]
no_license
lanctot/iioos
c0b5106ffd7e34954ab0e6615d0e404f036c32c3
14a13a78e08aae9038f392a0e158d67a524e3ce7
refs/heads/master
2021-01-25T05:34:40.985244
2015-02-20T12:39:40
2015-02-20T12:39:40
12,194,197
2
0
null
null
null
null
UTF-8
C++
false
false
8,154
cpp
#include <cstdlib> #include <iostream> #include <string> #include <cassert> #include "bluff.h" using namespace std; extern InfosetStore issfull; extern int RECALL; extern bool absAvgFullISS; static unsigned long long nextReport = 100; static unsigned long long reportMult = 2; double cfra(GameState & gs, int player, int depth, unsigned long long bidseq, double reach1, double reach2, double chanceReach, int phase, int updatePlayer) { // at terminal node? if (terminal(gs)) return payoff(gs, updatePlayer); nodesTouched++; // chance nodes (use chance sampling for imperfect recall paper) if (gs.p1roll == 0) { double EV = 0.0; for (int i = 1; i <= P1CO; i++) { GameState ngs = gs; ngs.p1roll = i; double newChanceReach = getChanceProb(1,i)*chanceReach; EV += getChanceProb(1,i)*cfra(ngs, player, depth+1, bidseq, reach1, reach2, newChanceReach, phase, updatePlayer); } return EV; } else if (gs.p2roll == 0) { double EV = 0.0; for (int i = 1; i <= P2CO; i++) { GameState ngs = gs; ngs.p2roll = i; double newChanceReach = getChanceProb(1,i)*chanceReach; EV += getChanceProb(2,i)*cfra(ngs, player, depth+1, bidseq, reach1, reach2, newChanceReach, phase, updatePlayer); } return EV; } // revert back for thesis #if 0 // sample chance if (gs.p1roll == 0) { double EV = 0.0; int outcome = 0; double prob = 0.0; sampleChanceEvent(1, outcome, prob); CHKPROBNZ(prob); assert(outcome > 0); GameState ngs = gs; ngs.p1roll = outcome; EV += cfra(ngs, player, depth+1, bidseq, reach1, reach2, chanceReach*prob, phase, updatePlayer); return EV; } else if (gs.p2roll == 0) { double EV = 0.0; int outcome = 0; double prob = 0.0; sampleChanceEvent(2, outcome, prob); CHKPROBNZ(prob); assert(outcome > 0); GameState ngs = gs; ngs.p2roll = outcome; EV += cfra(ngs, player, depth+1, bidseq, reach1, reach2, chanceReach*prob, phase, updatePlayer); return EV; } #endif // check for cuts // must include the updatePlayer if (phase == 1 && ( (player == 1 && updatePlayer == 1 && reach2 <= 0.0) || (player == 2 && updatePlayer == 2 && reach1 <= 0.0))) { phase = 2; } if (phase == 2 && ( (player == 1 && updatePlayer == 1 && reach1 <= 0.0) || (player == 2 && updatePlayer == 2 && reach2 <= 0.0))) { return 0.0; } // declare the variables Infoset is; unsigned long long infosetkey = 0; double stratEV = 0.0; int action = -1; int maxBid = (gs.curbid == 0 ? BLUFFBID-1 : BLUFFBID); int actionshere = maxBid - gs.curbid; // count the number of actions and initialize moveEVs // special case. can't just call bluff on the first move! assert(actionshere > 0); double moveEVs[actionshere]; for (int i = 0; i < actionshere; i++) moveEVs[i] = 0.0; // get the info set infosetkey = 0; getAbsInfosetKey(gs, infosetkey, player, bidseq); bool ret = iss.get(infosetkey, is, actionshere, 0); assert(ret); // iterate over the actions for (int i = gs.curbid+1; i <= maxBid; i++) { // there is a valid action here action++; assert(action < actionshere); unsigned long long newbidseq = bidseq; double moveProb = is.curMoveProbs[action]; double newreach1 = (player == 1 ? moveProb*reach1 : reach1); double newreach2 = (player == 2 ? moveProb*reach2 : reach2); GameState ngs = gs; ngs.prevbid = gs.curbid; ngs.curbid = i; ngs.callingPlayer = player; newbidseq |= (1ULL << (BLUFFBID-i)); double payoff = cfra(ngs, 3-player, depth+1, newbidseq, newreach1, newreach2, chanceReach, phase, updatePlayer); moveEVs[action] = payoff; stratEV += moveProb*payoff; } // post-traversals: update the infoset double myreach = (player == 1 ? reach1 : reach2); double oppreach = (player == 1 ? reach2 : reach1); if (phase == 1 && player == updatePlayer) // regrets { for (int a = 0; a < actionshere; a++) { is.cfr[a] += (chanceReach*oppreach)*(moveEVs[a] - stratEV); } } if (phase >= 1 && player == updatePlayer) // av. strat { unsigned long long fisk = 0; Infoset fis; if (absAvgFullISS) { bool ret = false; getInfosetKey(gs, fisk, player, bidseq); ret = issfull.get(fisk, fis, actionshere, 0); assert(ret); } assert(ret); for (int a = 0; a < actionshere; a++) { if (absAvgFullISS) fis.totalMoveProbs[a] += myreach*is.curMoveProbs[a]; else is.totalMoveProbs[a] += myreach*is.curMoveProbs[a]; } if (absAvgFullISS) issfull.put(fisk, fis, actionshere, 0); } // save the infoset back to the store if (player == updatePlayer) { totalUpdates++; iss.put(infosetkey, is, actionshere, 0); } return stratEV; } int main(int argc, char ** argv) { unsigned long long maxIters = 0; init(); if (argc < 2) { cerr << "Usage: ./cfra <recall value> <abstract infoset file> <full infoset file> [maxIters]" << endl; exit(-1); } if (argc < 3) { string recstr = argv[1]; RECALL = to_int(recstr); assert(RECALL >= 1); absInitInfosets(); exit(-1); } else { if (argc < 3) { cerr << "Usage: ./cfra <recall value> <abstract infoset file> <full infoset file> [maxIters]" << endl; exit(-1); } string recstr = argv[1]; RECALL = to_int(recstr); assert(RECALL >= 1); string filename = argv[2]; cout << "Reading the infosets from " << filename << "..." << endl; iss.readFromDisk(filename); absAvgFullISS = false; if (argc >= 4) { string filename2 = argv[3]; cout << "Reading the infosets from " << filename2 << "..." << endl; issfull.readFromDisk(filename2); absAvgFullISS = true; } if (argc >= 5) maxIters = to_ull(argv[4]); } // get the iteration string filename = argv[1]; vector<string> parts; split(parts, filename, '.'); if (parts.size() != 3 || parts[1] == "initial") iter = 1; else iter = to_ull(parts[1]); cout << "Set iteration to " << iter << endl; iter = MAX(1,iter); unsigned long long bidseq = 0; StopWatch stopwatch; double totaltime = 0; cout << "absAvgFullISS = " << absAvgFullISS << endl; cout << "CFRa; starting iterations" << endl; for (; true; iter++) { GameState gs1; bidseq = 0; double ev1 = cfra(gs1, 1, 0, bidseq, 1.0, 1.0, 1.0, 1, 1); GameState gs2; double ev2 = cfra(gs2, 1, 0, bidseq, 1.0, 1.0, 1.0, 1, 2); //cout << "time taken: " << (stopwatch.stop() - totaltime) << " seconds." << endl; //totaltime = stopwatch.stop(); sumEV1 += ev1; sumEV2 += ev2; if (iter % 100 == 0) { cout << "."; cout.flush(); totaltime += stopwatch.stop(); stopwatch.reset(); } //double b1 = 0.0, b2 = 0.0; //iss.computeBound(b1, b2); //cout << " b1 = " << b1 << ", b2 = " << b2 << ", sum = " << (b1+b2) << endl; //if (totaltime > nextCheckpoint) //if (iter >= nextReport) if (nodesTouched >= ntNextReport) { cout << endl; double conv = 0.0; double p1value = 0.0; double p2value = 0.0; conv = computeBestResponses(true, false, p1value, p2value); double R1Tplus = iter*p1value - sumEV1; if (R1Tplus <= 0.0) { R1Tplus = 0.0; } double R2Tplus = iter*p2value - sumEV2; if (R2Tplus <= 0.0) { R2Tplus = 0.0; } // Note: can't do BR on-the-fly for abstraction. Must save then import later. report( "cfra-r" + to_string(RECALL) + "-afull" + to_string(absAvgFullISS) + ".report.txt", totaltime, 0.0, 0, 0, conv, (R1Tplus+R2Tplus)/iter); //dumpInfosets("issa"); cout << endl; //nextCheckpoint += cpWidth; stopwatch.reset(); nextReport *= reportMult; ntNextReport *= ntMultiplier; } if (iter == maxIters) break; } }
[ "marc.lanctot@maastrichtuniversity.nl" ]
marc.lanctot@maastrichtuniversity.nl
31484faca3f1d9220b7d3b9cc1befdab890cd025
071a284b4eb8e59920e9877965976d8d78df8079
/lab3_WavCore/task/src/wav_core.cpp
dc88b84ebf973d42554fe06d7dc010977329d93b
[]
no_license
scrat98/OOP
0789a2572d39a01e230b667e15b65c3e18e4f2df
04bad6a2f93aaf4db5f4b0ca378339efedba9991
refs/heads/master
2021-03-24T09:50:40.802310
2017-12-09T06:49:08
2017-12-09T06:49:08
105,458,768
0
0
null
null
null
null
UTF-8
C++
false
false
11,387
cpp
#include <cstdio> #include <cstring> #include "wav_header.h" #include "wav_core.h" // TODO: Remove all 'magic' numbers // TODO: Make the code more secure. Get rid of pointers (after creating a class, of course). wav_errors_e read_header(const char *filename, wav_header_s *header_ptr) { printf( ">>>> read_header( %s )\n", filename ); null_header( header_ptr); // Fill header with zeroes. FILE* f = fopen( filename, "rb" ); if ( !f ) { return IO_ERROR; } size_t blocks_read = fread( header_ptr, sizeof(wav_header_s), 1, f); if ( blocks_read != 1 ) { // can't read header, because the file is too small. return BAD_FORMAT; } fseek( f, 0, SEEK_END ); // seek to the end of the file size_t file_size = ftell( f ); // current position is a file size! fclose( f ); if ( check_header( header_ptr, file_size ) != HEADER_OK ) { return BAD_FORMAT; } else { return WAV_OK; } } void print_info(const wav_header_s *header_ptr) { printf( "-------------------------\n" ); printf( " audioFormat %u\n", header_ptr->audioFormat ); printf( " numChannels %u\n", header_ptr->numChannels ); printf( " sampleRate %u\n", header_ptr->sampleRate ); printf( " bitsPerSample %u\n", header_ptr->bitsPerSample ); printf( " byteRate %u\n", header_ptr->byteRate ); printf( " blockAlign %u\n", header_ptr->blockAlign ); printf( " chunkSize %u\n", header_ptr->chunkSize ); printf( " subchunk1Size %u\n", header_ptr->subchunk1Size ); printf( " subchunk2Size %u\n", header_ptr->subchunk2Size ); printf( "-------------------------\n" ); } wav_errors_e extract_data_int16( const char* filename, std::vector<std::vector<short>>& channels_data ) { printf( ">>>> extract_data_int16( %s )\n", filename ); wav_errors_e err; wav_header_s header; err = read_header( filename, &header ); if ( err != WAV_OK ) { // Problems with reading a header. return err; } if ( header.bitsPerSample != 16 ) { // Only 16-bit samples is supported. return UNSUPPORTED_FORMAT; } FILE* f = fopen( filename, "rb" ); if ( !f ) { return IO_ERROR; } fseek( f, 44, SEEK_SET ); // Seek to the begining of PCM data. int chan_count = header.numChannels; int samples_per_chan = ( header.subchunk2Size / sizeof(short) ) / chan_count; // 1. Reading all PCM data from file to a single vector. std::vector<short> all_channels; all_channels.resize( chan_count * samples_per_chan ); size_t read_bytes = fread( all_channels.data(), 1, header.subchunk2Size, f ); if ( read_bytes != header.subchunk2Size ) { printf( "extract_data_int16() read only %zu of %u\n", read_bytes, header.subchunk2Size ); return IO_ERROR; } fclose( f ); // 2. Put all channels to its own vector. channels_data.resize( chan_count ); for ( size_t ch = 0; ch < channels_data.size(); ch++ ) { channels_data[ ch ].resize( samples_per_chan ); } for ( int ch = 0; ch < chan_count; ch++ ) { std::vector<short>& chdata = channels_data[ ch ]; for ( size_t i = 0; i < samples_per_chan; i++ ) { chdata[ i ] = all_channels[ chan_count * i + ch ]; } } return WAV_OK; } wav_headers_errors_e check_header( const wav_header_s *header_ptr, size_t file_size_bytes ) { // Go to wav_header.h for details if ( header_ptr->chunkId[0] != 0x52 || header_ptr->chunkId[1] != 0x49 || header_ptr->chunkId[2] != 0x46 || header_ptr->chunkId[3] != 0x46 ) { printf( "HEADER_RIFF_ERROR\n" ); return HEADER_RIFF_ERROR; } if ( header_ptr->chunkSize != file_size_bytes - 8 ) { printf( "HEADER_FILE_SIZE_ERROR\n" ); return HEADER_FILE_SIZE_ERROR; } if ( header_ptr->format[0] != 0x57 || header_ptr->format[1] != 0x41 || header_ptr->format[2] != 0x56 || header_ptr->format[3] != 0x45 ) { printf( "HEADER_WAVE_ERROR\n" ); return HEADER_WAVE_ERROR; } if ( header_ptr->subchunk1Id[0] != 0x66 || header_ptr->subchunk1Id[1] != 0x6d || header_ptr->subchunk1Id[2] != 0x74 || header_ptr->subchunk1Id[3] != 0x20 ) { printf( "HEADER_FMT_ERROR\n" ); return HEADER_FMT_ERROR; } if ( header_ptr->audioFormat != 1 ) { printf( "HEADER_NOT_PCM\n" ); return HEADER_NOT_PCM; } if ( header_ptr->subchunk1Size != 16 ) { printf( "HEADER_SUBCHUNK1_ERROR\n" ); return HEADER_SUBCHUNK1_ERROR; } if ( header_ptr->byteRate != header_ptr->sampleRate * header_ptr->numChannels * header_ptr->bitsPerSample/8 ) { printf( "HEADER_BYTES_RATE_ERROR\n" ); return HEADER_BYTES_RATE_ERROR; } if ( header_ptr->blockAlign != header_ptr->numChannels * header_ptr->bitsPerSample/8 ) { printf( "HEADER_BLOCK_ALIGN_ERROR\n" ); return HEADER_BLOCK_ALIGN_ERROR; } if ( header_ptr->subchunk2Id[0] != 0x64 || header_ptr->subchunk2Id[1] != 0x61 || header_ptr->subchunk2Id[2] != 0x74 || header_ptr->subchunk2Id[3] != 0x61 ) { printf( "HEADER_FMT_ERROR\n" ); return HEADER_FMT_ERROR; } if ( header_ptr->subchunk2Size != file_size_bytes - 44 ) { printf( "HEADER_SUBCHUNK2_SIZE_ERROR\n" ); return HEADER_SUBCHUNK2_SIZE_ERROR; } return HEADER_OK; } void prefill_header(wav_header_s *header_ptr) { // Go to wav_header.h for details header_ptr->chunkId[0] = 0x52; header_ptr->chunkId[1] = 0x49; header_ptr->chunkId[2] = 0x46; header_ptr->chunkId[3] = 0x46; header_ptr->format[0] = 0x57; header_ptr->format[1] = 0x41; header_ptr->format[2] = 0x56; header_ptr->format[3] = 0x45; header_ptr->subchunk1Id[0] = 0x66; header_ptr->subchunk1Id[1] = 0x6d; header_ptr->subchunk1Id[2] = 0x74; header_ptr->subchunk1Id[3] = 0x20; header_ptr->subchunk2Id[0] = 0x64; header_ptr->subchunk2Id[1] = 0x61; header_ptr->subchunk2Id[2] = 0x74; header_ptr->subchunk2Id[3] = 0x61; header_ptr->audioFormat = 1; header_ptr->subchunk1Size = 16; header_ptr->bitsPerSample = 16; } wav_errors_e fill_header(wav_header_s *header_ptr, int chan_count, int bits_per_sample, int sample_rate, int samples_count_per_chan) { if ( bits_per_sample != 16 ) { return UNSUPPORTED_FORMAT; } if ( chan_count < 1 ) { return BAD_PARAMS; } prefill_header( header_ptr ); int file_size_bytes = 44 + chan_count * (bits_per_sample/8) * samples_count_per_chan; header_ptr->sampleRate = sample_rate; header_ptr->numChannels = chan_count; header_ptr->bitsPerSample = 16; header_ptr->chunkSize = file_size_bytes - 8; header_ptr->subchunk2Size = file_size_bytes - 44; header_ptr->byteRate = header_ptr->sampleRate * header_ptr->numChannels * header_ptr->bitsPerSample/8; header_ptr->blockAlign = header_ptr->numChannels * header_ptr->bitsPerSample/8; return WAV_OK; } wav_errors_e make_wav_file(const char* filename, int sample_rate, const std::vector< std::vector<short> > &channels_data) { printf( ">>>> make_wav_file( %s )\n", filename ); wav_errors_e err; wav_header_s header; int chan_count = (int)channels_data.size(); if ( chan_count < 1 ) { return BAD_PARAMS; } int samples_count_per_chan = (int)channels_data[0].size(); // Verify that all channels have the same number of samples. for ( size_t ch = 0; ch < chan_count; ch++ ) { if ( channels_data[ ch ].size() != (size_t) samples_count_per_chan ) { return BAD_PARAMS; } } err = fill_header( &header, chan_count, 16, sample_rate, samples_count_per_chan ); if ( err != WAV_OK ) { return err; } std::vector<short> all_channels; all_channels.resize( chan_count * samples_count_per_chan ); for ( int ch = 0; ch < chan_count; ch++ ) { const std::vector<short>& chdata = channels_data[ ch ]; for ( size_t i = 0; i < samples_count_per_chan; i++ ) { all_channels[ chan_count * i + ch ] = chdata[ i ]; } } FILE* f = fopen( filename, "wb" ); fwrite( &header, sizeof(wav_header_s), 1, f ); fwrite( all_channels.data(), sizeof(short), all_channels.size(), f ); if ( !f ) { return IO_ERROR; } fclose( f ); return WAV_OK; } void null_header(wav_header_s *header_ptr) { memset( header_ptr, 0, sizeof(wav_header_s) ); } wav_errors_e make_mono(const std::vector<std::vector<short> > &source, std::vector< std::vector<short> > &dest_mono) { int chan_count = (int)source.size(); if ( chan_count != 2 ) { return BAD_PARAMS; } int samples_count_per_chan = (int)source[0].size(); // Verify that all channels have the same number of samples. for ( size_t ch = 0; ch < chan_count; ch++ ) { if ( source[ ch ].size() != (size_t) samples_count_per_chan ) { return BAD_PARAMS; } } dest_mono.resize( 1 ); std::vector<short>& mono = dest_mono[ 0 ]; mono.resize( samples_count_per_chan ); // Mono channel is an arithmetic mean of all (two) channels. for ( size_t i = 0; i < samples_count_per_chan; i++ ) { mono[ i ] = ( source[0][i] + source[1][i] ) / 2; } return WAV_OK; } wav_errors_e make_reverb(std::vector<std::vector<short> > &sounds, int sample_rate, double delay_seconds, float decay) { int chan_count = (int)sounds.size(); if ( chan_count < 1 ) { return BAD_PARAMS; } int samples_count_per_chan = (int)sounds[0].size(); // Verify that all channels have the same number of samples. for ( size_t ch = 0; ch < chan_count; ch++ ) { if ( sounds[ ch ].size() != (size_t) samples_count_per_chan ) { return BAD_PARAMS; } } int delay_samples = (int)(delay_seconds * sample_rate); for ( size_t ch = 0; ch < chan_count; ch++ ) { std::vector<float> tmp; tmp.resize(sounds[ch].size()); // Convert signal from short to float for ( size_t i = 0; i < samples_count_per_chan; i++ ) { tmp[ i ] = sounds[ ch ][ i ]; } // Add a reverb for ( size_t i = 0; i < samples_count_per_chan - delay_samples; i++ ) { tmp[ i + delay_samples ] += decay * tmp[ i ]; } // Find maximum signal's magnitude float max_magnitude = 0.0f; for ( size_t i = 0; i < samples_count_per_chan - delay_samples; i++ ) { if ( abs(tmp[ i ]) > max_magnitude ) { max_magnitude = abs(tmp[ i ]); } } // Signed short can keep values from -32768 to +32767, // After reverb, usually there are values large 32000. // So we must scale all values back to [ -32768 ... 32768 ] float norm_coef = 30000.0f / max_magnitude; printf( "max_magnitude = %.1f, coef = %.3f\n", max_magnitude, norm_coef ); // Scale back and transform floats to shorts. for ( size_t i = 0; i < samples_count_per_chan; i++ ) { sounds[ ch ][ i ] = (short)(norm_coef * tmp[ i ]); } } return WAV_OK; }
[ "scrat98@mail.ru" ]
scrat98@mail.ru
84e0fd4e148601ea179b6b1ef8da7fb4693d43af
453ef442430b58701b4e67bc9c6d55cc0d7aeb3f
/workspace/src/SlalomEebuiInfomation/SlEbPidInfomation.cpp
d2182d1958238652c2b4d05b8ff6721581fe2341
[]
no_license
sakiyama02/chanponship
6d6348eb3e200b7682aa3ec3917e2c7746f754cb
2dccb2670d03db301434c223d3b80beed55a24d3
refs/heads/master
2023-09-06T00:12:07.740578
2021-10-22T02:33:11
2021-10-22T02:33:11
419,940,625
0
0
null
null
null
null
UTF-8
C++
false
false
1,356
cpp
//SlEbpidInfomation //スラロームイーブイPIDカーブインフォメーション // #include "../../include/SlalomEebuiInfomation/SlEbPidInfomation.h" SlEbpidInfomation::SlEbpidInfomation(){ memset(pidData,0,sizeof(PIDData)*SLALOMEEBUI_NUM); int16 index = 0; //template /* //pidゲイン値の設定 //p:p値の設定 //i:i値の設定 //d:d値の設定 pidData[index].pGain=0f; pidData[index].iGain=0f; pidData[index].dGain=0f; //v値の設定 pidData[index].targetVal=0f; index++; */ //1 pidData[index].pGain=0.2; pidData[index].iGain=0.2; pidData[index].dGain=0.04; pidData[index].targetVal=60; //4 /* index = 3; pidData[index].pGain=0.2; pidData[index].iGain=0; pidData[index].dGain=0; pidData[index].targetVal=50; */ //8 index = 7; pidData[index].pGain=0.8; pidData[index].iGain=0.2; pidData[index].dGain=0.04; pidData[index].targetVal=13; //9 index++; pidData[index].pGain=0.2;//1; pidData[index].iGain=0; pidData[index].dGain=0; pidData[index].targetVal=13; } SlEbpidInfomation::~SlEbpidInfomation(){ delete(pidData); } int8 SlEbpidInfomation::getter(int16 scene_num,PIDData* pid_data){ memcpy(pid_data,&pidData[scene_num],sizeof(PIDData)); return SYS_OK; }
[ "sakiyama.hayato02@gmail.com" ]
sakiyama.hayato02@gmail.com
46755047a06cdccf0f9f998027d6e528edfee3f7
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/chrome/browser/font_pref_change_notifier.cc
84b19a1e4770f6b79c6a3e04a19989ae2550b69d
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
2,089
cc
// Copyright 2017 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 "chrome/browser/font_pref_change_notifier.h" #include "base/bind.h" #include "base/check.h" #include "base/strings/string_util.h" #include "chrome/common/pref_names_util.h" #include "components/prefs/pref_service.h" FontPrefChangeNotifier::Registrar::Registrar() {} FontPrefChangeNotifier::Registrar::~Registrar() { if (is_registered()) Unregister(); } void FontPrefChangeNotifier::Registrar::Register( FontPrefChangeNotifier* notifier, FontPrefChangeNotifier::Callback cb) { DCHECK(!is_registered()); notifier_ = notifier; callback_ = std::move(cb); notifier_->AddRegistrar(this); } void FontPrefChangeNotifier::Registrar::Unregister() { DCHECK(is_registered()); notifier_->RemoveRegistrar(this); notifier_ = nullptr; callback_ = FontPrefChangeNotifier::Callback(); } FontPrefChangeNotifier::FontPrefChangeNotifier(PrefService* pref_service) : pref_service_(pref_service) { pref_service_->AddPrefObserverAllPrefs(this); } FontPrefChangeNotifier::~FontPrefChangeNotifier() { pref_service_->RemovePrefObserverAllPrefs(this); // There could be a shutdown race between this class and the objects // registered with it. We don't want the registrars to call back into us // when we're deleted, so tell them to unregister now. for (auto& reg : registrars_) reg.Unregister(); } void FontPrefChangeNotifier::AddRegistrar(Registrar* registrar) { registrars_.AddObserver(registrar); } void FontPrefChangeNotifier::RemoveRegistrar(Registrar* registrar) { registrars_.RemoveObserver(registrar); } void FontPrefChangeNotifier::OnPreferenceChanged(PrefService* pref_service, const std::string& pref_name) { if (base::StartsWith(pref_name, pref_names_util::kWebKitFontPrefPrefix, base::CompareCase::SENSITIVE)) { for (auto& reg : registrars_) reg.callback_.Run(pref_name); } }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f6e5db1d347bcc16dc54ecc344c86e53239ea7fc
3136459fd674e1027f480895ba6685312ac6959b
/include/owl/shellitm.h
f9452b4f94052d648b2fcba77f5ad5ead84cc97f
[ "Zlib" ]
permissive
pierrebestwork/owl-next
701d1a6cbabd4566a0628aa8a64343b498d1e977
94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e
refs/heads/master
2023-02-14T02:03:33.656218
2020-03-16T16:41:49
2020-03-16T16:41:49
326,663,717
0
0
null
null
null
null
UTF-8
C++
false
false
39,854
h
//---------------------------------------------------------------------------- // ObjectWindows // Copyright (c) 1995, 1996 by Borland International, All Rights Reserved // /// \file /// Definitions of Win95 Shell Clases: /// TShellItem, TShellItemIterator, TPidl, TShellMalloc /// /// Also the following lightweight "wrapper" classes are defined: /// TExtractIcon, TContextMenu, TDataObject, TDropTarget /// /// These are wrapper classes for the Win95 deskop. //---------------------------------------------------------------------------- #if !defined(OWL_SHELLITM_H) #define OWL_SHELLITM_H #include <owl/defs.h> #if defined(BI_HAS_PRAGMA_ONCE) # pragma once #endif #if defined(BI_COMP_WATCOM) # pragma read_only_file #endif #include <owl/except.h> #include <owl/pointer.h> #include <owl/string.h> #include <shlobj.h> namespace owl { // Generic definitions/compiler options (eg. alignment) preceeding the // definition of classes #include <owl/preclass.h> /// \addtogroup winsys /// @{ // /// \class TShell // ~~~~~ ~~~~~~ /// delay loading SHELL32.DLL/SHELL.DLL class _OWLCLASS TShell { public: static void DragAcceptFiles(HWND,BOOL); static void DragFinish(HDROP); static UINT DragQueryFile(HDROP,UINT,LPTSTR,UINT); static BOOL DragQueryPoint(HDROP,LPPOINT); static HICON ExtractIcon(HINSTANCE,LPCTSTR,UINT); static HINSTANCE ShellExecute(HWND,LPCTSTR,LPCTSTR,LPCTSTR,LPCTSTR,INT); static void SHAddToRecentDocs(UINT, LPCVOID); static LPITEMIDLIST SHBrowseForFolder(LPBROWSEINFO); static void SHChangeNotify(LONG,UINT,LPCVOID,LPCVOID); static DWORD SHGetFileInfo(LPCTSTR,DWORD,SHFILEINFO *,UINT,UINT); static int SHFileOperation(LPSHFILEOPSTRUCT); static HRESULT SHGetDesktopFolder(LPSHELLFOLDER*); static HRESULT SHGetMalloc(LPMALLOC*); static BOOL SHGetPathFromIDList(LPCITEMIDLIST,LPTSTR); static HRESULT SHGetSpecialFolderLocation(HWND,int,LPITEMIDLIST*); static BOOL Shell_NotifyIcon(DWORD,PNOTIFYICONDATA); static TModule& GetModule(); }; // /// \class TShellMalloc // ~~~~~ ~~~~~~~~~~~~ /// Wraps the shell's IMalloc interface. /// Default constructor obtains shell's IMalloc interface. /// TComRef<IMalloc> and copy constructors supplied. /// TComRef<IMalloc> and TShellMalloc assignment operators also supplied. // // class TShellMalloc: public TComRef<IMalloc> { public: TShellMalloc(); TShellMalloc(const TComRef<IMalloc>& source); TShellMalloc(const TShellMalloc& source); TShellMalloc& operator = (const TComRef<IMalloc>& source); TShellMalloc& operator = (const TShellMalloc& source); }; // /// \class TExtractIcon // ~~~~~ ~~~~~~~~~~~~ /// Wraps the IExtractIcon interface (currently lightweight). /// A TExtractIcon is returned by TShellItem::GetExtractIcon. /// Default, TComRef<IExtractIcon> and copy constructors supplied. /// TComRef<IExtractIcon> and TExtractIcon assignment opreators also supplied. // class TExtractIcon: public TComRef<IExtractIcon> { public: TExtractIcon(IExtractIcon* iface = 0); TExtractIcon(const TComRef<IExtractIcon>& source); TExtractIcon(const TExtractIcon& source); TExtractIcon& operator= (const TComRef<IExtractIcon>& source); TExtractIcon& operator= (const TExtractIcon& source); }; // /// \class TContextMenu // ~~~~~ ~~~~~~~~~~~~ /// Wraps the IContextMenu interface (currently lightweight). /// A TContextMenu is returned by TShellItem::GetContextMenu. /// Default, TComRef<IContextMenu> and copy constructors supplied. /// TComRef<IContextMenu> and TContextMenu assignment opreators also supplied. // class TContextMenu: public TComRef<IContextMenu> { public: TContextMenu(IContextMenu* iface = 0); TContextMenu(const TComRef<IContextMenu>& source); TContextMenu(const TContextMenu& source); TContextMenu& operator = (const TComRef<IContextMenu>& source); TContextMenu& operator = (const TContextMenu& source); }; // /// \class TDataObject // ~~~~~ ~~~~~~~~~~~ /// Wraps the IDataObject interface (currently lightweight). /// A TDataObject is returned by TShellItem::GetDataObject. /// Default, TComRef<IDataObject> and copy constructors supplied. /// TComRef<IDataObject> and TDataObject assignment opreators also supplied. // class TDataObject: public TComRef<IDataObject> { public: TDataObject(IDataObject* iface = 0); TDataObject(const TComRef<IDataObject>& source); TDataObject(const TDataObject& source); TDataObject& operator = (const TComRef<IDataObject>& source); TDataObject& operator = (const TDataObject& source); }; // /// \class TDropTarget // ~~~~~ ~~~~~~~~~~~ /// Wraps the IDropTarget interface (currently lightweight). /// A TDropTarget is returned by TShellItem::GetDropTarget. /// Default, TComRef<IDropTarget> and copy constructors supplied. /// TComRef<IDropTarget> and TDropTarget assignment opreators also supplied. // class TDropTarget: public TComRef<IDropTarget> { public: TDropTarget(IDropTarget* iface = 0); TDropTarget(const TComRef<IDropTarget>& source); TDropTarget(const TDropTarget& source); TDropTarget& operator = (const TComRef<IDropTarget>& source); TDropTarget& operator = (const TDropTarget& source); }; // /// \class TPidl // ~~~~~ ~~~~~ /// TPidl is an item identifier list class (ITEMIDLIST). Its constructor takes an /// LPITEMIDLIST (a.k.a., pidl). The copy constructor and assignement operators /// supplied function to manipulate the ITEMIDLIST, get the size, get the number of /// items in the list, etc, supplied. Normally, the programmer will not have to be /// concerned with ITEMIDLISTs nor with the TPidl class. The TShellItem class hides /// all this. // class _OWLCLASS TPidl { public: static LPITEMIDLIST Next(LPITEMIDLIST pidl); // TPidl constructors and destructor // TPidl(LPITEMIDLIST pidl = 0); TPidl(const TPidl& source); virtual ~TPidl(); // Assignment operators // TPidl& operator = (const TPidl& source); TPidl& operator = (LPITEMIDLIST pidl); // Test to see if valid pidl bool operator !() const; /// Use TPidl in place of pidl // operator LPCITEMIDLIST () const; operator LPITEMIDLIST (); /// Use TPidl in place of pointer to a pidl // operator LPCITEMIDLIST* () const; operator LPITEMIDLIST* (); /// Get size (in bytes) of a pidl // ulong GetSize() const; /// Get number of item ids in the TPidl (the TPidl can be a list of ids) // long GetItemCount() const; /// Get the last item id in the TPidl // TPidl GetLastItem() const; /// Return a TPidl with the last item id stripped off of it // TPidl StripLastItem() const; /// Copy a pidl // LPITEMIDLIST CopyPidl() const; protected: /// Free a pidl with the shell's allocator // void FreePidl(); protected_data: /// A PIDL // LPITEMIDLIST Pidl; }; // /// \class TShellItem // ~~~~~ ~~~~~~~~~~ /// An item in the shell's name space. All items in the shell's /// namespace can be identified by a fully qualified pidl. Another /// way to uniquely identify an item is via it's parent and an item id /// (i.e., a single item rather than a list). A TShellItem contains a /// parent (TComRef<IShellFolder> ParentFolder) and the item id (TPidl pidl) // class _OWLCLASS TShellItem: public TComRef<IShellFolder> { public: /// Used by TShelItem::GetDisplayName() and TShellItem::Rename() /// See MS doc for SHGNO for more information, Programmer's /// Guide to MS Windows 95, MS Press, p. 218. // enum TDisplayNameKind { Normal = SHGDN_NORMAL, ///< File object displayed by itself. InFolder = SHGDN_INFOLDER, ///< File object displayed within a folder. ForParsing = SHGDN_FORPARSING ///< File object suitable for parsing. }; /// Used by TShellItem::GetIcon /// See MS doc for SHGetFileInfo for more information, Programmer's /// Guide to MS Windows 95, MS Press, pp. 205-207. enum TIconSize { Large = SHGFI_LARGEICON, ///< Retrieves the shell item's large icon Small = SHGFI_SMALLICON, ///< Retrieves the shell item's small icon Shell = SHGFI_SHELLICONSIZE ///< Retrieves the shell-sized icon (if unavailable, the normal icon ///< is sized according to the system metric values) }; /// Used by TShellItem::GetIcon /// See MS doc for SHGetFileInfo for more information, Programmer's /// Guide to MS Windows 95, MS Press, pp. 205-207. // enum TIconKind { Link = SHGFI_LINKOVERLAY, ///< Adds the link overlay to the shell item's icon Open = SHGFI_OPENICON, ///< Retrieves the shell item's open icon Selected = SHGFI_SELECTED ///< Blends the shell item's icon with the system highlight color }; /// Used by TShellItem::TShellItem(const TSpecialFolderKind kind, /// HWND windowOwner = 0) /// See MS doc for SHGetSpecialFolderLocation for more information, /// Programmer's Guide to MS Windows 95, MS Press, pp. 209-210. // enum TSpecialFolderKind { RecycleBin = CSIDL_BITBUCKET, ///< Directory containing file objects in the user's recycle bin ControlPanel = CSIDL_CONTROLS, ///< Virtual folder containing icons for the Control Panel Desktop = CSIDL_DESKTOP, ///< Virtual folder at the root of the namespace DesktopFileDir = CSIDL_DESKTOPDIRECTORY, ///< Directory used to physically store file objects on the desktop MyComputer = CSIDL_DRIVES, ///< Virtual folder containing everything on the local computer Fonts = CSIDL_FONTS, ///< Virtual folder containing fonts NetworkNeighborhoodFileDir = CSIDL_NETHOOD, ///< Directory containing objects that appeat in the Network Neighborhood NetworkNeighborhood = CSIDL_NETWORK, ///< Virtual folder representing the top level of the network hierarchy CommonDocuments = CSIDL_PERSONAL, ///< Directory that serves as a repository for common documents Printers = CSIDL_PRINTERS, ///< Virtual folder containing installed printers Programs = CSIDL_PROGRAMS, ///< Directory containing the user's program groups RecentDocuments = CSIDL_RECENT, ///< Directory containing the user's most recently used documents SendTo = CSIDL_SENDTO, ///< Directory containing Send To menu items StartMenu = CSIDL_STARTMENU, ///< Directory containing Start menu items Startup = CSIDL_STARTUP, ///< Directory that corresponds to the user's Startup program group CommonTemplates = CSIDL_TEMPLATES, ///< Directory that serves as a repository for document templates Favorites = CSIDL_FAVORITES ///< }; /// Used by TShellItem::GetAttributes /// See MS doc for IShellFolder::GetAttributesOf for more information, /// Programmer's Guide to MS Windows 95, MS Press, pp. 194-196. // enum TAttribute { // Capabilities // atCapabilityMask = SFGAO_CAPABILITYMASK, ///< Mask for the capability flags atCanBeCopied = SFGAO_CANCOPY, ///< The shell item can be copied atCanBeDeleted = SFGAO_CANDELETE, ///< The shell item can be deleted atCanCreateShortcut = SFGAO_CANLINK, ///< Shortcuts can be created for the shell item atCanBeMoved = SFGAO_CANMOVE, ///< The shell item can be moved atCanBeRenamed = SFGAO_CANRENAME, ///< The shell item can be renamed atIsADropTarget = SFGAO_DROPTARGET, ///< The shell item is a drop target atHasAPropertySheet = SFGAO_HASPROPSHEET, ///< The shell item has a property sheet // Display Attributes // atDisplayAttributeMask = SFGAO_DISPLAYATTRMASK, ///< Mask for the display attributes atDisplayGhosted = SFGAO_GHOSTED, ///< The shell item should be displayed using a ghosted icon atIsShortcut = SFGAO_LINK, ///< The shell item is a shortcut atIsReadOnly = SFGAO_READONLY, ///< The shell item is readonly atIsShared = SFGAO_SHARE, ///< The shell item is shared // Contents // atContentsMask = SFGAO_CONTENTSMASK, ///< Mask for the contents attributes atContainsSubFolder = SFGAO_HASSUBFOLDER, ///< The shell item has subfolders // Miscellaneous // atContainsFileSystemFolder = SFGAO_FILESYSANCESTOR, ///< The shell item contains one or more system folders atIsPartOfFileSystem = SFGAO_FILESYSTEM, ///< The shell item is part of the file system atIsFolder = SFGAO_FOLDER, ///< The shell item is a folder atCanBeRemoved = SFGAO_REMOVABLE ///< The shell item is on removable media }; /// Used by TShellItem::Rename,Copy,Move,Delete /// See MS doc for SHFILEOPSTRUCT for more information, Programmer's /// Guide to MS Windows 95, MS Press, pp. 214-215. // enum TFileOpFlags { AllowUndo = FOF_ALLOWUNDO, ///< Preserves undo information (if possible) NoConfirmation = FOF_NOCONFIRMATION, ///< Responds with "yes to all" for any dialog NoConfirmMkDir = FOF_NOCONFIRMMKDIR, ///< No confirmation on the creation of a new directory RenameOnCollision = FOF_RENAMEONCOLLISION, ///< Renames the file being operated on if a file of the same name already exists (i.e., Copy #1 of ...) Silent = FOF_SILENT, ///< No progess dialog box is displayed SimpleProgress = FOF_SIMPLEPROGRESS ///< A simple progress dialog box is diaplayed (no file names) }; /// Used by TShellItem::BrowseForFolder /// See MS doc for BROWSEINFO for more information, Programmer's /// Guide to MS Windows 95, MS Press, pp. 211-212. // enum TBrowseFlags { OnlyComputers, ///< Returns only computers OnlyPrinters, ///< Returns only printers NoNetorkFoldersBelowDomain, ///< Does not return network folders below the domain OnlyFSAncestors, ///< Returns only file system ancestors OnlyFSDirs ///< Returns only file system directories }; /// Returned by TShellItem::GetExeType /// See MS doc for SHGetFileInfo for more information, Programmer's /// Guide to MS Windows 95, MS Press, pp. 205-207. // enum TExeKind { NonExecutable, ///< Nonexecutable file or an error condition WindowsNE, ///< Windows-based application WindowsPE, ///< Windows level (3.0, 3.5, or 4.0) MSDOS, ///< MS-DOS .EXE, .COM, or .BAT file Win32Console ///< Win32-based console application }; /// TCreateStruct contains information to construct a TShellItem /// Typically a TCreateStruct is returned (for example by GetParentFolder) /// and this TCreateStruct is used to construct a TshellItem /// Passed in as arguments to: /// - TShellItem::TShellItem(const TCreateStruct& cs) /// - TShellItem::operator =(const TCreateStruct& cs) /// Returned as an out argument by: /// - TShellItem::BrowseForFolder /// - TShellItem::ParseDisplayName /// Returned by: /// - TShellItem::GetParentFolder /// - TShellItemIterator::operator ++ (); /// - TShellItemIterator::operator ++ (int); /// - TShellItemIterator::operator -- (); /// - TShellItemIterator::operator -- (int); /// - TShellItemIterator::operator [] (const long index); /// - TShellItemIterator::Current(); // struct TCreateStruct { TCreateStruct(); TCreateStruct(TPidl& ptr, TComRef<IShellFolder>& parentFolder); TCreateStruct(const TCreateStruct& source); TPidl Pidl; TComRef<IShellFolder> ParentFolder; }; // Constructors for TShellItem // TShellItem(const tchar* path, bool throwOnInvalidPath = true, HWND windowOwner = 0); TShellItem(const TSpecialFolderKind kind, HWND windowOwner = 0); TShellItem(const TCreateStruct& cs); // used with TShellItemIterator TShellItem(const TPidl& Pidl, const TComRef<IShellFolder>& parentFolder); TShellItem(LPITEMIDLIST pidl = 0, const TComRef<IShellFolder>& parentFolder = TComRef<IShellFolder>(0)); TShellItem(const TShellItem& source); // Assignment operators // TShellItem& operator =(const TShellItem& source); TShellItem& operator =(const TCreateStruct& cs); /// Determine if TShellItem reprsents a valid item // bool Valid() const; /// Allow TShellItems to be used in place of pidls operator LPCITEMIDLIST() const; // 05/26/98 Yura Bidus // Get TExtractIcon, TContextMenu, TDataObject, TDropTarget for a TShellItem TExtractIcon GetExtractIcon(HWND windowOwner = 0); TContextMenu GetContextMenu(HWND windowOwner = 0); TDataObject GetDataObject(HWND windowOwner = 0); TDropTarget GetDropTarget(HWND windowOwner = 0); HICON GetIcon(TIconSize size = Shell, uint kind = 0); /// Get Attributes of a TShellItem /// GetAttributes - Get Capabilities, Display, Contents, & Misc. Attributes with one call // ulong GetAttributes(const ulong reqAttrib, const bool validateCachedInfo = false) const; // Attributes - Capabilties // bool CanBeCopied(const bool validateCachedInfo = false) const; bool CanBeDeleted(const bool validateCachedInfo = false) const; bool CanCreateShortcut(const bool validateCachedInfo = false) const; bool CanBeMoved(const bool validateCachedInfo = false) const; bool CanBeRenamed(const bool validateCachedInfo = false) const; bool IsADropTarget(const bool validateCachedInfo = false) const; bool HasAPropertySheet(const bool validateCachedInfo = false)const; // Attributes - Display // bool DisplayGhosted(const bool validateCachedInfo = false) const; bool IsShortcut(const bool validateCachedInfo = false) const; bool IsReadOnly(const bool validateCachedInfo = false) const; bool IsShared(const bool validateCachedInfo = false) const; // Attributes - Contents // bool ContainsSubFolder(const bool validateCachedInfo = false) const; // Attributes - Miscellaneous // bool ContainsFileSystemFolder(const bool validateCachedInfo = false) const; bool IsPartOfFileSystem(const bool validateCachedInfo = false) const; bool IsFolder(const bool validateCachedInfo = false) const; bool CanBeRemoved(const bool validateCachedInfo = false) const; // Attributes - Additional (Not part of GetAttributes) // bool IsDesktop() const; /// Get TPidl (relative to parent) // TPidl GetPidl() const; /// Get fully qualified TPidl // TPidl GetFullyQualifiedPidl() const; /// Get Parent Folder // TCreateStruct GetParentFolder() const; /// Get type of executable file (may return NonExecutable) // TExeKind GetExeType(uint* major = 0, uint* minor = 0) const; /// Get type of file (e.g., "Borland C++ Header File", "Notepad File") // TString GetTypeName() const; /// Get Displayname (for a TShellItem that's part of the filesystem, this is the filename) // TString GetDisplayName(const TDisplayNameKind kind = Normal) const; /// Get path (only call if the TShellItem is part of the file system (IsPartOfFileSystem == true) // TString GetPath() const; // File Opertations (Rename, Copy, Move, Delete) // void Rename(const tchar* newName, HWND windowOwner = 0, const TDisplayNameKind kind = Normal); bool Copy(const tchar* dest, const bool destIsFolder = true, const USHORT flags = 0, const tchar* title = 0, HWND windowOwner = 0) const; bool Copy(const TShellItem& dest, const USHORT flags = 0, const tchar* title = 0, HWND windowOwner = 0) const; bool Move(const tchar* destFolder, const USHORT flags = 0, const tchar* title = 0, HWND windowOwner = 0); bool Move(const TShellItem& destFolder, const USHORT flags = 0, const tchar* title = 0, HWND windowOwner = 0); bool Delete(const USHORT flags = 0, const tchar* title = 0, HWND windowOwner = 0); /// Add to recent docs (Win95 taskbar:Start:Documents) // void AddToRecentDocs() const; /// Get the TShellItem that a shortcut points to // TShellItem ResolveShortcut(HWND windowOwner = 0); // Create a shortcut // TODO: Add string-aware overloads. // static HRESULT CreateShortCut(LPCTSTR objPath, LPTSTR pathLink, LPTSTR description); static HRESULT CreateShortCut(LPCITEMIDLIST pidl, LPTSTR pathLink, LPTSTR description); TShellItem CreateShortCut(LPTSTR pathLink, LPTSTR description); // Pidl compares (so that they can be ordered) // bool operator==(const TShellItem& rhs) const; bool operator!=(const TShellItem& rhs) const; bool operator<(const TShellItem& rhs) const; bool operator<=(const TShellItem& rhs) const; bool operator>(const TShellItem& rhs) const; bool operator>=(const TShellItem& rhs) const; // Folder Only Functions // EnumObjects is called by TShellItemIterator // void EnumObjects(IEnumIDList** iface, HWND windowOwner = 0, const int kind = -1) const; /// Select a Foler under this TShellItem // bool BrowseForFolder(TCreateStruct& cs, HWND windowOwner = 0, const tchar* title = 0, const UINT flags = 0, int* image = 0, const bool includeStatus = false, BFFCALLBACK func = 0, const LPARAM param = 0) const; /// Parse a display name into a TShellItem (actually, into a TCreateStruct) // HRESULT ParseDisplayName(TCreateStruct& cs, const tchar* displayName, ulong* eaten = 0, HWND windowOwner = 0, ulong* attrib = 0) const; protected: // CompareIDs is used by the pidl compare functions above // short CompareIDs(const TShellItem& rhs) const; void EnforceValidity() const; void RetrieveIShellFolder() const; bool HaveSameParent(const TShellItem& other) const; bool GetAttribute(const TAttribute at, const bool validateCachedInfo) const; protected_data: TPidl Pidl; TComRef<IShellFolder> ParentFolder; }; // /// \class TShellItemIterator // ~~~~~ ~~~~~~~~~~~~~~~~~~ /// TShellItemIterator is an interator for walking through the contents of a folder. /// A folder is a TShellItem whose IsFolder or ContainsSubFolder attributes are true. // class _OWLCLASS TShellItemIterator: public TComRef<IEnumIDList> { public: /// Used by TShellItemIterator::TShellItemIterator(const TShellItem& folder, /// HWND windowOwner = 0, const UINT kind = Folders | NonFolders) /// See MS doc for SHCONTF for more information, Programmer's Guide to /// MS Windows 95, MS Press, p. 213. enum TIncludeKind { Folders = SHCONTF_FOLDERS, ///< For shell browser NonFolders = SHCONTF_NONFOLDERS, ///< For default view HiddenAndSystem = SHCONTF_INCLUDEHIDDEN ///< For hidden or system objects }; // constructor for TShellItemIterator // TShellItemIterator(const TShellItem& folder, HWND windowOwner = 0, const int kind = Folders | NonFolders); TShellItemIterator(const TShellItemIterator& source); /// Assignment operator // TShellItemIterator& operator= (const TShellItemIterator& source); /// True if iterator is still valid // bool Valid() const; /// Get number of TShellItems in the list // long GetCount() const; // Get next item, previous item, item at index, and current item // TShellItem::TCreateStruct operator ++ (); TShellItem::TCreateStruct operator ++ (int); TShellItem::TCreateStruct operator -- (); TShellItem::TCreateStruct operator -- (int); TShellItem::TCreateStruct operator [] (const long index); TShellItem::TCreateStruct Current(); /// Skip count items // void Skip(const ulong count); /// Reset list // void Reset(); protected: void Next(); void EnforceValidInterface() const; protected_data: long Index; TPidl Pidl; TComRef<IShellFolder> Folder; operator IEnumIDList**(); }; // /// \class TXShell // ~~~~~ ~~~~~~~ /// Base Shell exception class. Handles all TShellItem and related class exceptions // class _OWLCLASS TXShell: public TXOwl { public: // Constructor for TXShell // TXShell(uint resId = IDS_SHELLFAILURE, HANDLE handle = 0); // Clone a TXShell // TXShell* Clone(); // Throw an exception // void Throw(); // Construct a TXShell exception from scratch, and throw it. // static void Raise(uint resId = IDS_SHELLFAILURE, HANDLE handle = 0); // Check an HRESULT and throw a TXShell if not SUCCEEDED(hr) // static void Check(HRESULT hr, uint resId = IDS_SHELLFAILURE, HANDLE handle = 0); }; /// @} // Generic definitions/compiler options (eg. alignment) following the // definition of classes #include <owl/posclass.h> //---------------------------------------------------------------------------- // Inline implementations // /// Default constructor for TShellMalloc. For more info, see MS doc for /// SHGetMalloc (Prog. Guide to MS Win95, p. 208) // inline TShellMalloc::TShellMalloc() { HRESULT hr = TShell::SHGetMalloc(*this); TXShell::Check(hr, IDS_SHGETMALLOCFAIL); } /// TShellMalloc constructor to construct from TComRef<IMalloc> // inline TShellMalloc::TShellMalloc(const TComRef<IMalloc>& source) :TComRef<IMalloc>(source) { } /// TShellMalloc copy constructor // inline TShellMalloc::TShellMalloc(const TShellMalloc& source) :TComRef<IMalloc>(source) { } /// TShellMalloc assignment operator (from TComRef<IMalloc>) // inline TShellMalloc& TShellMalloc::operator =(const TComRef<IMalloc>& source) { if (&source != this) TComRef<IMalloc>::operator=(source); return *this; } /// TShellMalloc assignment operator (from another TShellMalloc) // inline TShellMalloc& TShellMalloc::operator =(const TShellMalloc& source) { if (&source != this) TComRef<IMalloc>::operator=(source); return *this; } /// Default constructor for TExtractIcon // inline TExtractIcon::TExtractIcon(IExtractIcon* iface) :TComRef<IExtractIcon>(iface) { } /// TExtractIcon constructor to construct from TComRef<IExtractIcon> // inline TExtractIcon::TExtractIcon(const TComRef<IExtractIcon>& source) :TComRef<IExtractIcon>(source) { } /// TExtractIcon copy constructor // inline TExtractIcon::TExtractIcon(const TExtractIcon& source) :TComRef<IExtractIcon>(source) { } /// TExtractIcon assignment operator (from TComRef<IExtractIcon>) // inline TExtractIcon& TExtractIcon::operator =(const TComRef<IExtractIcon>& source) { if (&source != this) TComRef<IExtractIcon>::operator=(source); return *this; } /// TExtractIcon assignment operator (from another TExtractIcon) // inline TExtractIcon& TExtractIcon::operator =(const TExtractIcon& source) { if (&source != this) TComRef<IExtractIcon>::operator=(source); return *this; } /// Default constructor for TContextMenu // inline TContextMenu::TContextMenu(IContextMenu* iface) :TComRef<IContextMenu>(iface) { } /// TContextMenu constructor to construct from TComRef<IContextMenu> // inline TContextMenu::TContextMenu(const TComRef<IContextMenu>& source) :TComRef<IContextMenu>(source) { } /// TContextMenu copy constructor // inline TContextMenu::TContextMenu(const TContextMenu& source) :TComRef<IContextMenu>(source) { } /// TContextMenu assignment operator (from TComRef<IContextMenu>) // inline TContextMenu& TContextMenu::operator =(const TComRef<IContextMenu>& source) { if (&source != this) TComRef<IContextMenu>::operator=(source); return *this; } /// TContextMenu assignment operator (from another TContextMenu) // inline TContextMenu& TContextMenu::operator = (const TContextMenu& source) { if (&source != this) TComRef<IContextMenu>::operator=(source); return *this; } /// Default constructor for TDataObject // inline TDataObject::TDataObject(IDataObject* iface) : TComRef<IDataObject>(iface) { } /// TDataObject constructor to construct from TComRef<IDataObject> // inline TDataObject::TDataObject(const TComRef<IDataObject>& source) :TComRef<IDataObject>(source) { } /// TDataObject copy constructor // inline TDataObject::TDataObject(const TDataObject& source) :TComRef<IDataObject>(source) { } /// TDataObject assignment operator (from TComRef<IDataObject>) // inline TDataObject& TDataObject::operator =(const TComRef<IDataObject>& source) { if (&source != this) TComRef<IDataObject>::operator=(source); return *this; } /// TDataObject assignment operator (from another TDataObject) // inline TDataObject& TDataObject::operator =(const TDataObject& source) { if (&source != this) TComRef<IDataObject>::operator=(source); return *this; } /// Default constructor for TDropTarget // inline TDropTarget::TDropTarget(IDropTarget* iface) :TComRef<IDropTarget>(iface) { } /// TDropTarget constructor to construct from TComRef<IDropTarget> // inline TDropTarget::TDropTarget(const TComRef<IDropTarget>& source) :TComRef<IDropTarget>(source) { } /// TDropTarget copy constructor // inline TDropTarget::TDropTarget(const TDropTarget& source) :TComRef<IDropTarget>(source) { } /// TDropTarget assignment operator (from TComRef<IDropTarget>) // inline TDropTarget& TDropTarget::operator =(const TComRef<IDropTarget>& source) { if (&source != this) TComRef<IDropTarget>::operator=(source); return *this; } /// TDropTarget assignment operator (from another TDropTarget) // inline TDropTarget& TDropTarget::operator =(const TDropTarget& source) { if (&source != this) TComRef<IDropTarget>::operator=(source); return *this; } /// Check to see if TPidl represents an ITEMIDLIST (return true if it does not) // inline bool TPidl::operator !() const { return Pidl == 0; } /// Return next item id (in the list) // inline LPITEMIDLIST TPidl::Next(LPITEMIDLIST pidl) { return reinterpret_cast<LPITEMIDLIST>(reinterpret_cast<char*>(pidl) + pidl->mkid.cb); } /// TPidl copy constructor // inline TPidl::TPidl(const TPidl& source) :Pidl(source.CopyPidl()) { } /// Construct a TPidl from an LPITEMIDLIST (pidl) // inline TPidl::TPidl(LPITEMIDLIST pidl) :Pidl(pidl) { } /// TPidl assignement operator (from another TPidl) // inline TPidl& TPidl::operator =(const TPidl& source) { if (&source == this) return *this; Pidl = source.CopyPidl(); return *this; } /// TPidl assignement operator (from an LPITEMIDLIST (pidl)) // inline TPidl& TPidl::operator =(LPITEMIDLIST pidl) { FreePidl(); Pidl = pidl; return *this; } /// TPidl destructor // inline TPidl::~TPidl() { FreePidl(); } inline TPidl::operator LPCITEMIDLIST() const { return Pidl; } inline TPidl::operator LPITEMIDLIST() { return Pidl; } inline TPidl::operator LPCITEMIDLIST*() const { return const_cast<LPCITEMIDLIST*>(&Pidl); } inline TPidl::operator LPITEMIDLIST*() { if (Pidl) FreePidl(); return &Pidl; } /// Return true if the TShellItem represents an item in the namespace // inline bool TShellItem::Valid() const { return !!Pidl && !!ParentFolder; } // Attributes - Capabilties /// Return true if the TShellItem represents an item that can be copied // inline bool TShellItem::CanBeCopied(const bool validateCachedInfo) const { return GetAttribute(atCanBeCopied, validateCachedInfo); } /// Return true if the TShellItem represents an item that can be deleted // inline bool TShellItem::CanBeDeleted(const bool validateCachedInfo) const { return GetAttribute(atCanBeDeleted, validateCachedInfo); } /// Return true if the TShellItem represents an item for which a shortcut can /// be created // inline bool TShellItem::CanCreateShortcut(const bool validateCachedInfo) const { return GetAttribute(atCanCreateShortcut, validateCachedInfo); } /// Return true if the TShellItem represents an item that can be moved // inline bool TShellItem::CanBeMoved(const bool validateCachedInfo) const { return GetAttribute(atCanBeMoved, validateCachedInfo); } /// Return true if the TShellItem represents an item that can be renamed // inline bool TShellItem::CanBeRenamed(const bool validateCachedInfo) const { return GetAttribute(atCanBeRenamed, validateCachedInfo); } /// Return true if the TShellItem represents an item is a drop target // inline bool TShellItem::IsADropTarget(const bool validateCachedInfo) const { return GetAttribute(atIsADropTarget, validateCachedInfo); } /// Return true if the TShellItem represents an item that has a property sheet // inline bool TShellItem::HasAPropertySheet(const bool validateCachedInfo) const { return GetAttribute(atHasAPropertySheet, validateCachedInfo); } // Attributes - Display /// Return true if the TShellItem represents an item that should be displayed /// as ghosted // inline bool TShellItem::DisplayGhosted(const bool validateCachedInfo) const { return GetAttribute(atDisplayGhosted, validateCachedInfo); } /// Return true if the TShellItem represents an item that is a shortcut // inline bool TShellItem::IsShortcut(const bool validateCachedInfo) const { return GetAttribute(atIsShortcut, validateCachedInfo); } /// Return true if the TShellItem represents an item that is read only // inline bool TShellItem::IsReadOnly(const bool validateCachedInfo) const { return GetAttribute(atIsReadOnly, validateCachedInfo); } /// Return true if the TShellItem represents an item that is shared // inline bool TShellItem::IsShared(const bool validateCachedInfo) const { return GetAttribute(atIsShared, validateCachedInfo); } // Attributes - Contents /// Return true if the TShellItem represents an item that contains a subfolder // inline bool TShellItem::ContainsSubFolder(const bool validateCachedInfo) const { return GetAttribute(atContainsSubFolder, validateCachedInfo); } // Attributes - Miscellaneous /// Return true if the TShellItem represents an item that contains a file system folder // inline bool TShellItem::ContainsFileSystemFolder(const bool validateCachedInfo) const { return GetAttribute(atContainsFileSystemFolder, validateCachedInfo); } /// Return true if the TShellItem represents an item that is part of the file system // inline bool TShellItem::IsPartOfFileSystem(const bool validateCachedInfo) const { return GetAttribute(atIsPartOfFileSystem, validateCachedInfo); } /// Return true if the TShellItem represents an item that is a folder // inline bool TShellItem::IsFolder(const bool validateCachedInfo) const { return GetAttribute(atIsFolder, validateCachedInfo); } /// Return true if the TShellItem represents an item that can be removed // inline bool TShellItem::CanBeRemoved(const bool validateCachedInfo) const { return GetAttribute(atCanBeRemoved, validateCachedInfo); } /// TShellItem::TCreateStruct default constructor // inline TShellItem::TCreateStruct::TCreateStruct() { } /// TShellItem::TCreateStruct constructor (takes a TPidl and TComRef<IShellFolder> // inline TShellItem::TCreateStruct::TCreateStruct( TPidl& pidl, TComRef<IShellFolder>& parentFolder) : Pidl(pidl), ParentFolder(parentFolder) { } /// TShellItem::TCreateStruct copy constructor // inline TShellItem::TCreateStruct::TCreateStruct(const TCreateStruct& source) : Pidl(source.Pidl), ParentFolder(source.ParentFolder) { } /// use TShellItem in place of an LPITEMIDLIST (pidl) // inline TShellItem::operator LPCITEMIDLIST() const { return Pidl; } /// Get a TShellItem's TPidl // inline TPidl TShellItem::GetPidl() const { return Pidl; // Return a copy } /// Compare sort order of this TShellItem equals another TShellItem // inline bool TShellItem::operator ==(const TShellItem& rhs) const { return CompareIDs(rhs) == 0; } /// Compare sort order of this TShellItem is less than another TShellItem // inline bool TShellItem::operator <(const TShellItem& rhs) const { return CompareIDs(rhs) < 0; } /// Compare sort order of this TShellItem is greater than another TShellItem // inline bool TShellItem::operator >(const TShellItem& rhs) const { return CompareIDs(rhs) > 0; } /// Compare sort order of this TShellItem is not equal to another TShellItem // inline bool TShellItem::operator !=(const TShellItem& rhs) const { return !operator==(rhs); } /// Compare sort order of this TShellItem <= another TShellItem // inline bool TShellItem::operator <=(const TShellItem& rhs) const { return !operator>(rhs); } /// Compare sort order of this TShellItem >= another TShellItem // inline bool TShellItem::operator >=(const TShellItem& rhs) const { return !operator<(rhs); } /// HaveSameParent returns true if this TShellItem and other TShellItem have the /// same immediate parent folder. // inline bool TShellItem::HaveSameParent(const TShellItem& other) const { TShellItem* constThis = CONST_CAST(TShellItem*, this); TShellItem* constOther = CONST_CAST(TShellItem*, &other); return STATIC_CAST(IShellFolder*, constThis->ParentFolder) != STATIC_CAST(IShellFolder*, constOther->ParentFolder); } /// Return true if TShellItemIterator is valid and not at end of list of items // inline bool TShellItemIterator::Valid() const { return Index != -1; } } // OWL namespace #endif // OWL_SHELLITM_H
[ "Pierre.Best@taxsystems.com" ]
Pierre.Best@taxsystems.com
ada45a731dd4de1331827f2f319520341e4d4a5c
b75842b25932071ab1a098913bb2b09b0f9c7231
/C++/Binary Tree/VerticalOrderTraversal.cpp
842e8e7c57a16efb58653f25000dfd1743444b3a
[]
no_license
Ketan-Suthar/DataStructure
489c9a9cccb93dcce30a795bcdfeb4b8c7eed604
278ad5b70feefde5d5eb8cba7b82ed2c333f575a
refs/heads/master
2022-11-04T20:16:47.164023
2022-10-17T06:52:44
2022-10-17T06:52:44
199,179,496
8
8
null
2022-10-17T06:52:45
2019-07-27T15:05:34
C++
UTF-8
C++
false
false
3,148
cpp
// { Driver Code Starts #include <bits/stdc++.h> using namespace std; // Tree Node struct Node { int data; Node* left; Node* right; }; // Utility function to create a new Tree Node Node* newNode(int val) { Node* temp = new Node; temp->data = val; temp->left = NULL; temp->right = NULL; return temp; } void verticalOrder(Node *root); // Function to Build Tree Node* buildTree(string str) { // Corner Case if(str.length() == 0 || str[0] == 'N') return NULL; // Creating vector of strings from input // string after spliting by space vector<string> ip; istringstream iss(str); for(string str; iss >> str; ) ip.push_back(str); // Create the root of the tree Node* root = newNode(stoi(ip[0])); // Push the root to the queue queue<Node*> queue; queue.push(root); // Starting from the second element int i = 1; while(!queue.empty() && i < ip.size()) { // Get and remove the front of the queue Node* currNode = queue.front(); queue.pop(); // Get the current node's value from the string string currVal = ip[i]; // If the left child is not null if(currVal != "N") { // Create the left child for the current node currNode->left = newNode(stoi(currVal)); // Push it to the queue queue.push(currNode->left); } // For the right child i++; if(i >= ip.size()) break; currVal = ip[i]; // If the right child is not null if(currVal != "N") { // Create the right child for the current node currNode->right = newNode(stoi(currVal)); // Push it to the queue queue.push(currNode->right); } i++; } return root; } // Function for Inorder Traversal void printInorder(Node* root) { if(!root) return; printInorder(root->left); cout<<root->data<<" "; printInorder(root->right); } int main() { int t; string tc; getline(cin,tc); t=stoi(tc); while(t--) { string s; getline(cin,s); // string c; // getline(cin,c); Node* root = buildTree(s); verticalOrder(root); cout << endl; } return 0; } void verticalOrder(Node *root) { //Your code here if(!root) return; queue<pair<Node*, int>> q; map<int, vector<int>> m; q.push(make_pair(root, 0)); while(!q.empty()) { Node *p = q.front().first; int v = q.front().second; q.pop(); if(p->left) q.push(make_pair(p->left, v-1)); if(p->right) q.push(make_pair(p->right, v+1)); m[v].push_back(p->data); } for(auto it = m.begin(); it!=m.end(); it++) for(auto d=it->second.begin(); d!=it->second.end(); d++ ) cout << *d << " "; }
[ "ketansuthar899@gmail.com" ]
ketansuthar899@gmail.com
6e0259e4ce4cedf65a3273fb523413e1472dc0d1
7584d322729e30cac05504b6da95429f6f75b5b7
/lib/dlib/graph_utils/ordered_sample_pair_abstract.h
9dfd17b35963ef0e48ca65e34a5457afe05cc64b
[ "Apache-2.0", "BSL-1.0" ]
permissive
lorenzhaas/cppagent
290f698017119d401046d6d58b15f02669ad021d
2f88a4f894a98e522177ea06a44cfadf1adb7914
refs/heads/master
2020-03-28T21:47:56.330417
2019-10-21T09:38:37
2019-10-21T17:41:28
149,183,419
0
0
Apache-2.0
2019-10-21T08:49:47
2018-09-17T20:23:49
C++
UTF-8
C++
false
false
3,376
h
// Copyright (C) 2012 Davis E. King (davis@dlib.net) // License: Boost Software License See LICENSE.txt for the full license. #undef DLIB_ORDERED_SAMPLE_PaIR_ABSTRACT_H__ #ifdef DLIB_ORDERED_SAMPLE_PaIR_ABSTRACT_H__ #include <limits> #include "../serialize.h" namespace dlib { // ---------------------------------------------------------------------------------------- class ordered_sample_pair { /*! WHAT THIS OBJECT REPRESENTS This object is intended to represent an edge in a directed graph which has data samples at its vertices. So it contains two integers (index1 and index2) which represent the identifying indices of the samples at the ends of an edge. This object also contains a double which can be used for any purpose. !*/ public: ordered_sample_pair( ); /*! ensures - #index1() == 0 - #index2() == 0 - #distance() == 1 !*/ ordered_sample_pair ( const unsigned long idx1, const unsigned long idx2 ); /*! ensures - #index1() == idx1 - #index2() == idx2 - #distance() == 1 !*/ ordered_sample_pair ( const unsigned long idx1, const unsigned long idx2, const double dist ); /*! ensures - #index1() == idx1 - #index2() == idx2 - #distance() == dist !*/ const unsigned long& index1 ( ) const; /*! ensures - returns the first index value stored in this object !*/ const unsigned long& index2 ( ) const; /*! ensures - returns the second index value stored in this object !*/ const double& distance ( ) const; /*! ensures - returns the floating point number stored in this object !*/ }; // ---------------------------------------------------------------------------------------- inline bool operator == ( const ordered_sample_pair& a, const ordered_sample_pair& b ); /*! ensures - returns a.index1() == b.index1() && a.index2() == b.index2(); I.e. returns true if a and b both represent the same pair and false otherwise. Note that the distance field is not involved in this comparison. !*/ inline bool operator != ( const ordered_sample_pair& a, const ordered_sample_pair& b ); /*! ensures - returns !(a == b) !*/ // ---------------------------------------------------------------------------------------- inline void serialize ( const ordered_sample_pair& item, std::ostream& out ); /*! provides serialization support !*/ inline void deserialize ( ordered_sample_pair& item, std::istream& in ); /*! provides deserialization support !*/ // ---------------------------------------------------------------------------------------- } #endif // DLIB_ORDERED_SAMPLE_PaIR_ABSTRACT_H__
[ "will@systeminsights.com" ]
will@systeminsights.com
67627042dca182d701ebdecf82ddd20c55b018dd
c9fe5e4efcfcbb053dd21b91251a68254ba22cb5
/src/Window.cpp
aadf53c2924d04f6acb8510f9e50dcba4ea0a2e5
[ "MIT" ]
permissive
shvrd/shvrdengine-deprecated
9723356740c819cb4b35a548da984afe8c9646e8
88a8cd30bcdd6c815a16497e6ba54eea70b6c2df
refs/heads/master
2020-03-16T07:57:56.842332
2018-07-11T16:18:09
2018-07-11T16:18:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,512
cpp
// // Created by thekatze on 17/05/18. // #include <GL/glew.h> #include <SDL.h> #include "Window.h" #include "Util/Logger.h" #include "Util/Constants.h" Window::Window(const char *title, int windowWidth, int windowHeight) { Logger::info("Creating Window"); this->initialize(title, windowWidth, windowHeight); } /** * Changes the window title * @param title The new window title */ void Window::setTitle(const char* title) { SDL_SetWindowTitle(window, title); } void Window::initialize(const char *title, int windowWidth, int windowHeight) { Logger::info("Initializing SDL"); //Initialize Graphics if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { Logger::error("Initializing SDL_VIDEO failed."); Logger::error(SDL_GetError()); exit(Constants::STATUS_FAILED); } //Create Window //Enable Doublebuffering SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetSwapInterval(1); //VSync on window = SDL_CreateWindow(title, SDL_WINDOWPOS_CENTERED_DISPLAY(0), SDL_WINDOWPOS_CENTERED_DISPLAY(0), windowWidth, windowHeight, SDL_WINDOW_OPENGL); if (window == nullptr) { Logger::error("Initializing Window failed."); Logger::error(SDL_GetError()); exit(Constants::STATUS_FAILED); } //Create Context Logger::info("Creating SDL_GL Context"); context = SDL_GL_CreateContext(window); if (context == nullptr) { Logger::error("Initializing OpenGL Context failed."); Logger::error(SDL_GetError()); exit(Constants::STATUS_FAILED); } // Initialize OGL Logger::info("Initializing GLEW"); int glewError = glewInit(); if (glewError != GLEW_OK) { Logger::error("Initializing GLEW failed"); Logger::error(std::to_string(glewError).append(" - GLEW Error Code.")); exit(Constants::STATUS_FAILED); } Logger::info("Initializing OpenGL"); const GLubyte *glVersion = glGetString(GL_VERSION); std::string glVersionString = reinterpret_cast<char const *>(glVersion); Logger::info("OpenGL Version: " + glVersionString); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); GLenum glError = glGetError(); if (glError != GL_NO_ERROR) { Logger::error("Initializing OpenGL Failed"); Logger::error(std::to_string(glError).append(" - OpenGL Error Code.")); exit(Constants::STATUS_FAILED); } } Window::~Window() { SDL_DestroyWindow(window); SDL_Quit(); }
[ "TheKatze@users.noreply.github.com" ]
TheKatze@users.noreply.github.com
226a838a4922e07506984362213753f70815cade
6b552ae10d4b1871a41f3a6e3bd46a268d9344c0
/patterns/decorator/header.hpp
da342a180cb713d5da567ca9c890c2585135b9b5
[]
no_license
heyfaraday/cpp_examples
6326cbafc8638cefee45be3167d964582f596f12
85f9eae1ceaf4a3e5f0227d1eb5f5bb0eb607531
refs/heads/master
2020-03-11T18:33:23.593709
2018-04-22T15:23:48
2018-04-22T15:23:48
130,180,474
0
0
null
null
null
null
UTF-8
C++
false
false
538
hpp
#pragma once #include <string> #include <vector> #include <boost/algorithm/string.hpp> class String { private: std::string s; public: String(const std::string &s) : s(s) {} std::vector<std::string> split(std::string input) { std::vector<std::string> result; boost::split(result, s, boost::is_any_of(input), boost::token_compress_on); return result; } size_t get_length() const { return s.length(); } // non-standart! __declspec(property(get = get_length)) size_t length; };
[ "edigaryev.ig@phystech.edu" ]
edigaryev.ig@phystech.edu
b6d86aa2dd5fd7f6be5420afcc52d7616ac9ab54
1d571c0b0b55b2004d6812dbaed976ff1737ce28
/all-possible-full-binary-trees/all-possible-full-binary-trees.cpp
a7139fc81b01838a3c43e99d8da1e894be5f2aa7
[]
no_license
prajapati-rasik/Leetcode-Questions
ef799be458ca020286c2a1b1c55c075dc197b84b
022d4960f9343defafd64c1f1372ede686f44a7b
refs/heads/main
2023-08-16T16:24:44.370124
2021-09-26T06:28:55
2021-09-26T06:28:55
349,081,906
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
cpp
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: unordered_map<int, vector<TreeNode*> > m; vector<TreeNode*> allPossibleFBT(int n) { if(m.find(n) != m.end()){ return m[n]; }else if(n == 1){ vector<TreeNode*> v; v.push_back(new TreeNode(0)); m[1] = v; }else if(n%2 == 1){ vector<TreeNode*> v; for(int i = 0;i < n;i++){ int j = n - 1 - i; for(TreeNode* left : allPossibleFBT(i)){ for(TreeNode* right : allPossibleFBT(j)){ TreeNode* t = new TreeNode(0); t->left = left; t->right = right; v.push_back(t); } } } m[n] = v; } return m[n]; } };
[ "56621182+prajapati-rasik@users.noreply.github.com" ]
56621182+prajapati-rasik@users.noreply.github.com
ed51ca3562c2594c4a70aefd58f6d1546f34fdce
e0437abc4d30c290d74b0c8b0ffaba0150d8d847
/Source/TPS_Project/TPS_ProjectCharacter.h
2b0d18ce739f5010b0197cd84ed9adb87455f037
[]
no_license
MinjiMun/Unreal_WeekProject
c656b0e9205fedb3c02c3d1fe883b050a4d93b8b
e8de2e318216bd4fd680097d2e56b8bc5801ceaf
refs/heads/master
2022-11-15T05:11:42.306199
2020-07-14T15:17:17
2020-07-14T15:17:17
279,317,014
0
0
null
null
null
null
UTF-8
C++
false
false
2,227
h
// Copyright Epic Games, Inc. All Rights Reserved. #pragma once #include "CoreMinimal.h" #include "GameFramework/Character.h" #include "TPS_ProjectCharacter.generated.h" UCLASS(config=Game) class ATPS_ProjectCharacter : public ACharacter { GENERATED_BODY() /** Camera boom positioning the camera behind the character */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class USpringArmComponent* CameraBoom; /** Follow camera */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Camera, meta = (AllowPrivateAccess = "true")) class UCameraComponent* FollowCamera; public: ATPS_ProjectCharacter(); /** Base turn rate, in deg/sec. Other scaling may affect final turn rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera) float BaseTurnRate; /** Base look up/down rate, in deg/sec. Other scaling may affect final rate. */ UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category=Camera) float BaseLookUpRate; protected: /** Resets HMD orientation in VR. */ void OnResetVR(); /** Called for forwards/backward input */ void MoveForward(float Value); /** Called for side to side input */ void MoveRight(float Value); /** * Called via input to turn at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void TurnAtRate(float Rate); /** * Called via input to turn look up/down at a given rate. * @param Rate This is a normalized rate, i.e. 1.0 means 100% of desired turn rate */ void LookUpAtRate(float Rate); /** Handler for when a touch input begins. */ void TouchStarted(ETouchIndex::Type FingerIndex, FVector Location); /** Handler for when a touch input stops. */ void TouchStopped(ETouchIndex::Type FingerIndex, FVector Location); protected: // APawn interface virtual void SetupPlayerInputComponent(class UInputComponent* PlayerInputComponent) override; // End of APawn interface public: /** Returns CameraBoom subobject **/ FORCEINLINE class USpringArmComponent* GetCameraBoom() const { return CameraBoom; } /** Returns FollowCamera subobject **/ FORCEINLINE class UCameraComponent* GetFollowCamera() const { return FollowCamera; } };
[ "52391149+mmj0426@users.noreply.github.com" ]
52391149+mmj0426@users.noreply.github.com
5aed2da7ea2daa26d5e9340065382ca5dad91ecf
af7977991477325ddc604b6d3e2ac3cb4aa29337
/FlappyBirdGame3D3.0/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Collections_Generic_Dictionary_2_T3371700925.h
5e58f32ef43373613a7bf5d885f662705e0d2b03
[]
no_license
jpf2141/FlappyBird3D
b824cf5fac6ca3c5739afc342b659af1f2836ab9
fe4e9c421ec8dc26a7befd620f9deaf3c6361de5
refs/heads/master
2021-01-21T13:53:25.062470
2016-05-06T02:39:28
2016-05-06T02:39:28
55,712,365
3
1
null
null
null
null
UTF-8
C++
false
false
1,058
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.String struct String_t; // UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager/VirtualButton struct VirtualButton_t788573694; // System.IAsyncResult struct IAsyncResult_t537683269; // System.AsyncCallback struct AsyncCallback_t1363551830; // System.Object struct Il2CppObject; #include "mscorlib_System_MulticastDelegate2585444626.h" #include "mscorlib_System_Collections_DictionaryEntry130027246.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<System.String,UnityStandardAssets.CrossPlatformInput.CrossPlatformInputManager/VirtualButton,System.Collections.DictionaryEntry> struct Transform_1_t3371700925 : public MulticastDelegate_t2585444626 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "kdj2109@columbia.edu" ]
kdj2109@columbia.edu