blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author
stringlengths
0
119
b3a9f06a2beb496a368a28c02dc9d5a72e5c81d4
a84730d2a6666e7d7deb86ac939876ecf4397502
/littl/Unicode.hpp
f8a41c1783f57e7fbf742c91aac6cd76edcc432e
[]
no_license
minexew/littl
44587a113fceb5ef761139c3c94e10d168ce1918
7889fbc515a088f9ade6ccb8772aaff9c62dfe79
refs/heads/master
2021-06-06T05:03:59.158975
2020-02-04T10:03:01
2020-02-04T10:05:25
23,193,008
0
0
null
null
null
null
UTF-8
C++
false
false
2,249
hpp
/* Copyright (C) 2011, 2012, 2013 Xeatheran Minexew 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. */ #pragma once #include "Base.hpp" namespace li { class Unicode { public: typedef char32_t Char; static const Char backspaceChar = 0x00000008; static const Char tabChar = 0x00000009; static const Char lineFeedChar = 0x0000000A; static const Char invalidChar = 0xFFFFFFFF; static bool isAlpha( Char c ) { return ( c >= 'A' && c <= 'Z' ) || ( c >= 'a' && c <= 'z' ); } static bool isAlphaNumeric( Char c ) { return isAlpha( c ) || isNumeric( c ); } static bool isNumeric( Char c ) { return c >= '0' && c <= '9'; } }; struct UnicodeChar { Unicode::Char c; UnicodeChar( Unicode::Char c = Unicode::invalidChar ) : c( c ) {} UnicodeChar& operator = ( Unicode::Char c ) { this->c = c; return *this; } operator Unicode::Char& () { return c; } operator const Unicode::Char& () const { return c; } }; }
fb2f013c32dab39a97caef773ef5ba626ae401ec
e50b5f066628ef65fd7f79078b4b1088f9d11e87
/llvm/tools/clang/test/CodeGenObjCXX/block-nested-in-lambda.cpp
7c9714584ae4154586106fb09845266cc5a24e23
[ "NCSA" ]
permissive
uzleo/coast
1471e03b2a1ffc9883392bf80711e6159917dca1
04bd688ac9a18d2327c59ea0c90f72e9b49df0f4
refs/heads/master
2020-05-16T11:46:24.870750
2019-04-23T13:57:53
2019-04-23T13:57:53
183,025,687
0
0
null
2019-04-23T13:52:28
2019-04-23T13:52:27
null
UTF-8
C++
false
false
1,213
cpp
// RUN: %clang_cc1 -triple=x86_64-apple-darwin10 -emit-llvm -std=c++11 -fblocks -o - %s | FileCheck %s // CHECK: %[[BLOCK_CAPTURED0:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>, <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>* %[[BLOCK:.*]], i32 0, i32 5 // CHECK: %[[V0:.*]] = getelementptr inbounds %[[LAMBDA_CLASS:.*]], %[[LAMBDA_CLASS]]* %[[THIS:.*]], i32 0, i32 0 // CHECK: %[[V1:.*]] = load i32*, i32** %[[V0]], align 8 // CHECK: store i32* %[[V1]], i32** %[[BLOCK_CAPTURED0]], align 8 // CHECK: %[[BLOCK_CAPTURED1:.*]] = getelementptr inbounds <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>, <{ i8*, i32, i32, i8*, %struct.__block_descriptor*, i32*, i32* }>* %[[BLOCK]], i32 0, i32 6 // CHECK: %[[V2:.*]] = getelementptr inbounds %[[LAMBDA_CLASS]], %[[LAMBDA_CLASS]]* %[[THIS]], i32 0, i32 1 // CHECK: %[[V3:.*]] = load i32*, i32** %[[V2]], align 8 // CHECK: store i32* %[[V3]], i32** %[[BLOCK_CAPTURED1]], align 8 void foo1(int &, int &); void block_in_lambda(int &s1, int &s2) { auto lambda = [&s1, &s2]() { auto block = ^{ foo1(s1, s2); }; block(); }; lambda(); }
dd3ab9dbbfdc817ace282aa442f3d1fa37a845a9
1349bac38d0c70d2d4abf45adb5ce08423b128f2
/Proyecto/4-Sistema-utilizando-clases/clientes.h
89be9e081145309926ee08fca459dcd219e46b8c
[ "MIT" ]
permissive
jdelcidz/cpp-1
4c5cac6bc35bbbee07cdabc4d1636348bbbc1a53
47562fac7939ac0e942f5ad29a08d6405996c9a0
refs/heads/master
2022-10-22T13:01:43.299891
2020-06-13T15:01:48
2020-06-13T15:01:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
385
h
#include <iostream> using namespace std; class Cliente { public: string Codigo; string Nombre; string Telefono; Cliente() { } Cliente(string codigo, string nombre, string telefono) { Codigo = codigo; Nombre = nombre; Telefono = telefono; } }; void inicializarDatosdeClientes(); void clientes(); bool buscarCliente(string &codigo, string &nombreCliente);
75c791d96d328bde914eede19276e9f4751d49c0
67efc5a1259f2ea7f592bbf37f05e0cd5542cea6
/PA9_KendraKendall/Square.cpp
54ac4c0bf4bb9bdb466459507ab58450e4ef0a91
[]
no_license
kylerlittle/worlds-hardest-game
c96e7a7ed7a618c7609232ea9727e1a8e35b5c9d
403be2795a984982e7bd5d9da7945b48f4f8e74c
refs/heads/master
2021-07-06T14:44:04.622126
2017-09-26T22:58:27
2017-09-26T22:58:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
212
cpp
#include "Square.h" /*Default constructor*/ Square::Square() : RectangleShape(sf::Vector2f(SQUARE_LEN, SQUARE_LEN)) { setFillColor(sf::Color::Red); setOutlineThickness(1); setOutlineColor(sf::Color::Black); }
[ "Kyler Little@DESKTOP-KQ9SPFN" ]
Kyler Little@DESKTOP-KQ9SPFN
f5e5fbaec7699770d69f36d7f0405fe2cc42c653
abf463fdb8a7c7631fb1db4380807e336f039ea6
/c++/pointerstofunction.cpp
93ed02f826d163fb363b2f16df12b66e61fa70d2
[]
no_license
Jayad/Program_practise
ea1a16bf17519e581d75978c062c2f31a960c7a2
6de6f5cf8ebb24b264f999853cb11925c00ac746
refs/heads/master
2021-06-16T08:33:50.630104
2017-03-27T16:12:41
2017-03-27T16:12:41
8,859,196
0
0
null
null
null
null
UTF-8
C++
false
false
580
cpp
#include<iostream> using namespace std; int addition(int a, int b) { return (a+b); } int subtraction(int a, int b) { return (a-b); } int operation(int a, int b, int (*func)(int a, int b)) { int g; g=(*func)(a,b); return g; } int main() { int m,n,p; //minus is a pointer to a function that has two parameters of type int. It is immediately assigned to point to the function subtraction, all in a single line: int (*minus)(int,int) =subtraction; m=operation(5,6,addition); n=operation(25,m,minus); p=operation(25,m,subtraction); cout << n <<endl; cout << p <<endl; return 0; }
3bd86ff317413bcd0786f4b5352373e6245f56a7
83552346a7d778e88569fdc16d686576836a1977
/Plan/main.cpp
0732972378ade10c53ec99576a6e85ad0bac7b55
[]
no_license
Berezowski-Dominik/Plan_generator
75baddb2a4aadf6543e64b6fdef70889a683419f
66edc08eb6c5428bf733f77b3e8e4f3400c6e225
refs/heads/master
2023-08-22T22:58:06.735671
2021-10-10T19:00:07
2021-10-10T19:00:07
415,674,221
0
0
null
null
null
null
UTF-8
C++
false
false
66,307
cpp
#include <stdio.h> #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <cmath> #include <map> #include <cmath> #include <set> #include <ctime> #include <algorithm> #include <sys/stat.h> #include "Przedmiot.h" #include "Nauczyciel.h" #include "Nad_grupa.h" #include "Grupa.h" #include "Zajecia.h" #include "Sala.h" using namespace std; int Wczytanie_Przedmiotow(vector<vector<Przedmiot>>&Przedmioty_Lab,vector<vector<Przedmiot>>&Przedmioty_Cw,vector<vector<Przedmiot>>&Przedmioty_Wykl); int Wczytanie_Nauczycieli(vector < Nauczyciel> &Nauczyciele); void Wczytanie_Grup(vector <vector<Nad_grupa>> &Grupy_Wyk, vector <vector<Nad_grupa>> &Grupy_Cw, vector<vector<Grupa>> &Grupy_Lab); void Wczytanie_Sal(vector <Sala> &Sala_Wykl,vector <Sala> &Sala_Cw,vector <Sala> &Sala_Lab); int Czy_istnieje_plik(const char* nazwa_pliku); void Podzial_nauczycieli_i_przedmiotow(); void Dop_godz_nauczycieli(vector < Nauczyciel> &Nauczyciele); void Niedop_godz_nauczycieli(vector < Nauczyciel> &Nauczyciele); void Grup_Wyk_Podz(vector <vector<Nad_grupa>> &Grupy_Wyk,vector <vector<Grupa>> &Grupy_Lab,vector <vector<Nad_grupa>> &Grupy_Cw); void Grup_Cw_Podz(vector<vector<Nad_grupa>> &Grupy_Cw, vector <vector<Grupa>> &Grupy_Lab); void Wczytanie_nauczycieli_wykladow(vector <vector<Przedmiot>> &Przedmioty_Wykl,vector <Nauczyciel> &Nauczyciele); void Wczytanie_nauczycieli_cwiczen(vector <vector<Przedmiot>> &Przedmioty_Cw,vector < Nauczyciel> &Nauczyciele); void Wczytanie_nauczycieli_laborek(vector <vector<Przedmiot>> &Przedmioty_Lab,vector < Nauczyciel> &Nauczyciele); void Zajecia_wykladowe(vector <Zajecia> &Zajecie,vector<vector<Przedmiot>> &Przedmioty_Wykl,vector <vector<Nad_grupa>> &Grupy_Wyk,vector<Sala> &Sala_Wykl,int &il_wykl); void Zajecia_cwiczeniowe(vector <Zajecia> &Zajecie,vector<vector<Przedmiot>> &Przedmioty_Cw,vector <vector<Nad_grupa>> &Grupy_Cw,vector<Sala> &Sala_Cw, int &il_wykl_i_cw); void Zajecia_laborki(vector <Zajecia> &Zajecie,vector <vector<Przedmiot>> &Przedmioty_Lab,vector <vector<Grupa>> &Grupy_Lab,vector<Sala> &Sala_Lab); void Zajecia_nauczyciele(vector<Zajecia> &Zajecie,vector<Nauczyciel> &Nauczyciele,int il_wykl,int il_wykl_i_cw); void Tworzenie_harmonogramu(vector <Zajecia> &Zajecie); void Wypisanie_danych_harmonogramu(vector <Zajecia> &Zajecie,vector <vector<Grupa>> &Grupy_Lab, vector <Nauczyciel> &Nauczyciele); float Kara_laczna_grup(vector<vector<Grupa>> &Grupy_Lab); float Kara_laczna_nauczycieli(vector <Nauczyciel> &Nauczyciele); float Ogolna_kara_planu(vector <vector<Grupa>> &Grupy_Lab,vector <Nauczyciel> &Nauczyciele); void Poprawianie_grupy(vector <Zajecia> &Zajecie,vector <float>::iterator &it, vector <float> &kara_grupy, vector <Grupa*> &Grupy_Lab, int &najg_grupa); void Poprawianie_nauczycieli(vector <Zajecia> &Zajecie,vector <float>::iterator &it, vector <float> &kara_nauczy, vector <Nauczyciel> &Nauczyciele, int &najg_nauczy); void Poprawianie_harmonogramu(vector <Zajecia> &Zajecie,vector <vector<Grupa>> &Grupy_Lab,vector <Nauczyciel> &Nauczyciele, vector <Sala> Sala_Lab, int ile_popraw); void Wypisywanie_planow_grup(vector <vector<Grupa>> &Grupy_Lab,vector <Zajecia> &Zajecie_Naj); void Wypisywanie_planow_nauczycieli(vector <Nauczyciel> &Nauczyciele_Naj,vector <Zajecia> &Zajecie_Naj); int main(int argc, char **argv) { srand(time(NULL)); fstream plik; vector<vector<Przedmiot>>Przedmioty_Lab; vector<vector<Przedmiot>>Przedmioty_Cw; vector<vector<Przedmiot>>Przedmioty_Wykl; vector<vector<Grupa>>Grupy_Lab; vector<vector<Nad_grupa>>Grupy_Cw; vector<vector<Nad_grupa>>Grupy_Wykl; vector <Sala> Sala_Wykl; vector <Sala> Sala_Cw; vector <Sala> Sala_Lab; vector <Zajecia> Zajecie; vector<Nauczyciel>Nauczyciele; int il_wykl = 0; int il_wykl_i_cw = 0; if(Czy_istnieje_plik("wyklady_nauczyciele.csv") == 0) { cout << "Brak koniecznych pilkow do stworzenia planiu !!!" << endl; cout << "Uzupelnij stworzone plik w katalogu programu: " << endl; cout << "wyklady_nauczyciele.csv,cwiczenia_nauczyciele.csv,laborki_nauczyciele.csv" << endl; Podzial_nauczycieli_i_przedmiotow(); } else if(Czy_istnieje_plik("wyklady_nauczyciele.csv") != 0) { Wczytanie_Przedmiotow(Przedmioty_Lab,Przedmioty_Cw,Przedmioty_Wykl); Wczytanie_Nauczycieli(Nauczyciele); Wczytanie_Grup(Grupy_Wykl,Grupy_Cw,Grupy_Lab); Wczytanie_Sal(Sala_Wykl,Sala_Cw,Sala_Lab); Grup_Wyk_Podz(Grupy_Wykl,Grupy_Lab,Grupy_Cw); Grup_Cw_Podz(Grupy_Cw,Grupy_Lab); Wczytanie_nauczycieli_wykladow(Przedmioty_Wykl,Nauczyciele); Wczytanie_nauczycieli_cwiczen(Przedmioty_Cw,Nauczyciele); Wczytanie_nauczycieli_laborek(Przedmioty_Lab,Nauczyciele); Zajecia_wykladowe(Zajecie,Przedmioty_Wykl,Grupy_Wykl,Sala_Wykl,il_wykl); Zajecia_cwiczeniowe(Zajecie,Przedmioty_Cw,Grupy_Cw,Sala_Cw,il_wykl_i_cw); Zajecia_laborki(Zajecie,Przedmioty_Lab,Grupy_Lab,Sala_Lab); Zajecia_nauczyciele(Zajecie,Nauczyciele,il_wykl,il_wykl_i_cw); Tworzenie_harmonogramu(Zajecie); Poprawianie_harmonogramu(Zajecie,Grupy_Lab,Nauczyciele,Sala_Lab,10); cout <<"Kara najlepszego rozwiazania wynosi: " << Ogolna_kara_planu(Grupy_Lab,Nauczyciele) << endl; Wypisywanie_planow_grup(Grupy_Lab,Zajecie); Wypisywanie_planow_nauczycieli(Nauczyciele,Zajecie); } return 0; } void Wypisywanie_planow_nauczycieli(vector <Nauczyciel> &Nauczyciele,vector <Zajecia> &Zajecie) { int ilosc_nauczycieli = Nauczyciele.size(); string nazwa_pliku; ofstream plik; nazwa_pliku.append("plany_nauczycieli.csv"); plik.open(nazwa_pliku,ios::out); string do_pliku; for(int i = 0; i < ilosc_nauczycieli; i++) { do_pliku.append(Nauczyciele[i].Zwroc_imie_i_nazwisko()); do_pliku.append("\n"); for(int j = 0; j < 4; j++) { for(int k = 0; k < 20; k+=4) { if(Nauczyciele[i].Numer_zajecia(k+j) != 0) { do_pliku.append(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].przedmiot()->Zwroc_nazwe()); do_pliku.append(" "); do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].sala()->Zwroc_numer())); do_pliku.append(" "); if(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa() == NULL) { do_pliku.append(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].grupa()->Zwroc_kierunek()); do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].grupa()->Zwroc_stopien())); do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].grupa()->Zwroc_rocznik())); do_pliku.append(to_string(3)); do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].grupa()->Zwroc_numer())); } if(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa() != NULL) { do_pliku.append(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->grupa_lab(0)->Zwroc_kierunek()); do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->grupa_lab(0)->Zwroc_stopien())); do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->grupa_lab(0)->Zwroc_rocznik())); do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->Zwroc_rodzaj())); do_pliku.append(to_string(Zajecie[Nauczyciele[i].Numer_zajecia(k+j)-1].nad_grupa()->Zwroc_numer_grupy())); } do_pliku.append(","); } else { do_pliku.append("Wolne,"); } } do_pliku.append("\n"); plik << do_pliku; do_pliku.clear(); } do_pliku.append("\n"); } plik.close(); } void Wypisywanie_planow_grup(vector <vector<Grupa>> &Grupy_Lab,vector <Zajecia> &Zajecie) { int ilosc_zbiorow_grup = Grupy_Lab.size(); int ilosc_grup = 0; string nazwa_pliku; ofstream plik; for(int l = 0; l < ilosc_zbiorow_grup; l++) { nazwa_pliku.append(Grupy_Lab[l][0].Zwroc_kierunek()); nazwa_pliku.append(to_string(Grupy_Lab[l][0].Zwroc_stopien())); nazwa_pliku.append(to_string(Grupy_Lab[l][0].Zwroc_rocznik())); nazwa_pliku.append(".csv"); plik.open(nazwa_pliku,ios::out); nazwa_pliku.clear(); string do_pliku; ilosc_grup = Grupy_Lab[l].size(); for(int i = 0; i < ilosc_grup; i++) { do_pliku.append("Grupa"); do_pliku.append(to_string(Grupy_Lab[l][i].Zwroc_numer())); do_pliku.append("\n"); for(int j = 0; j < 4; j++) { for(int k = 0; k < 20; k+=4) { if(Grupy_Lab[l][i].Zwroc_numer_zaj(k+j) != 0) { do_pliku.append(Zajecie[Grupy_Lab[l][i].Zwroc_numer_zaj(k+j)-1].przedmiot()->Zwroc_nazwe()); do_pliku.append(" "); do_pliku.append(Zajecie[Grupy_Lab[l][i].Zwroc_numer_zaj(k+j)-1].Zwroc_imie_i_nazwisko_nauczyciela()); do_pliku.append(" "); do_pliku.append(to_string(Zajecie[Grupy_Lab[l][i].Zwroc_numer_zaj(k+j)-1].sala()->Zwroc_numer())); do_pliku.append(","); } else { do_pliku.append("Wolne,"); } } do_pliku.append("\n"); plik << do_pliku; do_pliku.clear(); } do_pliku.append("\n"); } plik.close(); } } void Podzial_nauczycieli_i_przedmiotow() { vector<Nauczyciel> nauczyciele; vector<vector<Przedmiot>> przedmioty_lab; vector<vector<Przedmiot>> przedmioty_cw; vector<vector<Przedmiot>> przedmioty_wykl; vector<vector<Grupa>> grupy_lab; vector<vector<Nad_grupa>> grupy_cw; vector<vector<Nad_grupa>> grupy_wykl; Wczytanie_Nauczycieli(nauczyciele); Wczytanie_Przedmiotow(przedmioty_lab,przedmioty_cw,przedmioty_wykl); Wczytanie_Grup(grupy_wykl,grupy_cw,grupy_lab); int ilosc_zbiorow_wykladow = przedmioty_wykl.size(); int ilosc_zbiorow_cwiczen = przedmioty_cw.size(); int ilosc_zbiorow_laborek = przedmioty_lab.size(); int ilosc_nauczycieli = nauczyciele.size(); int ilosc_wykladow = 0; int ilosc_cwiczen = 0; int ilosc_laborek = 0; ofstream plik; plik.open("wyklady_nauczyciele.csv",ios::out); for(int i = 0; i < ilosc_zbiorow_wykladow; i++) { ilosc_wykladow = przedmioty_wykl[i].size(); for(int j = 0; j < ilosc_wykladow; j++) { plik << ","; plik << przedmioty_wykl[i][j].Zwroc_nazwe(); } plik << ",Ilosc grup-"; plik << grupy_wykl[i].size(); plik << ","; } plik << "\n"; for(int i = 0; i < ilosc_nauczycieli; i++) { plik << nauczyciele[i].Zwroc_imie_i_nazwisko(); plik << ",\n"; } plik.close(); plik.open("cwiczenia_nauczyciele.csv",ios::out); for(int i = 0; i < ilosc_zbiorow_cwiczen; i++) { ilosc_cwiczen = przedmioty_cw[i].size(); for(int j = 0; j < ilosc_cwiczen; j++) { plik << ","; plik << przedmioty_cw[i][j].Zwroc_nazwe(); } plik << ",Ilosc grup-"; plik << grupy_cw[i].size(); plik << ","; } plik << "\n"; for(int i = 0; i < ilosc_nauczycieli; i++) { plik << nauczyciele[i].Zwroc_imie_i_nazwisko(); plik << ",\n"; } plik.close(); plik.open("laborki_nauczyciele.csv",ios::out); for(int i = 0; i < ilosc_zbiorow_laborek; i++) { ilosc_laborek = przedmioty_lab[i].size(); for(int j = 0; j < ilosc_laborek; j++) { plik << ","; plik << przedmioty_lab[i][j].Zwroc_nazwe(); } plik << ",Ilosc grup-"; plik << grupy_lab[i].size(); plik << ","; } plik << "\n"; for(int i = 0; i < ilosc_nauczycieli; i++) { plik << nauczyciele[i].Zwroc_imie_i_nazwisko(); plik << ",\n"; } plik.close(); } float Ogolna_kara_planu(vector <vector<Grupa>> &Grupy_Lab,vector <Nauczyciel> &Nauczyciele) { return Kara_laczna_grup(Grupy_Lab) + Kara_laczna_nauczycieli(Nauczyciele); } void Poprawianie_nauczycieli(vector <Zajecia> &Zajecie,vector <float>::iterator &it, vector <float> &kara_nauczy, vector <Nauczyciel> &Nauczyciele, int &najg_nauczy) { vector <int> pozyc_labek; vector <int> sprawdz_nauczy; int labki = 0; int ile_spraw_naucz = 0; int i = 0; while(i == 0) { int ilosc_labek = Nauczyciele[najg_nauczy].Ile_lab_w_planie(); for(int i = 0; i < ilosc_labek; i++) { pozyc_labek.push_back(Nauczyciele[najg_nauczy].Termin_labek(i)); } ilosc_labek++; pozyc_labek.push_back(20); labki = ilosc_labek-1; do { pozyc_labek.erase(pozyc_labek.begin()+labki); ilosc_labek--; labki = rand() % ilosc_labek; }while((!Zajecie[Nauczyciele[najg_nauczy].Numer_zajecia(pozyc_labek[labki])-1].Mozliwosc_zmiany()) || (ilosc_labek == 0)); if(ilosc_labek == 0) { i--; kara_nauczy[najg_nauczy] = 0; sprawdz_nauczy.push_back(najg_nauczy); it = max_element(kara_nauczy.begin(),kara_nauczy.end()); najg_nauczy = distance(kara_nauczy.begin(), it); } else { Zajecie[Nauczyciele[najg_nauczy].Numer_zajecia(pozyc_labek[labki])-1].Zmiana_terminu(); kara_nauczy[najg_nauczy] = Nauczyciele[najg_nauczy].Zwroc_kare(); ile_spraw_naucz = sprawdz_nauczy.size(); for(int i = 0; i < ile_spraw_naucz; i++) { kara_nauczy[sprawdz_nauczy[i]] = Nauczyciele[sprawdz_nauczy[i]].Zwroc_kare(); } } sprawdz_nauczy.clear(); pozyc_labek.clear(); it = max_element(kara_nauczy.begin(),kara_nauczy.end()); najg_nauczy = distance(kara_nauczy.begin(), it); i++; } } void Poprawianie_grupy(vector <Zajecia> &Zajecie,vector <float>::iterator &it, vector <float> &kara_grupy, vector <Grupa*> &Grupy_Lab,int &najg_grupa) { vector <int> pozyc_labek; vector <int> sprawdzone_grupy; int labki = 0; int ile_spraw_grup = 0; int i = 0; while(i == 0) { int ilosc_labek = Grupy_Lab[najg_grupa]->Ile_lab_w_planie(); for(int i = 0; i < ilosc_labek; i++) { pozyc_labek.push_back(Grupy_Lab[najg_grupa]->Termin_labek(i)); } ilosc_labek++; pozyc_labek.push_back(20); labki = ilosc_labek-1; do { pozyc_labek.erase(pozyc_labek.begin()+labki); ilosc_labek--; labki = rand() % ilosc_labek; }while((!Zajecie[Grupy_Lab[najg_grupa]->Zwroc_numer_zaj(pozyc_labek[labki])-1].Mozliwosc_zmiany()) || (ilosc_labek == 0)); if(ilosc_labek == 0) { i--; kara_grupy[najg_grupa] = 0; sprawdzone_grupy.push_back(najg_grupa); it = max_element(kara_grupy.begin(),kara_grupy.end()); najg_grupa = distance(kara_grupy.begin(), it); } else { Zajecie[Grupy_Lab[najg_grupa]->Zwroc_numer_zaj(pozyc_labek[labki])-1].Zmiana_terminu(); kara_grupy[najg_grupa] = Grupy_Lab[najg_grupa]->Zwroc_kare(); ile_spraw_grup = sprawdzone_grupy.size(); for(int i = 0; i < ile_spraw_grup; i++) { kara_grupy[sprawdzone_grupy[i]] = Grupy_Lab[sprawdzone_grupy[i]]->Zwroc_kare(); } } sprawdzone_grupy.clear(); pozyc_labek.clear(); it = max_element(kara_grupy.begin(),kara_grupy.end()); najg_grupa = distance(kara_grupy.begin(), it); i++; } } float Kara_laczna_grup(vector<vector<Grupa>> &Grupy_Lab) { int ilosc_zbiorow_grup = Grupy_Lab.size(); float suma_kar = 0; for(int j = 0; j < ilosc_zbiorow_grup;j++) { int ilosc_grup = Grupy_Lab[j].size(); for(int i = 0; i < ilosc_grup; i++) { suma_kar += Grupy_Lab[j][i].Oblicz_kare(); } } return suma_kar; } float Kara_laczna_nauczycieli(vector < Nauczyciel> &Nauczyciele) { int ilosc_nauczycieli = Nauczyciele.size(); float suma_kar = 0; for(int i = 0; i < ilosc_nauczycieli; i++) { suma_kar += Nauczyciele[i].Oblicz_kare(); } return suma_kar; } void Grup_Cw_Podz(vector <Nad_grupa> &Grupy_Cw, vector <Grupa> &Grupy_Lab,vector <Nad_grupa> &Grupy_Wyk) { int Wszystkie_gr_lab = Grupy_Lab.size(); float nie_przydzielone_gr_lab = Grupy_Lab.size(); int ilosc_gr_do_stworzenia = Grupy_Cw.size(); float wielkosc_nowa_gr_cwiczeniowa = 0; for (int i = ilosc_gr_do_stworzenia; i > 0; i--) { wielkosc_nowa_gr_cwiczeniowa = round(nie_przydzielone_gr_lab / i); for(int j = 0; j < wielkosc_nowa_gr_cwiczeniowa; j++) { Grupy_Cw[ilosc_gr_do_stworzenia - i].grupa_lab()->push_back(&Grupy_Lab[j + Wszystkie_gr_lab - nie_przydzielone_gr_lab]); } nie_przydzielone_gr_lab -= wielkosc_nowa_gr_cwiczeniowa; } } int Wczytanie_Nauczycieli(vector < Nauczyciel> &Nauczyciele) { fstream plik; plik.open("nauczyciele.csv", ios::in | ios::out); if(plik.is_open()) { cout << "Poprawne otwarcie pliku z nauczycielami" << endl; string linia; string czesc; vector <string> dane; int i = 0; while(!plik.eof()) { plik >> linia; if(linia == ";") { break; return 1; } else { if(linia == "") cout << "Blad w wierszu " << i << endl; else Nauczyciele.push_back({linia}); } i++; } plik.close(); } else cout<<"Nie udało się otworzyć pliku z nauczycielami"; return 1; } void Dop_godz_nauczycieli(vector < Nauczyciel> &Nauczyciele) { fstream plik; plik.open("dop_term_nauczycieli.csv", ios::in | ios::out); int numer = 0; if(plik.is_open()) { cout << "Plik z dopuszczalnymi terminami nauczycieli otwarty" << endl << endl; string linia; string czesc; vector <string> dane; int ile_godzin = 0; while(!plik.eof()) { plik >> linia; if(linia == ";") break; stringstream strumien(linia); while(getline(strumien,czesc,',')) { dane.push_back(czesc); } if(dane[0] == "") { dane.erase(dane.begin(), dane.end()); numer++; continue; } else if(dane[0] != "") { ile_godzin = dane.size(); for(int i = 0; i < ile_godzin; i++) { Nauczyciele[numer].Dodanie_dop_terminu(stoi(dane[i])-1); } dane.erase(dane.begin(), dane.end()); numer++; } } plik.close(); } else cout<<"Nie udało się otworzyć pliku z dopuszczalnymi terminami nauczycieli"; } void Niedop_godz_nauczycieli(vector < Nauczyciel> &Nauczyciele) { fstream plik; plik.open("niedop_term_nauczycieli.csv", ios::in | ios::out); int numer = 0; if(plik.is_open()) { cout << "Plik z niedopuszczalnymi terminami nauczycieli otwarty" << endl << endl; string linia; string czesc; vector <string> dane; int ile_godzin = 0; while(!plik.eof()) { plik >> linia; if(linia == ";") break; stringstream strumien(linia); while(getline(strumien,czesc,',')) { dane.push_back(czesc); } if(dane[0] == "") { dane.erase(dane.begin(), dane.end()); numer++; continue; } else if(dane[0] != "") { ile_godzin = dane.size(); for(int i = 0; i < ile_godzin; i++) { Nauczyciele[numer].Dodanie_niedos_terminu(stoi(dane[i])-1); Nauczyciele[numer].Dodanie_zaj_terminu(stoi(dane[i])-1); } dane.erase(dane.begin(), dane.end()); numer++; } } plik.close(); } else cout<<"Nie udało się otworzyć pliku z niedopuszczalnymi terminami nauczycieli"; } int Wczytanie_Przedmiotow(vector<vector<Przedmiot>>&Przedmioty_Lab,vector<vector<Przedmiot>>&Przedmioty_Cw,vector<vector<Przedmiot>>&Przedmioty_Wykl) { string linia; string czesc; vector <string> dane; int numer_wyk = 0; int numer_cw = 0; int numer_lab = 0; int przedmioty = 0; int numer_wiersza = 1; Przedmioty_Wykl.push_back(vector<Przedmiot>()); Przedmioty_Cw.push_back(vector<Przedmiot>()); Przedmioty_Lab.push_back(vector<Przedmiot>()); fstream plik; plik.open("przedmioty.csv", ios::in | ios::out); if(plik.is_open()) { cout << "Poprawne otwarcie pliku z przedmiotami" << endl; while(!plik.eof()) { plik >> linia; stringstream strumien(linia); while(getline(strumien,czesc,',')) { dane.push_back(czesc); } if(dane[0] == "" && dane[1] == "") { Przedmioty_Wykl.push_back(vector<Przedmiot>()); Przedmioty_Cw.push_back(vector<Przedmiot>()); Przedmioty_Lab.push_back(vector<Przedmiot>()); przedmioty++; } else if(dane[0] == ";") { break; return 1; } else { if(dane[0] == "") {cout << "Brak nazwy przedmiotu w wierszu " << numer_wiersza << endl; return 0;} if((dane[1] == "") || ((dane[1] != "1") && (dane[1] != "2") && (dane[1] != "3"))) {cout << "Bledna wartosc w 2 kolumnie wiersza " << numer_wiersza << endl; return 0;} if((dane[2] == "") || ((dane[2] != "1") && (dane[2] != "2"))) {cout << "Bledna wartosc w 3 kolumnie wiersza " << numer_wiersza << endl; return 0;} if(stoi(dane[1]) == 1) { Przedmioty_Wykl[przedmioty].push_back({dane[0],stoi(dane[1]),stoi(dane[2]),numer_wyk}); numer_wyk++; } else if(stoi(dane[1]) == 2) { Przedmioty_Cw[przedmioty].push_back({dane[0],stoi(dane[1]),stoi(dane[2]),numer_cw}); numer_cw++; } else if(stoi(dane[1]) == 3) { Przedmioty_Lab[przedmioty].push_back({dane[0],stoi(dane[1]),stoi(dane[2]),numer_lab}); numer_lab++; } } numer_wiersza++; dane.erase(dane.begin(), dane.end()); } plik.close(); } else cout<<"Nie udało się otworzyć pliku z przedmiotami"; return 1; } int Czy_istnieje_plik(const char* nazwa_pliku) { struct stat bufor; if (stat(nazwa_pliku,&bufor) == 0) return 1; else return 0; } void Wczytanie_Grup(vector<vector<Nad_grupa>>&Grupy_Wyk, vector<vector<Nad_grupa>>&Grupy_Cw, vector<vector<Grupa>>&Grupy_Lab) { string linia; string czesc; vector <string> dane; int zbior_grup = 0; int j = 0; fstream plik; plik.open("grupy.csv", ios::in | ios::out); if(plik.is_open()) { while(!plik.eof()) { plik >> linia; stringstream strumien(linia); while(getline(strumien,czesc,',')) { dane.push_back(czesc); } if(dane[0] != "" && dane[0] != ";") { Grupy_Wyk.push_back(vector<Nad_grupa>()); Grupy_Cw.push_back(vector<Nad_grupa>()); Grupy_Lab.push_back(vector<Grupa>()); if(dane[1] == "" || dane[2] == "" || dane[3] == "" || dane[4] == "" || dane[5] == "") cout << "Blad w wierszu " << j << endl; else { for(int i = 0; i < stoi(dane[3]); i++) { Grupy_Wyk[zbior_grup].push_back({1,i+1}); } for(int i = 0; i < stoi(dane[4]); i++) { Grupy_Cw[zbior_grup].push_back({2,i+1}); } for(int i = 0; i < stoi(dane[5]); i++) { Grupy_Lab[zbior_grup].push_back({dane[0],stoi(dane[1]),stoi(dane[2]),i+1}); } zbior_grup++; } } else if(dane[0] == ";") { break; } j++; dane.erase(dane.begin(), dane.end()); } plik.close(); } else cout<<"Nie udało się otworzyć pliku z przedmiotami"; } void Wczytanie_Sal(vector <Sala> &Sala_Wykl,vector <Sala> &Sala_Cw,vector <Sala> &Sala_Lab) { fstream plik; plik.open("sale.csv", ios::in | ios::out); if(plik.is_open()) { string linia; string czesc; vector <string> dane; while(!plik.eof()) { plik >> linia; stringstream strumien(linia); while(getline(strumien,czesc,',')) { dane.push_back(czesc); } if(dane[0] != "" && dane[0] != ";") { if(stoi(dane[0]) == 1) { for(int i = 0; i < stoi(dane[1]); i++) { if(dane[2+i] == "") { cout << "Brak numeru sali wykladowej" << endl; } else { Sala_Wykl.push_back({stoi(dane[2+i])}); } } } else if(stoi(dane[0]) == 2) { for(int i = 0; i < stoi(dane[1]); i++) { if(dane[2+i] == "") { cout << "Brak numeru sali cwiczeniowej" << endl; } else { Sala_Cw.push_back({stoi(dane[2+i])}); } } } else if(stoi(dane[0]) == 3) { for(int i = 0; i < stoi(dane[1]); i++) { if(dane[2+i] == "") { cout << "Brak numeru sali laboratoryjnej" << endl; } else { Sala_Lab.push_back({stoi(dane[2+i])}); } } } } else if(dane[0] == ";") { break; } dane.erase(dane.begin(), dane.end()); } plik.close(); } else cout<<"Nie udało się otworzyć pliku z salami"; } void Grup_Wyk_Podz(vector<vector<Nad_grupa>> &Grupy_Wyk,vector<vector<Grupa>> &Grupy_Lab,vector <vector<Nad_grupa>> &Grupy_Cw) { int ilosc_rocznikow = Grupy_Wyk.size(); for(int k = 0; k < ilosc_rocznikow; k++) { int Wszystkie_gr_lab = Grupy_Lab[k].size(); int nie_przydzielone_gr_lab = Grupy_Lab[k].size(); int Wszystkie_gr_cw = Grupy_Cw[k].size(); int nie_przydzielone_gr_cw = Grupy_Cw[k].size(); int ilosc_gr_do_stworzenia = Grupy_Wyk[k].size(); int wielkosc_nowa_gr_wykladowa = 0; for (int i = ilosc_gr_do_stworzenia; i > 0; i--) { wielkosc_nowa_gr_wykladowa = round(nie_przydzielone_gr_cw / i); for(int j = 0; j < wielkosc_nowa_gr_wykladowa; j++) { Grupy_Wyk[k][ilosc_gr_do_stworzenia - i].grupa_cw()->push_back(&Grupy_Cw[k][j + Wszystkie_gr_cw - nie_przydzielone_gr_cw]); } nie_przydzielone_gr_cw -= wielkosc_nowa_gr_wykladowa; } for (int i = ilosc_gr_do_stworzenia; i > 0; i--) { wielkosc_nowa_gr_wykladowa = round(nie_przydzielone_gr_lab / i); for(int j = 0; j < wielkosc_nowa_gr_wykladowa; j++) { Grupy_Wyk[k][ilosc_gr_do_stworzenia - i].grupa_lab()->push_back(&Grupy_Lab[k][j + Wszystkie_gr_lab - nie_przydzielone_gr_lab]); } nie_przydzielone_gr_lab -= wielkosc_nowa_gr_wykladowa; } } } void Grup_Cw_Podz(vector<vector<Nad_grupa>> &Grupy_Cw, vector <vector<Grupa>> &Grupy_Lab) { int ilosc_rocznikow = Grupy_Cw.size(); for(int k = 0; k < ilosc_rocznikow; k++) { int Wszystkie_gr_lab = Grupy_Lab[k].size(); float nie_przydzielone_gr_lab = Grupy_Lab[k].size(); int ilosc_gr_do_stworzenia = Grupy_Cw[k].size(); float wielkosc_nowa_gr_cwiczeniowa = 0; for (int i = ilosc_gr_do_stworzenia; i > 0; i--) { wielkosc_nowa_gr_cwiczeniowa = round(nie_przydzielone_gr_lab / i); for(int j = 0; j < wielkosc_nowa_gr_cwiczeniowa; j++) { Grupy_Cw[k][ilosc_gr_do_stworzenia - i].grupa_lab()->push_back(&Grupy_Lab[k][j + Wszystkie_gr_lab - nie_przydzielone_gr_lab]); } nie_przydzielone_gr_lab -= wielkosc_nowa_gr_cwiczeniowa; } } } void Wczytanie_nauczycieli_wykladow(vector <vector<Przedmiot>> &Przedmioty_Wykl,vector <Nauczyciel> &Nauczyciele) { fstream plik; plik.open("wyklady_nauczyciele.csv", ios::in | ios::out); if(plik.is_open()) { cout << "Plik z nauczycielami wykladow otwarty" << endl << endl; string linia; string czesc; int numer_nauczyciela = 0; int numer_wykladu = 0; int ile_wykladow = 0; int ile_wykl_wcze = 0; vector <string> dane; int il_zbiorow_wykladow = Przedmioty_Wykl.size(); while(!plik.eof()) { plik >> linia; stringstream strumien(linia); while(getline(strumien,czesc,',')) { dane.push_back(czesc); } if(dane[0] != "" && dane[0] != ";") { numer_wykladu = 0; ile_wykladow = Przedmioty_Wykl[0].size(); ile_wykl_wcze = 0; for(int j = 0; j < il_zbiorow_wykladow;j++) { for(int i = numer_wykladu; i < ile_wykladow; i++) { if(stoi(dane[i]) != 0) { Nauczyciele[numer_nauczyciela].Godziny_wykl(i,stoi(dane[i])); Przedmioty_Wykl[j][i-ile_wykl_wcze].Dodaj_nauczyciela(numer_nauczyciela); } else if(stoi(dane[i]) == "") { cout << "Blad w pliku nauczyciele_wykladow wiersz " << numer_nauczyciela << endl; } numer_wykladu++; } ile_wykl_wcze = ile_wykladow; ile_wykladow += Przedmioty_Wykl[j+1].size(); } } else if(dane[0] == ";") { break; } dane.erase(dane.begin(), dane.end()); numer_nauczyciela++; } plik.close(); } else cout<<"Nie udało się otworzyć pliku z nauczycielami wykladow przedmiotow"; } void Wczytanie_nauczycieli_cwiczen(vector<vector<Przedmiot>> &Przedmioty_Cw,vector <Nauczyciel> &Nauczyciele) { fstream plik; plik.open("cwiczenia_nauczyciele.csv", ios::in | ios::out); if(plik.is_open()) { cout << "Plik z nauczycielami cwiczeniami otwarty" << endl << endl; string linia; string czesc; int numer_nauczyciela = 0; int numer_cwiczenia = 0; int ile_cwiczen = 0; int ile_cw_wcze = 0; vector <string> dane; int il_zbiorow_cwiczen = Przedmioty_Cw.size(); while(!plik.eof()) { plik >> linia; stringstream strumien(linia); while(getline(strumien,czesc,',')) { dane.push_back(czesc); } if(dane[0] != "" && dane[0] != ";") { numer_cwiczenia = 0; ile_cwiczen = Przedmioty_Cw[0].size(); ile_cw_wcze = 0; for(int j = 0; j < il_zbiorow_cwiczen;j++) { for(int i = numer_cwiczenia; i < ile_cwiczen; i++) { if(stoi(dane[i]) != 0) { Nauczyciele[numer_nauczyciela].Godziny_cw(i,stoi(dane[i])); Przedmioty_Cw[j][i-ile_cw_wcze].Dodaj_nauczyciela(numer_nauczyciela); } else if(stoi(dane[i]) == "") { cout << "Blad w pliku nauczyciele_cwiczen wiersz:" << numer_nauczyciela << endl; } numer_cwiczenia++; } ile_cw_wcze = ile_cwiczen; ile_cwiczen += Przedmioty_Cw[j+1].size(); } } else if(dane[0] == ";") { break; } dane.erase(dane.begin(), dane.end()); numer_nauczyciela++; } plik.close(); } else cout<<"Nie udało się otworzyć pliku z nauczycielami cwiczen przedmiotow"; } void Wczytanie_nauczycieli_laborek(vector <vector<Przedmiot>> &Przedmioty_Lab,vector < Nauczyciel> &Nauczyciele) { fstream plik; plik.open("laborki_nauczyciele.csv", ios::in | ios::out); if(plik.is_open()) { cout << "Plik z nauczycielami laborek otwarty" << endl << endl; string linia; string czesc; int numer_nauczyciela = 0; int numer_laborek = 0; int ile_laborek = 0; int ile_lab_wcze = 0; vector <string> dane; int il_zbiorow_labek = Przedmioty_Lab.size(); while(!plik.eof()) { plik >> linia; stringstream strumien(linia); while(getline(strumien,czesc,',')) { dane.push_back(czesc); } if(dane[0] != "" && dane[0] != ";") { numer_laborek = 0; ile_laborek = Przedmioty_Lab[0].size(); ile_lab_wcze = 0; for(int j = 0; j < il_zbiorow_labek;j++) { for(int i = numer_laborek; i < ile_laborek; i++) { if(stoi(dane[i]) != 0) { Nauczyciele[numer_nauczyciela].Godziny_labek(i,stoi(dane[i])); Przedmioty_Lab[j][i-ile_lab_wcze].Dodaj_nauczyciela(numer_nauczyciela); } else if(stoi(dane[i]) == "") { cout << "Blad w pliku nauczyciele_laborek wiersz: " << numer_nauczyciela << endl; } numer_laborek++; } ile_lab_wcze = ile_laborek; ile_laborek += Przedmioty_Lab[j+1].size(); } } else if(dane[0] == ";") { break; } dane.erase(dane.begin(), dane.end()); numer_nauczyciela++; } plik.close(); } else cout<<"Nie udało się otworzyć pliku z nauczycielami laborek przedmiotow"; } void Zajecia_wykladowe(vector <Zajecia>&Zajecie,vector<vector<Przedmiot>>&Przedmioty_Wykl,vector<vector<Nad_grupa>>&Grupy_Wykl,vector<Sala>&Sala_Wykl,int &il_wykl) { int ile_zbior_gr_wykl = Grupy_Wykl.size(); int ile_zbior_wykl = Przedmioty_Wykl.size(); int ilosc_wykladow = 0; int ilosc_grup = 0; int maks_ile_grup = 0; int maks_ile_wykl = 0; vector<vector<Przedmiot>>::iterator it1 = Przedmioty_Wykl.begin(); vector<vector<Nad_grupa>>::iterator it2 = Grupy_Wykl.begin(); for(;it1 != Przedmioty_Wykl.end() && it2 != Grupy_Wykl.end();it1++,it2++) { ilosc_wykladow = it1->size(); ilosc_grup = it2->size(); if(maks_ile_wykl < ilosc_wykladow) maks_ile_wykl = ilosc_wykladow; if(maks_ile_grup < ilosc_grup) maks_ile_grup = ilosc_grup; } int numer_zajecia = 0; if(ile_zbior_gr_wykl == ile_zbior_wykl) { for(int k = 0; k < maks_ile_wykl; k++) { for(int i = 0; i < maks_ile_grup; i++) { for(int j = 0; j < ile_zbior_wykl; j++) { ilosc_wykladow = Przedmioty_Wykl[j].size(); ilosc_grup = Grupy_Wykl[j].size(); if(k < ilosc_wykladow && i < ilosc_grup) { Zajecie.push_back({{&Przedmioty_Wykl[j][k]},{NULL},{&Grupy_Wykl[j][i]},(numer_zajecia+1)}); numer_zajecia++; } } } } int sala_wykl = 0; int ilosc_sal = Sala_Wykl.size(); int ilosc_zajec = Zajecie.size(); for(int i = 0; i < ilosc_zajec; i++) { if(sala_wykl == ilosc_sal) sala_wykl = 0; Zajecie[i].dodaj_sale()->push_back({&Sala_Wykl[sala_wykl]}); sala_wykl++; } il_wykl = Zajecie.size(); } else { cout << "Zbiory wykladow i grup wykladowych nie sa sobie rowne" << endl; } } void Zajecia_cwiczeniowe(vector <Zajecia> &Zajecie,vector<vector<Przedmiot>> &Przedmioty_Cw,vector <vector<Nad_grupa>> &Grupy_Cw,vector<Sala> &Sala_Cw,int &il_wykl_i_cw) { int ile_zbior_gr_cw = Grupy_Cw.size(); int ile_zbior_cw = Przedmioty_Cw.size(); int ilosc_cwiczen = 0; int ilosc_grup = 0; int maks_ile_grup = 0; int maks_ile_cw = 0; vector<vector<Przedmiot>>::iterator it1 = Przedmioty_Cw.begin(); vector<vector<Nad_grupa>>::iterator it2 = Grupy_Cw.begin(); for(;it1 != Przedmioty_Cw.end() && it2 != Grupy_Cw.end();it1++,it2++) { ilosc_cwiczen = it1->size(); ilosc_grup = it2->size(); if(maks_ile_cw < ilosc_cwiczen) maks_ile_cw = ilosc_cwiczen; if(maks_ile_grup < ilosc_grup) maks_ile_grup = ilosc_grup; } int numer_zajecia = Zajecie.size(); int ilosc_wykladow = Zajecie.size(); if(ile_zbior_gr_cw == ile_zbior_cw) { for(int k = 0; k < maks_ile_cw; k++) { for(int i = 0; i < maks_ile_grup; i++) { for(int j = 0; j < ile_zbior_cw; j++) { ilosc_cwiczen = Przedmioty_Cw[j].size(); ilosc_grup = Grupy_Cw[j].size(); if(k < ilosc_cwiczen && i < ilosc_grup) { Zajecie.push_back({{&Przedmioty_Cw[j][k]},{NULL},{&Grupy_Cw[j][i]},(numer_zajecia+1)}); numer_zajecia++; } } } } int sala_cw = 0; int ilosc_sal = Sala_Cw.size(); int ilosc_zajec = Zajecie.size(); for(int i = ilosc_wykladow; i < ilosc_zajec; i++) { if(sala_cw == ilosc_sal) sala_cw = 0; Zajecie[i].dodaj_sale()->push_back({&Sala_Cw[sala_cw]}); sala_cw++; } il_wykl_i_cw = Zajecie.size(); } else { cout << "Zbiory cwiczen i grup cwiczeniowych nie sa sobie rowne" << endl; } } void Zajecia_laborki(vector <Zajecia> &Zajecie,vector <vector<Przedmiot>> &Przedmioty_Lab,vector<vector<Grupa>> &Grupy_Lab,vector<Sala> &Sala_Lab) { int ile_zbior_gr_lab = Grupy_Lab.size(); int ile_zbior_lab = Przedmioty_Lab.size(); int ilosc_laborek = 0; int ilosc_grup = 0; int maks_ile_grup = 0; int maks_ile_lab = 0; vector<vector<Przedmiot>>::iterator it1 = Przedmioty_Lab.begin(); vector<vector<Grupa>>::iterator it2 = Grupy_Lab.begin(); for(;it1 != Przedmioty_Lab.end() && it2 != Grupy_Lab.end();it1++,it2++) { ilosc_laborek = it1->size(); ilosc_grup = it2->size(); if(maks_ile_lab < ilosc_laborek) maks_ile_lab = ilosc_laborek; if(maks_ile_grup < ilosc_grup) maks_ile_grup = ilosc_grup; } int numer_zajecia = Zajecie.size(); int ilosc_wykl_i_cw = Zajecie.size(); if(ile_zbior_gr_lab == ile_zbior_lab) { for(int k = 0; k < maks_ile_lab; k++) { for(int i = 0; i < maks_ile_grup; i++) { for(int j = 0; j < ile_zbior_lab; j++) { ilosc_laborek = Przedmioty_Lab[j].size(); ilosc_grup = Grupy_Lab[j].size(); if(k < ilosc_laborek && i < ilosc_grup) { Zajecie.push_back({{&Przedmioty_Lab[j][k]},{&Grupy_Lab[j][i]},{NULL},numer_zajecia+1}); numer_zajecia++; } } } } int sala_lab = 0; int ilosc_sal = Sala_Lab.size(); int ilosc_zajec = Zajecie.size(); for(int i = ilosc_wykl_i_cw; i < ilosc_zajec; i++) { if(sala_lab == ilosc_sal) sala_lab = 0; Zajecie[i].dodaj_sale()->push_back({&Sala_Lab[sala_lab]}); sala_lab++; } } else { cout << "Zbiory laborek i grup laboratoryjnych nie sa sobie rowne" << endl; } } void Zajecia_nauczyciele(vector<Zajecia> &Zajecie,vector<Nauczyciel> &Nauczyciele,int il_wykl,int il_wykl_i_cw) { int ilosc_zajec = Zajecie.size(); for(int i = 0; i < il_wykl; i++) { if(Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_wykl(Zajecie[i].przedmiot()->Zwroc_numer())) { Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]); } else { Zajecie[i].przedmiot()->Nastepny_nauczyciel(); Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_wykl(Zajecie[i].przedmiot()->Zwroc_numer()); Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]); } } for(int i = il_wykl; i < il_wykl_i_cw; i++) { if(Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_cw(Zajecie[i].przedmiot()->Zwroc_numer())) { Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]); } else { Zajecie[i].przedmiot()->Nastepny_nauczyciel(); Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_cw(Zajecie[i].przedmiot()->Zwroc_numer()); Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]); } } for(int i = il_wykl_i_cw; i < ilosc_zajec; i++) { if(Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_lab(Zajecie[i].przedmiot()->Zwroc_numer())) { Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]); } else { Zajecie[i].przedmiot()->Nastepny_nauczyciel(); Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()].Dostepny_lab(Zajecie[i].przedmiot()->Zwroc_numer()); Zajecie[i].nauczyciel()->push_back(&Nauczyciele[Zajecie[i].przedmiot()->Zwroc_nauczyciela()]); } } } void Tworzenie_harmonogramu(vector <Zajecia> &Zajecie) { int ilosc_zajec = Zajecie.size(); for(int i = 0; i < ilosc_zajec; i++) { int losowa = rand() % 2; Zajecie[i].Termin_zajec(losowa); } } void Wypisanie_danych_harmonogramu(vector <Zajecia> &Zajecie,vector <vector<Grupa>> &Grupy_Lab, vector <Nauczyciel> &Nauczyciele) { int ilosc_nauczycieli = Nauczyciele.size(); int ilosc_zajec = 0; set <int>::iterator it; for(int i = 0; i < ilosc_nauczycieli; i++) { cout << "Plan nauczyciela " << i+1 << endl; for(int j = 0; j < 20; j++) { Nauczyciele[i].Wypisz_poz_w_plan(j); } cout << endl; ilosc_zajec = Nauczyciele[i].Ile_zajec(); cout << "Ilosc zajec nauczyciela: " << ilosc_zajec << endl; it = Nauczyciele[i].Pierwszy_zaj_termin(); cout << "Zajecie pierwsze: " << *it << endl; it = --Nauczyciele[i].Ostatni_zaj_termin(); cout << "Zajecie ostatnie: " << *it << endl; cout << "Kara: " << Nauczyciele[i].Oblicz_kare() << endl; cout << "Godziny dopuszczalne: "; for(it = Nauczyciele[i].Pierwszy_dop_termin(); it != Nauczyciele[i].Ostatni_dop_termin(); it++) { cout << *it << " "; } cout << endl; cout << "Terminy wykluczone: "; for(it = Nauczyciele[i].Pierwszy_niedop_termin(); it != Nauczyciele[i].Ostatni_niedop_termin(); it++) { cout << *it << " "; } cout << endl; cout << "Zajete terminy: "; for(it = Nauczyciele[i].Pierwszy_zaj_termin(); it != Nauczyciele[i].Ostatni_zaj_termin(); it++) { cout << *it << " "; } cout << endl << endl; } cout << "Suma kar dla nauczycieli: " << Kara_laczna_nauczycieli(Nauczyciele) << endl << endl; int ile_zbior_grup = Grupy_Lab.size(); int ilosc_grup = 0; for(int k = 0; k < ile_zbior_grup; k++) { ilosc_grup = Grupy_Lab[k].size(); for(int i = 0; i < ilosc_grup; i++) { cout << "Plan Grupy " << i+1 << endl; for(int j = 0; j < 20; j++) { cout << Grupy_Lab[k][i].Zwroc_numer_zaj(j) << " "; } cout << endl; ilosc_zajec = Grupy_Lab[k][i].Ile_zajec(); cout << "Ilosc zajec grup: " << ilosc_zajec << endl; it = Grupy_Lab[k][i].Pierwszy_zaj_termin(); cout << "Zajecie pierwsze: " << *it << endl; it = --Grupy_Lab[k][i].Ostatni_zaj_termin(); cout << "Zajecie ostatnie: " << *it << endl; cout << "Kara planu: " << Grupy_Lab[k][i].Oblicz_kare() << endl; cout << "Zajete terminy: "; for(it = Grupy_Lab[k][i].Pierwszy_zaj_termin(); it != Grupy_Lab[k][i].Ostatni_zaj_termin(); it++) { cout << *it << " "; } cout << endl << endl; } } cout << "Suma kar dla grup: " << Kara_laczna_grup(Grupy_Lab) << endl << endl; cout << "Kara laczna dla grup i nauczycieli: " << Kara_laczna_nauczycieli(Nauczyciele) + Kara_laczna_grup(Grupy_Lab) << endl << endl; } void Poprawianie_harmonogramu(vector <Zajecia> &Zajecie,vector <vector<Grupa>> &Grupy_Lab,vector <Nauczyciel> &Nauczyciele, vector <Sala> Sala_Lab, int ile_popraw) { vector <Sala> Sala_Lab_Naj = Sala_Lab; vector <vector<Grupa>> Grupy_Lab_Naj = Grupy_Lab; vector <Nauczyciel> Nauczyciele_Naj = Nauczyciele; vector <Zajecia> Zajecie_Naj = Zajecie; vector <float> kara_grupy; vector <float> kara_nauczyciel; vector <float>::iterator it; vector <Nauczyciel*> nauczyciele_labek; vector <Grupa*> grupy; int ilosc_zbiorow_grup = Grupy_Lab.size(); int ilosc_grup = 0; int ilosc_nauczy = Nauczyciele.size(); int il_nauczy_lab = 0; int najg_nauczy = 0; int najg_grupa = 0; int ile_zmian = 0; for(int i = 0; i < ilosc_zbiorow_grup; i++) { ilosc_grup = Grupy_Lab[i].size(); for(int j = 0; j < ilosc_grup; j++) { grupy.push_back({&Grupy_Lab[i][j]}); } } ilosc_grup = grupy.size(); for(int i = 0; i < ilosc_grup; i++) { kara_grupy.push_back({grupy[i]->Oblicz_kare()}); } cout << endl; it = max_element(kara_grupy.begin(),kara_grupy.end()); najg_grupa = distance(kara_grupy.begin(), it); for(int i = 0; i < ilosc_nauczy; i++) { if(Nauczyciele[i].Ile_lab_w_planie() != 0) nauczyciele_labek.push_back({&Nauczyciele[i]}); } il_nauczy_lab = nauczyciele_labek.size(); for(int i = 0; i < il_nauczy_lab; i++) { kara_nauczyciel.push_back(nauczyciele_labek[i]->Oblicz_kare()); } it = max_element(kara_nauczyciel.begin(),kara_nauczyciel.end()); najg_nauczy = distance(kara_nauczyciel.begin(), it); cout << "Ogolna wartosc kary planu: " << Ogolna_kara_planu(Grupy_Lab,Nauczyciele) << endl; for(int i = 0; i < ile_popraw; i++) { Poprawianie_grupy(Zajecie,it,kara_grupy,grupy,najg_grupa); Poprawianie_nauczycieli(Zajecie,it,kara_nauczyciel,Nauczyciele,najg_nauczy); if(Ogolna_kara_planu(Grupy_Lab,Nauczyciele) < Ogolna_kara_planu(Grupy_Lab_Naj,Nauczyciele_Naj)) { Sala_Lab_Naj = Sala_Lab; Grupy_Lab_Naj = Grupy_Lab; Nauczyciele_Naj = Nauczyciele; Zajecie_Naj = Zajecie; ile_zmian = 0; } else if(ile_zmian == 2) { Sala_Lab = Sala_Lab_Naj; Grupy_Lab = Grupy_Lab_Naj; Nauczyciele = Nauczyciele_Naj; Zajecie = Zajecie_Naj; for(int i = 0; i < ilosc_grup; i++) { kara_grupy[i] = grupy[i]->Zwroc_kare(); } for(int i = 0; i < il_nauczy_lab; i++) { kara_nauczyciel[i] = Nauczyciele[i].Zwroc_kare(); } ile_zmian = 0; } cout << "Ogolna wartosc kary planu: " << Ogolna_kara_planu(Grupy_Lab,Nauczyciele) << endl; } Sala_Lab = Sala_Lab_Naj; Grupy_Lab = Grupy_Lab_Naj; Nauczyciele = Nauczyciele_Naj; Zajecie = Zajecie_Naj; }
07737784510130c542c5f91c387a0d793b1f688f
070d630a312f393372d9264089329120186a8f3a
/Galatea/Bomb.h
144e62037e0c30159b751816de6b1b5e1004b7f5
[]
no_license
peersmg/WW2ShooterGame
35ca31078e0ee205cddc399bc7ae5f6b0d29d440
7980af2c4ff980651f74f6f18d0b8c4a57bde4de
refs/heads/master
2021-01-11T10:50:01.099834
2016-12-13T18:53:34
2016-12-13T18:53:34
76,181,606
1
1
null
null
null
null
UTF-8
C++
false
false
959
h
//Title : Bomb.h //Purpose : Bomb header. //Author : Matthew Peers //Date : 05/12/16 #pragma once #include "GameObject.h" class Bomb : public GameObject { private: Rectangle2D collisionShape; // Objects collision shape Vector2D m_velocity; // The velocity of the bomb Vector2D m_imageSize; // The size of the bomb graphic within the image file float m_speed; // How fast the bomb should fall public: // Constructor Bomb(); // Set up the bomb void Initialise(float angle, Vector2D position); // Process the collisions of this gameobject void ProcessCollision(GameObject &other); // Update the gameobject logic, called every frame void Update(float deltaTime); // Deactivate this game object and create an explosion effect void Explode(); // Returns the collision shape IShape2D& GetCollisionShape(); // Recieves and handles events void HandleEvent(Event evt); };
5b5df4f93f44ec357943180ec7d2252b49f66c31
99d3c5d09886c1d45cc7eed7a6dcce3548ac4da3
/nebula/doc/old/RCS/Samples/SampleFramework/renderer/drivers/d3d9/D3D9RendererTarget.cpp
54121c655b907bce59a20369ccfc296a67989aa0
[]
no_license
nebula-engine/nebula_old
1e49843c7c8a4915d0303cca5b8067d6e62de4fb
d61f91140b6ac5334a8292bfece97092a99c53b0
refs/heads/master
2021-01-23T13:49:01.855177
2015-03-05T04:07:06
2015-03-05T04:07:06
29,644,714
0
0
null
null
null
null
UTF-8
C++
false
false
6,024
cpp
/* * Copyright 2008-2012 NVIDIA Corporation. All rights reserved. * * NOTICE TO USER: * * This source code is subject to NVIDIA ownership rights under U.S. and * international Copyright laws. Users and possessors of this source code * are hereby granted a nonexclusive, royalty-free license to use this code * in individual and commercial software. * * NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE * CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR * IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. * IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOURCE CODE. * * U.S. Government End Users. This source code is a "commercial item" as * that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of * "commercial computer software" and "commercial computer software * documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995) * and is provided to the U.S. Government only as a commercial end item. * Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through * 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the * source code with only those rights set forth herein. * * Any use of this source code in individual and commercial software must * include, in the user documentation and internal comments to the code, * the above Disclaimer and U.S. Government End Users Notice. */ // suppress LNK4221 on Xbox namespace {char dummySymbol; } #include <RendererConfig.h> #include "D3D9RendererTarget.h" #if defined(RENDERER_ENABLE_DIRECT3D9) && defined(RENDERER_ENABLE_DIRECT3D9_TARGET) #include <RendererTargetDesc.h> #include "D3D9RendererTexture2D.h" using namespace SampleRenderer; D3D9RendererTarget::D3D9RendererTarget(IDirect3DDevice9 &d3dDevice, const RendererTargetDesc &desc) : m_d3dDevice(d3dDevice) { m_d3dLastSurface = 0; m_d3dLastDepthStencilSurface = 0; m_d3dDepthStencilSurface = 0; for(PxU32 i=0; i<desc.numTextures; i++) { D3D9RendererTexture2D &texture = *static_cast<D3D9RendererTexture2D*>(desc.textures[i]); m_textures.push_back(&texture); } m_depthStencilSurface = static_cast<D3D9RendererTexture2D*>(desc.depthStencilSurface); RENDERER_ASSERT(m_depthStencilSurface && m_depthStencilSurface->m_d3dTexture, "Invalid Target Depth Stencil Surface!"); onDeviceReset(); } D3D9RendererTarget::~D3D9RendererTarget(void) { if(m_d3dDepthStencilSurface) m_d3dDepthStencilSurface->Release(); } void D3D9RendererTarget::bind(void) { RENDERER_ASSERT(m_d3dLastSurface==0 && m_d3dLastDepthStencilSurface==0, "Render Target in bad state!"); if(m_d3dDepthStencilSurface && !m_d3dLastSurface && !m_d3dLastDepthStencilSurface) { m_d3dDevice.GetRenderTarget(0, &m_d3dLastSurface); m_d3dDevice.GetDepthStencilSurface(&m_d3dLastDepthStencilSurface); const PxU32 numTextures = (PxU32)m_textures.size(); for(PxU32 i=0; i<numTextures; i++) { IDirect3DSurface9 *d3dSurcace = 0; D3D9RendererTexture2D &texture = *m_textures[i]; /* HRESULT result = */ texture.m_d3dTexture->GetSurfaceLevel(0, &d3dSurcace); RENDERER_ASSERT(d3dSurcace, "Cannot get Texture Surface!"); if(d3dSurcace) { m_d3dDevice.SetRenderTarget(i, d3dSurcace); d3dSurcace->Release(); } } m_d3dDevice.SetDepthStencilSurface(m_d3dDepthStencilSurface); const DWORD flags = D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER; m_d3dDevice.Clear(0, 0, flags, 0x00000000, 1.0f, 0); } float depthBias = 0.0001f; float biasSlope = 1.58f; #if RENDERER_ENABLE_DRESSCODE depthBias = dcParam("depthBias", depthBias, 0.0f, 0.01f); biasSlope = dcParam("biasSlope", biasSlope, 0.0f, 5.0f); #endif m_d3dDevice.SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias); m_d3dDevice.SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&biasSlope); } void D3D9RendererTarget::unbind(void) { RENDERER_ASSERT(m_d3dLastSurface && m_d3dLastDepthStencilSurface, "Render Target in bad state!"); if(m_d3dDepthStencilSurface && m_d3dLastSurface && m_d3dLastDepthStencilSurface) { m_d3dDevice.SetDepthStencilSurface(m_d3dLastDepthStencilSurface); m_d3dDevice.SetRenderTarget(0, m_d3dLastSurface); const PxU32 numTextures = (PxU32)m_textures.size(); for(PxU32 i=1; i<numTextures; i++) { m_d3dDevice.SetRenderTarget(i, 0); } m_d3dLastSurface->Release(); m_d3dLastSurface = 0; m_d3dLastDepthStencilSurface->Release(); m_d3dLastDepthStencilSurface = 0; } float depthBias = 0; float biasSlope = 0; m_d3dDevice.SetRenderState(D3DRS_DEPTHBIAS, *(DWORD*)&depthBias); m_d3dDevice.SetRenderState(D3DRS_SLOPESCALEDEPTHBIAS, *(DWORD*)&biasSlope); } void D3D9RendererTarget::onDeviceLost(void) { RENDERER_ASSERT(m_d3dLastDepthStencilSurface==0, "Render Target in bad state!"); RENDERER_ASSERT(m_d3dDepthStencilSurface, "Render Target in bad state!"); if(m_d3dDepthStencilSurface) { m_d3dDepthStencilSurface->Release(); m_d3dDepthStencilSurface = 0; } } void D3D9RendererTarget::onDeviceReset(void) { RENDERER_ASSERT(m_d3dDepthStencilSurface==0, "Render Target in bad state!"); if(!m_d3dDepthStencilSurface && m_depthStencilSurface && m_depthStencilSurface->m_d3dTexture) { bool ok = m_depthStencilSurface->m_d3dTexture->GetSurfaceLevel(0, &m_d3dDepthStencilSurface) == D3D_OK; if(!ok) { RENDERER_ASSERT(ok, "Failed to create Render Target Depth Stencil Surface."); } } } #endif //#if defined(RENDERER_ENABLE_DIRECT3D9) && defined(RENDERER_ENABLE_DIRECT3D9_TARGET)
007afcd159ffcc5116171b1c538e46556afa5ff5
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-cloudtrail/include/aws/cloudtrail/model/PutEventSelectorsRequest.h
63ba924f8dac3ec11c50d390820f5155086beb9e
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
9,978
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ #pragma once #include <aws/cloudtrail/CloudTrail_EXPORTS.h> #include <aws/cloudtrail/CloudTrailRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/cloudtrail/model/EventSelector.h> namespace Aws { namespace CloudTrail { namespace Model { /** */ class AWS_CLOUDTRAIL_API PutEventSelectorsRequest : public CloudTrailRequest { public: PutEventSelectorsRequest(); Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * <p>Specifies the name of the trail or trail ARN. If you specify a trail name, * the string must meet the following requirements:</p> <ul> <li> <p>Contain only * ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes * (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or * number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have * no adjacent periods, underscores or dashes. Names like * <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li> * <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul> * <p>If you specify a trail ARN, it must be in the format:</p> <p> * <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p> */ inline const Aws::String& GetTrailName() const{ return m_trailName; } /** * <p>Specifies the name of the trail or trail ARN. If you specify a trail name, * the string must meet the following requirements:</p> <ul> <li> <p>Contain only * ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes * (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or * number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have * no adjacent periods, underscores or dashes. Names like * <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li> * <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul> * <p>If you specify a trail ARN, it must be in the format:</p> <p> * <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p> */ inline void SetTrailName(const Aws::String& value) { m_trailNameHasBeenSet = true; m_trailName = value; } /** * <p>Specifies the name of the trail or trail ARN. If you specify a trail name, * the string must meet the following requirements:</p> <ul> <li> <p>Contain only * ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes * (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or * number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have * no adjacent periods, underscores or dashes. Names like * <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li> * <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul> * <p>If you specify a trail ARN, it must be in the format:</p> <p> * <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p> */ inline void SetTrailName(Aws::String&& value) { m_trailNameHasBeenSet = true; m_trailName = value; } /** * <p>Specifies the name of the trail or trail ARN. If you specify a trail name, * the string must meet the following requirements:</p> <ul> <li> <p>Contain only * ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes * (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or * number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have * no adjacent periods, underscores or dashes. Names like * <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li> * <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul> * <p>If you specify a trail ARN, it must be in the format:</p> <p> * <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p> */ inline void SetTrailName(const char* value) { m_trailNameHasBeenSet = true; m_trailName.assign(value); } /** * <p>Specifies the name of the trail or trail ARN. If you specify a trail name, * the string must meet the following requirements:</p> <ul> <li> <p>Contain only * ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes * (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or * number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have * no adjacent periods, underscores or dashes. Names like * <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li> * <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul> * <p>If you specify a trail ARN, it must be in the format:</p> <p> * <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p> */ inline PutEventSelectorsRequest& WithTrailName(const Aws::String& value) { SetTrailName(value); return *this;} /** * <p>Specifies the name of the trail or trail ARN. If you specify a trail name, * the string must meet the following requirements:</p> <ul> <li> <p>Contain only * ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes * (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or * number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have * no adjacent periods, underscores or dashes. Names like * <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li> * <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul> * <p>If you specify a trail ARN, it must be in the format:</p> <p> * <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p> */ inline PutEventSelectorsRequest& WithTrailName(Aws::String&& value) { SetTrailName(value); return *this;} /** * <p>Specifies the name of the trail or trail ARN. If you specify a trail name, * the string must meet the following requirements:</p> <ul> <li> <p>Contain only * ASCII letters (a-z, A-Z), numbers (0-9), periods (.), underscores (_), or dashes * (-)</p> </li> <li> <p>Start with a letter or number, and end with a letter or * number</p> </li> <li> <p>Be between 3 and 128 characters</p> </li> <li> <p>Have * no adjacent periods, underscores or dashes. Names like * <code>my-_namespace</code> and <code>my--namespace</code> are invalid.</p> </li> * <li> <p>Not be in IP address format (for example, 192.168.5.4)</p> </li> </ul> * <p>If you specify a trail ARN, it must be in the format:</p> <p> * <code>arn:aws:cloudtrail:us-east-1:123456789012:trail/MyTrail</code> </p> */ inline PutEventSelectorsRequest& WithTrailName(const char* value) { SetTrailName(value); return *this;} /** * <p>Specifies the settings for your event selectors. You can configure up to five * event selectors for a trail.</p> */ inline const Aws::Vector<EventSelector>& GetEventSelectors() const{ return m_eventSelectors; } /** * <p>Specifies the settings for your event selectors. You can configure up to five * event selectors for a trail.</p> */ inline void SetEventSelectors(const Aws::Vector<EventSelector>& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors = value; } /** * <p>Specifies the settings for your event selectors. You can configure up to five * event selectors for a trail.</p> */ inline void SetEventSelectors(Aws::Vector<EventSelector>&& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors = value; } /** * <p>Specifies the settings for your event selectors. You can configure up to five * event selectors for a trail.</p> */ inline PutEventSelectorsRequest& WithEventSelectors(const Aws::Vector<EventSelector>& value) { SetEventSelectors(value); return *this;} /** * <p>Specifies the settings for your event selectors. You can configure up to five * event selectors for a trail.</p> */ inline PutEventSelectorsRequest& WithEventSelectors(Aws::Vector<EventSelector>&& value) { SetEventSelectors(value); return *this;} /** * <p>Specifies the settings for your event selectors. You can configure up to five * event selectors for a trail.</p> */ inline PutEventSelectorsRequest& AddEventSelectors(const EventSelector& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors.push_back(value); return *this; } /** * <p>Specifies the settings for your event selectors. You can configure up to five * event selectors for a trail.</p> */ inline PutEventSelectorsRequest& AddEventSelectors(EventSelector&& value) { m_eventSelectorsHasBeenSet = true; m_eventSelectors.push_back(value); return *this; } private: Aws::String m_trailName; bool m_trailNameHasBeenSet; Aws::Vector<EventSelector> m_eventSelectors; bool m_eventSelectorsHasBeenSet; }; } // namespace Model } // namespace CloudTrail } // namespace Aws
840dcf27278063660fa44194e5b89fdda06ad237
5c3f6bdd0aa5446a78372c967d5a642c429b8eda
/src/versionbits.h
a9e0c63d836f63cecba02a2e2110b6be67fd9289
[ "MIT" ]
permissive
GlobalBoost/GlobalBoost-Y
defeb2f930222d8b78447a9440d03cce9d8d602c
b4c8f1bb88ebbfa5016376fee9a00ae98902133f
refs/heads/master
2023-08-11T12:04:12.578240
2023-07-11T03:56:18
2023-07-11T03:56:18
23,804,954
20
22
MIT
2023-07-11T03:56:19
2014-09-08T19:26:43
C++
UTF-8
C++
false
false
3,223
h
// Copyright (c) 2016-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef GLOBALBOOST_VERSIONBITS_H #define GLOBALBOOST_VERSIONBITS_H #include <chain.h> #include <map> /** What block version to use for new blocks (pre versionbits) */ static const int32_t VERSIONBITS_LAST_OLD_BLOCK_VERSION = 4; /** What bits to set in version for versionbits blocks */ static const int32_t VERSIONBITS_TOP_BITS = 0x20000000UL; /** What bitmask determines whether versionbits is in use */ static const int32_t VERSIONBITS_TOP_MASK = 0xE0000000UL; /** Total bits available for versionbits */ static const int32_t VERSIONBITS_NUM_BITS = 29; enum class ThresholdState { DEFINED, STARTED, LOCKED_IN, ACTIVE, FAILED, }; // A map that gives the state for blocks whose height is a multiple of Period(). // The map is indexed by the block's parent, however, so all keys in the map // will either be nullptr or a block with (height + 1) % Period() == 0. typedef std::map<const CBlockIndex*, ThresholdState> ThresholdConditionCache; struct VBDeploymentInfo { /** Deployment name */ const char *name; /** Whether GBT clients can safely ignore this rule in simplified usage */ bool gbt_force; }; struct BIP9Stats { int period; int threshold; int elapsed; int count; bool possible; }; extern const struct VBDeploymentInfo VersionBitsDeploymentInfo[]; /** * Abstract class that implements BIP9-style threshold logic, and caches results. */ class AbstractThresholdConditionChecker { protected: virtual bool Condition(const CBlockIndex* pindex, const Consensus::Params& params) const =0; virtual int64_t BeginTime(const Consensus::Params& params) const =0; virtual int64_t EndTime(const Consensus::Params& params) const =0; virtual int Period(const Consensus::Params& params) const =0; virtual int Threshold(const Consensus::Params& params) const =0; public: BIP9Stats GetStateStatisticsFor(const CBlockIndex* pindex, const Consensus::Params& params) const; // Note that the functions below take a pindexPrev as input: they compute information for block B based on its parent. ThresholdState GetStateFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const; int GetStateSinceHeightFor(const CBlockIndex* pindexPrev, const Consensus::Params& params, ThresholdConditionCache& cache) const; }; struct VersionBitsCache { ThresholdConditionCache caches[Consensus::MAX_VERSION_BITS_DEPLOYMENTS]; void Clear(); }; ThresholdState VersionBitsState(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, VersionBitsCache& cache); BIP9Stats VersionBitsStatistics(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos); int VersionBitsStateSinceHeight(const CBlockIndex* pindexPrev, const Consensus::Params& params, Consensus::DeploymentPos pos, VersionBitsCache& cache); uint32_t VersionBitsMask(const Consensus::Params& params, Consensus::DeploymentPos pos); #endif // GLOBALBOOST_VERSIONBITS_H
[ "null" ]
null
4a875cef049e86b3d405a51174546f8ce2c76b73
5f67df4e0d6d82b6877e4f899dd6395850ca3604
/Hackerrank/Miser-Nim.cpp
6871314b85c7309cb80f77b54e0c0b6fe812b1e0
[ "MIT" ]
permissive
dfm066/Programming
c27115bffed568fa1fe05a5448a7a82042451415
53d28460cd40b966cca1d4695d9dc6792ced4c6f
refs/heads/master
2021-07-03T17:40:22.010361
2020-09-14T19:59:03
2020-09-14T19:59:03
63,838,561
0
0
null
null
null
null
UTF-8
C++
false
false
682
cpp
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int t,n,s,flg; scanf("%d",&t); while(t--){ scanf("%d",&n); for(int i = 0; i < n; i++){ scanf("%d",&s); if(i!=0) flg ^= s; else flg=s; } if(n==1&&s==1) printf("Second\n"); else if((n%2==0&&flg==0)||(n%2!=0&&flg!=0)) printf("First\n"); else printf("Second\n"); } return 0; }
bd23a417f929fbe61f9532b724581b0b5138391c
cd99ca9461435d1417cb146d966e54272fbcc7ad
/3rd party/maxsdk/samples/systems/sunlight/PhysicalSunSkyEnv_UI.h
835e3a73d76e02d0da3b8f152ec6c1e6b49f011e
[]
no_license
mortany/xray15
eacce7965e785dd71d1877eae25c1f9eff680eec
72a13fb24e9b388850bc769427c231da8f599228
refs/heads/master
2020-08-02T20:45:23.493981
2019-10-14T18:48:48
2019-10-14T18:48:48
211,499,718
0
0
null
2019-09-28T12:50:47
2019-09-28T12:50:46
null
UTF-8
C++
false
false
1,664
h
////////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // ////////////////////////////////////////////////////////////////////////////// #pragma once // local #include "PhysicalSunSkyEnv.h" // Max SDK #include <Qt/QMaxParamBlockWidget.h> // Qt #include "ui_PhysSunSky.h" #include <QtWidgets/QWidget> //================================================================================================== // class PhysicalSunSkyEnv::MainPanelWidget // // Qt widget that implements the UI for the main panel of the physical sun & sky environment. // class PhysicalSunSkyEnv::MainPanelWidget : public MaxSDK::QMaxParamBlockWidget { Q_OBJECT public: explicit MainPanelWidget(IParamBlock2& param_block); ~MainPanelWidget(); // -- inherited from QMaxParamBlockWidget virtual void SetParamBlock(ReferenceMaker* owner, IParamBlock2* const param_block) override; virtual void UpdateUI(const TimeValue t) override; virtual void UpdateParameterUI(const TimeValue t, const ParamID param_id, const int tab_index) override; protected slots: void create_sun_positioner_button_clicked(); private: void update_illuminance_model_controls(const TimeValue t); private: // UI designer object Ui_PhysSunSky m_ui_builder; IParamBlock2* m_param_block; };
c3f7d961b7690ecc82fbb80bdfe88010c2f688df
f9fed164f610b5ce23c5e56f0b0ebdaa7f0ca6e7
/oj/1683/1683/main.cpp
d3799d4eae23ff019386f0cf88e2f6e9fbe4c935
[]
no_license
lszr-x/MiscellaneousAlgorithmOfC-
b0f4bc53ee191d31b66425ff83fbb26d7c470fde
a4b1af0e3935616e136f9e3d37eaf9728b846f8a
refs/heads/master
2021-04-15T14:18:17.640846
2018-03-27T13:27:34
2018-03-27T13:27:34
126,178,134
0
0
null
null
null
null
UTF-8
C++
false
false
673
cpp
// // main.cpp // 1683 // // Created by apple on 2017/3/20. // Copyright © 2017年 apple. All rights reserved. // #include <iostream> #include <set> #include <cstdio> using namespace std; int main(int argc, const char * argv[]) { set<string> s; string a,b; char x; while(~scanf("%c",&x)){ if(x=='A'){ b.resize(1000); scanf("%s",&b[0]); if(s.count(b)){ printf("他得奖了\n"); } else printf("没有快滚\n"); } if(x=='B'){ b.resize(1000); scanf("%s",&b[0]); s.insert(b); } } return 0; }
6ad15fed7348b9c02a45ce67d575780989be98d5
753244933fc4465b0047821aea81c311738e1732
/culture/target/cpp-O3/ts2/src/__boot__.cpp
4b1c891c0f75dfc3b8fbfa4ada38343b16600895
[]
no_license
mboussaa/HXvariability
abfaba5452fecb1b83bc595dc3ed942a126510b8
ea32b15347766b6e414569b19cbc113d344a56d9
refs/heads/master
2021-01-01T17:45:54.656971
2017-07-26T01:27:49
2017-07-26T01:27:49
98,127,672
0
0
null
null
null
null
UTF-8
C++
false
true
6,348
cpp
// Generated by Haxe 3.3.0 #include <hxcpp.h> #ifndef INCLUDED_utest_ui_common_SuccessResultsDisplayMode #include <utest/ui/common/SuccessResultsDisplayMode.h> #endif #ifndef INCLUDED_utest_ui_common_HeaderDisplayMode #include <utest/ui/common/HeaderDisplayMode.h> #endif #ifndef INCLUDED_utest__Dispatcher_EventException #include <utest/_Dispatcher/EventException.h> #endif #ifndef INCLUDED_utest_Assertation #include <utest/Assertation.h> #endif #ifndef INCLUDED_haxe_StackItem #include <haxe/StackItem.h> #endif #ifndef INCLUDED_ValueType #include <ValueType.h> #endif #ifndef INCLUDED_utest_TestHandler #include <utest/TestHandler.h> #endif #ifndef INCLUDED_utest_Assert #include <utest/Assert.h> #endif #ifndef INCLUDED_thx_culture_DateFormatInfo #include <thx/culture/DateFormatInfo.h> #endif #ifndef INCLUDED_haxe_MainLoop #include <haxe/MainLoop.h> #endif #ifndef INCLUDED_haxe_Log #include <haxe/Log.h> #endif #ifndef INCLUDED_haxe_EntryPoint #include <haxe/EntryPoint.h> #endif #ifndef INCLUDED_utest_ui_text_PrintReport #include <utest/ui/text/PrintReport.h> #endif #ifndef INCLUDED_utest_ui_text_PlainTextReport #include <utest/ui/text/PlainTextReport.h> #endif #ifndef INCLUDED_utest_ui_common_ResultStats #include <utest/ui/common/ResultStats.h> #endif #ifndef INCLUDED_utest_ui_common_ResultAggregator #include <utest/ui/common/ResultAggregator.h> #endif #ifndef INCLUDED_utest_ui_common_ReportTools #include <utest/ui/common/ReportTools.h> #endif #ifndef INCLUDED_utest_ui_common_PackageResult #include <utest/ui/common/PackageResult.h> #endif #ifndef INCLUDED_utest_ui_common_IReport #include <utest/ui/common/IReport.h> #endif #ifndef INCLUDED_utest_ui_common_FixtureResult #include <utest/ui/common/FixtureResult.h> #endif #ifndef INCLUDED_utest_ui_common_ClassResult #include <utest/ui/common/ClassResult.h> #endif #ifndef INCLUDED_utest_ui_Report #include <utest/ui/Report.h> #endif #ifndef INCLUDED_utest_TestResult #include <utest/TestResult.h> #endif #ifndef INCLUDED_utest_TestFixture #include <utest/TestFixture.h> #endif #ifndef INCLUDED_utest_Runner #include <utest/Runner.h> #endif #ifndef INCLUDED_utest_Notifier #include <utest/Notifier.h> #endif #ifndef INCLUDED_utest_Dispatcher #include <utest/Dispatcher.h> #endif #ifndef INCLUDED_thx_culture_TestDateFormatInfo #include <thx/culture/TestDateFormatInfo.h> #endif #ifndef INCLUDED_haxe_io_Eof #include <haxe/io/Eof.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_haxe_ds_StringMap #include <haxe/ds/StringMap.h> #endif #ifndef INCLUDED_haxe_Timer #include <haxe/Timer.h> #endif #ifndef INCLUDED_haxe_MainEvent #include <haxe/MainEvent.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_CallStack #include <haxe/CallStack.h> #endif #ifndef INCLUDED_cpp_vm_Thread #include <cpp/vm/Thread.h> #endif #ifndef INCLUDED_cpp_vm_Mutex #include <cpp/vm/Mutex.h> #endif #ifndef INCLUDED_cpp_vm_Lock #include <cpp/vm/Lock.h> #endif #ifndef INCLUDED_cpp_Lib #include <cpp/Lib.h> #endif #ifndef INCLUDED_Type #include <Type.h> #endif #ifndef INCLUDED_TS2 #include <TS2.h> #endif #ifndef INCLUDED_Sys #include <Sys.h> #endif #ifndef INCLUDED_StringTools #include <StringTools.h> #endif #ifndef INCLUDED_StringBuf #include <StringBuf.h> #endif #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_Reflect #include <Reflect.h> #endif #ifndef INCLUDED__List_ListIterator #include <_List/ListIterator.h> #endif #ifndef INCLUDED__List_ListNode #include <_List/ListNode.h> #endif #ifndef INCLUDED_List #include <List.h> #endif #ifndef INCLUDED_Lambda #include <Lambda.h> #endif #ifndef INCLUDED_EReg #include <EReg.h> #endif #ifndef INCLUDED_Date #include <Date.h> #endif void __files__boot(); void __boot_all() { __files__boot(); hx::RegisterResources( hx::GetResources() ); ::utest::ui::common::SuccessResultsDisplayMode_obj::__register(); ::utest::ui::common::HeaderDisplayMode_obj::__register(); ::utest::_Dispatcher::EventException_obj::__register(); ::utest::Assertation_obj::__register(); ::haxe::StackItem_obj::__register(); ::ValueType_obj::__register(); ::utest::TestHandler_obj::__register(); ::utest::Assert_obj::__register(); ::thx::culture::DateFormatInfo_obj::__register(); ::haxe::MainLoop_obj::__register(); ::haxe::Log_obj::__register(); ::haxe::EntryPoint_obj::__register(); ::utest::ui::text::PrintReport_obj::__register(); ::utest::ui::text::PlainTextReport_obj::__register(); ::utest::ui::common::ResultStats_obj::__register(); ::utest::ui::common::ResultAggregator_obj::__register(); ::utest::ui::common::ReportTools_obj::__register(); ::utest::ui::common::PackageResult_obj::__register(); ::utest::ui::common::IReport_obj::__register(); ::utest::ui::common::FixtureResult_obj::__register(); ::utest::ui::common::ClassResult_obj::__register(); ::utest::ui::Report_obj::__register(); ::utest::TestResult_obj::__register(); ::utest::TestFixture_obj::__register(); ::utest::Runner_obj::__register(); ::utest::Notifier_obj::__register(); ::utest::Dispatcher_obj::__register(); ::thx::culture::TestDateFormatInfo_obj::__register(); ::haxe::io::Eof_obj::__register(); ::haxe::io::Bytes_obj::__register(); ::haxe::ds::StringMap_obj::__register(); ::haxe::Timer_obj::__register(); ::haxe::MainEvent_obj::__register(); ::haxe::IMap_obj::__register(); ::haxe::CallStack_obj::__register(); ::cpp::vm::Thread_obj::__register(); ::cpp::vm::Mutex_obj::__register(); ::cpp::vm::Lock_obj::__register(); ::cpp::Lib_obj::__register(); ::Type_obj::__register(); ::TS2_obj::__register(); ::Sys_obj::__register(); ::StringTools_obj::__register(); ::StringBuf_obj::__register(); ::Std_obj::__register(); ::Reflect_obj::__register(); ::_List::ListIterator_obj::__register(); ::_List::ListNode_obj::__register(); ::List_obj::__register(); ::Lambda_obj::__register(); ::EReg_obj::__register(); ::Date_obj::__register(); ::utest::ui::common::SuccessResultsDisplayMode_obj::__boot(); ::utest::ui::common::HeaderDisplayMode_obj::__boot(); ::utest::_Dispatcher::EventException_obj::__boot(); ::utest::Assertation_obj::__boot(); ::haxe::StackItem_obj::__boot(); ::ValueType_obj::__boot(); ::haxe::Log_obj::__boot(); ::haxe::EntryPoint_obj::__boot(); ::haxe::MainLoop_obj::__boot(); ::thx::culture::DateFormatInfo_obj::__boot(); ::utest::Assert_obj::__boot(); ::utest::TestHandler_obj::__boot(); }
3578ea595763f21308abf2db57b0d0f3907ba8da
9c04f0b56921c56328a990e83226a8913d92f6ad
/Week 4/BoekHeap/BoekHeap/Boek.cpp
1028fb2f0820dfa8869fbafd6b41e4deafbd2a22
[]
no_license
JoasKleine/IOOP
ca6c6f9090b719a07bdb7dfea7da0352d32af002
19c0521964ee143db8c311b30b5c7a538817139b
refs/heads/master
2021-07-24T06:31:16.854480
2017-11-02T22:10:52
2017-11-02T22:10:52
103,421,723
0
0
null
null
null
null
UTF-8
C++
false
false
150
cpp
#include "stdafx.h" #include "Boek.h" Boek::Boek() { } Boek::Boek(std::string name) { _name = name; } Boek::~Boek() { }
b6a456f7fba3501c2a87b358ec2b6efeaa135893
7fc17454c7eba676faf9c78c0c09f40668e11250
/api/c/tests/unit/basic/test_containers.cpp
55e7889d1db0ae94be64b6e68c410900709327bc
[ "Apache-2.0" ]
permissive
yjy616/Indigo
3bcecf7728289082667222d8b5545c27199d3d50
82f9ef9f43ca605f7265709e7a9256f1ff468d6c
refs/heads/master
2023-05-29T01:21:48.688094
2021-06-07T16:36:33
2021-06-07T16:36:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
734
cpp
#include <gtest/gtest.h> #include <base_cpp/array.h> #include <base_cpp/red_black.h> using namespace indigo; TEST(IndigoContainersTest, test_array) { Array<int> array; const auto initial_size = 100; array.resize(initial_size); array.zerofill(); ASSERT_EQ(array.size(), initial_size); array.clear(); ASSERT_EQ(array.size(), 0); const auto final_size = 200; array.resize(final_size); array.fffill(); ASSERT_EQ(array.size(), final_size); array.clear(); ASSERT_EQ(array.size(), 0); } TEST(IndigoContainersTest, test_red_black) { RedBlackMap<int, int> map; map.insert(1, 2); map.insert(2,3); ASSERT_EQ(map.size(), 2); map.clear(); ASSERT_EQ(map.size(), 0); }
80ef5a59199c409447ecee19eb6df840e03b08a4
2ebbf732886a1889b2fe1c4c2b075660a6a6aa59
/Cipher.cpp
480b9d565e516717721a011d6b9d410644d18dc4
[]
no_license
nperry15/202-proj4
a3104463bed4d331893c8d67f8b90e6d6f257849
0b6b8f8d589a158c7d57933f96167f261f319862
refs/heads/master
2022-04-26T09:49:08.270593
2020-04-28T22:39:19
2020-04-28T22:39:19
259,767,488
0
0
null
null
null
null
UTF-8
C++
false
false
2,292
cpp
//Title: Cipher.cpp //Author: Ncholas Perry //Date: 4/20/2020 //Description: This is an abstract class file; parent class to all the other cipher classes #include "Cipher.h" #include <iostream> #include <string> #include <sstream> //Used to format output for each subtype for output using namespace std; // Name: Cipher (Default Constructor) // Desc - Stores a message that is either read to be encrypted or already encrypted // Preconditions - None // Postconditions - A message is stored in a Cipher object Cipher::Cipher() { m_isEncrypted = false; m_message = ""; } // Name: Cipher (Overloaded Constructor) // Desc - Stores a message that is either read to be encrypted or already encrypted // Preconditions - A message is passed to this constructor, and if it is encrypted // Postconditions - A message is stored in a Cipher object Cipher::Cipher(string message, bool isEncrypted) { m_isEncrypted = isEncrypted; m_message = message; } // Name: ~Cipher (Destructor) // Desc - Virtual destructor // Preconditions - A derived class is being deleted // Postconditions - A base class is deleted Cipher::~Cipher() { m_message = ""; m_isEncrypted = false; } // Name: GetMessage // Desc - Returns the message // Preconditions - The message exists // Postconditions - A message is returned string Cipher::GetMessage() { return m_message; } // Name: GetIsEncrypted // Desc - Returns isEncrypted (0 is not encrypted and 1 is encrypted) // Preconditions - The cipher exists // Postconditions - A bool is returned bool Cipher::GetIsEncrypted() { return m_isEncrypted; } // Name: SetMessage // Desc - Updates a message // Preconditions - The message exists // Postconditions - A message is updated void Cipher::SetMessage(string message) { m_message = message; } // Name: ToggleEncrypted // Desc - Turns (true to false) or (false to true) // Preconditions - The cipher exists // Postconditions - The m_isEncrypted is toggled void Cipher::ToggleEncrypted() { if (m_isEncrypted) m_isEncrypted = false; else m_isEncrypted = true; } // Name: Overloaded << Operator // Desc - Outputs the message // Preconditions - The object exists // Postconditions - The message from the object is returned ostream& operator<<(ostream& output, Cipher& C) { return output << C.m_message; }
710cc5465a8f1005f68b2025d414f2f897935b04
31ac07ecd9225639bee0d08d00f037bd511e9552
/externals/OCCTLib/inc/StepVisual_ColourRgb.hxx
314f72478c4c2ef2fc33810c2d891c44006b7f05
[]
no_license
litao1009/SimpleRoom
4520e0034e4f90b81b922657b27f201842e68e8e
287de738c10b86ff8f61b15e3b8afdfedbcb2211
refs/heads/master
2021-01-20T19:56:39.507899
2016-07-29T08:01:57
2016-07-29T08:01:57
64,462,604
1
0
null
null
null
null
UTF-8
C++
false
false
1,916
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _StepVisual_ColourRgb_HeaderFile #define _StepVisual_ColourRgb_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_DefineHandle_HeaderFile #include <Standard_DefineHandle.hxx> #endif #ifndef _Handle_StepVisual_ColourRgb_HeaderFile #include <Handle_StepVisual_ColourRgb.hxx> #endif #ifndef _Standard_Real_HeaderFile #include <Standard_Real.hxx> #endif #ifndef _StepVisual_ColourSpecification_HeaderFile #include <StepVisual_ColourSpecification.hxx> #endif #ifndef _Handle_TCollection_HAsciiString_HeaderFile #include <Handle_TCollection_HAsciiString.hxx> #endif class TCollection_HAsciiString; class StepVisual_ColourRgb : public StepVisual_ColourSpecification { public: //! Returns a ColourRgb <br> Standard_EXPORT StepVisual_ColourRgb(); Standard_EXPORT virtual void Init(const Handle(TCollection_HAsciiString)& aName) ; Standard_EXPORT virtual void Init(const Handle(TCollection_HAsciiString)& aName,const Standard_Real aRed,const Standard_Real aGreen,const Standard_Real aBlue) ; Standard_EXPORT void SetRed(const Standard_Real aRed) ; Standard_EXPORT Standard_Real Red() const; Standard_EXPORT void SetGreen(const Standard_Real aGreen) ; Standard_EXPORT Standard_Real Green() const; Standard_EXPORT void SetBlue(const Standard_Real aBlue) ; Standard_EXPORT Standard_Real Blue() const; DEFINE_STANDARD_RTTI(StepVisual_ColourRgb) protected: private: Standard_Real red; Standard_Real green; Standard_Real blue; }; // other Inline functions and methods (like "C++: function call" methods) #endif
fb08c0d2636672b54a4222a71083226d91ea9697
e1071cd8065ed01b8bc42f5f47f964837ec723b8
/src/ripple/ledger/ApplyView.h
8c90ab09e0cde9dd2d05e251d724b2d31b69d0ec
[ "MIT-Wu", "MIT", "ISC", "BSL-1.0" ]
permissive
SAN-CHAIN/sand
07355acf0ba4607a5cb1408a1d86d87f03e3a317
1c51a7d1b215a7a2e1e06bd3b87a7e1da7239664
refs/heads/master
2020-06-22T01:27:21.168067
2016-10-15T11:22:18
2016-10-15T11:22:18
94,208,495
0
3
null
null
null
null
UTF-8
C++
false
false
6,190
h
//------------------------------------------------------------------------------ /* This file is part of rippled: https://github.com/ripple/rippled Copyright (c) 2012, 2013 Ripple Labs Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ //============================================================================== #ifndef RIPPLE_LEDGER_APPLYVIEW_H_INCLUDED #define RIPPLE_LEDGER_APPLYVIEW_H_INCLUDED #include <ripple/ledger/RawView.h> #include <ripple/ledger/ReadView.h> namespace ripple { enum ApplyFlags { tapNONE = 0x00, // Signature already checked tapNO_CHECK_SIGN = 0x01, // Enable supressed features for testing. // This lets unit tests exercise code that // is not turned on for production. // tapENABLE_TESTING = 0x02, // This is not the transaction's last pass // Transaction can be retried, soft failures allowed tapRETRY = 0x20, // Transaction came from a privileged source tapADMIN = 0x400, }; inline ApplyFlags operator|(ApplyFlags const& lhs, ApplyFlags const& rhs) { return static_cast<ApplyFlags>( static_cast<int>(lhs) | static_cast<int>(rhs)); } inline ApplyFlags operator&(ApplyFlags const& lhs, ApplyFlags const& rhs) { return static_cast<ApplyFlags>( static_cast<int>(lhs) & static_cast<int>(rhs)); } //------------------------------------------------------------------------------ /** Writeable view to a ledger, for applying a transaction. This refinement of ReadView provides an interface where the SLE can be "checked out" for modifications and put back in an updated or removed state. Also added is an interface to provide contextual information necessary to calculate the results of transaction processing, including the metadata if the view is later applied to the parent (using an interface in the derived class). The context info also includes values from the base ledger such as sequence number and the network time. This allows implementations to journal changes made to the state items in a ledger, with the option to apply those changes to the base or discard the changes without affecting the base. Typical usage is to call read() for non-mutating operations. For mutating operations the sequence is as follows: // Add a new value v.insert(sle); // Check out a value for modification sle = v.peek(k); // Indicate that changes were made v.update(sle) // Or, erase the value v.erase(sle) The invariant is that insert, update, and erase may not be called with any SLE which belongs to different view. */ class ApplyView : public ReadView { public: /** Returns the tx apply flags. Flags can affect the outcome of transaction processing. For example, transactions applied to an open ledger generate "local" failures, while transactions applied to the consensus ledger produce hard failures (and claim a fee). */ virtual ApplyFlags flags() const = 0; /** Prepare to modify the SLE associated with key. Effects: Gives the caller ownership of a modifiable SLE associated with the specified key. The returned SLE may be used in a subsequent call to erase or update. The SLE must not be passed to any other ApplyView. @return `nullptr` if the key is not present */ virtual std::shared_ptr<SLE> peek (Keylet const& k) = 0; /** Remove a peeked SLE. Requirements: `sle` was obtained from prior call to peek() on this instance of the RawView. Effects: The key is no longer associated with the SLE. */ virtual void erase (std::shared_ptr<SLE> const& sle) = 0; /** Insert a new state SLE Requirements: `sle` was not obtained from any calls to peek() on any instances of RawView. The SLE's key must not already exist. Effects: The key in the state map is associated with the SLE. The RawView acquires ownership of the shared_ptr. @note The key is taken from the SLE */ virtual void insert (std::shared_ptr<SLE> const& sle) = 0; /** Indicate changes to a peeked SLE Requirements: The SLE's key must exist. `sle` was obtained from prior call to peek() on this instance of the RawView. Effects: The SLE is updated @note The key is taken from the SLE */ /** @{ */ virtual void update (std::shared_ptr<SLE> const& sle) = 0; /** Get the number of modified entries */ virtual std::size_t size () = 0; //-------------------------------------------------------------------------- // Called when a credit is made to an account // This is required to support PaymentSandbox virtual void creditHook (AccountID const& from, AccountID const& to, STAmount const& amount) { } }; } // ripple #endif
3386100488410794c0ee148f203fed290ff288cf
e7e245b6f266ab277997b06e9d334f62fd67494e
/BUG_2.CPP
421c404df325589e4d931622ed78917408f64bc6
[]
no_license
amankumarkeshu/Spoj-Questions
22c2ec58db9ca4ce02c106629018edc1633ecc5f
29c9f16fb028979e7bfa5b7bf9091715290a0afd
refs/heads/master
2020-03-28T17:51:49.314185
2019-04-17T10:06:24
2019-04-17T10:06:24
148,829,949
3
0
null
null
null
null
UTF-8
C++
false
false
5,204
cpp
#include<bits/stdc++.h> #define ll long long #define ld long double #define tt(t) read(t); while(t--) #define endl '\n' #define vll vector<ll> #define vvll vector< vll > #define pll pair<ll ,ll > #define pss pair < string , string > #define vpll vector< pll > #define vpss vector< pss > #define mp make_pair #define pb push_back #define MOD 1000000007 #define inf 1e18; #define find(v,x) ((v).find(x) != (v).end()) #define vfind(v,x) (find(all(v),x) != (v).end()) #define clr(c) (c).clear() #define cres(c,n) (c).clear(),(c).resize(n) #define ios ios_base::sync_with_stdio(false),cin.tie(NULL),cout.tie(NULL) #define all(v) v.begin(),v.end() #define rall(v) v.rbegin(),v.rend() #define fst first #define scd second #define fr(i,n) for(ll (i) = 0 ; (i) < (n) ; ++(i)) #define fr1(i,n) for(ll (i) = 1 ; (i) <= (n) ; ++(i)) #define frr(i,n) for(ll (i) = (n)-1 ; (i)>=0 ; --(i)) #define frab(i,a,b,c) for(ll (i) = a ; (i) <= (b) ; (i)+=(c)) #define mst(A) memset( (A) , 0 , sizeof(A) ); template< class T > void setmax(T &a, T b) { if(a < b) a = b; } template< class T > void setmin(T &a, T b) { if(b < a) a = b; } using namespace std; void read(ll &x){ scanf("%lld",&x); } void read(ll &x,ll &y){ scanf("%lld %lld",&x,&y); } void read(ll &x,ll &y,ll &z){ scanf("%lld %lld %lld",&x,&y,&z); } void read(ll &x,ll &y,ll &z,ll &w){ scanf("%lld %lld %lld %lld",&x,&y,&z,&w); } void read(vll &oneD){ for(ll i=0;i<oneD.size();i++){ read(oneD[i]); } } void read(vvll &twoD){ for(ll i=0;i<twoD.size();i++){ read(twoD[i]); } } void write(vll &oneD){ for(ll i=0;i<oneD.size();i++){ printf("%lld ",oneD[i]); } printf("\n"); } void write(vvll &twoD){ for(ll i=0;i<twoD.size();i++){ write(twoD[i]); } } void write(vpll &oneDP){ fr(i,oneDP.size()){ printf("%lld %lld\n" , oneDP[i].fst , oneDP[i].scd); } cout<<"\n"; } void write(map< ll , ll > &mpp){ for(map<ll , ll >::iterator it = mpp.begin() ; it != mpp.end() ; it++){ cout<<it->fst<<" : "<<it->scd<<endl; } cout<<endl; } bool cmp(const pair<ll,ll> &a,const pair<ll,ll> &b) { if(a.first == b.first) return (a.scd >= b.scd); return (a.first < b.first); } vll seive; vll primes; void Seive(){ const ll maxn = 100005; seive.resize(maxn); fr(i,maxn) seive[i] = 1; //seive[1] = 0; //seive[0] = 0; for(ll i=2;i*i<maxn;i++) { if(seive[i]==1 ) { for(ll j = i*i ; j <maxn ; j+=i) { seive[j] = 0; } } } primes.pb(2); for(ll i=3;i<maxn;i+=2) { if(seive[i]) primes.pb(i); } } void printprime(ll l,ll r) { if(l<2) l=2; bool isprime[r-l+1]; fr(i,r-l+1) isprime[i]=true; for( int i =0; primes[i]*primes[i] <= r; i++) { // Smaller or equal value to l //cout<<primes[i]<<"primes[i] "; ll base = (l/primes[i])*primes[i]; if(base < l) { base =base + primes[i]; } //Mark all multiples of primes [i] as false for( ll j= base ;j<=r; j+=primes[i]) { isprime[j-l]= false; } // There may be a case where base itsef a prime if(base == primes[i]) isprime[base-l]=true; } for( int i=0; i<r-l+1; i++) { if(isprime[i]==true) cout<<i+l<<endl; } } ll isprime(ll N){ if(N<2 || (!(N&1) && N!=2)) return 0; for(ll i=3; i*i<=N; i+=2){ if(!(N%i)) return 0; } return 1; } ll mulmod(ll a, ll b, ll mod) { ll res = 0; // Initialize result a = a % mod; while (b > 0) { // If b is odd, add 'a' to result if (b % 2 == 1) res = (res + a) % mod; // Multiply 'a' with 2 a = (a * 2) % mod; // Divide b by 2 b /= 2; } // Return result return res % mod; } ll power(ll x, ll y , ll m){ long long int res = 1; x = x % m; while (y > 0) { // If y is odd, multiply x with result if (y & 1) res = mulmod(res,x,m); // y must be even now y = y>>1; // y = y/2 x = mulmod(x,x, m); } return res; } ll modinv(ll x , ll mod = MOD){ return power(x , mod - 2 , mod); } ////////////////////////////////////////////////////////////////////////////////////// int main() { ll a,b,c,d; ll k,l,m,n,p,q,r,s,t; vpll v; v.clear(); //Seive(); tt(t) { ll A[127]={0},B[127]={0}; string s1,s2; cin>>s1>>s2; n=s1.length(); m=s2.length(); ll flag=0; fr(i,n) { A[s1[i]]++; } fr(i,m) { B[s2[i]]++; } fr1(i,123) { if(B[i]>=A[i]) { //cout<<(char)i+96<<" "; } else { //cout<<i<<" "; //cout<<B[i]<<" "<<A[i]<<endl; flag=1; } } if(flag) cout<<"No\n"; else cout<<"Yes\n"; } }
e876096692ee190e801ade224df0faafc62ba8f3
a98dda4df2b85fc27192378d6fbde58510dc0ed0
/Vectors/Vectors/Vectors.cpp
c7ce91a3edf696b664e08214c970f49324af308f
[]
no_license
rydanie/VestorsExample
d7159ba793eee637cddfd4c67b914e717c3ec2f9
406498cf84fdd7ee8f52303c1365ac14b2aa3405
refs/heads/master
2020-12-14T07:10:49.576338
2020-01-18T03:51:14
2020-01-18T03:51:14
234,677,470
0
0
null
null
null
null
UTF-8
C++
false
false
2,317
cpp
///VECTOR #include <vector> #include <iostream> #include <algorithm> #include <iomanip> using namespace std; void calculate(); //Function To calculate int main() { int choice = 0; do { system("cls"); //Clear the Screen cout << "Vector\n\n"; cout << " 1. Enter Numbers \n"; cout << " 2. End Program \n"; while ((!(cin >> choice) || (choice < 0 || choice > 2))) { cout << "must Ener 1 or 2\n "; cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } if (choice == 1) { calculate(); cout << "Enter To Continue "; cin.get(); cin.get(); } } while (choice != 2); return 0; } void calculate() { cout << setprecision(2) << fixed; char choice = 'Y'; vector<double> array; double number = 0.0, sum = 0.0, mean = 0.0, median = 0.0; do { system("CLS"); cout << "Enter your number: " << endl; while (!(cin >> number) || (choice < 0)) { cout << "Must Ener a positive Number\n "; cin.clear(); cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } array.push_back(number); cout << "Enter Another Number Y/N "; cin >> choice; } while (toupper(choice) == 'Y'); //Unsorted Numbers cout << "\nUnsorted Numbers "; for (int j = 0; j < array.size(); ++j) cout << array[j] << ' '; //Sort Descending cout << "\nSorted Ascending "; sort(array.begin(), array.end()); for (int j = 0; j < array.size(); ++j) cout << array[j] << ' '; //Sort Ascending cout << "\nSorted Descending "; sort(array.begin(), array.end(), greater<int>()); for (int j = 0; j < array.size(); ++j) cout << array[j] << ' '; //Mean (Average) cout << "\nAverage "; for (int j = 0; j < array.size(); ++j) sum += array[j]; mean = sum / array.size(); cout << mean << ' '; //Median cout << "\nMedian "; int size = array.size(); int oddeven = size % 2; if (size == 1) { median = array[0]; cout << median << ' '; } else if (oddeven = 0) { int index = size / 2; median = array[index]; cout << median << ' '; } else { int index = size / 2; median = (array[index]+ array[index-1])/2; cout << median << ' '; } cout << "\n\nEnter to Continue "; //cin.get(); }
79f0b9167ead7bc77891775ab3a98bbe58afec88
fc2d01d1afa08ffc46c23901163c37e679c3beaf
/Core/StdFile.cpp
533d3729043f127ca134fd910935909cd517be4f
[]
no_license
seblef/ShadowEngine
a9428607b49cdd41eb22dcbd8504555454e26a0c
fba95e910c63269bfe0a05ab639dc78b6c16ab8b
refs/heads/master
2023-02-14T19:08:25.878492
2021-01-08T16:16:44
2021-01-08T16:16:44
113,681,956
1
0
null
null
null
null
UTF-8
C++
false
false
297
cpp
#include "StdFile.h" using namespace Core; bool StdFile::seek(size_t offset, FileSeek fs) { ios::seekdir sd; switch(fs) { case FS_START: sd=ios::beg; break; case FS_END: sd=ios::end; break; default: sd=ios::cur; } _fs.seekp(offset,sd); return _fs.good(); }
1f4d72ceb37d50dd8a694c5d49e2f087f583b158
6ca4d5f12e9a3839e70163856ff29220f63375f9
/dependencies/thermite3d/include/scriptable/RenderComponent.h
cea8e0b67c70db2e50e5b99078cf3c9b0fec1585
[ "MIT" ]
permissive
weflowers/voxeliens
8d75f304067cea534cd906c86715f08207496640
64322d13d1661b6d5f88032b16f410516b9690b8
refs/heads/master
2023-01-31T21:22:55.461634
2020-12-11T19:35:47
2020-12-11T19:35:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
492
h
#ifndef RENDER_COMPONENT_H_ #define RENDER_COMPONENT_H_ #include "Component.h" #include "OgreSceneNode.h" namespace Thermite { class RenderComponent : public Component { public: RenderComponent(Object* parent); ~RenderComponent(void); void onEnabled(bool enabled); void update(void); public: Ogre::SceneManager* mSceneManager; Ogre::SceneNode* mOgreSceneNode; bool mIsVisible; bool mUpdateIsVisible; }; } #endif //RENDER_COMPONENT_H_
b968362744c2d2e1d65238878d04021c9e45ecfb
96d44e7e9ba85a38d44c204c58e93bf5fc4a546c
/for_spectra/auau15gev/tpcAnal/StRoot/StRefMultCorr/StRefMultCorr.h
0b4f560303156126792af9651819524e068a19a5
[]
no_license
ManukhovStepan/Aparin-laboratory
00abfcb53d634de6026fbfa98009113db13a45f7
b1072a7eb036e5cadf3388b8511f755c039dbb37
refs/heads/master
2022-11-28T01:17:57.519553
2020-08-11T08:59:47
2020-08-11T08:59:47
255,908,201
0
2
null
2020-08-11T08:59:49
2020-04-15T12:21:54
C++
UTF-8
C++
false
false
8,217
h
//------------------------------------------------------------------------------ // $Id: StRefMultCorr.h,v 1.1 2018/09/07 10:49:45 nasim Exp $ // $Log: StRefMultCorr.h,v $ // Revision 1.1 2018/09/07 10:49:45 nasim // *** empty log message *** // // Revision 1.9 2015/05/22 06:52:07 hmasui // Add grefmult for Run14 Au+Au 200 GeV // // Revision 1.8 2013/05/10 18:33:33 hmasui // Add TOF tray mult, preliminary update for Run12 U+U // // Revision 1.7 2012/05/08 03:19:51 hmasui // Move parameters to Centrality_def_refmult.txt // // Revision 1.6 2012/04/23 21:29:33 hmasui // Added isBadRun() function for outlier rejection, getBeginRun() and getEndRun() to obtain the run range for a given (energy,year) // // Revision 1.5 2011/11/08 19:11:03 hmasui // Add luminosity corrections for 200 GeV // // Revision 1.4 2011/10/11 19:35:18 hmasui // Fix typo. Add z-vertex check in getWeight() function // // Revision 1.3 2011/10/10 21:30:34 hmasui // Replaced hard coded parameters for z-vertex and weight corrections by input parameters from text file // // Revision 1.2 2011/08/12 20:28:04 hmasui // Avoid varying corrected refmult in the same event by random number // // Revision 1.1 2011/08/11 18:38:36 hmasui // First version of Refmult correction class // //------------------------------------------------------------------------------ // StRefMultCorr class // - Provide centrality bins based on multiplicity (refmult, refmult2, tof tray mulitplicity etc) // * 5% increment centrality bins (16 bins) // * 5% increment in 0-10%, and 10% increment in 10-80% (9 bins) // - Provide corrected multiplicity (z-vertex dependence) // - Provide "re-weighting" correction, only relevant to the peripheral bins // // Centrality binning: // Bin Centrality (16) Centrality (9) // 0 75-80% 70-80% // 1 70-75% 60-70% // 2 65-70% 50-60% // 3 60-65% 40-50% // 4 55-60% 30-40% // 5 50-55% 20-30% // 6 45-50% 10-20% // 7 40-45% 5-10% // 8 35-40% 0- 5% // 9 30-35% // 10 25-30% // 11 20-25% // 12 15-20% // 13 10-15% // 14 5-10% // 15 0- 5% // // See how to use this class in StRefMultCorr/macros/getCentralityBins.C // // authors: Alexander Schmah, Hiroshi Masui //------------------------------------------------------------------------------ #ifndef __StRefMultCorr_h__ #define __StRefMultCorr_h__ #include <vector> #include <map> #include "TString.h" //______________________________________________________________________________ // Class to correct z-vertex dependence, luminosity dependence of multiplicity class StRefMultCorr { public: // Specify the type of multiplicity (default is refmult) // "refmult" - reference multiplicity defined in |eta|<0.5 // "refmult2" - reference multiplicity defined in 0.5<|eta|<1.0 // "refmult3" - reference multiplicity defined in |eta|<0.5 without protons // "toftray" - TOF tray multiplicity // "grefmult" - global reference multiplicity defined in |eta|<0.5,dca<3,nHitsFit>10 StRefMultCorr(const TString name="refmult"); virtual ~StRefMultCorr(); /// Default destructor // Bad run rejection Bool_t isBadRun(const Int_t RunId) ; // Event-by-event initialization. Call this function event-by-event // * Default ZDC coincidence rate = 0 to make the function backward compatible // --> i.e. no correction will be applied unless users set the values for 200 GeV void initEvent(const UShort_t RefMult, const Double_t z, const Double_t zdcCoincidenceRate=0.0) ; // Set multiplicity, vz and zdc coincidence rate /// Get corrected multiplicity, correction as a function of primary z-vertex Double_t getRefMultCorr() const; // Corrected multiplity // flag=0: Luminosity only // flag=1: z-vertex only // flag=2: full correction (default) Double_t getRefMultCorr(const UShort_t RefMult, const Double_t z, const Double_t zdcCoincidenceRate, const UInt_t flag=2) const ; /// Get 16 centrality bins (5% increment, 0-5, 5-10, ..., 75-80) Int_t getCentralityBin16() const; /// Get 9 centrality bins (10% increment except for 0-5 and 5-10) Int_t getCentralityBin9() const; /// Re-weighting correction, correction is only applied up to mNormalize_step (energy dependent) Double_t getWeight() const; // Initialization of centrality bins etc void init(const Int_t RunId); // Read scale factor from text file void setVzForWeight(const Int_t nbin, const Double_t min, const Double_t max) ; void readScaleForWeight(const Char_t* input) ; // Return begin/end run from energy and year Int_t getBeginRun(const Double_t energy, const Int_t year) ; Int_t getEndRun(const Double_t energy, const Int_t year) ; // Print all parameters void print(const Option_t* option="") const ; private: const TString mName ; // refmult, refmult2, refmult3 or toftray (case insensitive) // Functions void read() ; /// Read input parameters from text file StRoot/StRefMultCorr/Centrality_def.txt void readBadRuns() ; /// Read bad run numbers void clear() ; /// Clear all arrays Bool_t isIndexOk() const ; /// 0 <= mParameterIndex < maxArraySize Bool_t isZvertexOk() const ; /// mStart_zvertex < z < mStop_zvertex Bool_t isRefMultOk() const ; /// 0-80%, (corrected multiplicity) > mCentrality_bins[0] Bool_t isCentralityOk(const Int_t icent) const ; /// centrality bin check Int_t setParameterIndex(const Int_t RunId) ; /// Parameter index from run id (return mParameterIndex) // Special scale factor for Run14 to take into account the weight // between different triggers // - return 1 for all the other runs Double_t getScaleForWeight() const ; // Get table name based on the input multiplicity definition const Char_t* getTable() const ; // Data members enum { mNCentrality = 16, /// 16 centrality bins, starting from 75-80% with 5% bin width mNPar_z_vertex = 8, mNPar_weight = 8, mNPar_luminosity = 2 }; // Use these variables to avoid varying the corrected multiplicity // in the same event by random numbers UShort_t mRefMult ; /// Current multiplicity Double_t mVz ; /// Current primary z-vertex Double_t mZdcCoincidenceRate ; /// Current ZDC coincidence rate Double_t mRefMult_corr; /// Corrected refmult std::vector<Int_t> mYear ; /// Year std::vector<Int_t> mStart_runId ; /// Start run id std::vector<Int_t> mStop_runId ; /// Stop run id std::vector<Double_t> mStart_zvertex ; /// Start z-vertex (cm) std::vector<Double_t> mStop_zvertex ; /// Stop z-vertex (cm) std::vector<Double_t> mNormalize_stop ; /// Normalization between MC and data (normalized in refmult>mNormalize_stop) std::vector<Int_t> mCentrality_bins[mNCentrality+1] ; /// Centrality bins (last value is set to 5000) std::vector<Double_t> mPar_z_vertex[mNPar_z_vertex] ; /// parameters for z-vertex correction std::vector<Double_t> mPar_weight[mNPar_weight] ; /// parameters for weight correction std::vector<Double_t> mPar_luminosity[mNPar_luminosity] ; /// parameters for luminosity correction (valid only for 200 GeV) Int_t mParameterIndex; /// Index of correction parameters std::multimap<std::pair<Double_t, Int_t>, Int_t> mBeginRun ; /// Begin run number for a given (energy, year) std::multimap<std::pair<Double_t, Int_t>, Int_t> mEndRun ; /// End run number for a given (energy, year) std::vector<Int_t> mBadRun ; /// Bad run number list // [6][680]; Int_t mnVzBinForWeight ; /// vz bin size for scale factor std::vector<Double_t> mVzEdgeForWeight ; /// vz edge value std::vector<Double_t> mgRefMultTriggerCorrDiffVzScaleRatio ; /// Scale factor for global refmult ClassDef(StRefMultCorr, 0) }; #endif
fbd95e919280ee7cda0bda642c89214ab67cb77f
bd1fea86d862456a2ec9f56d57f8948456d55ee6
/000/107/405/CWE590_Free_Memory_Not_on_Heap__delete_int64_t_placement_new_63b.cpp
4f1509d3599a480515654a657f303a28fafea0b3
[]
no_license
CU-0xff/juliet-cpp
d62b8485104d8a9160f29213368324c946f38274
d8586a217bc94cbcfeeec5d39b12d02e9c6045a2
refs/heads/master
2021-03-07T15:44:19.446957
2020-03-10T12:45:40
2020-03-10T12:45:40
246,275,244
0
1
null
null
null
null
UTF-8
C++
false
false
1,241
cpp
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE590_Free_Memory_Not_on_Heap__delete_int64_t_placement_new_63b.cpp Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete.pointer.label.xml Template File: sources-sink-63b.tmpl.cpp */ /* * @description * CWE: 590 Free Memory Not on Heap * BadSource: placement_new Data buffer is declared on the stack * GoodSource: Allocate memory on the heap * Sinks: * BadSink : Print then free data * Flow Variant: 63 Data flow: pointer to data passed from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> namespace CWE590_Free_Memory_Not_on_Heap__delete_int64_t_placement_new_63 { #ifndef OMITBAD void badSink(int64_t * * dataPtr) { int64_t * data = *dataPtr; printLongLongLine(*data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(int64_t * * dataPtr) { int64_t * data = *dataPtr; printLongLongLine(*data); /* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */ delete data; } #endif /* OMITGOOD */ } /* close namespace */
98d1cc526d52777216be2f2ee9225df26442ba48
e9e6534a8b8f9112eb8349fcf95394d9ffee5de9
/msm/fff0/src/msm.cpp
c14a7dee7f6d493f123764e2fb88b2557a7814f7
[]
no_license
ld1988/Fokker-Planck
473933a3d7d99964a2e858c74851d47bea483c35
9136c18e058e7737e3b10c67a750f271b13136b2
refs/heads/master
2020-05-18T07:13:16.252321
2019-04-26T10:30:51
2019-04-26T10:30:51
184,258,321
0
0
null
2019-04-30T12:30:05
2019-04-30T12:30:04
null
UTF-8
C++
false
false
5,680
cpp
#include <iostream> #include <time.h> #include <stdlib.h> #include <algorithm> #include <vector> #include <string> #include <sstream> #include <fstream> #include <math.h> #include "header.h" using namespace std; ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void transitionMatrix1d(int f, double *x, par parameters, const std::string& folder) { ////////PARAMETERS int T = parameters.nsteps; int tau = parameters.tau; int delta = parameters.delta; int mx; double xmin, xmax; double xdelta; if (f==0) { mx = parameters.mx; xmin = parameters.xmin; xmax = parameters.xmax; xdelta = parameters.xdelta; } else if (f==1) { mx = parameters.my; xmin = parameters.ymin; xmax = parameters.ymax; xdelta = parameters.ydelta; } ///////// COUNTING MATRIX int i,j; double C[mx][mx]; int start, end; int k; for (i=0; i<mx; i++) for (j=0; j<mx; j++) C[i][j]=0; for (k=0; k<T-tau; k=k+delta) { if( fmod((double)(k+1), (double)((T-tau)/100.))==0) cout << "\r" << "Counting matrix..." << 100*(double)(k+1)/(double)(T-tau) << "% " <<std::flush; //Get index of start start = floor((x[k] - xmin) / xdelta); //Get index of end end = floor((x[k+tau] - xmin) / xdelta); //cout << x[k] << " " << xmin << endl; // increase count in the corresponding transition C[start][end]++; // enforce detailed balance C[end][start]++ ; } cout << endl; //////// SAVE MATRIX string name; if (f==0) name = ".//" + folder + "Cx" + doubleToString(tau) + ".txt"; else if (f==1) name = ".//" + folder + "Cy" + doubleToString(tau) + ".txt"; ofstream file; file.open(name.c_str()); for (int i=0 ; i<mx ; i++) { for (int j=0 ; j<mx; j++) file<< C[i][j] << " "; file << endl; } file.close(); file.clear(); cout <<"Transition matrix " << doubleToString(tau) << ", done." <<endl; cout << endl; } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void transitionMatrix2d(double *x, double *y, par parameters, const std::string& folder) { ////////PARAMETERS int T = parameters.nsteps; int tau = parameters.tau; int delta = parameters.delta; int mx, my; double xmin, xmax, ymin, ymax; double xdelta, ydelta; mx = parameters.mx; xmin = parameters.xmin; xmax = parameters.xmax; xdelta = parameters.xdelta; my = parameters.my; ymin = parameters.ymin; ymax = parameters.ymax; ydelta = parameters.ydelta; ///////// COUNTING MATRIX int i,j; int m=mx*my; double** C = new double*[m]; for (i = 0; i < m; ++i) C[i] = new double[m]; int x_start, y_start, start; int x_end, y_end, end; int k; for (i=0; i<m; i++) for (j=0; j<m; j++) C[i][j]=0; for (k=0; k<T-tau; k=k+delta) { // if( fmod((double)(k+1), (double)((T-tau)/100.))==0) //cout << "\r" << "Counting matrix..." << 100*(double)(k+1)/(double)(T-tau) << "% " <<std::flush; /* //Get index of start x_start = x[k] < xmin ? 0 : x[k] >= xmax ? mx-1 : floor((x[k] - xmin) / xdelta); y_start = y[k] < ymin ? 0 : y[k] >= ymax ? my-1 : floor((y[k] - ymin) / ydelta); //Get index of end x_end = x[k+tau] < xmin ? 0 : x[k+tau] >= xmax ? mx-1 : floor((x[k+tau] - xmin) / xdelta); y_end = y[k+tau] < ymin ? 0 : y[k+tau] >= ymax ? my-1 : floor((y[k+tau] - ymin) / ydelta); start = x_start + my*y_start; end = x_end + my*y_end; */ x_start = floor((x[k] - xmin) / xdelta); //cout << xmin << " " << x[k] << " " << x_start << endl; x_end = floor((x[k+tau] - xmin) / xdelta); //cout << xmin << " " << x[k+tau] << " " << x_end << endl; y_start = floor((y[k] - ymin) / ydelta); //cout << ymin << " " << y[k] << " " << y_start << endl; y_end = floor((y[k+tau] - ymin) / ydelta); //cout << ymin << " " << y[k+tau] << " " << y_end << endl; start = x_start + mx * y_start; end = x_end + my * y_end; //cout << start << " " << end << endl; //cout << k << " " << T-tau << endl; // increase count in the corresponding transition C[start][end]++; // enforce detailed balance C[end][start]++ ; //cout << " dsaas " <<endl; } cout << endl; //////// SAVE MATRIX string name; name = ".//" + folder + "Cxy" + doubleToString(tau) + ".txt"; ofstream file; file.open(name.c_str()); for (int i=0 ; i<m ; i++) { for (int j=0 ; j<m ; j++) file<< C[i][j] << " "; file << endl; } file.close(); file.clear(); for (i = 0; i < m; ++i) delete [] C[i]; delete [] C; cout <<"Transition matrix2d " << doubleToString(tau) << ", done." <<endl; cout << endl; cout << endl; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
6082b8716ab84be93deda605ad6f22a2584c7e98
328ad992496c5d45b1dabf2027185435b5b281bc
/source/lock.hpp
9ce56ced93f9e7889c4d22a0d83b55e16be475c4
[ "MIT" ]
permissive
masagrator/NX-FPS
cdfdb2873bd4c6c4b9474ca1613935066d7853da
3d6a19e7b6a6b4fb19fc63e7baaf34b1173b8f76
refs/heads/master
2023-09-01T14:05:01.650718
2023-07-01T16:20:19
2023-07-01T16:20:19
243,776,092
179
11
MIT
2023-05-22T16:35:08
2020-02-28T14:04:56
C
UTF-8
C++
false
false
11,144
hpp
#pragma once #define NOINLINE __attribute__ ((noinline)) /* Design file how to build binary file for FPSLocker. 1. Helper functions */ namespace LOCK { uint32_t offset = 0; bool blockDelayFPS = false; uint8_t gen = 0; bool MasterWriteApplied = false; struct { int64_t main_start; uint64_t alias_start; uint64_t heap_start; } mappings; template <typename T> bool compareValues(T value1, T value2, uint8_t compare_type) { // 1 - >, 2 - >=, 3 - <, 4 - <=, 5 - ==, 6 - != switch(compare_type) { case 1: return (value1 > value2); case 2: return (value1 >= value2); case 3: return (value1 < value2); case 4: return (value1 <= value2); case 5: return (value1 == value2); case 6: return (value1 != value2); } return false; } uint8_t read8(uint8_t* buffer) { uint8_t ret = buffer[offset]; offset += sizeof(uint8_t); return ret; } uint16_t read16(uint8_t* buffer) { uint16_t ret = *(uint16_t*)(&buffer[offset]); offset += sizeof(uint16_t); return ret; } uint32_t read32(uint8_t* buffer) { uint32_t ret = *(uint32_t*)(&buffer[offset]); offset += sizeof(uint32_t); return ret; } uint64_t read64(uint8_t* buffer) { uint64_t ret = *(uint64_t*)(&buffer[offset]); offset += sizeof(uint64_t); return ret; } float readFloat(uint8_t* buffer) { float ret = *(float*)(&buffer[offset]); offset += sizeof(float); return ret; } double readDouble(uint8_t* buffer) { double ret = *(double*)(&buffer[offset]); offset += sizeof(double); return ret; } template <typename T> void writeValue(T value, int64_t address) { if (*(T*)address != value) *(T*)address = value; } bool unsafeCheck = false; bool NOINLINE isAddressValid(int64_t address) { MemoryInfo memoryinfo = {0}; u32 pageinfo = 0; if (unsafeCheck) return true; if ((address < 0) || (address >= 0x8000000000)) return false; Result rc = svcQueryMemory(&memoryinfo, &pageinfo, address); if (R_FAILED(rc)) return false; if ((memoryinfo.perm & Perm_Rw) && ((address - memoryinfo.addr >= 0) && (address - memoryinfo.addr <= memoryinfo.size))) return true; return false; } int64_t NOINLINE getAddress(uint8_t* buffer, uint8_t offsets_count) { uint8_t region = read8(buffer); offsets_count -= 1; int64_t address = 0; switch(region) { case 1: { address = mappings.main_start; break; } case 2: { address = mappings.heap_start; break; } case 3: { address = mappings.alias_start; break; } default: return -1; } for (int i = 0; i < offsets_count; i++) { int32_t temp_offset = (int32_t)read32(buffer); address += temp_offset; if (i+1 < offsets_count) { if (!isAddressValid(*(int64_t*)address)) return -2; address = *(uint64_t*)address; } } return address; } ///2. File format and reading bool isValid(uint8_t* buffer, size_t filesize) { if (*(uint32_t*)buffer != 0x4B434F4C) return false; gen = buffer[4]; if (gen < 1 || gen > 2) return false; if (*(uint16_t*)(&(buffer[5])) != 0) return false; if (buffer[7] > 1) return false; unsafeCheck = (bool)buffer[7]; uint8_t start_offset = 0x30; if (gen == 2) start_offset += 4; if (*(uint32_t*)(&(buffer[8])) != start_offset) return false; return true; } Result applyMasterWrite(FILE* file, size_t filesize) { uint32_t offset = 0; if (gen != 2) return 0x311; SaltySDCore_fseek(file, 0x30, 0); SaltySDCore_fread(&offset, 4, 1, file); SaltySDCore_fseek(file, offset, 0); if (SaltySDCore_ftell(file) != offset) return 0x312; int8_t OPCODE = 0; while(true) { SaltySDCore_fread(&OPCODE, 1, 1, file); if (OPCODE == 1) { uint32_t main_offset = 0; SaltySDCore_fread(&main_offset, 4, 1, file); uint8_t value_type = 0; SaltySDCore_fread(&value_type, 1, 1, file); uint8_t elements = 0; SaltySDCore_fread(&elements, 1, 1, file); switch(value_type) { case 1: case 0x11: { void* temp_buffer = calloc(elements, 1); SaltySDCore_fread(temp_buffer, 1, elements, file); SaltySD_Memcpy(LOCK::mappings.main_start + main_offset, (u64)temp_buffer, elements); free(temp_buffer); break; } case 2: case 0x12: { void* temp_buffer = calloc(elements, 2); SaltySDCore_fread(temp_buffer, 2, elements, file); SaltySD_Memcpy(LOCK::mappings.main_start + main_offset, (u64)temp_buffer, elements*2); free(temp_buffer); break; } case 4: case 0x14: case 0x24: { void* temp_buffer = calloc(elements, 4); SaltySDCore_fread(temp_buffer, 4, elements, file); SaltySD_Memcpy(LOCK::mappings.main_start + main_offset, (u64)temp_buffer, elements*4); free(temp_buffer); break; } case 8: case 0x18: case 0x28: { void* temp_buffer = calloc(elements, 8); SaltySDCore_fread(temp_buffer, 8, elements, file); SaltySD_Memcpy(LOCK::mappings.main_start + main_offset, (u64)temp_buffer, elements*8); free(temp_buffer); break; } default: return 0x313; } } else if (OPCODE == -1) { MasterWriteApplied = true; return 0; } else return 0x355; } } Result applyPatch(uint8_t* buffer, size_t filesize, uint8_t FPS) { FPS -= 15; FPS /= 5; FPS *= 4; blockDelayFPS = false; offset = *(uint32_t*)(&buffer[FPS+8]); while(true) { /* OPCODE: 0 = err 1 = write 2 = compare 3 = block -1 = endExecution */ int8_t OPCODE = read8(buffer); if (OPCODE == 1) { uint8_t offsets_count = read8(buffer); int64_t address = getAddress(buffer, offsets_count); if (address < 0) return 6; /* value_type: 1 = uint8 2 = uin16 4 = uint32 8 = uint64 0x11 = int8 0x12 = in16 0x14 = int32 0x18 = int64 0x24 = float 0x28 = double */ uint8_t value_type = read8(buffer); uint8_t loops = read8(buffer); switch(value_type) { case 1: case 0x11: { for (uint8_t i = 0; i < loops; i++) { *(uint8_t*)address = read8(buffer); address += 1; } break; } case 2: case 0x12: { for (uint8_t i = 0; i < loops; i++) { *(uint16_t*)address = read16(buffer); address += 2; } break; } case 4: case 0x14: case 0x24: { for (uint8_t i = 0; i < loops; i++) { *(uint32_t*)address = read32(buffer); address += 4; } break; } case 8: case 0x18: case 0x28: { for (uint8_t i = 0; i < loops; i++) { *(uint64_t*)address = read64(buffer); address += 8; } break; } default: return 3; } } else if (OPCODE == 2) { uint8_t offsets_count = read8(buffer); int64_t address = getAddress(buffer, offsets_count); if (address < 0) return 6; /* compare_type: 1 = > 2 = >= 3 = < 4 = <= 5 = == 6 = != */ uint8_t compare_type = read8(buffer); uint8_t value_type = read8(buffer); bool passed = false; switch(value_type) { case 1: { uint8_t uint8_compare = *(uint8_t*)address; uint8_t uint8_tocompare = read8(buffer); passed = compareValues(uint8_compare, uint8_tocompare, compare_type); break; } case 2: { uint16_t uint16_compare = *(uint16_t*)address; uint16_t uint16_tocompare = read16(buffer); passed = compareValues(uint16_compare, uint16_tocompare, compare_type); break; } case 4: { uint32_t uint32_compare = *(uint32_t*)address; uint32_t uint32_tocompare = read32(buffer); passed = compareValues(uint32_compare, uint32_tocompare, compare_type); break; } case 8: { uint64_t uint64_compare = *(uint64_t*)address; uint64_t uint64_tocompare = read64(buffer); passed = compareValues(uint64_compare, uint64_tocompare, compare_type); break; } case 0x11: { int8_t int8_compare = *(int8_t*)address; int8_t int8_tocompare = (int8_t)read8(buffer); passed = compareValues(int8_compare, int8_tocompare, compare_type); break; } case 0x12: { int16_t int16_compare = *(int16_t*)address; int16_t int16_tocompare = (int16_t)read16(buffer); passed = compareValues(int16_compare, int16_tocompare, compare_type); break; } case 0x14: { int32_t int32_compare = *(int32_t*)address; int32_t int32_tocompare = (int32_t)read32(buffer); passed = compareValues(int32_compare, int32_tocompare, compare_type); break; } case 0x18: { int64_t int64_compare = *(int64_t*)address; int64_t int64_tocompare = (int64_t)read64(buffer); passed = compareValues(int64_compare, int64_tocompare, compare_type); break; } case 0x24: { float float_compare = *(float*)address; float float_tocompare = readFloat(buffer); passed = compareValues(float_compare, float_tocompare, compare_type); break; } case 0x28: { double double_compare = *(double*)address; double double_tocompare = readDouble(buffer); passed = compareValues(double_compare, double_tocompare, compare_type); break; } default: return 3; } offsets_count = read8(buffer); address = getAddress(buffer, offsets_count); if (address < 0) return 6; value_type = read8(buffer); uint8_t loops = read8(buffer); switch(value_type) { case 1: case 0x11: { for (uint8_t i = 0; i < loops; i++) { uint8_t value8 = read8(buffer); if (passed) writeValue(value8, address); address += 1; } break; } case 2: case 0x12: { for (uint8_t i = 0; i < loops; i++) { uint16_t value16 = read16(buffer); if (passed) writeValue(value16, address); address += 2; } break; } case 4: case 0x14: case 0x24: { for (uint8_t i = 0; i < loops; i++) { uint32_t value32 = read32(buffer); if (passed) writeValue(value32, address); address += 4; } break; } case 8: case 0x18: case 0x28: { for (uint8_t i = 0; i < loops; i++) { uint64_t value64 = read64(buffer); if (passed) writeValue(value64, address); address += 8; } break; } default: return 3; } } else if (OPCODE == 3) { switch(read8(buffer)) { case 1: blockDelayFPS = true; break; default: return 7; } } else if (OPCODE == -1) { return -1; } else return 255; } } }
673a7db6492227e1c1996b24178c3487367db332
f75d79c35ee9c42213837405efb0489ef95dff4a
/C867/securityStudent.h
94e4da17a8c4d659bd59057e518d829c7cacb8c9
[]
no_license
djok1/C867
398951964038a6a9c1c4b95fa008ae21bd7901f1
b8234c59c361757709da95ec964ceb3a5b767f9c
refs/heads/master
2022-10-29T10:13:27.146076
2019-09-09T04:58:59
2019-09-09T04:58:59
202,541,307
1
0
null
null
null
null
UTF-8
C++
false
false
414
h
#pragma once #include "student.h" class securityStudent : public student { private: DegreeType degreeType = security; public: string getDegreeType() { return "Security"; } securityStudent(string StudentID, string FirstName, string LastName, string Email, string Age, string Days1, string Days2, string Days3) :student(StudentID, FirstName, LastName, Email, Age, Days1, Days2, Days3) { } };
1aef01f180436c891cb128393d345da60a8b8b8d
5971ac054f281c79989f29765443b7aa510650d7
/src/standard/bits/DD_replace.hpp
a716ddf6fcab6421ce38cdff9987b7a475e7f37e
[ "BSD-3-Clause" ]
permissive
ArshartCloud/libDDCPP
41c01b5f88912b7af49387b54d2cd2854616f0e0
e9e717794c38fe8a9e1098cd4892f01df1594889
refs/heads/master
2021-01-15T11:08:06.050206
2015-09-29T09:05:30
2015-09-29T09:05:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,063
hpp
// DDCPP/standard/bits/DD_replace.hpp #ifndef DD_REPLACE_HPP_INCLUDED_ # define DD_REPLACE_HPP_INCLUDED_ 1 # include "DD_global_definitions.hpp" DD_BEGIN_ template <typename UndirectionalIteratorT_, typename ValueT1_, typename ValueT2_> ProcessType replace( UndirectionalIteratorT_ begin__, UndirectionalIteratorT_ const& end__, ValueT1_ const& old__, ValueT2_ value__ ) DD_NOEXCEPT_AS(*++begin__ = value__ DD_COMMA begin__ != end__ && *begin__ == old__) { for (; begin__ != end__; ++begin__) { if (*begin__ == old__) { *begin__ = value__; } } } template <typename UndirectionalIteratorT_, typename ValueT1_, typename BinaryPredicatorT_, typename ValueT2_> ProcessType replace( UndirectionalIteratorT_ begin__, UndirectionalIteratorT_ const& end__, ValueT1_ old__, BinaryPredicatorT_ const& equal__, ValueT2_ value__ ) DD_NOEXCEPT_AS(*++begin__ = value__ DD_COMMA begin__ != end__ && equal__(*begin__, old__)) { for (; begin__ != end__; ++begin__) { if (equal__(*begin__, old__)) { *begin__ = value__; } } } DD_END_ #endif
f2875b792519f990a2bb56acc2de73a1a2ca58a0
44ab5e73bae277f1078dbe73fd0f99a7f0c98fa6
/include/MacroSupplyManager.h
d8afce8137869f38a5d7a81c4378058e35e81a64
[]
no_license
albertouri/dementor-bot
f66dfb00f1391a7457d07cf136eee086b5cdfd29
b62de93062767943bb8a6c30aaa825ddd31198be
refs/heads/master
2021-01-20T09:36:41.993561
2015-07-23T19:26:08
2015-07-23T19:26:08
39,587,387
1
0
null
null
null
null
UTF-8
C++
false
false
427
h
#pragma once #include <Arbitrator.h> #include <BWAPI.h> #include <MacroManager.h> class MacroSupplyManager { public: static MacroSupplyManager* create(); static void destroy(); void update(); int lastFrameCheck; int initialSupplyTotal; int initialSupplyProviderCount; private: MacroSupplyManager(); ~MacroSupplyManager(); }; extern MacroSupplyManager* TheMacroSupplyManager;
c3f31821e15b08d46f6e86b6d01868c3fb114d02
2b9cc67d4bbb5257b4c64bf6437bf7c589300c06
/scripts/NuisanceChecks/AutoDict_binary_function_TString_TString_bool_.cxx
8b9b688dc17be4a4d24fd0070b0e23bb186c3bf2
[]
no_license
gerbaudo/hlfv-fitmodel
81bfe391a4a19af5268fa056319dc552f6b9e1cf
17a44604fa860382f72e27a5ee5c1432677e40cd
refs/heads/master
2020-06-07T09:34:42.487189
2015-05-25T09:44:23
2015-05-25T09:44:23
35,870,053
1
0
null
2015-05-25T09:05:46
2015-05-19T08:43:13
C
UTF-8
C++
false
false
275
cxx
#include "map" #include "TString.h" #include "TString.h" #ifdef __CINT__ #pragma link C++ nestedclasses; #pragma link C++ nestedtypedefs; #pragma link C++ class binary_function<TString,TString,bool>+; #pragma link C++ class binary_function<TString,TString,bool>::*+; #endif
[ "avitald@883ba7d9-fdd0-4202-9341-49aa55999ad8" ]
avitald@883ba7d9-fdd0-4202-9341-49aa55999ad8
9f30de5b08b44027dc3b197a5a0d3a685aebc4c0
fb57dc0efeab3e51e6c59c8d58c654ac253c3ba9
/Sharing/Src/Source/Common/Private/json/json_parsing.cpp
a47f3378e2a6f0cb628b8d34bffae5eddd693588
[ "MIT" ]
permissive
microsoft/MixedRealityToolkit
aa7eddbeb36cbb5894beea32e2ff91cef29afcdf
8454abcce504effd83c9d6e20725f6037c11e2b4
refs/heads/main
2023-07-08T11:15:38.879033
2023-06-28T19:21:12
2023-06-28T19:21:12
46,008,487
251
61
MIT
2023-06-28T19:21:13
2015-11-11T20:37:59
C++
UTF-8
C++
false
false
31,445
cpp
/*** * ==++== * * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * ==--== * =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ * * json_parsing.cpp * * HTTP Library: JSON parser and writer * * For the latest on this and related APIs, please see http://casablanca.codeplex.com. * * =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- ****/ #include "stdafx.h" #include "./cpprest/json.h" #include <vector> #pragma warning(disable : 4127) // allow expressions like while(true) pass using namespace web; using namespace web::json; using namespace utility; using namespace utility::conversions; int _hexval [] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }; namespace web { namespace json { namespace details { // // JSON Parsing // template <typename Token> #ifdef _MS_WINDOWS __declspec(noreturn) #else __attribute__((noreturn)) #endif void CreateError(const Token &tk, const utility::string_t &message) { utility::ostringstream_t os; os << _XPLATSTR("* Line ") << tk.start.m_line << _XPLATSTR(", Column ") << tk.start.m_column << _XPLATSTR(" Syntax error: ") << message; throw web::json::json_exception(os.str().c_str()); } template <typename CharType> class JSON_Parser { public: JSON_Parser() : m_currentLine(1), m_eof(std::char_traits<CharType>::eof()), m_currentColumn(1), m_currentParsingDepth(0) { } struct Location { size_t m_line; size_t m_column; }; struct Token { enum Kind { TKN_EOF, TKN_OpenBrace, TKN_CloseBrace, TKN_OpenBracket, TKN_CloseBracket, TKN_Comma, TKN_Colon, TKN_StringLiteral, TKN_NumberLiteral, TKN_IntegerLiteral, TKN_BooleanLiteral, TKN_NullLiteral, TKN_Comment }; Token() : kind(TKN_EOF) {} Kind kind; std::basic_string<CharType> string_val; typename JSON_Parser<CharType>::Location start; union { double double_val; int64_t int64_val; uint64_t uint64_val; bool boolean_val; bool has_unescape_symbol; }; bool signed_number; }; void GetNextToken(Token &); web::json::value ParseValue(typename JSON_Parser<CharType>::Token &first) { auto _value = _ParseValue(first); #ifdef ENABLE_JSON_VALUE_VISUALIZER auto type = _value->type(); #endif return web::json::value(std::move(_value) #ifdef ENABLE_JSON_VALUE_VISUALIZER ,type #endif ); } protected: virtual CharType NextCharacter() = 0; virtual CharType PeekCharacter() = 0; virtual bool CompleteComment(Token &token); virtual bool CompleteStringLiteral(Token &token); bool handle_unescape_char(Token &token); private: bool CompleteNumberLiteral(CharType first, Token &token); bool ParseInt64(CharType first, uint64_t& value); bool CompleteKeywordTrue(Token &token); bool CompleteKeywordFalse(Token &token); bool CompleteKeywordNull(Token &token); std::unique_ptr<web::json::details::_Value> _ParseValue(typename JSON_Parser<CharType>::Token &first); std::unique_ptr<web::json::details::_Object> _ParseObject(typename JSON_Parser<CharType>::Token &tkn); std::unique_ptr<web::json::details::_Array> _ParseArray(typename JSON_Parser<CharType>::Token &tkn); JSON_Parser& operator=(const JSON_Parser&); CharType EatWhitespace(); void CreateToken(typename JSON_Parser<CharType>::Token& tk, typename Token::Kind kind, Location &start) { tk.kind = kind; tk.start = start; tk.string_val.clear(); } void CreateToken(typename JSON_Parser<CharType>::Token& tk, typename Token::Kind kind) { tk.kind = kind; tk.start.m_line = m_currentLine; tk.start.m_column = m_currentColumn; tk.string_val.clear(); } protected: size_t m_currentLine; size_t m_currentColumn; size_t m_currentParsingDepth; #ifndef __APPLE__ static const size_t maxParsingDepth = 128; #else static const size_t maxParsingDepth = 32; #endif const typename std::char_traits<CharType>::int_type m_eof; }; template <typename CharType> class JSON_StreamParser : public JSON_Parser<CharType> { public: JSON_StreamParser(std::basic_istream<CharType> &stream) : m_streambuf(stream.rdbuf()) { } protected: virtual CharType NextCharacter(); virtual CharType PeekCharacter(); private: typename std::basic_streambuf<CharType, std::char_traits<CharType>>* m_streambuf; }; template <typename CharType> class JSON_StringParser : public JSON_Parser<CharType> { public: JSON_StringParser(const std::basic_string<CharType>& string) : m_position(&string[0]) { m_startpos = m_position; m_endpos = m_position+string.size(); } protected: virtual CharType NextCharacter(); virtual CharType PeekCharacter(); virtual bool CompleteComment(typename JSON_Parser<CharType>::Token &token); virtual bool CompleteStringLiteral(typename JSON_Parser<CharType>::Token &token); private: bool finish_parsing_string_with_unescape_char(typename JSON_Parser<CharType>::Token &token); const CharType* m_position; const CharType* m_startpos; const CharType* m_endpos; }; template <typename CharType> CharType JSON_StreamParser<CharType>::NextCharacter() { CharType ch = (CharType) m_streambuf->sbumpc(); if (ch == '\n') { this->m_currentLine += 1; this->m_currentColumn = 0; } else { this->m_currentColumn += 1; } return (CharType)ch; } template <typename CharType> CharType JSON_StreamParser<CharType>::PeekCharacter() { return (CharType)m_streambuf->sgetc(); } template <typename CharType> CharType JSON_StringParser<CharType>::NextCharacter() { if (m_position == m_endpos) return (CharType)this->m_eof; CharType ch = *m_position; m_position += 1; if ( ch == '\n' ) { this->m_currentLine += 1; this->m_currentColumn = 0; } else { this->m_currentColumn += 1; } return (CharType)ch; } template <typename CharType> CharType JSON_StringParser<CharType>::PeekCharacter() { if ( m_position == m_endpos ) return (CharType)this->m_eof; return (CharType)*m_position; } // // Consume whitespace characters and return the first non-space character or EOF // template <typename CharType> CharType JSON_Parser<CharType>::EatWhitespace() { CharType ch = NextCharacter(); while ( ch != this->m_eof && iswspace((int)ch) ) { ch = NextCharacter(); } return ch; } template <typename CharType> bool JSON_Parser<CharType>::CompleteKeywordTrue(Token &token) { if (NextCharacter() != 'r') return false; if (NextCharacter() != 'u') return false; if (NextCharacter() != 'e') return false; token.kind = Token::TKN_BooleanLiteral; token.boolean_val = true; return true; } template <typename CharType> bool JSON_Parser<CharType>::CompleteKeywordFalse(Token &token) { if (NextCharacter() != 'a') return false; if (NextCharacter() != 'l') return false; if (NextCharacter() != 's') return false; if (NextCharacter() != 'e') return false; token.kind = Token::TKN_BooleanLiteral; token.boolean_val = false; return true; } template <typename CharType> bool JSON_Parser<CharType>::CompleteKeywordNull(Token &token) { if (NextCharacter() != 'u') return false; if (NextCharacter() != 'l') return false; if (NextCharacter() != 'l') return false; token.kind = Token::TKN_NullLiteral; return true; } // Returns false only on overflow template <typename CharType> inline bool JSON_Parser<CharType>::ParseInt64(CharType first, uint64_t& value) { value = first - '0'; CharType ch = PeekCharacter(); while (ch >= '0' && ch <= '9') { int next_digit = ch - '0'; if (value > (ULLONG_MAX / 10) || (value == ULLONG_MAX/10 && next_digit > ULLONG_MAX%10)) return false; NextCharacter(); value *= 10; value += next_digit; ch = PeekCharacter(); } return true; } // This namespace hides the x-plat helper functions namespace { #ifdef _MS_WINDOWS static int print_llu(char* ptr, size_t n, uint64_t val64) { return _snprintf_s(ptr, n, _TRUNCATE, "%I64u", val64); } static int print_llu(wchar_t* ptr, size_t n, uint64_t val64) { return _snwprintf_s(ptr, n, _TRUNCATE, L"%I64u", val64); } static double anystod(const wchar_t* str) { return wcstod(str, nullptr); } #else static int print_llu(char* ptr, size_t n, unsigned long long val64) { return snprintf(ptr, n, "%llu", val64); } #endif static double anystod(const char* str) { return strtod(str, nullptr); } } template <typename CharType> bool JSON_Parser<CharType>::CompleteNumberLiteral(CharType first, Token &token) { bool minus_sign; if (first == '-') { minus_sign = true; first = NextCharacter(); } else { minus_sign = false; } if (first < '0' || first > '9') return false; CharType ch = PeekCharacter(); //Check for two (or more) zeros at the begining if (first == '0' && ch == '0') return false; // Parse the number assuming its integer uint64_t val64; bool complete = ParseInt64(first, val64); ch = PeekCharacter(); if (complete && ch!='.' && ch!='E' && ch!='e') { if (minus_sign) { if (val64 > static_cast<uint64_t>(1) << 63 ) { // It is negative and cannot be represented in int64, so we resort to double token.double_val = 0 - static_cast<double>(val64); token.signed_number = true; token.kind = JSON_Parser<CharType>::Token::TKN_NumberLiteral; return true; } // It is negative, but fits into int64 token.int64_val = 0 - static_cast<int64_t>(val64); token.kind = JSON_Parser<CharType>::Token::TKN_IntegerLiteral; token.signed_number = true; return true; } // It is positive so we use unsigned int64 token.uint64_val = val64; token.kind = JSON_Parser<CharType>::Token::TKN_IntegerLiteral; token.signed_number = false; return true; } // Magic number 5 leaves room for decimal point, null terminator, etc (in most cases) ::std::vector<CharType> buf(::std::numeric_limits<uint64_t>::digits10 + 5); int count = print_llu(buf.data(), buf.size(), val64); _ASSERTE(count >= 0); _ASSERTE((size_t)count < buf.size()); // Resize to cut off the null terminator buf.resize(count); bool decimal = false; while (ch != this->m_eof) { // Digit encountered? if (ch >= '0' && ch <= '9') { buf.push_back(ch); NextCharacter(); ch = PeekCharacter(); } // Decimal dot? else if (ch == '.') { if (decimal) return false; decimal = true; buf.push_back(ch); NextCharacter(); ch = PeekCharacter(); // Check that the following char is a digit if (ch < '0' || ch > '9') return false; buf.push_back(ch); NextCharacter(); ch = PeekCharacter(); } // Exponent? else if (ch == 'E' || ch == 'e') { buf.push_back(ch); NextCharacter(); ch = PeekCharacter(); // Check for the exponent sign if (ch == '+') { buf.push_back(ch); NextCharacter(); ch = PeekCharacter(); } else if (ch == '-') { buf.push_back(ch); NextCharacter(); ch = PeekCharacter(); } // First number of the exponent if (ch >= '0' && ch <= '9') { buf.push_back(ch); NextCharacter(); ch = PeekCharacter(); } else return false; // The rest of the exponent while (ch >= '0' && ch <= '9') { buf.push_back(ch); NextCharacter(); ch = PeekCharacter(); } // The peeked character is not a number, so we can break from the loop and construct the number break; } else { // Not expected number character? break; } }; buf.push_back('\0'); token.double_val = anystod(buf.data()); if (minus_sign) { token.double_val = -token.double_val; } token.kind = (JSON_Parser<CharType>::Token::TKN_NumberLiteral); return true; } template <typename CharType> bool JSON_Parser<CharType>::CompleteComment(Token &token) { // We already found a '/' character as the first of a token -- what kind of comment is it? CharType ch = NextCharacter(); if ( ch == this->m_eof || (ch != '/' && ch != '*') ) return false; if ( ch == '/' ) { // Line comment -- look for a newline or EOF to terminate. ch = NextCharacter(); while ( ch != this->m_eof && ch != '\n') { ch = NextCharacter(); } } else { // Block comment -- look for a terminating "*/" sequence. ch = NextCharacter(); while ( true ) { if ( ch == this->m_eof ) return false; if ( ch == '*' ) { CharType ch1 = PeekCharacter(); if ( ch1 == this->m_eof ) return false; if ( ch1 == '/' ) { // Consume the character NextCharacter(); break; } ch = ch1; } ch = NextCharacter(); } } token.kind = Token::TKN_Comment; return true; } template <typename CharType> bool JSON_StringParser<CharType>::CompleteComment(typename JSON_Parser<CharType>::Token &token) { // This function is specialized for the string parser, since we can be slightly more // efficient in copying data from the input to the token: do a memcpy() rather than // one character at a time. CharType ch = JSON_StringParser<CharType>::NextCharacter(); if ( ch == this->m_eof || (ch != '/' && ch != '*') ) return false; if ( ch == '/' ) { // Line comment -- look for a newline or EOF to terminate. ch = JSON_StringParser<CharType>::NextCharacter(); while ( ch != this->m_eof && ch != '\n') { ch = JSON_StringParser<CharType>::NextCharacter(); } } else { // Block comment -- look for a terminating "*/" sequence. ch = JSON_StringParser<CharType>::NextCharacter(); while ( true ) { if ( ch == this->m_eof ) return false; if ( ch == '*' ) { ch = JSON_StringParser<CharType>::PeekCharacter(); if ( ch == this->m_eof ) return false; if ( ch == '/' ) { // Consume the character JSON_StringParser<CharType>::NextCharacter(); break; } } ch = JSON_StringParser<CharType>::NextCharacter(); } } token.kind = JSON_Parser<CharType>::Token::TKN_Comment; return true; } template <typename CharType> inline bool JSON_Parser<CharType>::handle_unescape_char(Token &token) { // This function converts unescape character pairs (e.g. "\t") into their ASCII or UNICODE representations (e.g. tab sign) // Also it handles \u + 4 hexadecimal digits CharType ch = NextCharacter(); switch (ch) { case '\"': token.string_val.push_back('\"'); return true; case '\\': token.string_val.push_back('\\'); return true; case '/': token.string_val.push_back('/'); return true; case 'b': token.string_val.push_back('\b'); return true; case 'f': token.string_val.push_back('\f'); return true; case 'r': token.string_val.push_back('\r'); return true; case 'n': token.string_val.push_back('\n'); return true; case 't': token.string_val.push_back('\t'); return true; case 'u': { // A four-hexdigit unicode character int decoded = 0; for (int i = 0; i < 4; ++i) { ch = NextCharacter(); if (!isxdigit((unsigned char) (ch))) return false; int val = _hexval[ch]; _ASSERTE(val != -1); // Add the input char to the decoded number decoded |= (val << (4 * (3 - i))); } // Construct the character based on the decoded number ch = static_cast<CharType>(decoded & 0xFFFF); token.string_val.push_back(ch); return true; } default: return false; } } template <typename CharType> bool JSON_Parser<CharType>::CompleteStringLiteral(Token &token) { CharType ch = NextCharacter(); while ( ch != '"' ) { if ( ch == '\\' ) { handle_unescape_char(token); } else if (ch >= CharType(0x0) && ch < CharType(0x20)) { return false; } else { if (ch == this->m_eof) return false; token.string_val.push_back(ch); } ch = NextCharacter(); } if ( ch == '"' ) { token.kind = Token::TKN_StringLiteral; } else { return false; } return true; } template <typename CharType> bool JSON_StringParser<CharType>::CompleteStringLiteral(typename JSON_Parser<CharType>::Token &token) { // This function is specialized for the string parser, since we can be slightly more // efficient in copying data from the input to the token: do a memcpy() rather than // one character at a time. auto start = m_position; token.has_unescape_symbol = false; CharType ch = JSON_StringParser<CharType>::NextCharacter(); while (ch != '"') { if (ch == this->m_eof) return false; if (ch == '\\') { token.string_val.resize(m_position - start - 1); if (token.string_val.size() > 0) memcpy(&token.string_val[0], start, (m_position - start - 1)*sizeof(CharType)); token.has_unescape_symbol = true; return finish_parsing_string_with_unescape_char(token); } else if (ch >= CharType(0x0) && ch < CharType(0x20)) { return false; } ch = JSON_StringParser<CharType>::NextCharacter(); } token.string_val.resize(m_position - start - 1); if (token.string_val.size() > 0) memcpy(&token.string_val[0], start, (m_position - start - 1)*sizeof(CharType)); token.kind = JSON_Parser<CharType>::Token::TKN_StringLiteral; return true; } template <typename CharType> bool JSON_StringParser<CharType>::finish_parsing_string_with_unescape_char(typename JSON_Parser<CharType>::Token &token) { // This function handles parsing the string when an unescape character is encountered. // It is called once the part before the unescape char is copied to the token.string_val string CharType ch; if (!JSON_StringParser<CharType>::handle_unescape_char(token)) return false; while ((ch = JSON_StringParser<CharType>::NextCharacter()) != '"') { if (ch == '\\') { if (!JSON_StringParser<CharType>::handle_unescape_char(token)) return false; } else { if (ch == this->m_eof) return false; token.string_val.push_back(ch); } } token.kind = JSON_StringParser<CharType>::Token::TKN_StringLiteral; return true; } template <typename CharType> void JSON_Parser<CharType>::GetNextToken(typename JSON_Parser<CharType>::Token& result) { try_again: CharType ch = EatWhitespace(); CreateToken(result, Token::TKN_EOF); if (ch == this->m_eof) return; switch (ch) { case '{': case '[': { if(++m_currentParsingDepth > JSON_Parser<CharType>::maxParsingDepth) { CreateError(result, _XPLATSTR("Nesting too deep!")); break; } typename JSON_Parser<CharType>::Token::Kind tk = ch == '{' ? Token::TKN_OpenBrace : Token::TKN_OpenBracket; CreateToken(result, tk, result.start); break; } case '}': case ']': { if((signed int)(--m_currentParsingDepth) < 0) { CreateError(result, _XPLATSTR("Mismatched braces!")); break; } typename JSON_Parser<CharType>::Token::Kind tk = ch == '}' ? Token::TKN_CloseBrace : Token::TKN_CloseBracket; CreateToken(result, tk, result.start); break; } case ',': CreateToken(result, Token::TKN_Comma, result.start); break; case ':': CreateToken(result, Token::TKN_Colon, result.start); break; case 't': if (!CompleteKeywordTrue(result)) CreateError(result, _XPLATSTR("Malformed literal")); break; case 'f': if (!CompleteKeywordFalse(result)) CreateError(result, _XPLATSTR("Malformed literal")); break; case 'n': if (!CompleteKeywordNull(result)) CreateError(result, _XPLATSTR("Malformed literal")); break; case '/': if ( !CompleteComment(result) ) CreateError(result, _XPLATSTR("Malformed comment")); // For now, we're ignoring comments. goto try_again; case '"': if ( !CompleteStringLiteral(result) ) CreateError(result, _XPLATSTR("Malformed string literal")); break; case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if ( !CompleteNumberLiteral(ch, result) ) CreateError(result, _XPLATSTR("Malformed numeric literal")); break; default: CreateError(result, _XPLATSTR("Malformed token")); break; } } template <typename CharType> std::unique_ptr<web::json::details::_Object> JSON_Parser<CharType>::_ParseObject(typename JSON_Parser<CharType>::Token &tkn) { GetNextToken(tkn); auto obj = utility::details::make_unique<web::json::details::_Object>(g_keep_json_object_unsorted); auto& elems = obj->m_object.m_elements; if ( tkn.kind != JSON_Parser<CharType>::Token::TKN_CloseBrace ) { while ( true ) { // State 1: New field or end of object, looking for field name or closing brace std::basic_string<CharType> fieldName; switch ( tkn.kind ) { case JSON_Parser<CharType>::Token::TKN_StringLiteral: fieldName = std::move(tkn.string_val); break; default: goto error; } GetNextToken(tkn); // State 2: Looking for a colon. if ( tkn.kind != JSON_Parser<CharType>::Token::TKN_Colon ) goto done; GetNextToken(tkn); // State 3: Looking for an expression. #ifdef ENABLE_JSON_VALUE_VISUALIZER auto fieldValue = _ParseValue(tkn); auto type = fieldValue->type(); elems.emplace_back(utility::conversions::to_string_t(std::move(fieldName)), json::value(std::move(fieldValue), type)); #else elems.emplace_back(utility::conversions::to_string_t(std::move(fieldName)), json::value(_ParseValue(tkn))); #endif // State 4: Looking for a comma or a closing brace switch (tkn.kind) { case JSON_Parser<CharType>::Token::TKN_Comma: GetNextToken(tkn); break; case JSON_Parser<CharType>::Token::TKN_CloseBrace: goto done; default: goto error; } } } done: GetNextToken(tkn); if (!g_keep_json_object_unsorted) { ::std::sort(elems.begin(), elems.end(), json::object::compare_pairs); } return obj; error: CreateError(tkn, _XPLATSTR("Malformed object literal")); } template <typename CharType> std::unique_ptr<web::json::details::_Array> JSON_Parser<CharType>::_ParseArray(typename JSON_Parser<CharType>::Token &tkn) { GetNextToken(tkn); auto result = utility::details::make_unique<web::json::details::_Array>(); if ( tkn.kind != JSON_Parser<CharType>::Token::TKN_CloseBracket ) { while ( true ) { // State 1: Looking for an expression. result->m_array.m_elements.emplace_back(ParseValue(tkn)); // State 4: Looking for a comma or a closing bracket switch (tkn.kind) { case JSON_Parser<CharType>::Token::TKN_Comma: GetNextToken(tkn); break; case JSON_Parser<CharType>::Token::TKN_CloseBracket: GetNextToken(tkn); return result; default: CreateError(tkn, _XPLATSTR("Malformed array literal")); } } } GetNextToken(tkn); return result; } template <typename CharType> std::unique_ptr<web::json::details::_Value> JSON_Parser<CharType>::_ParseValue(typename JSON_Parser<CharType>::Token &tkn) { switch (tkn.kind) { case JSON_Parser<CharType>::Token::TKN_OpenBrace: return _ParseObject(tkn); case JSON_Parser<CharType>::Token::TKN_OpenBracket: return _ParseArray(tkn); case JSON_Parser<CharType>::Token::TKN_StringLiteral: { auto value = utility::details::make_unique<web::json::details::_String>(std::move(tkn.string_val), tkn.has_unescape_symbol); GetNextToken(tkn); return std::move(value); } case JSON_Parser<CharType>::Token::TKN_IntegerLiteral: { std::unique_ptr<web::json::details::_Number> value; if (tkn.signed_number) value = utility::details::make_unique<web::json::details::_Number>(tkn.int64_val); else value = utility::details::make_unique<web::json::details::_Number>(tkn.uint64_val); GetNextToken(tkn); return std::move(value); } case JSON_Parser<CharType>::Token::TKN_NumberLiteral: { auto value = utility::details::make_unique<web::json::details::_Number>(tkn.double_val); GetNextToken(tkn); return std::move(value); } case JSON_Parser<CharType>::Token::TKN_BooleanLiteral: { auto value = utility::details::make_unique<web::json::details::_Boolean>(tkn.boolean_val); GetNextToken(tkn); return std::move(value); } case JSON_Parser<CharType>::Token::TKN_NullLiteral: { GetNextToken(tkn); return utility::details::make_unique<web::json::details::_Null>(); } default: CreateError(tkn, _XPLATSTR("Unexpected token")); } } }}} static web::json::value _parse_stream(utility::istream_t &stream) { web::json::details::JSON_StreamParser<utility::char_t> parser(stream); web::json::details::JSON_Parser<utility::char_t>::Token tkn; parser.GetNextToken(tkn); auto value = parser.ParseValue(tkn); if ( tkn.kind != web::json::details::JSON_Parser<utility::char_t>::Token::TKN_EOF ) { web::json::details::CreateError(tkn, _XPLATSTR("Left-over characters in stream after parsing a JSON value")); } return value; } #ifdef _MS_WINDOWS static web::json::value _parse_narrow_stream(std::istream &stream) { web::json::details::JSON_StreamParser<char> parser(stream); web::json::details::JSON_StreamParser<char>::Token tkn; parser.GetNextToken(tkn); auto value = parser.ParseValue(tkn); if ( tkn.kind != web::json::details::JSON_Parser<char>::Token::TKN_EOF ) { web::json::details::CreateError(tkn, _XPLATSTR("Left-over characters in stream after parsing a JSON value")); } return value; } #endif web::json::value web::json::value::parse(const utility::string_t& str) { web::json::details::JSON_StringParser<utility::char_t> parser(str); web::json::details::JSON_Parser<utility::char_t>::Token tkn; parser.GetNextToken(tkn); auto value = parser.ParseValue(tkn); if (tkn.kind != web::json::details::JSON_Parser<utility::char_t>::Token::TKN_EOF) { web::json::details::CreateError(tkn, _XPLATSTR("Left-over characters in stream after parsing a JSON value")); } return value; } web::json::value web::json::value::parse(utility::istream_t &stream) { return _parse_stream(stream); } #ifdef _MS_WINDOWS web::json::value web::json::value::parse(std::istream& stream) { return _parse_narrow_stream(stream); } #endif
e5031dbebf3a2c7f67a0e11f0cdb81242aafd0c2
7e5be101928eb7ea43bc1a335d3475536f8a5bb2
/2016 Training/7.24/E.cpp
93b0907a0e3a12e39f6cf75f5d0d0d4a4a2ef55b
[]
no_license
TaoSama/ICPC-Code-Library
f94d4df0786a8a1c175da02de0a3033f9bd103ec
ec80ec66a94a5ea1d560c54fe08be0ecfcfc025e
refs/heads/master
2020-04-04T06:19:21.023777
2018-11-05T18:22:32
2018-11-05T18:22:32
54,618,194
0
2
null
null
null
null
UTF-8
C++
false
false
2,005
cpp
// // Created by TaoSama on 2016-07-24 // Copyright (c) 2016 TaoSama. All rights reserved. // #pragma comment(linker, "/STACK:102400000,102400000") #include <algorithm> #include <cctype> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <string> #include <set> #include <vector> using namespace std; #define pr(x) cout << #x << " = " << x << " " #define prln(x) cout << #x << " = " << x << endl const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7; int n, a[N], b[N]; void solve(vector<int>& ans, bool rev) { map<int, int> mp; int sum = 0; for(int i = 1; i <= n; ++i) { sum += a[i] - b[i + rev]; ++mp[sum]; } int last = 0; for(auto& p : mp) { int tmp = p.second; p.second += last; last = tmp; } int delta = 0; for(int i = 1; i <= n; ++i) { auto iter = mp.lower_bound(delta); if(iter == mp.begin()) ans.push_back(rev ? n - i + 1 : i); delta += a[i] - b[i + rev]; } } int main() { #ifdef LOCAL freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin); // freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout); #endif ios_base::sync_with_stdio(0); clock_t _ = clock(); while(scanf("%d", &n) == 1) { for(int i = 1; i <= n; ++i) scanf("%d", a + i); for(int i = 1; i <= n; ++i) scanf("%d", b + i); vector<int> ans; solve(ans, 0); reverse(a + 1, a + 1 + n); reverse(b + 1, b + 1 + n); b[n + 1] = b[1]; solve(ans, 1); sort(ans.begin(), ans.end()); ans.resize(unique(ans.begin(), ans.end()) - ans.begin()); printf("%d\n", ans.size()); for(int i = 0; i < ans.size(); ++i) printf("%d%c", ans[i], " \n"[i == ans.size() - 1]); } #ifdef LOCAL printf("\nTime cost: %.2fs\n", 1.0 * (clock() - _) / CLOCKS_PER_SEC); #endif return 0; }
8bbf23fb186358ddf914798a6f42624299e68764
5821d864fb40417184cd37a3ee3c889895d39efb
/manuscript/img-src/lscm/OpenNL_psm.cpp
cf85b3614f3e3d8ca19c2b7de0b4a1a7f7dd554f
[ "WTFPL" ]
permissive
ssloy/least-squares-course
9c86d8c54894248440fba78206ce253559f4257b
13692cdfd40a8005893fd33887d6cc743c5f01ec
refs/heads/master
2022-08-18T15:53:15.313071
2021-12-01T12:44:59
2021-12-01T12:44:59
222,901,933
162
18
WTFPL
2022-07-28T21:16:03
2019-11-20T09:38:37
TeX
UTF-8
C++
false
false
217,065
cpp
#include "OpenNL_psm.h" /* * Copyright (c) 2004-2010, Bruno Levy * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ALICE Project-Team nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * If you modify this software, you should include a notice giving the * name of the person performing the modification, the date of modification, * and the reason for such modification. * * Contact: Bruno Levy * * [email protected] * * ALICE Project * LORIA, INRIA Lorraine, * Campus Scientifique, BP 239 * 54506 VANDOEUVRE LES NANCY CEDEX * FRANCE * */ /* * This file is a PSM (pluggable software module) * generated from the distribution of Geogram. * * See Geogram documentation on: * http://alice.loria.fr/software/geogram/doc/html/index.html * * See documentation of the functions bundled in this PSM on: * http://alice.loria.fr/software/geogram/doc/html/nl_8h.html */ /******* extracted from nl_private.h *******/ #ifndef OPENNL_PRIVATE_H #define OPENNL_PRIVATE_H #include <stdlib.h> #include <string.h> #include <stdio.h> #include <math.h> #if defined(__APPLE__) && defined(__MACH__) #define NL_OS_APPLE #endif #if defined(__linux__) || defined(__ANDROID__) || defined(NL_OS_APPLE) #define NL_OS_UNIX #endif #if defined(WIN32) || defined(_WIN64) #define NL_OS_WINDOWS #endif #define nl_arg_used(x) (void)x #if defined(__clang__) || defined(__GNUC__) #define NL_NORETURN __attribute__((noreturn)) #else #define NL_NORETURN #endif #if defined(_MSC_VER) #define NL_NORETURN_DECL __declspec(noreturn) #else #define NL_NORETURN_DECL #endif NL_NORETURN_DECL void nl_assertion_failed( const char* cond, const char* file, int line ) NL_NORETURN; NL_NORETURN_DECL void nl_range_assertion_failed( double x, double min_val, double max_val, const char* file, int line ) NL_NORETURN; NL_NORETURN_DECL void nl_should_not_have_reached( const char* file, int line ) NL_NORETURN; #define nl_assert(x) { \ if(!(x)) { \ nl_assertion_failed(#x,__FILE__, __LINE__) ; \ } \ } #define nl_range_assert(x,min_val,max_val) { \ if(((x) < (min_val)) || ((x) > (max_val))) { \ nl_range_assertion_failed(x, min_val, max_val, \ __FILE__, __LINE__ \ ) ; \ } \ } #define nl_assert_not_reached { \ nl_should_not_have_reached(__FILE__, __LINE__) ; \ } #ifdef NL_DEBUG #define nl_debug_assert(x) nl_assert(x) #define nl_debug_range_assert(x,min_val,max_val) \ nl_range_assert(x,min_val,max_val) #else #define nl_debug_assert(x) #define nl_debug_range_assert(x,min_val,max_val) #endif #ifdef NL_PARANOID #define nl_parano_assert(x) nl_assert(x) #define nl_parano_range_assert(x,min_val,max_val) \ nl_range_assert(x,min_val,max_val) #else #define nl_parano_assert(x) #define nl_parano_range_assert(x,min_val,max_val) #endif void nlError(const char* function, const char* message) ; void nlWarning(const char* function, const char* message) ; NLdouble nlCurrentTime(void); typedef void* NLdll; #define NL_LINK_NOW 1 #define NL_LINK_LAZY 2 #define NL_LINK_GLOBAL 4 #define NL_LINK_QUIET 8 #define NL_LINK_USE_FALLBACK 16 NLdll nlOpenDLL(const char* filename, NLenum flags); void nlCloseDLL(NLdll handle); NLfunc nlFindFunction(NLdll handle, const char* funcname); /* classic macros */ #ifndef MIN #define MIN(x,y) (((x) < (y)) ? (x) : (y)) #endif #ifndef MAX #define MAX(x,y) (((x) > (y)) ? (x) : (y)) #endif #define NL_NEW(T) (T*)(calloc(1, sizeof(T))) #define NL_NEW_ARRAY(T,NB) (T*)(calloc((size_t)(NB),sizeof(T))) #define NL_RENEW_ARRAY(T,x,NB) (T*)(realloc(x,(size_t)(NB)*sizeof(T))) #define NL_DELETE(x) free(x); x = NULL #define NL_DELETE_ARRAY(x) free(x); x = NULL #define NL_CLEAR(T, x) memset(x, 0, sizeof(T)) #define NL_CLEAR_ARRAY(T,x,NB) memset(x, 0, (size_t)(NB)*sizeof(T)) #define NL_UINT_MAX 0xffffffff #define NL_USHORT_MAX 0xffff extern NLprintfFunc nl_printf; extern NLfprintfFunc nl_fprintf; #endif /******* extracted from nl_blas.h *******/ #ifndef OPENNL_BLAS_H #define OPENNL_BLAS_H struct NLBlas; typedef struct NLBlas* NLBlas_t; typedef enum { NoTranspose=0, Transpose=1, ConjugateTranspose=2 } MatrixTranspose ; typedef enum { UpperTriangle=0, LowerTriangle=1 } MatrixTriangle ; typedef enum { UnitTriangular=0, NotUnitTriangular=1 } MatrixUnitTriangular ; typedef enum { NL_HOST_MEMORY, NL_DEVICE_MEMORY } NLmemoryType; typedef void* (*FUNPTR_malloc)( NLBlas_t blas, NLmemoryType type, size_t size ); typedef void (*FUNPTR_free)( NLBlas_t blas, NLmemoryType type, size_t size, void* ptr ); typedef void (*FUNPTR_memcpy)( NLBlas_t blas, void* to, NLmemoryType to_type, void* from, NLmemoryType from_type, size_t size ); typedef void (*FUNPTR_dcopy)( NLBlas_t blas, int n, const double *x, int incx, double *y, int incy ); typedef void (*FUNPTR_dscal)( NLBlas_t blas, int n, double a, double *x, int incx ); typedef double (*FUNPTR_ddot)( NLBlas_t blas, int n, const double *x, int incx, const double *y, int incy ); typedef double (*FUNPTR_dnrm2)(NLBlas_t blas, int n, const double *x, int incx); typedef void (*FUNPTR_daxpy)( NLBlas_t blas, int n, double a, const double *x, int incx, double *y, int incy ); typedef void (*FUNPTR_dgemv)( NLBlas_t blas, MatrixTranspose trans, int m, int n, double alpha, const double *A, int ldA, const double *x, int incx, double beta, double *y, int incy ); typedef void (*FUNPTR_dtpsv)( NLBlas_t blas, MatrixTriangle uplo, MatrixTranspose trans, MatrixUnitTriangular diag, int n, const double *AP, double *x, int incx ); struct NLBlas { FUNPTR_malloc Malloc; FUNPTR_free Free; FUNPTR_memcpy Memcpy; FUNPTR_dcopy Dcopy; FUNPTR_dscal Dscal; FUNPTR_ddot Ddot; FUNPTR_dnrm2 Dnrm2; FUNPTR_daxpy Daxpy; FUNPTR_dgemv Dgemv; FUNPTR_dtpsv Dtpsv; NLboolean has_unified_memory; double start_time; NLulong flops; NLulong used_ram[2]; NLulong max_used_ram[2]; /* * Used for stats of the linear solver * (a bit ugly, should not be here, but * more convenient for now...) */ double sq_rnorm; double sq_bnorm; }; NLboolean nlBlasHasUnifiedMemory(NLBlas_t blas); void nlBlasResetStats(NLBlas_t blas); double nlBlasGFlops(NLBlas_t blas); NLulong nlBlasUsedRam(NLBlas_t blas, NLmemoryType type); NLulong nlBlasMaxUsedRam(NLBlas_t blas, NLmemoryType type); NLBlas_t nlHostBlas(void); #define NL_NEW_VECTOR(blas, memtype, dim) \ (double*)blas->Malloc(blas,memtype,(size_t)(dim)*sizeof(double)) #define NL_DELETE_VECTOR(blas, memtype, dim, ptr) \ blas->Free(blas,memtype,(size_t)(dim)*sizeof(double),ptr) #endif /******* extracted from nl_matrix.h *******/ #ifndef OPENNL_MATRIX_H #define OPENNL_MATRIX_H #ifdef __cplusplus extern "C" { #endif /* Abstract matrix interface */ struct NLMatrixStruct; typedef struct NLMatrixStruct* NLMatrix; typedef void(*NLDestroyMatrixFunc)(NLMatrix M); typedef void(*NLMultMatrixVectorFunc)(NLMatrix M, const double* x, double* y); #define NL_MATRIX_SPARSE_DYNAMIC 0x1001 #define NL_MATRIX_CRS 0x1002 #define NL_MATRIX_SUPERLU_EXT 0x1003 #define NL_MATRIX_CHOLMOD_EXT 0x1004 #define NL_MATRIX_FUNCTION 0x1005 #define NL_MATRIX_OTHER 0x1006 struct NLMatrixStruct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; }; NLAPI void NLAPIENTRY nlDeleteMatrix(NLMatrix M); NLAPI void NLAPIENTRY nlMultMatrixVector( NLMatrix M, const double* x, double* y ); /* Dynamic arrays for sparse row/columns */ typedef struct { NLuint index; NLdouble value; } NLCoeff; typedef struct { NLuint size; NLuint capacity; NLCoeff* coeff; } NLRowColumn; NLAPI void NLAPIENTRY nlRowColumnConstruct(NLRowColumn* c); NLAPI void NLAPIENTRY nlRowColumnDestroy(NLRowColumn* c); NLAPI void NLAPIENTRY nlRowColumnGrow(NLRowColumn* c); NLAPI void NLAPIENTRY nlRowColumnAdd( NLRowColumn* c, NLuint index, NLdouble value ); NLAPI void NLAPIENTRY nlRowColumnAppend( NLRowColumn* c, NLuint index, NLdouble value ); NLAPI void NLAPIENTRY nlRowColumnZero(NLRowColumn* c); NLAPI void NLAPIENTRY nlRowColumnClear(NLRowColumn* c); NLAPI void NLAPIENTRY nlRowColumnSort(NLRowColumn* c); /* Compressed Row Storage */ typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; NLdouble* val; NLuint* rowptr; NLuint* colind; NLuint nslices; NLuint* sliceptr; NLboolean symmetric_storage; } NLCRSMatrix; NLAPI void NLAPIENTRY nlCRSMatrixConstruct( NLCRSMatrix* M, NLuint m, NLuint n, NLuint nnz, NLuint nslices ); NLAPI void NLAPIENTRY nlCRSMatrixConstructSymmetric( NLCRSMatrix* M, NLuint n, NLuint nnz ); NLAPI NLboolean NLAPIENTRY nlCRSMatrixLoad( NLCRSMatrix* M, const char* filename ); NLAPI NLboolean NLAPIENTRY nlCRSMatrixSave( NLCRSMatrix* M, const char* filename ); NLAPI NLuint NLAPIENTRY nlCRSMatrixNNZ(NLCRSMatrix* M); /* SparseMatrix data structure */ #define NL_MATRIX_STORE_ROWS 1 #define NL_MATRIX_STORE_COLUMNS 2 #define NL_MATRIX_STORE_SYMMETRIC 4 typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; NLuint diag_size; NLuint diag_capacity; NLenum storage; NLRowColumn* row; NLRowColumn* column; NLdouble* diag; NLuint row_capacity; NLuint column_capacity; } NLSparseMatrix; NLAPI NLMatrix NLAPIENTRY nlSparseMatrixNew( NLuint m, NLuint n, NLenum storage ); NLAPI void NLAPIENTRY nlSparseMatrixConstruct( NLSparseMatrix* M, NLuint m, NLuint n, NLenum storage ); NLAPI void NLAPIENTRY nlSparseMatrixDestroy(NLSparseMatrix* M); NLAPI void NLAPIENTRY nlSparseMatrixMult( NLSparseMatrix* A, const NLdouble* x, NLdouble* y ); NLAPI void NLAPIENTRY nlSparseMatrixAdd( NLSparseMatrix* M, NLuint i, NLuint j, NLdouble value ); NLAPI void NLAPIENTRY nlSparseMatrixAddMatrix( NLSparseMatrix* M, double mul, const NLMatrix N ); NLAPI void NLAPIENTRY nlSparseMatrixZero( NLSparseMatrix* M); NLAPI void NLAPIENTRY nlSparseMatrixClear( NLSparseMatrix* M); NLAPI NLuint NLAPIENTRY nlSparseMatrixNNZ( NLSparseMatrix* M); NLAPI void NLAPIENTRY nlSparseMatrixSort( NLSparseMatrix* M); NLAPI void NLAPIENTRY nlSparseMatrixAddRow( NLSparseMatrix* M); NLAPI void NLAPIENTRY nlSparseMatrixAddColumn( NLSparseMatrix* M); NLAPI void NLAPIENTRY nlSparseMatrixMAddRow( NLSparseMatrix* M, NLuint i1, double s, NLuint i2 ); NLAPI void NLAPIENTRY nlSparseMatrixScaleRow( NLSparseMatrix* M, NLuint i, double s ); NLAPI void NLAPIENTRY nlSparseMatrixZeroRow( NLSparseMatrix* M, NLuint i ); NLAPI NLMatrix NLAPIENTRY nlCRSMatrixNewFromSparseMatrix(NLSparseMatrix* M); NLAPI NLMatrix NLAPIENTRY nlCRSMatrixNewFromSparseMatrixSymmetric( NLSparseMatrix* M ); NLAPI void NLAPIENTRY nlMatrixCompress(NLMatrix* M); NLAPI NLuint NLAPIENTRY nlMatrixNNZ(NLMatrix M); NLAPI NLMatrix NLAPIENTRY nlMatrixFactorize(NLMatrix M, NLenum solver); typedef void(*NLMatrixFunc)(const double* x, double* y); NLAPI NLMatrix NLAPIENTRY nlMatrixNewFromFunction( NLuint m, NLuint n, NLMatrixFunc func ); NLAPI NLMatrixFunc NLAPIENTRY nlMatrixGetFunction(NLMatrix M); NLAPI NLMatrix NLAPIENTRY nlMatrixNewFromProduct( NLMatrix M, NLboolean product_owns_M, NLMatrix N, NLboolean product_owns_N ); #ifdef __cplusplus } #endif #endif /******* extracted from nl_context.h *******/ #ifndef OPENNL_CONTEXT_H #define OPENNL_CONTEXT_H /* NLContext data structure */ typedef NLboolean(*NLSolverFunc)(void); typedef void(*NLProgressFunc)( NLuint cur_iter, NLuint max_iter, double cur_err, double max_err ); #define NL_STATE_INITIAL 0 #define NL_STATE_SYSTEM 1 #define NL_STATE_MATRIX 2 #define NL_STATE_ROW 3 #define NL_STATE_MATRIX_CONSTRUCTED 4 #define NL_STATE_SYSTEM_CONSTRUCTED 5 #define NL_STATE_SOLVED 6 typedef struct { void* base_address; NLuint stride; } NLBufferBinding; #define NL_BUFFER_ITEM(B,i) \ *(double*)((void*)((char*)((B).base_address)+((i)*(B).stride))) typedef struct { NLenum state; NLboolean user_variable_buffers; NLBufferBinding* variable_buffer; NLdouble* variable_value; NLboolean* variable_is_locked; NLuint* variable_index; NLuint n; NLenum matrix_mode; NLMatrix M; NLMatrix P; NLMatrix B; NLRowColumn af; NLRowColumn al; NLdouble* x; NLdouble* b; NLdouble* right_hand_side; NLdouble row_scaling; NLenum solver; NLenum preconditioner; NLboolean preconditioner_defined; NLuint nb_variables; NLuint nb_systems; NLboolean ij_coefficient_called; NLuint current_row; NLboolean least_squares; NLboolean symmetric; NLuint max_iterations; NLboolean max_iterations_defined; NLuint inner_iterations; NLdouble threshold; NLboolean threshold_defined; NLdouble omega; NLboolean normalize_rows; NLuint used_iterations; NLdouble error; NLdouble start_time; NLdouble elapsed_time; NLSolverFunc solver_func; NLProgressFunc progress_func; NLboolean verbose; NLulong flops; NLenum eigen_solver; NLdouble eigen_shift; NLboolean eigen_shift_invert; NLdouble* eigen_value; NLdouble* temp_eigen_value; } NLContextStruct; extern NLContextStruct* nlCurrentContext; void nlCheckState(NLenum state); void nlTransition(NLenum from_state, NLenum to_state); NLboolean nlDefaultSolver(void); #endif /******* extracted from nl_iterative_solvers.h *******/ #ifndef OPENNL_ITERATIVE_SOLVERS_H #define OPENNL_ITERATIVE_SOLVERS_H NLAPI NLuint NLAPIENTRY nlSolveSystemIterative( NLBlas_t blas, NLMatrix M, NLMatrix P, NLdouble* b, NLdouble* x, NLenum solver, double eps, NLuint max_iter, NLuint inner_iter ); #endif /******* extracted from nl_preconditioners.h *******/ #ifndef OPENNL_PRECONDITIONERS_H #define OPENNL_PRECONDITIONERS_H /* preconditioners */ NLMatrix nlNewJacobiPreconditioner(NLMatrix M); NLMatrix nlNewSSORPreconditioner(NLMatrix M, double omega); #endif /******* extracted from nl_superlu.h *******/ #ifndef OPENNL_SUPERLU_H #define OPENNL_SUPERLU_H NLAPI NLMatrix NLAPIENTRY nlMatrixFactorize_SUPERLU( NLMatrix M, NLenum solver ); NLboolean nlInitExtension_SUPERLU(void); NLboolean nlExtensionIsInitialized_SUPERLU(void); #endif /******* extracted from nl_cholmod.h *******/ #ifndef OPENNL_CHOLMOD_H #define OPENNL_CHOLMOD_H NLAPI NLMatrix NLAPIENTRY nlMatrixFactorize_CHOLMOD( NLMatrix M, NLenum solver ); NLboolean nlInitExtension_CHOLMOD(void); NLboolean nlExtensionIsInitialized_CHOLMOD(void); #endif /******* extracted from nl_arpack.h *******/ #ifndef OPENNL_ARPACK_H #define OPENNL_ARPACK_H NLboolean nlInitExtension_ARPACK(void); NLboolean nlExtensionIsInitialized_ARPACK(void); void nlEigenSolve_ARPACK(void); #endif /******* extracted from nl_mkl.h *******/ #ifndef OPENNL_MKL_H #define OPENNL_MKL_H NLboolean nlInitExtension_MKL(void); NLboolean nlExtensionIsInitialized_MKL(void); extern NLMultMatrixVectorFunc NLMultMatrixVector_MKL; #endif /******* extracted from nl_cuda.h *******/ #ifndef OPENNL_CUDA_EXT_H #define OPENNL_CUDA_EXT_H NLboolean nlInitExtension_CUDA(void); NLboolean nlExtensionIsInitialized_CUDA(void); NLMatrix nlCUDAMatrixNewFromCRSMatrix(NLMatrix M); NLMatrix nlCUDAJacobiPreconditionerNewFromCRSMatrix(NLMatrix M); NLBlas_t nlCUDABlas(void); #endif /******* extracted from nl_os.c *******/ #if (defined (WIN32) || defined(_WIN64)) #include <windows.h> #else #include <sys/types.h> #include <sys/times.h> #endif #if defined(GEO_DYNAMIC_LIBS) && defined(NL_OS_UNIX) #include <dlfcn.h> #endif /* Assertions */ void nl_assertion_failed(const char* cond, const char* file, int line) { nl_fprintf( stderr, "OpenNL assertion failed: %s, file:%s, line:%d\n", cond,file,line ) ; abort() ; } void nl_range_assertion_failed( double x, double min_val, double max_val, const char* file, int line ) { nl_fprintf( stderr, "OpenNL range assertion failed: " "%f in [ %f ... %f ], file:%s, line:%d\n", x, min_val, max_val, file,line ) ; abort() ; } void nl_should_not_have_reached(const char* file, int line) { nl_fprintf( stderr, "OpenNL should not have reached this point: file:%s, line:%d\n", file,line ) ; abort() ; } /* Timing */ #ifdef WIN32 NLdouble nlCurrentTime() { return (NLdouble)GetTickCount() / 1000.0 ; } #else double nlCurrentTime() { clock_t user_clock ; struct tms user_tms ; user_clock = times(&user_tms) ; return (NLdouble)user_clock / 100.0 ; } #endif /* DLLs/shared objects/dylibs */ #if defined(GEO_DYNAMIC_LIBS) # if defined(NL_OS_UNIX) NLdll nlOpenDLL(const char* name, NLenum flags_in) { void* result = NULL; int flags = 0; if((flags_in & NL_LINK_NOW) != 0) { flags |= RTLD_NOW; } if((flags_in & NL_LINK_LAZY) != 0) { flags |= RTLD_LAZY; } if((flags_in & NL_LINK_GLOBAL) != 0) { flags |= RTLD_GLOBAL; } if((flags_in & NL_LINK_QUIET) == 0) { nl_fprintf(stdout,"Trying to load %s\n", name); } result = dlopen(name, flags); if(result == NULL) { if((flags_in & NL_LINK_QUIET) == 0) { nl_fprintf(stderr,"Did not find %s,\n", name); nl_fprintf(stderr,"Retrying with libgeogram_num_3rdparty.so\n"); } if((flags_in & NL_LINK_USE_FALLBACK) != 0) { result=dlopen("libgeogram_num_3rdparty.so", flags); if(result == NULL) { if((flags_in & NL_LINK_QUIET) == 0) { nlError("nlOpenDLL/dlopen",dlerror()); } } } } if((flags_in & NL_LINK_QUIET) == 0 && result != NULL) { nl_fprintf(stdout,"Loaded %s\n", name); } return result; } void nlCloseDLL(void* handle) { dlclose(handle); } NLfunc nlFindFunction(void* handle, const char* name) { /* * It is not legal in modern C to cast a void* * pointer into a function pointer, thus requiring this * (quite dirty) function that uses a union. */ union { void* ptr; NLfunc fptr; } u; u.ptr = dlsym(handle, name); return u.fptr; } # elif defined(NL_OS_WINDOWS) NLdll nlOpenDLL(const char* name, NLenum flags) { /* Note: NL_LINK_LAZY and NL_LINK_GLOBAL are ignored. */ void* result = LoadLibrary(name); if(result == NULL && ((flags & NL_LINK_USE_FALLBACK) != 0)) { if((flags & NL_LINK_QUIET) == 0) { nl_fprintf(stderr,"Did not find %s,\n", name); nl_fprintf(stderr,"Retrying with geogram_num_3rdparty\n"); } result=LoadLibrary("geogram_num_3rdparty.dll"); } return result; } void nlCloseDLL(void* handle) { FreeLibrary((HMODULE)handle); } NLfunc nlFindFunction(void* handle, const char* name) { return (NLfunc)GetProcAddress((HMODULE)handle, name); } # endif #else NLdll nlOpenDLL(const char* name, NLenum flags) { nl_arg_used(name); nl_arg_used(flags); #ifdef NL_OS_UNIX nlError("nlOpenDLL","Was not compiled with dynamic linking enabled"); nlError("nlOpenDLL","(see VORPALINE_BUILD_DYNAMIC in CMakeLists.txt)"); #else nlError("nlOpenDLL","Not implemented"); #endif return NULL; } void nlCloseDLL(void* handle) { nl_arg_used(handle); nlError("nlCloseDLL","Not implemented"); } NLfunc nlFindFunction(void* handle, const char* name) { nl_arg_used(handle); nl_arg_used(name); nlError("nlFindFunction","Not implemented"); return NULL; } #endif /* Error-reporting functions */ NLprintfFunc nl_printf = printf; NLfprintfFunc nl_fprintf = fprintf; void nlError(const char* function, const char* message) { nl_fprintf(stderr, "OpenNL error in %s(): %s\n", function, message) ; } void nlWarning(const char* function, const char* message) { nl_fprintf(stderr, "OpenNL warning in %s(): %s\n", function, message) ; } void nlPrintfFuncs(NLprintfFunc f1, NLfprintfFunc f2) { nl_printf = f1; nl_fprintf = f2; } /******* extracted from nl_matrix.c *******/ /* Some warnings about const cast in callback for qsort() function. */ #ifdef __clang__ #pragma GCC diagnostic ignored "-Wcast-qual" #endif void nlDeleteMatrix(NLMatrix M) { if(M == NULL) { return; } M->destroy_func(M); NL_DELETE(M); } void nlMultMatrixVector( NLMatrix M, const double* x, double* y ) { M->mult_func(M,x,y); } void nlRowColumnConstruct(NLRowColumn* c) { c->size = 0; c->capacity = 0; c->coeff = NULL; } void nlRowColumnDestroy(NLRowColumn* c) { NL_DELETE_ARRAY(c->coeff); c->size = 0; c->capacity = 0; } void nlRowColumnGrow(NLRowColumn* c) { if(c->capacity != 0) { c->capacity = 2 * c->capacity; c->coeff = NL_RENEW_ARRAY(NLCoeff, c->coeff, c->capacity); } else { c->capacity = 4; c->coeff = NL_NEW_ARRAY(NLCoeff, c->capacity); } } void nlRowColumnAdd(NLRowColumn* c, NLuint index, NLdouble value) { NLuint i; for(i=0; i<c->size; i++) { if(c->coeff[i].index == index) { c->coeff[i].value += value; return; } } if(c->size == c->capacity) { nlRowColumnGrow(c); } c->coeff[c->size].index = index; c->coeff[c->size].value = value; c->size++; } /* Does not check whether the index already exists */ void nlRowColumnAppend(NLRowColumn* c, NLuint index, NLdouble value) { if(c->size == c->capacity) { nlRowColumnGrow(c); } c->coeff[c->size].index = index; c->coeff[c->size].value = value; c->size++; } void nlRowColumnZero(NLRowColumn* c) { c->size = 0; } void nlRowColumnClear(NLRowColumn* c) { c->size = 0; c->capacity = 0; NL_DELETE_ARRAY(c->coeff); } static int nlCoeffCompare(const void* p1, const void* p2) { return (((NLCoeff*)(p2))->index < ((NLCoeff*)(p1))->index); } void nlRowColumnSort(NLRowColumn* c) { qsort(c->coeff, c->size, sizeof(NLCoeff), nlCoeffCompare); } /* CRSMatrix data structure */ static void nlCRSMatrixDestroy(NLCRSMatrix* M) { NL_DELETE_ARRAY(M->val); NL_DELETE_ARRAY(M->rowptr); NL_DELETE_ARRAY(M->colind); NL_DELETE_ARRAY(M->sliceptr); M->m = 0; M->n = 0; M->nslices = 0; } NLboolean nlCRSMatrixSave(NLCRSMatrix* M, const char* filename) { NLuint nnz = M->rowptr[M->m]; FILE* f = fopen(filename, "rb"); if(f == NULL) { nlError("nlCRSMatrixSave", "Could not open file"); return NL_FALSE; } fwrite(&M->m, sizeof(NLuint), 1, f); fwrite(&M->n, sizeof(NLuint), 1, f); fwrite(&nnz, sizeof(NLuint), 1, f); fwrite(M->rowptr, sizeof(NLuint), M->m+1, f); fwrite(M->colind, sizeof(NLuint), nnz, f); fwrite(M->val, sizeof(double), nnz, f); return NL_TRUE; } NLboolean nlCRSMatrixLoad(NLCRSMatrix* M, const char* filename) { NLuint nnz = 0; FILE* f = fopen(filename, "rb"); NLboolean truncated = NL_FALSE; if(f == NULL) { nlError("nlCRSMatrixLoad", "Could not open file"); return NL_FALSE; } truncated = truncated || ( fread(&M->m, sizeof(NLuint), 1, f) != 1 || fread(&M->n, sizeof(NLuint), 1, f) != 1 || fread(&nnz, sizeof(NLuint), 1, f) != 1 ); if(truncated) { M->rowptr = NULL; M->colind = NULL; M->val = NULL; } else { M->rowptr = NL_NEW_ARRAY(NLuint, M->m+1); M->colind = NL_NEW_ARRAY(NLuint, nnz); M->val = NL_NEW_ARRAY(double, nnz); truncated = truncated || ( fread(M->rowptr, sizeof(NLuint), M->m+1, f) != M->m+1 || fread(M->colind, sizeof(NLuint), nnz, f) != nnz || fread(M->val, sizeof(double), nnz, f) != nnz ); } if(truncated) { nlError("nlCRSMatrixSave", "File appears to be truncated"); NL_DELETE_ARRAY(M->rowptr); NL_DELETE_ARRAY(M->colind); NL_DELETE_ARRAY(M->val); return NL_FALSE; } else { M->nslices = 1; M->sliceptr = NL_NEW_ARRAY(NLuint, M->nslices+1); M->sliceptr[0] = 0; M->sliceptr[1] = M->m; } fclose(f); return NL_TRUE; } NLuint nlCRSMatrixNNZ(NLCRSMatrix* M) { return M->rowptr[M->m]; } static void nlCRSMatrixMultSlice( NLCRSMatrix* M, const double* x, double* y, NLuint Ibegin, NLuint Iend ) { NLuint i,j; for(i=Ibegin; i<Iend; ++i) { double sum=0.0; for(j=M->rowptr[i]; j<M->rowptr[i+1]; ++j) { sum += M->val[j] * x[M->colind[j]]; } y[i] = sum; } } static void nlCRSMatrixMult( NLCRSMatrix* M, const double* x, double* y ) { int slice; int nslices = (int)(M->nslices); NLuint i,j,jj; NLdouble a; if(M->symmetric_storage) { for(i=0; i<M->m; ++i) { y[i] = 0.0; } for(i=0; i<M->m; ++i) { for(jj=M->rowptr[i]; jj<M->rowptr[i+1]; ++jj) { a = M->val[jj]; j = M->colind[jj]; y[i] += a * x[j]; if(j != i) { y[j] += a * x[i]; } } } } else { #if defined(_OPENMP) #pragma omp parallel for private(slice) #endif for(slice=0; slice<nslices; ++slice) { nlCRSMatrixMultSlice( M,x,y,M->sliceptr[slice],M->sliceptr[slice+1] ); } } nlHostBlas()->flops += (NLulong)(2*nlCRSMatrixNNZ(M)); } void nlCRSMatrixConstruct( NLCRSMatrix* M, NLuint m, NLuint n, NLuint nnz, NLuint nslices ) { M->m = m; M->n = n; M->type = NL_MATRIX_CRS; M->destroy_func = (NLDestroyMatrixFunc)nlCRSMatrixDestroy; if(NLMultMatrixVector_MKL != NULL) { M->mult_func = (NLMultMatrixVectorFunc)NLMultMatrixVector_MKL; } else { M->mult_func = (NLMultMatrixVectorFunc)nlCRSMatrixMult; } M->nslices = nslices; M->val = NL_NEW_ARRAY(double, nnz); M->rowptr = NL_NEW_ARRAY(NLuint, m+1); M->colind = NL_NEW_ARRAY(NLuint, nnz); M->sliceptr = NL_NEW_ARRAY(NLuint, nslices+1); M->symmetric_storage = NL_FALSE; } void nlCRSMatrixConstructSymmetric( NLCRSMatrix* M, NLuint n, NLuint nnz ) { M->m = n; M->n = n; M->type = NL_MATRIX_CRS; M->destroy_func = (NLDestroyMatrixFunc)nlCRSMatrixDestroy; M->mult_func = (NLMultMatrixVectorFunc)nlCRSMatrixMult; M->nslices = 0; M->val = NL_NEW_ARRAY(double, nnz); M->rowptr = NL_NEW_ARRAY(NLuint, n+1); M->colind = NL_NEW_ARRAY(NLuint, nnz); M->sliceptr = NULL; M->symmetric_storage = NL_TRUE; } /* SparseMatrix data structure */ static void nlSparseMatrixDestroyRowColumns(NLSparseMatrix* M) { NLuint i; if(M->storage & NL_MATRIX_STORE_ROWS) { for(i=0; i<M->m; i++) { nlRowColumnDestroy(&(M->row[i])); } NL_DELETE_ARRAY(M->row); } M->storage = (NLenum)((int)(M->storage) & ~NL_MATRIX_STORE_ROWS); if(M->storage & NL_MATRIX_STORE_COLUMNS) { for(i=0; i<M->n; i++) { nlRowColumnDestroy(&(M->column[i])); } NL_DELETE_ARRAY(M->column); } M->storage = (NLenum)((int)(M->storage) & ~NL_MATRIX_STORE_COLUMNS); } void nlSparseMatrixDestroy(NLSparseMatrix* M) { nl_assert(M->type == NL_MATRIX_SPARSE_DYNAMIC); nlSparseMatrixDestroyRowColumns(M); NL_DELETE_ARRAY(M->diag); #ifdef NL_PARANOID NL_CLEAR(NLSparseMatrix,M); #endif } void nlSparseMatrixAdd(NLSparseMatrix* M, NLuint i, NLuint j, NLdouble value) { nl_parano_range_assert(i, 0, M->m - 1); nl_parano_range_assert(j, 0, M->n - 1); if((M->storage & NL_MATRIX_STORE_SYMMETRIC) && (j > i)) { return; } if(i == j) { M->diag[i] += value; } if(M->storage & NL_MATRIX_STORE_ROWS) { nlRowColumnAdd(&(M->row[i]), j, value); } if(M->storage & NL_MATRIX_STORE_COLUMNS) { nlRowColumnAdd(&(M->column[j]), i, value); } } static void nlSparseMatrixAddSparseMatrix( NLSparseMatrix* M, double mul, const NLSparseMatrix* N ) { NLuint i,j,ii,jj; nl_assert(M->m == N->m); nl_assert(M->n == N->n); if(N->storage & NL_MATRIX_STORE_SYMMETRIC) { nl_assert(M->storage & NL_MATRIX_STORE_SYMMETRIC); } if(N->storage & NL_MATRIX_STORE_ROWS) { for(i=0; i<N->m; ++i) { for(jj=0; jj<N->row[i].size; ++jj) { nlSparseMatrixAdd( M, i, N->row[i].coeff[jj].index, mul*N->row[i].coeff[jj].value ); } } } else { nl_assert(N->storage & NL_MATRIX_STORE_COLUMNS); for(j=0; j<N->n; ++j) { for(ii=0; ii<N->column[j].size; ++ii) { nlSparseMatrixAdd( M, N->column[j].coeff[ii].index, j, mul*N->column[j].coeff[ii].value ); } } } } static void nlSparseMatrixAddCRSMatrix( NLSparseMatrix* M, double mul, const NLCRSMatrix* N ) { NLuint i,jj; nl_assert(M->m == N->m); nl_assert(M->n == N->n); for(i=0; i<M->m; ++i) { for(jj=N->rowptr[i]; jj<N->rowptr[i+1]; ++jj) { nlSparseMatrixAdd( M, i, N->colind[jj], mul*N->val[jj] ); } } } void nlSparseMatrixAddMatrix( NLSparseMatrix* M, double mul, const NLMatrix N ) { nl_assert(M->m == N->m); nl_assert(M->n == N->n); if(N->type == NL_MATRIX_SPARSE_DYNAMIC) { nlSparseMatrixAddSparseMatrix(M, mul, (const NLSparseMatrix*)N); } else if(N->type == NL_MATRIX_CRS) { nlSparseMatrixAddCRSMatrix(M, mul, (const NLCRSMatrix*)N); } else { nl_assert_not_reached; } } void nlSparseMatrixZero( NLSparseMatrix* M) { NLuint i; if(M->storage & NL_MATRIX_STORE_ROWS) { for(i=0; i<M->m; i++) { nlRowColumnZero(&(M->row[i])); } } if(M->storage & NL_MATRIX_STORE_COLUMNS) { for(i=0; i<M->n; i++) { nlRowColumnZero(&(M->column[i])); } } NL_CLEAR_ARRAY(NLdouble, M->diag, M->diag_size); } void nlSparseMatrixClear( NLSparseMatrix* M) { NLuint i; if(M->storage & NL_MATRIX_STORE_ROWS) { for(i=0; i<M->m; i++) { nlRowColumnClear(&(M->row[i])); } } if(M->storage & NL_MATRIX_STORE_COLUMNS) { for(i=0; i<M->n; i++) { nlRowColumnClear(&(M->column[i])); } } NL_CLEAR_ARRAY(NLdouble, M->diag, M->diag_size); } /* Returns the number of non-zero coefficients */ NLuint nlSparseMatrixNNZ( NLSparseMatrix* M) { NLuint nnz = 0; NLuint i; if(M->storage & NL_MATRIX_STORE_ROWS) { for(i = 0; i<M->m; i++) { nnz += M->row[i].size; } } else if (M->storage & NL_MATRIX_STORE_COLUMNS) { for(i = 0; i<M->n; i++) { nnz += M->column[i].size; } } else { nl_assert_not_reached; } return nnz; } void nlSparseMatrixSort( NLSparseMatrix* M) { NLuint i; if(M->storage & NL_MATRIX_STORE_ROWS) { for(i = 0; i<M->m; i++) { nlRowColumnSort(&(M->row[i])); } } if (M->storage & NL_MATRIX_STORE_COLUMNS) { for(i = 0; i<M->n; i++) { nlRowColumnSort(&(M->column[i])); } } } void nlSparseMatrixMAddRow( NLSparseMatrix* M, NLuint i1, double s, NLuint i2 ) { NLuint jj; NLRowColumn* Ri2 = &(M->row[i2]); NLCoeff* c = NULL; nl_debug_assert(i1 < M->m); nl_debug_assert(i2 < M->m); for(jj=0; jj<Ri2->size; ++jj) { c = &(Ri2->coeff[jj]); nlSparseMatrixAdd(M, i1, c->index, s*c->value); } } void nlSparseMatrixScaleRow( NLSparseMatrix* M, NLuint i, double s ) { NLuint jj; NLRowColumn* Ri = &(M->row[i]); NLCoeff* c = NULL; nl_assert(M->storage & NL_MATRIX_STORE_ROWS); nl_assert(!(M->storage & NL_MATRIX_STORE_COLUMNS)); nl_debug_assert(i < M->m); for(jj=0; jj<Ri->size; ++jj) { c = &(Ri->coeff[jj]); c->value *= s; } if(i < M->diag_size) { M->diag[i] *= s; } } void nlSparseMatrixZeroRow( NLSparseMatrix* M, NLuint i ) { NLRowColumn* Ri = &(M->row[i]); nl_debug_assert(i < M->m); Ri->size = 0; if(i < M->diag_size) { M->diag[i] = 0.0; } } /* SparseMatrix x Vector routines, internal helper routines */ static void nlSparseMatrix_mult_rows_symmetric( NLSparseMatrix* A, const NLdouble* x, NLdouble* y ) { NLuint m = A->m; NLuint i,ij; NLCoeff* c = NULL; for(i=0; i<m; i++) { NLRowColumn* Ri = &(A->row[i]); y[i] = 0; for(ij=0; ij<Ri->size; ++ij) { c = &(Ri->coeff[ij]); y[i] += c->value * x[c->index]; if(i != c->index) { y[c->index] += c->value * x[i]; } } } } static void nlSparseMatrix_mult_rows( NLSparseMatrix* A, const NLdouble* x, NLdouble* y ) { /* * Note: OpenMP does not like unsigned ints * (causes some floating point exceptions), * therefore I use here signed ints for all * indices. */ int m = (int)(A->m); int i,ij; NLCoeff* c = NULL; NLRowColumn* Ri = NULL; #if defined(_OPENMP) #pragma omp parallel for private(i,ij,c,Ri) #endif for(i=0; i<m; i++) { Ri = &(A->row[i]); y[i] = 0; for(ij=0; ij<(int)(Ri->size); ij++) { c = &(Ri->coeff[ij]); y[i] += c->value * x[c->index]; } } } static void nlSparseMatrix_mult_cols_symmetric( NLSparseMatrix* A, const NLdouble* x, NLdouble* y ) { NLuint n = A->n; NLuint j,ii; NLCoeff* c = NULL; for(j=0; j<n; j++) { NLRowColumn* Cj = &(A->column[j]); y[j] = 0; for(ii=0; ii<Cj->size; ii++) { c = &(Cj->coeff[ii]); y[c->index] += c->value * x[j]; if(j != c->index) { y[j] += c->value * x[c->index]; } } } } static void nlSparseMatrix_mult_cols( NLSparseMatrix* A, const NLdouble* x, NLdouble* y ) { NLuint n = A->n; NLuint j,ii; NLCoeff* c = NULL; NL_CLEAR_ARRAY(NLdouble, y, A->m); for(j=0; j<n; j++) { NLRowColumn* Cj = &(A->column[j]); for(ii=0; ii<Cj->size; ii++) { c = &(Cj->coeff[ii]); y[c->index] += c->value * x[j]; } } } void nlSparseMatrixMult( NLSparseMatrix* A, const NLdouble* x, NLdouble* y ) { nl_assert(A->type == NL_MATRIX_SPARSE_DYNAMIC); if(A->storage & NL_MATRIX_STORE_ROWS) { if(A->storage & NL_MATRIX_STORE_SYMMETRIC) { nlSparseMatrix_mult_rows_symmetric(A, x, y); } else { nlSparseMatrix_mult_rows(A, x, y); } } else { if(A->storage & NL_MATRIX_STORE_SYMMETRIC) { nlSparseMatrix_mult_cols_symmetric(A, x, y); } else { nlSparseMatrix_mult_cols(A, x, y); } } nlHostBlas()->flops += (NLulong)(2*nlSparseMatrixNNZ(A)); } NLMatrix nlSparseMatrixNew( NLuint m, NLuint n, NLenum storage ) { NLSparseMatrix* result = NL_NEW(NLSparseMatrix); nlSparseMatrixConstruct(result, m, n, storage); return (NLMatrix)result; } void nlSparseMatrixConstruct( NLSparseMatrix* M, NLuint m, NLuint n, NLenum storage ) { NLuint i; M->m = m; M->n = n; M->type = NL_MATRIX_SPARSE_DYNAMIC; M->destroy_func = (NLDestroyMatrixFunc)nlSparseMatrixDestroy; M->mult_func = (NLMultMatrixVectorFunc)nlSparseMatrixMult; M->storage = storage; if(storage & NL_MATRIX_STORE_ROWS) { M->row = NL_NEW_ARRAY(NLRowColumn, m); M->row_capacity = m; for(i=0; i<n; i++) { nlRowColumnConstruct(&(M->row[i])); } } else { M->row = NULL; M->row_capacity = 0; } if(storage & NL_MATRIX_STORE_COLUMNS) { M->column = NL_NEW_ARRAY(NLRowColumn, n); M->column_capacity = n; for(i=0; i<n; i++) { nlRowColumnConstruct(&(M->column[i])); } } else { M->column = NULL; M->column_capacity = 0; } M->diag_size = MIN(m,n); M->diag_capacity = M->diag_size; M->diag = NL_NEW_ARRAY(NLdouble, M->diag_size); } static void adjust_diag(NLSparseMatrix* M) { NLuint new_diag_size = MIN(M->m, M->n); NLuint i; if(new_diag_size > M->diag_size) { if(new_diag_size > M->diag_capacity) { M->diag_capacity *= 2; if(M->diag_capacity == 0) { M->diag_capacity = 16; } M->diag = NL_RENEW_ARRAY(double, M->diag, M->diag_capacity); for(i=M->diag_size; i<new_diag_size; ++i) { M->diag[i] = 0.0; } } M->diag_size= new_diag_size; } } void nlSparseMatrixAddRow( NLSparseMatrix* M) { ++M->m; if(M->storage & NL_MATRIX_STORE_ROWS) { if(M->m > M->row_capacity) { M->row_capacity *= 2; if(M->row_capacity == 0) { M->row_capacity = 16; } M->row = NL_RENEW_ARRAY( NLRowColumn, M->row, M->row_capacity ); } nlRowColumnConstruct(&(M->row[M->m-1])); } adjust_diag(M); } void nlSparseMatrixAddColumn( NLSparseMatrix* M) { ++M->n; if(M->storage & NL_MATRIX_STORE_COLUMNS) { if(M->n > M->column_capacity) { M->column_capacity *= 2; if(M->column_capacity == 0) { M->column_capacity = 16; } M->column = NL_RENEW_ARRAY( NLRowColumn, M->column, M->column_capacity ); } nlRowColumnConstruct(&(M->column[M->n-1])); } adjust_diag(M); } NLMatrix nlCRSMatrixNewFromSparseMatrix(NLSparseMatrix* M) { NLuint nnz = nlSparseMatrixNNZ(M); NLuint nslices = 8; /* TODO: get number of cores */ NLuint slice, cur_bound, cur_NNZ, cur_row; NLuint i,ij,k; NLuint slice_size = nnz / nslices; NLCRSMatrix* CRS = NL_NEW(NLCRSMatrix); nl_assert(M->storage & NL_MATRIX_STORE_ROWS); if(M->storage & NL_MATRIX_STORE_SYMMETRIC) { nl_assert(M->m == M->n); nlCRSMatrixConstructSymmetric(CRS, M->n, nnz); } else { nlCRSMatrixConstruct(CRS, M->m, M->n, nnz, nslices); } nlSparseMatrixSort(M); /* Convert matrix to CRS format */ k=0; for(i=0; i<M->m; ++i) { NLRowColumn* Ri = &(M->row[i]); CRS->rowptr[i] = k; for(ij=0; ij<Ri->size; ij++) { NLCoeff* c = &(Ri->coeff[ij]); CRS->val[k] = c->value; CRS->colind[k] = c->index; ++k; } } CRS->rowptr[M->m] = k; /* Create "slices" to be used by parallel sparse matrix vector product */ if(CRS->sliceptr != NULL) { cur_bound = slice_size; cur_NNZ = 0; cur_row = 0; CRS->sliceptr[0]=0; for(slice=1; slice<nslices; ++slice) { while(cur_NNZ < cur_bound && cur_row < M->m) { ++cur_row; cur_NNZ += CRS->rowptr[cur_row+1] - CRS->rowptr[cur_row]; } CRS->sliceptr[slice] = cur_row; cur_bound += slice_size; } CRS->sliceptr[nslices]=M->m; } return (NLMatrix)CRS; } NLMatrix nlCRSMatrixNewFromSparseMatrixSymmetric(NLSparseMatrix* M) { NLuint nnz; NLuint i,j,jj,k; NLCRSMatrix* CRS = NL_NEW(NLCRSMatrix); nl_assert(M->storage & NL_MATRIX_STORE_ROWS); nl_assert(M->m == M->n); nlSparseMatrixSort(M); if(M->storage & NL_MATRIX_STORE_SYMMETRIC) { nnz = nlSparseMatrixNNZ(M); } else { nnz = 0; for(i=0; i<M->n; ++i) { NLRowColumn* Ri = &M->row[i]; for(jj=0; jj<Ri->size; ++jj) { j = Ri->coeff[jj].index; if(j <= i) { ++nnz; } } } } nlCRSMatrixConstructSymmetric(CRS, M->n, nnz); k=0; for(i=0; i<M->m; ++i) { NLRowColumn* Ri = &(M->row[i]); CRS->rowptr[i] = k; for(jj=0; jj<Ri->size; ++jj) { j = Ri->coeff[jj].index; if((M->storage & NL_MATRIX_STORE_SYMMETRIC)) { nl_debug_assert(j <= i); } if(j <= i) { CRS->val[k] = Ri->coeff[jj].value; CRS->colind[k] = j; ++k; } } } CRS->rowptr[M->m] = k; return (NLMatrix)CRS; } void nlMatrixCompress(NLMatrix* M) { NLMatrix CRS = NULL; if((*M)->type != NL_MATRIX_SPARSE_DYNAMIC) { return; } CRS = nlCRSMatrixNewFromSparseMatrix((NLSparseMatrix*)*M); nlDeleteMatrix(*M); *M = CRS; } NLuint nlMatrixNNZ(NLMatrix M) { if(M->type == NL_MATRIX_SPARSE_DYNAMIC) { return nlSparseMatrixNNZ((NLSparseMatrix*)M); } else if(M->type == NL_MATRIX_CRS) { return nlCRSMatrixNNZ((NLCRSMatrix*)M); } return M->m * M->n; } NLMatrix nlMatrixFactorize(NLMatrix M, NLenum solver) { NLMatrix result = NULL; switch(solver) { case NL_SUPERLU_EXT: case NL_PERM_SUPERLU_EXT: case NL_SYMMETRIC_SUPERLU_EXT: result = nlMatrixFactorize_SUPERLU(M,solver); break; case NL_CHOLMOD_EXT: result = nlMatrixFactorize_CHOLMOD(M,solver); break; default: nlError("nlMatrixFactorize","unknown solver"); } return result; } typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; NLMatrixFunc matrix_func; } NLFunctionMatrix; static void nlFunctionMatrixDestroy(NLFunctionMatrix* M) { (void)M; /* to avoid 'unused parameter' warning */ /* * Nothing special to do, * there is no dynamic allocated mem. */ } static void nlFunctionMatrixMult( NLFunctionMatrix* M, const NLdouble* x, NLdouble* y ) { M->matrix_func(x,y); } NLMatrix nlMatrixNewFromFunction(NLuint m, NLuint n, NLMatrixFunc func) { NLFunctionMatrix* result = NL_NEW(NLFunctionMatrix); result->m = m; result->n = n; result->type = NL_MATRIX_FUNCTION; result->destroy_func = (NLDestroyMatrixFunc)nlFunctionMatrixDestroy; result->mult_func = (NLMultMatrixVectorFunc)nlFunctionMatrixMult; result->matrix_func = func; return (NLMatrix)result; } NLMatrixFunc nlMatrixGetFunction(NLMatrix M) { if(M == NULL) { return NULL; } if(M->type != NL_MATRIX_FUNCTION) { return NULL; } return ((NLFunctionMatrix*)M)->matrix_func; } typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; NLMatrixFunc matrix_func; NLMatrix M; NLboolean owns_M; NLMatrix N; NLboolean owns_N; NLdouble* work; } NLMatrixProduct; static void nlMatrixProductDestroy(NLMatrixProduct* P) { NL_DELETE_ARRAY(P->work); if(P->owns_M) { nlDeleteMatrix(P->M); P->M = NULL; } if(P->owns_N) { nlDeleteMatrix(P->N); P->N = NULL; } } static void nlMatrixProductMult( NLMatrixProduct* P, const NLdouble* x, NLdouble* y ) { nlMultMatrixVector(P->N, x, P->work); nlMultMatrixVector(P->M, P->work, y); } NLMatrix nlMatrixNewFromProduct( NLMatrix M, NLboolean owns_M, NLMatrix N, NLboolean owns_N ) { NLMatrixProduct* result = NL_NEW(NLMatrixProduct); nl_assert(M->n == N->m); result->m = M->m; result->n = N->n; result->type = NL_MATRIX_OTHER; result->work = NL_NEW_ARRAY(NLdouble,N->m); result->destroy_func = (NLDestroyMatrixFunc)nlMatrixProductDestroy; result->mult_func = (NLMultMatrixVectorFunc)nlMatrixProductMult; result->M = M; result->owns_M = owns_M; result->N = N; result->owns_N = owns_N; return (NLMatrix)result; } /******* extracted from nl_context.c *******/ NLContextStruct* nlCurrentContext = NULL; NLContext nlNewContext() { NLContextStruct* result = NL_NEW(NLContextStruct); result->state = NL_STATE_INITIAL; result->solver = NL_SOLVER_DEFAULT; result->max_iterations = 100; result->threshold = 1e-6; result->omega = 1.5; result->row_scaling = 1.0; result->inner_iterations = 5; result->solver_func = nlDefaultSolver; result->progress_func = NULL; result->verbose = NL_FALSE; result->nb_systems = 1; result->matrix_mode = NL_STIFFNESS_MATRIX; nlMakeCurrent(result); return result; } void nlDeleteContext(NLContext context_in) { NLContextStruct* context = (NLContextStruct*)(context_in); if(nlCurrentContext == context) { nlCurrentContext = NULL; } nlDeleteMatrix(context->M); context->M = NULL; nlDeleteMatrix(context->P); context->P = NULL; nlDeleteMatrix(context->B); context->B = NULL; nlRowColumnDestroy(&context->af); nlRowColumnDestroy(&context->al); NL_DELETE_ARRAY(context->variable_value); NL_DELETE_ARRAY(context->variable_buffer); NL_DELETE_ARRAY(context->variable_is_locked); NL_DELETE_ARRAY(context->variable_index); NL_DELETE_ARRAY(context->x); NL_DELETE_ARRAY(context->b); NL_DELETE_ARRAY(context->right_hand_side); NL_DELETE_ARRAY(context->eigen_value); #ifdef NL_PARANOID NL_CLEAR(NLContextStruct, context); #endif NL_DELETE(context); } void nlMakeCurrent(NLContext context) { nlCurrentContext = (NLContextStruct*)(context); } NLContext nlGetCurrent() { return nlCurrentContext; } /* Finite state automaton */ void nlCheckState(NLenum state) { nl_assert(nlCurrentContext->state == state); } void nlTransition(NLenum from_state, NLenum to_state) { nlCheckState(from_state); nlCurrentContext->state = to_state; } /* Preconditioner setup and default solver */ static void nlSetupPreconditioner() { /* Check compatibility between solver and preconditioner */ if( nlCurrentContext->solver == NL_BICGSTAB && nlCurrentContext->preconditioner == NL_PRECOND_SSOR ) { nlWarning( "nlSolve", "cannot use SSOR preconditioner with non-symmetric matrix, " "switching to Jacobi" ); nlCurrentContext->preconditioner = NL_PRECOND_JACOBI; } if( nlCurrentContext->solver == NL_GMRES && nlCurrentContext->preconditioner != NL_PRECOND_NONE ) { nlWarning("nlSolve", "Preconditioner not implemented yet for GMRES"); nlCurrentContext->preconditioner = NL_PRECOND_NONE; } if( nlCurrentContext->solver == NL_SUPERLU_EXT && nlCurrentContext->preconditioner != NL_PRECOND_NONE ) { nlWarning("nlSolve", "Preconditioner not implemented yet for SUPERLU"); nlCurrentContext->preconditioner = NL_PRECOND_NONE; } if( nlCurrentContext->solver == NL_CHOLMOD_EXT && nlCurrentContext->preconditioner != NL_PRECOND_NONE ) { nlWarning("nlSolve", "Preconditioner not implemented yet for CHOLMOD"); nlCurrentContext->preconditioner = NL_PRECOND_NONE; } if( nlCurrentContext->solver == NL_PERM_SUPERLU_EXT && nlCurrentContext->preconditioner != NL_PRECOND_NONE ) { nlWarning( "nlSolve", "Preconditioner not implemented yet for PERMSUPERLU" ); nlCurrentContext->preconditioner = NL_PRECOND_NONE; } if( nlCurrentContext->solver == NL_SYMMETRIC_SUPERLU_EXT && nlCurrentContext->preconditioner != NL_PRECOND_NONE ) { nlWarning( "nlSolve", "Preconditioner not implemented yet for PERMSUPERLU" ); nlCurrentContext->preconditioner = NL_PRECOND_NONE; } nlDeleteMatrix(nlCurrentContext->P); nlCurrentContext->P = NULL; switch(nlCurrentContext->preconditioner) { case NL_PRECOND_NONE: break; case NL_PRECOND_JACOBI: nlCurrentContext->P = nlNewJacobiPreconditioner(nlCurrentContext->M); break; case NL_PRECOND_SSOR: nlCurrentContext->P = nlNewSSORPreconditioner( nlCurrentContext->M,nlCurrentContext->omega ); break; case NL_PRECOND_USER: break; default: nl_assert_not_reached; } if(nlCurrentContext->preconditioner != NL_PRECOND_SSOR) { if(getenv("NL_LOW_MEM") == NULL) { nlMatrixCompress(&nlCurrentContext->M); } } } static NLboolean nlSolveDirect() { NLdouble* b = nlCurrentContext->b; NLdouble* x = nlCurrentContext->x; NLuint n = nlCurrentContext->n; NLuint k; NLMatrix F = nlMatrixFactorize( nlCurrentContext->M, nlCurrentContext->solver ); if(F == NULL) { return NL_FALSE; } for(k=0; k<nlCurrentContext->nb_systems; ++k) { nlMultMatrixVector(F, b, x); b += n; x += n; } nlDeleteMatrix(F); return NL_TRUE; } static NLboolean nlSolveIterative() { NLboolean use_CUDA = NL_FALSE; NLdouble* b = nlCurrentContext->b; NLdouble* x = nlCurrentContext->x; NLuint n = nlCurrentContext->n; NLuint k; NLBlas_t blas = nlHostBlas(); NLMatrix M = nlCurrentContext->M; NLMatrix P = nlCurrentContext->P; /* * For CUDA: it is implemented for * all iterative solvers except GMRES * Jacobi preconditioner */ if(nlExtensionIsInitialized_CUDA() && (nlCurrentContext->solver != NL_GMRES) && (nlCurrentContext->preconditioner == NL_PRECOND_NONE || nlCurrentContext->preconditioner == NL_PRECOND_JACOBI) ) { if(nlCurrentContext->verbose) { nl_printf("Using CUDA\n"); } use_CUDA = NL_TRUE; blas = nlCUDABlas(); if(nlCurrentContext->preconditioner == NL_PRECOND_JACOBI) { P = nlCUDAJacobiPreconditionerNewFromCRSMatrix(M); } M = nlCUDAMatrixNewFromCRSMatrix(M); } /* * We do not count CUDA transfers and CUDA matrix construction * when estimating GFlops */ nlCurrentContext->start_time = nlCurrentTime(); nlBlasResetStats(blas); for(k=0; k<nlCurrentContext->nb_systems; ++k) { nlSolveSystemIterative( blas, M, P, b, x, nlCurrentContext->solver, nlCurrentContext->threshold, nlCurrentContext->max_iterations, nlCurrentContext->inner_iterations ); b += n; x += n; } nlCurrentContext->flops += blas->flops; if(use_CUDA) { nlDeleteMatrix(M); nlDeleteMatrix(P); } return NL_TRUE; } NLboolean nlDefaultSolver() { NLboolean result = NL_TRUE; nlSetupPreconditioner(); switch(nlCurrentContext->solver) { case NL_CG: case NL_BICGSTAB: case NL_GMRES: { result = nlSolveIterative(); } break; case NL_SUPERLU_EXT: case NL_PERM_SUPERLU_EXT: case NL_SYMMETRIC_SUPERLU_EXT: case NL_CHOLMOD_EXT: { result = nlSolveDirect(); } break; default: nl_assert_not_reached; } return result; } /******* extracted from nl_blas.c *******/ /* Many warnings about const double* converted to double* when calling BLAS functions that do not have the const qualifier in their prototypes. */ #ifdef __clang__ #pragma GCC diagnostic ignored "-Wcast-qual" #pragma GCC diagnostic ignored "-Wcomma" #endif #ifndef NL_FORTRAN_WRAP #define NL_FORTRAN_WRAP(x) x##_ #endif #ifdef NL_USE_ATLAS int NL_FORTRAN_WRAP(xerbla)(char *srname, int *info) { nl_printf(stderr, "** On entry to %6s, parameter number %2d had an illegal value\n", srname, *info ); return 0; } #ifndef NL_USE_BLAS #define NL_USE_BLAS #endif #endif #ifdef NL_USE_SUPERLU #ifndef NL_USE_BLAS #define NL_USE_BLAS /* * The BLAS included in SuperLU does not have DTPSV, * we use the DTPSV embedded in OpenNL. */ #define NEEDS_DTPSV #endif #endif #ifndef NL_USE_BLAS #define NEEDS_DTPSV #endif /* BLAS routines */ /* copy-pasted from CBLAS (i.e. generated from f2c) */ /* * lsame * xerbla * daxpy * ddot * dscal * dnrm2 * dcopy * dgemv * dtpsv */ typedef NLint integer ; typedef NLdouble doublereal ; typedef NLboolean logical ; typedef NLint ftnlen ; #ifndef max #define max(x,y) ((x) > (y) ? (x) : (y)) #endif #ifndef NL_USE_BLAS static int NL_FORTRAN_WRAP(lsame)(const char *ca, const char *cb) { /* -- LAPACK auxiliary routine (version 2.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= LSAME returns .TRUE. if CA is the same letter as CB regardless of case. Arguments ========= CA (input) CHARACTER*1 CB (input) CHARACTER*1 CA and CB specify the single characters to be compared. ===================================================================== */ /* System generated locals */ int ret_val; /* Local variables */ int inta, intb, zcode; ret_val = *(unsigned char *)ca == *(unsigned char *)cb; if (ret_val) { return ret_val; } /* Now test for equivalence if both characters are alphabetic. */ zcode = 'Z'; /* Use 'Z' rather than 'A' so that ASCII can be detected on Prime machines, on which ICHAR returns a value with bit 8 set. ICHAR('A') on Prime machines returns 193 which is the same as ICHAR('A') on an EBCDIC machine. */ inta = *(unsigned char *)ca; intb = *(unsigned char *)cb; if (zcode == 90 || zcode == 122) { /* ASCII is assumed - ZCODE is the ASCII code of either lower or upper case 'Z'. */ if (inta >= 97 && inta <= 122) inta += -32; if (intb >= 97 && intb <= 122) intb += -32; } else if (zcode == 233 || zcode == 169) { /* EBCDIC is assumed - ZCODE is the EBCDIC code of either lower or upper case 'Z'. */ if ((inta >= 129 && inta <= 137) || (inta >= 145 && inta <= 153) || (inta >= 162 && inta <= 169) ) inta += 64; if ( (intb >= 129 && intb <= 137) || (intb >= 145 && intb <= 153) || (intb >= 162 && intb <= 169) ) intb += 64; } else if (zcode == 218 || zcode == 250) { /* ASCII is assumed, on Prime machines - ZCODE is the ASCII code plus 128 of either lower or upper case 'Z'. */ if (inta >= 225 && inta <= 250) inta += -32; if (intb >= 225 && intb <= 250) intb += -32; } ret_val = inta == intb; return ret_val; } /* lsame_ */ /* Subroutine */ static int NL_FORTRAN_WRAP(xerbla)(const char *srname, int *info) { /* -- LAPACK auxiliary routine (version 2.0) -- Univ. of Tennessee, Univ. of California Berkeley, NAG Ltd., Courant Institute, Argonne National Lab, and Rice University September 30, 1994 Purpose ======= XERBLA is an error handler for the LAPACK routines. It is called by an LAPACK routine if an input parameter has an invalid value. A message is printed and execution stops. Installers may consider modifying the STOP statement in order to call system-specific exception-handling facilities. Arguments ========= SRNAME (input) CHARACTER*6 The name of the routine which called XERBLA. INFO (input) INT The position of the invalid parameter in the parameter list of the calling routine. ===================================================================== */ nl_fprintf(stderr, "** On entry to %6s, parameter number %2d had an illegal value\n", srname, *info); /* End of XERBLA */ return 0; } /* xerbla_ */ /* Subroutine */ static int NL_FORTRAN_WRAP(daxpy)(integer *n, doublereal *da, doublereal *dx, integer *incx, doublereal *dy, integer *incy) { /* System generated locals */ integer i__1; /* Local variables */ static integer i, m, ix, iy, mp1; /* constant times a vector plus a vector. uses unrolled loops for increments equal to one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) Parameter adjustments Function Body */ #define DY(I) dy[(I)-1] #define DX(I) dx[(I)-1] if (*n <= 0) { return 0; } if (*da == 0.) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i = 1; i <= *n; ++i) { DY(iy) += *da * DX(ix); ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 4; if (m == 0) { goto L40; } i__1 = m; for (i = 1; i <= m; ++i) { DY(i) += *da * DX(i); /* L30: */ } if (*n < 4) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i = mp1; i <= *n; i += 4) { DY(i) += *da * DX(i); DY(i + 1) += *da * DX(i + 1); DY(i + 2) += *da * DX(i + 2); DY(i + 3) += *da * DX(i + 3); /* L50: */ } nl_arg_used(i__1); return 0; } /* daxpy_ */ #undef DY #undef DX static doublereal NL_FORTRAN_WRAP(ddot)(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy) { /* System generated locals */ integer i__1; doublereal ret_val; /* Local variables */ static integer i, m; static doublereal dtemp; static integer ix, iy, mp1; /* forms the dot product of two vectors. uses unrolled loops for increments equal to one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) Parameter adjustments Function Body */ #define DY(I) dy[(I)-1] #define DX(I) dx[(I)-1] ret_val = 0.; dtemp = 0.; if (*n <= 0) { return ret_val; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i = 1; i <= *n; ++i) { dtemp += DX(ix) * DY(iy); ix += *incx; iy += *incy; /* L10: */ } ret_val = dtemp; return ret_val; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 5; if (m == 0) { goto L40; } i__1 = m; for (i = 1; i <= m; ++i) { dtemp += DX(i) * DY(i); /* L30: */ } if (*n < 5) { goto L60; } L40: mp1 = m + 1; i__1 = *n; for (i = mp1; i <= *n; i += 5) { dtemp = dtemp + DX(i) * DY(i) + DX(i + 1) * DY(i + 1) + DX(i + 2) * DY(i + 2) + DX(i + 3) * DY(i + 3) + DX(i + 4) * DY(i + 4); /* L50: */ } L60: ret_val = dtemp; nl_arg_used(i__1); return ret_val; } /* ddot_ */ #undef DY #undef DX /* Subroutine */ static int NL_FORTRAN_WRAP(dscal)(integer *n, doublereal *da, doublereal *dx, integer *incx) { /* System generated locals */ integer i__1, i__2; /* Local variables */ static integer i, m, nincx, mp1; /* scales a vector by a constant. uses unrolled loops for increment equal to one. jack dongarra, linpack, 3/11/78. modified 3/93 to return if incx .le. 0. modified 12/3/93, array(1) declarations changed to array(*) Parameter adjustments Function Body */ #ifdef DX #undef DX #endif #define DX(I) dx[(I)-1] if (*n <= 0 || *incx <= 0) { return 0; } if (*incx == 1) { goto L20; } /* code for increment not equal to 1 */ nincx = *n * *incx; i__1 = nincx; i__2 = *incx; for (i = 1; *incx < 0 ? i >= nincx : i <= nincx; i += *incx) { DX(i) = *da * DX(i); /* L10: */ } return 0; /* code for increment equal to 1 clean-up loop */ L20: m = *n % 5; if (m == 0) { goto L40; } i__2 = m; for (i = 1; i <= m; ++i) { DX(i) = *da * DX(i); /* L30: */ } if (*n < 5) { return 0; } L40: mp1 = m + 1; i__2 = *n; for (i = mp1; i <= *n; i += 5) { DX(i) = *da * DX(i); DX(i + 1) = *da * DX(i + 1); DX(i + 2) = *da * DX(i + 2); DX(i + 3) = *da * DX(i + 3); DX(i + 4) = *da * DX(i + 4); /* L50: */ } nl_arg_used(i__1); nl_arg_used(i__2); return 0; } /* dscal_ */ #undef DX static doublereal NL_FORTRAN_WRAP(dnrm2)(integer *n, doublereal *x, integer *incx) { /* System generated locals */ integer i__1, i__2; doublereal ret_val, d__1; /* Builtin functions */ /* BL: already declared in the included <math.h>, we do not need it here. */ /*double sqrt(doublereal); */ /* Local variables */ static doublereal norm, scale, absxi; static integer ix; static doublereal ssq; /* DNRM2 returns the euclidean norm of a vector via the function name, so that DNRM2 := sqrt( x'*x ) -- This version written on 25-October-1982. Modified on 14-October-1993 to inline the call to DLASSQ. Sven Hammarling, Nag Ltd. Parameter adjustments Function Body */ #ifdef X #undef X #endif #define X(I) x[(I)-1] if (*n < 1 || *incx < 1) { norm = 0.; } else if (*n == 1) { norm = fabs(X(1)); } else { scale = 0.; ssq = 1.; /* The following loop is equivalent to this call to the LAPACK auxiliary routine: CALL DLASSQ( N, X, INCX, SCALE, SSQ ) */ i__1 = (*n - 1) * *incx + 1; i__2 = *incx; for (ix = 1; *incx < 0 ? ix >= (*n-1)**incx+1 : ix <= (*n-1)**incx+1; ix += *incx) { if (X(ix) != 0.) { absxi = (d__1 = X(ix), fabs(d__1)); if (scale < absxi) { /* Computing 2nd power */ d__1 = scale / absxi; ssq = ssq * (d__1 * d__1) + 1.; scale = absxi; } else { /* Computing 2nd power */ d__1 = absxi / scale; ssq += d__1 * d__1; } } /* L10: */ } norm = scale * sqrt(ssq); } ret_val = norm; nl_arg_used(i__1); nl_arg_used(i__2); return ret_val; /* End of DNRM2. */ } /* dnrm2_ */ #undef X /* Subroutine */ static int NL_FORTRAN_WRAP(dcopy)(integer *n, doublereal *dx, integer *incx, doublereal *dy, integer *incy) { /* System generated locals */ integer i__1; /* Local variables */ static integer i, m, ix, iy, mp1; /* copies a vector, x, to a vector, y. uses unrolled loops for increments equal to one. jack dongarra, linpack, 3/11/78. modified 12/3/93, array(1) declarations changed to array(*) Parameter adjustments Function Body */ #define DY(I) dy[(I)-1] #define DX(I) dx[(I)-1] if (*n <= 0) { return 0; } if (*incx == 1 && *incy == 1) { goto L20; } /* code for unequal increments or equal increments not equal to 1 */ ix = 1; iy = 1; if (*incx < 0) { ix = (-(*n) + 1) * *incx + 1; } if (*incy < 0) { iy = (-(*n) + 1) * *incy + 1; } i__1 = *n; for (i = 1; i <= *n; ++i) { DY(iy) = DX(ix); ix += *incx; iy += *incy; /* L10: */ } return 0; /* code for both increments equal to 1 clean-up loop */ L20: m = *n % 7; if (m == 0) { goto L40; } i__1 = m; for (i = 1; i <= m; ++i) { DY(i) = DX(i); /* L30: */ } if (*n < 7) { return 0; } L40: mp1 = m + 1; i__1 = *n; for (i = mp1; i <= *n; i += 7) { DY(i) = DX(i); DY(i + 1) = DX(i + 1); DY(i + 2) = DX(i + 2); DY(i + 3) = DX(i + 3); DY(i + 4) = DX(i + 4); DY(i + 5) = DX(i + 5); DY(i + 6) = DX(i + 6); /* L50: */ } nl_arg_used(i__1); return 0; } /* dcopy_ */ #undef DX #undef DY /* Subroutine */ static int NL_FORTRAN_WRAP(dgemv)(const char *trans, integer *m, integer *n, doublereal * alpha, doublereal *a, integer *lda, doublereal *x, integer *incx, doublereal *beta, doublereal *y, integer *incy) { /* System generated locals */ /* integer a_dim1, a_offset ; */ integer i__1, i__2; /* Local variables */ static integer info; static doublereal temp; static integer lenx, leny, i, j; /* extern logical lsame_(char *, char *); */ static integer ix, iy, jx, jy, kx, ky; /* extern int xerbla_(char *, integer *); */ /* Purpose ======= DGEMV performs one of the matrix-vector operations y := alpha*A*x + beta*y, or y := alpha*A'*x + beta*y, where alpha and beta are scalars, x and y are vectors and A is an m by n matrix. Parameters ========== TRANS - CHARACTER*1. On entry, TRANS specifies the operation to be performed as follows: TRANS = 'N' or 'n' y := alpha*A*x + beta*y. TRANS = 'T' or 't' y := alpha*A'*x + beta*y. TRANS = 'C' or 'c' y := alpha*A'*x + beta*y. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix A. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix A. N must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, n ). Before entry, the leading m by n part of the array A must contain the matrix of coefficients. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. LDA must be at least max( 1, m ). Unchanged on exit. X - DOUBLE PRECISION array of DIMENSION at least ( 1 + ( n - 1 )*abs( INCX ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( m - 1 )*abs( INCX ) ) otherwise. Before entry, the incremented array X must contain the vector x. Unchanged on exit. INCX - INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. Unchanged on exit. Y - DOUBLE PRECISION array of DIMENSION at least ( 1 + ( m - 1 )*abs( INCY ) ) when TRANS = 'N' or 'n' and at least ( 1 + ( n - 1 )*abs( INCY ) ) otherwise. Before entry with BETA non-zero, the incremented array Y must contain the vector y. On exit, Y is overwritten by the updated vector y. INCY - INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. Unchanged on exit. Level 2 Blas routine. -- Written on 22-October-1986. Jack Dongarra, Argonne National Lab. Jeremy Du Croz, Nag Central Office. Sven Hammarling, Nag Central Office. Richard Hanson, Sandia National Labs. Test the input parameters. Parameter adjustments Function Body */ #define X(I) x[(I)-1] #define Y(I) y[(I)-1] #define A(I,J) a[(I)-1 + ((J)-1)* ( *lda)] info = 0; if (! NL_FORTRAN_WRAP(lsame)(trans, "N") && ! NL_FORTRAN_WRAP(lsame)(trans, "T") && ! NL_FORTRAN_WRAP(lsame)(trans, "C")) { info = 1; } else if (*m < 0) { info = 2; } else if (*n < 0) { info = 3; } else if (*lda < max(1,*m)) { info = 6; } else if (*incx == 0) { info = 8; } else if (*incy == 0) { info = 11; } if (info != 0) { NL_FORTRAN_WRAP(xerbla)("DGEMV ", &info); return 0; } /* Quick return if possible. */ if (*m == 0 || *n == 0 || (*alpha == 0. && *beta == 1.)) { return 0; } /* Set LENX and LENY, the lengths of the vectors x and y, and set up the start points in X and Y. */ if (NL_FORTRAN_WRAP(lsame)(trans, "N")) { lenx = *n; leny = *m; } else { lenx = *m; leny = *n; } if (*incx > 0) { kx = 1; } else { kx = 1 - (lenx - 1) * *incx; } if (*incy > 0) { ky = 1; } else { ky = 1 - (leny - 1) * *incy; } /* Start the operations. In this version the elements of A are accessed sequentially with one pass through A. First form y := beta*y. */ if (*beta != 1.) { if (*incy == 1) { if (*beta == 0.) { i__1 = leny; for (i = 1; i <= leny; ++i) { Y(i) = 0.; /* L10: */ } } else { i__1 = leny; for (i = 1; i <= leny; ++i) { Y(i) = *beta * Y(i); /* L20: */ } } } else { iy = ky; if (*beta == 0.) { i__1 = leny; for (i = 1; i <= leny; ++i) { Y(iy) = 0.; iy += *incy; /* L30: */ } } else { i__1 = leny; for (i = 1; i <= leny; ++i) { Y(iy) = *beta * Y(iy); iy += *incy; /* L40: */ } } } } if (*alpha == 0.) { return 0; } if (NL_FORTRAN_WRAP(lsame)(trans, "N")) { /* Form y := alpha*A*x + y. */ jx = kx; if (*incy == 1) { i__1 = *n; for (j = 1; j <= *n; ++j) { if (X(jx) != 0.) { temp = *alpha * X(jx); i__2 = *m; for (i = 1; i <= *m; ++i) { Y(i) += temp * A(i,j); /* L50: */ } } jx += *incx; /* L60: */ } } else { i__1 = *n; for (j = 1; j <= *n; ++j) { if (X(jx) != 0.) { temp = *alpha * X(jx); iy = ky; i__2 = *m; for (i = 1; i <= *m; ++i) { Y(iy) += temp * A(i,j); iy += *incy; /* L70: */ } } jx += *incx; /* L80: */ } } } else { /* Form y := alpha*A'*x + y. */ jy = ky; if (*incx == 1) { i__1 = *n; for (j = 1; j <= *n; ++j) { temp = 0.; i__2 = *m; for (i = 1; i <= *m; ++i) { temp += A(i,j) * X(i); /* L90: */ } Y(jy) += *alpha * temp; jy += *incy; /* L100: */ } } else { i__1 = *n; for (j = 1; j <= *n; ++j) { temp = 0.; ix = kx; i__2 = *m; for (i = 1; i <= *m; ++i) { temp += A(i,j) * X(ix); ix += *incx; /* L110: */ } Y(jy) += *alpha * temp; jy += *incy; /* L120: */ } } } nl_arg_used(i__1); nl_arg_used(i__2); return 0; /* End of DGEMV . */ } /* dgemv_ */ #undef X #undef Y #undef A #else extern void NL_FORTRAN_WRAP(daxpy)( int *n, double *alpha, double *x, int *incx, double *y, int *incy ) ; extern double NL_FORTRAN_WRAP(dnrm2)( int *n, double *x, int *incx ) ; extern int NL_FORTRAN_WRAP(dcopy)(int* n, double* dx, int* incx, double* dy, int* incy) ; extern void NL_FORTRAN_WRAP(dscal)(int* n, double* alpha, double *x, int* incx) ; #ifndef NEEDS_DTPSV extern void NL_FORTRAN_WRAP(dtpsv)( char *uplo, char *trans, char *diag, int *n, double *AP, double *x, int *incx ) ; #endif extern void NL_FORTRAN_WRAP(dgemv)( char *trans, int *m, int *n, double *alpha, double *A, int *ldA, double *x, int *incx, double *beta, double *y, int *incy ) ; #endif #ifdef NEEDS_DTPSV /* DECK DTPSV */ /* Subroutine */ static int NL_FORTRAN_WRAP(dtpsv)( const char* uplo, const char* trans, const char* diag, integer* n, doublereal* ap, doublereal* x, integer* incx ) { /* System generated locals */ integer i__1, i__2; /* Local variables */ static integer info; static doublereal temp; static integer i__, j, k; /* extern logical lsame_(); */ static integer kk, ix, jx, kx; /* extern int xerbla_(); */ static logical nounit; /* ***BEGIN PROLOGUE DTPSV */ /* ***PURPOSE Solve one of the systems of equations. */ /* ***LIBRARY SLATEC (BLAS) */ /* ***CATEGORY D1B4 */ /* ***TYPE DOUBLE PRECISION (STPSV-S, DTPSV-D, CTPSV-C) */ /* ***KEYWORDS LEVEL 2 BLAS, LINEAR ALGEBRA */ /* ***AUTHOR Dongarra, J. J., (ANL) */ /* Du Croz, J., (NAG) */ /* Hammarling, S., (NAG) */ /* Hanson, R. J., (SNLA) */ /* ***DESCRIPTION */ /* DTPSV solves one of the systems of equations */ /* A*x = b, or A'*x = b, */ /* where b and x are n element vectors and A is an n by n unit, or */ /* non-unit, upper or lower triangular matrix, supplied in packed form. */ /* No test for singularity or near-singularity is included in this */ /* routine. Such tests must be performed before calling this routine. */ /* Parameters */ /* ========== */ /* UPLO - CHARACTER*1. */ /* On entry, UPLO specifies whether the matrix is an upper or */ /* lower triangular matrix as follows: */ /* UPLO = 'U' or 'u' A is an upper triangular matrix. */ /* UPLO = 'L' or 'l' A is a lower triangular matrix. */ /* Unchanged on exit. */ /* TRANS - CHARACTER*1. */ /* On entry, TRANS specifies the equations to be solved as */ /* follows: */ /* TRANS = 'N' or 'n' A*x = b. */ /* TRANS = 'T' or 't' A'*x = b. */ /* TRANS = 'C' or 'c' A'*x = b. */ /* Unchanged on exit. */ /* DIAG - CHARACTER*1. */ /* On entry, DIAG specifies whether or not A is unit */ /* triangular as follows: */ /* DIAG = 'U' or 'u' A is assumed to be unit triangular. */ /* DIAG = 'N' or 'n' A is not assumed to be unit */ /* triangular. */ /* Unchanged on exit. */ /* N - INTEGER. */ /* On entry, N specifies the order of the matrix A. */ /* N must be at least zero. */ /* Unchanged on exit. */ /* AP - DOUBLE PRECISION array of DIMENSION at least */ /* ( ( n*( n + 1))/2). */ /* Before entry with UPLO = 'U' or 'u', the array AP must */ /* contain the upper triangular matrix packed sequentially, */ /* column by column, so that AP( 1 ) contains a( 1, 1 ), */ /* AP( 2 ) and AP( 3 ) contain a( 1, 2 ) and a( 2, 2 ) */ /* respectively, and so on. */ /* Before entry with UPLO = 'L' or 'l', the array AP must */ /* contain the lower triangular matrix packed sequentially, */ /* column by column, so that AP( 1 ) contains a( 1, 1 ), */ /* AP( 2 ) and AP( 3 ) contain a( 2, 1 ) and a( 3, 1 ) */ /* respectively, and so on. */ /* Note that when DIAG = 'U' or 'u', the diagonal elements of */ /* A are not referenced, but are assumed to be unity. */ /* Unchanged on exit. */ /* X - DOUBLE PRECISION array of dimension at least */ /* ( 1 + ( n - 1 )*abs( INCX ) ). */ /* Before entry, the incremented array X must contain the n */ /* element right-hand side vector b. On exit, X is overwritten */ /* with the solution vector x. */ /* INCX - INTEGER. */ /* On entry, INCX specifies the increment for the elements of */ /* X. INCX must not be zero. */ /* Unchanged on exit. */ /* ***REFERENCES Dongarra, J. J., Du Croz, J., Hammarling, S., and */ /* Hanson, R. J. An extended set of Fortran basic linear */ /* algebra subprograms. ACM TOMS, Vol. 14, No. 1, */ /* pp. 1-17, March 1988. */ /* ***ROUTINES CALLED LSAME, XERBLA */ /* ***REVISION HISTORY (YYMMDD) */ /* 861022 DATE WRITTEN */ /* 910605 Modified to meet SLATEC prologue standards. Only comment */ /* lines were modified. (BKS) */ /* ***END PROLOGUE DTPSV */ /* .. Scalar Arguments .. */ /* .. Array Arguments .. */ /* .. Parameters .. */ /* .. Local Scalars .. */ /* .. External Functions .. */ /* .. External Subroutines .. */ /* ***FIRST EXECUTABLE STATEMENT DTPSV */ /* Test the input parameters. */ /* Parameter adjustments */ --x; --ap; /* Function Body */ info = 0; if (!NL_FORTRAN_WRAP(lsame)(uplo, "U") && !NL_FORTRAN_WRAP(lsame)(uplo, "L") ) { info = 1; } else if ( !NL_FORTRAN_WRAP(lsame)(trans, "N") && !NL_FORTRAN_WRAP(lsame)(trans, "T") && !NL_FORTRAN_WRAP(lsame)(trans, "C") ) { info = 2; } else if ( !NL_FORTRAN_WRAP(lsame)(diag, "U") && !NL_FORTRAN_WRAP(lsame)(diag, "N") ) { info = 3; } else if (*n < 0) { info = 4; } else if (*incx == 0) { info = 7; } if (info != 0) { NL_FORTRAN_WRAP(xerbla)("DTPSV ", &info); return 0; } /* Quick return if possible. */ if (*n == 0) { return 0; } nounit = (logical)(NL_FORTRAN_WRAP(lsame)(diag, "N")); /* Set up the start point in X if the increment is not unity. This */ /* will be ( N - 1 )*INCX too small for descending loops. */ if (*incx <= 0) { kx = 1 - (*n - 1) * *incx; } else if (*incx != 1) { kx = 1; } /* Start the operations. In this version the elements of AP are */ /* accessed sequentially with one pass through AP. */ if (NL_FORTRAN_WRAP(lsame)(trans, "N")) { /* Form x := inv( A )*x. */ if (NL_FORTRAN_WRAP(lsame)(uplo, "U")) { kk = *n * (*n + 1) / 2; if (*incx == 1) { for (j = *n; j >= 1; --j) { if (x[j] != 0.) { if (nounit) { x[j] /= ap[kk]; } temp = x[j]; k = kk - 1; for (i__ = j - 1; i__ >= 1; --i__) { x[i__] -= temp * ap[k]; --k; /* L10: */ } } kk -= j; /* L20: */ } } else { jx = kx + (*n - 1) * *incx; for (j = *n; j >= 1; --j) { if (x[jx] != 0.) { if (nounit) { x[jx] /= ap[kk]; } temp = x[jx]; ix = jx; i__1 = kk - j + 1; for (k = kk - 1; k >= i__1; --k) { ix -= *incx; x[ix] -= temp * ap[k]; /* L30: */ } } jx -= *incx; kk -= j; /* L40: */ } } } else { kk = 1; if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[j] != 0.) { if (nounit) { x[j] /= ap[kk]; } temp = x[j]; k = kk + 1; i__2 = *n; for (i__ = j + 1; i__ <= i__2; ++i__) { x[i__] -= temp * ap[k]; ++k; /* L50: */ } } kk += *n - j + 1; /* L60: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { if (x[jx] != 0.) { if (nounit) { x[jx] /= ap[kk]; } temp = x[jx]; ix = jx; i__2 = kk + *n - j; for (k = kk + 1; k <= i__2; ++k) { ix += *incx; x[ix] -= temp * ap[k]; /* L70: */ } } jx += *incx; kk += *n - j + 1; /* L80: */ } } } } else { /* Form x := inv( A' )*x. */ if (NL_FORTRAN_WRAP(lsame)(uplo, "U")) { kk = 1; if (*incx == 1) { i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = x[j]; k = kk; i__2 = j - 1; for (i__ = 1; i__ <= i__2; ++i__) { temp -= ap[k] * x[i__]; ++k; /* L90: */ } if (nounit) { temp /= ap[kk + j - 1]; } x[j] = temp; kk += j; /* L100: */ } } else { jx = kx; i__1 = *n; for (j = 1; j <= i__1; ++j) { temp = x[jx]; ix = kx; i__2 = kk + j - 2; for (k = kk; k <= i__2; ++k) { temp -= ap[k] * x[ix]; ix += *incx; /* L110: */ } if (nounit) { temp /= ap[kk + j - 1]; } x[jx] = temp; jx += *incx; kk += j; /* L120: */ } } } else { kk = *n * (*n + 1) / 2; if (*incx == 1) { for (j = *n; j >= 1; --j) { temp = x[j]; k = kk; i__1 = j + 1; for (i__ = *n; i__ >= i__1; --i__) { temp -= ap[k] * x[i__]; --k; /* L130: */ } if (nounit) { temp /= ap[kk - *n + j]; } x[j] = temp; kk -= *n - j + 1; /* L140: */ } } else { kx += (*n - 1) * *incx; jx = kx; for (j = *n; j >= 1; --j) { temp = x[jx]; ix = kx; i__1 = kk - (*n - (j + 1)); for (k = kk; k >= i__1; --k) { temp -= ap[k] * x[ix]; ix -= *incx; /* L150: */ } if (nounit) { temp /= ap[kk - *n + j]; } x[jx] = temp; jx -= *incx; kk -= *n - j + 1; /* L160: */ } } } } return 0; /* End of DTPSV . */ } /* dtpsv_ */ #endif /* End of BLAS routines */ /* Abstract BLAS interface */ void nlBlasResetStats(NLBlas_t blas) { blas->start_time = nlCurrentTime(); blas->flops = 0; blas->used_ram[0] = 0; blas->used_ram[1] = 0; blas->max_used_ram[0] = 0; blas->max_used_ram[1] = 0; blas->sq_rnorm = 0.0; blas->sq_bnorm = 0.0; } double nlBlasGFlops(NLBlas_t blas) { double now = nlCurrentTime(); double elapsed_time = now - blas->start_time; return (NLdouble)(blas->flops) / (elapsed_time * 1e9); } NLulong nlBlasUsedRam(NLBlas_t blas, NLmemoryType type) { return blas->used_ram[type]; } NLulong nlBlasMaxUsedRam(NLBlas_t blas, NLmemoryType type) { return blas->max_used_ram[type]; } NLboolean nlBlasHasUnifiedMemory(NLBlas_t blas) { return blas->has_unified_memory; } static void* host_blas_malloc( NLBlas_t blas, NLmemoryType type, size_t size ) { nl_arg_used(type); blas->used_ram[type] += (NLulong)size; blas->max_used_ram[type] = MAX( blas->max_used_ram[type],blas->used_ram[type] ); return malloc(size); } static void host_blas_free( NLBlas_t blas, NLmemoryType type, size_t size, void* ptr ) { nl_arg_used(type); blas->used_ram[type] -= (NLulong)size; free(ptr); } static void host_blas_memcpy( NLBlas_t blas, void* to, NLmemoryType to_type, void* from, NLmemoryType from_type, size_t size ) { nl_arg_used(blas); nl_arg_used(to_type); nl_arg_used(from_type); memcpy(to,from,size); } static void host_blas_dcopy( NLBlas_t blas, int n, const double *x, int incx, double *y, int incy ) { nl_arg_used(blas); NL_FORTRAN_WRAP(dcopy)(&n,(double*)x,&incx,y,&incy); } static double host_blas_ddot( NLBlas_t blas, int n, const double *x, int incx, const double *y, int incy ) { blas->flops += (NLulong)(2*n); return NL_FORTRAN_WRAP(ddot)(&n,(double*)x,&incx,(double*)y,&incy); } static double host_blas_dnrm2( NLBlas_t blas, int n, const double *x, int incx ) { blas->flops += (NLulong)(2*n); return NL_FORTRAN_WRAP(dnrm2)(&n,(double*)x,&incx); } static void host_blas_daxpy( NLBlas_t blas, int n, double a, const double *x, int incx, double *y, int incy ) { blas->flops += (NLulong)(2*n); NL_FORTRAN_WRAP(daxpy)(&n,&a,(double*)x,&incx,y,&incy); } static void host_blas_dscal( NLBlas_t blas, int n, double a, double *x, int incx ) { blas->flops += (NLulong)n; NL_FORTRAN_WRAP(dscal)(&n,&a,x,&incx); } static void host_blas_dgemv( NLBlas_t blas, MatrixTranspose trans, int m, int n, double alpha, const double *A, int ldA, const double *x, int incx, double beta, double *y, int incy ) { static const char *T[3] = { "N", "T", 0 }; nl_arg_used(blas); NL_FORTRAN_WRAP(dgemv)( T[(int)trans],&m,&n,&alpha,(double*)A,&ldA, (double*)x,&incx,&beta,y,&incy ); /* TODO: update flops */ } static void host_blas_dtpsv( NLBlas_t blas, MatrixTriangle uplo, MatrixTranspose trans, MatrixUnitTriangular diag, int n, const double *AP, double *x, int incx ) { static const char *UL[2] = { "U", "L" }; static const char *T[3] = { "N", "T", 0 }; static const char *D[2] = { "U", "N" }; nl_arg_used(blas); NL_FORTRAN_WRAP(dtpsv)( UL[(int)uplo],T[(int)trans],D[(int)diag],&n,(double*)AP,x,&incx ); /* TODO: update flops */ } NLBlas_t nlHostBlas() { static NLboolean initialized = NL_FALSE; static struct NLBlas blas; if(!initialized) { memset(&blas, 0, sizeof(blas)); blas.has_unified_memory = NL_TRUE; blas.Malloc = host_blas_malloc; blas.Free = host_blas_free; blas.Memcpy = host_blas_memcpy; blas.Dcopy = host_blas_dcopy; blas.Ddot = host_blas_ddot; blas.Dnrm2 = host_blas_dnrm2; blas.Daxpy = host_blas_daxpy; blas.Dscal = host_blas_dscal; blas.Dgemv = host_blas_dgemv; blas.Dtpsv = host_blas_dtpsv; nlBlasResetStats(&blas); initialized = NL_TRUE; } return &blas; } /******* extracted from nl_iterative_solvers.c *******/ /* Solvers */ /* * The implementation of the solvers is inspired by * the lsolver library, by Christian Badura, available from: * http://www.mathematik.uni-freiburg.de * /IAM/Research/projectskr/lin_solver/ * * About the Conjugate Gradient, details can be found in: * Ashby, Manteuffel, Saylor * A taxononmy for conjugate gradient methods * SIAM J Numer Anal 27, 1542-1568 (1990) * * This version is completely abstract, the same code can be used for * CPU/GPU, dense matrix / sparse matrix etc... * Abstraction is realized through: * - Abstract blas interface (NLBlas_t), that can implement BLAS * operations on the CPU or on the GPU. * - Abstract matrix interface (NLMatrix), that can implement different * versions of matrix x vector product (CPU/GPU, sparse/dense ...) */ static NLuint nlSolveSystem_CG( NLBlas_t blas, NLMatrix M, NLdouble* b, NLdouble* x, double eps, NLuint max_iter ) { NLint N = (NLint)M->m; NLdouble *g = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *r = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *p = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLuint its=0; NLdouble t, tau, sig, rho, gam; NLdouble b_square=blas->Ddot(blas,N,b,1,b,1); NLdouble err=eps*eps*b_square; NLdouble curr_err; nlMultMatrixVector(M,x,g); blas->Daxpy(blas,N,-1.,b,1,g,1); blas->Dscal(blas,N,-1.,g,1); blas->Dcopy(blas,N,g,1,r,1); curr_err = blas->Ddot(blas,N,g,1,g,1); while ( curr_err >err && its < max_iter) { if(nlCurrentContext != NULL) { if(nlCurrentContext->progress_func != NULL) { nlCurrentContext->progress_func(its, max_iter, curr_err, err); } if(nlCurrentContext->verbose && !(its % 100)) { nl_printf ( "%d : %.10e -- %.10e\n", its, curr_err, err ); } } nlMultMatrixVector(M,r,p); rho=blas->Ddot(blas,N,p,1,p,1); sig=blas->Ddot(blas,N,r,1,p,1); tau=blas->Ddot(blas,N,g,1,r,1); t=tau/sig; blas->Daxpy(blas,N,t,r,1,x,1); blas->Daxpy(blas,N,-t,p,1,g,1); gam=(t*t*rho-tau)/tau; blas->Dscal(blas,N,gam,r,1); blas->Daxpy(blas,N,1.,g,1,r,1); ++its; curr_err = blas->Ddot(blas,N,g,1,g,1); } NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, g); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, r); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, p); blas->sq_bnorm = b_square; blas->sq_rnorm = curr_err; return its; } static NLuint nlSolveSystem_PRE_CG( NLBlas_t blas, NLMatrix M, NLMatrix P, NLdouble* b, NLdouble* x, double eps, NLuint max_iter ) { NLint N = (NLint)M->n; NLdouble* r = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble* d = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble* h = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *Ad = h; NLuint its=0; NLdouble rh, alpha, beta; NLdouble b_square = blas->Ddot(blas,N,b,1,b,1); NLdouble err=eps*eps*b_square; NLdouble curr_err; nlMultMatrixVector(M,x,r); blas->Daxpy(blas,N,-1.,b,1,r,1); nlMultMatrixVector(P,r,d); blas->Dcopy(blas,N,d,1,h,1); rh=blas->Ddot(blas,N,r,1,h,1); curr_err = blas->Ddot(blas,N,r,1,r,1); while ( curr_err >err && its < max_iter) { if(nlCurrentContext != NULL) { if(nlCurrentContext->progress_func != NULL) { nlCurrentContext->progress_func(its, max_iter, curr_err, err); } if( nlCurrentContext->verbose && !(its % 100)) { nl_printf ( "%d : %.10e -- %.10e\n", its, curr_err, err ); } } nlMultMatrixVector(M,d,Ad); alpha=rh/blas->Ddot(blas,N,d,1,Ad,1); blas->Daxpy(blas,N,-alpha,d,1,x,1); blas->Daxpy(blas,N,-alpha,Ad,1,r,1); nlMultMatrixVector(P,r,h); beta=1./rh; rh=blas->Ddot(blas,N,r,1,h,1); beta*=rh; blas->Dscal(blas,N,beta,d,1); blas->Daxpy(blas,N,1.,h,1,d,1); ++its; curr_err = blas->Ddot(blas,N,r,1,r,1); } NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, r); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, d); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, h); blas->sq_bnorm = b_square; blas->sq_rnorm = curr_err; return its; } static NLuint nlSolveSystem_BICGSTAB( NLBlas_t blas, NLMatrix M, NLdouble* b, NLdouble* x, double eps, NLuint max_iter ) { NLint N = (NLint)M->n; NLdouble *rT = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *d = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *h = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *u = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *Ad = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *t = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *s = h; NLdouble rTh, rTAd, rTr, alpha, beta, omega, st, tt; NLuint its=0; NLdouble b_square = blas->Ddot(blas,N,b,1,b,1); NLdouble err=eps*eps*b_square; NLdouble *r = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); nlMultMatrixVector(M,x,r); blas->Daxpy(blas,N,-1.,b,1,r,1); blas->Dcopy(blas,N,r,1,d,1); blas->Dcopy(blas,N,d,1,h,1); blas->Dcopy(blas,N,h,1,rT,1); nl_assert( blas->Ddot(blas,N,rT,1,rT,1)>1e-40 ); rTh=blas->Ddot(blas,N,rT,1,h,1); rTr=blas->Ddot(blas,N,r,1,r,1); while ( rTr>err && its < max_iter) { if(nlCurrentContext != NULL) { if(nlCurrentContext->progress_func != NULL) { nlCurrentContext->progress_func(its, max_iter, rTr, err); } if( (nlCurrentContext->verbose) && !(its % 100)) { nl_printf ( "%d : %.10e -- %.10e\n", its, rTr, err ); } } nlMultMatrixVector(M,d,Ad); rTAd=blas->Ddot(blas,N,rT,1,Ad,1); nl_assert( fabs(rTAd)>1e-40 ); alpha=rTh/rTAd; blas->Daxpy(blas,N,-alpha,Ad,1,r,1); blas->Dcopy(blas,N,h,1,s,1); blas->Daxpy(blas,N,-alpha,Ad,1,s,1); nlMultMatrixVector(M,s,t); blas->Daxpy(blas,N,1.,t,1,u,1); blas->Dscal(blas,N,alpha,u,1); st=blas->Ddot(blas,N,s,1,t,1); tt=blas->Ddot(blas,N,t,1,t,1); if ( fabs(st)<1e-40 || fabs(tt)<1e-40 ) { omega = 0.; } else { omega = st/tt; } blas->Daxpy(blas,N,-omega,t,1,r,1); blas->Daxpy(blas,N,-alpha,d,1,x,1); blas->Daxpy(blas,N,-omega,s,1,x,1); blas->Dcopy(blas,N,s,1,h,1); blas->Daxpy(blas,N,-omega,t,1,h,1); beta=(alpha/omega)/rTh; rTh=blas->Ddot(blas,N,rT,1,h,1); beta*=rTh; blas->Dscal(blas,N,beta,d,1); blas->Daxpy(blas,N,1.,h,1,d,1); blas->Daxpy(blas,N,-beta*omega,Ad,1,d,1); rTr=blas->Ddot(blas,N,r,1,r,1); ++its; } NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, r); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, rT); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, d); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, h); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, u); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, Ad); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, t); blas->sq_bnorm = b_square; blas->sq_rnorm = rTr; return its; } static NLuint nlSolveSystem_PRE_BICGSTAB( NLBlas_t blas, NLMatrix M, NLMatrix P, NLdouble* b, NLdouble* x, double eps, NLuint max_iter ) { NLint N = (NLint)M->n; NLdouble *rT = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *d = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *h = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *u = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *Sd = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *t = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *aux = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); NLdouble *s = h; NLdouble rTh, rTSd, rTr, alpha, beta, omega, st, tt; NLuint its=0; NLdouble b_square = blas->Ddot(blas,N,b,1,b,1); NLdouble err = eps*eps*b_square; NLdouble *r = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, N); nlMultMatrixVector(M,x,r); blas->Daxpy(blas,N,-1.,b,1,r,1); nlMultMatrixVector(P,r,d); blas->Dcopy(blas,N,d,1,h,1); blas->Dcopy(blas,N,h,1,rT,1); nl_assert( blas->Ddot(blas,N,rT,1,rT,1)>1e-40 ); rTh=blas->Ddot(blas,N,rT,1,h,1); rTr=blas->Ddot(blas,N,r,1,r,1); while ( rTr>err && its < max_iter) { if(nlCurrentContext != NULL) { if(nlCurrentContext->progress_func != NULL) { nlCurrentContext->progress_func(its, max_iter, rTr, err); } if( (nlCurrentContext->verbose) && !(its % 100)) { nl_printf ( "%d : %.10e -- %.10e\n", its, rTr, err ); } } nlMultMatrixVector(M,d,aux); nlMultMatrixVector(P,aux,Sd); rTSd=blas->Ddot(blas,N,rT,1,Sd,1); nl_assert( fabs(rTSd)>1e-40 ); alpha=rTh/rTSd; blas->Daxpy(blas,N,-alpha,aux,1,r,1); blas->Dcopy(blas,N,h,1,s,1); blas->Daxpy(blas,N,-alpha,Sd,1,s,1); nlMultMatrixVector(M,s,aux); nlMultMatrixVector(P,aux,t); blas->Daxpy(blas,N,1.,t,1,u,1); blas->Dscal(blas,N,alpha,u,1); st=blas->Ddot(blas,N,s,1,t,1); tt=blas->Ddot(blas,N,t,1,t,1); if ( fabs(st)<1e-40 || fabs(tt)<1e-40 ) { omega = 0.; } else { omega = st/tt; } blas->Daxpy(blas,N,-omega,aux,1,r,1); blas->Daxpy(blas,N,-alpha,d,1,x,1); blas->Daxpy(blas,N,-omega,s,1,x,1); blas->Dcopy(blas,N,s,1,h,1); blas->Daxpy(blas,N,-omega,t,1,h,1); beta=(alpha/omega)/rTh; rTh=blas->Ddot(blas,N,rT,1,h,1); beta*=rTh; blas->Dscal(blas,N,beta,d,1); blas->Daxpy(blas,N,1.,h,1,d,1); blas->Daxpy(blas,N,-beta*omega,Sd,1,d,1); rTr=blas->Ddot(blas,N,r,1,r,1); ++its; } NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, r); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, rT); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, d); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, h); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, u); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, Sd); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, t); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, N, aux); blas->sq_bnorm = b_square; blas->sq_rnorm = rTr; return its; } /* * Note: this one cannot be executed on device (GPU) * because it directly manipulates the vectors. */ static NLuint nlSolveSystem_GMRES( NLBlas_t blas, NLMatrix M, NLdouble* b, NLdouble* x, double eps, NLuint max_iter, NLuint inner_iter ) { NLint n = (NLint)M->n; NLint m = (NLint)inner_iter; typedef NLdouble *NLdoubleP; NLdouble *V = NL_NEW_ARRAY(NLdouble, n*(m+1) ); NLdouble *U = NL_NEW_ARRAY(NLdouble, m*(m+1)/2 ); NLdouble *r = NL_NEW_ARRAY(NLdouble, n ); NLdouble *y = NL_NEW_ARRAY(NLdouble, m+1 ); NLdouble *c = NL_NEW_ARRAY(NLdouble, m ); NLdouble *s = NL_NEW_ARRAY(NLdouble, m ); NLdouble **v = NL_NEW_ARRAY(NLdoubleP, m+1 ); NLint i, j, io, uij, u0j; NLint its = -1; NLdouble beta, h, rd, dd, nrm2b; /* * The way it is written, this routine will not * work on the GPU since it directly modifies the * vectors. */ nl_assert(nlBlasHasUnifiedMemory(blas)); for ( i=0; i<=m; ++i ){ v[i]=V+i*n; } nrm2b=blas->Dnrm2(blas,n,b,1); io=0; do { /* outer loop */ ++io; nlMultMatrixVector(M,x,r); blas->Daxpy(blas,n,-1.,b,1,r,1); beta=blas->Dnrm2(blas,n,r,1); blas->Dcopy(blas,n,r,1,v[0],1); blas->Dscal(blas,n,1./beta,v[0],1); y[0]=beta; j=0; uij=0; do { /* inner loop: j=0,...,m-1 */ u0j=uij; nlMultMatrixVector(M,v[j],v[j+1]); blas->Dgemv( blas,Transpose,n,j+1,1.,V,n,v[j+1],1,0.,U+u0j,1 ); blas->Dgemv( blas,NoTranspose,n,j+1,-1.,V,n,U+u0j,1,1.,v[j+1],1 ); h=blas->Dnrm2(blas,n,v[j+1],1); blas->Dscal(blas,n,1./h,v[j+1],1); for (i=0; i<j; ++i ) { /* rotiere neue Spalte */ double tmp = c[i]*U[uij]-s[i]*U[uij+1]; U[uij+1] = s[i]*U[uij]+c[i]*U[uij+1]; U[uij] = tmp; ++uij; } { /* berechne neue Rotation */ rd = U[uij]; dd = sqrt(rd*rd+h*h); c[j] = rd/dd; s[j] = -h/dd; U[uij] = dd; ++uij; } { /* rotiere rechte Seite y (vorher: y[j+1]=0) */ y[j+1] = s[j]*y[j]; y[j] = c[j]*y[j]; } ++j; } while ( j<m && fabs(y[j])>=eps*nrm2b ); { /* minimiere bzgl Y */ blas->Dtpsv( blas, UpperTriangle, NoTranspose, NotUnitTriangular, j,U,y,1 ); /* correct X */ blas->Dgemv(blas,NoTranspose,n,j,-1.,V,n,y,1,1.,x,1); } } while ( fabs(y[j])>=eps*nrm2b && (m*(io-1)+j) < (NLint)max_iter); /* Count the inner iterations */ its = m*(io-1)+j; blas->sq_bnorm = nrm2b*nrm2b; blas->sq_rnorm = y[j]*y[j]; NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, V); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, U); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, r); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, y); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, c); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, s); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, n, v); return (NLuint)its; } /* Main driver routine */ NLuint nlSolveSystemIterative( NLBlas_t blas, NLMatrix M, NLMatrix P, NLdouble* b_in, NLdouble* x_in, NLenum solver, double eps, NLuint max_iter, NLuint inner_iter ) { NLuint N = M->n; NLuint result=0; NLdouble rnorm=0.0; NLdouble bnorm=0.0; double* b = b_in; double* x = x_in; nl_assert(M->m == M->n); if(!nlBlasHasUnifiedMemory(blas)) { b = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, (int)M->n); blas->Memcpy( blas, b, NL_DEVICE_MEMORY, b_in, NL_HOST_MEMORY, (size_t)N*sizeof(double) ); x = NL_NEW_VECTOR(blas, NL_DEVICE_MEMORY, (int)M->n); blas->Memcpy( blas, x, NL_DEVICE_MEMORY, x_in, NL_HOST_MEMORY, (size_t)N*sizeof(double) ); } switch(solver) { case NL_CG: if(P == NULL) { result = nlSolveSystem_CG(blas,M,b,x,eps,max_iter); } else { result = nlSolveSystem_PRE_CG(blas,M,P,b,x,eps,max_iter); } break; case NL_BICGSTAB: if(P == NULL) { result = nlSolveSystem_BICGSTAB(blas,M,b,x,eps,max_iter); } else { result = nlSolveSystem_PRE_BICGSTAB(blas,M,P,b,x,eps,max_iter); } break; case NL_GMRES: result = nlSolveSystem_GMRES(blas,M,b,x,eps,max_iter,inner_iter); break; default: nl_assert_not_reached; } /* Get residual norm and rhs norm from BLAS context */ if(nlCurrentContext != NULL) { bnorm = sqrt(blas->sq_bnorm); rnorm = sqrt(blas->sq_rnorm); if(bnorm == 0.0) { nlCurrentContext->error = rnorm; if(nlCurrentContext->verbose) { nl_printf("in OpenNL : ||Ax-b|| = %e\n",nlCurrentContext->error); } } else { nlCurrentContext->error = rnorm/bnorm; if(nlCurrentContext->verbose) { nl_printf("in OpenNL : ||Ax-b||/||b|| = %e\n", nlCurrentContext->error ); } } } nlCurrentContext->used_iterations = result; if(!nlBlasHasUnifiedMemory(blas)) { blas->Memcpy( blas, x_in, NL_HOST_MEMORY, x, NL_DEVICE_MEMORY, (size_t)N*sizeof(double) ); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, (int)M->n, x); NL_DELETE_VECTOR(blas, NL_DEVICE_MEMORY, (int)M->n, b); } return result; } /******* extracted from nl_preconditioners.c *******/ typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; NLdouble* diag_inv; } NLJacobiPreconditioner; static void nlJacobiPreconditionerDestroy(NLJacobiPreconditioner* M) { NL_DELETE_ARRAY(M->diag_inv); } static void nlJacobiPreconditionerMult( NLJacobiPreconditioner* M, const double* x, double* y ) { NLuint i; for(i=0; i<M->n; ++i) { y[i] = x[i] * M->diag_inv[i]; } nlHostBlas()->flops += (NLulong)(M->n); } NLMatrix nlNewJacobiPreconditioner(NLMatrix M_in) { NLSparseMatrix* M = NULL; NLJacobiPreconditioner* result = NULL; NLuint i; nl_assert(M_in->type == NL_MATRIX_SPARSE_DYNAMIC); nl_assert(M_in->m == M_in->n); M = (NLSparseMatrix*)M_in; result = NL_NEW(NLJacobiPreconditioner); result->m = M->m; result->n = M->n; result->type = NL_MATRIX_OTHER; result->destroy_func = (NLDestroyMatrixFunc)nlJacobiPreconditionerDestroy; result->mult_func = (NLMultMatrixVectorFunc)nlJacobiPreconditionerMult; result->diag_inv = NL_NEW_ARRAY(double, M->n); for(i=0; i<M->n; ++i) { result->diag_inv[i] = (M->diag[i] == 0.0) ? 1.0 : 1.0/M->diag[i]; } return (NLMatrix)result; } typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; NLSparseMatrix* M; double omega; NLdouble* work; } NLSSORPreconditioner; static void nlSSORPreconditionerDestroy(NLSSORPreconditioner* M) { NL_DELETE_ARRAY(M->work); } static void nlSparseMatrixMultLowerInverse( NLSparseMatrix* A, const NLdouble* x, NLdouble* y, double omega ) { NLuint n = A->n; NLdouble* diag = A->diag; NLuint i; NLuint ij; NLCoeff* c = NULL; NLdouble S; nl_assert(A->storage & NL_MATRIX_STORE_SYMMETRIC); nl_assert(A->storage & NL_MATRIX_STORE_ROWS); for(i=0; i<n; i++) { NLRowColumn* Ri = &(A->row[i]); S = 0; for(ij=0; ij < Ri->size; ij++) { c = &(Ri->coeff[ij]); nl_parano_assert(c->index <= i); if(c->index != i) { S += c->value * y[c->index]; } } nlHostBlas()->flops += (NLulong)(2*Ri->size); y[i] = (x[i] - S) * omega / diag[i]; } nlHostBlas()->flops += (NLulong)(n*3); } static void nlSparseMatrixMultUpperInverse( NLSparseMatrix* A, const NLdouble* x, NLdouble* y, NLdouble omega ) { NLuint n = A->n; NLdouble* diag = A->diag; NLint i; NLuint ij; NLCoeff* c = NULL; NLdouble S; nl_assert(A->storage & NL_MATRIX_STORE_SYMMETRIC); nl_assert(A->storage & NL_MATRIX_STORE_COLUMNS); for(i=(NLint)(n-1); i>=0; i--) { NLRowColumn* Ci = &(A->column[i]); S = 0; for(ij=0; ij < Ci->size; ij++) { c = &(Ci->coeff[ij]); nl_parano_assert(c->index >= i); if((NLint)(c->index) != i) { S += c->value * y[c->index]; } } nlHostBlas()->flops += (NLulong)(2*Ci->size); y[i] = (x[i] - S) * omega / diag[i]; } nlHostBlas()->flops += (NLulong)(n*3); } static void nlSSORPreconditionerMult( NLSSORPreconditioner* P, const double* x, double* y ) { NLdouble* diag = P->M->diag; NLuint i; nlSparseMatrixMultLowerInverse( P->M, x, P->work, P->omega ); for(i=0; i<P->n; i++) { P->work[i] *= (diag[i] / P->omega); } nlHostBlas()->flops += (NLulong)(P->n); nlSparseMatrixMultUpperInverse( P->M, P->work, y, P->omega ); nlHostBlas()->Dscal(nlHostBlas(),(NLint)P->n, 2.0 - P->omega, y, 1); } NLMatrix nlNewSSORPreconditioner(NLMatrix M_in, double omega) { NLSparseMatrix* M = NULL; NLSSORPreconditioner* result = NULL; nl_assert(M_in->type == NL_MATRIX_SPARSE_DYNAMIC); nl_assert(M_in->m == M_in->n); M = (NLSparseMatrix*)M_in; result = NL_NEW(NLSSORPreconditioner); result->m = M->m; result->n = M->n; result->type = NL_MATRIX_OTHER; result->destroy_func = (NLDestroyMatrixFunc)nlSSORPreconditionerDestroy; result->mult_func = (NLMultMatrixVectorFunc)nlSSORPreconditionerMult; result->M = M; result->work = NL_NEW_ARRAY(NLdouble, result->n); result->omega = omega; return (NLMatrix)result; } /******* extracted from nl_superlu.c *******/ #ifdef NL_OS_UNIX # ifdef NL_OS_APPLE # define SUPERLU_LIB_NAME "libsuperlu_5.dylib" # else # define SUPERLU_LIB_NAME "libsuperlu.so" # endif #else # define SUPERLU_LIB_NAME "libsuperlu.xxx" #endif typedef enum { SLU_NC, /* column-wise, no supernode */ SLU_NCP, /* column-wise, column-permuted, no supernode (The consecutive columns of nonzeros, after permutation, may not be stored contiguously.) */ SLU_NR, /* row-wize, no supernode */ SLU_SC, /* column-wise, supernode */ SLU_SCP, /* supernode, column-wise, permuted */ SLU_SR, /* row-wise, supernode */ SLU_DN, /* Fortran style column-wise storage for dense matrix */ SLU_NR_loc /* distributed compressed row format */ } Stype_t; typedef enum { SLU_S, /* single */ SLU_D, /* double */ SLU_C, /* single complex */ SLU_Z /* double complex */ } Dtype_t; typedef enum { SLU_GE, /* general */ SLU_TRLU, /* lower triangular, unit diagonal */ SLU_TRUU, /* upper triangular, unit diagonal */ SLU_TRL, /* lower triangular */ SLU_TRU, /* upper triangular */ SLU_SYL, /* symmetric, store lower half */ SLU_SYU, /* symmetric, store upper half */ SLU_HEL, /* Hermitian, store lower half */ SLU_HEU /* Hermitian, store upper half */ } Mtype_t; typedef int int_t; typedef struct { int_t nnz; /* number of nonzeros in the matrix */ void *nzval; /* pointer to array of nonzero values, packed by raw */ int_t *colind; /* pointer to array of columns indices of the nonzeros */ int_t *rowptr; /* pointer to array of beginning of rows in nzval[] and colind[] */ /* Note: Zero-based indexing is used; rowptr[] has nrow+1 entries, the last one pointing beyond the last row, so that rowptr[nrow] = nnz. */ } NRformat; typedef struct { Stype_t Stype; /* Storage type: interprets the storage structure pointed to by *Store. */ Dtype_t Dtype; /* Data type. */ Mtype_t Mtype; /* Matrix type: describes the mathematical property of the matrix. */ int_t nrow; /* number of rows */ int_t ncol; /* number of columns */ void *Store; /* pointer to the actual storage of the matrix */ } SuperMatrix; /* Stype == SLU_DN */ typedef struct { int_t lda; /* leading dimension */ void *nzval; /* array of size lda*ncol to represent a dense matrix */ } DNformat; typedef enum {NO, YES} yes_no_t; typedef enum {DOFACT, SamePattern, SamePattern_SameRowPerm, FACTORED} fact_t; typedef enum {NOROWPERM, LargeDiag, MY_PERMR} rowperm_t; typedef enum {NATURAL, MMD_ATA, MMD_AT_PLUS_A, COLAMD, METIS_AT_PLUS_A, PARMETIS, ZOLTAN, MY_PERMC} colperm_t; typedef enum {NOTRANS, TRANS, CONJ} trans_t; typedef enum {NOEQUIL, ROW, COL, BOTH} DiagScale_t; typedef enum {NOREFINE, SLU_SINGLE=1, SLU_DOUBLE, SLU_EXTRA} IterRefine_t; typedef enum {LUSUP, UCOL, LSUB, USUB, LLVL, ULVL} MemType; typedef enum {HEAD, TAIL} stack_end_t; typedef enum {SYSTEM, USER} LU_space_t; typedef enum {ONE_NORM, TWO_NORM, INF_NORM} norm_t; typedef enum {SILU, SMILU_1, SMILU_2, SMILU_3} milu_t; typedef struct { fact_t Fact; yes_no_t Equil; colperm_t ColPerm; trans_t Trans; IterRefine_t IterRefine; double DiagPivotThresh; yes_no_t SymmetricMode; yes_no_t PivotGrowth; yes_no_t ConditionNumber; rowperm_t RowPerm; int ILU_DropRule; double ILU_DropTol; /* threshold for dropping */ double ILU_FillFactor; /* gamma in the secondary dropping */ norm_t ILU_Norm; /* infinity-norm, 1-norm, or 2-norm */ double ILU_FillTol; /* threshold for zero pivot perturbation */ milu_t ILU_MILU; double ILU_MILU_Dim; /* Dimension of PDE (if available) */ yes_no_t ParSymbFact; yes_no_t ReplaceTinyPivot; /* used in SuperLU_DIST */ yes_no_t SolveInitialized; yes_no_t RefineInitialized; yes_no_t PrintStat; int nnzL, nnzU; /* used to store nnzs for now */ int num_lookaheads; /* num of levels in look-ahead */ yes_no_t lookahead_etree; /* use etree computed from the serial symbolic factorization */ yes_no_t SymPattern; /* symmetric factorization */ } superlu_options_t; typedef void* superlu_options_ptr; typedef float flops_t; typedef unsigned char Logical; typedef struct { int *panel_histo; /* histogram of panel size distribution */ double *utime; /* running time at various phases */ flops_t *ops; /* operation count at various phases */ int TinyPivots; /* number of tiny pivots */ int RefineSteps; /* number of iterative refinement steps */ int expansions; /* number of memory expansions (SuperLU4) */ } SuperLUStat_t; /*! \brief Headers for 4 types of dynamatically managed memory */ typedef struct e_node { int size; /* length of the memory that has been used */ void *mem; /* pointer to the new malloc'd store */ } ExpHeader; typedef struct { int size; int used; int top1; /* grow upward, relative to &array[0] */ int top2; /* grow downward */ void *array; } LU_stack_t; typedef struct { int *xsup; /* supernode and column mapping */ int *supno; int *lsub; /* compressed L subscripts */ int *xlsub; void *lusup; /* L supernodes */ int *xlusup; void *ucol; /* U columns */ int *usub; int *xusub; int nzlmax; /* current max size of lsub */ int nzumax; /* " " " ucol */ int nzlumax; /* " " " lusup */ int n; /* number of columns in the matrix */ LU_space_t MemModel; /* 0 - system malloc'd; 1 - user provided */ int num_expansions; ExpHeader *expanders; /* Array of pointers to 4 types of memory */ LU_stack_t stack; /* use user supplied memory */ } GlobalLU_t; typedef void (*FUNPTR_set_default_options)(superlu_options_ptr options); typedef void (*FUNPTR_ilu_set_default_options)(superlu_options_ptr options); typedef void (*FUNPTR_StatInit)(SuperLUStat_t *); typedef void (*FUNPTR_StatFree)(SuperLUStat_t *); typedef void (*FUNPTR_dCreate_CompCol_Matrix)( SuperMatrix *, int, int, int, const double *, const int *, const int *, Stype_t, Dtype_t, Mtype_t); typedef void (*FUNPTR_dCreate_Dense_Matrix)( SuperMatrix *, int, int, const double *, int, Stype_t, Dtype_t, Mtype_t); typedef void (*FUNPTR_Destroy_SuperNode_Matrix)(SuperMatrix *); typedef void (*FUNPTR_Destroy_CompCol_Matrix)(SuperMatrix *); typedef void (*FUNPTR_Destroy_CompCol_Permuted)(SuperMatrix *); typedef void (*FUNPTR_Destroy_SuperMatrix_Store)(SuperMatrix *); typedef void (*FUNPTR_dgssv)( superlu_options_ptr, SuperMatrix *, int *, int *, SuperMatrix *, SuperMatrix *, SuperMatrix *, SuperLUStat_t *, int * ); typedef void (*FUNPTR_dgstrs)( trans_t, SuperMatrix *, SuperMatrix *, int *, int *, SuperMatrix *, SuperLUStat_t*, int * ); typedef void (*FUNPTR_get_perm_c)(int, SuperMatrix *, int *); typedef void (*FUNPTR_sp_preorder)( superlu_options_t *, SuperMatrix*, int*, int*, SuperMatrix* ); typedef int (*FUNPTR_sp_ienv)(int); typedef int (*FUNPTR_input_error)(const char *, int *); typedef void (*FUNPTR_dgstrf) (superlu_options_t *options, SuperMatrix *A, int relax, int panel_size, int *etree, void *work, int lwork, int *perm_c, int *perm_r, SuperMatrix *L, SuperMatrix *U, GlobalLU_t *Glu, /* persistent to facilitate multiple factorizations */ SuperLUStat_t *stat, int *info ); typedef struct { FUNPTR_set_default_options set_default_options; FUNPTR_ilu_set_default_options ilu_set_default_options; FUNPTR_StatInit StatInit; FUNPTR_StatFree StatFree; FUNPTR_dCreate_CompCol_Matrix dCreate_CompCol_Matrix; FUNPTR_dCreate_Dense_Matrix dCreate_Dense_Matrix; FUNPTR_Destroy_SuperNode_Matrix Destroy_SuperNode_Matrix; FUNPTR_Destroy_CompCol_Matrix Destroy_CompCol_Matrix; FUNPTR_Destroy_CompCol_Permuted Destroy_CompCol_Permuted; FUNPTR_Destroy_SuperMatrix_Store Destroy_SuperMatrix_Store; FUNPTR_dgssv dgssv; FUNPTR_dgstrs dgstrs; FUNPTR_get_perm_c get_perm_c; FUNPTR_sp_preorder sp_preorder; FUNPTR_sp_ienv sp_ienv; FUNPTR_dgstrf dgstrf; FUNPTR_input_error input_error; NLdll DLL_handle; } SuperLUContext; static SuperLUContext* SuperLU() { static SuperLUContext context; static NLboolean init = NL_FALSE; if(!init) { init = NL_TRUE; memset(&context, 0, sizeof(context)); } return &context; } NLboolean nlExtensionIsInitialized_SUPERLU() { return SuperLU()->DLL_handle != NULL && SuperLU()->set_default_options != NULL && SuperLU()->ilu_set_default_options != NULL && SuperLU()->StatInit != NULL && SuperLU()->StatFree != NULL && SuperLU()->dCreate_CompCol_Matrix != NULL && SuperLU()->dCreate_Dense_Matrix != NULL && SuperLU()->Destroy_SuperNode_Matrix != NULL && SuperLU()->Destroy_CompCol_Matrix != NULL && SuperLU()->Destroy_CompCol_Permuted != NULL && SuperLU()->Destroy_SuperMatrix_Store != NULL && SuperLU()->dgssv != NULL && SuperLU()->dgstrs != NULL && SuperLU()->get_perm_c != NULL && SuperLU()->sp_preorder != NULL && SuperLU()->sp_ienv != NULL && SuperLU()->dgstrf != NULL && SuperLU()->input_error != NULL; } static void nlTerminateExtension_SUPERLU(void) { if(SuperLU()->DLL_handle != NULL) { nlCloseDLL(SuperLU()->DLL_handle); SuperLU()->DLL_handle = NULL; } } #define find_superlu_func(name) \ if( \ ( \ SuperLU()->name = \ (FUNPTR_##name)nlFindFunction(SuperLU()->DLL_handle,#name) \ ) == NULL \ ) { \ nlError("nlInitExtension_SUPERLU","function not found"); \ nlError("nlInitExtension_SUPERLU",#name); \ return NL_FALSE; \ } NLboolean nlInitExtension_SUPERLU(void) { NLenum flags = NL_LINK_NOW | NL_LINK_USE_FALLBACK; if(nlCurrentContext == NULL || !nlCurrentContext->verbose) { flags |= NL_LINK_QUIET; } if(SuperLU()->DLL_handle != NULL) { return nlExtensionIsInitialized_SUPERLU(); } SuperLU()->DLL_handle = nlOpenDLL(SUPERLU_LIB_NAME, flags); if(SuperLU()->DLL_handle == NULL) { return NL_FALSE; } find_superlu_func(set_default_options); find_superlu_func(ilu_set_default_options); find_superlu_func(StatInit); find_superlu_func(StatFree); find_superlu_func(dCreate_CompCol_Matrix); find_superlu_func(dCreate_Dense_Matrix); find_superlu_func(Destroy_SuperNode_Matrix); find_superlu_func(Destroy_CompCol_Matrix); find_superlu_func(Destroy_CompCol_Permuted); find_superlu_func(Destroy_SuperMatrix_Store); find_superlu_func(dgssv); find_superlu_func(dgstrs); find_superlu_func(get_perm_c); find_superlu_func(sp_preorder); find_superlu_func(sp_ienv); find_superlu_func(dgstrf); find_superlu_func(input_error); atexit(nlTerminateExtension_SUPERLU); return NL_TRUE; } typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; SuperMatrix L; SuperMatrix U; int* perm_r; int* perm_c; trans_t trans; } NLSuperLUFactorizedMatrix; static void nlSuperLUFactorizedMatrixDestroy(NLSuperLUFactorizedMatrix* M) { SuperLU()->Destroy_SuperNode_Matrix(&M->L); SuperLU()->Destroy_CompCol_Matrix(&M->U); NL_DELETE_ARRAY(M->perm_r); NL_DELETE_ARRAY(M->perm_c); } static void nlSuperLUFactorizedMatrixMult( NLSuperLUFactorizedMatrix* M, const double* x, double* y ) { SuperMatrix B; SuperLUStat_t stat; int info = 0; NLuint i; /* Create vector */ SuperLU()->dCreate_Dense_Matrix( &B, (int)(M->n), 1, y, (int)(M->n), SLU_DN, /* Fortran-type column-wise storage */ SLU_D, /* doubles */ SLU_GE /* general */ ); /* copy rhs onto y (superLU matrix-vector product expects it here */ for(i = 0; i < M->n; i++){ y[i] = x[i]; } /* Call SuperLU triangular solve */ SuperLU()->StatInit(&stat) ; SuperLU()->dgstrs( M->trans, &M->L, &M->U, M->perm_c, M->perm_r, &B, &stat, &info ); SuperLU()->StatFree(&stat) ; /* Only the "store" structure needs to be * deallocated (the array has been allocated * by client code). */ SuperLU()->Destroy_SuperMatrix_Store(&B) ; } /* * Copied from SUPERLU/dgssv.c, removed call to linear solve. */ static void dgssv_factorize_only( superlu_options_t *options, SuperMatrix *A, int *perm_c, int *perm_r, SuperMatrix *L, SuperMatrix *U, SuperLUStat_t *stat, int *info, trans_t *trans ) { SuperMatrix *AA = NULL; /* A in SLU_NC format used by the factorization routine.*/ SuperMatrix AC; /* Matrix postmultiplied by Pc */ int lwork = 0, *etree, i; GlobalLU_t Glu; /* Not needed on return. */ /* Set default values for some parameters */ int panel_size; /* panel size */ int relax; /* no of columns in a relaxed snodes */ int permc_spec; nl_assert(A->Stype == SLU_NR || A->Stype == SLU_NC); *trans = NOTRANS; if ( options->Fact != DOFACT ) *info = -1; else if ( A->nrow != A->ncol || A->nrow < 0 || (A->Stype != SLU_NC && A->Stype != SLU_NR) || A->Dtype != SLU_D || A->Mtype != SLU_GE ) *info = -2; if ( *info != 0 ) { i = -(*info); SuperLU()->input_error("SUPERLU/OpenNL dgssv_factorize_only", &i); return; } /* Convert A to SLU_NC format when necessary. */ if ( A->Stype == SLU_NR ) { NRformat *Astore = (NRformat*)A->Store; AA = NL_NEW(SuperMatrix); SuperLU()->dCreate_CompCol_Matrix( AA, A->ncol, A->nrow, Astore->nnz, (double*)Astore->nzval, Astore->colind, Astore->rowptr, SLU_NC, A->Dtype, A->Mtype ); *trans = TRANS; } else { if ( A->Stype == SLU_NC ) AA = A; } nl_assert(AA != NULL); /* * Get column permutation vector perm_c[], according to permc_spec: * permc_spec = NATURAL: natural ordering * permc_spec = MMD_AT_PLUS_A: minimum degree on structure of A'+A * permc_spec = MMD_ATA: minimum degree on structure of A'*A * permc_spec = COLAMD: approximate minimum degree column ordering * permc_spec = MY_PERMC: the ordering already supplied in perm_c[] */ permc_spec = options->ColPerm; if ( permc_spec != MY_PERMC && options->Fact == DOFACT ) SuperLU()->get_perm_c(permc_spec, AA, perm_c); etree = NL_NEW_ARRAY(int,A->ncol); SuperLU()->sp_preorder(options, AA, perm_c, etree, &AC); panel_size = SuperLU()->sp_ienv(1); relax = SuperLU()->sp_ienv(2); SuperLU()->dgstrf(options, &AC, relax, panel_size, etree, NULL, lwork, perm_c, perm_r, L, U, &Glu, stat, info); NL_DELETE_ARRAY(etree); SuperLU()->Destroy_CompCol_Permuted(&AC); if ( A->Stype == SLU_NR ) { SuperLU()->Destroy_SuperMatrix_Store(AA); NL_DELETE(AA); } } NLMatrix nlMatrixFactorize_SUPERLU( NLMatrix M, NLenum solver ) { NLSuperLUFactorizedMatrix* LU = NULL; NLCRSMatrix* CRS = NULL; SuperMatrix superM; NLuint n = M->n; superlu_options_t options; SuperLUStat_t stat; NLint info = 0; /* status code */ nl_assert(M->m == M->n); if(M->type == NL_MATRIX_CRS) { CRS = (NLCRSMatrix*)M; } else if(M->type == NL_MATRIX_SPARSE_DYNAMIC) { CRS = (NLCRSMatrix*)nlCRSMatrixNewFromSparseMatrix((NLSparseMatrix*)M); } nl_assert(!(CRS->symmetric_storage)); LU = NL_NEW(NLSuperLUFactorizedMatrix); LU->m = M->m; LU->n = M->n; LU->type = NL_MATRIX_OTHER; LU->destroy_func = (NLDestroyMatrixFunc)(nlSuperLUFactorizedMatrixDestroy); LU->mult_func = (NLMultMatrixVectorFunc)(nlSuperLUFactorizedMatrixMult); LU->perm_c = NL_NEW_ARRAY(int, n); LU->perm_r = NL_NEW_ARRAY(int, n); SuperLU()->dCreate_CompCol_Matrix( &superM, (int)n, (int)n, (int)nlCRSMatrixNNZ(CRS), CRS->val, (int*)CRS->colind, (int*)CRS->rowptr, SLU_NR, /* Row_wise, no supernode */ SLU_D, /* doubles */ CRS->symmetric_storage ? SLU_SYL : SLU_GE ); SuperLU()->set_default_options(&options); switch(solver) { case NL_SUPERLU_EXT: { options.ColPerm = NATURAL; } break; case NL_PERM_SUPERLU_EXT: { options.ColPerm = COLAMD; } break; case NL_SYMMETRIC_SUPERLU_EXT: { options.ColPerm = MMD_AT_PLUS_A; options.SymmetricMode = YES; } break; default: nl_assert_not_reached; } SuperLU()->StatInit(&stat); dgssv_factorize_only( &options, &superM, LU->perm_c, LU->perm_r, &LU->L, &LU->U, &stat, &info, &LU->trans ); SuperLU()->StatFree(&stat); /* * Only the "store" structure needs to be deallocated * (the arrays have been allocated by us, they are in CRS). */ SuperLU()->Destroy_SuperMatrix_Store(&superM); if((NLMatrix)CRS != M) { nlDeleteMatrix((NLMatrix)CRS); } if(info != 0) { NL_DELETE(LU); LU = NULL; } return (NLMatrix)LU; } /******* extracted from nl_cholmod.c *******/ #ifdef NL_OS_UNIX # ifdef NL_OS_APPLE # define CHOLMOD_LIB_NAME "libcholmod.dylib" # else # define CHOLMOD_LIB_NAME "libcholmod.so" # endif #else # define CHOLMOD_LIB_NAME "libcholmod.xxx" #endif /* Excerpt from cholmod_core.h */ /* A dense matrix in column-oriented form. It has no itype since it contains * no integers. Entry in row i and column j is located in x [i+j*d]. */ typedef struct cholmod_dense_struct { size_t nrow ; /* the matrix is nrow-by-ncol */ size_t ncol ; size_t nzmax ; /* maximum number of entries in the matrix */ size_t d ; /* leading dimension (d >= nrow must hold) */ void *x ; /* size nzmax or 2*nzmax, if present */ void *z ; /* size nzmax, if present */ int xtype ; /* pattern, real, complex, or zomplex */ int dtype ; /* x and z double or float */ } cholmod_dense ; /* A sparse matrix stored in compressed-column form. */ typedef struct cholmod_sparse_struct { size_t nrow ; /* the matrix is nrow-by-ncol */ size_t ncol ; size_t nzmax ; /* maximum number of entries in the matrix */ /* pointers to int or SuiteSparse_long: */ void *p ; /* p [0..ncol], the column pointers */ void *i ; /* i [0..nzmax-1], the row indices */ /* for unpacked matrices only: */ void *nz ; /* nz [0..ncol-1], the # of nonzeros in each col. In * packed form, the nonzero pattern of column j is in * A->i [A->p [j] ... A->p [j+1]-1]. In unpacked form, column j is in * A->i [A->p [j] ... A->p [j]+A->nz[j]-1] instead. In both cases, the * numerical values (if present) are in the corresponding locations in * the array x (or z if A->xtype is CHOLMOD_ZOMPLEX). */ /* pointers to double or float: */ void *x ; /* size nzmax or 2*nzmax, if present */ void *z ; /* size nzmax, if present */ int stype ; /* Describes what parts of the matrix are considered: * * 0: matrix is "unsymmetric": use both upper and lower triangular parts * (the matrix may actually be symmetric in pattern and value, but * both parts are explicitly stored and used). May be square or * rectangular. * >0: matrix is square and symmetric, use upper triangular part. * Entries in the lower triangular part are ignored. * <0: matrix is square and symmetric, use lower triangular part. * Entries in the upper triangular part are ignored. * * Note that stype>0 and stype<0 are different for cholmod_sparse and * cholmod_triplet. See the cholmod_triplet data structure for more * details. */ int itype ; /* CHOLMOD_INT: p, i, and nz are int. * CHOLMOD_INTLONG: p is SuiteSparse_long, * i and nz are int. * CHOLMOD_LONG: p, i, and nz are SuiteSparse_long */ int xtype ; /* pattern, real, complex, or zomplex */ int dtype ; /* x and z are double or float */ int sorted ; /* TRUE if columns are sorted, FALSE otherwise */ int packed ; /* TRUE if packed (nz ignored), FALSE if unpacked * (nz is required) */ } cholmod_sparse ; typedef void* cholmod_common_ptr; typedef cholmod_dense* cholmod_dense_ptr; typedef cholmod_sparse* cholmod_sparse_ptr; typedef void* cholmod_factor_ptr; typedef enum cholmod_xtype_enum { CHOLMOD_PATTERN =0, CHOLMOD_REAL =1, CHOLMOD_COMPLEX =2, CHOLMOD_ZOMPLEX =3 } cholmod_xtype; typedef enum cholmod_solve_type_enum { CHOLMOD_A =0, CHOLMOD_LDLt =1, CHOLMOD_LD =2, CHOLMOD_DLt =3, CHOLMOD_L =4, CHOLMOD_Lt =5, CHOLMOD_D =6, CHOLMOD_P =7, CHOLMOD_Pt =8 } cholmod_solve_type; typedef int cholmod_stype; typedef void (*FUNPTR_cholmod_start)(cholmod_common_ptr); typedef cholmod_sparse_ptr (*FUNPTR_cholmod_allocate_sparse)( size_t m, size_t n, size_t nnz, int sorted, int packed, int stype, int xtype, cholmod_common_ptr ); typedef cholmod_dense_ptr (*FUNPTR_cholmod_allocate_dense)( size_t m, size_t n, size_t d, int xtype, cholmod_common_ptr ); typedef cholmod_factor_ptr (*FUNPTR_cholmod_analyze)( cholmod_sparse_ptr A, cholmod_common_ptr ); typedef int (*FUNPTR_cholmod_factorize)( cholmod_sparse_ptr A, cholmod_factor_ptr L, cholmod_common_ptr ); typedef cholmod_dense_ptr (*FUNPTR_cholmod_solve)( int solve_type, cholmod_factor_ptr, cholmod_dense_ptr, cholmod_common_ptr ); typedef void (*FUNPTR_cholmod_free_factor)( cholmod_factor_ptr*, cholmod_common_ptr ); typedef void (*FUNPTR_cholmod_free_dense)( cholmod_dense_ptr*, cholmod_common_ptr ); typedef void (*FUNPTR_cholmod_free_sparse)( cholmod_sparse_ptr*, cholmod_common_ptr ); typedef void (*FUNPTR_cholmod_finish)(cholmod_common_ptr); typedef struct { char cholmod_common[16384]; FUNPTR_cholmod_start cholmod_start; FUNPTR_cholmod_allocate_sparse cholmod_allocate_sparse; FUNPTR_cholmod_allocate_dense cholmod_allocate_dense; FUNPTR_cholmod_analyze cholmod_analyze; FUNPTR_cholmod_factorize cholmod_factorize; FUNPTR_cholmod_solve cholmod_solve; FUNPTR_cholmod_free_factor cholmod_free_factor; FUNPTR_cholmod_free_sparse cholmod_free_sparse; FUNPTR_cholmod_free_dense cholmod_free_dense; FUNPTR_cholmod_finish cholmod_finish; NLdll DLL_handle; } CHOLMODContext; static CHOLMODContext* CHOLMOD() { static CHOLMODContext context; static NLboolean init = NL_FALSE; if(!init) { init = NL_TRUE; memset(&context, 0, sizeof(context)); } return &context; } NLboolean nlExtensionIsInitialized_CHOLMOD() { return CHOLMOD()->DLL_handle != NULL && CHOLMOD()->cholmod_start != NULL && CHOLMOD()->cholmod_allocate_sparse != NULL && CHOLMOD()->cholmod_allocate_dense != NULL && CHOLMOD()->cholmod_analyze != NULL && CHOLMOD()->cholmod_factorize != NULL && CHOLMOD()->cholmod_solve != NULL && CHOLMOD()->cholmod_free_factor != NULL && CHOLMOD()->cholmod_free_sparse != NULL && CHOLMOD()->cholmod_free_dense != NULL && CHOLMOD()->cholmod_finish != NULL ; } #define find_cholmod_func(name) \ if( \ ( \ CHOLMOD()->name = \ (FUNPTR_##name)nlFindFunction(CHOLMOD()->DLL_handle,#name) \ ) == NULL \ ) { \ nlError("nlInitExtension_CHOLMOD","function not found"); \ return NL_FALSE; \ } static void nlTerminateExtension_CHOLMOD(void) { if(CHOLMOD()->DLL_handle != NULL) { CHOLMOD()->cholmod_finish(&CHOLMOD()->cholmod_common); nlCloseDLL(CHOLMOD()->DLL_handle); CHOLMOD()->DLL_handle = NULL; } } NLboolean nlInitExtension_CHOLMOD(void) { NLenum flags = NL_LINK_NOW | NL_LINK_USE_FALLBACK; if(nlCurrentContext == NULL || !nlCurrentContext->verbose) { flags |= NL_LINK_QUIET; } if(CHOLMOD()->DLL_handle != NULL) { return nlExtensionIsInitialized_CHOLMOD(); } /* * MKL has a built-in CHOLMOD that conflicts with * the CHOLMOD used by OpenNL (to be fixed). For now * we simply output a warning message and deactivate the * CHOLMOD extension if the MKL extension was initialized * before. */ if(NLMultMatrixVector_MKL != NULL) { nl_fprintf( stderr, "CHOLMOD extension incompatible with MKL (deactivating)" ); return NL_FALSE; } CHOLMOD()->DLL_handle = nlOpenDLL(CHOLMOD_LIB_NAME,flags); if(CHOLMOD()->DLL_handle == NULL) { return NL_FALSE; } find_cholmod_func(cholmod_start); find_cholmod_func(cholmod_allocate_sparse); find_cholmod_func(cholmod_allocate_dense); find_cholmod_func(cholmod_analyze); find_cholmod_func(cholmod_factorize); find_cholmod_func(cholmod_solve); find_cholmod_func(cholmod_free_factor); find_cholmod_func(cholmod_free_sparse); find_cholmod_func(cholmod_free_dense); find_cholmod_func(cholmod_finish); CHOLMOD()->cholmod_start(&CHOLMOD()->cholmod_common); atexit(nlTerminateExtension_CHOLMOD); return NL_TRUE; } typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; cholmod_factor_ptr L; } NLCholmodFactorizedMatrix; static void nlCholmodFactorizedMatrixDestroy(NLCholmodFactorizedMatrix* M) { CHOLMOD()->cholmod_free_factor(&M->L, &CHOLMOD()->cholmod_common); } static void nlCholmodFactorizedMatrixMult( NLCholmodFactorizedMatrix* M, const double* x, double* y ) { /* * TODO: see whether CHOLDMOD can use user-allocated vectors * (and avoid copy) */ cholmod_dense_ptr X=CHOLMOD()->cholmod_allocate_dense( M->n, 1, M->n, CHOLMOD_REAL, &CHOLMOD()->cholmod_common ); cholmod_dense_ptr Y=NULL; memcpy(X->x, x, M->n*sizeof(double)); Y = CHOLMOD()->cholmod_solve( CHOLMOD_A, M->L, X, &CHOLMOD()->cholmod_common ); memcpy(y, Y->x, M->n*sizeof(double)); CHOLMOD()->cholmod_free_dense(&X, &CHOLMOD()->cholmod_common); CHOLMOD()->cholmod_free_dense(&Y, &CHOLMOD()->cholmod_common); } NLMatrix nlMatrixFactorize_CHOLMOD( NLMatrix M, NLenum solver ) { NLCholmodFactorizedMatrix* LLt = NULL; NLCRSMatrix* CRS = NULL; cholmod_sparse_ptr cM= NULL; NLuint nnz, cur, i, j, jj; int* rowptr = NULL; int* colind = NULL; double* val = NULL; NLuint n = M->n; nl_assert(solver == NL_CHOLMOD_EXT); nl_assert(M->m == M->n); if(M->type == NL_MATRIX_CRS) { CRS = (NLCRSMatrix*)M; } else if(M->type == NL_MATRIX_SPARSE_DYNAMIC) { /* * Note: since we convert once again into symmetric storage, * we could also directly read the NLSparseMatrix there instead * of copying once more... */ CRS = (NLCRSMatrix*)nlCRSMatrixNewFromSparseMatrix((NLSparseMatrix*)M); } LLt = NL_NEW(NLCholmodFactorizedMatrix); LLt->m = M->m; LLt->n = M->n; LLt->type = NL_MATRIX_OTHER; LLt->destroy_func = (NLDestroyMatrixFunc)(nlCholmodFactorizedMatrixDestroy); LLt->mult_func = (NLMultMatrixVectorFunc)(nlCholmodFactorizedMatrixMult); /* * Compute required nnz, if matrix is not already with symmetric storage, * ignore entries in the upper triangular part. */ nnz=0; for(i=0; i<n; ++i) { for(jj=CRS->rowptr[i]; jj<CRS->rowptr[i+1]; ++jj) { j=CRS->colind[jj]; if(j <= i) { ++nnz; } } } /* * Copy CRS matrix into CHOLDMOD matrix (and ignore upper trianglar part) */ cM = CHOLMOD()->cholmod_allocate_sparse( n, n, nnz, /* Dimensions and number of non-zeros */ NL_FALSE, /* Sorted = false */ NL_TRUE, /* Packed = true */ 1, /* stype (-1 = lower triangular, 1 = upper triangular) */ CHOLMOD_REAL, /* Entries are real numbers */ &CHOLMOD()->cholmod_common ); rowptr = (int*)cM->p; colind = (int*)cM->i; val = (double*)cM->x; cur = 0; for(i=0; i<n; ++i) { rowptr[i] = (int)cur; for(jj=CRS->rowptr[i]; jj<CRS->rowptr[i+1]; ++jj) { j = CRS->colind[jj]; if(j <= i) { val[cur] = CRS->val[jj]; colind[cur] = (int)j; ++cur; } } } rowptr[n] = (int)cur; nl_assert(cur==nnz); LLt->L = CHOLMOD()->cholmod_analyze(cM, &CHOLMOD()->cholmod_common); if(!CHOLMOD()->cholmod_factorize(cM, LLt->L, &CHOLMOD()->cholmod_common)) { CHOLMOD()->cholmod_free_factor(&LLt->L, &CHOLMOD()->cholmod_common); NL_DELETE(LLt); } CHOLMOD()->cholmod_free_sparse(&cM, &CHOLMOD()->cholmod_common); if((NLMatrix)CRS != M) { nlDeleteMatrix((NLMatrix)CRS); } return (NLMatrix)(LLt); } /******* extracted from nl_arpack.c *******/ #ifdef NL_OS_UNIX # ifdef NL_OS_APPLE # define ARPACK_LIB_NAME "libarpack.dylib" # else # define ARPACK_LIB_NAME "libarpack.so" # endif #else # define ARPACK_LIB_NAME "libarpack.dll" #endif typedef int ARint; typedef int ARlogical; /* double precision symmetric routines */ typedef void (*FUNPTR_dsaupd)( ARint *ido, char *bmat, ARint *n, char *which, ARint *nev, double *tol, double *resid, ARint *ncv, double *V, ARint *ldv, ARint *iparam, ARint *ipntr, double *workd, double *workl, ARint *lworkl, ARint *info ); typedef void (*FUNPTR_dseupd)( ARlogical *rvec, char *HowMny, ARlogical *select, double *d, double *Z, ARint *ldz, double *sigma, char *bmat, ARint *n, char *which, ARint *nev, double *tol, double *resid, ARint *ncv, double *V, ARint *ldv, ARint *iparam, ARint *ipntr, double *workd, double *workl, ARint *lworkl, ARint *info ); /* double precision nonsymmetric routines */ typedef void (*FUNPTR_dnaupd)( ARint *ido, char *bmat, ARint *n, char *which, ARint *nev, double *tol, double *resid, ARint *ncv, double *V, ARint *ldv, ARint *iparam, ARint *ipntr, double *workd, double *workl, ARint *lworkl, ARint *info ); typedef void (*FUNPTR_dneupd)( ARlogical *rvec, char *HowMny, ARlogical *select, double *dr, double *di, double *Z, ARint *ldz, double *sigmar, double *sigmai, double *workev, char *bmat, ARint *n, char *which, ARint *nev, double *tol, double *resid, ARint *ncv, double *V, ARint *ldv, ARint *iparam, ARint *ipntr, double *workd, double *workl, ARint *lworkl, ARint *info ); typedef struct { FUNPTR_dsaupd dsaupd; FUNPTR_dseupd dseupd; FUNPTR_dnaupd dnaupd; FUNPTR_dneupd dneupd; NLdll DLL_handle; } ARPACKContext; static ARPACKContext* ARPACK() { static ARPACKContext context; static NLboolean init = NL_FALSE; if(!init) { init = NL_TRUE; memset(&context, 0, sizeof(context)); } return &context; } NLboolean nlExtensionIsInitialized_ARPACK() { return ARPACK()->DLL_handle != NULL && ARPACK()->dsaupd != NULL && ARPACK()->dseupd != NULL && ARPACK()->dnaupd != NULL && ARPACK()->dneupd != NULL; } static void nlTerminateExtension_ARPACK(void) { if(ARPACK()->DLL_handle != NULL) { nlCloseDLL(ARPACK()->DLL_handle); ARPACK()->DLL_handle = NULL; } } static char* u(const char* str) { static char buff[1000]; sprintf(buff, "%s_", str); return buff; } #define find_arpack_func(name) \ if( \ ( \ ARPACK()->name = \ (FUNPTR_##name)nlFindFunction(ARPACK()->DLL_handle,u(#name)) \ ) == NULL \ ) { \ nlError("nlInitExtension_ARPACK","function not found"); \ nlError("nlInitExtension_ARPACK",u(#name)); \ return NL_FALSE; \ } NLboolean nlInitExtension_ARPACK(void) { NLenum flags = NL_LINK_NOW | NL_LINK_USE_FALLBACK; if(nlCurrentContext == NULL || !nlCurrentContext->verbose) { flags |= NL_LINK_QUIET; } if(ARPACK()->DLL_handle != NULL) { return nlExtensionIsInitialized_ARPACK(); } ARPACK()->DLL_handle = nlOpenDLL(ARPACK_LIB_NAME, flags); if(ARPACK()->DLL_handle == NULL) { return NL_FALSE; } find_arpack_func(dsaupd); find_arpack_func(dseupd); find_arpack_func(dnaupd); find_arpack_func(dneupd); atexit(nlTerminateExtension_ARPACK); return NL_TRUE; } static NLMatrix create_OP(NLboolean symmetric) { NLuint n = nlCurrentContext->M->n; NLuint i; NLMatrix result = NULL; if(nlCurrentContext->eigen_shift != 0.0) { /* * A = M */ NLSparseMatrix* A = NL_NEW(NLSparseMatrix); nlSparseMatrixConstruct(A, n, n, NL_MATRIX_STORE_ROWS); nlSparseMatrixAddMatrix(A, 1.0, nlCurrentContext->M); if(nlCurrentContext->B == NULL) { /* * A = A - shift * Id */ for(i=0; i<n; ++i) { nlSparseMatrixAdd(A, i, i, -nlCurrentContext->eigen_shift); } } else { /* * A = A - shift * B */ nlSparseMatrixAddMatrix( A, -nlCurrentContext->eigen_shift, nlCurrentContext->B ); } /* * OP = A^{-1} */ if(nlCurrentContext->verbose) { nl_printf("Factorizing matrix...\n"); } result = nlMatrixFactorize( (NLMatrix)A, symmetric ? NL_SYMMETRIC_SUPERLU_EXT : NL_PERM_SUPERLU_EXT ); if(nlCurrentContext->verbose) { if(result == NULL) { nl_printf("Could not factorize matrix\n"); } else { nl_printf("Matrix factorized\n"); } } nlDeleteMatrix((NLMatrix)A); } else { /* * OP = M^{-1} */ if(nlCurrentContext->verbose) { nl_printf("Factorizing matrix...\n"); } result = nlMatrixFactorize( nlCurrentContext->M, symmetric ? NL_SYMMETRIC_SUPERLU_EXT : NL_PERM_SUPERLU_EXT ); if(nlCurrentContext->verbose) { if(result == NULL) { nl_printf("Could not factorize matrix\n"); } else { nl_printf("Matrix factorized\n"); } } } if(result == NULL) { return NULL; } if(nlCurrentContext->B != NULL) { /* * OP = OP * B */ result = nlMatrixNewFromProduct( result, NL_TRUE, /* mem. ownership transferred */ nlCurrentContext->B, NL_FALSE /* mem. ownership kept by context */ ); } return result; } static int eigencompare(const void* pi, const void* pj) { NLuint i = *(const NLuint*)pi; NLuint j = *(const NLuint*)pj; double vali = fabs(nlCurrentContext->temp_eigen_value[i]); double valj = fabs(nlCurrentContext->temp_eigen_value[j]); if(vali == valj) { return 0; } return vali < valj ? -1 : 1; } void nlEigenSolve_ARPACK(void) { NLboolean symmetric = nlCurrentContext->symmetric && (nlCurrentContext->B == NULL); int n = (int)nlCurrentContext->M->n; /* Dimension of the matrix */ int nev = /* Number of eigenvectors requested */ (int)nlCurrentContext->nb_systems; NLMatrix OP = create_OP(symmetric); int ncv = (int)(nev * 2.5); /* Length of Arnoldi factorization */ /* Rule of thumb in ARPACK documentation: ncv > 2 * nev */ int* iparam = NULL; int* ipntr = NULL; NLdouble* resid = NULL; NLdouble* workev = NULL; NLdouble* workd = NULL; NLdouble* workl = NULL; NLdouble* v = NULL; NLdouble* d = NULL; ARlogical* select = NULL; ARlogical rvec = 1; double sigmar = 0.0; double sigmai = 0.0; int ierr; int i,k,kk; int ldv = (int)n; char* bmat = (char*)"I"; /*Standard problem */ char* which = (char*)"LM"; /*Largest eigenvalues, but we invert->smallest */ char* howmny = (char*)"A"; /*which eigens should be computed: all */ double tol = nlCurrentContext->threshold; int ido = 0; /* reverse communication variable (which operation ?) */ int info = 1; /* start with initial value of resid */ int lworkl; /* size of work array */ NLboolean converged = NL_FALSE; NLdouble value; int index; int* sorted; /* indirection array for sorting eigenpairs */ if(OP == NULL) { nlError("nlEigenSolve_ARPACK","Could not factorize matrix"); return; } if(ncv > n) { ncv = n; } if(nev > n) { nev = n; } if(nev + 2 > ncv) { nev = ncv - 2; } if(symmetric) { lworkl = ncv * (ncv + 8) ; } else { lworkl = 3*ncv*ncv + 6*ncv ; } iparam = NL_NEW_ARRAY(int, 11); ipntr = NL_NEW_ARRAY(int, 14); iparam[1-1] = 1; /* ARPACK chooses the shifts */ iparam[3-1] = (int)nlCurrentContext->max_iterations; iparam[7-1] = 1; /* Normal mode (we do not use shift-invert (3) since we do our own shift-invert */ workev = NL_NEW_ARRAY(NLdouble, 3*ncv); workd = NL_NEW_ARRAY(NLdouble, 3*n); resid = NL_NEW_ARRAY(NLdouble, n); for(i=0; i<n; ++i) { resid[i] = 1.0; /* (double)i / (double)n; */ } v = NL_NEW_ARRAY(NLdouble, ldv*ncv); if(symmetric) { d = NL_NEW_ARRAY(NLdouble, 2*ncv); } else { d = NL_NEW_ARRAY(NLdouble, 3*ncv); } workl = NL_NEW_ARRAY(NLdouble, lworkl); if(nlCurrentContext->verbose) { if(symmetric) { nl_printf("calling dsaupd()\n"); } else { nl_printf("calling dnaupd()\n"); } } while(!converged) { /* if(nlCurrentContext->verbose) { fprintf(stderr, "."); fflush(stderr); } */ if(symmetric) { ARPACK()->dsaupd( &ido, bmat, &n, which, &nev, &tol, resid, &ncv, v, &ldv, iparam, ipntr, workd, workl, &lworkl, &info ); } else { ARPACK()->dnaupd( &ido, bmat, &n, which, &nev, &tol, resid, &ncv, v, &ldv, iparam, ipntr, workd, workl, &lworkl, &info ); } if(ido == 1) { nlMultMatrixVector( OP, workd+ipntr[1-1]-1, /*The "-1"'s are for FORTRAN-to-C conversion */ workd+ipntr[2-1]-1 /*to keep the same indices as in ARPACK doc */ ); } else { converged = NL_TRUE; } } if(info < 0) { if(symmetric) { nl_fprintf(stderr, "\nError with dsaupd(): %d\n", info); } else { nl_fprintf(stderr, "\nError with dnaupd(): %d\n", info); } } else { if(nlCurrentContext->verbose) { fprintf(stderr, "\nconverged\n"); } select = NL_NEW_ARRAY(ARlogical, ncv); for(i=0; i<ncv; ++i) { select[i] = 1; } if(nlCurrentContext->verbose) { if(symmetric) { nl_printf("calling dseupd()\n"); } else { nl_printf("calling dneupd()\n"); } } if(symmetric) { ARPACK()->dseupd( &rvec, howmny, select, d, v, &ldv, &sigmar, bmat, &n, which, &nev, &tol, resid, &ncv, v, &ldv, iparam, ipntr, workd, workl, &lworkl, &ierr ); } else { ARPACK()->dneupd( &rvec, howmny, select, d, d+ncv, v, &ldv, &sigmar, &sigmai, workev, bmat, &n, which, &nev, &tol, resid, &ncv, v, &ldv, iparam, ipntr, workd, workl, &lworkl, &ierr ) ; } if(nlCurrentContext->verbose) { if(ierr != 0) { if(symmetric) { nl_fprintf(stderr, "Error with dseupd(): %d\n", ierr); } else { nl_fprintf(stderr, "Error with dneupd(): %d\n", ierr); } } else { if(symmetric) { nl_printf("dseupd() OK, nconv= %d\n", iparam[3-1]); } else { nl_printf("dneupd() OK, nconv= %d\n", iparam[3-1]); } } } NL_DELETE_ARRAY(select); } for(i=0; i<nev; ++i) { d[i] = (fabs(d[i]) < 1e-30) ? 1e30 : 1.0 / d[i] ; d[i] += nlCurrentContext->eigen_shift ; } /* Make it visible to the eigen_compare function */ nlCurrentContext->temp_eigen_value = d; sorted = NL_NEW_ARRAY(int, nev); for(i=0; i<nev; ++i) { sorted[i] = i; } qsort(sorted, (size_t)nev, sizeof(NLuint), eigencompare); nlCurrentContext->temp_eigen_value = NULL; for(k=0; k<nev; ++k) { kk = sorted[k]; nlCurrentContext->eigen_value[k] = d[kk]; for(i=0; i<(int)nlCurrentContext->nb_variables; ++i) { if(!nlCurrentContext->variable_is_locked[i]) { index = (int)nlCurrentContext->variable_index[i]; nl_assert(index < n); value = v[kk*n+index]; NL_BUFFER_ITEM( nlCurrentContext->variable_buffer[k],(NLuint)i ) = value; } } } NL_DELETE_ARRAY(sorted); NL_DELETE_ARRAY(workl); NL_DELETE_ARRAY(d); NL_DELETE_ARRAY(v); NL_DELETE_ARRAY(resid); NL_DELETE_ARRAY(workd); NL_DELETE_ARRAY(workev); nlDeleteMatrix(OP); NL_DELETE_ARRAY(iparam); NL_DELETE_ARRAY(ipntr); } /******* extracted from nl_mkl.c *******/ typedef unsigned int MKL_INT; typedef void (*FUNPTR_mkl_cspblas_dcsrgemv)( const char *transa, const MKL_INT *m, const double *a, const MKL_INT *ia, const MKL_INT *ja, const double *x, double *y ); typedef void (*FUNPTR_mkl_cspblas_dcsrsymv)( const char *transa, const MKL_INT *m, const double *a, const MKL_INT *ia, const MKL_INT *ja, const double *x, double *y ); typedef struct { NLdll DLL_mkl_intel_lp64; NLdll DLL_mkl_intel_thread; NLdll DLL_mkl_core; NLdll DLL_iomp5; FUNPTR_mkl_cspblas_dcsrgemv mkl_cspblas_dcsrgemv; FUNPTR_mkl_cspblas_dcsrsymv mkl_cspblas_dcsrsymv; } MKLContext; static MKLContext* MKL() { static MKLContext context; static NLboolean init = NL_FALSE; if(!init) { init = NL_TRUE; memset(&context, 0, sizeof(context)); } return &context; } NLboolean nlExtensionIsInitialized_MKL() { if( MKL()->DLL_iomp5 == NULL || MKL()->DLL_mkl_core == NULL || MKL()->DLL_mkl_intel_thread == NULL || MKL()->DLL_mkl_intel_lp64 == NULL || MKL()->mkl_cspblas_dcsrgemv == NULL || MKL()->mkl_cspblas_dcsrsymv == NULL ) { return NL_FALSE; } return NL_TRUE; } #define find_mkl_func(name) \ if( \ ( \ MKL()->name = \ (FUNPTR_##name)nlFindFunction( \ MKL()->DLL_mkl_intel_lp64,#name \ ) \ ) == NULL \ ) { \ nlError("nlInitExtension_MKL","function not found"); \ return NL_FALSE; \ } static void nlTerminateExtension_MKL(void) { if(!nlExtensionIsInitialized_MKL()) { return; } nlCloseDLL(MKL()->DLL_mkl_intel_lp64); nlCloseDLL(MKL()->DLL_mkl_intel_thread); nlCloseDLL(MKL()->DLL_mkl_core); nlCloseDLL(MKL()->DLL_iomp5); } NLMultMatrixVectorFunc NLMultMatrixVector_MKL = NULL; static void NLMultMatrixVector_MKL_impl(NLMatrix M_in, const double* x, double* y) { NLCRSMatrix* M = (NLCRSMatrix*)(M_in); nl_debug_assert(M_in->type == NL_MATRIX_CRS); if(M->symmetric_storage) { MKL()->mkl_cspblas_dcsrsymv( "N", /* No transpose */ &M->m, M->val, M->rowptr, M->colind, x, y ); } else { MKL()->mkl_cspblas_dcsrgemv( "N", /* No transpose */ &M->m, M->val, M->rowptr, M->colind, x, y ); } } #define INTEL_PREFIX "/opt/intel/" #define LIB_DIR "lib/intel64/" #define MKL_PREFIX INTEL_PREFIX "mkl/" LIB_DIR NLboolean nlInitExtension_MKL(void) { NLenum flags = NL_LINK_LAZY | NL_LINK_GLOBAL; if(nlCurrentContext == NULL || !nlCurrentContext->verbose) { flags |= NL_LINK_QUIET; } if(MKL()->DLL_mkl_intel_lp64 != NULL) { return nlExtensionIsInitialized_MKL(); } MKL()->DLL_iomp5 = nlOpenDLL( INTEL_PREFIX LIB_DIR "libiomp5.so", flags ); MKL()->DLL_mkl_core = nlOpenDLL( MKL_PREFIX "libmkl_core.so", flags ); MKL()->DLL_mkl_intel_thread = nlOpenDLL( MKL_PREFIX "libmkl_intel_thread.so", flags ); MKL()->DLL_mkl_intel_lp64 = nlOpenDLL( MKL_PREFIX "libmkl_intel_lp64.so", flags ); if( MKL()->DLL_iomp5 == NULL || MKL()->DLL_mkl_core == NULL || MKL()->DLL_mkl_intel_thread == NULL || MKL()->DLL_mkl_intel_lp64 == NULL ) { return NL_FALSE; } find_mkl_func(mkl_cspblas_dcsrgemv); find_mkl_func(mkl_cspblas_dcsrsymv); if(nlExtensionIsInitialized_MKL()) { NLMultMatrixVector_MKL = NLMultMatrixVector_MKL_impl; } atexit(nlTerminateExtension_MKL); return NL_TRUE; } /******* extracted from nl_cuda.c *******/ /* CUDA structures and functions */ /* Repeated here so that one can compile OpenNL without */ /* requiring CUDA to be installed in the system. */ struct cudaDeviceProp { char name[256]; size_t totalGlobalMem; size_t sharedMemPerBlock; int regsPerBlock; int warpSize; size_t memPitch; int maxThreadsPerBlock; int maxThreadsDim[3]; int maxGridSize[3]; int clockRate; size_t totalConstMem; int major; int minor; size_t textureAlignment; size_t texturePitchAlignment; int deviceOverlap; int multiProcessorCount; int kernelExecTimeoutEnabled; int integrated; int canMapHostMemory; int computeMode; int maxTexture1D; int maxTexture1DMipmap; int maxTexture1DLinear; int maxTexture2D[2]; int maxTexture2DMipmap[2]; int maxTexture2DLinear[3]; int maxTexture2DGather[2]; int maxTexture3D[3]; int maxTexture3DAlt[3]; int maxTextureCubemap; int maxTexture1DLayered[2]; int maxTexture2DLayered[3]; int maxTextureCubemapLayered[2]; int maxSurface1D; int maxSurface2D[2]; int maxSurface3D[3]; int maxSurface1DLayered[2]; int maxSurface2DLayered[3]; int maxSurfaceCubemap; int maxSurfaceCubemapLayered[2]; size_t surfaceAlignment; int concurrentKernels; int ECCEnabled; int pciBusID; int pciDeviceID; int pciDomainID; int tccDriver; int asyncEngineCount; int unifiedAddressing; int memoryClockRate; int memoryBusWidth; int l2CacheSize; int maxThreadsPerMultiProcessor; int streamPrioritiesSupported; int globalL1CacheSupported; int localL1CacheSupported; size_t sharedMemPerMultiprocessor; int regsPerMultiprocessor; int managedMemSupported; int isMultiGpuBoard; int multiGpuBoardGroupID; int singleToDoublePrecisionPerfRatio; int pageableMemoryAccess; int concurrentManagedAccess; char padding[1024]; /* More room for future evolutions */ }; enum cudaComputeMode { cudaComputeModeDefault = 0, cudaComputeModeExclusive = 1, cudaComputeModeProhibited = 2, cudaComputeModeExclusiveProcess = 3 }; enum cudaMemcpyKind { cudaMemcpyHostToHost = 0, cudaMemcpyHostToDevice = 1, cudaMemcpyDeviceToHost = 2, cudaMemcpyDeviceToDevice = 3, cudaMemcpyDefault = 4 }; typedef int cudaError_t; typedef cudaError_t (*FUNPTR_cudaGetDeviceCount)(int* device_count); typedef cudaError_t (*FUNPTR_cudaGetDeviceProperties)( struct cudaDeviceProp *props, int device ); typedef cudaError_t (*FUNPTR_cudaDeviceReset)(void); typedef cudaError_t (*FUNPTR_cudaMalloc)(void **devPtr, size_t size); typedef cudaError_t (*FUNPTR_cudaFree)(void* devPtr); typedef cudaError_t (*FUNPTR_cudaMemcpy)( void *dst, const void *src, size_t count, enum cudaMemcpyKind kind ); #define find_cuda_func(name) \ if( \ ( \ CUDA()->name = \ (FUNPTR_##name)nlFindFunction( \ CUDA()->DLL_cudart,#name \ ) \ ) == NULL \ ) { \ nlError("nlInitExtension_CUDA: function not found", #name); \ return NL_FALSE; \ } /* CUBLAS structures and functions */ struct cublasContext; typedef struct cublasContext *cublasHandle_t; typedef int cublasStatus_t; typedef enum { CUBLAS_SIDE_LEFT =0, CUBLAS_SIDE_RIGHT=1 } cublasSideMode_t; typedef enum { CUBLAS_FILL_MODE_LOWER=0, CUBLAS_FILL_MODE_UPPER=1 } cublasFillMode_t; typedef enum { CUBLAS_OP_N=0, CUBLAS_OP_T=1, CUBLAS_OP_C=2 } cublasOperation_t; typedef enum { CUBLAS_DIAG_NON_UNIT=0, CUBLAS_DIAG_UNIT=1 } cublasDiagType_t; typedef cublasStatus_t (*FUNPTR_cublasCreate)(cublasHandle_t* handle); typedef cublasStatus_t (*FUNPTR_cublasDestroy)(cublasHandle_t handle); typedef cublasStatus_t (*FUNPTR_cublasGetVersion)( cublasHandle_t handle, int* version ); typedef cublasStatus_t (*FUNPTR_cublasDdot)( cublasHandle_t handle, int n, const double *x, int incx, const double *y, int incy, double *result ); typedef cublasStatus_t (*FUNPTR_cublasDcopy)( cublasHandle_t handle, int n, const double *x, int incx, const double *y, int incy ); typedef cublasStatus_t (*FUNPTR_cublasDaxpy)( cublasHandle_t handle, int n, const double* alpha, const double *x, int incx, const double *y, int incy ); typedef cublasStatus_t (*FUNPTR_cublasDscal)( cublasHandle_t handle, int n, const double* alpha, const double *x, int incx ); typedef cublasStatus_t (*FUNPTR_cublasDnrm2)( cublasHandle_t handle, int n, const double *x, int incx, double* result ); typedef cublasStatus_t (*FUNPTR_cublasDdgmm)( cublasHandle_t handle, cublasSideMode_t mode, int m, int n, const double* A, int lda, const double* x, int incx, double* C, int ldc ); typedef cublasStatus_t (*FUNPTR_cublasDgemv)( cublasHandle_t handle, cublasOperation_t trans, int m, int n, const double *alpha, const double *A, int lda, const double *x, int incx, const double *beta, double *y, int incy ); typedef cublasStatus_t (*FUNPTR_cublasDtpsv)( cublasHandle_t handle, cublasFillMode_t uplo, cublasOperation_t trans, cublasDiagType_t diag, int n, const double *AP, double* x, int incx ); #define find_cublas_func(name) \ if( \ ( \ CUDA()->name = \ (FUNPTR_##name)nlFindFunction( \ CUDA()->DLL_cublas,#name "_v2" \ ) \ ) == NULL \ ) { \ nlError("nlInitExtension_CUDA: function not found", #name); \ return NL_FALSE; \ } #define find_cublas_func_v1(name) \ if( \ ( \ CUDA()->name = \ (FUNPTR_##name)nlFindFunction( \ CUDA()->DLL_cublas,#name \ ) \ ) == NULL \ ) { \ nlError("nlInitExtension_CUDA: function not found", #name); \ return NL_FALSE; \ } /* CUSPARSE structures and functions */ struct cusparseContext; typedef struct cusparseContext *cusparseHandle_t; typedef int cusparseStatus_t; struct cusparseMatDescr; typedef struct cusparseMatDescr *cusparseMatDescr_t; typedef enum { CUSPARSE_MATRIX_TYPE_GENERAL = 0, CUSPARSE_MATRIX_TYPE_SYMMETRIC = 1, CUSPARSE_MATRIX_TYPE_HERMITIAN = 2, CUSPARSE_MATRIX_TYPE_TRIANGULAR = 3 } cusparseMatrixType_t; typedef enum { CUSPARSE_INDEX_BASE_ZERO = 0, CUSPARSE_INDEX_BASE_ONE = 1 } cusparseIndexBase_t; typedef enum { CUSPARSE_OPERATION_NON_TRANSPOSE = 0, CUSPARSE_OPERATION_TRANSPOSE = 1, CUSPARSE_OPERATION_CONJUGATE_TRANSPOSE = 2 } cusparseOperation_t; struct cusparseHybMat; typedef struct cusparseHybMat *cusparseHybMat_t; typedef enum { CUSPARSE_HYB_PARTITION_AUTO = 0, CUSPARSE_HYB_PARTITION_USER = 1, CUSPARSE_HYB_PARTITION_MAX = 2 } cusparseHybPartition_t; typedef cusparseStatus_t (*FUNPTR_cusparseCreate)(cusparseHandle_t* handle); typedef cusparseStatus_t (*FUNPTR_cusparseDestroy)(cusparseHandle_t handle); typedef cusparseStatus_t (*FUNPTR_cusparseGetVersion)( cusparseHandle_t handle, int* version ); typedef cusparseStatus_t (*FUNPTR_cusparseCreateMatDescr)( cusparseMatDescr_t* descr ); typedef cusparseStatus_t (*FUNPTR_cusparseDestroyMatDescr)( cusparseMatDescr_t descr ); typedef cusparseStatus_t (*FUNPTR_cusparseSetMatType)( cusparseMatDescr_t descr, cusparseMatrixType_t mtype ); typedef cusparseStatus_t (*FUNPTR_cusparseSetMatIndexBase)( cusparseMatDescr_t descr, cusparseIndexBase_t ibase ); typedef cusparseStatus_t (*FUNPTR_cusparseDcsrmv)( cusparseHandle_t handle, cusparseOperation_t transA, int m, int n, int nnz, const double *alpha, const cusparseMatDescr_t descrA, const double *csrSortedValA, const int *csrSortedRowPtrA, const int *csrSortedColIndA, const double *x, const double *beta, double *y ); typedef cusparseStatus_t (*FUNPTR_cusparseCreateHybMat)( cusparseHybMat_t *hybA ); typedef cusparseStatus_t (*FUNPTR_cusparseDestroyHybMat)( cusparseHybMat_t hybA ); typedef cusparseStatus_t (*FUNPTR_cusparseDcsr2hyb)( cusparseHandle_t handle, int m, int n, const cusparseMatDescr_t descrA, const double *csrSortedValA, const int *csrSortedRowPtrA, const int *csrSortedColIndA, cusparseHybMat_t hybA, int userEllWidth, cusparseHybPartition_t partitionType ); typedef cusparseStatus_t (*FUNPTR_cusparseDhybmv)( cusparseHandle_t handle, cusparseOperation_t transA, const double *alpha, const cusparseMatDescr_t descrA, const cusparseHybMat_t hybA, const double *x, const double *beta, double *y ); #define find_cusparse_func(name) \ if( \ ( \ CUDA()->name = \ (FUNPTR_##name)nlFindFunction( \ CUDA()->DLL_cusparse,#name \ ) \ ) == NULL \ ) { \ nlError("nlInitExtension_CUDA : function not found", #name); \ return NL_FALSE; \ } typedef struct { NLdll DLL_cudart; FUNPTR_cudaGetDeviceCount cudaGetDeviceCount; FUNPTR_cudaGetDeviceProperties cudaGetDeviceProperties; FUNPTR_cudaDeviceReset cudaDeviceReset; FUNPTR_cudaMalloc cudaMalloc; FUNPTR_cudaFree cudaFree; FUNPTR_cudaMemcpy cudaMemcpy; NLdll DLL_cublas; cublasHandle_t HNDL_cublas; FUNPTR_cublasCreate cublasCreate; FUNPTR_cublasDestroy cublasDestroy; FUNPTR_cublasGetVersion cublasGetVersion; FUNPTR_cublasDdot cublasDdot; FUNPTR_cublasDcopy cublasDcopy; FUNPTR_cublasDaxpy cublasDaxpy; FUNPTR_cublasDscal cublasDscal; FUNPTR_cublasDnrm2 cublasDnrm2; FUNPTR_cublasDdgmm cublasDdgmm; FUNPTR_cublasDgemv cublasDgemv; FUNPTR_cublasDtpsv cublasDtpsv; NLdll DLL_cusparse; cusparseHandle_t HNDL_cusparse; FUNPTR_cusparseCreate cusparseCreate; FUNPTR_cusparseDestroy cusparseDestroy; FUNPTR_cusparseGetVersion cusparseGetVersion; FUNPTR_cusparseCreateMatDescr cusparseCreateMatDescr; FUNPTR_cusparseDestroyMatDescr cusparseDestroyMatDescr; FUNPTR_cusparseSetMatType cusparseSetMatType; FUNPTR_cusparseSetMatIndexBase cusparseSetMatIndexBase; FUNPTR_cusparseDcsrmv cusparseDcsrmv; FUNPTR_cusparseCreateHybMat cusparseCreateHybMat; FUNPTR_cusparseDestroyHybMat cusparseDestroyHybMat; FUNPTR_cusparseDcsr2hyb cusparseDcsr2hyb; FUNPTR_cusparseDhybmv cusparseDhybmv; int devID; } CUDAContext; static CUDAContext* CUDA() { static CUDAContext context; static NLboolean init = NL_FALSE; if(!init) { init = NL_TRUE; memset(&context, 0, sizeof(context)); } return &context; } NLboolean nlExtensionIsInitialized_CUDA() { if( CUDA()->DLL_cudart == NULL || CUDA()->cudaGetDeviceCount == NULL || CUDA()->cudaGetDeviceProperties == NULL || CUDA()->cudaDeviceReset == NULL || CUDA()->cudaMalloc == NULL || CUDA()->cudaFree == NULL || CUDA()->cudaMemcpy == NULL || CUDA()->DLL_cublas == NULL || CUDA()->HNDL_cublas == NULL || CUDA()->cublasCreate == NULL || CUDA()->cublasDestroy == NULL || CUDA()->cublasGetVersion == NULL || CUDA()->cublasDdot == NULL || CUDA()->cublasDcopy == NULL || CUDA()->cublasDaxpy == NULL || CUDA()->cublasDscal == NULL || CUDA()->cublasDnrm2 == NULL || CUDA()->cublasDdgmm == NULL || CUDA()->DLL_cusparse == NULL || CUDA()->HNDL_cusparse == NULL || CUDA()->cusparseCreate == NULL || CUDA()->cusparseDestroy == NULL || CUDA()->cusparseGetVersion == NULL || CUDA()->cusparseCreateMatDescr == NULL || CUDA()->cusparseDestroyMatDescr == NULL || CUDA()->cusparseSetMatType == NULL || CUDA()->cusparseSetMatIndexBase == NULL || CUDA()->cusparseDcsrmv == NULL || CUDA()->cusparseCreateHybMat == NULL || CUDA()->cusparseDestroyHybMat == NULL || CUDA()->cusparseDcsr2hyb == NULL || CUDA()->cusparseDhybmv == NULL ) { return NL_FALSE; } return NL_TRUE; } static void nlTerminateExtension_CUDA(void) { if(!nlExtensionIsInitialized_CUDA()) { return; } CUDA()->cusparseDestroy(CUDA()->HNDL_cusparse); nlCloseDLL(CUDA()->DLL_cusparse); CUDA()->cublasDestroy(CUDA()->HNDL_cublas); nlCloseDLL(CUDA()->DLL_cublas); CUDA()->cudaDeviceReset(); nlCloseDLL(CUDA()->DLL_cudart); } static int ConvertSMVer2Cores(int major, int minor) { /* Defines for GPU Architecture types (using the SM version to determine the # of cores per SM */ typedef struct { int SM; /* 0xMm (hexadecimal notation), M = SM Major version, and m = SM minor version */ int Cores; } sSMtoCores; sSMtoCores nGpuArchCoresPerSM[] = { { 0x10, 8 }, /* Tesla Generation (SM 1.0) G80 class */ { 0x11, 8 }, /* Tesla Generation (SM 1.1) G8x class */ { 0x12, 8 }, /* Tesla Generation (SM 1.2) G9x class */ { 0x13, 8 }, /* Tesla Generation (SM 1.3) GT200 class */ { 0x20, 32 }, /* Fermi Generation (SM 2.0) GF100 class */ { 0x21, 48 }, /* Fermi Generation (SM 2.1) GF10x class */ { 0x30, 192}, /* Kepler Generation (SM 3.0) GK10x class */ { 0x35, 192}, /* Kepler Generation (SM 3.5) GK11x class */ { 0x50, 128}, /* Maxwell Generation (SM 5.0) GM10x class (yes, #cores smaller than with 3.x) */ { 0x52, 128}, /* Maxwell Generation (SM 5.2) GM20x class */ { 0x60, 64 }, /* Pascal Generation (SM 6.0) GP100,GP102 (yes, 64, but GP100 has superfast double precision) */ { 0x61, 128}, /* Pascal Generation (SM 6.1) GP104 class (but FP64 runs as 1/32 FP32 speed) */ { -1, -1 } }; int index = 0; while (nGpuArchCoresPerSM[index].SM != -1) { if (nGpuArchCoresPerSM[index].SM == ((major << 4) + minor)) { return nGpuArchCoresPerSM[index].Cores; } index++; } /* If we don't find the values, we default use the previous one to run properly */ nl_printf( "MapSMtoCores for SM %d.%d is undefined. Default to use %d Cores/SM\n", major, minor, nGpuArchCoresPerSM[8].Cores ); return nGpuArchCoresPerSM[8].Cores; } static int getBestDeviceID() { int current_device = 0, sm_per_multiproc = 0; int max_compute_perf = 0, max_perf_device = 0; int device_count = 0, best_SM_arch = 0; int compute_perf = 0; struct cudaDeviceProp deviceProp; CUDA()->cudaGetDeviceCount(&device_count); /* Find the best major SM Architecture GPU device */ while (current_device < device_count) { CUDA()->cudaGetDeviceProperties(&deviceProp, current_device); /* If this GPU is not running on Compute Mode prohibited, then we can add it to the list */ if (deviceProp.computeMode != cudaComputeModeProhibited) { if (deviceProp.major > 0 && deviceProp.major < 9999) { best_SM_arch = MAX(best_SM_arch, deviceProp.major); } } current_device++; } /* Find the best CUDA capable GPU device */ current_device = 0; while (current_device < device_count) { CUDA()->cudaGetDeviceProperties(&deviceProp, current_device); /* If this GPU is not running on Compute Mode prohibited, then we can add it to the list */ if (deviceProp.computeMode != cudaComputeModeProhibited) { if (deviceProp.major == 9999 && deviceProp.minor == 9999) { sm_per_multiproc = 1; } else { sm_per_multiproc = ConvertSMVer2Cores( deviceProp.major, deviceProp.minor ); } compute_perf = deviceProp.multiProcessorCount * sm_per_multiproc * deviceProp.clockRate; if (compute_perf > max_compute_perf) { /* If we find GPU with SM major > 2, search only these */ if (best_SM_arch > 2) { /* If our device==dest_SM_arch, choose this, or else pass */ if (deviceProp.major == best_SM_arch) { max_compute_perf = compute_perf; max_perf_device = current_device; } } else { max_compute_perf = compute_perf; max_perf_device = current_device; } } } ++current_device; } return max_perf_device; } #ifdef NL_OS_UNIX # define LIBPREFIX "lib" # ifdef NL_OS_APPLE # define LIBEXTENSION ".dylib" # else # define LIBEXTENSION ".so" # endif #else # define LIBPREFIX # define LIBEXTENSION ".dll" #endif NLboolean nlInitExtension_CUDA(void) { struct cudaDeviceProp deviceProp; int cublas_version; int cusparse_version; NLenum flags = NL_LINK_LAZY | NL_LINK_GLOBAL; if(nlCurrentContext == NULL || !nlCurrentContext->verbose) { flags |= NL_LINK_QUIET; } if(nlExtensionIsInitialized_CUDA()) { return NL_TRUE; } CUDA()->DLL_cudart = nlOpenDLL( LIBPREFIX "cudart" LIBEXTENSION, flags ); find_cuda_func(cudaGetDeviceCount); find_cuda_func(cudaGetDeviceProperties); find_cuda_func(cudaDeviceReset); find_cuda_func(cudaMalloc); find_cuda_func(cudaFree); find_cuda_func(cudaMemcpy); CUDA()->devID = getBestDeviceID(); if(CUDA()->cudaGetDeviceProperties(&deviceProp, CUDA()->devID)) { nl_fprintf(stderr,"OpenNL CUDA: could not find a CUDA device\n"); return NL_FALSE; } nl_printf("OpenNL CUDA: Device ID = %d\n", CUDA()->devID); nl_printf("OpenNL CUDA: Device name=%s\n", deviceProp.name); nl_printf( "OpenNL CUDA: Device has %d Multi-Processors, " "%d cores per Multi-Processor, SM %d.%d compute capabilities\n", deviceProp.multiProcessorCount, ConvertSMVer2Cores(deviceProp.major, deviceProp.minor), deviceProp.major, deviceProp.minor ); nl_printf( "OpenNL CUDA: %d kB shared mem. per block, %d per MP\n", (int)(deviceProp.sharedMemPerBlock / 1024), (int)(deviceProp.sharedMemPerMultiprocessor / 1024) ); nl_printf( "OpenNL CUDA: %d regs. per block, %d per MP\n", deviceProp.regsPerBlock, deviceProp.regsPerMultiprocessor ); nl_printf( "OpenNL CUDA: warpsize=%d\n", deviceProp.warpSize ); if ((deviceProp.major * 0x10 + deviceProp.minor) < 0x11) { nl_fprintf(stderr, "OpenNL CUDA requires a minimum CUDA compute 1.1 capability\n"); CUDA()->cudaDeviceReset(); return NL_FALSE; } CUDA()->DLL_cublas = nlOpenDLL( LIBPREFIX "cublas" LIBEXTENSION, flags ); find_cublas_func(cublasCreate); find_cublas_func(cublasDestroy); find_cublas_func(cublasGetVersion); find_cublas_func(cublasDdot); find_cublas_func(cublasDaxpy); find_cublas_func(cublasDcopy); find_cublas_func(cublasDscal); find_cublas_func(cublasDnrm2); find_cublas_func(cublasDgemv); find_cublas_func(cublasDtpsv); find_cublas_func_v1(cublasDdgmm); if(CUDA()->cublasCreate(&CUDA()->HNDL_cublas)) { return NL_FALSE; } if(CUDA()->cublasGetVersion(CUDA()->HNDL_cublas, &cublas_version)) { return NL_FALSE; } nl_printf("OpenNL CUDA: cublas version = %d\n", cublas_version); CUDA()->DLL_cusparse = nlOpenDLL( LIBPREFIX "cusparse" LIBEXTENSION, flags ); find_cusparse_func(cusparseCreate); find_cusparse_func(cusparseDestroy); find_cusparse_func(cusparseGetVersion); find_cusparse_func(cusparseCreateMatDescr); find_cusparse_func(cusparseDestroyMatDescr); find_cusparse_func(cusparseSetMatType); find_cusparse_func(cusparseSetMatIndexBase); find_cusparse_func(cusparseDcsrmv); find_cusparse_func(cusparseCreateHybMat); find_cusparse_func(cusparseDestroyHybMat); find_cusparse_func(cusparseDcsr2hyb); find_cusparse_func(cusparseDhybmv); if(CUDA()->cusparseCreate(&CUDA()->HNDL_cusparse)) { return NL_FALSE; } if(CUDA()->cusparseGetVersion(CUDA()->HNDL_cusparse, &cusparse_version)) { return NL_FALSE; } nl_printf("OpenNL CUDA: cusparse version = %d\n", cusparse_version); if(!nlExtensionIsInitialized_CUDA()) { return NL_FALSE; } atexit(nlTerminateExtension_CUDA); return NL_TRUE; } static void nlCUDACheckImpl(int status, int line) { if(status != 0) { nl_fprintf(stderr,"nl_cuda.c:%d fatal error %d\n",line, status); CUDA()->cudaDeviceReset(); exit(-1); } } #define nlCUDACheck(status) nlCUDACheckImpl(status, __LINE__) typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; cusparseMatDescr_t descr; NLuint nnz; int* colind; int* rowptr; double* val; cusparseHybMat_t hyb; } NLCUDASparseMatrix; static void nlCRSMatrixCUDADestroyCRS(NLCUDASparseMatrix* Mcuda) { if(Mcuda->colind != NULL) { nlCUDACheck(CUDA()->cudaFree(Mcuda->colind)); Mcuda->colind = NULL; } if(Mcuda->rowptr != NULL) { nlCUDACheck(CUDA()->cudaFree(Mcuda->rowptr)); Mcuda->rowptr = NULL; } if(Mcuda->val != NULL) { nlCUDACheck(CUDA()->cudaFree(Mcuda->val)); Mcuda->val = NULL; } } static void nlCRSMatrixCUDADestroy(NLCUDASparseMatrix* Mcuda) { if(Mcuda->hyb != NULL) { nlCUDACheck(CUDA()->cusparseDestroyHybMat(Mcuda->hyb)); } nlCRSMatrixCUDADestroyCRS(Mcuda); nlCUDACheck(CUDA()->cusparseDestroyMatDescr(Mcuda->descr)); memset(Mcuda, 0, sizeof(*Mcuda)); } static void nlCRSMatrixCUDAMult( NLCUDASparseMatrix* Mcuda, const double* x, double* y ) { const double one = 1; const double zero = 0; if(Mcuda->hyb != NULL) { nlCUDACheck( CUDA()->cusparseDhybmv( CUDA()->HNDL_cusparse, CUSPARSE_OPERATION_NON_TRANSPOSE, &one, Mcuda->descr, Mcuda->hyb, x, &zero, y ) ); } else { nlCUDACheck( CUDA()->cusparseDcsrmv( CUDA()->HNDL_cusparse, CUSPARSE_OPERATION_NON_TRANSPOSE, (int)Mcuda->m, (int)Mcuda->n, (int)Mcuda->nnz, &one, Mcuda->descr, Mcuda->val, Mcuda->rowptr, Mcuda->colind, x, &zero, y ) ); } nlCUDABlas()->flops += (NLulong)(2*Mcuda->nnz); } NLMatrix nlCUDAMatrixNewFromCRSMatrix(NLMatrix M_in) { NLCUDASparseMatrix* Mcuda = NL_NEW(NLCUDASparseMatrix); NLCRSMatrix* M = (NLCRSMatrix*)(M_in); size_t colind_sz, rowptr_sz, val_sz; nl_assert(M_in->type == NL_MATRIX_CRS); nlCUDACheck(CUDA()->cusparseCreateMatDescr(&Mcuda->descr)); if(M->symmetric_storage) { nlCUDACheck(CUDA()->cusparseSetMatType( Mcuda->descr, CUSPARSE_MATRIX_TYPE_SYMMETRIC) ); } else { nlCUDACheck(CUDA()->cusparseSetMatType( Mcuda->descr, CUSPARSE_MATRIX_TYPE_GENERAL) ); } nlCUDACheck(CUDA()->cusparseSetMatIndexBase( Mcuda->descr, CUSPARSE_INDEX_BASE_ZERO) ); Mcuda->m = M->m; Mcuda->n = M->n; Mcuda->nnz = nlCRSMatrixNNZ(M); colind_sz = (size_t)Mcuda->nnz*sizeof(int); rowptr_sz = (size_t)(Mcuda->m+1)*sizeof(int); val_sz = (size_t)Mcuda->nnz*sizeof(double); nlCUDACheck(CUDA()->cudaMalloc((void**)&Mcuda->colind,colind_sz)); nlCUDACheck(CUDA()->cudaMalloc((void**)&Mcuda->rowptr,rowptr_sz)); nlCUDACheck(CUDA()->cudaMalloc((void**)&Mcuda->val,val_sz)); nlCUDACheck(CUDA()->cudaMemcpy( Mcuda->colind, M->colind, colind_sz, cudaMemcpyHostToDevice) ); nlCUDACheck(CUDA()->cudaMemcpy( Mcuda->rowptr, M->rowptr, rowptr_sz, cudaMemcpyHostToDevice) ); nlCUDACheck(CUDA()->cudaMemcpy( Mcuda->val, M->val, val_sz, cudaMemcpyHostToDevice) ); Mcuda->hyb=NULL; if(!M->symmetric_storage) { nlCUDACheck(CUDA()->cusparseCreateHybMat(&Mcuda->hyb)); nlCUDACheck(CUDA()->cusparseDcsr2hyb( CUDA()->HNDL_cusparse, (int)M->m, (int)M->n, Mcuda->descr, Mcuda->val, Mcuda->rowptr, Mcuda->colind, Mcuda->hyb, 0, CUSPARSE_HYB_PARTITION_AUTO )); /* We no longer need the CRS part */ nlCRSMatrixCUDADestroyCRS(Mcuda); } Mcuda->type=NL_MATRIX_OTHER; Mcuda->destroy_func=(NLDestroyMatrixFunc)nlCRSMatrixCUDADestroy; Mcuda->mult_func=(NLMultMatrixVectorFunc)nlCRSMatrixCUDAMult; return (NLMatrix)Mcuda; } typedef struct { NLuint m; NLuint n; NLenum type; NLDestroyMatrixFunc destroy_func; NLMultMatrixVectorFunc mult_func; double* val; } NLDiagonalMatrixCUDA; static void nlDiagonalMatrixCUDADestroy(NLDiagonalMatrixCUDA* Mcuda) { nlCUDACheck(CUDA()->cudaFree(Mcuda->val)); memset(Mcuda, 0, sizeof(*Mcuda)); } static void nlDiagonalMatrixCUDAMult( NLDiagonalMatrixCUDA* Mcuda, const double* x, double* y ) { int N = (int)Mcuda->n; /* * vector x vector component-wise product implemented * using diagonal matrix x matrix function. */ nlCUDACheck(CUDA()->cublasDdgmm( CUDA()->HNDL_cublas, CUBLAS_SIDE_LEFT, N, 1, x, N, Mcuda->val, 1, y, N )); nlCUDABlas()->flops += (NLulong)N; } static NLMatrix nlDiagonalMatrixCUDANew(const double* diag, NLuint n) { NLDiagonalMatrixCUDA* Mcuda = NL_NEW(NLDiagonalMatrixCUDA); Mcuda->m = n; Mcuda->n = n; Mcuda->type = NL_MATRIX_OTHER; nlCUDACheck(CUDA()->cudaMalloc( (void**)&Mcuda->val, n*sizeof(double)) ); nlCUDACheck(CUDA()->cudaMemcpy( Mcuda->val, diag, n*sizeof(double), cudaMemcpyHostToDevice) ); Mcuda->destroy_func=(NLDestroyMatrixFunc)nlDiagonalMatrixCUDADestroy; Mcuda->mult_func=(NLMultMatrixVectorFunc)nlDiagonalMatrixCUDAMult; return (NLMatrix)Mcuda; } NLMatrix nlCUDAJacobiPreconditionerNewFromCRSMatrix(NLMatrix M_in) { NLuint N = M_in->n; NLuint i,jj; double* diag = NULL; NLMatrix result = NULL; NLCRSMatrix* M = (NLCRSMatrix*)(M_in); nl_assert(M_in->type == NL_MATRIX_CRS); diag = NL_NEW_ARRAY(double,N); for(i=0; i<N; ++i) { for(jj=M->rowptr[i]; jj<M->rowptr[i+1]; ++jj) { if(M->colind[jj] == i) { diag[i] = M->val[jj]; } } } for(i=0; i<N; ++i) { diag[i] = ((diag[i] == 0.0) ? 1.0 : 1.0 / diag[i]); } result = nlDiagonalMatrixCUDANew(diag, N); NL_DELETE_ARRAY(diag); return result; } static void* cuda_blas_malloc( NLBlas_t blas, NLmemoryType type, size_t size ) { void* result = NULL; blas->used_ram[type] += (NLulong)size; blas->max_used_ram[type] = MAX( blas->max_used_ram[type],blas->used_ram[type] ); if(type == NL_HOST_MEMORY) { result = malloc(size); } else { nlCUDACheck(CUDA()->cudaMalloc(&result,size)); } return result; } static void cuda_blas_free( NLBlas_t blas, NLmemoryType type, size_t size, void* ptr ) { blas->used_ram[type] -= (NLulong)size; if(type == NL_HOST_MEMORY) { free(ptr); } else { nlCUDACheck(CUDA()->cudaFree(ptr)); } } static void cuda_blas_memcpy( NLBlas_t blas, void* to, NLmemoryType to_type, void* from, NLmemoryType from_type, size_t size ) { enum cudaMemcpyKind kind = cudaMemcpyDefault; nl_arg_used(blas); if(from_type == NL_HOST_MEMORY) { if(to_type == NL_HOST_MEMORY) { kind = cudaMemcpyHostToHost; } else { kind = cudaMemcpyHostToDevice; } } else { if(to_type == NL_HOST_MEMORY) { kind = cudaMemcpyDeviceToHost; } else { kind = cudaMemcpyDeviceToDevice; } } nlCUDACheck(CUDA()->cudaMemcpy(to, from, size, kind)); } static void cuda_blas_dcopy( NLBlas_t blas, int n, const double *x, int incx, double *y, int incy ) { nl_arg_used(blas); CUDA()->cublasDcopy(CUDA()->HNDL_cublas,n,x,incx,y,incy); } static double cuda_blas_ddot( NLBlas_t blas, int n, const double *x, int incx, const double *y, int incy ) { double result = 0.0; blas->flops += (NLulong)(2*n); CUDA()->cublasDdot(CUDA()->HNDL_cublas,n,x,incx,y,incy,&result); return result; } static double cuda_blas_dnrm2( NLBlas_t blas, int n, const double *x, int incx ) { double result = 0.0; blas->flops += (NLulong)(2*n); CUDA()->cublasDnrm2(CUDA()->HNDL_cublas,n,x,incx,&result); return result; } static void cuda_blas_daxpy( NLBlas_t blas, int n, double a, const double *x, int incx, double *y, int incy ) { blas->flops += (NLulong)(2*n); CUDA()->cublasDaxpy(CUDA()->HNDL_cublas,n,&a,x,incx,y,incy); } static void cuda_blas_dscal( NLBlas_t blas, int n, double a, double *x, int incx ) { blas->flops += (NLulong)n; CUDA()->cublasDscal(CUDA()->HNDL_cublas,n,&a,x,incx); } static void cuda_blas_dgemv( NLBlas_t blas, MatrixTranspose trans, int m, int n, double alpha, const double *A, int ldA, const double *x, int incx, double beta, double *y, int incy ) { nl_arg_used(blas); /* TODO: update FLOPS */ CUDA()->cublasDgemv( CUDA()->HNDL_cublas, (cublasOperation_t)trans, m, n, &alpha, A, ldA, x, incx, &beta, y, incy ); } static void cuda_blas_dtpsv( NLBlas_t blas, MatrixTriangle uplo, MatrixTranspose trans, MatrixUnitTriangular diag, int n, const double *AP, double *x, int incx ) { nl_arg_used(blas); /* TODO: update FLOPS */ CUDA()->cublasDtpsv( CUDA()->HNDL_cublas, (cublasFillMode_t)uplo, (cublasOperation_t)trans, (cublasDiagType_t)diag, n, AP, x, incx ); } NLBlas_t nlCUDABlas() { static NLboolean initialized = NL_FALSE; static struct NLBlas blas; if(!initialized) { memset(&blas, 0, sizeof(blas)); blas.has_unified_memory = NL_FALSE; blas.Malloc = cuda_blas_malloc; blas.Free = cuda_blas_free; blas.Memcpy = cuda_blas_memcpy; blas.Dcopy = cuda_blas_dcopy; blas.Ddot = cuda_blas_ddot; blas.Dnrm2 = cuda_blas_dnrm2; blas.Daxpy = cuda_blas_daxpy; blas.Dscal = cuda_blas_dscal; blas.Dgemv = cuda_blas_dgemv; blas.Dtpsv = cuda_blas_dtpsv; nlBlasResetStats(&blas); initialized = NL_TRUE; } return &blas; } /******* extracted from nl_api.c *******/ static NLSparseMatrix* nlGetCurrentSparseMatrix() { NLSparseMatrix* result = NULL; switch(nlCurrentContext->matrix_mode) { case NL_STIFFNESS_MATRIX: { nl_assert(nlCurrentContext->M != NULL); nl_assert(nlCurrentContext->M->type == NL_MATRIX_SPARSE_DYNAMIC); result = (NLSparseMatrix*)(nlCurrentContext->M); } break; case NL_MASS_MATRIX: { nl_assert(nlCurrentContext->B != NULL); nl_assert(nlCurrentContext->B->type == NL_MATRIX_SPARSE_DYNAMIC); result = (NLSparseMatrix*)(nlCurrentContext->B); } break; default: nl_assert_not_reached; } return result; } NLboolean nlInitExtension(const char* extension) { if(!strcmp(extension, "SUPERLU")) { return nlInitExtension_SUPERLU(); } else if(!strcmp(extension, "CHOLMOD")) { return nlInitExtension_CHOLMOD(); } else if(!strcmp(extension, "ARPACK")) { /* * SUPERLU is needed by OpenNL's ARPACK driver * (factorizes the matrix for the shift-invert spectral * transform). */ return nlInitExtension_SUPERLU() && nlInitExtension_ARPACK(); } else if(!strcmp(extension, "MKL")) { return nlInitExtension_MKL(); } else if(!strcmp(extension, "CUDA")) { return nlInitExtension_CUDA(); } return NL_FALSE; } NLboolean nlExtensionIsInitialized(const char* extension) { if(!strcmp(extension, "SUPERLU")) { return nlExtensionIsInitialized_SUPERLU(); } else if(!strcmp(extension, "CHOLMOD")) { return nlExtensionIsInitialized_CHOLMOD(); } else if(!strcmp(extension, "ARPACK")) { /* * SUPERLU is needed by OpenNL's ARPACK driver * (factorizes the matrix for the shift-invert spectral * transform). */ return nlExtensionIsInitialized_SUPERLU() && nlExtensionIsInitialized_ARPACK(); } else if(!strcmp(extension, "MKL")) { return nlExtensionIsInitialized_MKL(); } else if(!strcmp(extension, "CUDA")) { return nlExtensionIsInitialized_CUDA(); } return NL_FALSE; } void nlInitialize(int argc, char** argv) { int i=0; char* ptr=NULL; char extension[255]; /* Find all the arguments with the form: * nl:<extension>=true|false * and try to activate the corresponding extensions. */ for(i=1; i<argc; ++i) { ptr = strstr(argv[i],"=true"); if(!strncmp(argv[i], "nl:", 3) && (strlen(argv[i]) > 3) && (ptr != NULL)) { strncpy(extension, argv[i]+3, (size_t)(ptr-argv[i]-3)); extension[(size_t)(ptr-argv[i]-3)] = '\0'; if(nlInitExtension(extension)) { nl_fprintf(stdout,"OpenNL %s: initialized\n", extension); } else { nl_fprintf(stderr,"OpenNL %s: could not initialize\n", extension); } } } } /* Get/Set parameters */ void nlSolverParameterd(NLenum pname, NLdouble param) { nlCheckState(NL_STATE_INITIAL); switch(pname) { case NL_THRESHOLD: { nl_assert(param >= 0); nlCurrentContext->threshold = (NLdouble)param; nlCurrentContext->threshold_defined = NL_TRUE; } break; case NL_OMEGA: { nl_range_assert(param,1.0,2.0); nlCurrentContext->omega = (NLdouble)param; } break; default: { nlError("nlSolverParameterd","Invalid parameter"); nl_assert_not_reached; } } } void nlSolverParameteri(NLenum pname, NLint param) { nlCheckState(NL_STATE_INITIAL); switch(pname) { case NL_SOLVER: { nlCurrentContext->solver = (NLenum)param; } break; case NL_NB_VARIABLES: { nl_assert(param > 0); nlCurrentContext->nb_variables = (NLuint)param; } break; case NL_NB_SYSTEMS: { nl_assert(param > 0); nlCurrentContext->nb_systems = (NLuint)param; } break; case NL_LEAST_SQUARES: { nlCurrentContext->least_squares = (NLboolean)param; } break; case NL_MAX_ITERATIONS: { nl_assert(param > 0); nlCurrentContext->max_iterations = (NLuint)param; nlCurrentContext->max_iterations_defined = NL_TRUE; } break; case NL_SYMMETRIC: { nlCurrentContext->symmetric = (NLboolean)param; } break; case NL_INNER_ITERATIONS: { nl_assert(param > 0); nlCurrentContext->inner_iterations = (NLuint)param; } break; case NL_PRECONDITIONER: { nlCurrentContext->preconditioner = (NLuint)param; nlCurrentContext->preconditioner_defined = NL_TRUE; } break; default: { nlError("nlSolverParameteri","Invalid parameter"); nl_assert_not_reached; } } } void nlGetBooleanv(NLenum pname, NLboolean* params) { switch(pname) { case NL_LEAST_SQUARES: { *params = nlCurrentContext->least_squares; } break; case NL_SYMMETRIC: { *params = nlCurrentContext->symmetric; } break; default: { nlError("nlGetBooleanv","Invalid parameter"); nl_assert_not_reached; } } } void nlGetDoublev(NLenum pname, NLdouble* params) { switch(pname) { case NL_THRESHOLD: { *params = nlCurrentContext->threshold; } break; case NL_OMEGA: { *params = nlCurrentContext->omega; } break; case NL_ERROR: { *params = nlCurrentContext->error; } break; case NL_ELAPSED_TIME: { *params = nlCurrentContext->elapsed_time; } break; case NL_GFLOPS: { if(nlCurrentContext->elapsed_time == 0) { *params = 0.0; } else { *params = (NLdouble)(nlCurrentContext->flops) / (nlCurrentContext->elapsed_time * 1e9); } } break; default: { nlError("nlGetDoublev","Invalid parameter"); nl_assert_not_reached; } } } void nlGetIntegerv(NLenum pname, NLint* params) { switch(pname) { case NL_SOLVER: { *params = (NLint)(nlCurrentContext->solver); } break; case NL_NB_VARIABLES: { *params = (NLint)(nlCurrentContext->nb_variables); } break; case NL_NB_SYSTEMS: { *params = (NLint)(nlCurrentContext->nb_systems); } break; case NL_LEAST_SQUARES: { *params = (NLint)(nlCurrentContext->least_squares); } break; case NL_MAX_ITERATIONS: { *params = (NLint)(nlCurrentContext->max_iterations); } break; case NL_SYMMETRIC: { *params = (NLint)(nlCurrentContext->symmetric); } break; case NL_USED_ITERATIONS: { *params = (NLint)(nlCurrentContext->used_iterations); } break; case NL_PRECONDITIONER: { *params = (NLint)(nlCurrentContext->preconditioner); } break; case NL_NNZ: { *params = (NLint)(nlMatrixNNZ(nlCurrentContext->M)); } break; default: { nlError("nlGetIntegerv","Invalid parameter"); nl_assert_not_reached; } } } /* Enable / Disable */ void nlEnable(NLenum pname) { switch(pname) { case NL_NORMALIZE_ROWS: { nl_assert(nlCurrentContext->state != NL_STATE_ROW); nlCurrentContext->normalize_rows = NL_TRUE; } break; case NL_VERBOSE: { nlCurrentContext->verbose = NL_TRUE; } break; case NL_VARIABLES_BUFFER: { nlCurrentContext->user_variable_buffers = NL_TRUE; } break; default: { nlError("nlEnable","Invalid parameter"); nl_assert_not_reached; } } } void nlDisable(NLenum pname) { switch(pname) { case NL_NORMALIZE_ROWS: { nl_assert(nlCurrentContext->state != NL_STATE_ROW); nlCurrentContext->normalize_rows = NL_FALSE; } break; case NL_VERBOSE: { nlCurrentContext->verbose = NL_FALSE; } break; case NL_VARIABLES_BUFFER: { nlCurrentContext->user_variable_buffers = NL_FALSE; } break; default: { nlError("nlDisable","Invalid parameter"); nl_assert_not_reached; } } } NLboolean nlIsEnabled(NLenum pname) { NLboolean result = NL_FALSE; switch(pname) { case NL_NORMALIZE_ROWS: { result = nlCurrentContext->normalize_rows; } break; case NL_VERBOSE: { result = nlCurrentContext->verbose; } break; case NL_VARIABLES_BUFFER: { result = nlCurrentContext->user_variable_buffers; } break; default: { nlError("nlIsEnables","Invalid parameter"); nl_assert_not_reached; } } return result; } /* NL functions */ void nlSetFunction(NLenum pname, NLfunc param) { switch(pname) { case NL_FUNC_SOLVER: nlCurrentContext->solver_func = (NLSolverFunc)(param); nlCurrentContext->solver = NL_SOLVER_USER; break; case NL_FUNC_MATRIX: nlDeleteMatrix(nlCurrentContext->M); nlCurrentContext->M = nlMatrixNewFromFunction( nlCurrentContext->n, nlCurrentContext->n, (NLMatrixFunc)param ); break; case NL_FUNC_PRECONDITIONER: nlDeleteMatrix(nlCurrentContext->P); nlCurrentContext->P = nlMatrixNewFromFunction( nlCurrentContext->n, nlCurrentContext->n, (NLMatrixFunc)param ); nlCurrentContext->preconditioner = NL_PRECOND_USER; break; case NL_FUNC_PROGRESS: nlCurrentContext->progress_func = (NLProgressFunc)(param); break; default: nlError("nlSetFunction","Invalid parameter"); nl_assert_not_reached; } } void nlGetFunction(NLenum pname, NLfunc* param) { switch(pname) { case NL_FUNC_SOLVER: *param = (NLfunc)(nlCurrentContext->solver_func); break; case NL_FUNC_MATRIX: *param = (NLfunc)(nlMatrixGetFunction(nlCurrentContext->M)); break; case NL_FUNC_PRECONDITIONER: *param = (NLfunc)(nlMatrixGetFunction(nlCurrentContext->P)); break; default: nlError("nlGetFunction","Invalid parameter"); nl_assert_not_reached; } } /* Get/Set Lock/Unlock variables */ void nlSetVariable(NLuint index, NLdouble value) { nlCheckState(NL_STATE_SYSTEM); nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1); NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[0],index) = value; } void nlMultiSetVariable(NLuint index, NLuint system, NLdouble value) { nlCheckState(NL_STATE_SYSTEM); nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables-1); nl_debug_range_assert(system, 0, nlCurrentContext->nb_systems-1); NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[system],index) = value; } NLdouble nlGetVariable(NLuint index) { nl_assert(nlCurrentContext->state != NL_STATE_INITIAL); nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1); return NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[0],index); } NLdouble nlMultiGetVariable(NLuint index, NLuint system) { nl_assert(nlCurrentContext->state != NL_STATE_INITIAL); nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables-1); nl_debug_range_assert(system, 0, nlCurrentContext->nb_systems-1); return NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[system],index); } void nlLockVariable(NLuint index) { nlCheckState(NL_STATE_SYSTEM); nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1); nlCurrentContext->variable_is_locked[index] = NL_TRUE; } void nlUnlockVariable(NLuint index) { nlCheckState(NL_STATE_SYSTEM); nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1); nlCurrentContext->variable_is_locked[index] = NL_FALSE; } NLboolean nlVariableIsLocked(NLuint index) { nl_assert(nlCurrentContext->state != NL_STATE_INITIAL); nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1); return nlCurrentContext->variable_is_locked[index]; } /* System construction */ static void nlVariablesToVector() { NLuint n=nlCurrentContext->n; NLuint k,i,index; NLdouble value; nl_assert(nlCurrentContext->x != NULL); for(k=0; k<nlCurrentContext->nb_systems; ++k) { for(i=0; i<nlCurrentContext->nb_variables; ++i) { if(!nlCurrentContext->variable_is_locked[i]) { index = nlCurrentContext->variable_index[i]; nl_assert(index < nlCurrentContext->n); value = NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[k],i); nlCurrentContext->x[index+k*n] = value; } } } } static void nlVectorToVariables() { NLuint n=nlCurrentContext->n; NLuint k,i,index; NLdouble value; nl_assert(nlCurrentContext->x != NULL); for(k=0; k<nlCurrentContext->nb_systems; ++k) { for(i=0; i<nlCurrentContext->nb_variables; ++i) { if(!nlCurrentContext->variable_is_locked[i]) { index = nlCurrentContext->variable_index[i]; nl_assert(index < nlCurrentContext->n); value = nlCurrentContext->x[index+k*n]; NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[k],i) = value; } } } } static void nlBeginSystem() { NLuint k; nlTransition(NL_STATE_INITIAL, NL_STATE_SYSTEM); nl_assert(nlCurrentContext->nb_variables > 0); nlCurrentContext->variable_buffer = NL_NEW_ARRAY( NLBufferBinding, nlCurrentContext->nb_systems ); if(nlCurrentContext->user_variable_buffers) { nlCurrentContext->variable_value = NULL; } else { nlCurrentContext->variable_value = NL_NEW_ARRAY( NLdouble, nlCurrentContext->nb_variables * nlCurrentContext->nb_systems ); for(k=0; k<nlCurrentContext->nb_systems; ++k) { nlCurrentContext->variable_buffer[k].base_address = nlCurrentContext->variable_value + k * nlCurrentContext->nb_variables; nlCurrentContext->variable_buffer[k].stride = sizeof(NLdouble); } } nlCurrentContext->variable_is_locked = NL_NEW_ARRAY( NLboolean, nlCurrentContext->nb_variables ); nlCurrentContext->variable_index = NL_NEW_ARRAY( NLuint, nlCurrentContext->nb_variables ); } static void nlEndSystem() { nlTransition(NL_STATE_MATRIX_CONSTRUCTED, NL_STATE_SYSTEM_CONSTRUCTED); } static void nlInitializeM() { NLuint i; NLuint n = 0; NLenum storage = NL_MATRIX_STORE_ROWS; for(i=0; i<nlCurrentContext->nb_variables; i++) { if(!nlCurrentContext->variable_is_locked[i]) { nlCurrentContext->variable_index[i] = n; n++; } else { nlCurrentContext->variable_index[i] = (NLuint)~0; } } nlCurrentContext->n = n; /* * If the user trusts OpenNL and has left solver as NL_SOLVER_DEFAULT, * then we setup reasonable parameters for him. */ if(nlCurrentContext->solver == NL_SOLVER_DEFAULT) { if(nlCurrentContext->least_squares || nlCurrentContext->symmetric) { nlCurrentContext->solver = NL_CG; if(!nlCurrentContext->preconditioner_defined) { nlCurrentContext->preconditioner = NL_PRECOND_JACOBI; } } else { nlCurrentContext->solver = NL_BICGSTAB; } if(!nlCurrentContext->max_iterations_defined) { nlCurrentContext->max_iterations = n*5; } if(!nlCurrentContext->threshold_defined) { nlCurrentContext->threshold = 1e-6; } } /* SSOR preconditioner requires rows and columns */ if(nlCurrentContext->preconditioner == NL_PRECOND_SSOR) { storage = (storage | NL_MATRIX_STORE_COLUMNS); } /* a least squares problem results in a symmetric matrix */ if(nlCurrentContext->least_squares) { nlCurrentContext->symmetric = NL_TRUE; } if( nlCurrentContext->symmetric && nlCurrentContext->preconditioner == NL_PRECOND_SSOR ) { /* * For now, only used with SSOR preconditioner, because * for other modes it is either unsupported (SUPERLU) or * causes performance loss (non-parallel sparse SpMV) */ storage = (storage | NL_MATRIX_STORE_SYMMETRIC); } nlCurrentContext->M = (NLMatrix)(NL_NEW(NLSparseMatrix)); nlSparseMatrixConstruct( (NLSparseMatrix*)(nlCurrentContext->M), n, n, storage ); nlCurrentContext->x = NL_NEW_ARRAY( NLdouble, n*nlCurrentContext->nb_systems ); nlCurrentContext->b = NL_NEW_ARRAY( NLdouble, n*nlCurrentContext->nb_systems ); nlVariablesToVector(); nlRowColumnConstruct(&nlCurrentContext->af); nlRowColumnConstruct(&nlCurrentContext->al); nlCurrentContext->right_hand_side = NL_NEW_ARRAY( double, nlCurrentContext->nb_systems ); nlCurrentContext->current_row = 0; } static void nlEndMatrix() { nlTransition(NL_STATE_MATRIX, NL_STATE_MATRIX_CONSTRUCTED); nlRowColumnClear(&nlCurrentContext->af); nlRowColumnClear(&nlCurrentContext->al); if(!nlCurrentContext->least_squares) { nl_assert( nlCurrentContext->ij_coefficient_called || ( nlCurrentContext->current_row == nlCurrentContext->n ) ); } } static void nlBeginRow() { nlTransition(NL_STATE_MATRIX, NL_STATE_ROW); nlRowColumnZero(&nlCurrentContext->af); nlRowColumnZero(&nlCurrentContext->al); } static void nlScaleRow(NLdouble s) { NLRowColumn* af = &nlCurrentContext->af; NLRowColumn* al = &nlCurrentContext->al; NLuint nf = af->size; NLuint nl = al->size; NLuint i,k; for(i=0; i<nf; i++) { af->coeff[i].value *= s; } for(i=0; i<nl; i++) { al->coeff[i].value *= s; } for(k=0; k<nlCurrentContext->nb_systems; ++k) { nlCurrentContext->right_hand_side[k] *= s; } } static void nlNormalizeRow(NLdouble weight) { NLRowColumn* af = &nlCurrentContext->af; NLRowColumn* al = &nlCurrentContext->al; NLuint nf = af->size; NLuint nl = al->size; NLuint i; NLdouble norm = 0.0; for(i=0; i<nf; i++) { norm += af->coeff[i].value * af->coeff[i].value; } for(i=0; i<nl; i++) { norm += al->coeff[i].value * al->coeff[i].value; } norm = sqrt(norm); nlScaleRow(weight / norm); } static void nlEndRow() { NLRowColumn* af = &nlCurrentContext->af; NLRowColumn* al = &nlCurrentContext->al; NLSparseMatrix* M = nlGetCurrentSparseMatrix(); NLdouble* b = nlCurrentContext->b; NLuint nf = af->size; NLuint nl = al->size; NLuint n = nlCurrentContext->n; NLuint current_row = nlCurrentContext->current_row; NLuint i,j,jj; NLdouble S; NLuint k; nlTransition(NL_STATE_ROW, NL_STATE_MATRIX); if(nlCurrentContext->normalize_rows) { nlNormalizeRow(nlCurrentContext->row_scaling); } else if(nlCurrentContext->row_scaling != 1.0) { nlScaleRow(nlCurrentContext->row_scaling); } /* * if least_squares : we want to solve * A'A x = A'b */ if(nlCurrentContext->least_squares) { for(i=0; i<nf; i++) { for(j=0; j<nf; j++) { nlSparseMatrixAdd( M, af->coeff[i].index, af->coeff[j].index, af->coeff[i].value * af->coeff[j].value ); } } for(k=0; k<nlCurrentContext->nb_systems; ++k) { S = -nlCurrentContext->right_hand_side[k]; for(jj=0; jj<nl; ++jj) { j = al->coeff[jj].index; S += al->coeff[jj].value * NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[k],j); } for(jj=0; jj<nf; jj++) { b[ k*n+af->coeff[jj].index ] -= af->coeff[jj].value * S; } } } else { for(jj=0; jj<nf; ++jj) { nlSparseMatrixAdd( M, current_row, af->coeff[jj].index, af->coeff[jj].value ); } for(k=0; k<nlCurrentContext->nb_systems; ++k) { b[k*n+current_row] = nlCurrentContext->right_hand_side[k]; for(jj=0; jj<nl; ++jj) { j = al->coeff[jj].index; b[k*n+current_row] -= al->coeff[jj].value * NL_BUFFER_ITEM(nlCurrentContext->variable_buffer[k],j); } } } nlCurrentContext->current_row++; for(k=0; k<nlCurrentContext->nb_systems; ++k) { nlCurrentContext->right_hand_side[k] = 0.0; } nlCurrentContext->row_scaling = 1.0; } void nlCoefficient(NLuint index, NLdouble value) { nlCheckState(NL_STATE_ROW); nl_debug_range_assert(index, 0, nlCurrentContext->nb_variables - 1); if(nlCurrentContext->variable_is_locked[index]) { /* * Note: in al, indices are NLvariable indices, * within [0..nb_variables-1] */ nlRowColumnAppend(&(nlCurrentContext->al), index, value); } else { /* * Note: in af, indices are system indices, * within [0..n-1] */ nlRowColumnAppend( &(nlCurrentContext->af), nlCurrentContext->variable_index[index], value ); } } void nlAddIJCoefficient(NLuint i, NLuint j, NLdouble value) { NLSparseMatrix* M = nlGetCurrentSparseMatrix(); nlCheckState(NL_STATE_MATRIX); nl_debug_range_assert(i, 0, nlCurrentContext->nb_variables - 1); nl_debug_range_assert(j, 0, nlCurrentContext->nb_variables - 1); #ifdef NL_DEBUG for(NLuint i=0; i<nlCurrentContext->nb_variables; ++i) { nl_debug_assert(!nlCurrentContext->variable_is_locked[i]); } #endif nlSparseMatrixAdd(M, i, j, value); nlCurrentContext->ij_coefficient_called = NL_TRUE; } void nlAddIRightHandSide(NLuint i, NLdouble value) { nlCheckState(NL_STATE_MATRIX); nl_debug_range_assert(i, 0, nlCurrentContext->nb_variables - 1); #ifdef NL_DEBUG for(NLuint i=0; i<nlCurrentContext->nb_variables; ++i) { nl_debug_assert(!nlCurrentContext->variable_is_locked[i]); } #endif nlCurrentContext->b[i] += value; nlCurrentContext->ij_coefficient_called = NL_TRUE; } void nlMultiAddIRightHandSide(NLuint i, NLuint k, NLdouble value) { NLuint n = nlCurrentContext->n; nlCheckState(NL_STATE_MATRIX); nl_debug_range_assert(i, 0, nlCurrentContext->nb_variables - 1); nl_debug_range_assert(k, 0, nlCurrentContext->nb_systems - 1); #ifdef NL_DEBUG for(NLuint i=0; i<nlCurrentContext->nb_variables; ++i) { nl_debug_assert(!nlCurrentContext->variable_is_locked[i]); } #endif nlCurrentContext->b[i + k*n] += value; nlCurrentContext->ij_coefficient_called = NL_TRUE; } void nlRightHandSide(NLdouble value) { nlCurrentContext->right_hand_side[0] = value; } void nlMultiRightHandSide(NLuint k, NLdouble value) { nl_debug_range_assert(k, 0, nlCurrentContext->nb_systems - 1); nlCurrentContext->right_hand_side[k] = value; } void nlRowScaling(NLdouble value) { nlCheckState(NL_STATE_MATRIX); nlCurrentContext->row_scaling = value; } void nlBegin(NLenum prim) { switch(prim) { case NL_SYSTEM: { nlBeginSystem(); } break; case NL_MATRIX: { nlTransition(NL_STATE_SYSTEM, NL_STATE_MATRIX); if( nlCurrentContext->matrix_mode == NL_STIFFNESS_MATRIX && nlCurrentContext->M == NULL ) { nlInitializeM(); } } break; case NL_ROW: { nlBeginRow(); } break; default: { nl_assert_not_reached; } } } void nlEnd(NLenum prim) { switch(prim) { case NL_SYSTEM: { nlEndSystem(); } break; case NL_MATRIX: { nlEndMatrix(); } break; case NL_ROW: { nlEndRow(); } break; default: { nl_assert_not_reached; } } } /* nlSolve() driver routine */ NLboolean nlSolve() { NLboolean result; nlCheckState(NL_STATE_SYSTEM_CONSTRUCTED); nlCurrentContext->start_time = nlCurrentTime(); nlCurrentContext->elapsed_time = 0.0; nlCurrentContext->flops = 0; result = nlCurrentContext->solver_func(); nlVectorToVariables(); nlCurrentContext->elapsed_time = nlCurrentTime() - nlCurrentContext->start_time; nlTransition(NL_STATE_SYSTEM_CONSTRUCTED, NL_STATE_SOLVED); return result; } void nlUpdateRightHandSide(NLdouble* values) { /* * If we are in the solved state, get back to the * constructed state. */ nl_assert(nlCurrentContext->nb_systems == 1); if(nlCurrentContext->state == NL_STATE_SOLVED) { nlTransition(NL_STATE_SOLVED, NL_STATE_SYSTEM_CONSTRUCTED); } nlCheckState(NL_STATE_SYSTEM_CONSTRUCTED); memcpy(nlCurrentContext->x, values, nlCurrentContext->n * sizeof(double)); } /* Buffers management */ void nlBindBuffer( NLenum buffer, NLuint k, void* addr, NLuint stride ) { nlCheckState(NL_STATE_SYSTEM); nl_assert(nlIsEnabled(buffer)); nl_assert(buffer == NL_VARIABLES_BUFFER); nl_assert(k<nlCurrentContext->nb_systems); if(stride == 0) { stride = sizeof(NLdouble); } nlCurrentContext->variable_buffer[k].base_address = addr; nlCurrentContext->variable_buffer[k].stride = stride; } /* Eigen solver */ void nlMatrixMode(NLenum matrix) { NLuint n = 0; NLuint i; nl_assert( nlCurrentContext->state == NL_STATE_SYSTEM || nlCurrentContext->state == NL_STATE_MATRIX_CONSTRUCTED ); nlCurrentContext->state = NL_STATE_SYSTEM; nlCurrentContext->matrix_mode = matrix; nlCurrentContext->current_row = 0; nlCurrentContext->ij_coefficient_called = NL_FALSE; switch(matrix) { case NL_STIFFNESS_MATRIX: { /* Stiffness matrix is already constructed. */ } break ; case NL_MASS_MATRIX: { if(nlCurrentContext->B == NULL) { for(i=0; i<nlCurrentContext->nb_variables; ++i) { if(!nlCurrentContext->variable_is_locked[i]) { ++n; } } nlCurrentContext->B = (NLMatrix)(NL_NEW(NLSparseMatrix)); nlSparseMatrixConstruct( (NLSparseMatrix*)(nlCurrentContext->B), n, n, NL_MATRIX_STORE_ROWS ); } } break ; default: nl_assert_not_reached; } } void nlEigenSolverParameterd( NLenum pname, NLdouble val ) { switch(pname) { case NL_EIGEN_SHIFT: { nlCurrentContext->eigen_shift = val; } break; case NL_EIGEN_THRESHOLD: { nlSolverParameterd(pname, val); } break; default: nl_assert_not_reached; } } void nlEigenSolverParameteri( NLenum pname, NLint val ) { switch(pname) { case NL_EIGEN_SOLVER: { nlCurrentContext->eigen_solver = (NLenum)val; } break; case NL_SYMMETRIC: case NL_NB_VARIABLES: case NL_NB_EIGENS: case NL_EIGEN_MAX_ITERATIONS: { nlSolverParameteri(pname, val); } break; default: nl_assert_not_reached; } } void nlEigenSolve() { if(nlCurrentContext->eigen_value == NULL) { nlCurrentContext->eigen_value = NL_NEW_ARRAY( NLdouble,nlCurrentContext->nb_systems ); } nlMatrixCompress(&nlCurrentContext->M); if(nlCurrentContext->B != NULL) { nlMatrixCompress(&nlCurrentContext->B); } switch(nlCurrentContext->eigen_solver) { case NL_ARPACK_EXT: nlEigenSolve_ARPACK(); break; default: nl_assert_not_reached; } } double nlGetEigenValue(NLuint i) { nl_debug_assert(i < nlCurrentContext->nb_variables); return nlCurrentContext->eigen_value[i]; }
4a96122257743f573717ca0f180d4478d508a3ee
786de89be635eb21295070a6a3452f3a7fe6712c
/pypdsdata/tags/0.8/src/types/pnCCD/ConfigV1.cpp
454f1aec49bb07e9d902c59cf77e868471c6fcf9
[]
no_license
connectthefuture/psdmrepo
85267cfe8d54564f99e17035efe931077c8f7a37
f32870a987a7493e7bf0f0a5c1712a5a030ef199
refs/heads/master
2021-01-13T03:26:35.494026
2015-09-03T22:22:11
2015-09-03T22:22:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,706
cpp
//-------------------------------------------------------------------------- // File and Version Information: // $Id$ // // Description: // Class ConfigV1... // // Author List: // Andrei Salnikov // //------------------------------------------------------------------------ //----------------------- // This Class's Header -- //----------------------- #include "ConfigV1.h" //----------------- // C/C++ Headers -- //----------------- //------------------------------- // Collaborating Class Headers -- //------------------------------- #include "Exception.h" #include "types/TypeLib.h" #include "types/camera/FrameCoord.h" //----------------------------------------------------------------------- // Local Macros, Typedefs, Structures, Unions and Forward Declarations -- //----------------------------------------------------------------------- namespace { // methods FUN0_WRAPPER(pypdsdata::PNCCD::ConfigV1, numLinks) FUN0_WRAPPER(pypdsdata::PNCCD::ConfigV1, payloadSizePerLink) PyMethodDef methods[] = { {"numLinks", numLinks, METH_NOARGS, "Returns number of links." }, {"payloadSizePerLink", payloadSizePerLink, METH_NOARGS, "Returns data size per link." }, {0, 0, 0, 0} }; char typedoc[] = "Python class wrapping C++ Pds::PNCCD::ConfigV1 class."; } // ---------------------------------------- // -- Public Function Member Definitions -- // ---------------------------------------- void pypdsdata::PNCCD::ConfigV1::initType( PyObject* module ) { PyTypeObject* type = BaseType::typeObject() ; type->tp_doc = ::typedoc; type->tp_methods = ::methods; BaseType::initType( "ConfigV1", module ); }
[ "salnikov@b967ad99-d558-0410-b138-e0f6c56caec7" ]
salnikov@b967ad99-d558-0410-b138-e0f6c56caec7
146667344c2c1171d15ff754316cad6a1370c9ce
ce152a04306cf4ae69ff0c462e7016de376eba47
/1062.cpp
aba7355190855a4f174b0265e5da66afcde522a3
[]
no_license
the-badcoder/UVA-Solutions
9038384e657acf810bd2eb6e356d4b8c47117c73
b061787a998d4456fec290f896f80c12590eb256
refs/heads/master
2018-09-22T11:23:22.380688
2018-09-15T14:32:14
2018-09-15T14:32:14
105,517,803
1
1
null
null
null
null
UTF-8
C++
false
false
2,445
cpp
/// Bismillah Hir Rahmanir Rahim #include <bits/stdc++.h> using namespace std; using ll = long long; using vi = vector<int>; using ii = pair <int, int>; using vii = vector<ii>; #define ff first #define ss second #define sz(x) (x).size() #define space " " #define all(x) (x).begin(), (x).end() #define eprintf(...) fprintf(stderr, __VA_ARGS__) /* template <class T> T gcd(T a,T b){ if(b == 0) return a; return gcd( b,a % b ); } template <class T> T lcm(T a, T b ){ return ( a / gcd( a,b ) ) * b; } template<class T> string ToString(const T &x){ stringstream s; s << x; return s.str(); } template<class T> int ToInteger(const T &x){ stringstream s; s << x; int r; s >> r; return r; } */ template<class T1> void deb(T1 e1) { cout << e1 << endl; } template<class T1,class T2> void deb(T1 e1, T2 e2) { cout << e1 << space << e2 << endl; } template<class T1,class T2,class T3> void deb(T1 e1, T2 e2, T3 e3) { cout << e1 << space << e2 << space << e3 << endl; } #define pf printf #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 sf4(a,b,c,d) scanf("%d %d %d %d", &a, &b, &c, &d) #define sf1ll(a) scanf("%lld", &a) #define sf2ll(a,b) scanf("%lld %lld", &a, &b) #define sf3ll(a,b,c) scanf("%lld %lld %lld", &a, &b, &c) #define sf4ll(a,b,c,d) scanf("%lld %lld %lld %lld", &a, &b, &c, &d) #define READ freopen("in.txt", "r", stdin); #define WRITE freopen("out.txt", "w", stdout); /// The End. const int res = 1e6 + 10; const ll mod = 1e9 + 7; stack <char> st; vector < stack <char> > vs; string s; int loop = 0; int check( int x ) { for( int i = 0; i < vs.size(); i++ ) { if( s[ x ] <= vs[ i ].top() ) { vs[ i ].push( s[ x ] ); return 0; } } vs.push_back( st ); vs[ vs.size() - 1 ].push( s[ x ] ); return 1; } int main() { while( cin >> s ) { int ans = 0; vs.clear(); if( s == "end" ) { break; } int len = s.size(); for( int i = 0; i < len; i++ ) { ans += check( i ); } printf("Case %d: %d\n", ++loop, ans ); } return 0; }
cbb5ea0f6eadede1af2ce6a67dcdc7b751de9331
eabffc4df9bcb5b98a64242c544f45be4bfe85f3
/Project_Uno/Project_Uno_Tos/Uno_V14/main.cpp
6b64bc2e2fab20f79e72f32b95c13d6d37f425a9
[]
no_license
Dredz223/Fall_Class_2018_Csc5
7d1086a8fc31a6cd3151bc5adfd68a9f247575a9
8c404cbfd560293b3558b474bc10d2fd961eae48
refs/heads/master
2020-04-04T22:33:47.099653
2018-12-15T02:51:18
2018-12-15T02:51:18
156,328,113
0
0
null
null
null
null
UTF-8
C++
false
false
28,609
cpp
/* * File: main.cpp * Author: Andres Guerrero Maldonado * Created on December 9th, 2018 8:40PM * Purpose: Uno Project_V14 * */ //System Libraries #include <iostream> //I/O Library -> cout,endl #include <cstdlib> //Random Library #include <cstring> //String Library #include <ctime> //Time Library #include <fstream> //Stream Library #include <iomanip> //I/o Manip Library #include <cmath> //Math Library using namespace std;//namespace I/O stream library created //User Libraries //Global Constants //Math, Physics, Science, Conversions, 2-D Array Columns //Function Prototypes void Rules(); //Rules function void filDeck(string [],int); //Fill the deck 1-9, Red, Green, Blue, Yellow void prnDeck(string [],int,int); //Print the Deck of Cards void shuffle(string [],int,int); //Shuffle the Deck //Execution Begins Here! int main(int argc, char** argv) { //Initialize random seed srand(static_cast<unsigned int>(time(0))); //Declare Variables const int NUMCRDS=72; //Size of the Deck const int NUMCRDZ=57; //Size of the Deck that will be randomized int n2Shufl=7; //How many times to Shuffle the Deck string deck[NUMCRDS]; //72 Cards represented as a string Face|Suit string hand1; //Hand 1 display 7 cards string strtCD,tempCD; //Starting card where we compare to other hands string player1,player2;//Player Names string tempN,tempC; string null[NUMCRDS]; //array with no values int numhnd=7,tempH1,tempH2; bool end, //End Condition turn, //Used when player 1 is skipped and to not repeat p2's turn lturn; //Used to not repeat p2's turn after already played int count=2; //used to force end game float pnts; //Points awarded //Displays Rules Rules(); cout<<endl; //Ask the players for their name cout<<"This is a game of UNO!"<<endl; cout<<"Enter the names of the 2 players!"<<endl; cin>>player1>>player2;//Insert the names of the players //Initial Variables filDeck(deck,NUMCRDS); //Print the Cards cout<<"Fresh Deck of Cards before Shuffling"<<endl; prnDeck(deck,NUMCRDS,NUMCRDS/8); //Print the Cards shuffle(deck,NUMCRDS,n2Shufl); //Print the Cards cout<<"Deck of Cards after Shuffling"<<endl; prnDeck(deck,NUMCRDS,NUMCRDS/8); //Getting Starting card strtCD=deck[14+rand()%(NUMCRDZ)]; cout<<"The starting card is: "<<strtCD<<endl; //Hand 1 display 7 cards cout<<"============================================="<<endl; cout<<player1<<"'s hand is: "<<endl; for(int i=0;i<7;i++){ cout<<"Card "<<i+1<<": "<<deck[i]<<endl; } string card1 = deck[0]; string card2 = deck[1]; string card3 = deck[2]; string card4 = deck[3]; string card5 = deck[4]; string card6 = deck[5]; string card7 = deck[6]; cout<<"============================================="<<endl; //Hand 2 display 7 cards cout<<player2<<"'s hand is: "<<endl; for(int i=7;i<14;i++){ cout<<"Card "<<i-6<<": "<<deck[i]<<endl; } string card8 = deck[7]; string card9 = deck[8]; string card10 = deck[9]; string card11 = deck[10]; string card12 = deck[11]; string card13 = deck[12]; string card14 = deck[13]; cout<<"============================================="<<endl; //return 0; //Initialize Variables end = false; //condition to end the game //Map/Process Inputs to Outputs //Display Player names cout<<"Players: "<<player1<<", "<<player2<<endl; //Display starting deck cout<<"The starting card for the game is: "<<strtCD<<endl; cout<<"============================================="<<endl; //Player one goes first card 1-7 check //Start if statement with a color check //card[1] represents color, cards[0] represents number //Player 1 goes first cout<<player1<<"'s turn"<<endl; if(card1[1] == strtCD[1] || card1[0] == strtCD[0]){ tempN = card1[0]; tempC = card1[1]; tempCD = card1; card1 = null[0]; tempH1 = numhnd -1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card2[1] == strtCD[1] || card2[0] == strtCD[0]){ tempN = card2[0]; tempC = card2[1]; tempCD = card2; card2 = null[1]; tempH1 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card3[1] == strtCD[1] || card3[0] == strtCD[0]){ tempN = card3[0]; tempC = card3[1]; tempCD = card3; card3 = null[2]; tempH1 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card4[1] == strtCD[1] || card4[0] == strtCD[0]){ tempN = card4[0]; tempC = card4[1]; tempCD = card4; card4 = null[3]; tempH1 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card5[1] == strtCD[1] || card5[0] == strtCD[0]){ tempN = card5[0]; tempC = card5[1]; tempCD = card5; card5 = null[4]; tempH1 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card6[1] == strtCD[1] || card6[0] == strtCD[0]){ tempN = card6[0]; tempC = card6[1]; tempCD = card6; card6 = null[5]; tempH1 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card7[1] == strtCD[1] || card7[0] == strtCD[0]){ tempN = card7[0]; tempC = card7[1]; tempCD = card7; card7 = null[6]; tempH1 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else{ cout<<"No cards available to play!!!"<<endl; cout<<"The number of cards left in "<<player1<<"'s current hand is " <<numhnd<<endl; cout<<"============================================="<<endl; cout<<player1<<"'s turn is skipped"<<endl; //Player 2's turn if player 1 was skipped cout<<player2<<"'s turn"<<endl; if(card8[1] == strtCD[1] || card8[0] == strtCD[0]){ tempN = card8[0]; tempC = card8[1]; tempCD = card8; card8 = null[7]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; turn = false; } else if(card9[1] == strtCD[1] || card9[0] == strtCD[0]){ tempN = card9[0]; tempC = card9[1]; tempCD = card9; card9 = null[8]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; turn = false; } else if(card10[1] == strtCD[1] || card10[0] == strtCD[0]){ tempN = card10[0]; tempC = card10[1]; tempCD = card10; card10 = null[9]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; turn = false; } else if(card11[1] == strtCD[1] || card11[0] == strtCD[0]){ tempN = card11[0]; tempC = card11[1]; tempCD = card11; card11 = null[10]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; turn = false; } else if(card12[1] == strtCD[1] || card12[0] == strtCD[0]){ tempN = card12[0]; tempC = card12[1]; tempCD = card12; card12 = null[11]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; turn = false; } else if(card13[1] == strtCD[1] || card13[0] == strtCD[0]){ tempN = card13[0]; tempC = card13[1]; tempCD = card13; card13 = null[12]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; turn = false; } else if(card14[1] == strtCD[1] || card14[0] == strtCD[0]){ tempN = card14[0]; tempC = card14[1]; tempCD = card14; card14 = null[13]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; turn = false; } else{ cout<<"No cards available!!!"<<endl; //cout<<player2<<"'s current hand is "<<hand<<endl; cout<<player2<<"'s turn skipped"<<endl; cout<<"============================================="<<endl; turn = false; } } //Player 2 after player 1 had played a card cout<<player2<<"'s turn"<<endl; do{ if(card8[1] == tempCD[1] || card8[0] == tempCD[0]){ tempN = card8[0]; tempC = card8[1]; tempCD = card8; card8 = null[0]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; turn = false; cout<<"============================================="<<endl; } else if(card9[1] == tempCD[1] || card9[0] == tempCD[0]){ tempN = card9[0]; tempC = card9[1]; tempCD = card9; card9 = null[0]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; turn = false; cout<<"============================================="<<endl; } else if(card10[1] == tempCD[1] || card10[0] == tempCD[0]){ tempN = card10[0]; tempC = card10[1]; tempCD = card10; card10 = null[0]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; turn = false; cout<<"============================================="<<endl; } else if(card11[1] == tempCD[1] || card11[0] == tempCD[0]){ tempN = card11[0]; tempC = card11[1]; tempCD = card11; card11 = null[0]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; turn = false; cout<<"============================================="<<endl; } else if(card12[1] == tempCD[1] || card12[0] == tempCD[0]){ tempN = card12[0]; tempC = card12[1]; tempCD = card12; card12 = null[0]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; turn = false; cout<<"============================================="<<endl; } else if(card13[1] == tempCD[1] || card13[0] == tempCD[0]){ tempN = card13[0]; tempC = card13[1]; tempCD = card13; card13 = null[0]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; turn = false; cout<<"============================================="<<endl; } else if(card14[1] == tempCD[1] || card14[0] == tempCD[0]){ tempN = card14[0]; tempC = card14[1]; tempCD = card14; card14 = null[0]; tempH2 = numhnd - 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; turn = false; cout<<"============================================="<<endl; } else{ cout<<"No cards available!!!"<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; turn = false; cout<<"============================================="<<endl; cout<<player2<<"'s turn skipped"<<endl; } }while(turn); //MAJOR DO WHILE LOOP AHEAD //Repeat loop turn 2 and beyond until player a has 1 card and says "UNO" do{ cout<<player1<<"'s turn"<<endl; if(card1[1] == tempCD[1] || card1[0] == tempCD[0]){ tempN = card1[0]; tempC = card1[1]; tempCD = card1; card1 = null[0]; tempH1 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card2[1] == tempCD[1] || card2[0] == tempCD[0]){ tempN = card2[0]; tempC = card2[1]; tempCD = card2; card2 = null[0]; tempH1 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card3[1] == tempCD[1] || card3[0] == tempCD[0]){ tempN = card3[0]; tempC = card3[1]; tempCD = card3; card3 = null[0]; tempH1 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card4[1] == tempCD[1] || card4[0] == tempCD[0]){ tempN = card4[0]; tempC = card4[1]; tempCD= card4; tempH1 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card5[1] == tempCD[1] || card5[0] == tempCD[0]){ tempN = card5[0]; tempC = card5[1]; tempCD = card5; card5 = null[0]; tempH1 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else if(card6[1] == tempCD[1] || card6[0] == tempCD[0]){ tempN = card6[0]; tempC = card6[1]; tempCD = card6; card6 = null[0]; tempH1 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl;; cout<<"============================================="<<endl; } else if(card7[1] == tempCD[1] || card7[0] == tempCD[0]){ tempN = card7[0]; tempC = card7[1]; tempCD = card7; card7 = null[0]; tempH1 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player1<<"'s hand is " <<tempH1<<endl; cout<<"============================================="<<endl; } else{ cout<<"No cards available to play!!!"<<endl; //cout<<player1<<"'s current hand is "<<hand<<endl; cout<<player1<<"'s turn is skipped"<<endl; cout<<"============================================="<<endl; //Player 2's turn if player 1 was skipped cout<<player2<<"'s turn"<<endl; if(card8[1] == tempCD[1] || card8[0] == tempCD[0]){ tempN = card8[0]; tempC = card8[1]; tempCD = card8; card8 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; lturn = false; cout<<"============================================="<<endl; } else if(card9[1] == tempCD[1] || card9[0] == tempCD[0]){ tempN = card9[0]; tempC = card9[1]; tempCD = card9; card9 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; lturn = false; cout<<"============================================="<<endl; } else if(card10[1] == tempCD[1] || card10[0] == tempCD[0]){ tempN = card10[0]; tempC = card10[1]; tempCD = card10; card10 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; lturn = false; cout<<"============================================="<<endl; } else if(card11[1] == tempCD[1] || card11[0] == tempCD[0]){ tempN = card11[0]; tempC = card11[1]; tempCD = card11; card11 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; lturn = false; cout<<"============================================="<<endl; } else if(card12[1] == tempCD[1] || card12[0] == tempCD[0]){ tempN = card12[0]; tempC = card12[1]; tempCD = card12; card12 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; lturn = false; cout<<"============================================="<<endl; } else if(card13[1] == tempCD[1] || card13[0] == tempCD[0]){ tempN = card13[0]; tempC = card13[1]; tempCD = card13; card13 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; lturn = false; cout<<"============================================="<<endl; } else if(card14[1] == tempCD[1] || card14[0] == tempCD[0]){ tempN = card14[0]; tempC = card14[1]; tempCD = card14; card14 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; lturn = false; cout<<"============================================="<<endl; } else{ cout<<"No cards available!!!"<<endl; //cout<<player2<<"'s current hand is "<<hand<<endl; cout<<player2<<"'s turn skipped"<<endl; cout<<"============================================="<<endl; } } //says uno for player 1 if(tempH1 == 1){ cout<<player1<<" UNO!!!"<<endl; cout<<"============================================="<<endl; } //Player 2 if player 1 plays a card cout<<player2<<"'s turn"<<endl; do{ if(card8[1] == tempCD[1] || card8[0] == tempCD[0]){ tempN = card8[0]; tempC = card8[1]; tempCD = card8; card8 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; } else if(card9[1] == tempCD[1] || card9[0] == tempCD[0]){ tempN = card9[0]; tempC = card9[1]; tempCD = card9; card9 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; } else if(card10[1] == tempCD[1] || card10[0] == tempCD[0]){ tempN = card10[0]; tempC = card10[1]; tempCD = card10; card10 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; } else if(card11[1] == tempCD[1] || card11[0] == tempCD[0]){ tempN = card11[0]; tempC = card11[1]; tempCD = card11; card11 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; } else if(card12[1] == tempCD[1] || card12[0] == tempCD[0]){ tempN = card12[0]; tempC = card12[1]; tempCD = card12; card12 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; } else if(card13[1] == tempCD[1] || card13[0] == tempCD[0]){ tempN = card13[0]; tempC = card13[1]; tempCD = card13; card13 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; } else if(card14[1] == tempCD[1] || card14[0] == tempCD[0]){ tempN = card14[0]; tempC = card14[1]; tempCD = card14; card14 = null[0]; tempH2 -= 1; cout<<"The new deck is: "<<tempCD<<endl; cout<<"The number of cards left in "<<player2<<"'s hand is " <<tempH2<<endl; cout<<"============================================="<<endl; } else{ cout<<"No cards available!!!"<<endl; cout<<player2<<"'s turn skipped"<<endl; cout<<"============================================="<<endl; } }while(lturn); //Player hands used to display UNO!!! and end game //Ends game player 1 wins if(tempH1 == 0){ end = true; cout<<player1<<" Wins! Congratulations! "<<endl; cout<<"============================================="<<endl; } //Says Uno if(tempH2 == 1){ cout<<player2<<" UNO!!!"<<endl; cout<<"============================================="<<endl; } //Ends game player 2 wins if(tempH2 == 0){ end = true; cout<<player2<<" Wins! Congratulations! "<<endl; cout<<"============================================="<<endl; } //Counter used to end game where the game cannot be finished count++; if(count==15){ cout<<"Game cannot be finished!!!"<<endl; end = true; } }while (end == false); //Exit program! return 0; } void Rules(){ string line; fstream inputFile; //open file inputFile.open("Rules.txt"); if(inputFile.is_open()){ while(getline(inputFile,line)){ cout<<line<<"\n"; } inputFile.close(); } } void shuffle(string c[],int nCrd,int nShuf){ for(int shuf=1;shuf<=nShuf;shuf++){ for(int card=0;card<nCrd;card++){ int indx=rand()%nCrd; string temp=c[card]; c[card]=c[indx]; c[indx]=temp; } } } void prnDeck(string c[],int n,int perLine){ for(int i=0;i<n;i++){ cout<<c[i]<<" "; if(i%perLine==(perLine-1))cout<<endl; } cout<<endl; } void filDeck(string c[],int n){ //Red, Blue, Green, Yellow char suit[]={'R','B','G','Y'}; char face[]={'1','2','3','4','5','6','7','8','9', '1','2','3','4','5','6','7','8','9'}; for(int i=0;i<n;i++){ c[i]=face[i%18]; c[i]+=suit[i/18]; } }
427460ace16471358f937e8a1e445c2160331979
5a443213123cdaccae8e9b374d872bd1740d80b5
/oap-native-sql/cpp/src/third_party/row_wise_memory/unsafe_row.h
1954ba143b54ac310e6886b52895b20306910c63
[ "Apache-2.0" ]
permissive
haojinIntel/OAP
8f8f5c8c32ab597a6d436e8c0719afad1cfae248
b892390f880af43486abb28268dd1f14f178a64f
refs/heads/master
2020-11-25T18:40:45.798287
2020-11-04T07:06:02
2020-11-04T07:06:02
228,792,909
1
0
Apache-2.0
2019-12-18T09:14:44
2019-12-18T08:25:48
null
UTF-8
C++
false
false
5,953
h
#pragma once #include <arrow/util/decimal.h> #include <assert.h> #include <inttypes.h> #include <stdlib.h> #include <string.h> #include <string> #include "third_party/row_wise_memory/native_memory.h" #define TEMP_UNSAFEROW_BUFFER_SIZE 1024 typedef struct { int numFields; int sizeInBytes; char* data; int cursor; } UnsafeRow; /* Unsafe Row Layout as below * * | validity | col 0 | col 1 | col 2 | ... | cursor | * explain: * validity: 64 * n fields = 8 * n bytes * col: each col is 8 bytes, string col should be offsetAndLength * cursor: used by string data * */ static inline int calculateBitSetWidthInBytes(int numFields) { return ((numFields + 63) / 64) * 8; } static inline int64_t getFieldOffset(UnsafeRow* row, int ordinal) { int bitSetWidthInBytes = calculateBitSetWidthInBytes(row->numFields); return bitSetWidthInBytes + ordinal * 8LL; } static inline void initTempUnsafeRow(UnsafeRow* row, int numFields) { if (row) { row->numFields = numFields; row->data = (char*)nativeMalloc(TEMP_UNSAFEROW_BUFFER_SIZE, MEMTYPE_ROW); auto validity_size = calculateBitSetWidthInBytes(numFields); memset(row->data, 0, validity_size); row->cursor = getFieldOffset(row, numFields); row->sizeInBytes = row->cursor; } } static inline void releaseTempUnsafeRow(UnsafeRow* row) { if (row && row->data) { nativeFree(row->data); } } static inline int getSizeInBytes(UnsafeRow* row) { return row->sizeInBytes; } static inline bool isEqualUnsafeRow(UnsafeRow* row0, UnsafeRow* row1) { if (row0->sizeInBytes != row1->sizeInBytes) return false; return (memcmp(row0->data, row1->data, row0->sizeInBytes) == 0); } static inline int roundNumberOfBytesToNearestWord(int numBytes) { int remainder = numBytes & 0x07; // This is equivalent to `numBytes % 8` if (remainder == 0) { return numBytes; } else { return numBytes + (8 - remainder); } } static inline void zeroOutPaddingBytes(UnsafeRow* row, int numBytes) { if ((numBytes & 0x07) > 0) { *((int64_t*)(char*)(row->data + row->cursor + ((numBytes >> 3) << 3))) = 0L; } } static inline void setNullAt(UnsafeRow* row, int index) { assert((index >= 0) && (index < row->numFields)); int64_t mask = 1LL << (index & 0x3f); // mod 64 and shift int64_t wordOffset = (index >> 6) * WORD_SIZE; int64_t word = *((int64_t*)(char*)(row->data + wordOffset)); // set validity *((int64_t*)(row->data + wordOffset)) = word | mask; // set data *((int64_t*)(row->data + getFieldOffset(row, index))) = 0; } static inline void setNotNullAt(UnsafeRow* row, int index) { assert((index >= 0) && (index < row->numFields)); int64_t mask = 1LL << (index & 0x3f); // mod 64 and shift int64_t wordOffset = (index >> 6) * WORD_SIZE; int64_t word = *((int64_t*)(char*)(row->data + wordOffset)); // set validity *((int64_t*)(row->data + wordOffset)) = word & ~mask; } static inline void setOffsetAndSize(UnsafeRow* row, int ordinal, int64_t size) { int64_t relativeOffset = row->cursor; int64_t fieldOffset = getFieldOffset(row, ordinal); int64_t offsetAndSize = (relativeOffset << 32) | size; // set data *((int64_t*)(char*)(row->data + fieldOffset)) = offsetAndSize; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, bool val) { setNotNullAt(row, index); int64_t offset = getFieldOffset(row, index); *((int64_t*)(row->data + offset)) = val; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, int8_t val) { setNotNullAt(row, index); int64_t offset = getFieldOffset(row, index); *((int64_t*)(row->data + offset)) = val; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, uint8_t val) { appendToUnsafeRow(row, index, static_cast<int8_t>(val)); } static inline void appendToUnsafeRow(UnsafeRow* row, int index, int16_t val) { setNotNullAt(row, index); int64_t offset = getFieldOffset(row, index); uint64_t longValue = (uint64_t)(uint16_t)val; *((int64_t*)(char*)(row->data + offset)) = longValue; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, uint16_t val) { appendToUnsafeRow(row, index, static_cast<int16_t>(val)); } static inline void appendToUnsafeRow(UnsafeRow* row, int index, int32_t val) { setNotNullAt(row, index); int64_t offset = getFieldOffset(row, index); uint64_t longValue = (uint64_t)(unsigned int)val; *((int64_t*)(char*)(row->data + offset)) = longValue; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, uint32_t val) { appendToUnsafeRow(row, index, static_cast<int32_t>(val)); } static inline void appendToUnsafeRow(UnsafeRow* row, int index, int64_t val) { setNotNullAt(row, index); int64_t offset = getFieldOffset(row, index); *((int64_t*)(char*)(row->data + offset)) = val; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, uint64_t val) { appendToUnsafeRow(row, index, static_cast<int64_t>(val)); } static inline void appendToUnsafeRow(UnsafeRow* row, int index, float val) { setNotNullAt(row, index); int64_t offset = getFieldOffset(row, index); double longValue = (double)val; *((double*)(char*)(row->data + offset)) = val; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, double val) { setNotNullAt(row, index); int64_t offset = getFieldOffset(row, index); *((double*)(char*)(row->data + offset)) = val; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, std::string str) { int numBytes = str.size(); int roundedSize = roundNumberOfBytesToNearestWord(numBytes); setNotNullAt(row, index); zeroOutPaddingBytes(row, numBytes); memcpy(row->data + row->cursor, str.c_str(), numBytes); setOffsetAndSize(row, index, numBytes); // move the cursor forward. row->cursor += roundedSize; row->sizeInBytes = row->cursor; } static inline void appendToUnsafeRow(UnsafeRow* row, int index, arrow::Decimal128 dcm, int precision, int scale) {}
6709b905feb7467620da6dcd62252ce952f83df2
66862c422fda8b0de8c4a6f9d24eced028805283
/slambook2/3rdparty/Pangolin/external/pybind11/tests/test_constants_and_functions.cpp
f5f9340959b6e1a6caee2ba95e5ed974393256e0
[ "MIT", "BSD-3-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
zhh2005757/slambook2_in_Docker
57ed4af958b730e6f767cd202717e28144107cdb
f0e71327d196cdad3b3c10d96eacdf95240d528b
refs/heads/main
2023-09-01T03:26:37.542232
2021-10-27T11:45:47
2021-10-27T11:45:47
416,666,234
17
6
MIT
2021-10-13T09:51:00
2021-10-13T09:12:15
null
UTF-8
C++
false
false
3,905
cpp
/* tests/test_constants_and_functions.cpp -- global constants and functions, enumerations, raw byte strings Copyright (c) 2016 Wenzel Jakob <[email protected]> All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. */ #include "pybind11_tests.h" enum MyEnum { EFirstEntry = 1, ESecondEntry }; std::string test_function1() { return "test_function()"; } std::string test_function2(MyEnum k) { return "test_function(enum=" + std::to_string(k) + ")"; } std::string test_function3(int i) { return "test_function(" + std::to_string(i) + ")"; } py::str test_function4() { return "test_function()"; } py::str test_function4(char *) { return "test_function(char *)"; } py::str test_function4(int, float) { return "test_function(int, float)"; } py::str test_function4(float, int) { return "test_function(float, int)"; } py::bytes return_bytes() { const char *data = "\x01\x00\x02\x00"; return std::string(data, 4); } std::string print_bytes(py::bytes bytes) { std::string ret = "bytes["; const auto value = static_cast<std::string>(bytes); for (size_t i = 0; i < value.length(); ++i) { ret += std::to_string(static_cast<int>(value[i])) + " "; } ret.back() = ']'; return ret; } // Test that we properly handle C++17 exception specifiers (which are part of the function signature // in C++17). These should all still work before C++17, but don't affect the function signature. namespace test_exc_sp { int f1(int x) noexcept { return x+1; } int f2(int x) noexcept(true) { return x+2; } int f3(int x) noexcept(false) { return x+3; } int f4(int x) throw() { return x+4; } // Deprecated equivalent to noexcept(true) struct C { int m1(int x) noexcept { return x-1; } int m2(int x) const noexcept { return x-2; } int m3(int x) noexcept(true) { return x-3; } int m4(int x) const noexcept(true) { return x-4; } int m5(int x) noexcept(false) { return x-5; } int m6(int x) const noexcept(false) { return x-6; } int m7(int x) throw() { return x-7; } int m8(int x) const throw() { return x-8; } }; } TEST_SUBMODULE(constants_and_functions, m) { // test_constants m.attr("some_constant") = py::int_(14); // test_function_overloading m.def("test_function", &test_function1); m.def("test_function", &test_function2); m.def("test_function", &test_function3); #if defined(PYBIND11_OVERLOAD_CAST) m.def("test_function", py::overload_cast<>(&test_function4)); m.def("test_function", py::overload_cast<char *>(&test_function4)); m.def("test_function", py::overload_cast<int, float>(&test_function4)); m.def("test_function", py::overload_cast<float, int>(&test_function4)); #else m.def("test_function", static_cast<py::str (*)()>(&test_function4)); m.def("test_function", static_cast<py::str (*)(char *)>(&test_function4)); m.def("test_function", static_cast<py::str (*)(int, float)>(&test_function4)); m.def("test_function", static_cast<py::str (*)(float, int)>(&test_function4)); #endif py::enum_<MyEnum>(m, "MyEnum") .value("EFirstEntry", EFirstEntry) .value("ESecondEntry", ESecondEntry) .export_values(); // test_bytes m.def("return_bytes", &return_bytes); m.def("print_bytes", &print_bytes); // test_exception_specifiers using namespace test_exc_sp; py::class_<C>(m, "C") .def(py::init<>()) .def("m1", &C::m1) .def("m2", &C::m2) .def("m3", &C::m3) .def("m4", &C::m4) .def("m5", &C::m5) .def("m6", &C::m6) .def("m7", &C::m7) .def("m8", &C::m8) ; m.def("f1", f1); m.def("f2", f2); m.def("f3", f3); m.def("f4", f4); }
e3a3dc2a7e4e45b67c3de0e0411b68caea317f92
d6f182688087f16a6c174e01638de38266fe5459
/工作目录/称重项目/20170723/WeighSensor/shuruxishu.cpp
b13ef2876704aae58a5c70f600791acf1cd7a903
[]
no_license
xsw258x2s5w8/WorkDir1
ad1c9f1c30233ab74094a0b89e5db831b0e6cf8f
83fd028bea424c11e9068cf6d1cebc0091584d3d
refs/heads/master
2021-01-01T18:20:41.799845
2017-07-27T11:38:00
2017-07-27T11:38:00
98,314,467
0
0
null
null
null
null
UTF-8
C++
false
false
655
cpp
#include "shuruxishu.h" #include "ui_shuruxishu.h" #include "index.h" #include "shuruxishutioajiao.h" Shuruxishu::Shuruxishu(QWidget *parent) : QWidget(parent), ui(new Ui::Shuruxishu) { ui->setupUi(this); connect(ui->returnIndex,SIGNAL(clicked()),this,SLOT(returnIndex())); connect(ui->returnPage,SIGNAL(clicked()),this,SLOT(returnPage())); } Shuruxishu::~Shuruxishu() { delete ui; } void Shuruxishu::returnIndex() { // Index *menu=new Index(); // menu->show(); this->close(); } void Shuruxishu::returnPage() { Shuruxishutioajiao *returnPage=new Shuruxishutioajiao(); returnPage->show(); this->close(); }
8cbeac265cd09daf007ad3a5fb239bc5782e24f8
96d9346a16fdbeff7d81cd5344b52d0cc3069c37
/libs/strong_typedef/tagged_float_example.cpp
6e0ebfa19e2461f2560758fccdbe0b2b1dd217ef
[]
no_license
schardong/Shand
fbee3d305adeea40bcdb85acad989486a60d5b4c
8603dbef52f4324cfd16a181a0f58f2642489e61
refs/heads/master
2020-12-02T20:58:32.950971
2017-03-31T06:07:49
2017-03-31T06:07:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,491
cpp
// Copyright Akira Takahashi 2012 // Use, modification and distribution is subject to 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) #include <boost/math/constants/constants.hpp> #include <shand/strong_typedef/tagged_float.hpp> #include <shand/strong_typedef/tagged_float_io.hpp> struct degree_tag {}; struct radian_tag {}; template <class T> using degree = shand::tagged_float<T, degree_tag>; template <class T> using radian = shand::tagged_float<T, radian_tag>; template <class T> radian<T> degree_to_radian(const degree<T>& x) { return radian<T>(x.get() * boost::math::constants::pi<T>() / static_cast<T>(180.0)); } template <class T> degree<T> radian_to_degree(const radian<T>& x) { return degree<T>(x.get() * static_cast<T>(180.0) / boost::math::constants::pi<T>()); } int main () { // 異なる型(タグ)間での暗黙変換はできない { degree<float> deg(90.0f); // radian<float> rad = deg; // コンパイルエラー!型が違う } // degreeからradianへの変換 { degree<float> deg(90.0f); radian<float> rad = degree_to_radian(deg); std::cout << rad << std::endl; } // radianからdegreeへの変換 { radian<float> rad(0.5 * boost::math::constants::pi<float>()); degree<float> deg = radian_to_degree(rad); std::cout << deg << std::endl; } } /* output: 1.5708 90 */
ea8aced1719207ae48408b8c869b1b39321b001f
2cf838b54b556987cfc49f42935f8aa7563ea1f4
/aws-cpp-sdk-awstransfer/include/aws/awstransfer/model/Protocol.h
b916cbb80e3b96b2cd32a08683e2afe256637a6f
[ "MIT", "Apache-2.0", "JSON" ]
permissive
QPC-database/aws-sdk-cpp
d11e9f0ff6958c64e793c87a49f1e034813dac32
9f83105f7e07fe04380232981ab073c247d6fc85
refs/heads/main
2023-06-14T17:41:04.817304
2021-07-09T20:28:20
2021-07-09T20:28:20
384,714,703
1
0
Apache-2.0
2021-07-10T14:16:41
2021-07-10T14:16:41
null
UTF-8
C++
false
false
617
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/awstransfer/Transfer_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace Transfer { namespace Model { enum class Protocol { NOT_SET, SFTP, FTP, FTPS }; namespace ProtocolMapper { AWS_TRANSFER_API Protocol GetProtocolForName(const Aws::String& name); AWS_TRANSFER_API Aws::String GetNameForProtocol(Protocol value); } // namespace ProtocolMapper } // namespace Model } // namespace Transfer } // namespace Aws
9c32880c4500482ea735947486eaac06db6f2553
abc04815d208c517907228cae60161d6e1d769ef
/inc/IThread.hpp
60c2720429c78062cf865624ae7cc585bd6d9b04
[]
no_license
zirkome/plazza
2f85c474cfa6664f7e496a630f509d805b06facd
63e8f497fcfa430d107ef181916e0d182afd8316
refs/heads/master
2021-05-26T13:52:45.492697
2014-04-27T15:46:24
2014-04-27T15:46:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
469
hpp
#ifndef _ITHREAD_H_ # define _ITHREAD_H_ # include "ITask.hpp" class IThread { public: enum State { THR_WAITING, THR_ALIVE, THR_DEAD }; public: virtual ~IThread() {}; public: virtual void join(void** retval) = 0; virtual int cancel() const = 0; virtual ITask *getTask() const = 0; virtual void setTask(ITask *) = 0; virtual State getState() const = 0; virtual void setState(State state) = 0; }; #endif /* _ITHREAD_H_ */
90a04ac4cf8490b973d3f872556115bfce48e3fb
c2bbe165858014ea7fd226710fa3dc1f4af36fe8
/src/utilities.hpp
6d2a191684e3a236196738757b0907d78bf3e144
[]
no_license
tonymugen/GWAlikeMeth
5781bb71e0ac79d6772d405a025f4379a52453cc
8245a7224ba4253681f54aaedd17a60b4520bedf
refs/heads/master
2020-04-16T00:34:56.464885
2020-01-31T22:28:18
2020-01-31T22:28:18
165,144,017
0
0
null
null
null
null
UTF-8
C++
false
false
24,541
hpp
// // utilities.hpp // // // Created by Tony Greenberg on 12/21/16. // Copyright © 2016 Tony Greenberg. All rights reserved. // /// Miscellaneous functions and algorithms /** \file * \author Anthony J. Greenberg * \copyright Copyright (c) 2016 Anthony J. Greenberg * \version 0.1 * * This is the project header file containing function definitions and constants. * */ #ifndef utilities_hpp #define utilities_hpp #include <vector> #include <string> #include <utility> #include <limits> #include <cmath> #include <cstdint> // for uint64_t #include <stack> using std::vector; using std::string; using std::swap; using std::numeric_limits; using std::signbit; using std::stack; namespace BayesicSpace { /// The definition of \f$\pi\f$ const double BS_PI = 3.14159265358979323846264338328; /// Machine \f$\epsilon\f$ const double BS_EPS = numeric_limits<double>::epsilon(); /// Tiny value to guard agains underflow const double BS_FPMIN = numeric_limits<double>::min()/BS_EPS; /** \brief Swap two `uint64_t` values * * Uses the three XORs trick to swap two integers. Safe if the variables happen to refer to the same address. * * \param[in,out] i first integer * \param[in,out] j second integer */ void swapXOR(uint64_t &i, uint64_t &j){ if (&i != &j) { // no move needed if this is actually the same variable i ^= j; j ^= i; i ^= j; } } /** \brief Swap two `in64_t` values * * Uses the three XORs trick to swap two integers. Safe if the variables happen to refer to the same address. * * \param[in,out] i first integer * \param[in,out] j second integer */ void swapXOR(int64_t &i, int64_t &j){ if (&i != &j) { // no move needed if this is actually the same variable i ^= j; j ^= i; i ^= j; } } /** \brief Swap two `uint32_t` values * * Uses the three XORs trick to swap two integers. Safe if the variables happen to refer to the same address. * * \param[in,out] i first integer * \param[in,out] j second integer */ void swapXOR(uint32_t &i, uint32_t &j){ if (&i != &j) { // no move needed if this is actually the same variable i ^= j; j ^= i; i ^= j; } } /** \brief Swap two `int32_t` values * * Uses the three XORs trick to swap two integers. Safe if the variables happen to refer to the same address. * * \param[in,out] i first integer * \param[in,out] j second integer */ void swapXOR(int32_t &i, int32_t &j){ if (&i != &j) { // no move needed if this is actually the same variable i ^= j; j ^= i; i ^= j; } } /** \brief Mean of a C array * * Calculates a mean of an array. Uses the recursive algorithm for numerical stability. * * \param[in] arr array to average * \param[in] len array length * */ double mean(const double *arr, const size_t &len){ double mean = 0.0; for (size_t i = 0; i < len; i++) { mean += (arr[i] - mean)/static_cast<double>(i + 1); } return mean; } /** \brief Mean of a C array with stride * * Calculates a mean of an array with stride (i.e., using every _stride_ element). Uses the recursive algorithm for numerical stability. * * \param[in] arr array to average * \param[in] len array length * \param[in] stride stride * */ double mean(const double *arr, const size_t &len, const size_t &stride){ double mean = 0.0; size_t nSteps = len/stride; // floor is what I want for (size_t i = 0; i < nSteps; i++) { mean += (arr[i * stride] - mean)/static_cast<double>(i + 1); } return mean; } /** \brief Mean of a C++ vector * * Calculates a mean of a vector. Uses the recursive algorithm for numerical stability. * * \param[in] vec vector to average * */ double mean(const vector<double> &vec){ double mean = 0.0; for (size_t i = 0; i < vec.size(); i++) { mean += (vec[i] - mean)/static_cast<double>(i + 1); } return mean; } /** \brief Mean of a C++ vector with stride * * Calculates a mean of a vector with stride (i.e., using every _stride_ element). Uses the recursive algorithm for numerical stability. * * \param[in] vec vector to average * \param[in] stride stride * */ double mean(const vector<double> &vec, const size_t &stride){ double mean = 0.0; size_t nSteps = vec.size()/stride; // floor is what I want for (size_t i = 0; i < nSteps; i++) { mean += (vec[i * stride] - mean)/static_cast<double>(i + 1); } return mean; } /** \brief Square of a double * * \param[in] x value to square * \return double square of the input */ inline double pow2(const double &x) {return x*x; }; /** \brief Shift three values left * * Shifts a new value, moving the old to the left. The first value is discarded. * * \param[in,out] a first value (becomes _b_) * \param[in,out] b second value (becomes _c_) * \param[in,out] c third value (becomes _d_) * \param[in] d unchanged fourth value (shifted to _c_) * */ inline void shft3(double &a, double &b, double &c, const double &d){ a = b; b = c; c = d; } /** \brief Bracket a maximum * * Brackets a maximum of a function given two initial guesses. Based on the Numerical Recipes in C++ function. Using max rather than min because max is more important in statistical applications. * The resulting bracketing values are candA < candB < candC. * * \param[in] func function to maximize. Has to take a double and return a double * \param[in] startA starting value A * \param[in] startB starting value B * \param[out] candA first bracketing value * \param[out] candB second bracketing value * \param[out] candC third breacketing value * */ template<class T> void bracketMax(T &func, const double &startA, const double &startB, double &candA, double &candB, double &candC); // body of the function has to be in the header file because of template stuff template<class T> void bracketMax(T &func, const double &startA, const double &startB, double &candA, double &candB, double &candC){ // set up constants const double GOLD = 1.618034; // default successive magnification ratio const double GLIMIT = 100.0; // maximum magnification allowed for the parabolic fit const double TINY = 1.0e-20; // tiny value to assure no division by zero // set the initial values candA = startA; candB = startB; double fa = func(candA); double fb = func(candB); // test if the function changes value at all (or at least a little over epsilon) if (fabs(fa - fb) < 1.001*BS_EPS) { candB += 100.0; // maybe just unlucky; change candB fb = func(candB); if (fabs(fa - fb) < 1.001*BS_EPS) { // now for sure there is a problem throw string("ERROR: function does not change over the candidate interval"); } } // want to keep going uphill, so reverse order if b takes us down if (fb < fa) { swap(candA, candB); swap(fa, fb); } // first guess at candC candC = candB + GOLD*(candB - candA); double fc = func(candC); while (fb < fc) { // stop when we bracket (func(candC) drops below func(candB)); will not execute if our first guess at candC hit the jackpot // parabolic extrapolation from a,b,c to find a new candidate u // note that parabolic extrapolation works the same for min and max double r = (candB-candA)*(fb-fc); double q = (candB-candC)*(fb-fa); // NOTE: signbit() is C++11; true if negative double qrDiff = (signbit(q-r) ? -fmax(fabs(q-r), TINY) : fmax(fabs(q-r), TINY)); // using TINY to guard against division by zero double u = candB - ((candB-candC)*q-(candB-candA)*r)/(2.0*qrDiff); double ulim = candB + GLIMIT*(candC-candB); double fu; if (!signbit((candB - u)*(u - candC))) { // u is between b and c; try it fu = func(u); if (fu > fc) { // maximum between b and c candA = candB; candB = u; break; } else if (fu < fb){ // maximum between a and u candC = u; break; } // Nothing good found; revert to golden rule magnification u = candC + GOLD*(candC-candB); fu = func(u); } else if (!signbit((candC-u)*(u-ulim))){ // u is between c and limit fu = func(u); if (fu > fc) { shft3(candB, candC, u, u+GOLD*(u-candC)); shft3(fb, fc, fu, func(u)); // u has changed in the previous shift } } else if ((u-ulim)*(ulim-candC) >= 0.0) { // limit u to maximum allowed value if it is closer than c u = ulim; fu = func(u); } else { // reject the parabolic approach and use golden rule magnification u = candC + GOLD*(candC-candB); fu = func(u); } // did not bracket yet; eliminate the oldest point and continue shft3(candA, candB, candC, u); shft3(fa, fb, fc, fu); } } /** \brief Find the value that maximizes a function * * Uses the Brent method to find the value of \f$x\f$ that maximizes a function. Modification of the implementation found in Numerical Recipes in C++. Maximizing rather than minimizing because that is the most common application in statistics. * Tolerance is set at \f$1.001 \times \sqrt{\epsilon}\f$, where \f$\epsilon\f$ is machine floating-point precision for _double_. This is just above the theoretical limit of precision. * * \param[in] func functor that represents the function to be maximized * \param[in] startX starting value * \param[out] xMax value of \f$x\f$ at maximum * \param[out] fMax function value at maximum * */ template<class T> void maximizer(T &func, const double &startX, double &xMax, double &fMax); // Template function. Body has to be in the .hpp file. template<class T> void maximizer(T &func, const double &startX, double &xMax, double &fMax){ const double tol = 1.001 * sqrt(BS_EPS); // set the tolerance just above the theoretical limit const unsigned int ITMAX = 1000; // maximum number of iterations const double CGOLD = 0.3819660; // golden ratio for when we abandon parabolic interpolation const double ZEPS = 1e-3 * BS_EPS; // small number to protect against numerical problems when the maximum is zero and we are trying to achieve a certain fractional accuracy // misc. parameters; named the same as the ones in Numerical Recipes Chapter 10.3 double d = 0.0; double e = 0.0; // the distance moved in the step before last double etemp; double fu; double fv; double fw; double fx; double u; double v; double w; double x; double xm; double p; double q; double r; double tol1; double mtol1; double tol2; // start by bracketing const double startB = startX + 100.0; double ax; double bx; double cx; bracketMax(func, startX, startB, ax, bx, cx); double a = (ax < cx ? ax : cx); double b = (ax > cx ? ax : cx); // a and b (but not necessarily func(a) and func(b)) must be ascending order // initialize x = w = v = bx; fw = fv = fx = func(x); unsigned int iter; for (iter = 0; iter < ITMAX; iter++) { xm = 0.5 * (a + b); // xm is the midpoint between a and b tol1 = tol * fabs(x) + ZEPS; tol2 = 2.0 * tol1; mtol1 = -tol1; // test for doneness if (fabs(x - xm) <= (tol2 - 0.5*(b-a))) { fMax = fx; xMax = x; break; } if (fabs(e) > tol1) { // construct parabolic fit; not happening for the first round since e is set to 0.0 to begin with r = (x-w)*(fx-fv); q = (x-v)*(fx-fw); p = (x-v)*q-(x-w)*r; q = 2.0*(q-r); if (q > 0.0) { p = -p; } q = fabs(q); etemp = e; e = d; // Test the parabolic fit for acceptability. // The parabolic step has to be (1) in the (a,b) interval and (2) the movement has to be smaller than 0.5*(the one before last) if ((fabs(p) >= fabs(0.5*q*etemp)) || (p <= q*(a-x)) || (p >= q*(b-x))) { // parabolic step no good; take golden section into the larger segment e = (x >= xm ? a-x : b-x); d = CGOLD*e; } else { // take the parabolic step d = p/q; u = x+d; if ((u-a < tol2) || (b-u < tol2)) { d = (signbit(xm - x) ? mtol1 : tol1); } } } else { e = (x >= xm ? a-x : b-x); d = CGOLD * e; } u = (fabs(d) >= tol1 ? x+d : x+(signbit(d) ? mtol1 : tol1)); fu = func(u); // our one function evaluation // once we have our function evaluation, we decide what to do with it if (fu >= fx) { if (u >= x) { a = x; } else { b = x; } shft3(v,w,x,u); shft3(fv,fw,fx,fu); } else { if (u < x) { a = u; } else { b = u; } if ((fu >= fw) || (w == x)) { v = w; w = u; fv = fw; fw = fu; } else if ((fu >= fv) || (v == x) || (v == w)) { v = u; fv = fu; } } } // if we did not get there after max # of iterations if (iter + 1 >= ITMAX) { xMax = x; fMax = nan(""); } } /** \brief Logarithm of the Gamma function * * The log of the \f$ \Gamma(x) \f$ function. Implementing the Lanczos algorythm following Numerical Recipes in C++. * * \param[in] x value * \return \f$ \log \Gamma(x) \f$ * */ double lnGamma(const double &x){ if (x <= 0.0) return nan(""); // define the weird magical coefficients const double coeff[14] {57.1562356658629235,-59.5979603554754912,14.1360979747417471,-0.491913816097620199,0.339946499848118887e-4,0.465236289270485756e-4,-0.983744753048795646e-4,0.158088703224912494e-3,-0.210264441724104883e-3,0.217439618115212643e-3,-0.164318106536763890e-3,0.844182239838527433e-4,-0.261908384015814087e-4,0.368991826595316234e-5}; // save a copy of x for incrementing double y = x; double gamma = 5.24218750000000000; // 671/128 double tmp = x + gamma; tmp = (x + 0.5)*log(tmp) - tmp; double logPi = 0.91893853320467267; // 0.5*log(2.0*pi) tmp += logPi; double cZero = 0.999999999999997092; // c_0 for (size_t i = 0; i < 14; i++) { cZero += coeff[i]/(++y); } return tmp + log(cZero/x); } /** \brief Continued fraction of the Beta function * * Computes the continued fraction of the Beta function following the Lenz method (see Numerical Recipes in C++). To be used in the _betai_ function. * * \param[in] x value * \param[in] a shape parameter \f$a\f$ * \param[in] b shape parameter \f$b\f$ * * \return continued fraction value * */ double betacf(const double &x, const double &a, const double &b){ const unsigned int maxIter = 10000; const double aPb = a + b; const double aPo = a + 1.0; const double aMo = a - 1.0; double numer = 1.0; // first step of Lentz's method; define first continued fraction numerator double denom = 1.0 - aPb*x/aPo; // define the denominator to start if (fabs(denom) < BS_FPMIN) denom = BS_FPMIN; // set d to something resonalbly small if it is too close to 0 denom = 1.0/denom; double cFrac = denom; // will become the continued fraction for (unsigned int m = 1; m < maxIter; m++) { double dm = static_cast<double>(m); double m2 = 2.0*dm; double aa = dm*(b-dm)*x/( (aMo+m2)*(a+m2) ); // even step of the recurrence denom = 1.0 + aa*denom; numer = 1.0 + aa/numer; if (fabs(denom) < BS_FPMIN) denom = BS_FPMIN; if (fabs(numer) < BS_FPMIN) numer = BS_FPMIN; denom = 1.0/denom; cFrac *= denom*numer; aa = -(a+dm)*(aPb+dm)*x/( (a+m2)*(aPo+m2) ); // odd step of the recurrence denom = 1.0 + aa*denom; numer = 1.0 + aa/numer; if (fabs(denom) < BS_FPMIN) denom = BS_FPMIN; if (fabs(numer) < BS_FPMIN) numer = BS_FPMIN; denom = 1.0/denom; double del = denom*numer; cFrac *= del; if (fabs(del-1.0) <= BS_EPS) break; // done if within epsilon } return cFrac; } /** \brief Regularized incomplete Beta function * * Computes a quadrature approximatino of the regularized incomplete Beta function following the method in Numerical Recipes in C++. To be used in the _betai_ function. * * \param[in] x value * \param[in] a shape parameter \f$a\f$ * \param[in] b shape parameter \f$b\f$ * * \return approximate \f$ I_x(a, b) \f$ *s */ double betaiapprox(const double &x, const double &a, const double &b){ // Gauss-Legendre abscissas and weights. Magic numbers copied from Numerical Recipes in C++ const double y[18] {0.0021695375159141994,0.011413521097787704,0.027972308950302116,0.051727015600492421,0.082502225484340941, 0.12007019910960293, 0.16415283300752470,0.21442376986779355, 0.27051082840644336,0.33199876341447887,0.39843234186401943, 0.46931971407375483, 0.54413605556657973, 0.62232745288031077,0.70331500465597174, 0.78649910768313447,0.87126389619061517, 0.95698180152629142}; const double w[18] {0.0055657196642445571,0.012915947284065419,0.020181515297735382,0.027298621498568734,0.034213810770299537,0.040875750923643261, 0.047235083490265582,0.053244713977759692,0.058860144245324798,0.064039797355015485,0.068745323835736408,0.072941885005653087,0.076598410645870640, 0.079687828912071670,0.082187266704339706,0.084078218979661945,0.085346685739338721,0.085983275670394821}; double res; double xu; const double aMo = a - 1.0; const double bMo = b - 1.0; const double mu = a/(a+b); const double lnMu = log(mu); const double lnOMU = log(1.0 - mu); double t = sqrt(a*b/(pow2(a+b)*(a+b+1.0))); // set the extent of tail integration if (x > mu) { if (x > 1.0) return 1.0; xu = fmax(mu + 10.0*t, x + 5.0*t); xu = fmin(1.0, xu); } else { if (x < 0.0) return 0.0; xu = fmin(mu - 10.0*t, x - 5.0*t); xu = fmax(0.0, xu); } double sum = 0.0; // Gauss-Legendre accumulation for (size_t i = 0; i < 18; i++) { t = x + (xu-x)*y[i]; sum += w[i]*exp(aMo*(log(t)-lnMu)+bMo*(log(1-t)-lnOMU)); } res = sum*(xu-x)*exp(aMo*lnMu-lnGamma(a)+bMo*lnOMU-lnGamma(b)+lnGamma(a+b)); return res > 0.0 ? 1.0-res : -res; } /** \brief Regularized incomplete Beta function * * Computes the regularized incomplete Beta function following the method in Numerical Recipes in C++. * * \param[in] x value * \param[in] a shape parameter \f$a\f$ * \param[in] b shape parameter \f$b\f$ * * \return \f$ I_x(a, b) \f$ * */ double betai(const double &x, const double &a, const double &b){ if ( (a <= 0.0) || (b <= 0.0) ) return nan(""); if ( (x < 0.0) || (x > 1.0) ) return nan(""); if ( (x == 0.0) || (x == 1.0) ) return x; const double doApprox = 3000.0; // when to do the quadrature approximation if ( (a > doApprox) && (b > doApprox) ) return betaiapprox(x, a, b); double bt = exp(lnGamma(a+b) - lnGamma(a) - lnGamma(b) + a*log(x) + b*log(1.0 - x)); if (x < (a+1.0)/(a+b+2.0)) { return bt*betacf(x,a,b)/a; } else { return 1.0 - bt*betacf(1.0-x,b,a)/b; } } /** \brief Shell sort * * Sorts the provided vector in ascending order using Shell's method. Rather than move the elements themselves, save their indexes to the output vector. The first element of the index vector points to the smallest element of the input vector etc. The implementation is modified from code in Numerical Recipes in C++. * NOTE: This algorithm is too slow for vectors of \f$ > 50\f$ elements. I am using it to finish off the quickSort, this is why I am giving it a range within a larger vector. * * \param[in] target vector to be sorted * \param[in] beg index of the first element * \param[in] end index of one past the last element to be included * \param[out] outIdx vector of indexes */ void shellSort(const vector<double> &target, const size_t &beg, const size_t &end, vector<size_t> &outIdx){ if (target.size() < end) { throw string("Target vector size smaller than end index in shellSort()"); } else if (outIdx.size() < end) { throw string("Output vector size smaller than end index in shellSort()"); } else if (end < beg) { throw string("End index smaller than beginning index in shellSort()"); } else if (target.size() != outIdx.size()) { throw string("Target and output vectors must be of the same size in shellSort()"); } // set up the initial output index values //for (size_t i = beg; i < end; i++) { // outIdx[i] = i; //} // pick the initial increment size_t inc = 1; do { inc = inc*3 + 1; } while (inc <= end - beg); // start the sort do { // loop over partial sorts, decreasing the increment each time inc /= 3; const size_t bottom = beg + inc; for (size_t iOuter = bottom; iOuter < end; iOuter++) { // outer loop of the insertion sort, going over the indexes if (outIdx[iOuter] >= target.size()) { throw string("outIdx value out of bounds for target vector in shellSort()"); } const size_t curInd = outIdx[iOuter]; // save the current value of the index size_t jInner = iOuter; while (target[ outIdx[jInner - inc] ] > target[ curInd ]) { // Straight insertion inner loop; looking for a place to insert the current value if (outIdx[jInner-inc] >= target.size()) { throw string("outIdx value out of bounds for target vector in shellSort()"); } outIdx[jInner] = outIdx[jInner-inc]; jInner -= inc; if (jInner < bottom) { break; } } outIdx[jInner] = curInd; } } while (inc > 1); } /** Quicksort * * This function implements the Quicksort algorithm, taking the Numerical Recipes implementation as a base. It re-arranges the indexes in the output vector rather than move around the elements of the target vector. The output index must be the same size as the target (this is checked and exception thown if the condidition is not met). The output index is initialized with the correct index values. * * \param[in] target vector to be sorted * \param[in] beg index of the first element * \param[in] end index of one past the last element to be included * \param[out] outIdx vector of indexes * */ void quickSort(const vector<double> &target, const size_t &beg, const size_t &end, vector<size_t> &outIdx){ if (target.size() < end) { throw string("Target vector size smaller than end index in quickSort()"); } else if (outIdx.size() < end) { throw string("Output vector size smaller than end index in quickSort()"); } else if (end < beg) { throw string("End index smaller than beginning index in quickSort()"); } else if (target.size() != outIdx.size()) { throw string("Target and output vectors must be of the same size in quickSort()"); } for (size_t i = beg; i < end; i++) { outIdx[i] = i; } // stacks to keep the l and ir values of the sub-vectors that are not being worked on stack<size_t> lStack; stack<size_t> irStack; const size_t m = 15; // the size of the sub-vectors that will be sorted by shellSort size_t l = beg; // left side of the sub-vector to be bisected size_t ir = end - 1; // right side of the sub-vector to be bisected while(true){ if (ir-l < m) { // the current sub-vector is small enough for shellSort shellSort(target, l, ir+1, outIdx); if (lStack.empty()) { break; } l = lStack.top(); lStack.pop(); ir = irStack.top(); irStack.pop(); } else { const size_t k = (l+ir) >> 1; // median between l and ir swapXOR(outIdx[k], outIdx[l+1]); // rearrange the vector region so that target[outIdx[l]] <= target[outIdx[l+1]] <= target[outIdx[ir]] if (target[ outIdx[l] ] > target[ outIdx[ir] ]) { swapXOR(outIdx[l], outIdx[ir]); } if (target[ outIdx[l+1] ] > target[ outIdx[ir] ]) { swapXOR(outIdx[l+1], outIdx[ir]); } if (target[ outIdx[l] ] > target[ outIdx[l+1] ]) { swapXOR(outIdx[l], outIdx[l+1]); } // set the range for partitioning size_t i = l+1; size_t j = ir; size_t ip = outIdx[l+1]; // index of the pivot (partitioning element) while(true){ // inner loop do { i++; } while(target[ outIdx[i] ] < target[ ip ]); // scan forward to find element > pivot do { j--; } while(target[ outIdx[j] ] > target[ ip ]); // scan backwards to find element < pivot if (j < i) { // stop the scans if the indexes crossed break; } swapXOR(outIdx[i], outIdx[j]); // exchange elements unless the indexes have crossed } outIdx[l+1] = outIdx[j]; // insert the index of the pivot outIdx[j] = ip; // push the indexes of defining the larger sub-vector to the stacks; the smaller sub-vector will be processed in the next iteration of the loop if ( (ir-i+1) > (j-l) ) { lStack.push(i); irStack.push(ir); ir = j - 1; } else { lStack.push(l); irStack.push(j-1); l = i; } } } } } #endif /* utilities_hpp */
28d593a1c7ba0df620033e03fe7c673db2bff6d3
87d06658a55119d621cdf154215007ab3d35a2bc
/CORE/src/Scene/Scene.cpp
55c7645ad0fc975fe293ad9bcd72c7acc0cffeb6
[ "Apache-2.0" ]
permissive
varomix/orbit-dev
33ab945d28a82d975080b87df54614392714f06c
2c0d8586878a1bffc9e778783943dff233972581
refs/heads/master
2023-04-15T15:23:48.439292
2021-04-30T07:24:59
2021-04-30T07:24:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,498
cpp
#include "pch.h" #include "Scene.h" #include "Core/Application.h" // systems #include "ECS/Systems/SpotLightSystem.h" #include "ECS/Systems/PointLightSystem.h" #include "ECS/Systems/SceneCameraSystem.h" #include "ECS/Systems/GridRendererSystem.h" #include "ECS/Systems/MeshRendererSystem.h" #include "ECS/Systems/EditorCameraSystem.h" #include "ECS/Systems/DepthSamplingSystem.h" #include "ECS/Systems/SkyboxRendererSystem.h" #include "ECS/Systems/DirectionalLightSystem.h" namespace Orbit { // define all systems ! static ECS::SpotLightSystem s_SpotLightSystem; static ECS::PointLightSystem s_PointLightSystem; static ECS::SceneCameraSystem s_SceneCameraSystem; static ECS::EditorCameraSystem s_EditorCameraSystem; static ECS::MeshRendererSystem s_MeshRendererSystem; static ECS::GridRendererSystem s_GridRendererSystem; static ECS::DepthSamplingSystem s_DepthSamplingSystem; static ECS::SkyboxRendererSystem s_SkyboxRendererSystem; static ECS::DirectionalLightSystem s_DirectionalLightSystem; void Scene::Init() { _Registry = MakeUnique<ECS::Registry>(); _Renderer = MakeUnique<PlatformRenderer>(1280, 720); _Serializer = MakeUnique<SceneSerializer>(_Registry.get(), &_Loader); // Register all components _Registry->RegisterComponent<ECS::Common>("Common"); _Registry->RegisterComponent<ECS::Camera>("Camera"); _Registry->RegisterComponent<ECS::Transform>("Transform"); _Registry->RegisterComponent<ECS::SpotLight>("Spot Light"); _Registry->RegisterComponent<ECS::PointLight>("Point Light"); _Registry->RegisterComponent<ECS::MeshRenderer>("MeshRenderer"); _Registry->RegisterComponent<ECS::SkyboxRenderer>("SkyboxRenderer"); _Registry->RegisterComponent<ECS::DirectionalLight>("Directional Light"); // initialise callbacks auto disp = Application::Dispatcher(); disp->AddListener<OpenSceneEvent>(OB_BIND_FN(Scene::OnOpenScene)); disp->AddListener<AddEntityEvent>(OB_BIND_FN(Scene::OnAddEntity)); disp->AddListener<KeyPressedEvent>(OB_BIND_FN(Scene::OnKeyPressed)); disp->AddListener<AddComponentEvent>(OB_BIND_FN(Scene::OnAddComponent)); disp->AddListener<DestroyEntityEvent>(OB_BIND_FN(Scene::OnDestroyEntity)); disp->AddListener<RemoveComponentEvent>(OB_BIND_FN(Scene::OnRemoveComponent)); // load shaders _Loader.LoadShader("data/Shaders/PBR"); _Loader.LoadShader("data/Shaders/FLAT"); _Loader.LoadShader("data/Shaders/GRID"); _Loader.LoadShader("data/Shaders/DEPTH"); _Loader.LoadShader("data/Shaders/IRMAP"); _Loader.LoadShader("data/Shaders/SKYBOX"); _Loader.LoadShader("data/Shaders/HDR2MAP"); // meshes _Loader.LoadMesh("data/Models/Basics/cube.fbx"); _Loader.LoadMesh("data/Models/Basics/sphere.fbx"); // cubemap const char* faces[6]; faces[CUBEMAP_RIGHT] = "data/Skybox/right.png"; faces[CUBEMAP_LEFT] = "data/Skybox/left.png"; faces[CUBEMAP_TOP] = "data/Skybox/top.png"; faces[CUBEMAP_BOTTOM] = "data/Skybox/bottom.png"; faces[CUBEMAP_FRONT] = "data/Skybox/front.png"; faces[CUBEMAP_BACK] = "data/Skybox/back.png"; _Loader.LoadCubeMap(faces); // MATERIALS Material _default; _default.Name = "default"; _default.Data.Metallic = 0.05; _default.Data.Roughness = 0.02; _default.Data.Albedo = vec3f(0.8f, 0.2f, 4.0f); _Loader.AddMaterial(_default); // init systems s_SpotLightSystem.Init(); s_PointLightSystem.Init(); s_SceneCameraSystem.Init(); s_EditorCameraSystem.Init(); s_GridRendererSystem.Init(); s_MeshRendererSystem.Init(); s_SkyboxRendererSystem.Init(); s_DepthSamplingSystem.Init(); s_DirectionalLightSystem.Init(); } void Scene::Start() { // start all systems s_SpotLightSystem.Start(); s_PointLightSystem.Start(); s_SceneCameraSystem.Start(); s_EditorCameraSystem.Start(); s_MeshRendererSystem.Start(); s_SkyboxRendererSystem.Start(); s_DepthSamplingSystem.Start(); s_DirectionalLightSystem.Start(); } void Scene::Update() { // lights s_SpotLightSystem.Update(); s_PointLightSystem.Update(); s_DirectionalLightSystem.Update(); // depth sampling s_DepthSamplingSystem.Update(); // renderers _Renderer->GetFrameBuffer()->Clear(); s_MeshRendererSystem.Update(); s_GridRendererSystem.Update(); s_SkyboxRendererSystem.Update(); } void Scene::DestroyEntity(ECS::EntityID handle) { _Registry->Destroy(handle); } ECS::Entity Scene::AddEntity(std::string name, const vec3f& pos) { const ECS::EntityID handle = _Registry->AddEntity(); if (name.empty()) { name = "Entity" + std::to_string(handle);} _Registry->AddComponent<ECS::Transform>(handle, pos); _Registry->AddComponent<ECS::Common>(handle, name); return ToEntity(handle); } ECS::EntityList Scene::GetEntityList(const ECS::EntitySignature& filter) { ECS::EntityList list; for (auto handle : _Registry->GetEntityHandleList(filter)) { list.push_back(ToEntity(handle)); } return list; } // EVENTS CALLBACKS void Scene::OnOpenScene(const OpenSceneEvent& e) { OB_INFO("trying to parse: %s", e.GetFilename().c_str()); _Serializer->Load(e.GetFilename()); Application::Dispatcher()->Prioritize<SceneLoadedEvent>(); } void Scene::OnSceneResized(const SceneResizedEvent& e) { int32 w = e.Width(); int32 h = e.Height(); _Renderer->SetViewport(0, 0, w, h); _Renderer->GetFrameBuffer()->Validate(w, h); _Renderer->GetDepthBuffer()->Validate(w, h); } void Scene::OnAddEntity(const AddEntityEvent& e) { Application::Dispatcher()->Prioritize<EntityAddedEvent>(this->AddEntity(e.GetName())); } void Scene::OnKeyPressed(const KeyPressedEvent& e) { auto input = Application::Inputs(); if (input->IsKeypress(KEY_LEFT_CONTROL) && input->IsKeypress(KEY_S)) { _Serializer->Save("Assets/Scenes/project.obproj"); } } void Scene::OnAddComponent(const AddComponentEvent& e) { if (_Registry->IsEntityActive(e.GetEntity())) { std::string compTypeName = e.GetTypeName(); _Registry->AddComponent(e.GetEntity(), compTypeName); Application::Dispatcher()->Prioritize<ComponentAddedEvent>(ToEntity(e.GetEntity()), compTypeName); } } void Scene::OnDestroyEntity(const DestroyEntityEvent& e) { Application::Dispatcher()->Prioritize<EntityDestroyedEvent>(e.GetEntity()); _Registry->Destroy(e.GetEntity()); } void Scene::OnRemoveComponent(const RemoveComponentEvent& e) { e.GetEntity().RemoveComponent(e.GetTypeID()); Application::Dispatcher()->Prioritize<RefreshInspectorEvent>(e.GetEntity()); OB_INFO("Component %u removed", e.GetTypeID()); } }
498754cac19b2e0d4ec3906d3522676a14d85ee3
4c2062307f83cbd57e0cd83d57ed23272676ab88
/src/ast.cpp
7d028f2ecd37b5193c65269301015a5b03d7a0b4
[]
no_license
yunjuanhuakai/regex_syntax
14020700cf8dcc32bb0089b150fc61f66930d396
08a8ba7dda2158f8ac66f6c4c092d6008bc991c2
refs/heads/master
2021-01-20T21:06:38.170364
2017-03-10T13:59:51
2017-03-10T13:59:51
66,179,985
1
0
null
null
null
null
UTF-8
C++
false
false
4,100
cpp
// // Created by makai on 16-6-19. // #include <iostream> #include <algorithm> #include <iomanip> #include "ast.h" namespace regex { using std::cout; using std::copy; using std::make_move_iterator; using std::ostream_iterator; ast::ast() noexcept : is_null_(true), t_(mTAG::CONCAT) {} ast::ast(token const &t) noexcept : is_null_(false), t_(t) {} ast::ast(ast &&a) noexcept : is_null_(a.is_null_), t_(a.t_), children_(std::move(a.children_)) { a.clear(); } void ast::clear() noexcept { is_null_ = true; children_.clear(); } ast &ast::operator[](size_t i) noexcept { return children_[i]; } ast const &ast::operator[](size_t i) const noexcept { return children_[i]; } token const &ast::get_token() const noexcept { return t_; } token &ast::get_token() noexcept { return t_; } bool ast::null() const noexcept { return is_null_; } bool ast::empty() const noexcept { return children_.empty(); } size_t ast::size() const noexcept { return children_.size(); } void ast::emplace_child(token const &t) { this->is_null_ = false; children_.emplace_back(t); } void ast::push_child(ast &&a) { this->is_null_ = false; ast item; if (/*(*/a.t_.is(mTAG::CONCAT) /*|| a.t_.is(mTAG::Or))*/ && a.children_.size() == 1) { item.swap(a.children_[0]); a.clear(); } else { item.swap(a); } children_.push_back(std::move(item)); // children_.push_back(make_unique<ast>(std::move(a))); } ast &ast::last() noexcept { return children_.back(); } ast const &ast::last() const noexcept { return children_.back(); } void ast::swap(ast &a) { std::swap(a.t_, t_); std::swap(a.is_null_, is_null_); children_.swap(a.children_); } ast_iterator ast::begin() noexcept { return ast_iterator(children_.begin()); } ast_const_iterator ast::begin() const noexcept { return ast_const_iterator(children_.cbegin()); } ast_iterator ast::end() noexcept { return ast_iterator(children_.end()); } ast_const_iterator ast::end() const noexcept { return ast_const_iterator(children_.cend()); } string ast::to_string() const noexcept { return is_null_ ? "null" : token_to_string(t_); } string ast::to_string_tree() const { return _to_string_tree(0); } struct Set_E { int N_; }; Set_E set_e(int i) { return {i}; } ostream &operator<<(ostream &os, Set_E const &e) { std::fill_n(ostream_iterator<char>(os), e.N_, ' '); return os; } string ast::_to_string_tree(int i) const { ostringstream buf; if (children_.empty()) { buf << set_e(i) << to_string(); return buf.str(); } if (!null()) { buf << set_e(i) << '(' << t_ << '\n'; } auto beg = children_.begin(); while (beg != children_.end() - 1) { buf << (beg++)->_to_string_tree(i + 1) << '\n'; } buf << beg->_to_string_tree(i + 1); if (!null()) buf << ')'; return buf.str(); } } /* namespace regex { ast_iterator::ast_iterator(AstPtrs::iterator iter) : iter_(iter) {} ast &ast_iterator::operator*() const noexcept { return *(*iter_); } ast *ast_iterator::operator->() const noexcept { return iter_->get(); } ast_iterator& ast_iterator::operator++() noexcept { ++iter_; return *this; } ast_iterator ast_iterator::operator++(int) noexcept { return _Self(iter_++); } bool ast_iterator::operator==(_Self const &rhs) const noexcept { return rhs.iter_ == iter_; } bool ast_iterator::operator!=(_Self const &rhs) const noexcept { return !(this->operator==(rhs)); } ast_const_iterator::ast_const_iterator(AstPtrs::const_iterator iter) : iter_(iter) {} ast const& ast_const_iterator::operator*() const noexcept { return *(*iter_); } ast const *ast_const_iterator::operator->() const noexcept { return iter_->get(); } ast_const_iterator &ast_const_iterator::operator++() noexcept { ++iter_; return *this; } ast_const_iterator ast_const_iterator::operator++(int) noexcept { return _Self(iter_++); } bool ast_const_iterator::operator==(_Self const &rhs) const noexcept { return rhs.iter_ == iter_; } bool ast_const_iterator::operator!=(_Self const &rhs) const noexcept { return !(this->operator==(rhs)); } } */
41228d315e2b89d6ab69aebf71e914b5b58c34a8
e796b62a902f609a6f52223bc336a8b81155872a
/semaine 2/Challenges Boucle/challenge5.cpp
102787249c49754ec4125e1ccdbc6c120f97d75b
[]
no_license
souayrioss/Periode-SAS
551f28c6cbb672e498e3a14202225e6f301ae163
195596fc83083dde248828b7bfb9745bdf70e6cd
refs/heads/main
2023-09-02T16:53:49.638756
2021-11-19T07:49:22
2021-11-19T07:49:22
426,167,652
0
0
null
null
null
null
ISO-8859-1
C++
false
false
288
cpp
#include<stdio.h> #include<stdlib.h> int main() { int r,a,b; printf("Donner un entier positif:\n"); scanf("%d",&a); while(a!=0) { r=a%10; b=10*b+r; a=a/10; } printf("l'inverse de l'entier donne en entrée est %d\n",b); return 0; }
46a00a240b0509bc0d7427eef72dc2cb0f02d6d6
47a485fe6b512aee8ba7ccd03a97f744936801a9
/HR/maximal_square.cpp
1703b6bb8048ba80c44453cd67a7bd827f0e0425
[]
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,873
cpp
class Solution { public: // DP[x] = min(DP[x], DP[x-1], prev) + 1 // Time O(nm) Space O(m) int maximalSquare(vector<vector<char>>& matrix) { int n = matrix.size(); if (!n) return 0; int m = matrix[0].size(), prev = 0, tmp; vector<int> dp(m, 0); // bottom right down corner of rectangle, the length of the side of rectangle int ans = 0; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { if ('0' == matrix[y][x]) { prev = dp[x]; dp[x] = 0; } else { if (x == 0) { prev = dp[x]; dp[x] = 1; } else { tmp = min(min(dp[x], dp[x - 1]), prev) + 1; prev = dp[x]; dp[x] = tmp; } ans = max(ans, dp[x]); } } } return ans*ans; } // Brute Force // Time O(nm^2) Space O(m) int maximalSquare(vector<vector<char>>& matrix) { int n = matrix.size(); if (!n) return 0; int m = matrix[0].size(); vector<int> height(m, 0); int ans = 0; for (int y = 0; y < n; y++) { for (int x = 0; x < m; x++) { if ('0' == matrix[y][x]) height[x] = 0; else { height[x]++; int min_height = height[x]; for (int p = x; p >= 0; p--) { min_height = min(min_height, height[p]); int hor = x - p + 1; if (min_height >= hor) ans = max(ans, hor*hor); else break; } } } } return ans; } };
ae654a7c9b7902b516c3caae1e1dd4d9f5c95dd6
aefc133fdb19e4c7f20048fe9babf68cada7a109
/MD5/MD5.hpp
a5bd09889b23ab0121b584cf0d141219c98a569b
[]
no_license
abodelot/cpp-utils
d3998add2efe6fbfa5c77388dff65d4e8be690a8
480e172349c84725ae978e495a875d50770282af
refs/heads/master
2020-05-27T03:16:42.077984
2019-10-23T22:39:49
2019-10-23T22:56:33
20,619,186
5
0
null
null
null
null
UTF-8
C++
false
false
464
hpp
#ifndef MD5_HPP #define MD5_HPP #include <string> #include <cstdint> class MD5 { public: MD5(); MD5(const char* data, size_t len); void update(const char* data, size_t len); /** * Get digest as a 32 hexadecimal characters string */ std::string hexdigest() const; private: void transform(); void finalize(); uint32_t buffer_[4]; uint32_t bits_[2]; unsigned char in_[64]; unsigned char digest_[16]; }; #endif
6f744e38d05ecd3fe612b9cbe97777cc9ab7995a
3b9b4049a8e7d38b49e07bb752780b2f1d792851
/src/components/audio_modem/modem_impl.cc
447250cad9322254ae692e1137e71662c2210dc7
[ "BSD-3-Clause", "Apache-2.0" ]
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
11,449
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/audio_modem/modem_impl.h" #include <stdint.h> #include <algorithm> #include <limits> #include <memory> #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/command_line.h" #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/run_loop.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "base/strings/sys_string_conversions.h" #include "base/time/time.h" #include "build/build_config.h" #include "components/audio_modem/audio_modem_switches.h" #include "components/audio_modem/audio_player_impl.h" #include "components/audio_modem/audio_recorder_impl.h" #include "components/audio_modem/public/whispernet_client.h" #include "content/public/browser/browser_thread.h" #include "media/audio/audio_manager.h" #include "media/audio/audio_manager_base.h" #include "media/base/audio_bus.h" #include "third_party/webrtc/common_audio/wav_file.h" namespace audio_modem { namespace { const int kMaxSamples = 10000; const int kTokenTimeoutMs = 2000; const int kMonoChannelCount = 1; // UrlSafe is defined as: // '/' represented by a '_' and '+' represented by a '-' // TODO(ckehoe): Move this to a central place. std::string FromUrlSafe(std::string token) { base::ReplaceChars(token, "-", "+", &token); base::ReplaceChars(token, "_", "/", &token); return token; } std::string ToUrlSafe(std::string token) { base::ReplaceChars(token, "+", "-", &token); base::ReplaceChars(token, "/", "_", &token); return token; } // TODO(ckehoe): Move this to a central place. std::string AudioTypeToString(AudioType audio_type) { if (audio_type == AUDIBLE) return "audible"; if (audio_type == INAUDIBLE) return "inaudible"; NOTREACHED() << "Got unexpected token type " << audio_type; return std::string(); } bool ReadBooleanFlag(const std::string& flag, bool default_value) { const std::string flag_value = base::ToLowerASCII( base::CommandLine::ForCurrentProcess()->GetSwitchValueASCII(flag)); if (flag_value == "true" || flag_value == "1") return true; if (flag_value == "false" || flag_value == "0") return false; LOG_IF(ERROR, !flag_value.empty()) << "Unrecognized value \"" << flag_value << " for flag " << flag << ". Defaulting to " << default_value; return default_value; } } // namespace // Public functions. ModemImpl::ModemImpl() : client_(nullptr), recorder_(nullptr) { // TODO(rkc): Move all of these into initializer lists once it is allowed. should_be_playing_[AUDIBLE] = false; should_be_playing_[INAUDIBLE] = false; should_be_recording_[AUDIBLE] = false; should_be_recording_[INAUDIBLE] = false; player_enabled_[AUDIBLE] = ReadBooleanFlag( switches::kAudioModemEnableAudibleBroadcast, true); player_enabled_[INAUDIBLE] = ReadBooleanFlag( switches::kAudioModemEnableInaudibleBroadcast, true); player_[AUDIBLE] = nullptr; player_[INAUDIBLE] = nullptr; samples_caches_.resize(2); samples_caches_[AUDIBLE] = new SamplesMap(kMaxSamples); samples_caches_[INAUDIBLE] = new SamplesMap(kMaxSamples); } void ModemImpl::Initialize(WhispernetClient* client, const TokensCallback& tokens_cb) { DCHECK(client); client_ = client; tokens_cb_ = tokens_cb; // These will be unregistered on destruction, so unretained is safe to use. client_->RegisterTokensCallback( base::Bind(&ModemImpl::OnTokensFound, base::Unretained(this))); client_->RegisterSamplesCallback( base::Bind(&ModemImpl::OnTokenEncoded, base::Unretained(this))); if (!player_[AUDIBLE]) player_[AUDIBLE] = new AudioPlayerImpl(); player_[AUDIBLE]->Initialize(); if (!player_[INAUDIBLE]) player_[INAUDIBLE] = new AudioPlayerImpl(); player_[INAUDIBLE]->Initialize(); decode_cancelable_cb_.Reset(base::Bind( &ModemImpl::DecodeSamplesConnector, base::Unretained(this))); if (!recorder_) recorder_ = new AudioRecorderImpl(); recorder_->Initialize(decode_cancelable_cb_.callback()); dump_tokens_dir_ = base::FilePath(base::CommandLine::ForCurrentProcess() ->GetSwitchValueNative(switches::kAudioModemDumpTokensToDir)); } ModemImpl::~ModemImpl() { if (player_[AUDIBLE]) player_[AUDIBLE]->Finalize(); if (player_[INAUDIBLE]) player_[INAUDIBLE]->Finalize(); if (recorder_) recorder_->Finalize(); // Whispernet initialization may never have completed. if (client_) { client_->RegisterTokensCallback(TokensCallback()); client_->RegisterSamplesCallback(SamplesCallback()); } } void ModemImpl::StartPlaying(AudioType type) { DCHECK(type == AUDIBLE || type == INAUDIBLE); should_be_playing_[type] = true; // If we don't have our token encoded yet, this check will be false, for now. // Once our token is encoded, OnTokenEncoded will call UpdateToken, which // will call this code again (if we're still supposed to be playing). SamplesMap::iterator samples = samples_caches_[type]->Get(playing_token_[type]); if (samples != samples_caches_[type]->end()) { DCHECK(!playing_token_[type].empty()); if (player_enabled_[type]) { started_playing_[type] = base::Time::Now(); player_[type]->Play(samples->second); // If we're playing, we always record to hear what we are playing. recorder_->Record(); } else { DVLOG(3) << "Skipping playback for disabled " << AudioTypeToString(type) << " player."; } } } void ModemImpl::StopPlaying(AudioType type) { DCHECK(type == AUDIBLE || type == INAUDIBLE); should_be_playing_[type] = false; player_[type]->Stop(); // If we were only recording to hear our own played tokens, stop. if (!should_be_recording_[AUDIBLE] && !should_be_recording_[INAUDIBLE]) recorder_->Stop(); playing_token_[type] = std::string(); } void ModemImpl::StartRecording(AudioType type) { DCHECK(type == AUDIBLE || type == INAUDIBLE); should_be_recording_[type] = true; recorder_->Record(); } void ModemImpl::StopRecording(AudioType type) { DCHECK(type == AUDIBLE || type == INAUDIBLE); should_be_recording_[type] = false; recorder_->Stop(); } void ModemImpl::SetToken(AudioType type, const std::string& url_safe_token) { DCHECK(type == AUDIBLE || type == INAUDIBLE); std::string token = FromUrlSafe(url_safe_token); if (samples_caches_[type]->Get(token) == samples_caches_[type]->end()) { client_->EncodeToken(token, type, token_params_); } else { UpdateToken(type, token); } } const std::string ModemImpl::GetToken(AudioType type) const { return playing_token_[type]; } bool ModemImpl::IsPlayingTokenHeard(AudioType type) const { base::TimeDelta tokenTimeout = base::TimeDelta::FromMilliseconds(kTokenTimeoutMs); // This is a bit of a hack. If we haven't been playing long enough, // return true to avoid tripping an audio fail alarm. if (base::Time::Now() - started_playing_[type] < tokenTimeout) return true; return base::Time::Now() - heard_own_token_[type] < tokenTimeout; } void ModemImpl::SetTokenParams(AudioType type, const TokenParameters& params) { DCHECK_GT(params.length, 0u); token_params_[type] = params; // TODO(ckehoe): Make whispernet handle different token lengths // simultaneously without reinitializing the decoder over and over. } // static std::unique_ptr<Modem> Modem::Create() { return base::WrapUnique<Modem>(new ModemImpl); } // Private functions. void ModemImpl::OnTokenEncoded( AudioType type, const std::string& token, const scoped_refptr<media::AudioBusRefCounted>& samples) { samples_caches_[type]->Put(token, samples); DumpToken(type, token, samples.get()); UpdateToken(type, token); } void ModemImpl::OnTokensFound(const std::vector<AudioToken>& tokens) { std::vector<AudioToken> tokens_to_report; for (const auto& token : tokens) { AudioType type = token.audible ? AUDIBLE : INAUDIBLE; if (playing_token_[type] == token.token) heard_own_token_[type] = base::Time::Now(); if (should_be_recording_[AUDIBLE] && token.audible) { tokens_to_report.push_back(token); } else if (should_be_recording_[INAUDIBLE] && !token.audible) { tokens_to_report.push_back(token); } } if (!tokens_to_report.empty()) tokens_cb_.Run(tokens_to_report); } void ModemImpl::UpdateToken(AudioType type, const std::string& token) { DCHECK(type == AUDIBLE || type == INAUDIBLE); if (playing_token_[type] == token) return; // Update token. playing_token_[type] = token; // If we are supposed to be playing this token type at this moment, switch // out playback with the new samples. if (should_be_playing_[type]) RestartPlaying(type); } void ModemImpl::RestartPlaying(AudioType type) { DCHECK(type == AUDIBLE || type == INAUDIBLE); // We should already have this token in the cache. This function is not // called from anywhere except update token and only once we have our samples // in the cache. DCHECK(samples_caches_[type]->Get(playing_token_[type]) != samples_caches_[type]->end()); player_[type]->Stop(); StartPlaying(type); } void ModemImpl::DecodeSamplesConnector(const std::string& samples) { // If we are either supposed to be recording *or* playing, audible or // inaudible, we should be decoding that type. This is so that if we are // just playing, we will still decode our recorded token so we can check // if we heard our own token. Whether or not we report the token to the // server is checked for and handled in OnTokensFound. bool decode_audible = should_be_recording_[AUDIBLE] || should_be_playing_[AUDIBLE]; bool decode_inaudible = should_be_recording_[INAUDIBLE] || should_be_playing_[INAUDIBLE]; if (decode_audible && decode_inaudible) { client_->DecodeSamples(BOTH, samples, token_params_); } else if (decode_audible) { client_->DecodeSamples(AUDIBLE, samples, token_params_); } else if (decode_inaudible) { client_->DecodeSamples(INAUDIBLE, samples, token_params_); } } void ModemImpl::DumpToken(AudioType audio_type, const std::string& token, const media::AudioBus* samples) { if (dump_tokens_dir_.empty()) return; // Convert the samples to 16-bit integers. std::vector<int16_t> int_samples; int_samples.reserve(samples->frames()); for (int i = 0; i < samples->frames(); i++) { int_samples.push_back(round( samples->channel(0)[i] * std::numeric_limits<int16_t>::max())); } DCHECK_EQ(static_cast<int>(int_samples.size()), samples->frames()); DCHECK_EQ(kMonoChannelCount, samples->channels()); const std::string filename = base::StringPrintf("%s %s.wav", AudioTypeToString(audio_type).c_str(), ToUrlSafe(token).c_str()); DVLOG(3) << "Dumping token " << filename; std::string file_str; #if defined(OS_WIN) base::FilePath file_path = dump_tokens_dir_.Append( base::SysNativeMBToWide(filename)); file_str = base::SysWideToNativeMB(file_path.value()); #else file_str = dump_tokens_dir_.Append(filename).value(); #endif webrtc::WavWriter writer(file_str, kDefaultSampleRate, kMonoChannelCount); writer.WriteSamples(int_samples.data(), int_samples.size()); } } // namespace audio_modem
c45b8dbc95c4e28bbdf63bb529c3db62bc253028
8ad39dce5b7a4d9b0fa6bfc3d1745ae02064f506
/Book & Movie rental shop management/SpellChecker.cpp
510555a127341559f3b22496b5369196e3742e56
[]
no_license
aywhr75/Object-oriented-programming
73cf6c7d87fd834390b7c1d60281a63b1e067689
c9506420f9f36e931e13f091525e54fd91ca51d2
refs/heads/master
2021-03-11T22:45:23.157920
2020-03-11T12:46:39
2020-03-11T12:46:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,561
cpp
// Name: YoungA Lee // Seneca Student ID: 048417083 // Seneca email: [email protected] // Date of completion: Fab 17 2020 // // I confirm that the content of this file is created by me, // with the exception of the parts provided to me by my professor. #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<algorithm> #include<string> #include<fstream> #include "SpellChecker.h" using namespace std; namespace sdds { SpellChecker::SpellChecker(const char* filename) { auto pos = 0u; // unsigned int string len; ifstream textfile(filename); // ready to read a file if (!textfile.good()) throw "Bad file name!"; // exceptional check else { for (size_t i = 0; i < WORD_SIZE; i++) { getline(textfile, len); pos = len.find(' '); // find location number of white space m_badWords[i] = len.substr(0, pos); m_badWords[i].erase(remove(m_badWords[i].begin(), m_badWords[i].end(), ' '), m_badWords[i].end());// removed white space m_goodWords[i] = len.substr(pos, len.length() - 1); m_goodWords[i].erase(remove(m_goodWords[i].begin(), m_goodWords[i].end(), ' '), m_goodWords[i].end()); // remove white space } } } void SpellChecker::operator()(std::string& text) const { auto pos = 0u; for (size_t i = 0; i < WORD_SIZE; i++) { while (text.find(m_badWords[i]) != string::npos){ // if text.find is same with m_badWords return npos otherwise keep checking pos = text.find(m_badWords[i]); text.replace(pos, m_badWords[i].length(), m_goodWords[i]); // replace badwords to goodwords } } } }
d88a5766093c8014745f471541a3491d9f9bb1ef
80ee2a0df0ee1c927c2c828dd651793054f68905
/code/src/caros/components/caros_teleoperation/src/pose_teleoperate.cpp
26e93981152fd54299c27283dc8fa2e9becb2354
[]
no_license
ROVI2-SDU-GROUP1/ROVI2
d92904aff31a28b12c63f42a1a6b51db411f7602
93dd07b5815c6da9da3a790d58bd7e16ce55c2db
refs/heads/master
2021-06-21T15:03:17.935201
2017-05-22T10:02:10
2017-05-22T10:02:10
84,427,466
2
0
null
null
null
null
UTF-8
C++
false
false
10,347
cpp
#include <caros/pose_teleoperate.h> #include <rw/math/LinearAlgebra.hpp> #include <ros/ros.h> #include <std_srvs/Empty.h> #include <string> using rw::math::Deg2Rad; using rw::math::RPY; using rw::math::Rotation3D; using rw::math::Transform3D; using rw::math::Vector3D; using rw::math::Q; using rw::math::Quaternion; namespace caros { PoseTeleoperate::PoseTeleoperate(const ros::NodeHandle& nh, const std::string& name) : caros::CarosNodeServiceInterface(nh, 100), nh_(nh), do_teleoperate_(false) { pose_sensor_id1_ = -1; analog_button_pushed_ = false; analog_button_ = false; } bool PoseTeleoperate::activateHook() { std_srvs::Empty::Request request; std_srvs::Empty::Response response; if (!initNode()) { return false; } if (!startListening(request, response)) { return false; } return true; } bool PoseTeleoperate::recoverHook(const std::string& error_msg, const int64_t error_code) { std_srvs::Empty::Request request; std_srvs::Empty::Response response; bool resolved = false; switch (error_code) { case TELEOPERATE_MISSING_ROSPARAM_RUNTIME: if (startListening(request, response)) { ROS_DEBUG_STREAM("Subscribing to ButtonSensor topic"); button_sensor_state_ = nh_.subscribe(button_sensor_name_, 1, &PoseTeleoperate::handleButtonSensor, this); if (!button_sensor_state_) { CAROS_FATALERROR("Subscribing to ButtonSensor topic failed from recoverhook - FATALERROR", TELEOPERATE_SUBSCRIPTION_FAILED); } resolved = true; } if (!pose_array_state_) { CAROS_FATALERROR( "Not able to properly recover from the error condition 'missing rosparam at runtime' - going into " "FATALERROR", TELEOPERATE_MISSING_ROSPARAM_RUNTIME); resolved = false; ROS_DEBUG_STREAM("Subscribing to pose topic"); pose_array_state_ = nh_.subscribe(pose_array_name_, 1, &PoseTeleoperate::handlePoseArraySensor, this); if (!button_sensor_state_) { CAROS_FATALERROR("Subscribing to pose topic failed from recoverhook - FATALERROR", TELEOPERATE_SUBSCRIPTION_FAILED); } resolved = true; } else { CAROS_FATALERROR( "Not able to properly recover from the error condition 'failed subscription' - going into FATALERROR", TELEOPERATE_SUBSCRIPTION_FAILED); resolved = false; } break; default: CAROS_FATALERROR("The provided error code '" << error_code << "' has no recovery functionality! " << "- this should be considered a bug!", TELEOPERATE_INTERNAL_ERROR); resolved = false; break; } if (resolved) { do_teleoperate_ = true; } return resolved; } void PoseTeleoperate::errorLoopHook() { ROS_ERROR_STREAM("Something is wrong. Try calling recoverHook()"); do_teleoperate_ = false; } void PoseTeleoperate::fatalErrorLoopHook() { ROS_ERROR_STREAM("Fatal error. Shutting down node..."); std_srvs::Empty::Request request; std_srvs::Empty::Response response; stopListening(request, response); } void PoseTeleoperate::runLoopHook() { if (do_teleoperate_) { doTeleoperate(); } } bool PoseTeleoperate::initNode() { // the stuff we need to listen for std::string dev_name, button_name, pose_sensor_name; double rate, zoffset, zoffset_tcp; if (!nh_.getParam("device_name", dev_name)) { CAROS_FATALERROR("The parameter '" << nh_.getNamespace() << "/device_name' was not present on the parameter server! " << "This parameter has to be specified for this node to work properly.", TELEOPERATE_MISSING_ROSPARAM); return false; } nh_.param("rate", rate, 100.0); nh_.param("zoffset_tcp", zoffset_tcp, 0.0); nh_.param("zoffset", zoffset, 0.0); offset_Zpos_.P()[2] = zoffset_tcp; sensor_offset_.P()[2] = zoffset; setLoopRateFrequency(rate); // add some control interface srv_start_ = nh_.advertiseService("start", &PoseTeleoperate::startListening, this); srv_stop_ = nh_.advertiseService("stop", &PoseTeleoperate::stopListening, this); srv_pause_ = nh_.advertiseService("pause", &PoseTeleoperate::pauseListening, this); // get the workcell p_workcell_ = caros::getWorkCell(); if (p_workcell_ == NULL) { ROS_ERROR("No workcell added to the parameter server!"); CAROS_FATALERROR("No workcell added to the parameter server!", TELEOPERATE_MISSING_ROSPARAM); return false; } // device dev_ = p_workcell_->findDevice(dev_name); tmp_state_ = p_workcell_->getDefaultState(); if (dev_ == NULL) { ROS_ERROR_STREAM("No device by name " << dev_name << " Possible devices are:"); CAROS_FATALERROR("No device by name found in workcell.", TELEOPERATE_MISSING_DEVICE_IN_WORKCELL); for (rw::models::Device::Ptr dev : p_workcell_->getDevices()) { ROS_ERROR_STREAM("dev: " << dev->getName()); } return false; } return true; } PoseTeleoperate::~PoseTeleoperate() { /* Nothing specific to do */ } bool PoseTeleoperate::startListening(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { ROS_DEBUG_STREAM("start: "); if (do_teleoperate_) { ROS_DEBUG_STREAM("Stopping the running teleoperation"); stopListening(request, response); } // get pose sensor name if (!nh_.getParam("PoseArray", pose_array_name_)) { CAROS_ERROR("No pose sensor topic name defined in parameter server!", TELEOPERATE_MISSING_ROSPARAM_RUNTIME); return false; } if (!nh_.getParam("PushSensor", button_sensor_name_)) { CAROS_ERROR("No button sensor topic name defined in parameter server!", TELEOPERATE_MISSING_ROSPARAM_RUNTIME); return false; } nh_.param("PoseIdx", pose_sensor_id1_, 0); // initialize robot arm proxy ROS_INFO_STREAM("Subscribing to Device proxy, with:" << dev_->getName()); device_sip_ = std::make_shared<caros::SerialDeviceSIProxy>(nh_, dev_->getName()); ROS_INFO_STREAM("Subscribing to Pose Sensor proxy, with: " << pose_array_name_); pose_sip_ = std::make_shared<caros::PoseSensorSIProxy>(nh_, pose_array_name_); ROS_INFO_STREAM("Subscribing to ButtonSensor topic, with: " << button_sensor_name_); button_sensor_state_ = nh_.subscribe(button_sensor_name_, 1, &PoseTeleoperate::handleButtonSensor, this); if (!button_sensor_state_) { CAROS_ERROR("Subscribing to ButtonSensor topic, with: " << button_sensor_name_ << " failed!", TELEOPERATE_SUBSCRIPTION_FAILED); return false; } pose_array_state_ = nh_.subscribe(pose_array_name_, 1, &PoseTeleoperate::handlePoseArraySensor, this); ROS_INFO_STREAM("Subscribing to pose topic, with: " << pose_array_name_); if (!pose_array_state_) { CAROS_ERROR("Subscribing to pose topic, with: " << pose_array_name_ << " failed!", TELEOPERATE_SUBSCRIPTION_FAILED); return false; } // initialize doTeleoperate stuff do_teleoperate_ = true; return true; } void PoseTeleoperate::handleButtonSensor(caros_sensor_msgs::ButtonSensorState btn_state) { if (btn_state.analog[0] > 0) analog_button_pushed_ = true; else analog_button_pushed_ = false; } void PoseTeleoperate::handlePoseArraySensor(caros_sensor_msgs::PoseSensorState array) { poses_.clear(); for (const geometry_msgs::Transform pose : array.poses) { Quaternion<> quat(pose.rotation.x, pose.rotation.y, pose.rotation.z, pose.rotation.w); Vector3D<> pos(pose.translation.x, pose.translation.y, pose.translation.z); // Quaternion<> quat(pose.orientation.x, pose.orientation.y, pose.orientation.z, pose.orientation.w); // Vector3D<> pos(pose.position.x, pose.position.y, pose.position.z); poses_.push_back(Transform3D<>(pos, quat.toRotation3D())); } } bool PoseTeleoperate::pauseListening(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { /* TODO(any): */ ROS_WARN_STREAM("This method is not implemented!"); return true; } bool PoseTeleoperate::stopListening(std_srvs::Empty::Request& request, std_srvs::Empty::Response& response) { if (!do_teleoperate_) { ROS_DEBUG_STREAM("Already stopped!"); return true; } do_teleoperate_ = false; device_sip_ = NULL; pose_sip_ = NULL; return true; } void PoseTeleoperate::doTeleoperate() { // WARNING SHOULD NOT BLOCK, this should be called from another loop if (static_cast<signed int>(poses_.size()) <= pose_sensor_id1_) { ROS_WARN("no poses yet!"); return; } Transform3D<> robotbaseTtrans(RPY<>(180 * Deg2Rad, 0, 0).toRotation3D()); Transform3D<> pose1 = robotbaseTtrans * poses_[pose_sensor_id1_] * sensor_offset_; Q robQ = device_sip_->getQ(); Q robQd = device_sip_->getQd(); // std::cout << robQ << std::endl; // servoing of the robot device if (!analog_button_pushed_) { if (analog_button_) { ROS_INFO("Released BTN"); } analog_button_ = false; } else if (robQ.size() == 0) { ROS_WARN("robQ.size() is 0.... Probably due to read error in Robot State"); } else { dev_->setQ(robQ, tmp_state_); // if button was not pushed down before then save the tool/sensor transform if (!analog_button_) { ROS_INFO("Pushed BTN"); analog_button_ = true; initial_sensor_pose_ = pose1; // pose1 * offsetZpos initial_robotTtool_ = dev_->baseTend(tmp_state_) * offset_Zpos_; last_target_pose_ = pose1; } // calculate the change from initial pose to current pose // Transform3D<> initialSensorTcurrent = inverse(initialSensorPose_) * pose1; Vector3D<> relativeMotionPos = pose1.P() - initial_sensor_pose_.P(); Rotation3D<> relativeMotionRot = pose1.R() * inverse(initial_sensor_pose_.R()); Transform3D<> baseTtool_target = Transform3D<>(initial_robotTtool_.P() + relativeMotionPos, relativeMotionRot * initial_robotTtool_.R()); if (!device_sip_->moveServoT(baseTtool_target * inverse(offset_Zpos_))) { ROS_WARN("deviceSIP_->moveServoT(baseTtool_target * inverse(offsetZpos))) failed. Move command to robot failed."); } last_target_pose_ = pose1; } } } // namespace caros
31223a42c3ed9f7e31ac566031dc8bbcef5334c2
d93159d0784fc489a5066d3ee592e6c9563b228b
/SimTracker/TrackHistory/interface/HistoryBase.h
f93f8e93cec86e1a76107343ebaadb5ae48e7b4c
[]
permissive
simonecid/cmssw
86396e31d41a003a179690f8c322e82e250e33b2
2559fdc9545b2c7e337f5113b231025106dd22ab
refs/heads/CAallInOne_81X
2021-08-15T23:25:02.901905
2016-09-13T08:10:20
2016-09-13T08:53:42
176,462,898
0
1
Apache-2.0
2019-03-19T08:30:28
2019-03-19T08:30:24
null
UTF-8
C++
false
false
4,905
h
#ifndef HistoryBase_h #define HistoryBase_h #include <set> #include "SimDataFormats/TrackingAnalysis/interface/TrackingParticle.h" #include "SimDataFormats/TrackingAnalysis/interface/TrackingParticleFwd.h" #include "SimDataFormats/TrackingAnalysis/interface/TrackingVertex.h" #include "SimDataFormats/TrackingAnalysis/interface/TrackingVertexContainer.h" //! Base class to all the history types. class HistoryBase { public: //! GenParticle trail type. typedef std::vector<const HepMC::GenParticle *> GenParticleTrail; //! GenVertex trail type. typedef std::vector<const HepMC::GenVertex *> GenVertexTrail; //! GenVertex trail helper type. typedef std::set<const HepMC::GenVertex *> GenVertexTrailHelper; //! SimParticle trail type. typedef std::vector<TrackingParticleRef> SimParticleTrail; //! SimVertex trail type. typedef std::vector<TrackingVertexRef> SimVertexTrail; // Default constructor HistoryBase() { // Default depth depth_ = -1; } //! Set the depth of the history. /* Set TrackHistory to given depth. Positive values constrain the number of TrackingVertex visit in the history. Negatives values set the limit of the iteration over generated information i.e. (-1 -> status 1 or -2 -> status 2 particles). /param[in] depth the history */ void depth(int d) { depth_ = d; } //! Return all the simulated vertices in the history. SimVertexTrail const & simVertexTrail() const { return simVertexTrail_; } //! Return all the simulated particle in the history. SimParticleTrail const & simParticleTrail() const { return simParticleTrail_; } //! Return all generated vertex in the history. GenVertexTrail const & genVertexTrail() const { return genVertexTrail_; } //! Return all generated particle in the history. GenParticleTrail const & genParticleTrail() const { return genParticleTrail_; } //! Return the initial tracking particle from the history. const TrackingParticleRef & simParticle() const { return simParticleTrail_[0]; } //! Return the initial tracking vertex from the history. const TrackingVertexRef & simVertex() const { return simVertexTrail_[0]; } //! Returns a pointer to most primitive status 1 or 2 particle. const HepMC::GenParticle * genParticle() const { if ( genParticleTrail_.empty() ) return 0; return genParticleTrail_[genParticleTrail_.size()-1]; } protected: // History cointainers GenVertexTrail genVertexTrail_; GenParticleTrail genParticleTrail_; SimVertexTrail simVertexTrail_; SimParticleTrail simParticleTrail_; // Helper function to speedup search GenVertexTrailHelper genVertexTrailHelper_; //! Evaluate track history using a TrackingParticleRef. /* Return false when the history cannot be determined upto a given depth. If not depth is pass to the function no restriction are apply to it. /param[in] TrackingParticleRef of a simulated track /param[in] depth of the track history /param[out] boolean that is true when history can be determined */ bool evaluate(TrackingParticleRef tpr) { resetTrails(tpr); return traceSimHistory(tpr, depth_); } //! Evaluate track history using a TrackingParticleRef. /* Return false when the history cannot be determined upto a given depth. If not depth is pass to the function no restriction are apply to it. /param[in] TrackingVertexRef of a simulated vertex /param[in] depth of the track history /param[out] boolean that is true when history can be determined */ bool evaluate(TrackingVertexRef tvr) { resetTrails(); return traceSimHistory(tvr, depth_); } private: int depth_; //! Trace all the simulated information for a given reference to a TrackingParticle. bool traceSimHistory (TrackingParticleRef const &, int); //! Trace all the simulated information for a given reference to a TrackingVertex. bool traceSimHistory (TrackingVertexRef const &, int); //! Trace all the simulated information for a given pointer to a GenParticle. void traceGenHistory (HepMC::GenParticle const *); //! Trace all the simulated information for a given pointer to a GenVertex. void traceGenHistory (HepMC::GenVertex const *); //! Reset trail functions. void resetTrails() { simParticleTrail_.clear(); simVertexTrail_.clear(); genVertexTrail_.clear(); genParticleTrail_.clear(); genVertexTrailHelper_.clear(); } void resetTrails(TrackingParticleRef tpr) { resetTrails(); simParticleTrail_.push_back(tpr); } }; #endif
a6a34e5454cde0e7ab848175c76f1e4d99b0e29a
104a2ae28ff3a649c92ffa9cc0f397e452330f24
/aws-cpp-sdk-kinesisanalyticsv2/include/aws/kinesisanalyticsv2/model/MonitoringConfiguration.h
e6c73aa321c4ee170a10cbd8dbbbb83251a0c3c6
[ "MIT", "Apache-2.0", "JSON" ]
permissive
quatmax/aws-sdk-cpp
6ca111b3da69af5e802a3feac70a8da4de006d5d
578070580b614460a8bd76cf86e305a2e69d0adb
refs/heads/master
2021-01-18T00:30:48.206056
2020-10-05T14:10:05
2020-10-05T14:10:05
301,419,784
0
0
Apache-2.0
2020-10-05T13:34:23
2020-10-05T13:34:22
null
UTF-8
C++
false
false
6,441
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/kinesisanalyticsv2/KinesisAnalyticsV2_EXPORTS.h> #include <aws/kinesisanalyticsv2/model/ConfigurationType.h> #include <aws/kinesisanalyticsv2/model/MetricsLevel.h> #include <aws/kinesisanalyticsv2/model/LogLevel.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace KinesisAnalyticsV2 { namespace Model { /** * <p>Describes configuration parameters for Amazon CloudWatch logging for a * Java-based Kinesis Data Analytics application. For more information about * CloudWatch logging, see <a * href="https://docs.aws.amazon.com/kinesisanalytics/latest/java/monitoring-overview.html">Monitoring</a>.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/kinesisanalyticsv2-2018-05-23/MonitoringConfiguration">AWS * API Reference</a></p> */ class AWS_KINESISANALYTICSV2_API MonitoringConfiguration { public: MonitoringConfiguration(); MonitoringConfiguration(Aws::Utils::Json::JsonView jsonValue); MonitoringConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p>Describes whether to use the default CloudWatch logging configuration for an * application. You must set this property to <code>CUSTOM</code> in order to set * the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p> */ inline const ConfigurationType& GetConfigurationType() const{ return m_configurationType; } /** * <p>Describes whether to use the default CloudWatch logging configuration for an * application. You must set this property to <code>CUSTOM</code> in order to set * the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p> */ inline bool ConfigurationTypeHasBeenSet() const { return m_configurationTypeHasBeenSet; } /** * <p>Describes whether to use the default CloudWatch logging configuration for an * application. You must set this property to <code>CUSTOM</code> in order to set * the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p> */ inline void SetConfigurationType(const ConfigurationType& value) { m_configurationTypeHasBeenSet = true; m_configurationType = value; } /** * <p>Describes whether to use the default CloudWatch logging configuration for an * application. You must set this property to <code>CUSTOM</code> in order to set * the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p> */ inline void SetConfigurationType(ConfigurationType&& value) { m_configurationTypeHasBeenSet = true; m_configurationType = std::move(value); } /** * <p>Describes whether to use the default CloudWatch logging configuration for an * application. You must set this property to <code>CUSTOM</code> in order to set * the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p> */ inline MonitoringConfiguration& WithConfigurationType(const ConfigurationType& value) { SetConfigurationType(value); return *this;} /** * <p>Describes whether to use the default CloudWatch logging configuration for an * application. You must set this property to <code>CUSTOM</code> in order to set * the <code>LogLevel</code> or <code>MetricsLevel</code> parameters.</p> */ inline MonitoringConfiguration& WithConfigurationType(ConfigurationType&& value) { SetConfigurationType(std::move(value)); return *this;} /** * <p>Describes the granularity of the CloudWatch Logs for an application.</p> */ inline const MetricsLevel& GetMetricsLevel() const{ return m_metricsLevel; } /** * <p>Describes the granularity of the CloudWatch Logs for an application.</p> */ inline bool MetricsLevelHasBeenSet() const { return m_metricsLevelHasBeenSet; } /** * <p>Describes the granularity of the CloudWatch Logs for an application.</p> */ inline void SetMetricsLevel(const MetricsLevel& value) { m_metricsLevelHasBeenSet = true; m_metricsLevel = value; } /** * <p>Describes the granularity of the CloudWatch Logs for an application.</p> */ inline void SetMetricsLevel(MetricsLevel&& value) { m_metricsLevelHasBeenSet = true; m_metricsLevel = std::move(value); } /** * <p>Describes the granularity of the CloudWatch Logs for an application.</p> */ inline MonitoringConfiguration& WithMetricsLevel(const MetricsLevel& value) { SetMetricsLevel(value); return *this;} /** * <p>Describes the granularity of the CloudWatch Logs for an application.</p> */ inline MonitoringConfiguration& WithMetricsLevel(MetricsLevel&& value) { SetMetricsLevel(std::move(value)); return *this;} /** * <p>Describes the verbosity of the CloudWatch Logs for an application.</p> */ inline const LogLevel& GetLogLevel() const{ return m_logLevel; } /** * <p>Describes the verbosity of the CloudWatch Logs for an application.</p> */ inline bool LogLevelHasBeenSet() const { return m_logLevelHasBeenSet; } /** * <p>Describes the verbosity of the CloudWatch Logs for an application.</p> */ inline void SetLogLevel(const LogLevel& value) { m_logLevelHasBeenSet = true; m_logLevel = value; } /** * <p>Describes the verbosity of the CloudWatch Logs for an application.</p> */ inline void SetLogLevel(LogLevel&& value) { m_logLevelHasBeenSet = true; m_logLevel = std::move(value); } /** * <p>Describes the verbosity of the CloudWatch Logs for an application.</p> */ inline MonitoringConfiguration& WithLogLevel(const LogLevel& value) { SetLogLevel(value); return *this;} /** * <p>Describes the verbosity of the CloudWatch Logs for an application.</p> */ inline MonitoringConfiguration& WithLogLevel(LogLevel&& value) { SetLogLevel(std::move(value)); return *this;} private: ConfigurationType m_configurationType; bool m_configurationTypeHasBeenSet; MetricsLevel m_metricsLevel; bool m_metricsLevelHasBeenSet; LogLevel m_logLevel; bool m_logLevelHasBeenSet; }; } // namespace Model } // namespace KinesisAnalyticsV2 } // namespace Aws
a90dd159ef105427d1cf4330c73ea7433dadd24e
d625eb0f2e675d6e40b0849d1e5f20b1aef4c406
/codeforce/Codeforce_Rating_Round/Round_395/B_test.cpp
4102b655ca9600da0c79b0b504a7bf2111f74d02
[]
no_license
aseem01/Competitive_Programming
b5a57c7b10b731ea2b03288c500dd85c8f5fda2c
ad7354c56cada964b2c5331f15424d580febe2b6
refs/heads/master
2021-01-25T11:28:57.402352
2018-11-09T06:59:46
2018-11-09T06:59:46
93,930,174
0
0
null
null
null
null
UTF-8
C++
false
false
847
cpp
#include <bits/stdc++.h> using namespace std; int main() { int n,l; cin>>n>>l; int i,j,m; int k[100],s[100],kk[100]; for(i=0; i<n; i++) { cin>>k[i]; } kk[0]=l-k[n-1]+k[0]; for(i=1; i<n; i++) { kk[i]=k[i]-k[i-1]; } for(i=0; i<n; i++) { cin>>s[i]; } int ss[1000]; ss[0]=l-s[n-1]+s[0]; for(i=1; i<n; i++) { ss[i]=s[i]-s[i-1]; } j=0; for(i=n; i<2*n; i++) { ss[i]=ss[j]; j++; } int flg; for(i=0; i<n; i++) { flg=0; for(j=0; j<n; j++) { if(ss[i+j]!=kk[j]) { flg=1; break; } } if(flg==0) { cout<<"YES"<<endl; return 0; } } cout<<"NO"<<endl; }
9911eb6635830ceb9819d097f306f33462274b8f
63cb28e9191fb16bb7940d187595227f81d0e7a4
/Frequency.cpp
05c974572cf2992e7c089e992d61f946211c4908
[]
no_license
Varun2851/CppBasics
b6082c61f3973cc8e9be41ecc7bf05e93fe83a6d
2e24decd361acc442a1c7c96005fee9b1c100fe6
refs/heads/main
2023-07-05T17:09:44.514478
2021-08-26T06:38:17
2021-08-26T06:38:17
389,422,796
0
1
null
null
null
null
UTF-8
C++
false
false
647
cpp
#include<iostream> using namespace std; void freq(int arr[],int n){ for(int i =0; i<n; i++){ bool flag = false; for(int j = 0 ; j<i; j++){ if(arr[i] == arr[j]){ flag = true; break; } } if(flag == true){ continue; } int freq1 = 1; for(int j = i+1; j<n; j++){ if(arr[i] == arr[j]){ freq1++; } } cout<<arr[i]<<" "<<freq1<<endl; } } int main(){ int arr[] = {10,10,10,30,30,70,60,60}; int n = sizeof(arr)/sizeof(int); freq(arr , n); return 0; }
3bfb5442b4377d84bcf56e5ae6238b76ae268581
c32a95e4444812f204bed4de2c59e5ee9e5134ad
/AlgorithmChallenges/ActorJobs.cpp
7c7ca025ff00ff3cf50c95381d5644d31f8deb3d
[]
no_license
AlwinJoshy/Algorithm_Challenges
7f6fb060df458e7012195d7b87c194761d8c629d
dd2ef610148d7f5bdca12d90ecd5fa4461089a3e
refs/heads/master
2020-08-10T16:28:16.686273
2019-10-11T13:58:03
2019-10-11T13:58:03
214,371,542
0
0
null
null
null
null
UTF-8
C++
false
false
1,311
cpp
#include <iostream> enum Months { jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec }; class Job { public: int startMonth; int endMonth; Job(Months start, Months end) { startMonth = start; endMonth = end; } }; bool Overlaping(Job jobOne, Job jobTwo) { if (jobOne.startMonth < jobTwo.endMonth && jobOne.endMonth > jobTwo.startMonth) return true; else return false; } int main() { Job allJobs[11] = { Job(jan, oct), Job(may, jun), Job(jan, apr), Job(oct, dec), Job(aug, oct), Job(apr, aug), Job(feb, jul), Job(sep, nov), Job(may, jul), Job(jan, feb), Job(feb, mar) }; int jobMemo[10] = { 0,0,0,0,0,0,0,0,0,0 }; int memoSize = 0; for (int i = 0; i < 11; i++) { memoSize = 1; jobMemo[memoSize - 1] = i; for (int n = 0; n < 11; n++) { bool addJob = true; for (int k = 0; k < memoSize; k++) { if (jobMemo[k] != n) { if (Overlaping(allJobs[jobMemo[k]], allJobs[n])) { addJob = false; break; } } else addJob = false; } if (addJob) { memoSize++; jobMemo[memoSize - 1] = n; } } std::cout << "job count is : " << memoSize << " the job list no : "; for (int i = 0; i < memoSize; i++) { std::cout << jobMemo[i] << " | "; } std::cout << "\n"; } }
39916cc5b12eb20fd3d51582e38920fba939abd4
4fdc4944d15bbc4ba4f1cf28e8f86c26e7900d9d
/src/privatesend-util.cpp
a1fc39a1e0d3897bb64c63bd45b615f3adf63b4e
[ "MIT" ]
permissive
Abysmalsony/PESPCOIN
b99786197907096d302d5ad4641765cf4026803c
118b00e0ea3b86704d75dcce7ef7277d123d3d11
refs/heads/main
2023-07-13T11:14:04.544098
2021-08-19T13:32:55
2021-08-19T13:32:55
404,490,220
1
0
MIT
2021-09-08T20:45:08
2021-09-08T20:45:08
null
UTF-8
C++
false
false
1,824
cpp
// Copyright (c) 2014-2017 The PESPCOIN Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "privatesend-util.h" CKeyHolder::CKeyHolder(CWallet* pwallet) : reserveKey(pwallet) { reserveKey.GetReservedKey(pubKey, false); } void CKeyHolder::KeepKey() { reserveKey.KeepKey(); } void CKeyHolder::ReturnKey() { reserveKey.ReturnKey(); } CScript CKeyHolder::GetScriptForDestination() const { return ::GetScriptForDestination(pubKey.GetID()); } CScript CKeyHolderStorage::AddKey(CWallet* pwallet) { auto keyHolder = std::unique_ptr<CKeyHolder>(new CKeyHolder(pwallet)); auto script = keyHolder->GetScriptForDestination(); LOCK(cs_storage); storage.emplace_back(std::move(keyHolder)); LogPrintf("CKeyHolderStorage::%s -- storage size %lld\n", __func__, storage.size()); return script; } void CKeyHolderStorage::KeepAll() { std::vector<std::unique_ptr<CKeyHolder>> tmp; { // don't hold cs_storage while calling KeepKey(), which might lock cs_wallet LOCK(cs_storage); std::swap(storage, tmp); } if (tmp.size() > 0) { for (auto &key : tmp) { key->KeepKey(); } LogPrintf("CKeyHolderStorage::%s -- %lld keys kept\n", __func__, tmp.size()); } } void CKeyHolderStorage::ReturnAll() { std::vector<std::unique_ptr<CKeyHolder>> tmp; { // don't hold cs_storage while calling ReturnKey(), which might lock cs_wallet LOCK(cs_storage); std::swap(storage, tmp); } if (tmp.size() > 0) { for (auto &key : tmp) { key->ReturnKey(); } LogPrintf("CKeyHolderStorage::%s -- %lld keys returned\n", __func__, tmp.size()); } }
13651d243149db666cff59d6813e20218d5428af
7fca22474c2741cf7e3fb31c8b8b89799068cdea
/examples/sample.cpp
d3b7184917b38bf95b71002bb8685d5bc27cdd74
[ "BSD-2-Clause" ]
permissive
rbock/sqlpp-concepts-experiments
fc0783d5ecc2dc852edd6950e60102888617f110
6ff7a93ba5bfa27e2aaa29d6860a6cbd3b806ad4
refs/heads/master
2020-05-07T15:10:38.256652
2015-03-31T07:58:06
2015-03-31T07:58:06
32,673,691
1
0
null
null
null
null
UTF-8
C++
false
false
2,141
cpp
/* * Copyright (c) 2014-2015 Roland Bock * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "Sample.h" #include "MockDb.h" #include <sqlpp11/sqlpp11.h> int main() { MockDb db; test::TabPerson p; test::TabFeature f; db(insert_into(f).set(f.name = "Loves C++", p.fatal = false)); db(insert_into(f).set(p.name = "Roland", p.feature = 1)); auto s = select(all_of(p)) .from(p, q) .where(p.name == any(select(q.name) .from(q) .where(true))) .group_by(q.name) .having(p.name.like("%Bee%")) .order_by(p.name.asc()) .limit(3).offset(7); auto x = s.as(sqlpp::alias::x); for (const auto& row : db(select(p.id, x.name) .from(p.join(x).on(p.feature == x.feature)) .where(true))) { int id = row.id; std::string name = row.name; } }
539bab2aaac7668978b291bdd3a39411c199b005
766996d84cc71493deaf100f2493ee42ed0d4243
/src/ifc/ifc4/IfcRelAssociatesLibrary.h
27a11dedd5c93ee66e42a44ff22de28026bab3a4
[]
no_license
andreasniggl/ifclite
6040cd72460d401a364c4c7554f2fe3f44ee6df8
aacc8a9f0add7036c4c04eeaed7938e731726ead
refs/heads/master
2020-03-09T05:13:57.641923
2018-08-06T21:42:27
2018-08-06T21:42:27
128,607,886
3
1
null
null
null
null
UTF-8
C++
false
false
1,389
h
// Automatically generated by ifclite express parser from ifc4 express file - do not modify #pragma once #include "IfcTypeDefinitions.h" #include "IfcRelAssociates.h" #include "IfcLibrarySelect.h" namespace ifc4 { class IfcRelAssociatesLibrary : public IfcRelAssociates { public: virtual ~IfcRelAssociatesLibrary(){} explicit IfcRelAssociatesLibrary() = default; explicit IfcRelAssociatesLibrary(const IfcGloballyUniqueId& _GlobalId, const std::vector< boost::optional<IfcDefinitionSelect> >& _RelatedObjects, const IfcLibrarySelect& _RelatingLibrary) : IfcRelAssociates(_GlobalId, _RelatedObjects), RelatingLibrary(_RelatingLibrary) {} virtual std::string className() const { return "IfcRelAssociatesLibrary"; } boost::optional<IfcLibrarySelect> RelatingLibrary; // required parameter protected: virtual void serialize(ifc::StepWriter& w) const { w.beginEntity(this); w.writeAttributeValue(GlobalId); w.writeAttributeInstance(OwnerHistory); w.writeAttributeValue(Name); w.writeAttributeValue(Description); w.writeAttributeSelect<IfcDefinitionSelectWriterVisitor>(RelatedObjects); w.writeAttributeSelect<IfcLibrarySelectWriterVisitor>(RelatingLibrary); w.endEntity(); } }; } // namespace ifc4
c134767e7d527dc572391ed3114e0f0079e401c3
c2233b9d54688c32836dea72b6c9ac3306d37213
/analyzer/analyzer.cpp
d0b1527cad1147c97616398264cea045dbd47a65
[ "MIT" ]
permissive
zarath/AntScope2
64f404acdad819aa886d63c259513cf9fb5e47b9
259f0d36e82384487ca214bfc793cb0097e28f5c
refs/heads/master
2022-11-17T23:32:59.507981
2020-07-14T20:13:50
2020-07-14T20:13:50
279,683,944
0
0
MIT
2020-07-14T20:14:14
2020-07-14T20:14:14
null
UTF-8
C++
false
false
34,902
cpp
#include "analyzer.h" #include "popupindicator.h" #include "customanalyzer.h" #include <QDateTime> #include "Notification.h" Analyzer::Analyzer(QObject *parent) : QObject(parent), m_hidAnalyzer(nullptr), m_comAnalyzer(nullptr), m_analyzerModel(0), m_comAnalyzerFound(false), m_hidAnalyzerFound(false), m_nanovnaAnalyzerFound(false), m_chartCounter(0), m_isMeasuring(false), m_isContinuos(false), m_dotsNumber(100), m_downloader(nullptr), m_updateDialog(nullptr), m_pfw(nullptr), m_INFOSIZE(512), m_MAGICAA230Z(0xFE02A185), m_MAGICHID(0x5c620202), m_INTERNALMAGICAA230Z(0x87654321), m_MAGICAA30ZERO(0x5c623002), m_calibrationMode(false) { m_pfw = new QByteArray; } Analyzer::~Analyzer() { if(m_downloader) { delete m_downloader; m_downloader = nullptr; } delete m_pfw; if(m_hidAnalyzer) { delete m_hidAnalyzer; m_hidAnalyzer = nullptr; } if(m_comAnalyzer) { comAnalyzer* tmp = m_comAnalyzer; m_comAnalyzer = nullptr; delete tmp; } } double Analyzer::getVersion() const { if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { return m_comAnalyzer->getVersion().toDouble(); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { return m_hidAnalyzer->getVersion().toDouble(); } return 0; } void Analyzer::on_downloadInfoComplete() { QString ver = m_downloader->version(); if (m_bManualUpdate) { if(ver.isEmpty()) { QMessageBox::information(nullptr, tr("Latest version"), tr("Can not get the latest version.\nPlease try later.")); }else { double internetVersion = ver.toDouble();//ver.remove(".").toInt(); m_updateDialog = new UpdateDialog(); m_updateDialog->setAttribute(Qt::WA_DeleteOnClose); m_updateDialog->setWindowTitle(tr("Updating")); connect(m_updateDialog,SIGNAL(update()),this,SLOT(on_internetUpdate())); connect(this, SIGNAL(updatePercentChanged(int)),m_updateDialog,SLOT(on_percentChanged(qint32))); if(internetVersion > getVersion()) { m_updateDialog->setMainText(tr("New version of firmware is available now!")); }else { m_updateDialog->setMainText(tr("You have the latest version of firmware.")); } m_updateDialog->exec(); } } else { // auto check for new firmvare if (!ver.isEmpty()) { double internetVersion = ver.toDouble(); if(internetVersion > getVersion()) { const qint64 interval = 24*60*60; QString serialNumber = getSerialNumber(); QString key = "firmware_" + serialNumber; QSettings settings(Settings::setIniFile(), QSettings::IniFormat); settings.beginGroup("Update"); qint64 last_notify = settings.value(key, 0).toLongLong(); QDateTime last_dt; last_dt.setMSecsSinceEpoch(last_notify); QDateTime current_dt = QDateTime::currentDateTime(); if (last_dt.secsTo(current_dt) > interval) { settings.setValue(key, QDateTime::currentMSecsSinceEpoch()); emit showNotification( QString(tr("New version of firmware is available now!")), m_downloader->downloadLink()); } settings.endGroup(); } } } } bool Analyzer::needCheckForUpdate() { const qint64 interval = 24*60*60; QString serialNumber = getSerialNumber(); QString key = "firmware_" + serialNumber; QSettings settings(Settings::setIniFile(), QSettings::IniFormat); settings.beginGroup("Update"); qint64 last_notify = settings.value(key, 0).toLongLong(); QDateTime last_dt; last_dt.setMSecsSinceEpoch(last_notify); QDateTime current_dt = QDateTime::currentDateTime(); return last_dt.secsTo(current_dt) > interval; } void Analyzer::on_downloadFileComplete() { *m_pfw = m_downloader->file(); QBuffer fwdata(m_pfw); fwdata.open(QIODevice::ReadOnly); fwdata.seek(m_INFOSIZE); updateFirmware(&fwdata); } void Analyzer::on_internetUpdate() { m_downloader->startDownloadFw(); m_updateDialog->setStatusText(tr("Downloading firmware...")); } void Analyzer::readFile(QString pathToFw) { QFile file(pathToFw); bool state = true; if(!file.open(QIODevice::ReadOnly)) { QMessageBox::warning(nullptr, tr("Warning"), tr("Can not open firmware file.")); return; } *m_pfw = file.readAll(); if (m_pfw->isEmpty()) { QMessageBox::warning(nullptr, tr("Warning"), tr("Can not read firmware file.")); state = false; } file.close(); if(state) { //m_updateDialog->setStatusText(tr("Updating, please wait...")); QBuffer fwdata(m_pfw); fwdata.open(QIODevice::ReadOnly); fwdata.seek(m_INFOSIZE); updateFirmware(&fwdata); } } bool Analyzer::checkFile(QString path) { QFile fwfile(path); QByteArray arr; QByteArray fw; quint32 magic = 0; quint32 len = 0; quint32 readCrc = 0; quint32 revision = 0; const char *pd; if (!fwfile.open(QIODevice::ReadOnly)) { QMessageBox::warning(nullptr, tr("Warning"), tr("Firmware file can not open")); return false; } arr = fwfile.read(m_INFOSIZE); if ((qint32)arr.length() < m_INFOSIZE) { fwfile.close(); return false; } pd = arr.constData(); magic = qFromLittleEndian<quint32>(*((quint32*)pd)); len = qFromLittleEndian<quint32>(*((quint32*)&pd[4])); readCrc = qFromLittleEndian<quint32>(*((quint32*)&pd[8])); revision = qFromLittleEndian<quint32>(*((quint32*)&pd[20])); if(m_hidAnalyzer) { //m_hidAnalyzer->setRevision(revision); // old m_hidAnalyzer->setRevision(QString::number(revision)); } QString prototype = CustomAnalyzer::currentPrototype(); if(((names[getAnalyzerModel()] == "AA-230 ZOOM" || prototype == "AA-230 ZOOM") && (magic == m_MAGICAA230Z)) || ((names[getAnalyzerModel()] == "AA-650 ZOOM" || prototype == "AA-650 ZOOM") && (magic == m_MAGICAA230Z)) || ((names[getAnalyzerModel()] == "AA-55 ZOOM" || prototype == "AA-55 ZOOM") && (magic == m_MAGICHID)) || ((names[getAnalyzerModel()] == "AA-35 ZOOM" || prototype == "AA-35 ZOOM") && (magic == m_MAGICHID)) || ((names[getAnalyzerModel()] == "AA-30 ZERO" || prototype == "AA-30 ZERO") && (magic == m_MAGICAA30ZERO)) || ((names[getAnalyzerModel()] == "AA-30.ZERO" || prototype == "AA-30.ZERO") && (magic == m_MAGICAA30ZERO))) { }else { QMessageBox::warning(nullptr, tr("Warning"), tr("Firmware file has wrong format")); fwfile.close(); return false; } if (!fwfile.seek(m_INFOSIZE)) { QMessageBox::warning(nullptr, tr("Warning"), tr("Firmware file is too short.")); fwfile.close(); return false; } fw = fwfile.readAll(); fwfile.close(); if ((quint32)fw.length() != len) { QMessageBox::warning(nullptr, tr("Warning"), tr("Firmware file has wrong length.")); return false; } if (readCrc != CRC32::crc(0xffffffff, fw)) { QMessageBox::warning(nullptr, tr("Warning"), tr("Firmware file has wrong CRC.")); return false; } return true; } QString Analyzer::getModelString( void ) { return CustomAnalyzer::customized() ? CustomAnalyzer::currentPrototype() : names[m_analyzerModel]; } quint32 Analyzer::getModel( void ) { return m_analyzerModel; } quint32 Analyzer::getHidModel( void ) { return m_hidAnalyzer->getModel(); } QString Analyzer::getSerialNumber(void) const { if(m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { return m_hidAnalyzer->getSerial(); }else if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { return m_comAnalyzer->getSerial(); } return QString(); } void Analyzer::on_measure (qint64 fqFrom, qint64 fqTo, qint32 dotsNumber) { m_getAnalyzerData = false; if(!m_isMeasuring) { m_isMeasuring = true; QDateTime datetime = QDateTime::currentDateTime(); QString name = datetime.toString("##dd.MM.yyyy-hh:mm:ss"); emit newMeasurement(name, fqFrom, fqTo, dotsNumber); //emit newMeasurement(name); m_dotsNumber = dotsNumber; m_chartCounter = 0; if (m_nanovnaAnalyzerFound && m_NanovnaAnalyzer != nullptr) { m_dotsNumber = 101; m_NanovnaAnalyzer->startMeasure(fqFrom, fqTo, m_dotsNumber); } else if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_comAnalyzer->setIsFRXMode(true); m_comAnalyzer->startMeasure(fqFrom,fqTo,m_dotsNumber); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { m_hidAnalyzer->setIsFRXMode(true); m_hidAnalyzer->startMeasure(fqFrom,fqTo,m_dotsNumber); } PopUpIndicator::setIndicatorVisible(true); } else { on_stopMeasure(); } } void Analyzer::on_measureContinuous(qint64 fqFrom, qint64 fqTo, qint32 dotsNumber) { if(!m_isMeasuring) { qDebug() << "Analyzer::on_measureContinuous" << fqFrom << fqTo << dotsNumber; m_isMeasuring = true; //QThread::msleep(500); emit continueMeasurement(fqFrom, fqTo, dotsNumber); m_dotsNumber = dotsNumber; m_chartCounter = 0; if (m_nanovnaAnalyzerFound && m_NanovnaAnalyzer != nullptr) { //m_NanovnaAnalyzer->startMeasure(fqFrom, fqTo, dotsNumber); } else if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_comAnalyzer->startMeasure(fqFrom,fqTo,dotsNumber); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { //m_hidAnalyzer->setIsFRXMode(true); m_hidAnalyzer->startMeasure(fqFrom,fqTo,dotsNumber); } PopUpIndicator::setIndicatorVisible(true); } else { qDebug() << "Analyzer::on_measureContinuous STOP"; on_stopMeasure(); } } void Analyzer::on_measureUser (qint64 fqFrom, qint64 fqTo, qint32 dotsNumber) { if(!m_isMeasuring) { m_isMeasuring = true; QDateTime datetime = QDateTime::currentDateTime(); QString name = datetime.toString("##dd.MM.yyyy-hh:mm:ss"); emit newMeasurement(name, fqFrom, fqTo, dotsNumber); m_dotsNumber = dotsNumber; m_chartCounter = 0; if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_comAnalyzer->setIsFRXMode(false); m_comAnalyzer->startMeasure(fqFrom,fqTo,dotsNumber); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { m_hidAnalyzer->setIsFRXMode(false); m_hidAnalyzer->startMeasure(fqFrom,fqTo,dotsNumber); } PopUpIndicator::setIndicatorVisible(true); } else { on_stopMeasure(); } } void Analyzer::on_measureOneFq(QWidget* /*parent*/, qint64 fqFrom, qint32 /*dotsNumber*/) { m_isMeasuring = true; m_dotsNumber = 100000; m_chartCounter = 0; if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_comAnalyzer->setIsFRXMode(true); m_comAnalyzer->startMeasureOneFq(fqFrom,m_dotsNumber); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { m_hidAnalyzer->setIsFRXMode(true); m_hidAnalyzer->startMeasureOneFq(fqFrom,m_dotsNumber); } } void Analyzer::on_stopMeasure() { PopUpIndicator::setIndicatorVisible(false); m_isMeasuring = false; m_chartCounter = 0; if (m_nanovnaAnalyzerFound && m_NanovnaAnalyzer != nullptr) { m_NanovnaAnalyzer->stopMeasure(); } else if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_comAnalyzer->stopMeasure(); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { m_hidAnalyzer->stopMeasure(); } emit measurementComplete(); } void Analyzer::updateFirmware (QIODevice *fw) { if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_comAnalyzer->update(fw); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { m_hidAnalyzer->update(fw); } } void Analyzer::setAutoCheckUpdate( bool state) { m_autoCheckUpdate = state; } void Analyzer::makeScreenshot() { if(!m_isMeasuring) { if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { QTimer::singleShot(100, m_comAnalyzer, SLOT(makeScreenshot())); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { QTimer::singleShot(100, m_hidAnalyzer, SLOT(makeScreenshot())); } } } void Analyzer::on_hidAnalyzerFound (quint32 analyzerNumber) { if(m_comAnalyzer) { comAnalyzer* tmp = m_comAnalyzer; m_comAnalyzer = nullptr; delete tmp; } m_hidAnalyzerFound = true; m_analyzerModel = analyzerNumber; QString str = CustomAnalyzer::customized() ? CustomAnalyzer::currentAlias() : names[m_analyzerModel]; emit analyzerFound(str); //if(m_autoCheckUpdate) extern bool g_developerMode; if (!g_developerMode) { QTimer::singleShot(5000, [this]() { this->checkFirmwareUpdate(); }); } } void Analyzer::on_hidAnalyzerDisconnected () { if(!m_comAnalyzer) { m_comAnalyzer = new comAnalyzer(this); connect(m_comAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData))); connect(m_comAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData))); connect(m_comAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList))); connect(m_comAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_comAnalyzerFound(quint32))); connect(m_comAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_comAnalyzerDisconnected())); connect(m_comAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString))); connect(m_comAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray))); connect(m_comAnalyzer,SIGNAL(updatePercentChanged(int)),this,SLOT(on_updatePercentChanged(int))); connect(this, SIGNAL(screenshotComplete()),m_comAnalyzer,SLOT(on_screenshotComplete())); connect(this, SIGNAL(measurementComplete()), m_comAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection); connect(m_comAnalyzer,SIGNAL(aa30bootFound()),this,SIGNAL(aa30bootFound())); connect(m_comAnalyzer, SIGNAL(aa30updateComplete()), this, SIGNAL(aa30updateComplete())); connect(m_comAnalyzer, &comAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo); connect(m_comAnalyzer, &comAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError); } m_hidAnalyzerFound = false; m_analyzerModel = 0; emit analyzerDisconnected(); } void Analyzer::on_comAnalyzerFound (quint32 analyzerNumber) { if(m_hidAnalyzer) { delete m_hidAnalyzer; m_hidAnalyzer = nullptr; } m_comAnalyzerFound = true; m_analyzerModel = analyzerNumber; QString str = CustomAnalyzer::customized() ? CustomAnalyzer::currentPrototype() : names[m_analyzerModel]; emit analyzerFound(str); // //if(m_autoCheckUpdate) // { // QString url = "https://www.rigexpert.com/getfirmware?model="; // url += names[m_analyzerModel].toLower().remove(" ").remove("-"); // url += "&sn="; // url += m_hidAnalyzer->getSerial(); // url += "&revision="; // url += "1"; // m_downloader->startDownloadInfo(QUrl(url)); // } //if(m_autoCheckUpdate) extern bool g_developerMode; if (!g_developerMode) { QTimer::singleShot(5000, [this]() { this->checkFirmwareUpdate(); }); } } void Analyzer::on_comAnalyzerDisconnected () { if(!m_hidAnalyzer) { m_hidAnalyzer = new hidAnalyzer(this); connect(m_hidAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData))); connect(m_hidAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData))); connect(m_hidAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList))); connect(m_hidAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_hidAnalyzerFound(quint32))); connect(m_hidAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_hidAnalyzerDisconnected())); connect(m_hidAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString))); connect(m_hidAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray))); connect(this, SIGNAL(screenshotComplete()),m_hidAnalyzer,SLOT(on_screenshotComplete())); connect(this, SIGNAL(measurementComplete()), m_hidAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection); connect(m_hidAnalyzer, &hidAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo); connect(m_hidAnalyzer, &hidAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError); } m_comAnalyzerFound = false; m_analyzerModel = 0; if(m_comAnalyzer != nullptr) { m_comAnalyzer->setAnalyzerModel(0); } emit analyzerDisconnected(); } void Analyzer::on_nanovnaAnalyzerFound (QString name) { if(m_hidAnalyzer) { delete m_hidAnalyzer; m_hidAnalyzer = nullptr; } if(m_comAnalyzer) { delete m_comAnalyzer; m_comAnalyzer = nullptr; } m_hidAnalyzerFound = false; m_comAnalyzerFound = false; m_nanovnaAnalyzerFound = true; for (int i=0; i<QUANTITY; i++) { if (names[i] == "NanoVNA") { m_analyzerModel = i; break; } } emit analyzerFound(name); } void Analyzer::on_nanovnaAnalyzerDisconnected() { if(!m_comAnalyzer) { m_comAnalyzer = new comAnalyzer(this); connect(m_comAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData))); connect(m_comAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData))); connect(m_comAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList))); connect(m_comAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_comAnalyzerFound(quint32))); connect(m_comAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_comAnalyzerDisconnected())); connect(m_comAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString))); connect(m_comAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray))); connect(m_comAnalyzer,SIGNAL(updatePercentChanged(int)),this,SLOT(on_updatePercentChanged(int))); connect(this, SIGNAL(screenshotComplete()),m_comAnalyzer,SLOT(on_screenshotComplete())); connect(this, SIGNAL(measurementComplete()), m_comAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection); connect(m_comAnalyzer,SIGNAL(aa30bootFound()),this,SIGNAL(aa30bootFound())); connect(m_comAnalyzer, SIGNAL(aa30updateComplete()), this, SIGNAL(aa30updateComplete())); connect(m_comAnalyzer, &comAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo); connect(m_comAnalyzer, &comAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError); } if(!m_hidAnalyzer) { m_hidAnalyzer = new hidAnalyzer(this); connect(m_hidAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData))); connect(m_hidAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData))); connect(m_hidAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList))); connect(m_hidAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_hidAnalyzerFound(quint32))); connect(m_hidAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_hidAnalyzerDisconnected())); connect(m_hidAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString))); connect(m_hidAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray))); connect(this, SIGNAL(screenshotComplete()),m_hidAnalyzer,SLOT(on_screenshotComplete())); connect(this, SIGNAL(measurementComplete()), m_hidAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection); connect(m_hidAnalyzer, &hidAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo); connect(m_hidAnalyzer, &hidAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError); } m_nanovnaAnalyzerFound = false; m_analyzerModel = 0; emit analyzerDisconnected(); } void Analyzer::on_newData(rawData _rawData) { if (m_getAnalyzerData) { emit newAnalyzerData (_rawData); } else { emit newData (_rawData); } if(++m_chartCounter >= m_dotsNumber+1 || !m_isMeasuring) { m_isMeasuring = false; m_chartCounter = 0; PopUpIndicator::setIndicatorVisible(false); if(!m_calibrationMode) { emit measurementComplete(); } } } void Analyzer::on_newUserData(rawData _rawData, UserData _userData) { if(++m_chartCounter == m_dotsNumber+1 || !m_isMeasuring) { emit newUserData (_rawData, _userData); m_isMeasuring = false; m_chartCounter = 0; PopUpIndicator::setIndicatorVisible(false); if(!m_calibrationMode) { emit measurementComplete(); } }else { emit newUserData (_rawData, _userData); } } void Analyzer::on_newUserDataHeader(QStringList fields) { emit newUserDataHeader (fields); } void Analyzer::on_analyzerDataStringArrived(QString str) { emit analyzerDataStringArrived(str); } void Analyzer::getAnalyzerData() { if(!m_isMeasuring) { if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { QTimer::singleShot(100, m_comAnalyzer, SLOT(getAnalyzerData())); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { QTimer::singleShot(100, m_hidAnalyzer, SLOT(getAnalyzerData())); } } } void Analyzer::on_itemDoubleClick(QString number, QString dotsNumber, QString name) { setIsMeasuring(true); if (name.trimmed().isEmpty()) { name = number; } m_getAnalyzerData = true; if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_chartCounter = 0; m_dotsNumber = dotsNumber.toInt(); emit newMeasurement(name); m_comAnalyzer->getAnalyzerData(number); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { m_chartCounter = 0; m_dotsNumber = dotsNumber.toInt(); emit newMeasurement(name); m_hidAnalyzer->getAnalyzerData(number); } } void Analyzer::on_dialogClosed() { //setIsMeasuring(false); } void Analyzer::on_stopMeasuring() { setIsMeasuring(false); } void Analyzer::on_analyzerScreenshotDataArrived(QByteArray arr) { emit analyzerScreenshotDataArrived(arr); } void Analyzer::on_screenshotComplete(void) { emit screenshotComplete(); } void Analyzer::on_updatePercentChanged(int number) { if (m_updateDialog != nullptr) m_updateDialog->on_percentChanged(number); emit updatePercentChanged(number); } void Analyzer::checkFirmwareUpdate() { if (needCheckForUpdate()) { on_checkUpdatesBtn_clicked(); m_bManualUpdate = false; } } void Analyzer::on_checkUpdatesBtn_clicked() { m_bManualUpdate = true; if(m_downloader == nullptr) { m_downloader = new Downloader(); connect(m_downloader, SIGNAL(downloadInfoComplete()), this, SLOT(on_downloadInfoComplete())); connect(m_downloader, SIGNAL(downloadFileComplete()), this, SLOT(on_downloadFileComplete())); connect(m_downloader, SIGNAL(progress(qint64,qint64)), this, SLOT(on_progress(qint64,qint64))); } QString url = "https://www.rigexpert.com/getfirmware?model="; QString prototype = CustomAnalyzer::customized() ? CustomAnalyzer::currentPrototype() : names[m_analyzerModel]; //url += names[m_analyzerModel].toLower().remove(" ").remove("-"); url += prototype.toLower().remove(" ").remove("-"); url += "&sn="; if(m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { url += m_hidAnalyzer->getSerial(); url += "&revision="; url += m_hidAnalyzer->getRevision(); }else if (m_comAnalyzerFound && m_comAnalyzer != nullptr) { url += m_comAnalyzer->getSerial(); url += "&revision="; url += m_comAnalyzer->getRevision(); } if (m_mapFullInfo.contains("MAC")) { url += "&mac=" + m_mapFullInfo["MAC"]; } if (m_mapFullInfo.contains("SN")) { url += "&s_n=" + m_mapFullInfo["SN"]; } m_downloader->startDownloadInfo(QUrl(url)); } void Analyzer::on_progress(qint64 downloaded,qint64 total) { int percent = downloaded*100/total; if (percent == 100) { emit updatePercentChanged(0); m_updateDialog->setStatusText(tr("Updating, please wait...")); }else { emit updatePercentChanged(percent); } } bool Analyzer::openComPort(const QString& portName, quint32 portSpeed) { return (m_comAnalyzer == nullptr ? false : m_comAnalyzer->openComPort(portName, portSpeed)); } void Analyzer::closeComPort() { if(m_comAnalyzer != nullptr) { m_comAnalyzer->closeComPort(); } } void Analyzer::setAnalyzerModel (int model) { if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_analyzerModel = model; m_comAnalyzer->setAnalyzerModel(model); m_comAnalyzer->setIsMeasuring(true); } } void Analyzer::on_measureCalib(int dotsNumber) { m_isMeasuring = true; m_dotsNumber = dotsNumber; qint64 minFq_ = minFq[m_analyzerModel].toULongLong()*1000; qint64 maxFq_ = maxFq[m_analyzerModel].toULongLong()*1000; if (CustomAnalyzer::customized()) { CustomAnalyzer* ca = CustomAnalyzer::getCurrent(); if (ca != nullptr) { minFq_ = ca->minFq().toULongLong()*1000; maxFq_ = ca->maxFq().toULongLong()*1000; } } if(m_comAnalyzerFound && m_comAnalyzer != nullptr) { m_comAnalyzer->startMeasure(minFq_, maxFq_, dotsNumber); }else if (m_hidAnalyzerFound && m_hidAnalyzer != nullptr) { m_hidAnalyzer->startMeasure(minFq_, maxFq_, dotsNumber); } } void Analyzer::setCalibrationMode(bool enabled) { m_calibrationMode = enabled; } void Analyzer::on_changedAutoDetectMode(bool state) { if(state) { if(m_hidAnalyzer == nullptr) { m_hidAnalyzer = new hidAnalyzer(this); connect(m_hidAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData))); connect(m_hidAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData))); connect(m_hidAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList))); connect(m_hidAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_hidAnalyzerFound(quint32))); connect(m_hidAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_hidAnalyzerDisconnected())); connect(m_hidAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString))); connect(m_hidAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray))); connect(m_hidAnalyzer,SIGNAL(updatePercentChanged(int)),this,SLOT(on_updatePercentChanged(int))); connect(this, SIGNAL(screenshotComplete()),m_hidAnalyzer,SLOT(on_screenshotComplete())); connect(this, SIGNAL(measurementComplete()), m_hidAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection); connect(m_hidAnalyzer, &hidAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo); connect(m_hidAnalyzer, &hidAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError); } }else { if(m_hidAnalyzer != nullptr) { delete m_hidAnalyzer; m_hidAnalyzer = nullptr; } } if(m_comAnalyzer == nullptr) { m_comAnalyzer = new comAnalyzer(this); connect(m_comAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData))); connect(m_comAnalyzer,SIGNAL(newUserData(rawData,UserData)),this,SLOT(on_newUserData(rawData,UserData))); connect(m_comAnalyzer,SIGNAL(newUserDataHeader(QStringList)),this,SLOT(on_newUserDataHeader(QStringList))); connect(m_comAnalyzer,SIGNAL(analyzerFound(quint32)),this,SLOT(on_comAnalyzerFound(quint32))); connect(m_comAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_comAnalyzerDisconnected())); connect(m_comAnalyzer,SIGNAL(analyzerDataStringArrived(QString)),this,SLOT(on_analyzerDataStringArrived(QString))); connect(m_comAnalyzer,SIGNAL(analyzerScreenshotDataArrived(QByteArray)),this,SLOT(on_analyzerScreenshotDataArrived(QByteArray))); connect(m_comAnalyzer,SIGNAL(updatePercentChanged(int)),this,SLOT(on_updatePercentChanged(int))); connect(this, SIGNAL(screenshotComplete()),m_comAnalyzer,SLOT(on_screenshotComplete())); connect(this, SIGNAL(measurementComplete()), m_comAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection); connect(m_comAnalyzer, SIGNAL(aa30bootFound()), this, SIGNAL(aa30bootFound())); connect(m_comAnalyzer, SIGNAL(aa30updateComplete()), this, SIGNAL(aa30updateComplete())); connect(m_comAnalyzer, &comAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo); connect(m_comAnalyzer, &comAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError); QTimer::singleShot(1000, m_comAnalyzer, SLOT(searchAnalyzer())); } m_comAnalyzer->on_changedAutoDetectMode(state); } void Analyzer::on_changedSerialPort(QString portName) { if(m_comAnalyzer != nullptr) { m_comAnalyzer->on_changedSerialPort(portName); } } void Analyzer::setIsMeasuring (bool _isMeasuring) { m_isMeasuring = _isMeasuring; if(m_comAnalyzer != nullptr) { m_comAnalyzer->setIsMeasuring(_isMeasuring); } if(m_hidAnalyzer != nullptr) { m_hidAnalyzer->setIsMeasuring(_isMeasuring); } if(m_NanovnaAnalyzer != nullptr) { m_NanovnaAnalyzer->setIsMeasuring(_isMeasuring); } PopUpIndicator::setIndicatorVisible(m_isMeasuring); } void Analyzer::slotFullInfo(QString str) { QStringList list = str.split("\t"); if (list.size() < 2) return; m_mapFullInfo.insert(list[0], list[1]); } void Analyzer::searchAnalyzer() { if (!isMeasuring()) { if (m_hidAnalyzer != nullptr) m_hidAnalyzer->searchAnalyzer(true); if (m_comAnalyzer != nullptr) m_comAnalyzer->searchAnalyzer(); } } bool Analyzer::sendCommand(QString cmd) { bool ret = true; if (getHidAnalyzer() != 0) { getHidAnalyzer()->sendData(cmd); } else if (getComAnalyzer() != 0) { getComAnalyzer()->sendData(cmd); } else { ret = false; } return ret; } void Analyzer::setParseState(int _state) { if (getHidAnalyzer() != 0) { getHidAnalyzer()->setParseState(_state); } else if (getComAnalyzer() != 0) { getComAnalyzer()->setParseState(_state); } } int Analyzer::getParseState() { int ret = WAIT_NO; if (getHidAnalyzer() != 0) { getHidAnalyzer()->getParseState(); } else if (getComAnalyzer() != 0) { getComAnalyzer()->getParseState(); } return ret; } void Analyzer::on_getLicenses() { QString cmd = "LLIC\r\n"; setParseState(WAIT_LICENSE_LIST); sendCommand(cmd); } void Analyzer::on_generateLicence() { QString cmd = "GLIC\r\n"; setParseState(WAIT_LICENSE_REQUEST); sendCommand(cmd); } void Analyzer::on_applyLicense(QString& _license) { if (getHidAnalyzer() != 0) { getHidAnalyzer()->applyLicense(_license); } else if (getComAnalyzer() != 0) { getComAnalyzer()->applyLicense(_license); } } void Analyzer::on_disconnectNanoNVA() { if (m_NanovnaAnalyzer != nullptr) { m_NanovnaAnalyzer->closeComPort(); m_NanovnaAnalyzer->disconnect(); m_NanovnaAnalyzer->deleteLater(); m_NanovnaAnalyzer = nullptr; } } void Analyzer::on_connectNanoNVA() { // TODO disconnect all // ... // if (m_NanovnaAnalyzer == nullptr) { // delete m_NanovnaAnalyzer; // m_NanovnaAnalyzer = nullptr; // } if (NanovnaAnalyzer::portsCount() == 0) { return; } int portIndex = 0; if (NanovnaAnalyzer::portsCount() > 1) { // TODO select comport } QString portName = NanovnaAnalyzer::availablePorts().at(portIndex).portName(); m_NanovnaAnalyzer = new NanovnaAnalyzer(this); bool connected = m_NanovnaAnalyzer->openComPort(portName); if (connected) { connect(m_NanovnaAnalyzer,SIGNAL(analyzerFound(QString)),this,SLOT(on_nanovnaAnalyzerFound(QString))); connect(m_NanovnaAnalyzer,SIGNAL(analyzerDisconnected()),this,SLOT(on_nanovnaAnalyzerDisconnected())); connect(this, SIGNAL(measurementComplete()), m_NanovnaAnalyzer, SLOT(on_measurementComplete()));//, Qt::QueuedConnection); connect(m_NanovnaAnalyzer, &NanovnaAnalyzer::signalFullInfo, this, &Analyzer::slotFullInfo); connect(m_NanovnaAnalyzer, &NanovnaAnalyzer::signalMeasurementError, this, &Analyzer::signalMeasurementError); connect(m_NanovnaAnalyzer,SIGNAL(newData(rawData)),this,SLOT(on_newData(rawData))); connect(m_NanovnaAnalyzer, &NanovnaAnalyzer::completeMeasurement, this, [=](){ emit measurementCompleteNano(); }); m_NanovnaAnalyzer->checkAnalyzer(); } }
c991b139f24c51d4376a9b3c8716a98af550c5a4
a0dce37339bf2e60d7ddff5b1b9346e364a04bc8
/comdiv.cpp
2ba71102f1f7b4efb7e10dd5759219247482b9d7
[]
no_license
archiver/spoj
c0dfdc2bfea0c4d811ee0b95dce83c720bea3eae
ac78437594b4ff062db886d03db2a7192478b603
refs/heads/master
2020-05-18T00:58:53.697941
2013-01-18T22:00:38
2013-01-18T22:00:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,394
cpp
#include <stdio.h> #define T 1000002 #define P 168 int divisors[T]; int primes[] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997}; void solve() { int i,j; int var,prod,cnt,num; divisors[1]=1; for(i=2;i<T;++i) { var=0; prod=1; j=0; num=i; for(;j<P;++j) { cnt=1; while(!(num%primes[j])) { num=num/primes[j]; cnt+=1; } if(cnt>1) { prod*=cnt; prod*=divisors[num]; break; } } if(1==cnt) prod=2; divisors[i]=prod; } } int gcd(int a, int b) { if(b==0) return a; return gcd(b,a%b); } int main() { int t,a,b; int hcf; scanf("%d",&t); solve(); while(t--) { scanf("%d %d",&a,&b); hcf=a>b?gcd(a,b):gcd(b,a); printf("%d\n",divisors[hcf]); } return 0; }
[ "pavan@pavan.(none)" ]
pavan@pavan.(none)
0747ba462e4df4374889a7d871d4ec5ebd680bd4
13bed30fd2f729cbcafc319c62ab6b0a65ab8863
/georgelok-cs207-sbalanovichs-georgelok-cs207/mesh_mass_spring.cpp
933363a10980f0000ec851a3010d97973defd99d
[]
no_license
jonahkall/JBParallel
eac0cd9c96d3a1de0378e1ca6bcf60c6ba7e007f
256492adac0320be836916e2cd38887f13048e25
refs/heads/master
2016-09-05T18:18:40.119827
2014-12-16T03:44:24
2014-12-16T03:44:24
27,520,312
1
0
null
null
null
null
UTF-8
C++
false
false
17,608
cpp
/** * @file mesh_mass_spring.cpp * Implementation of mass-spring system using Mesh * * @brief Reads in two files specified on the command line. * First file: 3D Points (one per line) defined by three doubles * Second file: Tetrahedra (one per line) defined by 4 indices into the point * list */ #include <fstream> #include "CS207/SDLViewer.hpp" #include "CS207/Util.hpp" #include "CS207/Color.hpp" #include "Mesh.hpp" #include "Point.hpp" #include "../jb_parallel.hpp" #include <omp.h> // Gravity in meters/sec^2 static constexpr double grav = 9.81; static constexpr double K = 100.; static constexpr double C = 30.; /** Custom structure of data to store with Nodes */ struct NodeData { Point velocity; //< Node velocity double mass; //< Node mass }; typedef Mesh<NodeData, double, int> MeshType; typedef typename MeshType::node_type Node; typedef typename MeshType::edge_type Edge; typedef typename MeshType::triangle_type Triangle; template <typename F> struct vmod { F force; double dt; double t; void operator () (Node n) { // n.value().velocity += force(n, t) * (dt / n.value().mass); } vmod(F forcei, double dti, double ti) : force(forcei), dt(dti), t(ti) {}; }; template <typename F> struct pmod { double dt; void operator () (Node n) { n.position() += n.value().value_.velocity * dt; } pmod(double dti) : dt(dti) {}; }; // template<typename Tri> // struct msv_mod { // volume // void operator () (Tri t) { // double volume = 0.; // Point sn = t.surface_normal(); // int val = t.value(); // if ((sn.z < 0 && val > 0) || (sn.z > 0 && val < 0)) // sn *= -1; // // Increment the volume // volume += (sn.z * val * t.area()) * // ((t.node(0).position().z + // t.node(1).position().z + // t.node(2).position().z) / 3.); // } // }; /** Change a mesh's nodes according to a step of the symplectic Euler * method with the given node force. * @param[in,out] m Mesh * @param[in] t The current time (useful for time-dependent forces) * @param[in] dt The time step * @param[in] force Function object defining the force per node * @return the next time step (usually @a t + @a dt) * * @tparam G::node_value_type supports any struct with velocity and mass * @tparam F is a function object called as @a force(n, @a t), * where n is a node of the mesh and @a t is the current time. * @a force must return a Point representing the force vector on Node * at time @a t. */ template <typename M, typename F, typename C> double symp_euler_step(M& m, double t, double dt, F force, C constraints) { // Compute the {n+1} node positions /*for (auto it = m.node_begin(); it != m.node_end(); ++it) { auto n = *it; // Update the position of the node according to its velocity // x^{n+1} = x^{n} + v^{n} * dt n.position() += n.value().value_.velocity * dt; }*/ pmod<F> pm(dt); jb_parallel::for_each(m.node_begin(), m.node_end(), pm); // Enfore constraints after position update but before force calculation. constraints(m, t); // Compute the {n+1} node velocities for (auto it = m.node_begin(); it != m.node_end(); ++it) { auto n = *it; // v^{n+1} = v^{n} + F(x^{n+1},t) * dt / m n.value().value_.velocity += force(n, t) * (dt / n.value().value_.mass); } return t + dt; } /** Set the direction flags on each triangle in order to * keep track of the direction in which they are facing * @param[in] mesh, the current Mesh * * @pre: @a mesh is a valid mesh * @post: for i in range(mesh), i.value() = -1 if i faces away from center and 1 otherwise * * Complexity: O(n) */ template <typename M> void set_tri_directions(M& mesh) { // Set flags for surface normals // Approximate center of sphere Point sphere_center = Point(0,0,0); for (auto it = mesh.node_begin(); it != mesh.node_end(); ++it) { sphere_center += (*it).position(); } sphere_center /= mesh.num_nodes(); for(auto it = mesh.triangle_begin(); it != mesh.triangle_end(); ++it) { // Approximate center of triangle auto tri = (*it); Point tri_center = Point(0,0,0); for(unsigned i = 0; i < 3; ++i) { tri_center += tri.node(i).position(); } tri_center /= 3.0; // Determine direction of surface normal. Point d_vector = tri_center - sphere_center; if(d_vector.z * tri.surface_normal().z > 0) { tri.value() = 1; } else { tri.value() = -1; } } } /** A boolean functor that compares two nodes * based on their velocity values and returns true * if the first node's velocity is smaller than the * second one's */ struct VelComparator { template <typename Node> bool operator()(const Node& n1, const Node& n2) const { return (norm(n1.value().value_.velocity) < norm(n2.value().value_.velocity)); } }; /** A NodeColor functor that colors nodes based off * of node velocities */ struct VelHeatMap { public: template <typename Node> // Returns a heat value for a node based off velocity(n) CS207::Color operator()(const Node& n) const { return CS207::Color::make_heat( norm(n.value().value_.velocity)/max_vel_); } /* Constructor */ VelHeatMap(double max_vel) : max_vel_(max_vel) {} private: const double max_vel_; }; struct volume_inc { double operator () (Triangle t) { double volume = 0.; Point sn = t.surface_normal(); int val = t.value(); if ((sn.z < 0 && val > 0) || (sn.z > 0 && val < 0)) sn *= -1; // Increment the volume volume += (sn.z * val * t.area()) * ((t.node(0).position().z + t.node(1).position().z + t.node(2).position().z) / 3.); return volume; } }; /** Calculate the volume of the mesh shape * @param[in] m, the Mesh * * @return the volume of the mesh * * Complexity: O(n) */ template <typename M> double mesh_shape_volume(M* m) { double volume = 0.; volume_inc vi; jb_parallel::parallel_reduction(m->triangle_begin(), m->triangle_end(), vi, volume); return volume; } /** Air Pressure force functor for the mesh. * Return the force being applied to @a n at time @a t. */ struct AirPressureForce { // Constructor. Establishes the current sphere's volume AirPressureForce(double volume) : volume_(volume) {} // Return the air pressure force being applied to @a n at time @a t. Point operator()(Node n, double t) { (void) t; Point n_i = Point(0,0,0); for(unsigned i = 0; i < n.value().neighbor_triangles_.size(); ++i) { auto tri = n.value().neighbor_triangle(i); n_i += (C) * tri.area() * tri.value() * tri.surface_normal(); } return n_i; } private: double volume_; }; /** Gravity force functor for the mesh. * Return the force being applied to @a n at time @a t. */ struct GravityForce { Point operator()(Node n, double t) { (void) t; return Point(0,0, -grav * n.value().value_.mass); } }; /** Mass spring force functor for the mesh. * Return the force being applied to @a n at time @a t. */ struct MassSpringForce { Point operator()(Node n, double t) { (void) t; // initialize force Point force = Point(0,0,0); // calculate spring force for(auto it = n.edge_begin(); it != n.edge_end(); ++it) { MeshType::edge_type temp_edge = *it; MeshType::node_type temp_node = temp_edge.node2(); Point diff = n.position() - temp_node.position(); force += (-K) * (diff) / norm(diff) * (norm(diff) - temp_edge.value().value_); } return force; } }; /** Wind force functor for the mesh. * Return the force being applied to @a n at time @a t. */ struct WindForce { // Constructor. Establishes constants for interaction and air velocty WindForce(const double& c, const double& w) : c_(c), w_(w) {}; // Return the wind force being applied to @a n at time @a t. Point operator()(Node n, double t) { (void) t; // initialize, calculate, and normalize the n_i surface normal Point n_i = Point(0,0,0); for(unsigned i = 0; i < n.value().neighbor_triangles_.size(); ++i) { n_i += n.value().neighbor_triangle(i).surface_normal(); } // n_i = n_i /norm(n_i); // return the force based on the wind formula return c_ * ((w_ - n.value().value_.velocity) * n_i) * n_i; } private: double c_; double w_; }; /** Damping force functor for the mesh. * Return the force being applied to @a n at time @a t. */ struct DampingForce { double c_; // Constructor. Establishes constant for damping. DampingForce(const double& c) : c_(c) {}; // Return the damping force being applied to @a n at time @a t. Point operator()(Node n, double t) { (void) t; return -c_ * n.value().value_.velocity; } }; /** MetaForce construction as shown in class * Constructs a new force given two forces. * @param[in] force_1 First force * @param[in] force_2 Second force * * @return a function object such output() = force_1_() + force_2_() * * @tparam force_1, force_2 are function objects called as @a force_#(n, @a t), * where n is a node of the mesh and @a t is the current time. * @a force must return a Point representing the force vector on Node * at time @a t. */ template<typename F1, typename F2> struct MetaForce { Point operator()(Node n, double t) { return force_1_(n, t) + force_2_(n, t); } MetaForce(F1 force_1, F2 force_2) : force_1_(force_1), force_2_(force_2) { } private: F1 force_1_; F2 force_2_; }; /** Combines two forces to create a new force * * @pre Inputs can be called as @a fun(n, @a t), * where n is a node and t is time. * Returns a MetaForce */ template<typename F1, typename F2> MetaForce<F1, F2> make_combined_force(F1 force_1, F2 force_2) { return MetaForce<F1, F2>(force_1, force_2); } /** Combines three forces to create a new force * * @pre Inputs can be called as @a fun(n, @a t), * where n is a node and t is time. * Returns a MetaForce */ template<typename F1, typename F2, typename F3> MetaForce<F1, MetaForce<F2, F3>> make_combined_force(F1 force_1, F2 force_2, F3 force_3) { MetaForce<F2, F3> f2_f3_combo = MetaForce<F2, F3>(force_2, force_3); return MetaForce<F1, MetaForce<F2, F3>>(force_1, f2_f3_combo); } /** Checks nodes in the graph to see if they are at a certain point and fixes them * @post n.position() == n.position() is true for all nodes at (0,0,0) and (0,0,1) * O(n) time * */ template <typename G> struct FixedConstraint { void operator()(G& g, double t) { (void) t; for(auto it = g.node_begin(); it != g.node_end(); ++it) { if((*it).position() == Point(0,0,0) || (*it).position() == Point(1,0,0) ) { (*it).value().value_.velocity = Point(0,0,0); } } } }; /** Constrains points to be above z = -0.75 * O(N) Time */ template <typename M> struct PlaneConstraint { void operator()(M& m, double t) { (void) t; for(auto it = m.node_begin(); it != m.node_end(); ++it) { if (dot((*it).position(), Point(0,0,1)) < -2) { (*it).position().z = -2; (*it).value().value_.velocity.z = 0; } } } }; /** Constrains points to be outside sphere of radius r with center c * O(N) Time */ template <typename M> struct SphereConstraint { SphereConstraint(Point c, double r) : c_(c), r_(r) {} void operator()(M& m, double t) { (void) t; for(auto it = m.node_begin(); it != m.node_end(); ++it) { if ( norm((*it).position() - c_) < r_ ) { Point Ri = ((*it).position() - c_) / norm((*it).position() - c_); (*it).position() = Ri * 0.15 + c_; (*it).value().value_.velocity -= dot((*it).value().value_.velocity, Ri)*Ri; } } } private: Point c_; double r_; }; /** Constrains points to radius of r * O(N) Time */ template <typename M> struct BallConstraint { // Constructor. Establishes the ball radius constant BallConstraint(double r) : r_(r) {} void operator()(M& m, double t) { (void) t; Point sphere_center = Point(0,0,0); // Calculate center of sphere for(auto it = m.node_begin(); it != m.node_end(); ++it) { sphere_center += (*it).position(); } sphere_center /= m.num_nodes(); // Constrain nodes to a particular radius. for(auto it = m.node_begin(); it != m.node_end(); ++it) { Point vector = (*it).position() - sphere_center; if(norm(vector) > r_) { vector = vector / norm(vector) * r_; (*it).position() = vector + sphere_center; } } } private: double r_; }; /** MetaConstraint in the same vein as the MetaForce * Constructs a new constraint given two constraints. * @param[in] constraint_1 First constraint * @param[in] constraint_2 Second constraint * * @return a function object such output() = constraint_1_() + constraint_2_() * * @tparam constraint_1, constraint_2 are function objects called as @a pconstraint_#(g, @a t), * where g is a mesh and @a t is the current time. * no return value */ template<typename M, typename C1, typename C2> struct MetaConstraint { void operator()(M& m, double t) { constraint_1_(m, t); constraint_2_(m, t); } MetaConstraint(C1 constraint_1, C2 constraint_2) : constraint_1_(constraint_1), constraint_2_(constraint_2) { } C1 constraint_1_; C2 constraint_2_; }; /** Combines two constraints to create a new constraint * * @pre Inputs can be called as @a fun(g, @a t), * where g is a node and t is time. * Returns a MetaConstraint */ template<typename C1, typename C2, typename M = MeshType> MetaConstraint<M, C1, C2> make_combined_constraint(C1 constraint_1, C2 constraint_2) { return MetaConstraint<M, C1, C2>(constraint_1, constraint_2); } /** Combines three constraints to create a new constraint * * @pre Inputs can be called as @a fun(g, @a t), * where g is a node and t is time. * Returns a MetaConstraint */ template<typename C1, typename C2, typename C3, typename M = MeshType> MetaConstraint<M, C1, MetaConstraint<M, C2, C3>> make_combined_constraint(C1 constraint_1, C2 constraint_2, C3 constraint_3) { MetaConstraint<M, C2, C3> c2_c3_combo = MetaConstraint<M, C2, C3>(constraint_2, constraint_3); return MetaConstraint<M, C1, MetaConstraint<M, C2, C3>>(constraint_1, c2_c3_combo); } int main(int argc, char** argv) { // Check arguments if (argc < 3) { std::cerr << "Usage: " << argv[0] << " NODES_FILE TETS_FILE\n"; exit(1); } // Construct a mesh MeshType mesh; std::vector<typename MeshType::node_type> mesh_node; // Read all Points and add them to the Mesh std::ifstream nodes_file(argv[1]); Point p; while (CS207::getline_parsed(nodes_file, p)) { mesh_node.push_back(mesh.add_node(p)); } // Read all mesh triangles and add them to the Mesh std::ifstream tris_file(argv[2]); std::array<int,3> t; while (CS207::getline_parsed(tris_file, t)) { mesh.add_triangle(mesh_node[t[0]], mesh_node[t[1]], mesh_node[t[2]]); } // Zero intial velocities and have constant density. for(MeshType::node_iterator it = mesh.node_begin(); it != mesh.node_end(); ++it) { MeshType::node_type temp_node = *it; temp_node.value().value_.velocity = Point(0,0,0); temp_node.value().value_.mass = 1 / double(mesh.num_nodes()); } // Set initial lengths to initial distances. for(MeshType::edge_iterator it = mesh.edge_begin(); it != mesh.edge_end(); ++it) { MeshType::edge_type temp_edge = *it; temp_edge.value().value_ = temp_edge.length(); } // Print out the stats //std::cout << mesh.num_nodes() << " " << mesh.num_edges() << std::endl; // Launch the SDLViewer //CS207::SDLViewer viewer; //auto node_map = viewer.empty_node_map(mesh); //viewer.launch(); //viewer.add_nodes(mesh.node_begin(), mesh.node_end(), node_map); //viewer.add_edges(mesh.edge_begin(), mesh.edge_end(), node_map); //viewer.center_view(); set_tri_directions(mesh); //std::cout << "Starting\n"; // Begin the mass-spring simulation double dt = 0.0001; double t_start = 0.0; double t_end = 0.001; double max_vel = -UINT_MAX; {jb_parallel::Timer timer(""); for (double t = t_start; t < t_end; t += dt) { auto force = make_combined_force( make_combined_force(MassSpringForce(), GravityForce()), AirPressureForce(mesh_shape_volume(&mesh)), // WindForce(3., 0.7), DampingForce(1/(mesh.num_nodes() * 10)) ); auto constraints = make_combined_constraint( FixedConstraint<MeshType>(), BallConstraint<MeshType>(1.9), PlaneConstraint<MeshType>() ); symp_euler_step(mesh, t, dt, force, constraints); // Clear the viewer's nodes and edges. //viewer.clear(); //node_map.clear(); // Update the viewer with new node positions and color // auto max_node = *std::max_element(mesh.node_begin(), // mesh.node_end(), // VelComparator()); // max_vel = std::max(max_vel, norm(max_node.value().value_.velocity)); // Update viewer with nodes' new positions and new edges. //viewer.add_nodes(mesh.node_begin(), mesh.node_end(), VelHeatMap(max_vel), node_map); //viewer.add_edges(mesh.edge_begin(), mesh.edge_end(), node_map); //viewer.set_label(t); } } return 0; }
3561654a4a0bf7177c63030b327a9fcee7649a30
696e35ccdf167c3f6b1a7f5458406d3bb81987c9
/net/base/ip_address.cc
6d39175a05bee3e2c0c73ac5b9251a4b8ce10b34
[ "BSD-3-Clause" ]
permissive
mgh3326/iridium-browser
064e91a5e37f4e8501ea971483bd1c76297261c3
e7de6a434d2659f02e94917be364a904a442d2d0
refs/heads/master
2023-03-30T16:18:27.391772
2019-04-24T02:14:32
2019-04-24T02:14:32
183,128,065
0
0
BSD-3-Clause
2019-11-30T06:06:02
2019-04-24T02:04:51
null
UTF-8
C++
false
false
15,410
cc
// Copyright (c) 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/ip_address.h" #include <algorithm> #include <climits> #include "base/containers/stack_container.h" #include "base/stl_util.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/strings/stringprintf.h" #include "net/base/parse_number.h" #include "url/gurl.h" #include "url/url_canon_ip.h" namespace net { namespace { // The prefix for IPv6 mapped IPv4 addresses. // https://tools.ietf.org/html/rfc4291#section-2.5.5.2 constexpr uint8_t kIPv4MappedPrefix[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF}; // Note that this function assumes: // * |ip_address| is at least |prefix_length_in_bits| (bits) long; // * |ip_prefix| is at least |prefix_length_in_bits| (bits) long. bool IPAddressPrefixCheck(const IPAddressBytes& ip_address, const uint8_t* ip_prefix, size_t prefix_length_in_bits) { // Compare all the bytes that fall entirely within the prefix. size_t num_entire_bytes_in_prefix = prefix_length_in_bits / 8; for (size_t i = 0; i < num_entire_bytes_in_prefix; ++i) { if (ip_address[i] != ip_prefix[i]) return false; } // In case the prefix was not a multiple of 8, there will be 1 byte // which is only partially masked. size_t remaining_bits = prefix_length_in_bits % 8; if (remaining_bits != 0) { uint8_t mask = 0xFF << (8 - remaining_bits); size_t i = num_entire_bytes_in_prefix; if ((ip_address[i] & mask) != (ip_prefix[i] & mask)) return false; } return true; } // Returns false if |ip_address| matches any of the reserved IPv4 ranges. This // method operates on a blacklist of reserved IPv4 ranges. Some ranges are // consolidated. // Sources for info: // www.iana.org/assignments/ipv4-address-space/ipv4-address-space.xhtml // www.iana.org/assignments/iana-ipv4-special-registry/ // iana-ipv4-special-registry.xhtml bool IsPubliclyRoutableIPv4(const IPAddressBytes& ip_address) { // Different IP versions have different range reservations. DCHECK_EQ(IPAddress::kIPv4AddressSize, ip_address.size()); struct { const uint8_t address[4]; size_t prefix_length_in_bits; } static const kReservedIPv4Ranges[] = { {{0, 0, 0, 0}, 8}, {{10, 0, 0, 0}, 8}, {{100, 64, 0, 0}, 10}, {{127, 0, 0, 0}, 8}, {{169, 254, 0, 0}, 16}, {{172, 16, 0, 0}, 12}, {{192, 0, 2, 0}, 24}, {{192, 88, 99, 0}, 24}, {{192, 168, 0, 0}, 16}, {{198, 18, 0, 0}, 15}, {{198, 51, 100, 0}, 24}, {{203, 0, 113, 0}, 24}, {{224, 0, 0, 0}, 3}}; for (const auto& range : kReservedIPv4Ranges) { if (IPAddressPrefixCheck(ip_address, range.address, range.prefix_length_in_bits)) { return false; } } return true; } // Returns false if |ip_address| matches any of the IPv6 ranges IANA reserved // for local networks. This method operates on a whitelist of non-reserved // IPv6 ranges, plus the blacklist of reserved IPv4 ranges mapped to IPv6. // Sources for info: // www.iana.org/assignments/ipv6-address-space/ipv6-address-space.xhtml bool IsPubliclyRoutableIPv6(const IPAddressBytes& ip_address) { DCHECK_EQ(IPAddress::kIPv6AddressSize, ip_address.size()); struct { const uint8_t address_prefix[2]; size_t prefix_length_in_bits; } static const kPublicIPv6Ranges[] = {// 2000::/3 -- Global Unicast {{0x20, 0}, 3}, // ff00::/8 -- Multicast {{0xff, 0}, 8}}; for (const auto& range : kPublicIPv6Ranges) { if (IPAddressPrefixCheck(ip_address, range.address_prefix, range.prefix_length_in_bits)) { return true; } } IPAddress addr(ip_address); if (addr.IsIPv4MappedIPv6()) { IPAddress ipv4 = ConvertIPv4MappedIPv6ToIPv4(addr); return IsPubliclyRoutableIPv4(ipv4.bytes()); } return false; } bool ParseIPLiteralToBytes(const base::StringPiece& ip_literal, IPAddressBytes* bytes) { // |ip_literal| could be either an IPv4 or an IPv6 literal. If it contains // a colon however, it must be an IPv6 address. if (ip_literal.find(':') != base::StringPiece::npos) { // GURL expects IPv6 hostnames to be surrounded with brackets. std::string host_brackets = "["; ip_literal.AppendToString(&host_brackets); host_brackets.push_back(']'); url::Component host_comp(0, host_brackets.size()); // Try parsing the hostname as an IPv6 literal. bytes->Resize(16); // 128 bits. return url::IPv6AddressToNumber(host_brackets.data(), host_comp, bytes->data()); } // Otherwise the string is an IPv4 address. bytes->Resize(4); // 32 bits. url::Component host_comp(0, ip_literal.size()); int num_components; url::CanonHostInfo::Family family = url::IPv4AddressToNumber( ip_literal.data(), host_comp, bytes->data(), &num_components); return family == url::CanonHostInfo::IPV4; } } // namespace IPAddressBytes::IPAddressBytes() : size_(0) {} IPAddressBytes::IPAddressBytes(const uint8_t* data, size_t data_len) { Assign(data, data_len); } IPAddressBytes::~IPAddressBytes() = default; IPAddressBytes::IPAddressBytes(IPAddressBytes const& other) = default; void IPAddressBytes::Assign(const uint8_t* data, size_t data_len) { size_ = data_len; CHECK_GE(16u, data_len); std::copy_n(data, data_len, bytes_.data()); } bool IPAddressBytes::operator<(const IPAddressBytes& other) const { if (size_ == other.size_) return std::lexicographical_compare(begin(), end(), other.begin(), other.end()); return size_ < other.size_; } bool IPAddressBytes::operator==(const IPAddressBytes& other) const { return size_ == other.size_ && std::equal(begin(), end(), other.begin()); } bool IPAddressBytes::operator!=(const IPAddressBytes& other) const { return !(*this == other); } IPAddress::IPAddress() = default; IPAddress::IPAddress(const IPAddress& other) = default; IPAddress::IPAddress(const IPAddressBytes& address) : ip_address_(address) {} IPAddress::IPAddress(const uint8_t* address, size_t address_len) : ip_address_(address, address_len) {} IPAddress::IPAddress(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) { ip_address_.push_back(b0); ip_address_.push_back(b1); ip_address_.push_back(b2); ip_address_.push_back(b3); } IPAddress::IPAddress(uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3, uint8_t b4, uint8_t b5, uint8_t b6, uint8_t b7, uint8_t b8, uint8_t b9, uint8_t b10, uint8_t b11, uint8_t b12, uint8_t b13, uint8_t b14, uint8_t b15) { ip_address_.push_back(b0); ip_address_.push_back(b1); ip_address_.push_back(b2); ip_address_.push_back(b3); ip_address_.push_back(b4); ip_address_.push_back(b5); ip_address_.push_back(b6); ip_address_.push_back(b7); ip_address_.push_back(b8); ip_address_.push_back(b9); ip_address_.push_back(b10); ip_address_.push_back(b11); ip_address_.push_back(b12); ip_address_.push_back(b13); ip_address_.push_back(b14); ip_address_.push_back(b15); } IPAddress::~IPAddress() = default; bool IPAddress::IsIPv4() const { return ip_address_.size() == kIPv4AddressSize; } bool IPAddress::IsIPv6() const { return ip_address_.size() == kIPv6AddressSize; } bool IPAddress::IsValid() const { return IsIPv4() || IsIPv6(); } bool IPAddress::IsPubliclyRoutable() const { if (IsIPv4()) { return IsPubliclyRoutableIPv4(ip_address_); } else if (IsIPv6()) { return IsPubliclyRoutableIPv6(ip_address_); } return true; } bool IPAddress::IsZero() const { for (auto x : ip_address_) { if (x != 0) return false; } return !empty(); } bool IPAddress::IsIPv4MappedIPv6() const { return IsIPv6() && IPAddressStartsWith(*this, kIPv4MappedPrefix); } bool IPAddress::IsLoopback() const { // 127.0.0.1/8 if (IsIPv4()) return ip_address_[0] == 127; // ::1 if (IsIPv6()) { for (size_t i = 0; i + 1 < ip_address_.size(); ++i) { if (ip_address_[i] != 0) return false; } return ip_address_.back() == 1; } return false; } bool IPAddress::IsLinkLocal() const { // 169.254.0.0/16 if (IsIPv4()) return (ip_address_[0] == 169) && (ip_address_[1] == 254); // [fe80::]/10 if (IsIPv6()) return (ip_address_[0] == 0xFE) && ((ip_address_[1] & 0xC0) == 0x80); return false; } bool IPAddress::AssignFromIPLiteral(const base::StringPiece& ip_literal) { bool success = ParseIPLiteralToBytes(ip_literal, &ip_address_); if (!success) ip_address_.Resize(0); return success; } std::vector<uint8_t> IPAddress::CopyBytesToVector() const { return std::vector<uint8_t>(ip_address_.begin(), ip_address_.end()); } // static IPAddress IPAddress::IPv4Localhost() { static const uint8_t kLocalhostIPv4[] = {127, 0, 0, 1}; return IPAddress(kLocalhostIPv4); } // static IPAddress IPAddress::IPv6Localhost() { static const uint8_t kLocalhostIPv6[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; return IPAddress(kLocalhostIPv6); } // static IPAddress IPAddress::AllZeros(size_t num_zero_bytes) { CHECK_LE(num_zero_bytes, 16u); IPAddress result; for (size_t i = 0; i < num_zero_bytes; ++i) result.ip_address_.push_back(0u); return result; } // static IPAddress IPAddress::IPv4AllZeros() { return AllZeros(kIPv4AddressSize); } // static IPAddress IPAddress::IPv6AllZeros() { return AllZeros(kIPv6AddressSize); } bool IPAddress::operator==(const IPAddress& that) const { return ip_address_ == that.ip_address_; } bool IPAddress::operator!=(const IPAddress& that) const { return ip_address_ != that.ip_address_; } bool IPAddress::operator<(const IPAddress& that) const { // Sort IPv4 before IPv6. if (ip_address_.size() != that.ip_address_.size()) { return ip_address_.size() < that.ip_address_.size(); } return ip_address_ < that.ip_address_; } std::string IPAddress::ToString() const { std::string str; url::StdStringCanonOutput output(&str); if (IsIPv4()) { url::AppendIPv4Address(ip_address_.data(), &output); } else if (IsIPv6()) { url::AppendIPv6Address(ip_address_.data(), &output); } output.Complete(); return str; } std::string IPAddressToStringWithPort(const IPAddress& address, uint16_t port) { std::string address_str = address.ToString(); if (address_str.empty()) return address_str; if (address.IsIPv6()) { // Need to bracket IPv6 addresses since they contain colons. return base::StringPrintf("[%s]:%d", address_str.c_str(), port); } return base::StringPrintf("%s:%d", address_str.c_str(), port); } std::string IPAddressToPackedString(const IPAddress& address) { return std::string(reinterpret_cast<const char*>(address.bytes().data()), address.size()); } IPAddress ConvertIPv4ToIPv4MappedIPv6(const IPAddress& address) { DCHECK(address.IsIPv4()); // IPv4-mapped addresses are formed by: // <80 bits of zeros> + <16 bits of ones> + <32-bit IPv4 address>. base::StackVector<uint8_t, 16> bytes; bytes->insert(bytes->end(), std::begin(kIPv4MappedPrefix), std::end(kIPv4MappedPrefix)); bytes->insert(bytes->end(), address.bytes().begin(), address.bytes().end()); return IPAddress(bytes->data(), bytes->size()); } IPAddress ConvertIPv4MappedIPv6ToIPv4(const IPAddress& address) { DCHECK(address.IsIPv4MappedIPv6()); base::StackVector<uint8_t, 16> bytes; bytes->insert(bytes->end(), address.bytes().begin() + base::size(kIPv4MappedPrefix), address.bytes().end()); return IPAddress(bytes->data(), bytes->size()); } bool IPAddressMatchesPrefix(const IPAddress& ip_address, const IPAddress& ip_prefix, size_t prefix_length_in_bits) { // Both the input IP address and the prefix IP address should be either IPv4 // or IPv6. DCHECK(ip_address.IsValid()); DCHECK(ip_prefix.IsValid()); DCHECK_LE(prefix_length_in_bits, ip_prefix.size() * 8); // In case we have an IPv6 / IPv4 mismatch, convert the IPv4 addresses to // IPv6 addresses in order to do the comparison. if (ip_address.size() != ip_prefix.size()) { if (ip_address.IsIPv4()) { return IPAddressMatchesPrefix(ConvertIPv4ToIPv4MappedIPv6(ip_address), ip_prefix, prefix_length_in_bits); } return IPAddressMatchesPrefix(ip_address, ConvertIPv4ToIPv4MappedIPv6(ip_prefix), 96 + prefix_length_in_bits); } return IPAddressPrefixCheck(ip_address.bytes(), ip_prefix.bytes().data(), prefix_length_in_bits); } bool ParseCIDRBlock(const std::string& cidr_literal, IPAddress* ip_address, size_t* prefix_length_in_bits) { // We expect CIDR notation to match one of these two templates: // <IPv4-literal> "/" <number of bits> // <IPv6-literal> "/" <number of bits> std::vector<base::StringPiece> parts = base::SplitStringPiece( cidr_literal, "/", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); if (parts.size() != 2) return false; // Parse the IP address. if (!ip_address->AssignFromIPLiteral(parts[0])) return false; // Parse the prefix length. uint32_t number_of_bits; if (!ParseUint32(parts[1], &number_of_bits)) return false; // Make sure the prefix length is in a valid range. if (number_of_bits > ip_address->size() * 8) return false; *prefix_length_in_bits = number_of_bits; return true; } bool ParseURLHostnameToAddress(const base::StringPiece& hostname, IPAddress* ip_address) { if (hostname.size() >= 2 && hostname.front() == '[' && hostname.back() == ']') { // Strip the square brackets that surround IPv6 literals. auto ip_literal = base::StringPiece(hostname).substr(1, hostname.size() - 2); return ip_address->AssignFromIPLiteral(ip_literal) && ip_address->IsIPv6(); } return ip_address->AssignFromIPLiteral(hostname) && ip_address->IsIPv4(); } unsigned CommonPrefixLength(const IPAddress& a1, const IPAddress& a2) { DCHECK_EQ(a1.size(), a2.size()); for (size_t i = 0; i < a1.size(); ++i) { unsigned diff = a1.bytes()[i] ^ a2.bytes()[i]; if (!diff) continue; for (unsigned j = 0; j < CHAR_BIT; ++j) { if (diff & (1 << (CHAR_BIT - 1))) return i * CHAR_BIT + j; diff <<= 1; } NOTREACHED(); } return a1.size() * CHAR_BIT; } unsigned MaskPrefixLength(const IPAddress& mask) { base::StackVector<uint8_t, 16> all_ones; all_ones->resize(mask.size(), 0xFF); return CommonPrefixLength(mask, IPAddress(all_ones->data(), all_ones->size())); } } // namespace net
f1d77dd7c8099155ca159879fa476468809c5d57
5f130ab9cceca7da249b768d787c80a1fe118476
/include/httprequest.h
c13daea55e87b9a444af55724af1d265a842772a
[]
no_license
taryura/Requests
64d97be389a1809ca9ea990f563de86ca5f0ce2b
02af79db8eb5d09e70bda7db66266dd4a6d02016
refs/heads/master
2021-04-15T05:04:58.046431
2019-02-13T17:36:02
2019-02-13T17:36:02
126,525,000
0
0
null
null
null
null
UTF-8
C++
false
false
294
h
#ifndef HTTPREQUEST_H #define HTTPREQUEST_H #include "a_requests.h" class httprequest { public: void rqst_set (std::string addr, std::string prt, const std::string &req_text); std::string replyreceived; protected: private: }; #endif // HTTPREQUEST_H
724a8e8ae27052cb05a718fbc8cf8285808ba4cd
7843de0205e0276b6c7e552f8ef4c63ee9cbe28d
/Program1_BenDiegel_Less3.cpp
f6f588ffdaa6ba2680aa2450ee107d78ae222acc
[]
no_license
DiegelB/CPPHW
721615b23655a1c3558ee58e898b9a51ae107061
ec2416ce2f01335e79b39a19bd0746b81dc740f2
refs/heads/master
2021-01-20T10:04:30.963230
2017-10-30T02:47:23
2017-10-30T02:47:23
101,620,470
0
0
null
null
null
null
UTF-8
C++
false
false
1,093
cpp
/* Program: Points calculator Programmer: Ben Diegel Date: 9/2/17 */ #include <iostream> using namespace std; int main() { int numberOfBooks, earnedPoints; cout << "Please enter the amount of books you've read this month. Please enter a\n" << "negative value to exit the program\n>>"; cin >> numberOfBooks; while (numberOfBooks > 0) { if (numberOfBooks == 0) { earnedPoints = 0; } else if (numberOfBooks == 1) { earnedPoints = 5; } else if (numberOfBooks == 2) { earnedPoints = 15; } else if (numberOfBooks == 3) { earnedPoints = 30; } else if (numberOfBooks >= 4) { earnedPoints = 60; } cout << "You've read " << numberOfBooks << " books and have earned " << earnedPoints << " points.\n\n"; cout << "Please enter the amount of books you've read this month. Please enter a\n" << "negative value to exit the program\n>>"; cin >> numberOfBooks; } return 0; }
cff7d23724fc1a46fdc807ed9decb0a2302df391
7d6c1d7e135cdb5e42f0762907cdd1927abf435b
/on_line_planning/pt_paper/src/lm_plan_recognition.cxx
093dc81e5eb6c1ef4aa3863145c6a4829cf78ef7
[ "MIT" ]
permissive
miquelramirez/aamas18-planning-for-transparency
058285ca12c0f270efd213b36225f5fc8d530c7a
dff3e635102bf351906807c5181113fbf4b67083
refs/heads/master
2020-07-01T10:32:01.898653
2019-08-18T22:04:48
2019-08-18T22:04:48
201,146,315
0
0
null
null
null
null
UTF-8
C++
false
false
16,061
cxx
/* Purpose: POM17 plan recognizer */ #include <map> #include <set> #include <limits> #include <algorithm> #include <strips_prob.hxx> #include <fluent.hxx> #include <action.hxx> #include <cond_eff.hxx> #include <fwd_search_prob.hxx> #include <landmark_graph.hxx> #include <landmark_graph_manager.hxx> #include <landmark_graph_generator.hxx> #include "lm_plan_recognition.hxx" #include "utility.hxx" using aptk::agnostic::Fwd_Search_Problem; using Goal_set = std::vector<std::vector<unsigned int>>; using Goal = std::vector<unsigned int>; using aptk::agnostic::Landmarks_Graph_Generator; using aptk::agnostic::Landmarks_Graph; typedef Landmarks_Graph_Generator<Fwd_Search_Problem> Gen_Lms_Fwd; typedef Landmarks_Graph::Node Search_Node; namespace pr_lm{ PlanRecognitionEngine_LM::PlanRecognitionEngine_LM(aptk::STRIPS_Problem * s_prob, Goal_set goal_set, double theta, bool verbose, std::vector<double> priors) : m_strips_model(s_prob), m_goal_set(goal_set), m_theta(theta),m_verbose(verbose), m_goal_set_priors(priors) { generate_landmarks_graphs(); } PlanRecognitionEngine_LM::PlanRecognitionEngine_LM(aptk::STRIPS_Problem const * s_prob, Goal_set goal_set, double theta, bool verbose, std::vector<double> priors) : m_strips_model(NULL), m_goal_set(goal_set), m_theta(theta),m_verbose(verbose), m_goal_set_priors(priors) { aptk::STRIPS_Problem * n = new aptk::STRIPS_Problem(*s_prob); m_strips_model = n; generate_landmarks_graphs(); } void PlanRecognitionEngine_LM::generate_landmarks_graphs(){ Goal_set new_goal_set; for(unsigned i = 0; i < m_goal_set.size(); i++){ new_goal_set.push_back(m_goal_set[i]); for(unsigned j = 0; j < m_goal_set[i].size(); j++){ Goal g; g.push_back(m_goal_set[i][j]); new_goal_set.push_back(g); } } for(unsigned int i = 0; i < new_goal_set.size(); i++){ m_strips_model->set_goal(*m_strips_model, new_goal_set[i]); Fwd_Search_Problem search_prob (m_strips_model); Gen_Lms_Fwd gen_lms( search_prob ); Landmarks_Graph * graph = new Landmarks_Graph( *m_strips_model ); gen_lms.compute_lm_graph_set_additive( *graph ); bool verbose = false; if (verbose){ std::cout << "For Goal: "; for (auto f : new_goal_set[i]){ std::cout << m_strips_model->fluents()[f]->signature() << ","; } std::cout << std::endl; std::cout << "\tLandmarks found are: "; auto e = extract_fluents_from_graph(*graph); for(auto f : e){ std::cout << m_strips_model->fluents()[f]->signature() << ","; } std::cout << std::endl; } Landmarks_Graph_Manager * lm = new Landmarks_Graph_Manager(search_prob, graph); m_lgm_v[new_goal_set[i]] = lm; } } PlanRecognitionEngine_LM::~PlanRecognitionEngine_LM(){ //for(Goal g : m_goal_set){ //delete m_lgm_v[g]; //} } void PlanRecognitionEngine_LM::update_graph(std::vector<unsigned int> observations){ auto init = m_strips_model->init(); for( auto g : m_goal_set ){ auto i = m_lgm_v[g]; i->reset_graph(); i->apply_state(init); aptk::State * root = new aptk::State(*m_strips_model); root->set(init); for(unsigned j = 0; j < observations.size(); j++){ aptk::State* next_root_state = root->progress_through( *(m_strips_model->actions()[observations[j]]) ); i->apply_action( next_root_state, observations[j]); root = next_root_state; } } } std::vector<unsigned int> PlanRecognitionEngine_LM::extract_landmarks(aptk::STRIPS_Problem& s_prob, Goal& g, bool verbose){ s_prob.set_goal(s_prob, g); Fwd_Search_Problem search_prob (&s_prob); Gen_Lms_Fwd gen_lms( search_prob ); Landmarks_Graph graph( s_prob ); gen_lms.compute_lm_graph_set_additive( graph ); std::vector<unsigned int> land_marks_fluents = extract_fluents_from_graph(graph); if (verbose){ std::cout << "For Goal: "; for (auto f : g){ std::cout << s_prob.fluents()[f]->signature() << ","; } std::cout << std::endl; std::cout << "\tLandmarks found are: "; for(auto f : land_marks_fluents){ std::cout << s_prob.fluents()[f]->signature() << ","; } } return land_marks_fluents; } std::vector<unsigned int> PlanRecognitionEngine_LM::extract_fluents_from_graph(Landmarks_Graph& lm){ std::vector<unsigned int> land_marks; std::vector<aptk::agnostic::Landmarks_Graph::Node*> m_lm = lm.m_lm_graph; for ( unsigned k = 0; k < m_lm.size(); k++ ) { auto n = m_lm[k]; land_marks.push_back(n->fluent()); } return land_marks; } std::tuple<std::vector<unsigned int>,std::vector<unsigned int>, std::vector<unsigned int>> PlanRecognitionEngine_LM::partition_facts( aptk::STRIPS_Problem& s_prob, std::vector<unsigned int>& land_marks) { std::vector<unsigned int> f_strictly_activating; std::vector<unsigned int> f_strictly_terminal; std::vector<unsigned int> f_unstable_activating; auto init = s_prob.init(); for (unsigned int f : land_marks){ // Is f in the initial State bool f_init_state = false; if(std::find(init.begin(), init.end(), f) != init.end()) { f_init_state = true; } bool not_in_any_adds = true; bool not_in_any_dels = true; bool not_in_any_precs = true; bool exists_a_f_as_prec = false; bool exists_a_f_as_del = false; bool exists_a_f_as_add = false; for( auto a_p : s_prob.actions() ){ auto adds = a_p->add_vec(); auto dels = a_p->del_vec(); auto precs = a_p->prec_vec(); if(std::find(adds.begin(), adds.end(), f) != adds.end()) { not_in_any_adds = false; exists_a_f_as_add = true; } if(std::find(dels.begin(), dels.end(), f) != dels.end()) { not_in_any_dels = false; exists_a_f_as_del = true; } if(std::find(precs.begin(), precs.end(), f) != precs.end()) { not_in_any_precs = false; exists_a_f_as_prec = true; } } if (f_init_state && not_in_any_adds && not_in_any_dels && exists_a_f_as_prec) f_strictly_activating.push_back(f); if(f_init_state && not_in_any_adds && exists_a_f_as_prec && exists_a_f_as_del) f_unstable_activating.push_back(f); if(exists_a_f_as_add && not_in_any_precs && not_in_any_dels) f_strictly_terminal.push_back(f); } std::tuple<std::vector<unsigned int>,std::vector<unsigned int>, std::vector<unsigned int>> t( f_strictly_activating, f_unstable_activating, f_strictly_terminal ); return t; } double PlanRecognitionEngine_LM::percentage_complete_lm(Goal g, unsigned int f, std::vector<unsigned int> observations){ //auto lmg = m_lgm_v[g]; std::vector<unsigned int> f_s = {f}; std::vector<unsigned int> lms = extract_fluents_from_graph(*(m_lgm_v[f_s]->graph())); if(m_verbose){ std::cout << "\t" << print_fluent_vec(*m_strips_model, f_s) << ": " << print_fluent_vec(*m_strips_model, lms)<< std::endl; } if(lms.size() == 0){ return 0; } std::set<unsigned int> g_a_lm; double percentage_complete; for(auto o : observations){ auto a = m_strips_model->actions()[o]; auto adds = a->add_vec(); auto precs = a->prec_vec(); for ( auto l : lms ){ if ( std::find(adds.begin(), adds.end(),l) != adds.end() ){ g_a_lm.insert(l); continue; } if ( std::find(precs.begin(), precs.end(),l) != precs.end() ){ g_a_lm.insert(l); continue; } } } //std::vector<unsigned int> output(g_a_lm.begin(), g_a_lm.end()); //std::cout << print_fluent_vec(*m_strips_model, output) << std::endl; percentage_complete = (double) g_a_lm.size() / (double) lms.size(); return percentage_complete; } std::map<Goal, double> PlanRecognitionEngine_LM::goal_filtering( std::vector<unsigned int> observations){ std::map<Goal, double> map_goal_percent; double max = 0; //for( unsigned int k = 0 ; k < m_goal_set.size(); k++ ){ //Goal g = m_goal_set[k]; //std::vector<unsigned int> land_marks_g = extract_fluents_from_graph(*(m_lgm_v[g]->graph())); //std::tuple<std::vector<unsigned int>, //std::vector<unsigned int>, std::vector<unsigned int>> fact_partition; //fact_partition = partition_facts(*m_strips_model, land_marks_g); //auto f_strictly_activating = std::get<0>(fact_partition); //auto f_unstable_activating = std::get<1>(fact_partition); //auto f_strictly_terminal = std::get<2>(fact_partition); //if(m_verbose){ //std::cout << "Strictly Activating: " << f_strictly_activating.size() << std::endl; //std::cout << "Unstable Activating: " << f_unstable_activating.size() << std::endl; //std::cout << "Strictly Terminal: " << f_strictly_terminal.size() << std::endl; //} //std::vector<unsigned int> int_fsa_init; //auto init = m_strips_model->init(); //sort(f_strictly_activating.begin(), f_strictly_activating.end()); //sort(init.begin(), init.end()); //std::set_intersection(f_strictly_activating.begin(),f_strictly_activating.end(), //init.begin(),init.end(),back_inserter(int_fsa_init)); //TODO: CLARIFY THIS ////if (int_fsa_init.empty() && f_strictly_activating.size() != 0){ //std::cout << "\tLandmarks found are: "; //for(auto f : land_marks_fluents){ //std::cout << m_strips_model.fluents()[f]->signature() << ","; //} //map_goal_percent[g] = -1; //continue; //} //std::set<unsigned int> achieved_landmarks_g; //bool discardg = false; //for(unsigned int o : observations){ //auto a = m_strips_model->actions()[o]; //auto adds_v = a->add_vec(); //std::set<unsigned int> adds(adds_v.begin(), adds_v.end()); //auto prec_v = a->prec_vec(); //std::set<unsigned int> precs(prec_v.begin(), prec_v.end()); //auto del_v = a->del_vec(); //std::set<unsigned int> dels(del_v.begin(), del_v.end()); //std::set<unsigned int> prec_adds; //std::set<unsigned int> prec_adds_dels; //std::set_union(adds.begin(), adds.end(), //precs.begin(), precs.end(), //std::inserter(prec_adds, prec_adds.begin())); //std::set_union(prec_adds.begin(), prec_adds.end(), //dels.begin(), dels.end(), //std::inserter(prec_adds_dels, prec_adds_dels.begin())); //std::set<unsigned int> fua_fst; //std::set_union(f_unstable_activating.begin(), f_unstable_activating.end(), //f_strictly_terminal.begin(), f_strictly_terminal.end(), //std::inserter(fua_fst, fua_fst.begin())); //std::set<unsigned int> intersect; //std::set_intersection(fua_fst.begin(),fua_fst.end(),prec_adds_dels.begin(), //prec_adds_dels.end(), std::inserter(intersect, intersect.begin())); //if(intersect.empty() && fua_fst.size() != 0){ //discardg = true; //map_goal_percent[g] = -1; //break; //} //if(m_verbose){ //std::cout << "\t\t\tLandmarks in Observation " << a->signature() << ": "; //} //for ( auto l : land_marks_g ){ //if (prec_adds.count(l)) { //if(m_verbose){ //std::cout << m_strips_model->fluents()[l]->signature() << ","; //} //achieved_landmarks_g.insert(l); //} //} //if(m_verbose) //std::cout << std::endl; //} //if(discardg) //break; //auto g1 = g; //double percentage = (double) achieved_landmarks_g.size() / (double)land_marks_g.size(); //if(percentage > max){ //max = percentage; //} //map_goal_percent[g] = percentage; //if(m_verbose){ //std::cout << std::endl; //} //} //for(std::map<Goal,double>::iterator iter = map_goal_percent.begin(); //iter != map_goal_percent.end(); ++iter){ //if(iter->second < max - m_theta) //map_goal_percent[iter->first] = -1; //} return map_goal_percent; } std::map<Goal,double> PlanRecognitionEngine_LM::heuristic(std::vector<unsigned int> observations){ auto goal = m_strips_model->goal(); //auto A_g = goal_filtering(observations); std::map<Goal, double> heuristic; //for(std::map<Goal,double>::iterator iter = A_g.begin(); //iter != A_g.end(); ++iter){ //Goal G = iter->first; for(auto G : m_goal_set){ double sum = 0; //if(iter->second == -1){ //heuristic[G] = -1; //continue; //} if(m_verbose) std::cout << "Goal: " << print_fluent_vec(*m_strips_model, G) << std::endl; for(unsigned int g : G){ int a = percentage_complete_lm(G,g,observations); sum += a; } heuristic[G] = sum / (double) G.size(); //heuristic[G] = (double) iter->second / (double) G.size(); } m_strips_model->set_goal(*m_strips_model, goal); return heuristic; } std::vector<double> PlanRecognitionEngine_LM::plan_recognition( std::vector<unsigned int> observations){ auto h = heuristic(observations); std::vector<double> probs; for (auto G : m_goal_set){ if(h[G] == -1) probs.push_back(0); else probs.push_back(h[G]); } //float sum = 0; //for(auto i : probs){ //sum += i; //} //std::vector<double> priors; //if (sum != 0) //probs = normalize_vector(probs); //else //{ //for (unsigned int i = 0; i < m_goal_set.size(); i++){ //priors.push_back(0.5); //} //probs = normalize_vector(priors); //} probs = normalize_vector(probs); std::vector<double> pOGpG; for (unsigned int i = 0 ; i < probs.size() ; i++){ pOGpG.push_back(probs[i]*(m_goal_set_priors[i])); } return normalize_vector(pOGpG); } //OLD //std::vector<double> PlanRecognitionEngine_LM::plan_recognition( //std::vector<unsigned int> observations){ //std::map<Goal,std::vector<unsigned int>> land_marks_g; //for (Goal g : m_goal_set){ //land_marks_g[g] = extract_fluents_from_graph(*(m_lgm_v[g]->graph())); //} //auto init = m_strips_model->init(); //std::set<unsigned int> observation_landmarks; //for(auto o : observations){ //auto a = m_strips_model->actions()[o]; //auto adds = a->add_vec(); //auto precs = a->prec_vec(); //for (auto a : adds){ //if (std::find(init.begin(), init.end(),a) == init.end()) //observation_landmarks.insert(a); //} //for (auto a : precs){ //if (std::find(init.begin(), init.end(),a) == init.end()) //observation_landmarks.insert(a); //} //} //std::vector<unsigned int> obs_lms(observation_landmarks.begin(),observation_landmarks.end()); //std::vector<double> liklihoods; //for(Goal G : m_goal_set){ //double counter = 0; //for(Goal g : m_goal_set){ //auto int_l = instersection<unsigned int>(land_marks_g[G],land_marks_g[g]); //if(!int_l.empty()) //counter++; //} //auto obs_int = instersection<unsigned int>(land_marks_g[G], obs_lms); //double liklihood = ((double) obs_int.size()) / (counter); //liklihoods.push_back(liklihood); //} //auto normalize_liklihoods = normalize_vector(liklihoods); //print_vector(normalize_liklihoods); //std::vector<double> pOGpG; //for (unsigned int i = 0 ; i < normalize_liklihoods.size() ; i++){ //pOGpG.push_back(normalize_liklihoods[i]*(m_strips_model->m_priors[i])); //} //return normalize_vector(pOGpG); //} }
3fd1506b83aa157b78f07bff76b195861270aced
ebfd5f8e22c68d85511a771e6c65a9d496016a90
/dense.cpp
ce7597bdc96e415674159fccd05acbc4175b18cc
[]
no_license
zhoujian89/Leetcode
4d3926fd2e7a5b52569f60750a7cc1e073b90247
68e91ae797557c7d23b0532b0e7b3c4d654e8f82
refs/heads/master
2021-01-01T05:49:57.720815
2015-07-21T14:45:15
2015-07-21T14:45:15
35,457,770
1
0
null
null
null
null
GB18030
C++
false
false
10,330
cpp
#include "DenseTrackStab.h" #include "Initialize.h" #include "Descriptors.h" #include "OpticalFlow.h" #include <time.h> using namespace cv; int show_track = 0; // set show_track = 1, if you want to visualize the trajectories int main(int argc, char** argv) { //加载视频 VideoCapture capture; char* video = argv[1]; int flag = arg_parse(argc, argv); capture.open(video); if(!capture.isOpened()) { fprintf(stderr, "Could not initialize capturing..\n"); return -1; } //帧数 int frame_num = 0; TrackInfo trackInfo; DescInfo hogInfo, hofInfo, mbhInfo; //四种特征 /* 1.trajectory 2.HOG nxy_cell*nxy_cell*nt_cell 8个方向 path_size 32个像素 3.HOF nxy_cell*nxy_cell*nt_cell 9个方向 4.MBH nxy_cell*nxy_cell*nt_cell 8个方向 */ InitTrackInfo(&trackInfo, track_length, init_gap); InitDescInfo(&hogInfo, 8, false, patch_size, nxy_cell, nt_cell); InitDescInfo(&hofInfo, 9, true, patch_size, nxy_cell, nt_cell); InitDescInfo(&mbhInfo, 8, false, patch_size, nxy_cell, nt_cell); SeqInfo seqInfo; InitSeqInfo(&seqInfo, video); std::vector<Frame> bb_list; if(bb_file) { LoadBoundBox(bb_file, bb_list);//加载人检测的boundbox assert(bb_list.size() == seqInfo.length); } if(flag) seqInfo.length = end_frame - start_frame + 1; // fprintf(stderr, "video size, length: %d, width: %d, height: %d\n", seqInfo.length, seqInfo.width, seqInfo.height); if(show_track == 1) namedWindow("DenseTrackStab", 0); SurfFeatureDetector detector_surf(200); SurfDescriptorExtractor extractor_surf(true, true); std::vector<Point2f> prev_pts_flow, pts_flow; std::vector<Point2f> prev_pts_surf, pts_surf; std::vector<Point2f> prev_pts_all, pts_all; std::vector<KeyPoint> prev_kpts_surf, kpts_surf; Mat prev_desc_surf, desc_surf; Mat flow, human_mask; Mat image, prev_grey, grey; std::vector<float> fscales(0); std::vector<Size> sizes(0); std::vector<Mat> prev_grey_pyr(0), grey_pyr(0), flow_pyr(0), flow_warp_pyr(0); std::vector<Mat> prev_poly_pyr(0), poly_pyr(0), poly_warp_pyr(0); std::vector<std::list<Track> > xyScaleTracks; int init_counter = 0; // indicate when to detect new feature points while(true) { Mat frame; int i, j, c; // get a new frame 输入一帧 capture >> frame; if(frame.empty()) break; if(frame_num < start_frame || frame_num > end_frame) { frame_num++; //在start和end里面 continue; } if(frame_num == start_frame) { image.create(frame.size(), CV_8UC3); grey.create(frame.size(), CV_8UC1); prev_grey.create(frame.size(), CV_8UC1); InitPry(frame, fscales, sizes); BuildPry(sizes, CV_8UC1, prev_grey_pyr); BuildPry(sizes, CV_8UC1, grey_pyr); BuildPry(sizes, CV_32FC2, flow_pyr); BuildPry(sizes, CV_32FC2, flow_warp_pyr); BuildPry(sizes, CV_32FC(5), prev_poly_pyr); BuildPry(sizes, CV_32FC(5), poly_pyr); BuildPry(sizes, CV_32FC(5), poly_warp_pyr); xyScaleTracks.resize(scale_num);//尺度 frame.copyTo(image); cvtColor(image, prev_grey, CV_BGR2GRAY);//转为灰度 for(int iScale = 0; iScale < scale_num; iScale++) { if(iScale == 0) prev_grey.copyTo(prev_grey_pyr[0]); else//不同的尺度进行resize resize(prev_grey_pyr[iScale-1], prev_grey_pyr[iScale], prev_grey_pyr[iScale].size(), 0, 0, INTER_LINEAR); // dense sampling feature points min_distance=5 足够dense std::vector<Point2f> points(0); DenseSample(prev_grey_pyr[iScale], points, quality, min_distance);//每一个尺度,在每一帧,dense采点 // save the feature points //对每个尺度保存特征点 std::list<Track>& tracks = xyScaleTracks[iScale]; for(i = 0; i < points.size(); i++) tracks.push_back(Track(points[i], trackInfo, hogInfo, hofInfo, mbhInfo)); } // compute polynomial expansion my::FarnebackPolyExpPyr(prev_grey, prev_poly_pyr, fscales, 7, 1.5); human_mask = Mat::ones(frame.size(), CV_8UC1); if(bb_file) InitMaskWithBox(human_mask, bb_list[frame_num].BBs); detector_surf.detect(prev_grey, prev_kpts_surf, human_mask); extractor_surf.compute(prev_grey, prev_kpts_surf, prev_desc_surf); frame_num++; continue; } init_counter++; frame.copyTo(image); cvtColor(image, grey, CV_BGR2GRAY); // match surf features if(bb_file) InitMaskWithBox(human_mask, bb_list[frame_num].BBs); detector_surf.detect(grey, kpts_surf, human_mask); extractor_surf.compute(grey, kpts_surf, desc_surf); ComputeMatch(prev_kpts_surf, kpts_surf, prev_desc_surf, desc_surf, prev_pts_surf, pts_surf); // compute optical flow for all scales once my::FarnebackPolyExpPyr(grey, poly_pyr, fscales, 7, 1.5); my::calcOpticalFlowFarneback(prev_poly_pyr, poly_pyr, flow_pyr, 10, 2); MatchFromFlow(prev_grey, flow_pyr[0], prev_pts_flow, pts_flow, human_mask); MergeMatch(prev_pts_flow, pts_flow, prev_pts_surf, pts_surf, prev_pts_all, pts_all); Mat H = Mat::eye(3, 3, CV_64FC1); if(pts_all.size() > 50) { std::vector<unsigned char> match_mask; Mat temp = findHomography(prev_pts_all, pts_all, RANSAC, 1, match_mask); if(countNonZero(Mat(match_mask)) > 25) H = temp; } Mat H_inv = H.inv(); Mat grey_warp = Mat::zeros(grey.size(), CV_8UC1); MyWarpPerspective(prev_grey, grey, grey_warp, H_inv); // warp the second frame // compute optical flow for all scales once my::FarnebackPolyExpPyr(grey_warp, poly_warp_pyr, fscales, 7, 1.5); my::calcOpticalFlowFarneback(prev_poly_pyr, poly_warp_pyr, flow_warp_pyr, 10, 2); for(int iScale = 0; iScale < scale_num; iScale++) { if(iScale == 0) grey.copyTo(grey_pyr[0]); else resize(grey_pyr[iScale-1], grey_pyr[iScale], grey_pyr[iScale].size(), 0, 0, INTER_LINEAR); int width = grey_pyr[iScale].cols; int height = grey_pyr[iScale].rows; // compute the integral histograms DescMat* hogMat = InitDescMat(height+1, width+1, hogInfo.nBins); HogComp(prev_grey_pyr[iScale], hogMat->desc, hogInfo); DescMat* hofMat = InitDescMat(height+1, width+1, hofInfo.nBins); HofComp(flow_warp_pyr[iScale], hofMat->desc, hofInfo); DescMat* mbhMatX = InitDescMat(height+1, width+1, mbhInfo.nBins); DescMat* mbhMatY = InitDescMat(height+1, width+1, mbhInfo.nBins); MbhComp(flow_warp_pyr[iScale], mbhMatX->desc, mbhMatY->desc, mbhInfo); // track feature points in each scale separately 在每一个尺度分开跟踪特征点 std::list<Track>& tracks = xyScaleTracks[iScale]; for (std::list<Track>::iterator iTrack = tracks.begin(); iTrack != tracks.end();) { int index = iTrack->index; Point2f prev_point = iTrack->point[index]; int x = std::min<int>(std::max<int>(cvRound(prev_point.x), 0), width-1); int y = std::min<int>(std::max<int>(cvRound(prev_point.y), 0), height-1); Point2f point; point.x = prev_point.x + flow_pyr[iScale].ptr<float>(y)[2*x]; point.y = prev_point.y + flow_pyr[iScale].ptr<float>(y)[2*x+1]; if(point.x <= 0 || point.x >= width || point.y <= 0 || point.y >= height) { iTrack = tracks.erase(iTrack); continue; } iTrack->disp[index].x = flow_warp_pyr[iScale].ptr<float>(y)[2*x]; iTrack->disp[index].y = flow_warp_pyr[iScale].ptr<float>(y)[2*x+1]; // get the descriptors for the feature point RectInfo rect; GetRect(prev_point, rect, width, height, hogInfo); GetDesc(hogMat, rect, hogInfo, iTrack->hog, index); GetDesc(hofMat, rect, hofInfo, iTrack->hof, index); GetDesc(mbhMatX, rect, mbhInfo, iTrack->mbhX, index); GetDesc(mbhMatY, rect, mbhInfo, iTrack->mbhY, index); iTrack->addPoint(point); // draw the trajectories at the first scale if(show_track == 1 && iScale == 0) DrawTrack(iTrack->point, iTrack->index, fscales[iScale], image); // if the trajectory achieves the maximal length if(iTrack->index >= trackInfo.length) { std::vector<Point2f> trajectory(trackInfo.length+1); for(int i = 0; i <= trackInfo.length; ++i) trajectory[i] = iTrack->point[i]*fscales[iScale]; std::vector<Point2f> displacement(trackInfo.length); for (int i = 0; i < trackInfo.length; ++i) displacement[i] = iTrack->disp[i]*fscales[iScale]; float mean_x(0), mean_y(0), var_x(0), var_y(0), length(0); if(IsValid(trajectory, mean_x, mean_y, var_x, var_y, length) && IsCameraMotion(displacement)) { // output the trajectory printf("%d\t%f\t%f\t%f\t%f\t%f\t%f\t", frame_num, mean_x, mean_y, var_x, var_y, length, fscales[iScale]); // for spatio-temporal pyramid printf("%f\t", std::min<float>(std::max<float>(mean_x/float(seqInfo.width), 0), 0.999)); printf("%f\t", std::min<float>(std::max<float>(mean_y/float(seqInfo.height), 0), 0.999)); printf("%f\t", std::min<float>(std::max<float>((frame_num - trackInfo.length/2.0 - start_frame)/float(seqInfo.length), 0), 0.999)); // output the trajectory for (int i = 0; i < trackInfo.length; ++i) printf("%f\t%f\t", displacement[i].x, displacement[i].y); PrintDesc(iTrack->hog, hogInfo, trackInfo); PrintDesc(iTrack->hof, hofInfo, trackInfo); PrintDesc(iTrack->mbhX, mbhInfo, trackInfo); PrintDesc(iTrack->mbhY, mbhInfo, trackInfo); printf("\n"); } iTrack = tracks.erase(iTrack); continue; } ++iTrack; } ReleDescMat(hogMat); ReleDescMat(hofMat); ReleDescMat(mbhMatX); ReleDescMat(mbhMatY); if(init_counter != trackInfo.gap) continue; // detect new feature points every gap frames std::vector<Point2f> points(0); for(std::list<Track>::iterator iTrack = tracks.begin(); iTrack != tracks.end(); iTrack++) points.push_back(iTrack->point[iTrack->index]); DenseSample(grey_pyr[iScale], points, quality, min_distance); // save the new feature points for(i = 0; i < points.size(); i++) tracks.push_back(Track(points[i], trackInfo, hogInfo, hofInfo, mbhInfo)); } init_counter = 0; grey.copyTo(prev_grey); for(i = 0; i < scale_num; i++) { grey_pyr[i].copyTo(prev_grey_pyr[i]); poly_pyr[i].copyTo(prev_poly_pyr[i]); } prev_kpts_surf = kpts_surf; desc_surf.copyTo(prev_desc_surf); frame_num++; if( show_track == 1 ) { imshow( "DenseTrackStab", image); c = cvWaitKey(3); if((char)c == 27) break; } } if( show_track == 1 ) destroyWindow("DenseTrackStab"); return 0; }
614092c26bd523eed51b31f45bdb1a6200de12ce
17a3219394eae342439be25d11c543944d6c7351
/common/trace_dump.hpp
4ffe65ac09b460f3fcdbb5da8e67b277f2913de9
[ "MIT" ]
permissive
rawoul/apitrace
1526bb0414d5499f2992d59a3e32aa3b9203230a
e9fcdcf14a99f5cb4729abb7bbf7817d7aa59d18
refs/heads/master
2020-04-08T02:53:03.770028
2011-12-14T23:18:49
2011-12-14T23:20:00
3,009,443
1
0
null
null
null
null
UTF-8
C++
false
false
2,015
hpp
/************************************************************************** * * Copyright 2010 VMware, Inc. * All Rights Reserved. * * 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. * **************************************************************************/ /* * Human-readible dumping. */ #ifndef _TRACE_DUMP_HPP_ #define _TRACE_DUMP_HPP_ #include <iostream> #include "trace_model.hpp" namespace trace { typedef unsigned DumpFlags; enum { DUMP_FLAG_NO_COLOR = (1 << 0), DUMP_FLAG_NO_ARG_NAMES = (1 << 1), }; void dump(Value *value, std::ostream &os, DumpFlags flags = 0); inline std::ostream & operator <<(std::ostream &os, Value *value) { if (value) { dump(value, os); } return os; } void dump(Call &call, std::ostream &os, DumpFlags flags = 0); inline std::ostream & operator <<(std::ostream &os, Call &call) { dump(call, os); return os; } } /* namespace trace */ #endif /* _TRACE_DUMP_HPP_ */
027e77dc08a5900136aae507901186a762678c6d
5c34abe10630b23da8ba7d1cbce38bda53a4b6fa
/RootAnalysis/src/LeaningTower/Residual.h
71ce6bbd478b017c865d09df2534b5f52ddf97a6
[]
no_license
fermi-lat/GlastRelease-scons-old
cde76202f706b1c8edbf47b52ff46fe6204ee608
95f1daa22299272314025a350f0c6ef66eceda08
refs/heads/master
2021-07-23T02:41:48.198247
2017-05-09T17:27:58
2017-05-09T17:27:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,026
h
#include "TCut.h" #include "TF1.h" #include "TFile.h" #include "TGraph.h" #include "TLine.h" #include "TList.h" #include "TPaveStats.h" #include "TString.h" #include "TStyle.h" #include "TSystem.h" #include "TTree.h" #include "Tracker.h" #include "Layer.h" #include "Event.h" #include "Recon.h" #include "Progress.h" const float damp = 0.63f; class Residual { private: Event* myEvent; Tracker* myTracker; TString myResFileName; int m_temid; public: Residual(const TString="MyRootFile.root", const TString="residual.root", const TString geo="", int temid=0); virtual ~Residual() { delete myEvent; delete myTracker; } void Go(int numEntries=-1, int firstEntry=0); // general for DrawXxx: residual is defined as h_abs_ext-h_abs // *********** // draws the residual, top without fitting, bottom with gauss fit void DrawResidual(TString plane, TCut=""); // draws top the residual vs. inv. slope, bottom the profile with pol1 fit void DrawResSlope(TString plane, TCut=""); // draws top the residual vs. other coordinate, bottom profile with pol1 fit void DrawResOrd(TString plane, TCut=""); // draws top the residual vs. position, bottom profile with pol1 fit void DrawResPos(TString plane, TCut=""); // draws the slope profiles for all planes void DrawResSlopeAll(TCut="abs(h_abs_ext-h_abs)<1"); // draws the ordinate profiles for all planes void DrawResOrdAll(TCut="abs(h_abs_ext-h_abs)<1"); // draws the position profiles for all planes void DrawResPosAll(TCut="abs(h_abs_ext-h_abs)<1"); // attempt to do a "statistical" (not event be event) correction of rotZ of // planes. 2x3 histograms. Left uncorrected, right rotZ corrected. Top // ordinate vs. residual, middle profile of that, bottom residual. void DrawResOrdCorr(TString plane, TCut=""); // saves the geometry into geoFileName void Residual::SaveGeometry(TString geoFileName=""); ClassDef(Residual,1) };
[ "" ]
abd3f64320ad8eed19c5b876c26ddeb7f973dfe2
5c4d57961bdd2afdc3bc6958aeb89d0e5fc99ef4
/lexical_analyzer/Token.h
ff5d2ebb098b5c7d857c3c744d42b81a6665db95
[]
no_license
beaubadilla/cpsc323_compilers
2174283ee21f78f2108c8bf7ceb1c9ee8b6a298c
89f3395ca2899509436ab4fe2b98bcd438fe38ae
refs/heads/master
2022-07-31T13:30:31.629647
2020-05-16T08:00:21
2020-05-16T08:00:21
264,386,835
0
0
null
null
null
null
UTF-8
C++
false
false
460
h
#pragma once #include <string> #include <iostream> enum TokenType { keyword, identifier, real, relop, arithop, separator, error }; class Token { private: TokenType type; std::string lexeme; public: Token(); Token(TokenType tT, std::string s) { this->type = tT; this->lexeme = s; } ~Token(); void print() { std::cout << this->type << "\t" << this->lexeme << std::endl; } std::string getTokenType(); std::string getLexeme() { return this->lexeme; } };
eb6d5ae824aa2a73bbe6d3351012da3fdc358cb4
c00a2490947ad10582b5d675f070ccb62b70901d
/chromium/media/renderers/default_renderer_factory.h
63828af52e0f6f149855a71af234f712957dd18b
[ "BSD-3-Clause" ]
permissive
teotikalki/vivaldi-source
543d0ab336fb5784eaae1904457598f95f426186
22a46f2c969f6a0b7ca239a05575d1ea2738768c
refs/heads/master
2021-01-23T01:17:34.305328
2016-04-29T20:28:18
2016-04-29T20:28:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,663
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 MEDIA_RENDERERS_DEFAULT_RENDERER_FACTORY_H_ #define MEDIA_RENDERERS_DEFAULT_RENDERER_FACTORY_H_ #include "base/callback.h" #include "base/macros.h" #include "media/base/media_export.h" #include "media/base/renderer_factory.h" namespace media { class AudioHardwareConfig; class AudioRendererSink; class GpuVideoAcceleratorFactories; class MediaLog; class VideoRendererSink; // The default factory class for creating RendererImpl. class MEDIA_EXPORT DefaultRendererFactory : public RendererFactory { public: DefaultRendererFactory(const scoped_refptr<MediaLog>& media_log, GpuVideoAcceleratorFactories* gpu_factories, const AudioHardwareConfig& audio_hardware_config); ~DefaultRendererFactory() final; scoped_ptr<Renderer> CreateRenderer( const scoped_refptr<base::SingleThreadTaskRunner>& media_task_runner, const scoped_refptr<base::TaskRunner>& worker_task_runner, AudioRendererSink* audio_renderer_sink, VideoRendererSink* video_renderer_sink, bool use_platform_media_pipeline, bool platform_pipeline_enlarges_buffers_on_underflow) final; private: scoped_refptr<MediaLog> media_log_; // Factories for supporting video accelerators. May be null. GpuVideoAcceleratorFactories* gpu_factories_; const AudioHardwareConfig& audio_hardware_config_; DISALLOW_COPY_AND_ASSIGN(DefaultRendererFactory); }; } // namespace media #endif // MEDIA_RENDERERS_DEFAULT_RENDERER_FACTORY_H_
a8ed1387e8a143a87b47156cae493118a10e00da
c0e0138bff95c2eac038349772e36754887a10ae
/mdk_release_18.08.10_general_purpose/mdk/common/components/imageWarpDyn/compShvDynApps/imageWarpDynlib/Entry.cpp
07c26e08a49b370ed278dbfb6038da9bef214b80
[]
no_license
elfmedy/vvdn_tofa
f24d2e1adc617db5f2b1aef85f478998aa1840c9
ce514e0506738a50c0e3f098d8363f206503a311
refs/heads/master
2020-04-13T17:52:19.490921
2018-09-25T12:01:21
2018-09-25T12:01:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,912
cpp
/// /// @file /// @copyright All code copyright Movidius Ltd 2012, all rights reserved. /// For License Warranty see: common/license.txt /// /// @brief Image warp component /// // 1: Includes // ---------------------------------------------------------------------------- #include <math.h> #include <stdio.h> #include <string.h> #include <assert.h> #include <svuCommonShave.h> #include "warpMeshExpand.h" #include "warpMeshSample8bit.h" #include "imageWarpDefines.h" #include "imageWarp.h" #ifdef USE_CMX_DMA_NEW_DRIVER #include <scCmxDma.h> #else #include "swcCdma.h" #endif #include "swcFrameTypes.h" #include "moviVectorUtils.h" // 2: Source Specific #defines and types (typedef,enum,struct) // ---------------------------------------------------------------------------- #define NO_DDR_OUTPUT ((u32)0xFFFFFFFF) //#define USE_DMA typedef struct meshPortion { tileList* head; }meshPortion; // 3: Global Data (Only if absolutely necessary) // ---------------------------------------------------------------------------- // Sections decoration is required here for downstream tool // 4: Static Local Data // ---------------------------------------------------------------------------- // Buffers __attribute__((aligned(16))) unsigned char inputBufferMem[CMX_BUFFER_SIZE]; __attribute__((aligned(16))) unsigned char outBufferMem[2][OUT_TILE_SIZE]; #ifdef USE_CMX_DMA_NEW_DRIVER ScCmxDmaTransaction list[2]; ScCmxDmaTransactionHnd ref[2]; #else dmaTransactionList_t list[2]; dmaTransactionList_t *ref[2]; #endif meshPortion meshLUT[MESH_LUT_LENGTH + 1]; u32 tileLutElemCount; reTileEntry tiles[2]; reTileEntry referenceTile; __attribute__((aligned(16))) half mx[OUT_TILE_WIDTH * OUT_TILE_WIDTH + 8]; __attribute__((aligned(16))) half my[OUT_TILE_WIDTH * OUT_TILE_WIDTH + 8]; // 5: Static Function Prototypes // ---------------------------------------------------------------------------- // 6: Functions Implementation // ---------------------------------------------------------------------------- static inline float min4Elem(float4 vec) { float xmin; xmin = __builtin_shave_cmu_min_f32_rr_float(vec[0], vec[1]); xmin = __builtin_shave_cmu_min_f32_rr_float(xmin, vec[2]); return __builtin_shave_cmu_min_f32_rr_float(xmin, vec[3]); } static inline float max4Elem(float4 vec) { float xmax; xmax = __builtin_shave_cmu_max_f32_rr_float(vec[0], vec[1]); xmax = __builtin_shave_cmu_max_f32_rr_float(xmax, vec[2]); return __builtin_shave_cmu_max_f32_rr_float(xmax, vec[3]); } static void initTileBuffers(reTileEntry* currTile, u8* buffer, u32 lineLength) { u32 ix; for(ix = 0; ix < VERTICAL_PAD; ix++) { currTile->cmxInBuffP[ix] = (u8*)buffer + CMX_BUFFER_LINES * lineLength + HORIZONTAL_PAD; currTile->cmxInBuffP[ix + CMX_BUFFER_LINES + VERTICAL_PAD] = (u8*)buffer + CMX_BUFFER_LINES * lineLength + HORIZONTAL_PAD; } for(ix = 0; ix < CMX_BUFFER_LINES; ix++) { currTile->cmxInBuffP[ix + VERTICAL_PAD] = (u8*)buffer + ix * lineLength + HORIZONTAL_PAD; } currTile->swapP = (u8*)buffer + (CMX_BUFFER_LINES + 1) * lineLength + HORIZONTAL_PAD; } static inline void rotateBufferPointers(reTileEntry* currTile) { // TODO: optimize u32 i; u8* swapP = currTile->cmxInBuffP[VERTICAL_PAD]; for(i = 0; i < CMX_BUFFER_LINES - 1 ; i++) { currTile->cmxInBuffP[i + VERTICAL_PAD] = currTile->cmxInBuffP[i + VERTICAL_PAD + 1]; } currTile->cmxInBuffP[CMX_BUFFER_LINES + VERTICAL_PAD - 1] = currTile->swapP; currTile->swapP = swapP; } static inline void adjustBufferPointers(reTileEntry* currTile, reTileEntry* refTile, int amount) { // TODO: optimize u32 i; uint4* lineP = (uint4*)&currTile->cmxInBuffP[VERTICAL_PAD]; uint4* lineP2 = (uint4*)&refTile->cmxInBuffP[VERTICAL_PAD]; for(i = 0; i < CMX_BUFFER_LINES >> 2 ; i++) { lineP[i] = lineP2[i] + (uint4)amount; } currTile->cmxInBuffP[CMX_BUFFER_LINES + VERTICAL_PAD - 1] = refTile->cmxInBuffP[CMX_BUFFER_LINES + VERTICAL_PAD - 1] + amount; } static inline void prepareMesh(meshStruct* mesh, frameSpec* frSpec, tileList* tileNodes) { unsigned int i, j, k; unsigned int meshH = mesh->meshHeight; unsigned int meshW = mesh->meshWidth; float *my = mesh->meshY; for (j = 0; j < frSpec->height; j++ ) { meshLUT[j].head = NULL; } meshLUT[MESH_LUT_LENGTH].head = NULL; tileLutElemCount = 0; for (i = 0; i < (meshH - 1); i++ ) { // Process all cells horizontally. We are doing vectorized processing here, we process 3 elements in an iteration // We use elements j, j+1, j+2, j+3 for (j = 0; j < meshW - 3; j += 3 ) { u32 ind = i * meshW + j; float4* first = (float4*)&my[ind]; float4* second = (float4*)&my[ind + meshW]; float4 min = __builtin_shave_cmu_min_f32_rr_float4(first[0], second[0]); float4 max = __builtin_shave_cmu_max_f32_rr_float4(first[0], second[0]); float4 min2 = __builtin_shave_cmu_alignvec_rri_float4(min, min, 4); float4 max2 = __builtin_shave_cmu_alignvec_rri_float4(max, max, 4); min = __builtin_shave_cmu_min_f32_rr_float4(min, min2); max = __builtin_shave_cmu_max_f32_rr_float4(max, max2); int4 minInt = mvuConvert_int4(min); int4 maxInt = mvuConvert_int4(max); int4 diff = maxInt - minInt; for(k = 0; k < 3; k++) { if ((diff[k] <= CMX_BUFFER_LINES) && (minInt[k] < (int)frSpec->height) && (maxInt[k] >= 0) && (minInt[k] > - VERTICAL_PAD)) { if (minInt[k] > 0) { tileNodes[tileLutElemCount].next = meshLUT[minInt[k]].head; tileNodes[tileLutElemCount].x = j + k; tileNodes[tileLutElemCount].y = i; meshLUT[minInt[k]].head = &tileNodes[tileLutElemCount++]; } else { tileNodes[tileLutElemCount].next = meshLUT[0].head; tileNodes[tileLutElemCount].x = j + k; tileNodes[tileLutElemCount].y = i; meshLUT[0].head = &tileNodes[tileLutElemCount++]; } } else { tileNodes[tileLutElemCount].next = meshLUT[MESH_LUT_LENGTH].head; tileNodes[tileLutElemCount].x = j + k; tileNodes[tileLutElemCount].y = i; meshLUT[MESH_LUT_LENGTH].head = &tileNodes[tileLutElemCount++]; } } } // In case the mesh width was not multiple of 3, we need to process the last elements u32 ind = i * meshW + j; float4* first = (float4*)&my[ind]; float4* second = (float4*)&my[ind + meshW]; float4 min = __builtin_shave_cmu_min_f32_rr_float4(first[0], second[0]); float4 max = __builtin_shave_cmu_max_f32_rr_float4(first[0], second[0]); float4 min2 = __builtin_shave_cmu_alignvec_rri_float4(min, min, 4); float4 max2 = __builtin_shave_cmu_alignvec_rri_float4(max, max, 4); min = __builtin_shave_cmu_min_f32_rr_float4(min, min2); max = __builtin_shave_cmu_max_f32_rr_float4(max, max2); int4 minInt = mvuConvert_int4(min); int4 maxInt = mvuConvert_int4(max); int4 diff = maxInt - minInt; // Processing last cells. for(k = 0; j + k < meshW - 1; k++) { if ((diff[k] <= CMX_BUFFER_LINES) && (minInt[k] < (int)frSpec->height) && (maxInt[k] >= 0) && (minInt[k] > - VERTICAL_PAD)) { if (minInt[k] > 0) { tileNodes[tileLutElemCount].next = meshLUT[minInt[k]].head; tileNodes[tileLutElemCount].x = j + k; tileNodes[tileLutElemCount].y = i; meshLUT[minInt[k]].head = &tileNodes[tileLutElemCount++]; } else { tileNodes[tileLutElemCount].next = meshLUT[0].head; tileNodes[tileLutElemCount].x = j + k; tileNodes[tileLutElemCount].y = i; meshLUT[0].head = &tileNodes[tileLutElemCount++]; } } else { tileNodes[tileLutElemCount].next = meshLUT[MESH_LUT_LENGTH].head; tileNodes[tileLutElemCount].x = j + k; tileNodes[tileLutElemCount].y = i; meshLUT[MESH_LUT_LENGTH].head = &tileNodes[tileLutElemCount++]; } } } } static inline void prepareTile(reTileEntry* tile, meshStruct* mesh, frameBuffer *inputFb, frameBuffer *outputFb, tileList* coord, unsigned int cmxY) { float4 x,y; unsigned int out_width = outputFb->spec.width; unsigned int in_width = inputFb->spec.width; unsigned int meshW = mesh->meshWidth; float *mx = mesh->meshX; float *my = mesh->meshY; unsigned int tileIndex = coord->y * meshW + coord->x; x[0] = mx[tileIndex]; x[1] = mx[tileIndex + 1]; x[2] = mx[tileIndex + meshW]; x[3] = mx[tileIndex + meshW + 1]; y[0] = my[tileIndex] - cmxY; y[1] = my[tileIndex + 1] - cmxY; y[2] = my[tileIndex + meshW] - cmxY; y[3] = my[tileIndex + meshW + 1] - cmxY; float min = min4Elem(x); float max = max4Elem(x); float minFloor = (int)(min - __builtin_shave_sau_frac_f32_r(min)); x -= minFloor; tile->dstOffsetDDR = coord->y * OUT_TILE_HEIGHT * out_width + coord->x * OUT_TILE_WIDTH; if (min > in_width || max < 0) { tile->isInsideImg = 0; // insert in the list which will be filled with padding } else { tile->isInsideImg = 1; adjustBufferPointers(tile, &referenceTile, (unsigned int) minFloor); tile->xCoords = mvuConvert_half4(x); tile->yCoords = mvuConvert_half4(y); } } static inline void processTile(reTileEntry* tile, frameBuffer *inputFb, frameBuffer *outputFb, unsigned short paddingvalue, dmaRequesterId dmaId) { UNUSED(outputFb); UNUSED(paddingvalue); UNUSED(dmaId); mvcvWarpMeshExpand_asm((half*)&tile->xCoords, (half*)&tile->yCoords, mx, my); mvcvWarpMeshSample8bit_asm(&tile->cmxInBuffP[VERTICAL_PAD], tile->cmxOutBuff, mx, my, inputFb->spec.width + 2 * HORIZONTAL_PAD, CMX_BUFFER_LINES); } // scCmxDmaResolveRelAddr is static inline in CMXDMA driver; TODO find a better solution than copying the function here // static uint32_t scCmxDmaResolveRelAddr(uint32_t in_addr, uint32_t shave_number) { uint32_t window = 0; uint32_t window_base; uint32_t *win_reg_ptr = (uint32_t *)(SHAVE_0_BASE_ADR + (SVU_SLICE_OFFSET * shave_number) + SLC_TOP_OFFSET_WIN_A); uint32_t resolved; switch (in_addr >> 24) { case 0x1C: window = 0; break; case 0x1D: window = 1; break; case 0x1E: window = 2; break; case 0x1F: window = 3; break; default: return (in_addr); break; // absolute address, no translation is to be done } window_base = win_reg_ptr[window]; resolved = ((in_addr & 0x00FFFFFF) + window_base); return resolved; } extern "C" void Entry(meshStruct* mesh, frameBuffer *inputFb, frameBuffer *outputFb, tileList* tileNodes, unsigned short paddingvalue) { unsigned int lineId; unsigned char *img = inputFb->p1; unsigned char *out_img = outputFb->p1; unsigned int out_width = outputFb->spec.width; unsigned int out_height = outputFb->spec.height; unsigned int in_width = inputFb->spec.width; unsigned int in_width_pad = inputFb->spec.width + 2* HORIZONTAL_PAD; reTileEntry* currTile, *nextTile, *swapTile; static u32 id1; #ifdef USE_CMX_DMA_NEW_DRIVER ScCmxDmaInitialize(NULL); #else id1 = dmaInitRequester(3); #endif assert((CMX_BUFFER_LINES - 1) % 4 == 0); // memset(inputBufferMem, paddingvalue, CMX_BUFFER_SIZE); currTile = &tiles[0]; nextTile = &tiles[1]; initTileBuffers(currTile, inputBufferMem, in_width_pad); initTileBuffers(nextTile, inputBufferMem, in_width_pad); initTileBuffers(&referenceTile, inputBufferMem, in_width_pad); prepareMesh(mesh, &inputFb->spec, tileNodes); lineId = 0; while (meshLUT[lineId].head == NULL) lineId++; #ifdef USE_CMX_DMA_NEW_DRIVER ScCmxDmaCreateStrideTransaction( &ref[0], &list[0], img + lineId * in_width, currTile->cmxInBuffP[VERTICAL_PAD], in_width, in_width, in_width, in_width_pad, in_width * CMX_BUFFER_LINES); ScCmxDmaStartTransfer(&ref[0]); // create output transaction with dummy addresses. We will fill it later ScCmxDmaCreateStrideTransaction( &ref[1], &list[1], img + lineId * in_width, // new CMXDMA driver requires addr!=NULL here, even if addr is updated later out_img + NO_DDR_OUTPUT, OUT_TILE_WIDTH, OUT_TILE_WIDTH, OUT_TILE_WIDTH, inputFb->spec.width, OUT_TILE_WIDTH * OUT_TILE_HEIGHT); ScCmxDmaWaitTransaction(&ref[0]); #else ref[0] = dmaCreateTransactionFullOptions( id1, &list[0], img + lineId * in_width, currTile->cmxInBuffP[VERTICAL_PAD], in_width * CMX_BUFFER_LINES, in_width, in_width, in_width, in_width_pad); dmaStartListTask(ref[0]); // create output transaction with dummy addresses. We will fill it later ref[1] = dmaCreateTransactionFullOptions( id1, &list[1], NULL, out_img + NO_DDR_OUTPUT, OUT_TILE_WIDTH * OUT_TILE_HEIGHT, OUT_TILE_WIDTH, OUT_TILE_WIDTH, OUT_TILE_WIDTH, inputFb->spec.width); dmaWaitTask(ref[0]); #endif // USE_CMX_DMA_NEW_DRIVER u8* dmaSrcAddress = img + in_width * (lineId + CMX_BUFFER_LINES); #ifdef USE_CMX_DMA_NEW_DRIVER ScCmxDmaCreateTransaction( &ref[0], &list[0], dmaSrcAddress, referenceTile.swapP, in_width); #else ref[0] = dmaCreateTransaction( id1, &list[0], dmaSrcAddress, referenceTile.swapP, in_width); #endif // USE_CMX_DMA_NEW_DRIVER currTile->cmxOutBuff = outBufferMem[0]; nextTile->cmxOutBuff = outBufferMem[1]; //main loop for (; lineId + 1 + CMX_BUFFER_LINES < out_height;lineId++) { u32 i; list[0].src = img + in_width * (lineId + CMX_BUFFER_LINES); list[0].dst = (u8 *)scCmxDmaResolveRelAddr((u32)referenceTile.swapP, scGetShaveNumber()); #ifdef USE_CMX_DMA_NEW_DRIVER ScCmxDmaStartTransfer(&ref[0]); #else dmaStartListTask(ref[0]); #endif // USE_CMX_DMA_NEW_DRIVER tileList *listP2, * listP = meshLUT[lineId].head; list[1].dst = (void*)NO_DDR_OUTPUT; if (listP != NULL) { #ifdef USE_CMX_DMA_NEW_DRIVER ScCmxDmaWaitTransaction(&ref[0]); #else dmaWaitTask(ref[0]); #endif while (listP != NULL) { if (list[1].dst != (void*)NO_DDR_OUTPUT) { #ifdef USE_CMX_DMA_NEW_DRIVER ScCmxDmaWaitTransaction(&ref[1]); #else dmaWaitTask(ref[1]); #endif // USE_CMX_DMA_NEW_DRIVER } //prepare tile may reorganize the list listP2 = listP; listP = listP->next; prepareTile(currTile, mesh, inputFb, outputFb, listP2, lineId); if (currTile->isInsideImg) processTile(currTile, inputFb, outputFb, paddingvalue, id1); u8* dstAddress = outputFb->p1 + currTile->dstOffsetDDR; u8* srcAddress = currTile->cmxOutBuff; if (currTile->isInsideImg) { #ifdef USE_DMA list[1].src = srcAddress; list[1].dst = dstAddress; ScCmxDmaStartTransfer(&ref[1]); #else for(i = 0; i < OUT_TILE_HEIGHT; ++i) { memcpy(dstAddress, srcAddress, OUT_TILE_WIDTH); dstAddress += inputFb->spec.width; srcAddress += OUT_TILE_WIDTH; } #endif } else { for(i = 0; i < OUT_TILE_HEIGHT; ++i) { memset(dstAddress, paddingvalue, OUT_TILE_WIDTH); dstAddress += inputFb->spec.width; } list[1].dst = (void*)NO_DDR_OUTPUT; } swapTile = currTile; currTile = nextTile; nextTile = swapTile; } #ifdef USE_DMA if (nextTile->dstOffsetDDR != NO_DDR_OUTPUT) dmaWaitTask(ref[1]); #endif } else { #ifdef USE_CMX_DMA_NEW_DRIVER ScCmxDmaWaitTransaction(&ref[0]); #else dmaWaitTask(ref[0]); #endif // USE_CMX_DMA_NEW_DRIVER } rotateBufferPointers(&referenceTile); } int i; // padding for (; lineId < out_height;lineId++) { referenceTile.swapP = referenceTile.cmxInBuffP[0]; tileList* listP = meshLUT[lineId].head; while (listP != NULL) { prepareTile(currTile, mesh, inputFb, outputFb, listP, lineId); processTile(currTile, inputFb, outputFb, paddingvalue, id1); u8* dstAddress = outputFb->p1 + currTile->dstOffsetDDR; u8* srcAddress = currTile->cmxOutBuff; if (currTile->dstOffsetDDR != NO_DDR_OUTPUT) for(i = 0; i < OUT_TILE_HEIGHT; ++i) { memcpy(dstAddress, srcAddress, OUT_TILE_WIDTH); dstAddress += inputFb->spec.width; srcAddress += OUT_TILE_WIDTH; } listP = listP->next; } rotateBufferPointers(&referenceTile); } // fill out the tiles which are out of image tileList* listP = meshLUT[MESH_LUT_LENGTH].head; while (listP != NULL) { u8* dstAddress = out_img + listP->y * OUT_TILE_HEIGHT * out_width + listP->x * OUT_TILE_WIDTH; for(i = 0; i < OUT_TILE_HEIGHT; ++i) { memset(dstAddress, paddingvalue, OUT_TILE_WIDTH); dstAddress += inputFb->spec.width; } listP = listP->next; } }
a96af18ac17f1733c882c18738739fd5fe0fab0a
28a43c8d0403d661f85a986e25e14adb29c50106
/arduino_code/arduino_code.ino
e2a042a7ae00abe054b818735fefa21e2240b7fd
[ "MIT" ]
permissive
darmbrus/plant-watering-tracker
53ed53c1e8d6a81c4449c1ded3cd4dbbb01b56e1
cb4f797104c2c4b2ea889d3725157861fcc19399
refs/heads/master
2021-01-11T00:39:19.172170
2016-10-19T04:18:12
2016-10-19T04:18:12
70,503,048
0
2
null
2016-10-19T04:18:13
2016-10-10T15:44:30
Ruby
UTF-8
C++
false
false
357
ino
const int buttonPin = 2; int buttonState = 0; void setup() { Serial.begin(9600); pinMode(buttonPin, INPUT); } void loop() { int randNum = random(300); buttonState = digitalRead(buttonPin); if (buttonState == HIGH) { Serial.println(randNum); while(buttonState) { buttonState = digitalRead(buttonPin); } } delay(50); }
ce769fce217719f3eb3148a416826ce2dd472e3e
62ca57c22b47d1ce2be9cef57df13aaee2544eb3
/MyGrid/Content/GridRenderer.h
84c44f82e43700d35b8163e94f36fe9f6dfb7ec4
[]
no_license
marcisolti/MyGrid
feffc68bef377c7e920877a68981f44646b377c2
06a093796fda44f3d618d0223d6135ee98fab21a
refs/heads/master
2023-06-25T06:37:23.573819
2021-07-30T09:08:38
2021-07-30T09:08:38
390,695,926
0
0
null
null
null
null
UTF-8
C++
false
false
1,540
h
#pragma once #include "..\Common\DeviceResources.h" #include "..\Common\StepTimer.h" // You can find the docs at %(SolutionDir)..\docs\index.html namespace MyGrid { struct alignas(16) ConstantBufferData { DirectX::XMFLOAT4X4 model; DirectX::XMFLOAT4X4 view; DirectX::XMFLOAT4X4 projection; DirectX::XMFLOAT4 eyePos; DirectX::XMFLOAT2 resolution; }; class GridRenderer { // Constants: const double m_revolutionsPerMinute; const float m_gridOrientation; const float m_gridSize; const int m_totalSegmentCount; public: GridRenderer(const std::shared_ptr<DX::DeviceResources>& deviceResources); void CreateDeviceDependentResources(); void CreateWindowSizeDependentResources(); void ReleaseDeviceDependentResources(); void Update(const DX::StepTimer& timer); void Render(); private: void CreateVertexBuffer(); std::shared_ptr<DX::DeviceResources> m_deviceResources; Microsoft::WRL::ComPtr<ID3D11VertexShader> m_vertexShader; Microsoft::WRL::ComPtr<ID3D11GeometryShader> m_geometryShader; Microsoft::WRL::ComPtr<ID3D11PixelShader> m_pixelShader; Microsoft::WRL::ComPtr<ID3D11InputLayout> m_inputLayout; Microsoft::WRL::ComPtr<ID3D11Buffer> m_vertexBuffer; uint32_t m_vertexCount; uint32_t m_stride; uint32_t m_offset; Microsoft::WRL::ComPtr<ID3D11Buffer> m_constantBuffer; ConstantBufferData m_constantBufferData; Microsoft::WRL::ComPtr<ID3D11BlendState> m_blendState; bool m_loadingComplete; }; }
d8a48d1da26efb82b52230f1b657d28e28255eb8
bd6b62b691f2e5fef2d0ad053616de20efbe1fd8
/cpp_c/gcc/lang_spec/inherit/override-by-non-vertual.cpp
b96f7ed08032c2e1bc1f7635d0866d421eee15fd
[]
no_license
kurokawh/test
ed273acb0f559ec17bbc529745e8cf6fb3130e95
172ba3cb4ed89ce5f6d4dfc2dbeccaf0d285bcc8
refs/heads/master
2023-01-25T02:59:49.617869
2023-01-19T05:40:08
2023-01-19T05:40:08
42,255,830
0
0
null
null
null
null
UTF-8
C++
false
false
1,152
cpp
#include <stdlib.h> #include <stdio.h> #include <stdint.h> // check if vertual func can be overrided by non-vertual func. // => non virtuan func can be called. class A { int a; public: virtual void test(A& arg) { printf("A::test(): %d\n", arg.a); } void publicFuncA() { printf("A::pulicFuncA(): \n"); } void publicFuncB() { printf("A::pulicFuncB(): \n"); } protected: void protectedFuncA() { printf("A::pulicFuncA(): \n"); } }; class SubVirtual : public A { int b; public: virtual void test(A& arg) { printf("SubVirtual::test()\n"); A::test(arg); protectedFuncA(); } }; class SubNonVirtual : public A { int b; public: void test(A& arg) { printf("SubNonVirtual::test()\n"); A::test(arg); protectedFuncA(); } }; void test(A& a, const char* s) { printf("== test(%s) ==>\n", s); a.test(a); a.publicFuncA(); printf("<== test(%s) ==\n", s); } int main(int argc, char** argv) { A* a = new A; A* spa = new SubVirtual; spa->test(*spa); spa->publicFuncA(); test(*a, "A"); test(*spa, "SubVirtual"); A* snv = new SubNonVirtual; test(*snv, "SubNonVirtual"); delete snv; delete a; delete spa; return 0; }
c818b103e2bd1f584873a454d31aeff6d22ea29e
21d7c1def6efcaf9ba5b74f521f75d2aaeae8192
/scorched3d/scorched3d.ver01/scorched-dep-win32/include/wx/wx/msw/dirdlg.h
6eacd391ba4694cf10b62ee4b1221eac3e9e31fc
[]
no_license
QuangNhat/GitHub
99f3714fc38f3cf007ccc947b1647f41fe8aa29b
bc9a35c5bfe53a648b717c46b6bf5ddbca9b2ea3
refs/heads/master
2021-01-10T16:06:11.305568
2015-12-17T16:45:59
2015-12-17T16:45:59
48,186,201
0
0
null
null
null
null
UTF-8
C++
false
false
1,472
h
///////////////////////////////////////////////////////////////////////////// // Name: wx/msw/dirdlg.h // Purpose: wxDirDialog class // Author: Julian Smart // Modified by: // Created: 01/02/97 // RCS-ID: $Id: dirdlg.h,v 1.1 2006/12/02 15:58:30 scara Exp $ // Copyright: (c) Julian Smart // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// #ifndef _WX_DIRDLG_H_ #define _WX_DIRDLG_H_ #ifdef __GNUG__ #pragma interface "dirdlg.h" #endif class WXDLLEXPORT wxDirDialog : public wxDialog { public: wxDirDialog(wxWindow *parent, const wxString& message = wxDirSelectorPromptStr, const wxString& defaultPath = wxEmptyString, long style = 0, const wxPoint& pos = wxDefaultPosition, const wxSize& size = wxDefaultSize, const wxString& name = wxDirDialogNameStr); void SetMessage(const wxString& message) { m_message = message; } void SetPath(const wxString& path); void SetStyle(long style) { m_dialogStyle = style; } wxString GetMessage() const { return m_message; } wxString GetPath() const { return m_path; } long GetStyle() const { return m_dialogStyle; } virtual int ShowModal(); protected: wxString m_message; long m_dialogStyle; wxString m_path; private: DECLARE_DYNAMIC_CLASS(wxDirDialog) }; #endif // _WX_DIRDLG_H_
89a75c7f97aacda7ad8e7ac6abd02b77a19778bb
6e8620c1a8f4b8a4ba3007ed87ec56aefe57753a
/uciType.cpp
83f5bf54b0d6d4d546497113bf09243260638df7
[ "BSD-3-Clause" ]
permissive
nexsct/mariana-NASA-adaptation
dee55c08d00c2e4b7e18634d501731527f75feb7
e7b2188f2d7ea79396e1c05dfe3745f6234b422d
refs/heads/main
2023-01-14T03:51:35.597190
2020-11-11T19:17:51
2020-11-11T19:17:51
312,066,452
2
0
null
null
null
null
MacCentralEurope
C++
false
false
14,981
cpp
/***************************************************************************** * Notices: Mariana - Copyright č 2007 United States Government as * represented by the Administrator of the National Aeronautics and Space * Administration.  All Rights Reserved. * * Libsvm - support vector routine library - Copyright (c) 2000-2007 * Chih-Chung Chang and Chih-Jen Lin All rights reserved. * * Disclaimers * * Mariana No Warranty: THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT * ANY WARRANTY OF ANY KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, * INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE * WILL CONFORM TO SPECIFICATIONS, ANY IMPLIED WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR FREEDOM FROM * INFRINGEMENT, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL BE ERROR FREE, * OR ANY WARRANTY THAT DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE * SUBJECT SOFTWARE. THIS AGREEMENT DOES NOT, IN ANY MANNER, CONSTITUTE AN * ENDORSEMENT BY GOVERNMENT AGENCY OR ANY PRIOR RECIPIENT OF ANY RESULTS, * RESULTING DESIGNS, HARDWARE, SOFTWARE PRODUCTS OR ANY OTHER APPLICATIONS * RESULTING FROM USE OF THE SUBJECT SOFTWARE.  FURTHER, GOVERNMENT AGENCY * DISCLAIMS ALL WARRANTIES AND LIABILITIES REGARDING THIRD-PARTY SOFTWARE, * IF PRESENT IN THE ORIGINAL SOFTWARE, AND DISTRIBUTES IT "AS IS." * * Waiver and Indemnity:  RECIPIENT AGREES TO WAIVE ANY AND ALL CLAIMS * AGAINST THE UNITED STATES GOVERNMENT, ITS CONTRACTORS AND * SUBCONTRACTORS, AS WELL AS ANY PRIOR RECIPIENT.  IF RECIPIENT'S USE OF * THE SUBJECT SOFTWARE RESULTS IN ANY LIABILITIES, DEMANDS, DAMAGES, * EXPENSES OR LOSSES ARISING FROM SUCH USE, INCLUDING ANY DAMAGES FROM * PRODUCTS BASED ON, OR RESULTING FROM, RECIPIENT'S USE OF THE SUBJECT * SOFTWARE, RECIPIENT SHALL INDEMNIFY AND HOLD HARMLESS THE UNITED STATES * GOVERNMENT, ITS CONTRACTORS AND SUBCONTRACTORS, AS WELL AS ANY PRIOR * RECIPIENT, TO THE EXTENT PERMITTED BY LAW.  RECIPIENT'S SOLE REMEDY FOR * ANY SUCH MATTER SHALL BE THE IMMEDIATE, UNILATERAL TERMINATION OF THIS * AGREEMENT. * * Libsvm Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither name of copyright holders nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ #define MAX_LINE_LENGTH 655360 #include "uciType.h" using namespace std; uciType::uciType() { } uciType::~uciType() { } void uciType::read(string fileName) { // Open the input file and make sure it exists ifstream inFile; inFile.open( fileName.c_str(), ios::in); if( inFile.bad()) { cerr << "load ERROR, " << "can't open input file (" << fileName << ")" << endl; exit( 1); } else { int aaaaa = 1; // cout << "load " // << "loading input file <" << fileName << ">" << endl; } char textline[ MAX_LINE_LENGTH]; int tmpInstance = 1000; //initialize the category array Cat = new int[tmpInstance]; int getLineCount = 0; while(!inFile.eof()){ ++getLineCount; int termCount = 0; inFile.getline( textline, MAX_LINE_LENGTH); istringstream ins; ins.str(textline); //int lineStart = ins.tellg(); while(!ins.eof()) { string tmp; ins >> tmp; if(tmp.find(":", 0) == string::npos){ // check to see if the labesl are correct istringstream a; a.str(tmp); int b; a >> b; if(b*b != 1) { cerr << "Line " << b << " should be labeled " << " as +-1" << endl; cerr << "error : Line" << getLineCount << "\n" << textline << endl; } } else if(ins.eof()){ break; } else{ termCount++; //cout << tmp << " "; } } int * ind = new int[termCount]; double * val = new double[termCount]; ins.clear(); ins.str(textline); if(termCount != 0) { //cout << termCount << " line 79 termcount\n"; ins >> Cat[getLineCount - 1]; //cout << getLineCount - 1 << "\t" ; for(int i = 0; i < termCount; i++) { string tmp; ins >> tmp; // if(!tmp.empty()) sscanf(tmp.c_str(),"%d:%lf",&ind[i],&val[i]); //cout << ind[i] << ":" << val[i] << " "; } //cout << endl; featureBag.insertRow(getLineCount - 1, termCount, ind, val); //featureBag.printRow(getLineCount - 1); } else if(inFile.peek() != EOF) { cout << "problem w/ line " << textline << " at " << getLineCount << " and has " << termCount << endl; } // expand memory if necessary if(getLineCount == tmpInstance){ tmpInstance += getLineCount; int* tmp = new int[tmpInstance]; for(int i = 0; i < getLineCount - 1; i++) { tmp[i] = Cat[i]; } delete [] Cat; Cat = tmp; } //cout << featureBag.rowSize(getLineCount - 2) << "line101\n"; } inFile.close(); // reduce Cat to the exact size { int *tmp = new int[getLineCount]; for(int i = 0; i < getLineCount; i++) tmp[i] = Cat[i]; Cat = tmp; } totalInstances = getLineCount - 1; } void uciType::setUsage(double *theSplit) { useSplit = theSplit; usage = new int[totalInstances]; int *rOrder = randomOrder(totalInstances); //for(int i = 0; i < 3; i++) cout << useSplit[i] << " "; trainCount = floor(useSplit[0]*(double)totalInstances); valCount = floor(useSplit[1]*(double)totalInstances); testCount = totalInstances - trainCount - valCount; trainIns_ = new int[trainCount]; valIns_ = new int[valCount]; testIns_ = new int[testCount]; trainInsIn = 0; valInsIn = 0; testInsIn = 0; int first = trainCount; int second = trainCount + valCount; int third = totalInstances; for(int i = 0; i < totalInstances; i ++) { if(i < trainCount){ usage[rOrder[i]] = 999; trainIns_[i] = rOrder[i]; if(Cat[trainIns_[i]] == 1){ trainInsIn++; } } else if(i >= trainCount && i < second) { usage[rOrder[i]] = -888; valIns_[i - trainCount ] = rOrder[i]; if(Cat[valIns_[i - trainCount]] == 1){ valInsIn++; } } else// if(i >= second && //i < totalInstances) { usage[rOrder[i]] = 7357; testIns_[i - trainCount - valCount] = rOrder[i]; if(Cat[testIns_[i - trainCount - valCount]] == 1){ testInsIn++; } } } // cout << "train/val/test" << trainCount << "/" // << valCount << "/" << testCount << endl; } void uciType::reduceInstance(int number, double rPer) { double natPer = ((double)trainInsIn + (double)valInsIn + (double)testInsIn)/(double)totalInstances; double usePer; int *tmpTrainIns = new int[trainCount]; for(int i = 0; i < trainCount; i++) tmpTrainIns[i] = trainIns_[i]; int newTrainCount; if(number < trainCount) newTrainCount = number; else newTrainCount = trainCount; if(natPer < rPer) usePer = rPer; else usePer = natPer; int trainInCount = round(usePer*(double)newTrainCount); int trainOutCount; if(trainInCount > trainInsIn){ trainInCount = trainInsIn; trainOutCount = floor((double)trainInsIn*(-1 + 1/usePer)); newTrainCount = trainInCount + trainOutCount; } else{ trainOutCount = newTrainCount - trainInCount; //newTrainCount = trainInCount + trainOutCount; } // cout << trainInCount << "/" << trainInsIn << " - " // << trainOutCount << "/" << (trainCount - trainInsIn) << " - " // << usePer << "/" << natPer << "/" << rPer << endl; int *newTrainIns = new int[newTrainCount]; int tmpInc = trainCount; trainCount = newTrainCount; while(newTrainCount > 0) { tmpInc--; if(Cat[tmpTrainIns[tmpInc]] == 1 && trainInCount > 0){ newTrainCount--; newTrainIns[newTrainCount] = tmpTrainIns[tmpInc]; trainInCount--; // cout << tmpInc << " " << newTrainCount << " " << trainInCount << " " << trainOutCount << " " // << newTrainIns[newTrainCount] << " " // << Cat[newTrainIns[newTrainCount]] << endl; } else if(Cat[tmpTrainIns[tmpInc]] == -1 && trainOutCount > 0) { newTrainCount--; newTrainIns[newTrainCount] = tmpTrainIns[tmpInc]; trainOutCount--; // cout << tmpInc << " " << newTrainCount << " " << trainInCount << " " << trainOutCount << " " // << newTrainIns[newTrainCount] << " " // << Cat[newTrainIns[newTrainCount]] << endl; } // ; // if(newTrainCount == 0) break; } delete [] trainIns_; trainIns_ = newTrainIns; // trainIns_ = new int[trainCount]; // for(int i = 0; i < trainCount; i++) // trainIns_[i] = newTrainIns[i]; // for(int i = 0; i < trainCount; i++) cout << trainIns_[i] << " "; // cout << endl; } void uciType::toLibSvmFormat( svm_problem & train, bool norm, int wht) { normalize = norm; //struct svm_node *x_space; // set up the svm problem int *docs2use; if(wht == 1) { train.l = trainCount; docs2use = trainIns_; } else if(wht == 2) { train.l = valCount; docs2use = valIns_; } else if(wht == 3) { train.l = testCount; docs2use = testIns_; } //cout << "toLibSvmFormat(228): " << train.l << endl; train.x = new svm_node*[train.l]; train.y = new double[train.l]; double* sum = new double[train.l]; for(int k=0; k<train.l; k++) sum[k]=1; int nElements=0; // for(int i = 0; i < train.l; i++) cout << docs2use[i] << " "; // cout << endl; int dim = featureBag.maxCol(); // If no normalization was requested, simply increment the number of // elements and set succesive elements of the SUM vector to '1'. (Note // that this was already done during the initlaization process above.) // Otherwise, normalize term frequencies. if( normalize) { //if(verbose) cout << " normalize\n"; // Loop: Evaluate values for successive lines of the svm_problem structure for( int h=0; h<train.l; h++) { // Add an element for each line (the lines with "-1") nElements++; // Add an element for each line (the lines with "-1") nElements++; // Get the index and value for this row //cout << h << ": " << docs2use[h] << " h/d\n"; int rowSize = featureBag.rowSize( docs2use[h]); // cout << featureBag.rowSize( docs2use[h]) << " rowsize\n"; //featureBag.printRow( docs2use[h]); int* idx = featureBag.getRowIndex( docs2use[h]); // cout << featureBag.rowSize( docs2use[h]) << " bbb\n"; double* val = featureBag.getRowValue( docs2use[h]); // cout << featureBag.rowSize( docs2use[h]) << " aaa\n"; // cout << "index:" << h <<":" << idx[0] // << ":" << val[0] <<":" << rowSize << " \n"; // Loop: Evaluate successive elements in this line double tmp = 0; int kv = 0; while( kv < rowSize && kv < dim){ // cout << "MMM:" << kv <<":" << idx[kv] << ":" // << dim << ":" << val[kv] << " \n"; tmp+=val[kv]; // cout << "=idx>dim:" << idx[kv] << ":" << dim[kd] << endl; nElements++; kv++; } //delete [] idx; //delete [] val; sum[h] = tmp; //cout << h << endl; } } else { nElements = featureBag.nElements() + train.l; for(int h=0; h<train.l; h++) sum[h] = 1; } // Allocate storage for global buffer, x_space, that will be used to read // all of the elements for this svm_problem structure. NOTE 2) Does this // have to be global? NOTE 2) Why doesn't this crash during successive // calls to this method? Could the new (or malloc) operation be allocating // new storage while leaking the old storage, which is later deallocated // when the relevant svm_problem structure is destroyed? x_space = new svm_node[ nElements]; // Loop: Go through and map the BOW into the X_SPACE vector int max_index = 0; // Biggest term index int j = 0; for( int i=0; i<train.l; i++) { // cout << "assign category:" << Cat[docs2use[i]] << endl; // cout << train.y[i] << " " << train.x[i] << "x_i\n"; train.y[i] = Cat[docs2use[i]]; train.x[i] = &x_space[j]; // cout << "category " << train.y[i] << endl; // Get dimensions and sizes associated with the BOW structure int* idx = featureBag.getRowIndex( docs2use[i]); double* val = featureBag.getRowValue( docs2use[i]); int rowSize = featureBag.rowSize( docs2use[i]); // Loop: process successive elements from the BOW structure int kd = 0, kv = 0; while( kv < rowSize && kv < dim) { // Go through the sparse vector x_space[j].index = idx[kv]; x_space[j].value = val[kv]/sum[i]; //cout << "toLibSvm::" << j << ":" << dim<< ": " << val[kv] << " \n"; nElements++; kd++; kv++; j++; } // If necessary, increment the value of the maximum index if( j>=1 && x_space[j-1].index > max_index) { max_index = x_space[j-1].index; //cout << "\n" << max_index << "\nMMMMM\n"; } // Write terminator to end this element of the x_space vector, then // increment index x_space[j].index = -1; // cout << "L:" << i << "/" << train.l << " - " << j // << "/" << nElements << endl; j++; } // Don't deallocate x_space here because this storage is referenced by this // svm_problem structure! NOTE 1) Tnis memory allocation is tricky, and it // is not immediately apparent how successive calls to this method can work. // NOTE 2) x_space must be deallocated in main() to avoid a memory leak. // delete x_space; // Report success // cout << "done building problem\n"; //delete[] x_space; x_space = new svm_node[1]; } void uciType::printBag() { for(int i = 0; i < totalInstances; i++) { cout << usage[i] << "\t"; featureBag.printRow(i); } cout << trainCount << " number for training docs\n"; cout << featureBag.maxCol() << " number of columns\n"; } void uciType::printBag2() { for(int i = 0; i < featureBag.nRows(); i++) { int *tmp = featureBag.getRowIndex(i); double *vl = featureBag.getRowValue(i); for(int j = 0; j < featureBag.maxCol(); j++) cout << tmp[j] << ":" << vl[j] << " "; cout << endl; } cout << trainCount << " number for training docs\n"; cout << featureBag.maxCol() << " number of columns\n"; }
20f44ac01e4a639ff2659dc043b3a70d96f28af0
349fe789ab1e4e46aae6812cf60ada9423c0b632
/Forms/HOT_SprObject/UHOT_FormaElementaSprObjectImpl.cpp
0e2ad0b3252b5615a355cadf7ac5960cd1c7019c
[]
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
WINDOWS-1251
C++
false
false
8,775
cpp
#include "vcl.h" #pragma hdrstop #include "UHOT_FormaElementaSprObjectImpl.h" #pragma package(smart_init) extern int NumObject; //--------------------------------------------------------------- THOT_FormaElementaSprObjectImpl::THOT_FormaElementaSprObjectImpl() { Object=new THOT_FormaElementaSprObject(Application); Object->FunctionDeleteImpl=DeleteImpl; NumRefs=0; ++NumObject; flDeleteObject=true; } //--------------------------------------------------------------- THOT_FormaElementaSprObjectImpl::~THOT_FormaElementaSprObjectImpl() { if (flDeleteObject==true) { Object->flDeleteImpl=false; delete Object; } --NumObject; } //--------------------------------------------------------------- void THOT_FormaElementaSprObjectImpl::DeleteImpl(void) { flDeleteObject=false; delete this; } //--------------------------------------------------------------- int THOT_FormaElementaSprObjectImpl::kanQueryInterface(REFIID id_interface, void ** ppv) { int result=0; if (id_interface==IID_IkanUnknown) { *ppv=static_cast<IkanUnknown*> (static_cast<IMainInterface*>(this)); result=-1; } else if (id_interface==IID_IMainInterface) { *ppv=static_cast<IMainInterface*> (this); result=-1; } else if (id_interface==IID_IkanCallBack) { *ppv=static_cast<IkanCallBack*> (this); result=-1; } else if (id_interface==IID_IHOT_FormaElementaSprObject) { *ppv=static_cast<IHOT_FormaElementaSprObject*> (this); result=-1; } else { *ppv=NULL; result=1; return result; } kanAddRef(); return result; } //--------------------------------------------------------------- int THOT_FormaElementaSprObjectImpl::kanAddRef(void) { return (++NumRefs); } //--------------------------------------------------------------- int THOT_FormaElementaSprObjectImpl::kanRelease(void) { if (--NumRefs==0) { delete this; return 0; } return NumRefs; } //--------------------------------------------------------------- //IMainInterface int THOT_FormaElementaSprObjectImpl::get_CodeError(void) { return Object->CodeError; } //--------------------------------------------------------------- void THOT_FormaElementaSprObjectImpl::set_CodeError(int CodeError) { } //--------------------------------------------------------------- UnicodeString THOT_FormaElementaSprObjectImpl::get_TextError(void) { return Object->TextError; } //--------------------------------------------------------------- void THOT_FormaElementaSprObjectImpl::set_TextError(UnicodeString TextError) { } //--------------------------------------------------------------- int THOT_FormaElementaSprObjectImpl::Init(IkanUnknown * i_main_object, IkanUnknown * i_owner_object) { kanQueryInterface(IID_IkanUnknown,(void**) &Object->InterfaceImpl); kanRelease(); Object->ClsIdImpl=CLSID_THOT_FormaElementaSprObjectImpl; Object->InterfaceMainObject=i_main_object; Object->InterfaceOwnerObject=i_owner_object; return Object->Init(); } //--------------------------------------------------------------- int THOT_FormaElementaSprObjectImpl::Done(void) { return Object->Done(); } //--------------------------------------------------------------- //IkanCallBack int THOT_FormaElementaSprObjectImpl::kanExternalEvent(IkanUnknown * pUnk, REFIID id_object,int type_event, int number_procedure_end) { return Object->ExternalEvent(pUnk, //интерфейс на дочерний объект id_object, //тип дочернего объекта type_event, //тип события в дочернем объекте number_procedure_end //номер процедуры в род. форме, обрабатывающей событие выбора ); } //--------------------------------------------------------------- //IHOT_FormaElementaSprObject IHOT_DMSprObject * THOT_FormaElementaSprObjectImpl::get_DM(void) { return Object->DM; } //--------------------------------------------------------------- void THOT_FormaElementaSprObjectImpl::set_DM(IHOT_DMSprObject * DM) { Object->DM=DM; } //--------------------------------------------------------------- bool THOT_FormaElementaSprObjectImpl::get_Vibor(void) { return Object->Vibor; } //--------------------------------------------------------------- void THOT_FormaElementaSprObjectImpl::set_Vibor(bool Vibor) { Object->Vibor=Vibor; } //--------------------------------------------------------------- int THOT_FormaElementaSprObjectImpl::get_NumberProcVibor(void) { return Object->NumberProcVibor; } //--------------------------------------------------------------- void THOT_FormaElementaSprObjectImpl::set_NumberProcVibor(int NumberProcVibor) { Object->NumberProcVibor=NumberProcVibor; } //--------------------------------------------------------------- void THOT_FormaElementaSprObjectImpl::UpdateForm(void) { return Object->UpdateForm(); } //---------------------------------------------------------------
515d0a35f121c01fd16cbef73c087905ea33076f
1d9df1156e49f768ed2633641075f4c307d24ad2
/tizen_src/chromium_impl/content/browser/compositor/evasgl_context_provider.cc
699dd42323d0cdd32a999319b0cb2f3592a8c699
[ "BSD-3-Clause", "LGPL-2.1-or-later", "BSD-2-Clause" ]
permissive
GSIL-Monitor/platform.framework.web.chromium-efl
8056d94301c67a8524f6106482087fd683c889ce
e156100b0c5cfc84c19de612dbdb0987cddf8867
refs/heads/master
2022-10-26T00:23:44.061873
2018-10-30T03:41:51
2018-10-30T03:41:51
161,171,104
0
1
BSD-3-Clause
2022-10-20T23:50:20
2018-12-10T12:24:06
C++
UTF-8
C++
false
false
2,193
cc
// Copyright 2015 Samsung Electronics. 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/browser/compositor/evasgl_context_provider.h" #include "gpu/skia_bindings/grcontext_for_gles2_interface.h" #include "third_party/skia/include/gpu/GrContext.h" namespace content { EvasGLContextProvider::EvasGLContextProvider(Evas_GL_API* evas_gl_api, Evas_GL* evas_gl) : evasgl_implementation_(evas_gl_api, evas_gl) { cache_controller_.reset( new viz::ContextCacheController(&evasgl_implementation_, nullptr)); } EvasGLContextProvider::~EvasGLContextProvider() {} bool EvasGLContextProvider::BindToCurrentThread() { return true; } void EvasGLContextProvider::DetachFromThread() {} const gpu::Capabilities& EvasGLContextProvider::ContextCapabilities() const { return capabilities_; } const gpu::GpuFeatureInfo& EvasGLContextProvider::GetGpuFeatureInfo() const { return gpu_feature_info_; } gpu::gles2::GLES2Interface* EvasGLContextProvider::ContextGL() { return &evasgl_implementation_; } gpu::ContextSupport* EvasGLContextProvider::ContextSupport() { return &evasgl_implementation_; } class GrContext* EvasGLContextProvider::GrContext() { if (gr_context_) return gr_context_->get(); gr_context_.reset(new skia_bindings::GrContextForGLES2Interface( ContextGL(), ContextCapabilities())); cache_controller_->SetGrContext(gr_context_->get()); // If GlContext is already lost, also abandon the new GrContext. if (gr_context_->get() && ContextGL()->GetGraphicsResetStatusKHR() != GL_NO_ERROR) { gr_context_->get()->abandonContext(); } return gr_context_->get(); } viz::ContextCacheController* EvasGLContextProvider::CacheController() { return cache_controller_.get(); } void EvasGLContextProvider::InvalidateGrContext(uint32_t state) { if (gr_context_) gr_context_->ResetContext(state); } base::Lock* EvasGLContextProvider::GetLock() { return nullptr; } void EvasGLContextProvider::SetLostContextCallback( const LostContextCallback& lost_context_callback) {} } // namespace content
[ "RetZero@desktop" ]
RetZero@desktop
d051ee2439151facf88044e833fb25a88c843d07
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function14276/function14276_schedule_0/function14276_schedule_0.cpp
19bad50d62f4787e41fdccac84fa4c51b34a18b6
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
1,698
cpp
#include <tiramisu/tiramisu.h> using namespace tiramisu; int main(int argc, char **argv){ tiramisu::init("function14276_schedule_0"); constant c0("c0", 65536), c1("c1", 1024); var i0("i0", 0, c0), i1("i1", 0, c1), i01("i01"), i02("i02"), i03("i03"), i04("i04"); input input00("input00", {i0}, p_int32); input input01("input01", {i0}, p_int32); input input02("input02", {i1}, p_int32); input input03("input03", {i1}, p_int32); input input04("input04", {i0}, p_int32); input input05("input05", {i0}, p_int32); input input06("input06", {i0}, p_int32); computation comp0("comp0", {i0, i1}, input00(i0) - input01(i0) + input02(i1) + input03(i1) + input04(i0) - input05(i0) * input06(i0)); comp0.tile(i0, i1, 32, 32, i01, i02, i03, i04); comp0.parallelize(i01); buffer buf00("buf00", {65536}, p_int32, a_input); buffer buf01("buf01", {65536}, p_int32, a_input); buffer buf02("buf02", {1024}, p_int32, a_input); buffer buf03("buf03", {1024}, p_int32, a_input); buffer buf04("buf04", {65536}, p_int32, a_input); buffer buf05("buf05", {65536}, p_int32, a_input); buffer buf06("buf06", {65536}, p_int32, a_input); buffer buf0("buf0", {65536, 1024}, p_int32, a_output); input00.store_in(&buf00); input01.store_in(&buf01); input02.store_in(&buf02); input03.store_in(&buf03); input04.store_in(&buf04); input05.store_in(&buf05); input06.store_in(&buf06); comp0.store_in(&buf0); tiramisu::codegen({&buf00, &buf01, &buf02, &buf03, &buf04, &buf05, &buf06, &buf0}, "../data/programs/function14276/function14276_schedule_0/function14276_schedule_0.o"); return 0; }
bf604670f217b0c17d93eb4a31c78cacf026c289
4ef69f0044f45be4fbce54f7b7c0319e4c5ec53d
/include/cv/core/cmd/out/dhseqr.inl
916e4f4aba4fc9b5981781279e494c69b73adb94
[]
no_license
15831944/cstd
c6c3996103953ceda7c06625ee1045127bf79ee8
53b7e5ba73cbdc9b5bbc61094a09bf3d5957f373
refs/heads/master
2021-09-15T13:44:37.937208
2018-06-02T10:14:16
2018-06-02T10:14:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
276
inl
#ifndef __dhseqr__ #define __dhseqr__ #define c_b11 c_b11_dhseqr #define c_b12 c_b12_dhseqr #define c__12 c__12_dhseqr #define c__2 c__2_dhseqr #define c__49 c__49_dhseqr #include "dhseqr.c" #undef c_b11 #undef c_b12 #undef c__12 #undef c__2 #undef c__49 #endif // __dhseqr__
119943f722c510b727fb0c7fc6d8bcb6db01b047
bd1e457d3bc7aba76c1200d15416fa5c1bf847de
/DSA/LAB/Lab 6/Task2.cpp
d57dd5a64bf34c562ff7e33039d90897ee3207c0
[]
no_license
Mu-Ahmad/OOP-CMP-244-241
6da4f2fee88c207a688b8c70a8dd3ad8655921c3
3dd826fff83c9a539f89fc2483ac80c032b269dc
refs/heads/main
2023-06-06T16:30:06.089789
2021-06-18T15:33:35
2021-06-18T15:33:35
303,761,272
17
6
null
2020-10-26T11:14:37
2020-10-13T16:19:04
C++
UTF-8
C++
false
false
4,647
cpp
/* Name: Muhammad Ahmad Roll: BCSF19M509 */ #include <iostream> using namespace std; #define DUMMY 0 class DNode { public: DNode *prev, *next; int data; DNode (int d, DNode *p = NULL , DNode *n = NULL ) { data = d; prev = p; next = n; } }; class DHCLList { public: DNode *head; DHCLList() { head = new DNode(DUMMY); head -> next = head -> prev = head; } void addNodeAtHead(int d) { DNode *newNode = new DNode(d, head, head->next); head -> next -> prev = newNode; head -> next = newNode; } void addNodeAtTail(int d) { DNode *newNode = new DNode(d, head->prev, head); head -> prev -> next = newNode; head -> prev = newNode; } void print(DNode *t) { if (t == head) return; cout << t -> data << ' '; print(t->next); } void print() { print(head->next); cout << '\n'; } void printR(DNode *t) { if (t == head) return; cout << t -> data << ' '; printR(t->prev); } void printR() { printR(head->prev); cout << '\n'; } void addInOrder(int d, DNode *t) { if (t == head || t -> data > d) { DNode *newNode = new DNode (d, t -> prev, t); t -> prev -> next = newNode; t -> prev = newNode; return; } addInOrder(d, t -> next) ; } void addNodeInOrder(int d) { if (head -> next == head) { addNodeAtHead(d); return; } addInOrder(d, head -> next) ; } // ================= Task A ============== // Helper Functions int indexOf(const int& ELEMENT) const { int index = 1; // 1 Based indexing DNode* temp = head->next; while (temp != head) { if (temp->data == ELEMENT) return index; index++; temp = temp->next; } return -1; } void swapNodes(int d1, int d2) { int i1 = indexOf(d1); int i2 = indexOf(d2); // if elements are same or one of element is not found if (i1 == i2 or i1 == -1 or i2 == -1) return; // Do nothing DNode *Node1 = head, *Node2 = head; if (i1 > i2) swap(i1, i2); // Node1 will come before Node2 int t1 = i1, t2 = i2; while (t1--) Node1 = Node1->next; while (t2--) Node2 = Node2->next; if (i2 - i1 == 1) { // Updating Links for neighbors DNode* tempPrev = Node1->prev; Node1->next = Node2->next; Node2->next->prev = Node1; Node1->prev = Node2; Node2->next = Node1; Node2->prev = tempPrev; tempPrev->next = Node2; } else { // Updating Links for non-neighbors DNode* tempPrev = Node1->prev; DNode* tempNext = Node1->next; Node1->next = Node2->next; Node2->next->prev = Node1; Node1->prev = Node2->prev; Node2->prev->next = Node1; Node2->next = tempNext; tempNext->prev = Node2; Node2->prev = tempPrev; tempPrev->next = Node2; } } // ================= Task B ============== void reverse() { head->prev = reverse(head->next); } DNode* reverse(DNode *curr) { //Base Case // Empty list if (curr == head) return head; //Last Element i.e tail or new head if (curr->next == head) { head->next = curr; curr->prev = head; return curr; } // Recursive Case DNode* the_next = reverse(curr->next); // This Will reverse the rest of the list and return a reference to next node // move the current node infront of next the_next->next = curr; //curr node becomes the last curr->next = head; // Repair the prev reference curr->prev = the_next; return curr; } void reverse2() { reverse2(head->next); swap(head->next, head->prev); } void reverse2(DNode* curr) { if (curr == head) return; swap(curr->next, curr->prev); return reverse2(curr->prev); } }; int main() { DHCLList list; cout << "================ Task A ============\n"; list.addNodeAtTail(1); list.addNodeAtTail(2); list.addNodeAtTail(3); list.addNodeAtTail(4); list.addNodeAtTail(5); list.addNodeAtTail(6); list.print(); cout << "Swapping 3 and 4:\n"; list.swapNodes(3, 4); // Swapping Neighbors list.print(); cout << "Swapping 1 and 6:\n"; list.swapNodes(1, 6); // Swapping Non-Neighbors list.print(); cout << "Swapping 2 and 5:\n"; list.swapNodes(2, 5); // Swapping Non-Neighbors list.print(); // Swaping Back to original state cout << "================ Task B ============\n"; list.swapNodes(3, 4); // Swapping Neighbors list.swapNodes(1, 6); // Swapping Non-Neighbors list.swapNodes(2, 5); // Swapping Non-Neighbors cout << "Original List:\n"; list.print(); list.reverse2(); cout << "Reversed List:\n"; list.print(); cout << "Using prev Reference: (In Reverse Order)\n"; // This prove that previous reference are also updated correctly // during the reversing process DNode* start = list.head->prev; while (start != list.head) { cout << start->data << ' '; start = start->prev; } return 0; }
66648d243f3d684b29abe7cb60c4e78240995665
d41f4166f65f7b6ca163d9d5e9ef1889edcd2654
/Simplifier/Geometry.cpp
47c94fd16a9458df584d6bac71fb0a64a78a7383
[]
no_license
AlexandrShcherbakov/Demo3
ad073a0712de7275899505f3256017b2c357d8dd
0c387fdf9cea8cff8eab8b17bc1b2251aa3b04d7
refs/heads/master
2021-01-21T21:43:13.658982
2016-03-22T11:31:36
2016-03-22T11:31:36
51,869,564
0
0
null
null
null
null
UTF-8
C++
false
false
26,086
cpp
#include "Geometry.h" ///Small changes void Geometry::mergeTwoPoints(uint p1, uint p2) { mergeTwoPoints(p1, p2, (points[p1] + points[p2]) / 2.0f); } void Geometry::mergeTwoPoints(uint p1, uint p2, vec4 newP) { ///Update points /*points[p1] = newP; indices[p2] = p1;*/ uint tmp = std::min(p1, p2); p2 = std::max(p1, p2); p1 = tmp; std::vector<uint> newTriangles; for (uint i = 0; i < triangles.size(); i += 3) { if (triangles[i + 0] == p2) triangles[i + 0] = p1; if (triangles[i + 1] == p2) triangles[i + 1] = p1; if (triangles[i + 2] == p2) triangles[i + 2] = p1; sort(triangles.begin() + i, triangles.begin() + i + 3); if (triangles[i + 0] == triangles[i + 1] || triangles[i + 1] == triangles[i + 2]) continue; newTriangles.push_back(triangles[i + 0]); newTriangles.push_back(triangles[i + 1]); newTriangles.push_back(triangles[i + 2]); } points.erase(points.begin() + p2); points[p1] = newP; } void Geometry::removeTriangle(uint p1, uint p2, uint p3) { vec4 resP = (points[p1] + points[p2] + points[p3]) / 3.0f; mergeTwoPoints(p1, p2, resP); mergeTwoPoints(p1, p3, resP); } void Geometry::removePointsIntoPolygons() { ///Create sets of plants for points and sets of edges std::vector<std::vector<vec4> > plants(points.size()); std::vector<std::set<uint> > edgeList(points.size()); for (uint i = 0; i < triangles.size(); i += 3) { sort(triangles.begin() + i, triangles.begin() + i + 3); uint a_ind = triangles[i + 0]; uint b_ind = triangles[i + 1]; uint c_ind = triangles[i + 2]; vec4 plant = getTrianglePlant(i / 3); bool flag = false; for (uint i = 0; i < plants[a_ind].size() && !flag; ++i) { flag = flag || plant == plants[a_ind][i]; } if (!flag) { plants[a_ind].push_back(plant); } flag = false; for (uint i = 0; i < plants[b_ind].size() && !flag; ++i) { flag = flag || plant == plants[b_ind][i]; } if (!flag) { plants[b_ind].push_back(plant); } flag = false; for (uint i = 0; i < plants[c_ind].size() && !flag; ++i) { flag = flag || plant == plants[c_ind][i]; } if (!flag) { plants[c_ind].push_back(plant); } edgeList[a_ind].insert(b_ind); edgeList[a_ind].insert(c_ind); edgeList[b_ind].insert(a_ind); edgeList[b_ind].insert(c_ind); edgeList[c_ind].insert(a_ind); edgeList[c_ind].insert(b_ind); } ///Remove bad points for (uint i = 0; i < plants.size(); ++i) { //std::cout << i << ' ' << plants[i].size() << ' ' << edgeList[i].size() << std::endl; if (100 * (i + 1) / plants.size() > 100 * i / plants.size()) std::cout << 100 * i / plants.size() << "% bad points removed!" << std::endl; if (plants[i].size() != 1) continue; auto j = edgeList[i].begin(); uint mn = *j; for (j++; j != edgeList[i].end(); ++j) { if (length(points[i] - points[mn]) > length(points[i] - points[*j])) { mn = *j; } } //std::cout << "Nearest point found" << std::endl; mergeTwoPoints(mn, i, points[mn]); for (uint j = i + 1; j < edgeList.size(); ++j) { auto badNumIt = edgeList[j].find(i); if (badNumIt != edgeList[j].end()) { edgeList[j].erase(badNumIt); if (j != mn) edgeList[j].insert(mn); edgeList[j].insert(mn); } } //std::cout << i << " removed" << std::endl; } compressData(); repairGeometry(); } vec3 Geometry::positiveOrient(vec3 v) { if (v.x < 0) return v * -1; if (v.x > 0) return v; if (v.y < 0) return vec3(0, -v.y, -v.z); if (v.y > 0) return v; if (v.z < 0) return vec3(0, 0, -v.z); if (v.z > 0) return v; return v; } void Geometry::removePointsIntoLines() { std::cout << "Remove points into lines start: " << points.size() << ' ' << triangles.size() << std::endl; auto pointLines = getOutLines(); auto edgeList = getBidirAdjacencyListIndices(); std::vector<uint> IndexMap(points.size()); for (uint i = 0; i < pointLines.size(); ++i) { IndexMap[i] = i; if (pointLines[i].size() == 1) { int nearest = -1; for (auto j = edgeList[i].begin(); j != edgeList[i].end(); ++j) { if (IndexMap[*j] == i) continue; if (nearest == -1 || length(points[i] - points[*j]) < length(points[i] - points[nearest])) { nearest = *j; } } IndexMap[i] = nearest; } } for (uint i = 0; i < IndexMap.size(); ++i) { uint j = i; while (j != IndexMap[j]) { j = IndexMap[j]; std::cout << j << ' ' << IndexMap[j] << std::endl; } IndexMap[i] = j; points[i] = points[j]; } mergeSimilarPoints(); std::cout << "Remove points into lines end: " << points.size() << ' ' << triangles.size() << std::endl; /*///Create sets of lines for points and sets of edges //std::vector<std::set<vec3> > lines(points.size()); std::vector<std::vector<vec3> > lines(points.size()); std::vector<std::set<uint> > edgeList(points.size()); for (uint i = 0; i < edges.size(); i += 2) { uint a_ind = edges[i + 0]; uint b_ind = edges[i + 1]; vec3 a = points[a_ind].xyz(); vec3 b = points[b_ind].xyz(); vec3 line = normalize(b - a); bool flag = false; for (uint j = 0; j < lines[a_ind].size() && !flag; ++j) { flag = flag || length(cross(lines[a_ind][j], line)) < VEC_EPS; } if (!flag) { lines[a_ind].push_back(line); edgeList[a_ind].insert(b_ind); } flag = false; for (uint j = 0; j < lines[b_ind].size() && !flag; ++j) { flag = flag || length(cross(lines[b_ind][j], line)) < VEC_EPS; } if (!flag) { lines[b_ind].push_back(line); edgeList[b_ind].insert(a_ind); } } ///Remove bad points for (uint i = 0; i < points.size(); ++i) { if (lines[i].size() != 1) continue; auto j = edgeList[i].begin(); int mn = -1; for (; j != edgeList[i].end(); ++j) { //vec3 line = normalize(points[i].xyz() - points[*j].xyz()); vec3 line = lines[i][0]; if (mn == -1 || (length(points[i] - points[mn]) > length(points[i] - points[*j]) && length(cross(points[i].xyz() - points[mn].xyz(), line)) < VEC_EPS * 1e5)) { mn = *j; } } mergeTwoPoints(mn, i, points[mn]); } compressData(); repairGeometry();*/ } void Geometry::compressData() { ///Create new indices std::vector<vec4> newPoints; std::vector<uint> newIndices; std::vector<uint> indexMap(points.size()); /*for (uint i = 0; i < points.size(); ++i) { if (indices[i] == i) { indexMap[i] = newIndices.size(); newIndices.push_back(newPoints.size()); newPoints.push_back(points[i]); } } for (uint i = 0; i < indices.size(); ++i) { if (indices[i] != i) { indexMap[i] = indexMap[indices[i]]; } } for (uint i = 0; i < edges.size(); ++i) { edges[i] = indexMap[edges[i]]; } for (uint i = 0; i < triangles.size(); ++i) { triangles[i] = indexMap[triangles[i]]; } points = newPoints; indices = newIndices; ////Create index map //std::sort(removedPoints.begin(), removedPoints.end()); std::vector<uint> newIndices(points.size()); for (uint i = 0, sh = 0; i < points.size(); ++i) { if (removedPoints.size() > sh && i == removedPoints[sh]) sh++; newIndices[i] = i - sh; } ///Update edges std::vector<uint> newEdges; for (uint i = 0; i < edges.size(); i += 2) { if (edges[i] == edges[i + 1]) continue; newEdges.push_back(newIndices[edges[i]]); newEdges.push_back(newIndices[edges[i + 1]]); } edges = newEdges; ///Update triangles std::vector<uint> newTriangles; for (uint i = 0; i < triangles.size(); i += 3) { if (triangles[i] == triangles[i + 1] || triangles[i] == triangles[i + 2] || triangles[i + 1] == triangles[i + 2]) continue; newTriangles.push_back(newIndices[triangles[i]]); newTriangles.push_back(newIndices[triangles[i + 1]]); newTriangles.push_back(newIndices[triangles[i + 2]]); } triangles = newTriangles; ///Update points std::vector<vec4> newPoints; for (uint i = 0, sh = 0; i < points.size(); ++i) { if (removedPoints.size() > sh && i == removedPoints[sh]) sh++; else newPoints.push_back(points[i]); } points = newPoints; removedPoints.clear();*/ } void Geometry::compressIndices() { /*std::vector<vec4> edgeBegin; std::vector<std::vector<vec4> > edgeEnds; for (uint i = 0; i < this->edges.size(); i += 2) { vec4 a;// = points[this->edges[i]]; vec4 b;// = points[this->edges[i + 1]]; if (a == b) continue; bool flag1 = false; for (uint j = 0; j < edgeBegin.size() && !flag1; ++j) { if (a == edgeBegin[j]) { flag1 = true; bool flag2 = false; for (uint h = 0; h < edgeEnds[j].size() && !flag2; ++h) { flag2 = flag2 || edgeEnds[j][h] == b; } if (!flag2) edgeEnds[j].push_back(b); } } } std::vector<vec4> edges; for (auto i = 0; i < edgeBegin.size(); ++i) { for (auto j = 0; j < edgeEnds[i].size(); ++j) { edges.push_back(edgeBegin[i]); edges.push_back(edgeEnds[i][j]); } } loadFromEdges(edges);*/ } void Geometry::loadFromTriangles(const std::vector<vec4> &points, const std::vector<uint>& indices) { this->points = std::vector<vec4>(points.begin(), points.end()); this->triangles = std::vector<uint>(indices.begin(), indices.end()); /*this->indices = std::vector<uint>(this->points.size()); for (uint i = 0; i < this->indices.size(); ++i) this->indices[i] = i; edges.clear(); std::vector<std::set<uint> > edgeList(points.size()); for (uint i = 0; i < triangles.size(); i += 3) { sort(triangles.begin() + i, triangles.begin() + i + 3); uint a = triangles[i]; uint b = triangles[i + 1]; uint c = triangles[i + 2]; if (a < b) edgeList[a].insert(b); if (a < c) edgeList[a].insert(c); if (b < c) edgeList[b].insert(c); } for (uint i = 0; i < edgeList.size(); ++i) { for (auto j = edgeList[i].begin(); j != edgeList[i].end(); ++j) { edges.push_back(i); edges.push_back(*j); } }*/ } void Geometry::loadFromEdges(const std::vector<vec4> &edges) { std::vector<vec4> points; std::vector<uint> edgesIndices; for (uint i = 0; i < edges.size(); ++i) { bool flag = false; for (uint j = 0; j < points.size() && !flag; ++j) { flag = edges[i] == points[j]; if (flag) edgesIndices.push_back(j); } if (!flag) { points.push_back(edges[i]); edgesIndices.push_back(points.size() - 1); } } this->points = points; std::vector<std::set<uint> > edgeList(points.size()); for (uint i = 0; i < edgesIndices.size(); i += 2) { uint ind1 = std::min(edgesIndices[i], edgesIndices[i + 1]); uint ind2 = std::max(edgesIndices[i], edgesIndices[i + 1]); if (ind1 == ind2) continue; edgeList[ind1].insert(ind2); } triangles.clear(); for (uint i = 0; i < points.size(); ++i) { for (auto j = edgeList[i].begin(); j != edgeList[i].end(); ++j) { for (auto h = j; h != edgeList[i].end(); ++h) { if (*h == *j) continue; if (edgeList[*j].find(*h) != edgeList[*j].end()) { triangles.push_back(i); triangles.push_back(*j); triangles.push_back(*h); } } } } } std::vector<vec4>& Geometry::getPoints() { return points; } std::vector<uint>& Geometry::getTriangles() { return triangles; } std::vector<uint>& Geometry::getEdges() { //return edges; } const std::vector<vec4>& Geometry::getPoints() const { const std::vector<vec4> &rf = points; return rf; } const std::vector<uint>& Geometry::getTriangles() const { const std::vector<uint> &rf = triangles; return rf; } const std::vector<uint>& Geometry::getEdges() const { //const std::vector<uint> &rf = edges; //return rf; } std::vector<vec4> Geometry::getEdgesAsPoints() const { std::vector<vec4> result; //for (uint i = 0; i < edges.size(); ++i) // result.push_back(points[edges[i]]); return result; } uint Geometry::getTrianglesNumber() const { return triangles.size() / 3; } uint Geometry::getEdgesNumber() const { // return edges.size() / 2; } uint Geometry::getPointsNumber() const { return points.size(); } vec4 Geometry::getTrianglePlant(const uint index) const { vec3 a = points[triangles[3 * index + 0]].xyz(); vec3 b = points[triangles[3 * index + 1]].xyz(); vec3 c = points[triangles[3 * index + 2]].xyz(); vec3 norm = normalize(cross(b - a, c - a)); return vec4(norm, dot(norm, a)); } void Geometry::removeNullEdges() { std::vector<uint> newEdges; // for (uint i = 0; i < edges.size(); i += 2) { // if (edges[i] == edges[i + 1]) continue; // newEdges.push_back(edges[i + 0]); // newEdges.push_back(edges[i + 1]); //} //edges = newEdges; } void Geometry::mergeSimilarPoints() { std::cout << "Merge similar points begin: " << points.size() << ' ' << triangles.size() << std::endl; std::vector<vec4> goodPoints; std::vector<uint> IndexMap(points.size()); for (uint i = 0; i < points.size(); ++i) { bool flag = false; uint goodInd; for (uint j = 0; j < goodPoints.size() && !flag; ++j) { goodInd = j; flag = points[i] == goodPoints[j]; } if (flag) IndexMap[i] = goodInd; else { IndexMap[i] = goodPoints.size(); goodPoints.push_back(points[i]); } } points = goodPoints; std::vector<uint> newTri; for (uint i = 0; i < triangles.size(); i += 3) { triangles[i + 0] = IndexMap[triangles[i + 0]]; triangles[i + 1] = IndexMap[triangles[i + 1]]; triangles[i + 2] = IndexMap[triangles[i + 2]]; sort(triangles.begin() + i, triangles.begin() + i + 3); if (triangles[i] == triangles[i + 1] || triangles[i + 1] == triangles[i + 2]) continue; newTri.push_back(triangles[i + 0]); newTri.push_back(triangles[i + 1]); newTri.push_back(triangles[i + 2]); } triangles = newTri; std::cout << "Merge similar points end: " << points.size() << ' ' << triangles.size() << std::endl; } void Geometry::removeBadTriangles() { std::vector<uint> newTriangles; for (uint i = 0; i < triangles.size(); i += 3) { sort(triangles.begin() + i, triangles.begin() + i + 3); if (triangles[i] == triangles[i + 1] || triangles[i + 1] == triangles[i + 2]) continue; newTriangles.push_back(triangles[i + 0]); newTriangles.push_back(triangles[i + 1]); newTriangles.push_back(triangles[i + 2]); } triangles = newTriangles; } void Geometry::removeSmallTriangles(const float minSqure) { std::cout << "Remove small triangles begin: " << points.size() << ' ' << triangles.size() << std::endl; uint cnt = 0; for (uint i = 0; i < triangles.size(); i += 3) { if (100 * (i + 3) / triangles.size() > 100 * i / triangles.size()) std::cout << 100 * i / triangles.size() << "% small triangles removed " << cnt << std::endl; vec4 a = points[triangles[i + 0]]; vec4 b = points[triangles[i + 1]]; vec4 c = points[triangles[i + 2]]; if (length(cross((a - b).xyz(), (a - c).xyz()) / 2) < minSqure / 100) { cnt++; mergeTwoPoints(triangles[i], triangles[i + 1], (a + b + c) / 3); mergeTwoPoints(triangles[i], triangles[i + 2], (a + b + c) / 3); } } std::cout << "Remove small triangles end: " << points.size() << ' ' << triangles.size() << std::endl; } void Geometry::removeEqualEdges() { /*std::vector<std::set<uint> > edgeList(points.size()); for (uint i = 0; i < edges.size(); i += 2) { sort(edges.begin() + i, edges.begin() + i + 2); edgeList[edges[i]].insert(edges[i + 1]); } std::vector<uint> newEdges; for (uint i = 0; i < edgeList.size(); ++i) { for (auto j = edgeList[i].begin(); j != edgeList[i].end(); ++j) { newEdges.push_back(i); newEdges.push_back(*j); } } edges = newEdges;*/ } void Geometry::repairGeometry() { /*std::cout << points.size() << ' ' << edges.size() << ' ' << triangles.size() << std::endl; mergeSimilarPoints(); std::cout << points.size() << ' ' << edges.size() << ' ' << triangles.size() << std::endl; removeNullEdges(); std::cout << points.size() << ' ' << edges.size() << ' ' << triangles.size() << std::endl; removeEqualEdges(); std::cout << points.size() << ' ' << edges.size() << ' ' << triangles.size() << std::endl; removeBadTriangles(); std::cout << points.size() << ' ' << edges.size() << ' ' << triangles.size() << std::endl;*/ } void Geometry::Write(const std::string &path) const { std::ofstream out(path); out << points.size() << std::endl; out.precision(10); for (auto v: points) out << std::fixed << v.x << ' ' << std::fixed << v.y << ' ' << std::fixed << v.z << ' ' << std::fixed << v.w << ' '; out << std::endl << triangles.size() << std::endl; for (auto i: triangles) out << i << ' '; out.close(); } void Geometry::Read(const std::string &path) { std::ifstream in(path); uint pC; in >> pC; points.resize(pC); for (uint i = 0; i < pC; ++i) { vec4 v; in >> v.x >> v.y >> v.z >> v.w; points[i] = v; } in >> pC; triangles.resize(pC); for (uint i = 0; i < pC; ++i) in >> triangles[i]; in.close(); } std::vector<std::set<uint> > Geometry::getAdjacencyListIndices() { std::vector<std::set<uint> > result(points.size()); for (uint i = 0; i < triangles.size(); i += 3) { std::sort(triangles.begin() + i, triangles.begin() + i + 3); result[triangles[i + 0]].insert(triangles[i + 1]); result[triangles[i + 0]].insert(triangles[i + 2]); result[triangles[i + 1]].insert(triangles[i + 2]); } return result; } std::vector<uint> Geometry::getEdgeListIndices(){ std::vector<uint> result; auto adjListInd = getAdjacencyListIndices(); for (uint i = 0; i < adjListInd.size(); ++i) { for (auto j = adjListInd[i].begin(); j != adjListInd[i].end(); ++j) { result.push_back(i); result.push_back(*j); } } return result; } std::vector<vec4> Geometry::getEdgeList(){ std::vector<vec4> result; auto edgeList = getEdgeListIndices(); for (uint i = 0; i < edgeList.size(); ++i) { result.push_back(points[edgeList[i]]); } return result; } std::vector<std::vector<vec4> > Geometry::getOutLines() { std::vector<std::vector<vec4> > result(points.size()); auto edgeList = getAdjacencyListIndices(); for (uint i = 0; i < points.size(); ++i) { for (auto j = edgeList[i].begin(); j != edgeList[i].end(); ++j) { vec4 newVec = points[*j] - points[i]; bool flag = true; for (uint h = 0; h < result[i].size() && flag; ++h) flag = length(cross(newVec.xyz(), result[i][h].xyz())) >= VEC_EPS; if (flag) result[i].push_back(newVec); } } return result; } std::vector<std::set<uint> > Geometry::getBidirAdjacencyListIndices() { std::vector<std::set<uint> > result(points.size()); for (uint i = 0; i < triangles.size(); i += 3) { result[triangles[i + 0]].insert(triangles[i + 1]); result[triangles[i + 0]].insert(triangles[i + 2]); result[triangles[i + 1]].insert(triangles[i + 0]); result[triangles[i + 1]].insert(triangles[i + 2]); result[triangles[i + 2]].insert(triangles[i + 0]); result[triangles[i + 2]].insert(triangles[i + 1]); } return result; } std::vector<uint> splitPolygonByTriangles(const std::vector<uint> &polygon) { //std::cout << "Split polygons by triangles begin" << std::endl; std::vector<uint> result; for (uint i = 2; i < polygon.size(); ++i) { result.push_back(polygon[0]); result.push_back(polygon[i - 1]); result.push_back(polygon[i]); } //std::cout << "Split polygons by triangles end" << std::endl; return result; } std::vector<std::vector<uint> > mergeTriangles(const std::vector<std::vector<uint> > &triangles) { //std::cout << "Merge triangles begin" << std::endl; std::map<uint, std::map<uint, uint> > neibors; for (uint i = 0; i < triangles.size(); i++) { neibors[triangles[i][0]][triangles[i][1]]++; neibors[triangles[i][0]][triangles[i][2]]++; neibors[triangles[i][1]][triangles[i][0]]++; neibors[triangles[i][1]][triangles[i][2]]++; neibors[triangles[i][2]][triangles[i][1]]++; neibors[triangles[i][2]][triangles[i][0]]++; } std::set<uint> cont; for (auto i = neibors.begin(); i != neibors.end(); ++i) { uint sum = 0; for (auto j = i->second.begin(); j != i->second.end(); ++j) sum += j->second & 1; if (sum) cont.insert(i->first); } std::map<uint, std::set<uint> > edgeList; for (uint i = 0; i < triangles.size(); ++i) { std::vector<uint> subcont; for (uint j = 0; j < 3; ++j) if (cont.find(triangles[i][j]) != cont.end()) subcont.push_back(triangles[i][j]); for (uint j = 0; j < subcont.size(); ++j) { for (uint h = 0; h < subcont.size(); ++h) { if (h == j) continue; edgeList[triangles[i][j]].insert(triangles[i][h]); } } } std::vector<std::vector<uint> > result; std::set<uint> removed; for (auto i = cont.begin(); i != cont.end(); ++i) { uint value = *i; if (removed.find(value) != removed.end()) continue; result.push_back(std::vector<uint>()); while (removed.find(value) == removed.end()) { result.back().push_back(value); removed.insert(value); for (auto j = edgeList[value].begin(); j != edgeList[value].end(); ++j) if (removed.find(*j) == removed.end() && cont.find(*j) != cont.end()) { value = *j; break; } } } //std::cout << "Merge triangles end" << std::endl; return result; } void Geometry::removeExcessPoints() { std::cout << "Remove excess points begin" << std::endl; std::set<uint> badPoints; for (uint i = 0; i < points.size(); ++i) badPoints.insert(i); for (uint i = 0; i < triangles.size(); ++i) badPoints.erase(triangles[i]); std::vector<vec4> newPoints; std::vector<uint> newInd(points.size()); for (uint i = 0; i < points.size(); ++i) { if (badPoints.find(i) == badPoints.end()) { newInd[i] = newPoints.size(); newPoints.push_back(points[i]); } } points = newPoints; for (uint i = 0; i < triangles.size(); ++i) triangles[i] = newInd[triangles[i]]; std::cout << "Remove excess points end" << std::endl; } std::vector<std::vector<uint> > removeNotAnglePoints(const std::vector<std::vector<uint> > &polys, const std::vector<vec4> points) { std::vector<std::vector<uint> > res(polys.size()); for (uint i = 0; i < polys.size(); ++i) { vec3 direct = (points[polys[i][0]] - points[polys[i][1]]).xyz(); for (uint j = 0; j < polys[i].size(); ++j) { vec3 newDir = (points[polys[i][(j + 1) % polys[i].size()]] - points[polys[i][j]]).xyz(); if (length(cross(direct, newDir)) > VEC_EPS) { res[i].push_back(polys[i][j]); } direct = newDir; } } return res; } std::vector<std::vector<std::vector<uint> > > Geometry::groupTrianglesByPlanes() { std::cout << "Group triangles by planes begin" << std::endl; std::vector<std::vector<std::vector<uint> > > result; std::vector<vec4> planes; for (uint i = 0; i < triangles.size(); i += 3) { vec4 plane = getTrianglePlant(i / 3); uint ind = 0; for (; ind < planes.size() && planes[ind] != plane; ++ind); if (ind == planes.size()) { planes.push_back(plane); result.resize(result.size() + 1); } result[ind].push_back(std::vector<uint>(triangles.begin() + i, triangles.begin() + i + 3)); } std::cout << "Group triangles by planes end" << std::endl; return result; } void Geometry::removeInternalPoints() { std::cout << "Remove internal points begin" << std::endl; std::vector<uint> newTriangles; for (auto &plant: groupTrianglesByPlanes()) { for (auto &polygon: mergeTriangles(plant)) { for (auto i: splitPolygonByTriangles(polygon)) { newTriangles.push_back(i); } } break; } triangles = newTriangles; removeExcessPoints(); std::cout << "Remove internal points end" << std::endl; } void Geometry::FirstPlane() { auto plant = groupTrianglesByPlanes()[0]; std::vector<uint> newTriangles; for (uint i = 0; i < plant.size(); ++i) for (uint j = 0; j < plant[i].size(); ++j) newTriangles.push_back(plant[i][j]); triangles = newTriangles; removeExcessPoints(); }
a7bcdc72e709f1eccbdd82ae91bed9a5f93fc4fd
af0ecafb5428bd556d49575da2a72f6f80d3d14b
/CodeJamCrawler/dataset/14_23342_6.cpp
1c3fcb70c1814aa6784be1ce3fcca0152aed4d0f
[]
no_license
gbrlas/AVSP
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
e259090bf282694676b2568023745f9ffb6d73fd
refs/heads/master
2021-06-16T22:25:41.585830
2017-06-09T06:32:01
2017-06-09T06:32:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
#include <iostream> #include <set> #include <vector> using namespace std; int main() { int t,T; cin >> T; int board[4][4]; set<int> s; int i,j; for( t = 0; t < T; t++) { int row; cin >> row; for( i = 0; i < 4; i++ ) { for( j = 0; j < 4; j++ ) { cin >> board[i][j]; } } s.clear(); for( i = 0; i < 4; i++ ) { s.insert(board[row-1][i]); } cin >> row; for( i = 0; i < 4; i++) { for( j = 0; j < 4; j++ ) { cin >> board[i][j]; } } vector<int> result; result.clear(); for( i = 0; i < 4; i++ ) { if( s.find(board[row-1][i]) != s.end() ) { result.push_back(board[row-1][i]); } } cout << "Case #" << (t+1) << ": "; if( result.size() == 1 ) cout << result[0]; else if( result.size() > 1 ) cout << "Bad magician!"; else cout << "Volunteer cheated!"; cout << endl; } return 0; }
89112359f67cf7c373905735e2fc41664359413b
d8010b0cfced1c941e632ed4cc927d20d7b7bf95
/devel/include/inspire_hand/set_gesture_noRequest.h
2d4d0366095439eb5125a2c9c97464d14a20d022
[]
no_license
ZJU-Robotics-Lab/motion-retargeting-rl
b143b7695d8813edc12def6e218975ad8a499329
073a511edfad5b758537d4564a05fea43c229004
refs/heads/master
2022-11-29T13:57:33.736198
2020-07-28T08:04:20
2020-07-28T08:04:20
283,143,525
1
1
null
null
null
null
UTF-8
C++
false
false
5,208
h
// Generated by gencpp from file inspire_hand/set_gesture_noRequest.msg // DO NOT EDIT! #ifndef INSPIRE_HAND_MESSAGE_SET_GESTURE_NOREQUEST_H #define INSPIRE_HAND_MESSAGE_SET_GESTURE_NOREQUEST_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace inspire_hand { template <class ContainerAllocator> struct set_gesture_noRequest_ { typedef set_gesture_noRequest_<ContainerAllocator> Type; set_gesture_noRequest_() : gesture_no(0) { } set_gesture_noRequest_(const ContainerAllocator& _alloc) : gesture_no(0) { (void)_alloc; } typedef int32_t _gesture_no_type; _gesture_no_type gesture_no; typedef boost::shared_ptr< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> const> ConstPtr; }; // struct set_gesture_noRequest_ typedef ::inspire_hand::set_gesture_noRequest_<std::allocator<void> > set_gesture_noRequest; typedef boost::shared_ptr< ::inspire_hand::set_gesture_noRequest > set_gesture_noRequestPtr; typedef boost::shared_ptr< ::inspire_hand::set_gesture_noRequest const> set_gesture_noRequestConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> & v) { ros::message_operations::Printer< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace inspire_hand namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > { static const char* value() { return "ea289c543a56bf8388893db17ebece7f"; } static const char* value(const ::inspire_hand::set_gesture_noRequest_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xea289c543a56bf83ULL; static const uint64_t static_value2 = 0x88893db17ebece7fULL; }; template<class ContainerAllocator> struct DataType< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > { static const char* value() { return "inspire_hand/set_gesture_noRequest"; } static const char* value(const ::inspire_hand::set_gesture_noRequest_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > { static const char* value() { return "int32 gesture_no\n\ "; } static const char* value(const ::inspire_hand::set_gesture_noRequest_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.gesture_no); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct set_gesture_noRequest_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::inspire_hand::set_gesture_noRequest_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::inspire_hand::set_gesture_noRequest_<ContainerAllocator>& v) { s << indent << "gesture_no: "; Printer<int32_t>::stream(s, indent + " ", v.gesture_no); } }; } // namespace message_operations } // namespace ros #endif // INSPIRE_HAND_MESSAGE_SET_GESTURE_NOREQUEST_H
8596d0c908734000468bf1781892c9fbc28d0e06
5852e3aab5677d380c22b2de9508ab043ea28657
/Console Test Chess/FieldG2.cpp
8ed116c7f0c837b1b6f13e665eb8affbdd5bab2a
[]
no_license
ongornbk/Chessy
b1307df6f8bdc95780094d1aa8be709e30f64754
efa0b2cdf0e6d60084b51e409414207f6a01a637
refs/heads/master
2023-04-16T09:54:36.266850
2021-05-01T18:47:40
2021-05-01T18:47:40
363,280,402
0
0
null
null
null
null
UTF-8
C++
false
false
711
cpp
#include "FieldG2.h" const __int64 _stdcall FieldG2::GetIndex() const noexcept { return FIELD_G2; } modern_array<IField*>& FieldG2::GetWhitePawnMoves() { modern_array<IField*>* fields = new modern_array<IField*>(2); if (m_board->GetFieldByIndex(FIELD_F3)->HasBlackPiece()) fields->push_back(m_board->GetFieldByIndex(FIELD_F3)); if (m_board->GetFieldByIndex(FIELD_H3)->HasBlackPiece()) fields->push_back(m_board->GetFieldByIndex(FIELD_H3)); if (m_board->GetFieldByIndex(FIELD_G3)->IsEmpty()) fields->push_back(m_board->GetFieldByIndex(FIELD_G3)); else return *fields; if (m_board->GetFieldByIndex(FIELD_G4)->IsEmpty()) fields->push_back(m_board->GetFieldByIndex(FIELD_G4)); return *fields; }
[ "MSI@DESKTOP-RIEGR2K" ]
MSI@DESKTOP-RIEGR2K
f7f10f51d693d004eb5da32e3c014a83e2fba750
66c92642dada5d01da0be5e855b663d9081f1b6d
/Matrices/matrix_snake_pattern.cpp
e44b8196ff17f83f65347cdcd06eebf4e4ca640c
[]
no_license
PranavUpadhyay7/DSA_GeeksForGeeks
9a73237b3b1279c97fc123bd401fba7e5f39d75d
6afa41d3da871e2678a243f3ff17e8f60415df9a
refs/heads/main
2023-08-21T12:35:45.601356
2021-10-06T13:11:34
2021-10-06T13:11:34
414,212,330
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
#include <bits/stdc++.h> using namespace std; class Solution { public: //Function to return list of integers visited in snake pattern in matrix. vector<int> snakePattern(vector<vector<int> > matrix) { vector<int> result; for(int i=0; i<matrix.size(); i++) { if (i % 2 == 0) { for(int j=0; j<matrix[0].size(); j++) { result.push_back(matrix[i][j]); } } else { for(int j=matrix[0].size()-1; j>=0; j--) { result.push_back(matrix[i][j]); } } } return result; } }; int main() { int t; cin>>t; while(t--) { int n; cin>>n; vector<vector<int> > matrix(n); for(int i=0; i<n; i++) { matrix[i].assign(n, 0); for( int j=0; j<n; j++) { cin>>matrix[i][j]; } } Solution ob; vector<int> result = ob.snakePattern(matrix); for (int i = 0; i < result.size(); ++i) cout<<result[i]<<" "; cout<<endl; } return 0; }
d93b7a1c7fd1e77c85d5c9a69ce93b1f4e2a367a
4002bc4433e1493cea98d1a54a3247c7a14cd39d
/ejemplo 3.cpp
fa6f660fe7a64edc9bc106910aeb374269db4a48
[]
no_license
rafaelapure82/C-Parte-3
481e8cea7afdf6df105e15d5c0096d16766374a1
ec33f0afc12c68dcab50541abc0e6a77de610f58
refs/heads/master
2021-09-04T12:38:40.801038
2018-01-18T18:53:53
2018-01-18T18:53:53
118,021,386
0
0
null
null
null
null
UTF-8
C++
false
false
336
cpp
#include <iostream> // ejemplo 3 #include <string> using namespace std; int main() { string s1 = "Hola ", s3="maria"; string s2="maria"; s2 = "carlos"; //Cambio del valor de la variable string s = s1 + s2; cout << s1 << s2 << '\n'; //Primer mensaje cout << s << '\n'; //Segundo Mensaje s += '\n'; cout << s;//Tercer mensaje }
[ "ing.rafaelmontenegro" ]
ing.rafaelmontenegro
8d372dcf75a92c930d581fc96e6cfc70265a206b
97398fef26adee8f02d173d1355abed2f8ff5ffa
/ue.spat/externals/ue.binaural.decoder~.mxo/ue.binaural.decoder.cpp
2c04161cca7b8958e3173cecfbfe20eda182c3dc
[]
no_license
etiennedemoulin/spat4unreal
ccb2feb8f7f7accb7c89cc8e59af4e4541db15b0
5a40feca322884eb52d9d51c7a25216f73ef7a9c
refs/heads/master
2022-12-09T15:39:02.380492
2020-08-29T23:23:16
2020-08-29T23:23:16
290,445,185
0
0
null
null
null
null
UTF-8
C++
false
false
598,428
cpp
/* ------------------------------------------------------------ author: "Pierre Lecomte" copyright: "(c) Pierre Lecomte 2015" license: "GPL)" name: "Binaural decoder" version: "1.0" Code generated with Faust 2.26.2 (https://faust.grame.fr) Compilation options: -lang cpp -double -ftz 0 ------------------------------------------------------------ */ #ifndef __ue_binaural_decoder_H__ #define __ue_binaural_decoder_H__ /************************************************************************ IMPORTANT NOTE : this file contains two clearly delimited sections : the ARCHITECTURE section (in two parts) and the USER section. Each section is governed by its own copyright and license. Please check individually each section for license and copyright information. *************************************************************************/ /*******************BEGIN ARCHITECTURE SECTION (part 1/2)****************/ /************************************************************************ FAUST Architecture File Copyright (C) 2004-2020 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. MAX MSP SDK : in order to compile a MaxMSP external with this architecture file you will need the official MaxMSP SDK from cycling'74. Please check the corresponding license. ************************************************************************ ************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <limits.h> #include <errno.h> #include <time.h> #include <unistd.h> #include <fcntl.h> #include <assert.h> #include <string> #include <vector> #include <map> #include <iostream> #include <fstream> #include <sstream> #ifdef __APPLE__ #include <Carbon/Carbon.h> #include <unistd.h> #endif #ifdef WIN32 #ifndef NAN static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; #define NAN (*(const float *) __nan) #endif #endif // FAUSTFLOAT is setup by faust2max6 /************************** BEGIN UI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2020 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __UI_H__ #define __UI_H__ #ifndef FAUSTFLOAT #define FAUSTFLOAT float #endif /******************************************************************************* * UI : Faust DSP User Interface * User Interface as expected by the buildUserInterface() method of a DSP. * This abstract class contains only the method that the Faust compiler can * generate to describe a DSP user interface. ******************************************************************************/ struct Soundfile; template <typename REAL> struct UIReal { UIReal() {} virtual ~UIReal() {} // -- widget's layouts virtual void openTabBox(const char* label) = 0; virtual void openHorizontalBox(const char* label) = 0; virtual void openVerticalBox(const char* label) = 0; virtual void closeBox() = 0; // -- active widgets virtual void addButton(const char* label, REAL* zone) = 0; virtual void addCheckButton(const char* label, REAL* zone) = 0; virtual void addVerticalSlider(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) = 0; virtual void addHorizontalSlider(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) = 0; virtual void addNumEntry(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) = 0; // -- passive widgets virtual void addHorizontalBargraph(const char* label, REAL* zone, REAL min, REAL max) = 0; virtual void addVerticalBargraph(const char* label, REAL* zone, REAL min, REAL max) = 0; // -- soundfiles virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) = 0; // -- metadata declarations virtual void declare(REAL* zone, const char* key, const char* val) {} }; struct UI : public UIReal<FAUSTFLOAT> { UI() {} virtual ~UI() {} }; #endif /************************** END UI.h **************************/ /************************** BEGIN SimpleParser.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef SIMPLEPARSER_H #define SIMPLEPARSER_H // --------------------------------------------------------------------- // Simple Parser // A parser returns true if it was able to parse what it is // supposed to parse and advance the pointer. Otherwise it returns false // and the pointer is not advanced so that another parser can be tried. // --------------------------------------------------------------------- #include <vector> #include <map> #include <string> #include <fstream> #include <sstream> #include <iostream> #include <ctype.h> #ifndef _WIN32 # pragma GCC diagnostic ignored "-Wunused-function" #endif struct itemInfo { std::string type; std::string label; std::string url; std::string address; int index; double init; double min; double max; double step; std::vector<std::pair<std::string, std::string> > meta; itemInfo():index(0), init(0.), min(0.), max(0.), step(0.) {} }; // --------------------------------------------------------------------- // Elementary parsers // --------------------------------------------------------------------- // Report a parsing error static bool parseError(const char*& p, const char* errmsg) { std::cerr << "Parse error : " << errmsg << " here : " << p << std::endl; return true; } /** * @brief skipBlank : advance pointer p to the first non blank character * @param p the string to parse, then the remaining string */ static void skipBlank(const char*& p) { while (isspace(*p)) { p++; } } // Parse character x, but don't report error if fails static bool tryChar(const char*& p, char x) { skipBlank(p); if (x == *p) { p++; return true; } else { return false; } } /** * @brief parseChar : parse a specific character x * @param p the string to parse, then the remaining string * @param x the character to recognize * @return true if x was found at the begin of p */ static bool parseChar(const char*& p, char x) { skipBlank(p); if (x == *p) { p++; return true; } else { return false; } } /** * @brief parseWord : parse a specific string w * @param p the string to parse, then the remaining string * @param w the string to recognize * @return true if string w was found at the begin of p */ static bool parseWord(const char*& p, const char* w) { skipBlank(p); const char* saved = p; // to restore position if we fail while ((*w == *p) && (*w)) {++w; ++p;} if (*w) { p = saved; return false; } else { return true; } } /** * @brief parseDouble : parse number [s]dddd[.dddd] and store the result in x * @param p the string to parse, then the remaining string * @param x the float number found if any * @return true if a float number was found at the begin of p */ static bool parseDouble(const char*& p, double& x) { std::stringstream reader(p); std::streambuf* pbuf = reader.rdbuf(); // Keep position before parsing std::streamsize size1 = pbuf->in_avail(); // Parse the number reader >> x; // Keep position after parsing std::streamsize size2 = pbuf->in_avail(); // Move from the actual size p += (size1 - size2); // True if the number contains at least one digit return (size1 > size2); } /** * @brief parseString, parse an arbitrary quoted string q...q and store the result in s * @param p the string to parse, then the remaining string * @param quote the character used to quote the string * @param s the (unquoted) string found if any * @return true if a string was found at the begin of p */ static bool parseString(const char*& p, char quote, std::string& s) { std::string str; skipBlank(p); const char* saved = p; // to restore position if we fail if (*p++ == quote) { while ((*p != 0) && (*p != quote)) { str += *p++; } if (*p++ == quote) { s = str; return true; } } p = saved; return false; } /** * @brief parseSQString, parse a single quoted string '...' and store the result in s * @param p the string to parse, then the remaining string * @param s the (unquoted) string found if any * @return true if a string was found at the begin of p */ static bool parseSQString(const char*& p, std::string& s) { return parseString(p, '\'', s); } /** * @brief parseDQString, parse a double quoted string "..." and store the result in s * @param p the string to parse, then the remaining string * @param s the (unquoted) string found if any * @return true if a string was found at the begin of p */ static bool parseDQString(const char*& p, std::string& s) { return parseString(p, '"', s); } // --------------------------------------------------------------------- // // IMPLEMENTATION // // --------------------------------------------------------------------- /** * @brief parseMenuItem, parse a menu item ...'low':440.0... * @param p the string to parse, then the remaining string * @param name the name found * @param value the value found * @return true if a nemu item was found */ static bool parseMenuItem(const char*& p, std::string& name, double& value) { const char* saved = p; // to restore position if we fail if (parseSQString(p, name) && parseChar(p, ':') && parseDouble(p, value)) { return true; } else { p = saved; return false; } } static bool parseMenuItem2(const char*& p, std::string& name) { const char* saved = p; // to restore position if we fail // single quoted if (parseSQString(p, name)) { return true; } else { p = saved; return false; } } /** * @brief parseMenuList, parse a menu list {'low' : 440.0; 'mid' : 880.0; 'hi' : 1760.0}... * @param p the string to parse, then the remaining string * @param names the vector of names found * @param values the vector of values found * @return true if a menu list was found */ static bool parseMenuList(const char*& p, std::vector<std::string>& names, std::vector<double>& values) { std::vector<std::string> tmpnames; std::vector<double> tmpvalues; const char* saved = p; // to restore position if we fail if (parseChar(p, '{')) { do { std::string n; double v; if (parseMenuItem(p, n, v)) { tmpnames.push_back(n); tmpvalues.push_back(v); } else { p = saved; return false; } } while (parseChar(p, ';')); if (parseChar(p, '}')) { // we suceeded names = tmpnames; values = tmpvalues; return true; } } p = saved; return false; } static bool parseMenuList2(const char*& p, std::vector<std::string>& names, bool debug) { std::vector<std::string> tmpnames; const char* saved = p; // to restore position if we fail if (parseChar(p, '{')) { do { std::string n; if (parseMenuItem2(p, n)) { tmpnames.push_back(n); } else { goto error; } } while (parseChar(p, ';')); if (parseChar(p, '}')) { // we suceeded names = tmpnames; return true; } } error: if (debug) { std::cerr << "parseMenuList2 : (" << saved << ") is not a valid list !\n"; } p = saved; return false; } /// --------------------------------------------------------------------- // Parse list of strings /// --------------------------------------------------------------------- static bool parseList(const char*& p, std::vector<std::string>& items) { const char* saved = p; // to restore position if we fail if (parseChar(p, '[')) { do { std::string item; if (!parseDQString(p, item)) { p = saved; return false; } items.push_back(item); } while (tryChar(p, ',')); return parseChar(p, ']'); } else { p = saved; return false; } } static bool parseMetaData(const char*& p, std::map<std::string, std::string>& metadatas) { const char* saved = p; // to restore position if we fail std::string metaKey, metaValue; if (parseChar(p, ':') && parseChar(p, '[')) { do { if (parseChar(p, '{') && parseDQString(p, metaKey) && parseChar(p, ':') && parseDQString(p, metaValue) && parseChar(p, '}')) { metadatas[metaKey] = metaValue; } } while (tryChar(p, ',')); return parseChar(p, ']'); } else { p = saved; return false; } } static bool parseItemMetaData(const char*& p, std::vector<std::pair<std::string, std::string> >& metadatas) { const char* saved = p; // to restore position if we fail std::string metaKey, metaValue; if (parseChar(p, ':') && parseChar(p, '[')) { do { if (parseChar(p, '{') && parseDQString(p, metaKey) && parseChar(p, ':') && parseDQString(p, metaValue) && parseChar(p, '}')) { metadatas.push_back(std::make_pair(metaKey, metaValue)); } } while (tryChar(p, ',')); return parseChar(p, ']'); } else { p = saved; return false; } } // --------------------------------------------------------------------- // Parse metadatas of the interface: // "name" : "...", "inputs" : "...", "outputs" : "...", ... // and store the result as key/value /// --------------------------------------------------------------------- static bool parseGlobalMetaData(const char*& p, std::string& key, std::string& value, double& dbl, std::map<std::string, std::string>& metadatas, std::vector<std::string>& items) { const char* saved = p; // to restore position if we fail if (parseDQString(p, key)) { if (key == "meta") { return parseMetaData(p, metadatas); } else { return parseChar(p, ':') && (parseDQString(p, value) || parseList(p, items) || parseDouble(p, dbl)); } } else { p = saved; return false; } } // --------------------------------------------------------------------- // Parse gui: // "type" : "...", "label" : "...", "address" : "...", ... // and store the result in uiItems Vector /// --------------------------------------------------------------------- static bool parseUI(const char*& p, std::vector<itemInfo>& uiItems, int& numItems) { const char* saved = p; // to restore position if we fail if (parseChar(p, '{')) { std::string label; std::string value; double dbl = 0; do { if (parseDQString(p, label)) { if (label == "type") { if (uiItems.size() != 0) { numItems++; } if (parseChar(p, ':') && parseDQString(p, value)) { itemInfo item; item.type = value; uiItems.push_back(item); } } else if (label == "label") { if (parseChar(p, ':') && parseDQString(p, value)) { uiItems[numItems].label = value; } } else if (label == "url") { if (parseChar(p, ':') && parseDQString(p, value)) { uiItems[numItems].url = value; } } else if (label == "address") { if (parseChar(p, ':') && parseDQString(p, value)) { uiItems[numItems].address = value; } } else if (label == "index") { if (parseChar(p, ':') && parseDouble(p, dbl)) { uiItems[numItems].index = int(dbl); } } else if (label == "meta") { if (!parseItemMetaData(p, uiItems[numItems].meta)) { return false; } } else if (label == "init") { if (parseChar(p, ':') && parseDouble(p, dbl)) { uiItems[numItems].init = dbl; } } else if (label == "min") { if (parseChar(p, ':') && parseDouble(p, dbl)) { uiItems[numItems].min = dbl; } } else if (label == "max") { if (parseChar(p, ':') && parseDouble(p, dbl)) { uiItems[numItems].max = dbl; } } else if (label == "step") { if (parseChar(p, ':') && parseDouble(p, dbl)) { uiItems[numItems].step = dbl; } } else if (label == "items") { if (parseChar(p, ':') && parseChar(p, '[')) { do { if (!parseUI(p, uiItems, numItems)) { p = saved; return false; } } while (tryChar(p, ',')); if (parseChar(p, ']')) { itemInfo item; item.type = "close"; uiItems.push_back(item); numItems++; } } } } else { p = saved; return false; } } while (tryChar(p, ',')); return parseChar(p, '}'); } else { return true; // "items": [] is valid } } // --------------------------------------------------------------------- // Parse full JSON record describing a JSON/Faust interface : // {"metadatas": "...", "ui": [{ "type": "...", "label": "...", "items": [...], "address": "...","init": "...", "min": "...", "max": "...","step": "..."}]} // // and store the result in map Metadatas and vector containing the items of the interface. Returns true if parsing was successfull. /// --------------------------------------------------------------------- static bool parseJson(const char*& p, std::map<std::string, std::pair<std::string, double> >& metaDatas0, std::map<std::string, std::string>& metaDatas1, std::map<std::string, std::vector<std::string> >& metaDatas2, std::vector<itemInfo>& uiItems) { parseChar(p, '{'); do { std::string key; std::string value; double dbl = 0; std::vector<std::string> items; if (parseGlobalMetaData(p, key, value, dbl, metaDatas1, items)) { if (key != "meta") { // keep "name", "inputs", "outputs" key/value pairs if (items.size() > 0) { metaDatas2[key] = items; items.clear(); } else if (value != "") { metaDatas0[key].first = value; } else { metaDatas0[key].second = dbl; } } } else if (key == "ui") { int numItems = 0; parseChar(p, '[') && parseUI(p, uiItems, numItems); } } while (tryChar(p, ',')); return parseChar(p, '}'); } #endif // SIMPLEPARSER_H /************************** END SimpleParser.h **************************/ /************************** BEGIN PathBuilder.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef FAUST_PATHBUILDER_H #define FAUST_PATHBUILDER_H #include <vector> #include <string> #include <algorithm> /******************************************************************************* * PathBuilder : Faust User Interface * Helper class to build complete hierarchical path for UI items. ******************************************************************************/ class PathBuilder { protected: std::vector<std::string> fControlsLevel; public: PathBuilder() {} virtual ~PathBuilder() {} std::string buildPath(const std::string& label) { std::string res = "/"; for (size_t i = 0; i < fControlsLevel.size(); i++) { res += fControlsLevel[i]; res += "/"; } res += label; std::replace(res.begin(), res.end(), ' ', '_'); return res; } void pushLabel(const std::string& label) { fControlsLevel.push_back(label); } void popLabel() { fControlsLevel.pop_back(); } }; #endif // FAUST_PATHBUILDER_H /************************** END PathBuilder.h **************************/ /************************** BEGIN dsp-combiner.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2019 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __dsp_combiner__ #define __dsp_combiner__ #include <string.h> #include <string> #include <assert.h> #include <sstream> /************************** BEGIN dsp.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __dsp__ #define __dsp__ #include <string> #include <vector> #ifndef FAUSTFLOAT #define FAUSTFLOAT float #endif struct UI; struct Meta; /** * DSP memory manager. */ struct dsp_memory_manager { virtual ~dsp_memory_manager() {} virtual void* allocate(size_t size) = 0; virtual void destroy(void* ptr) = 0; }; /** * Signal processor definition. */ class dsp { public: dsp() {} virtual ~dsp() {} /* Return instance number of audio inputs */ virtual int getNumInputs() = 0; /* Return instance number of audio outputs */ virtual int getNumOutputs() = 0; /** * Trigger the ui_interface parameter with instance specific calls * to 'openTabBox', 'addButton', 'addVerticalSlider'... in order to build the UI. * * @param ui_interface - the user interface builder */ virtual void buildUserInterface(UI* ui_interface) = 0; /* Returns the sample rate currently used by the instance */ virtual int getSampleRate() = 0; /** * Global init, calls the following methods: * - static class 'classInit': static tables initialization * - 'instanceInit': constants and instance state initialization * * @param sample_rate - the sampling rate in Hertz */ virtual void init(int sample_rate) = 0; /** * Init instance state * * @param sample_rate - the sampling rate in Hertz */ virtual void instanceInit(int sample_rate) = 0; /** * Init instance constant state * * @param sample_rate - the sampling rate in Hertz */ virtual void instanceConstants(int sample_rate) = 0; /* Init default control parameters values */ virtual void instanceResetUserInterface() = 0; /* Init instance state (delay lines...) */ virtual void instanceClear() = 0; /** * Return a clone of the instance. * * @return a copy of the instance on success, otherwise a null pointer. */ virtual dsp* clone() = 0; /** * Trigger the Meta* parameter with instance specific calls to 'declare' (key, value) metadata. * * @param m - the Meta* meta user */ virtual void metadata(Meta* m) = 0; /** * DSP instance computation, to be called with successive in/out audio buffers. * * @param count - the number of frames to compute * @param inputs - the input audio buffers as an array of non-interleaved FAUSTFLOAT samples (eiher float, double or quad) * @param outputs - the output audio buffers as an array of non-interleaved FAUSTFLOAT samples (eiher float, double or quad) * */ virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) = 0; /** * DSP instance computation: alternative method to be used by subclasses. * * @param date_usec - the timestamp in microsec given by audio driver. * @param count - the number of frames to compute * @param inputs - the input audio buffers as an array of non-interleaved FAUSTFLOAT samples (either float, double or quad) * @param outputs - the output audio buffers as an array of non-interleaved FAUSTFLOAT samples (either float, double or quad) * */ virtual void compute(double /*date_usec*/, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); } }; /** * Generic DSP decorator. */ class decorator_dsp : public dsp { protected: dsp* fDSP; public: decorator_dsp(dsp* dsp = nullptr):fDSP(dsp) {} virtual ~decorator_dsp() { delete fDSP; } virtual int getNumInputs() { return fDSP->getNumInputs(); } virtual int getNumOutputs() { return fDSP->getNumOutputs(); } virtual void buildUserInterface(UI* ui_interface) { fDSP->buildUserInterface(ui_interface); } virtual int getSampleRate() { return fDSP->getSampleRate(); } virtual void init(int sample_rate) { fDSP->init(sample_rate); } virtual void instanceInit(int sample_rate) { fDSP->instanceInit(sample_rate); } virtual void instanceConstants(int sample_rate) { fDSP->instanceConstants(sample_rate); } virtual void instanceResetUserInterface() { fDSP->instanceResetUserInterface(); } virtual void instanceClear() { fDSP->instanceClear(); } virtual decorator_dsp* clone() { return new decorator_dsp(fDSP->clone()); } virtual void metadata(Meta* m) { fDSP->metadata(m); } // Beware: subclasses usually have to overload the two 'compute' methods virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { fDSP->compute(count, inputs, outputs); } virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { fDSP->compute(date_usec, count, inputs, outputs); } }; /** * DSP factory class. */ class dsp_factory { protected: // So that to force sub-classes to use deleteDSPFactory(dsp_factory* factory); virtual ~dsp_factory() {} public: virtual std::string getName() = 0; virtual std::string getSHAKey() = 0; virtual std::string getDSPCode() = 0; virtual std::string getCompileOptions() = 0; virtual std::vector<std::string> getLibraryList() = 0; virtual std::vector<std::string> getIncludePathnames() = 0; virtual dsp* createDSPInstance() = 0; virtual void setMemoryManager(dsp_memory_manager* manager) = 0; virtual dsp_memory_manager* getMemoryManager() = 0; }; /** * On Intel set FZ (Flush to Zero) and DAZ (Denormals Are Zero) * flags to avoid costly denormals. */ #ifdef __SSE__ #include <xmmintrin.h> #ifdef __SSE2__ #define AVOIDDENORMALS _mm_setcsr(_mm_getcsr() | 0x8040) #else #define AVOIDDENORMALS _mm_setcsr(_mm_getcsr() | 0x8000) #endif #else #define AVOIDDENORMALS #endif #endif /************************** END dsp.h **************************/ // Base class and common code for binary combiners class dsp_binary_combiner : public dsp { protected: dsp* fDSP1; dsp* fDSP2; void buildUserInterfaceAux(UI* ui_interface, const char* name) { ui_interface->openTabBox(name); ui_interface->openVerticalBox("DSP1"); fDSP1->buildUserInterface(ui_interface); ui_interface->closeBox(); ui_interface->openVerticalBox("DSP2"); fDSP2->buildUserInterface(ui_interface); ui_interface->closeBox(); ui_interface->closeBox(); } FAUSTFLOAT** allocateChannels(int num, int buffer_size) { FAUSTFLOAT** channels = new FAUSTFLOAT*[num]; for (int chan = 0; chan < num; chan++) { channels[chan] = new FAUSTFLOAT[buffer_size]; memset(channels[chan], 0, sizeof(FAUSTFLOAT) * buffer_size); } return channels; } void deleteChannels(FAUSTFLOAT** channels, int num) { for (int chan = 0; chan < num; chan++) { delete [] channels[chan]; } delete [] channels; } public: dsp_binary_combiner(dsp* dsp1, dsp* dsp2):fDSP1(dsp1), fDSP2(dsp2) {} virtual ~dsp_binary_combiner() { delete fDSP1; delete fDSP2; } virtual int getSampleRate() { return fDSP1->getSampleRate(); } virtual void init(int sample_rate) { fDSP1->init(sample_rate); fDSP2->init(sample_rate); } virtual void instanceInit(int sample_rate) { fDSP1->instanceInit(sample_rate); fDSP2->instanceInit(sample_rate); } virtual void instanceConstants(int sample_rate) { fDSP1->instanceConstants(sample_rate); fDSP2->instanceConstants(sample_rate); } virtual void instanceResetUserInterface() { fDSP1->instanceResetUserInterface(); fDSP2->instanceResetUserInterface(); } virtual void instanceClear() { fDSP1->instanceClear(); fDSP2->instanceClear(); } virtual void metadata(Meta* m) { fDSP1->metadata(m); fDSP2->metadata(m); } }; // Combine two 'compatible' DSP in sequence class dsp_sequencer : public dsp_binary_combiner { private: FAUSTFLOAT** fDSP1Outputs; public: dsp_sequencer(dsp* dsp1, dsp* dsp2, int buffer_size = 4096):dsp_binary_combiner(dsp1, dsp2) { fDSP1Outputs = allocateChannels(fDSP1->getNumOutputs(), buffer_size); } virtual ~dsp_sequencer() { deleteChannels(fDSP1Outputs, fDSP1->getNumOutputs()); } virtual int getNumInputs() { return fDSP1->getNumInputs(); } virtual int getNumOutputs() { return fDSP2->getNumOutputs(); } virtual void buildUserInterface(UI* ui_interface) { buildUserInterfaceAux(ui_interface, "Sequencer"); } virtual dsp* clone() { return new dsp_sequencer(fDSP1->clone(), fDSP2->clone()); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { fDSP1->compute(count, inputs, fDSP1Outputs); fDSP2->compute(count, fDSP1Outputs, outputs); } virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); } }; // Combine two DSP in parallel class dsp_parallelizer : public dsp_binary_combiner { private: FAUSTFLOAT** fDSP2Inputs; FAUSTFLOAT** fDSP2Outputs; public: dsp_parallelizer(dsp* dsp1, dsp* dsp2, int buffer_size = 4096):dsp_binary_combiner(dsp1, dsp2) { fDSP2Inputs = new FAUSTFLOAT*[fDSP2->getNumInputs()]; fDSP2Outputs = new FAUSTFLOAT*[fDSP2->getNumOutputs()]; } virtual ~dsp_parallelizer() { delete [] fDSP2Inputs; delete [] fDSP2Outputs; } virtual int getNumInputs() { return fDSP1->getNumInputs() + fDSP2->getNumInputs(); } virtual int getNumOutputs() { return fDSP1->getNumOutputs() + fDSP2->getNumOutputs(); } virtual void buildUserInterface(UI* ui_interface) { buildUserInterfaceAux(ui_interface, "Parallelizer"); } virtual dsp* clone() { return new dsp_parallelizer(fDSP1->clone(), fDSP2->clone()); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { fDSP1->compute(count, inputs, outputs); // Shift inputs/outputs channels for fDSP2 for (int chan = 0; chan < fDSP2->getNumInputs(); chan++) { fDSP2Inputs[chan] = inputs[fDSP1->getNumInputs() + chan]; } for (int chan = 0; chan < fDSP2->getNumOutputs(); chan++) { fDSP2Outputs[chan] = outputs[fDSP1->getNumOutputs() + chan]; } fDSP2->compute(count, fDSP2Inputs, fDSP2Outputs); } virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); } }; // Combine two 'compatible' DSP in splitter class dsp_splitter : public dsp_binary_combiner { private: FAUSTFLOAT** fDSP1Outputs; FAUSTFLOAT** fDSP2Inputs; public: dsp_splitter(dsp* dsp1, dsp* dsp2, int buffer_size = 4096):dsp_binary_combiner(dsp1, dsp2) { fDSP1Outputs = allocateChannels(fDSP1->getNumOutputs(), buffer_size); fDSP2Inputs = new FAUSTFLOAT*[fDSP2->getNumInputs()]; } virtual ~dsp_splitter() { deleteChannels(fDSP1Outputs, fDSP1->getNumOutputs()); delete [] fDSP2Inputs; } virtual int getNumInputs() { return fDSP1->getNumInputs(); } virtual int getNumOutputs() { return fDSP2->getNumOutputs(); } virtual void buildUserInterface(UI* ui_interface) { buildUserInterfaceAux(ui_interface, "Splitter"); } virtual dsp* clone() { return new dsp_splitter(fDSP1->clone(), fDSP2->clone()); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { fDSP1->compute(count, inputs, fDSP1Outputs); for (int chan = 0; chan < fDSP2->getNumInputs(); chan++) { fDSP2Inputs[chan] = fDSP1Outputs[chan % fDSP1->getNumOutputs()]; } fDSP2->compute(count, fDSP2Inputs, outputs); } }; // Combine two 'compatible' DSP in merger class dsp_merger : public dsp_binary_combiner { private: FAUSTFLOAT** fDSP1Inputs; FAUSTFLOAT** fDSP1Outputs; FAUSTFLOAT** fDSP2Inputs; void mix(int count, FAUSTFLOAT* dst, FAUSTFLOAT* src) { for (int frame = 0; frame < count; frame++) { dst[frame] += src[frame]; } } public: dsp_merger(dsp* dsp1, dsp* dsp2, int buffer_size = 4096):dsp_binary_combiner(dsp1, dsp2) { fDSP1Inputs = allocateChannels(fDSP1->getNumInputs(), buffer_size); fDSP1Outputs = allocateChannels(fDSP1->getNumOutputs(), buffer_size); fDSP2Inputs = new FAUSTFLOAT*[fDSP2->getNumInputs()]; } virtual ~dsp_merger() { deleteChannels(fDSP1Inputs, fDSP1->getNumInputs()); deleteChannels(fDSP1Outputs, fDSP1->getNumOutputs()); delete [] fDSP2Inputs; } virtual int getNumInputs() { return fDSP1->getNumInputs(); } virtual int getNumOutputs() { return fDSP2->getNumOutputs(); } virtual void buildUserInterface(UI* ui_interface) { buildUserInterfaceAux(ui_interface, "Merge"); } virtual dsp* clone() { return new dsp_merger(fDSP1->clone(), fDSP2->clone()); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { fDSP1->compute(count, fDSP1Inputs, fDSP1Outputs); memset(fDSP2Inputs, 0, sizeof(FAUSTFLOAT*) * fDSP2->getNumInputs()); for (int chan = 0; chan < fDSP1->getNumOutputs(); chan++) { int mchan = chan % fDSP2->getNumInputs(); if (fDSP2Inputs[mchan]) { mix(count, fDSP2Inputs[mchan], fDSP1Outputs[chan]); } else { fDSP2Inputs[mchan] = fDSP1Outputs[chan]; } } fDSP2->compute(count, fDSP2Inputs, outputs); } }; // Combine two 'compatible' DSP in a recursive way class dsp_recursiver : public dsp_binary_combiner { private: FAUSTFLOAT** fDSP1Inputs; FAUSTFLOAT** fDSP1Outputs; FAUSTFLOAT** fDSP2Inputs; FAUSTFLOAT** fDSP2Outputs; public: dsp_recursiver(dsp* dsp1, dsp* dsp2):dsp_binary_combiner(dsp1, dsp2) { fDSP1Inputs = allocateChannels(fDSP1->getNumInputs(), 1); fDSP1Outputs = allocateChannels(fDSP1->getNumOutputs(), 1); fDSP2Inputs = allocateChannels(fDSP2->getNumInputs(), 1); fDSP2Outputs = allocateChannels(fDSP2->getNumOutputs(), 1); } virtual ~dsp_recursiver() { deleteChannels(fDSP1Inputs, fDSP1->getNumInputs()); deleteChannels(fDSP1Outputs, fDSP1->getNumOutputs()); deleteChannels(fDSP2Inputs, fDSP2->getNumInputs()); deleteChannels(fDSP2Outputs, fDSP2->getNumOutputs()); } virtual int getNumInputs() { return fDSP1->getNumInputs() - fDSP2->getNumOutputs(); } virtual int getNumOutputs() { return fDSP1->getNumOutputs(); } virtual void buildUserInterface(UI* ui_interface) { buildUserInterfaceAux(ui_interface, "Recursiver"); } virtual dsp* clone() { return new dsp_recursiver(fDSP1->clone(), fDSP2->clone()); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { for (int frame = 0; (frame < count); frame++) { for (int chan = 0; chan < fDSP2->getNumOutputs(); chan++) { fDSP1Inputs[chan][0] = fDSP2Outputs[chan][0]; } for (int chan = 0; chan < fDSP1->getNumInputs() - fDSP2->getNumOutputs(); chan++) { fDSP1Inputs[chan + fDSP2->getNumOutputs()][0] = inputs[chan][frame]; } fDSP1->compute(1, fDSP1Inputs, fDSP1Outputs); for (int chan = 0; chan < fDSP1->getNumOutputs(); chan++) { outputs[chan][frame] = fDSP1Outputs[chan][0]; } for (int chan = 0; chan < fDSP2->getNumInputs(); chan++) { fDSP2Inputs[chan][0] = fDSP1Outputs[chan][0]; } fDSP2->compute(1, fDSP2Inputs, fDSP2Outputs); } } virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); } }; #ifndef __dsp_algebra_api__ #define __dsp_algebra_api__ // DSP algebra API /* Each operation takes two DSP as parameters, returns the combined DSPs, or null if failure with an error message. */ static dsp* createDSPSequencer(dsp* dsp1, dsp* dsp2, std::string& error) { if (dsp1->getNumOutputs() != dsp2->getNumInputs()) { std::stringstream error_aux; error_aux << "Connection error int dsp_sequencer : the number of outputs (" << dsp1->getNumOutputs() << ") of A " << "must be equal to the number of inputs (" << dsp2->getNumInputs() << ") of B" << std::endl; error = error_aux.str(); return nullptr; } else { return new dsp_sequencer(dsp1, dsp2); } } static dsp* createDSPParallelizer(dsp* dsp1, dsp* dsp2, std::string& error) { return new dsp_parallelizer(dsp1, dsp2); } static dsp* createDSPSplitter(dsp* dsp1, dsp* dsp2, std::string& error) { if (dsp1->getNumOutputs() == 0) { error = "Connection error in dsp_splitter : the first expression has no outputs\n"; return nullptr; } else if (dsp2->getNumInputs() == 0) { error = "Connection error in dsp_splitter : the second expression has no inputs\n"; return nullptr; } else if (dsp2->getNumInputs() % dsp1->getNumOutputs() != 0) { std::stringstream error_aux; error_aux << "Connection error in dsp_splitter : the number of outputs (" << dsp1->getNumOutputs() << ") of the first expression should be a divisor of the number of inputs (" << dsp2->getNumInputs() << ") of the second expression" << std::endl; error = error_aux.str(); return nullptr; } else if (dsp2->getNumInputs() == dsp1->getNumOutputs()) { return new dsp_sequencer(dsp1, dsp2); } else { return new dsp_splitter(dsp1, dsp2); } } static dsp* createDSPMerger(dsp* dsp1, dsp* dsp2, std::string& error) { if (dsp1->getNumOutputs() == 0) { error = "Connection error in dsp_merger : the first expression has no outputs\n"; return nullptr; } else if (dsp2->getNumInputs() == 0) { error = "Connection error in dsp_merger : the second expression has no inputs\n"; return nullptr; } else if (dsp1->getNumOutputs() % dsp2->getNumInputs() != 0) { std::stringstream error_aux; error_aux << "Connection error in dsp_merger : the number of outputs (" << dsp1->getNumOutputs() << ") of the first expression should be a multiple of the number of inputs (" << dsp2->getNumInputs() << ") of the second expression" << std::endl; error = error_aux.str(); return nullptr; } else if (dsp2->getNumInputs() == dsp1->getNumOutputs()) { return new dsp_sequencer(dsp1, dsp2); } else { return new dsp_merger(dsp1, dsp2); } } static dsp* createDSPRecursiver(dsp* dsp1, dsp* dsp2, std::string& error) { if ((dsp2->getNumInputs() > dsp1->getNumOutputs()) || (dsp2->getNumOutputs() > dsp1->getNumInputs())) { std::stringstream error_aux; error_aux << "Connection error in : dsp_recursiver" << std::endl; if (dsp2->getNumInputs() > dsp1->getNumOutputs()) { error_aux << "The number of outputs " << dsp1->getNumOutputs() << " of the first expression should be greater or equal to the number of inputs (" << dsp2->getNumInputs() << ") of the second expression" << std::endl; } if (dsp2->getNumOutputs() > dsp1->getNumInputs()) { error_aux << "The number of inputs " << dsp1->getNumInputs() << " of the first expression should be greater or equal to the number of outputs (" << dsp2->getNumOutputs() << ") of the second expression" << std::endl; } error = error_aux.str(); return nullptr; } else { return new dsp_recursiver(dsp1, dsp2); } } #endif #endif /************************** END dsp-combiner.h **************************/ /************************** BEGIN dsp-adapter.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2020 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __dsp_adapter__ #define __dsp_adapter__ #ifndef _WIN32 #include <alloca.h> #endif #include <string.h> #include <iostream> #include <cmath> // Adapts a DSP for a different number of inputs/outputs class dsp_adapter : public decorator_dsp { private: FAUSTFLOAT** fAdaptedInputs; FAUSTFLOAT** fAdaptedOutputs; int fHardwareInputs; int fHardwareOutputs; void adaptBuffers(FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { for (int i = 0; i < fHardwareInputs; i++) { fAdaptedInputs[i] = inputs[i]; } for (int i = 0; i < fHardwareOutputs; i++) { fAdaptedOutputs[i] = outputs[i]; } } public: dsp_adapter(dsp* dsp, int hardware_inputs, int hardware_outputs, int buffer_size):decorator_dsp(dsp) { fHardwareInputs = hardware_inputs; fHardwareOutputs = hardware_outputs; fAdaptedInputs = new FAUSTFLOAT*[dsp->getNumInputs()]; for (int i = 0; i < dsp->getNumInputs() - fHardwareInputs; i++) { fAdaptedInputs[i + fHardwareInputs] = new FAUSTFLOAT[buffer_size]; memset(fAdaptedInputs[i + fHardwareInputs], 0, sizeof(FAUSTFLOAT) * buffer_size); } fAdaptedOutputs = new FAUSTFLOAT*[dsp->getNumOutputs()]; for (int i = 0; i < dsp->getNumOutputs() - fHardwareOutputs; i++) { fAdaptedOutputs[i + fHardwareOutputs] = new FAUSTFLOAT[buffer_size]; memset(fAdaptedOutputs[i + fHardwareOutputs], 0, sizeof(FAUSTFLOAT) * buffer_size); } } virtual ~dsp_adapter() { for (int i = 0; i < fDSP->getNumInputs() - fHardwareInputs; i++) { delete [] fAdaptedInputs[i + fHardwareInputs]; } delete [] fAdaptedInputs; for (int i = 0; i < fDSP->getNumOutputs() - fHardwareOutputs; i++) { delete [] fAdaptedOutputs[i + fHardwareOutputs]; } delete [] fAdaptedOutputs; } virtual int getNumInputs() { return fHardwareInputs; } virtual int getNumOutputs() { return fHardwareOutputs; } virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { adaptBuffers(inputs, outputs); fDSP->compute(date_usec, count, fAdaptedInputs, fAdaptedOutputs); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { adaptBuffers(inputs, outputs); fDSP->compute(count, fAdaptedInputs, fAdaptedOutputs); } }; // Adapts a DSP for a different sample size template <typename REAL_INT, typename REAL_EXT> class dsp_sample_adapter : public decorator_dsp { protected: REAL_INT** fAdaptedInputs; REAL_INT** fAdaptedOutputs; void adaptInputBuffers(int count, FAUSTFLOAT** inputs) { for (int chan = 0; chan < fDSP->getNumInputs(); chan++) { for (int frame = 0; frame < count; frame++) { fAdaptedInputs[chan][frame] = REAL_INT(reinterpret_cast<REAL_EXT**>(inputs)[chan][frame]); } } } void adaptOutputsBuffers(int count, FAUSTFLOAT** outputs) { for (int chan = 0; chan < fDSP->getNumOutputs(); chan++) { for (int frame = 0; frame < count; frame++) { reinterpret_cast<REAL_EXT**>(outputs)[chan][frame] = REAL_EXT(fAdaptedOutputs[chan][frame]); } } } public: dsp_sample_adapter(dsp* dsp):decorator_dsp(dsp) { fAdaptedInputs = new REAL_INT*[dsp->getNumInputs()]; for (int i = 0; i < dsp->getNumInputs(); i++) { fAdaptedInputs[i] = new REAL_INT[4096]; } fAdaptedOutputs = new REAL_INT*[dsp->getNumOutputs()]; for (int i = 0; i < dsp->getNumOutputs(); i++) { fAdaptedOutputs[i] = new REAL_INT[4096]; } } virtual ~dsp_sample_adapter() { for (int i = 0; i < fDSP->getNumInputs(); i++) { delete [] fAdaptedInputs[i]; } delete [] fAdaptedInputs; for (int i = 0; i < fDSP->getNumOutputs(); i++) { delete [] fAdaptedOutputs[i]; } delete [] fAdaptedOutputs; } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { adaptInputBuffers(count, inputs); // DSP base class uses FAUSTFLOAT** type, so reinterpret_cast has to be used even if the real DSP uses REAL_INT fDSP->compute(count, reinterpret_cast<FAUSTFLOAT**>(fAdaptedInputs), reinterpret_cast<FAUSTFLOAT**>(fAdaptedOutputs)); adaptOutputsBuffers(count, outputs); } virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { adaptInputBuffers(count, inputs); // DSP base class uses FAUSTFLOAT** type, so reinterpret_cast has to be used even if the real DSP uses REAL_INT fDSP->compute(date_usec, count, reinterpret_cast<FAUSTFLOAT**>(fAdaptedInputs), reinterpret_cast<FAUSTFLOAT**>(fAdaptedOutputs)); adaptOutputsBuffers(count, outputs); } }; // Template used to specialize double parameters expressed as NUM/DENOM template <int NUM, int DENOM> struct Double { static constexpr double value() { return double(NUM)/double(DENOM); } }; // Base class for filters template <class fVslider0, int fVslider1> struct Filter { inline int getFactor() { return fVslider1; } }; // Identity filter: copy input to output template <class fVslider0, int fVslider1> struct Identity : public Filter<fVslider0, fVslider1> { inline int getFactor() { return fVslider1; } inline void compute(int count, FAUSTFLOAT* input0, FAUSTFLOAT* output0) { memcpy(output0, input0, count * sizeof(FAUSTFLOAT)); } }; // Generated with process = fi.lowpass(3, ma.SR*hslider("FCFactor", 0.4, 0.4, 0.5, 0.01)/hslider("Factor", 2, 2, 8, 1)); template <class fVslider0, int fVslider1, typename REAL> struct LowPass3 : public Filter<fVslider0, fVslider1> { REAL fVec0[2]; REAL fRec1[2]; REAL fRec0[3]; inline REAL LowPass3_faustpower2_f(REAL value) { return (value * value); } LowPass3() { for (int l0 = 0; (l0 < 2); l0 = (l0 + 1)) { fVec0[l0] = 0.0; } for (int l1 = 0; (l1 < 2); l1 = (l1 + 1)) { fRec1[l1] = 0.0; } for (int l2 = 0; (l2 < 3); l2 = (l2 + 1)) { fRec0[l2] = 0.0; } } inline void compute(int count, FAUSTFLOAT* input0, FAUSTFLOAT* output0) { // Computed at template specialization time REAL fSlow0 = std::tan((3.1415926535897931 * (REAL(fVslider0::value()) / REAL(fVslider1)))); REAL fSlow1 = (1.0 / fSlow0); REAL fSlow2 = (1.0 / (((fSlow1 + 1.0000000000000002) / fSlow0) + 1.0)); REAL fSlow3 = (1.0 / (fSlow1 + 1.0)); REAL fSlow4 = (1.0 - fSlow1); REAL fSlow5 = (((fSlow1 + -1.0000000000000002) / fSlow0) + 1.0); REAL fSlow6 = (2.0 * (1.0 - (1.0 / LowPass3_faustpower2_f(fSlow0)))); // Computed at runtime for (int i = 0; (i < count); i = (i + 1)) { REAL fTemp0 = REAL(input0[i]); fVec0[0] = fTemp0; fRec1[0] = (0.0 - (fSlow3 * ((fSlow4 * fRec1[1]) - (fTemp0 + fVec0[1])))); fRec0[0] = (fRec1[0] - (fSlow2 * ((fSlow5 * fRec0[2]) + (fSlow6 * fRec0[1])))); output0[i] = FAUSTFLOAT((fSlow2 * (fRec0[2] + (fRec0[0] + (2.0 * fRec0[1]))))); fVec0[1] = fVec0[0]; fRec1[1] = fRec1[0]; fRec0[2] = fRec0[1]; fRec0[1] = fRec0[0]; } } }; // Generated with process = fi.lowpass(4, ma.SR*hslider("FCFactor", 0.4, 0.4, 0.5, 0.01)/hslider("Factor", 2, 2, 8, 1)); template <class fVslider0, int fVslider1, typename REAL> struct LowPass4 : public Filter<fVslider0, fVslider1> { REAL fRec1[3]; REAL fRec0[3]; inline REAL LowPass4_faustpower2_f(REAL value) { return (value * value); } LowPass4() { for (int l0 = 0; (l0 < 3); l0 = (l0 + 1)) { fRec1[l0] = 0.0f; } for (int l1 = 0; (l1 < 3); l1 = (l1 + 1)) { fRec0[l1] = 0.0f; } } inline void compute(int count, FAUSTFLOAT* input0, FAUSTFLOAT* output0) { // Computed at template specialization time REAL fSlow0 = std::tan((3.1415926535897931 * (REAL(fVslider0::value()) / REAL(fVslider1)))); REAL fSlow1 = (1.0 / fSlow0); REAL fSlow2 = (1.0 / (((fSlow1 + 0.76536686473017945) / fSlow0) + 1.0)); REAL fSlow3 = (1.0 / (((fSlow1 + 1.8477590650225735) / fSlow0) + 1.0)); REAL fSlow4 = (((fSlow1 + -1.8477590650225735) / fSlow0) + 1.0); REAL fSlow5 = (2.0 * (1.0 - (1.0 / LowPass4_faustpower2_f(fSlow0)))); REAL fSlow6 = (((fSlow1 + -0.76536686473017945) / fSlow0) + 1.0); // Computed at runtime for (int i = 0; (i < count); i = (i + 1)) { fRec1[0] = (REAL(input0[i]) - (fSlow3 * ((fSlow4 * fRec1[2]) + (fSlow5 * fRec1[1])))); fRec0[0] = ((fSlow3 * (fRec1[2] + (fRec1[0] + (2.0 * fRec1[1])))) - (fSlow2 * ((fSlow6 * fRec0[2]) + (fSlow5 * fRec0[1])))); output0[i] = FAUSTFLOAT((fSlow2 * (fRec0[2] + (fRec0[0] + (2.0 * fRec0[1]))))); fRec1[2] = fRec1[1]; fRec1[1] = fRec1[0]; fRec0[2] = fRec0[1]; fRec0[1] = fRec0[0]; } } }; // Generated with process = fi.lowpass3e(ma.SR*hslider("FCFactor", 0.4, 0.4, 0.5, 0.01)/hslider("Factor", 2, 2, 8, 1)); template <class fVslider0, int fVslider1, typename REAL> struct LowPass3e : public Filter<fVslider0, fVslider1> { REAL fRec1[3]; REAL fVec0[2]; REAL fRec0[2]; inline REAL LowPass3e_faustpower2_f(REAL value) { return (value * value); } LowPass3e() { for (int l0 = 0; (l0 < 3); l0 = (l0 + 1)) { fRec1[l0] = 0.0; } for (int l1 = 0; (l1 < 2); l1 = (l1 + 1)) { fVec0[l1] = 0.0; } for (int l2 = 0; (l2 < 2); l2 = (l2 + 1)) { fRec0[l2] = 0.0; } } inline void compute(int count, FAUSTFLOAT* input0, FAUSTFLOAT* output0) { // Computed at template specialization time REAL fSlow0 = std::tan((3.1415926535897931 * (REAL(fVslider0::value()) / REAL(fVslider1)))); REAL fSlow1 = (1.0 / fSlow0); REAL fSlow2 = (1.0 / (fSlow1 + 0.82244590899881598)); REAL fSlow3 = (0.82244590899881598 - fSlow1); REAL fSlow4 = (1.0 / (((fSlow1 + 0.80263676416103003) / fSlow0) + 1.4122708937742039)); REAL fSlow5 = LowPass3e_faustpower2_f(fSlow0); REAL fSlow6 = (0.019809144837788999 / fSlow5); REAL fSlow7 = (fSlow6 + 1.1615164189826961); REAL fSlow8 = (((fSlow1 + -0.80263676416103003) / fSlow0) + 1.4122708937742039); REAL fSlow9 = (2.0 * (1.4122708937742039 - (1.0 / fSlow5))); REAL fSlow10 = (2.0 * (1.1615164189826961 - fSlow6)); // Computed at runtime for (int i = 0; (i < count); i = (i + 1)) { fRec1[0] = (REAL(input0[i]) - (fSlow4 * ((fSlow8 * fRec1[2]) + (fSlow9 * fRec1[1])))); REAL fTemp0 = (fSlow4 * (((fSlow7 * fRec1[0]) + (fSlow10 * fRec1[1])) + (fSlow7 * fRec1[2]))); fVec0[0] = fTemp0; fRec0[0] = (0.0 - (fSlow2 * ((fSlow3 * fRec0[1]) - (fTemp0 + fVec0[1])))); output0[i] = FAUSTFLOAT(fRec0[0]); fRec1[2] = fRec1[1]; fRec1[1] = fRec1[0]; fVec0[1] = fVec0[0]; fRec0[1] = fRec0[0]; } } }; // Generated with process = fi.lowpass6e(ma.SR*hslider("FCFactor", 0.4, 0.4, 0.5, 0.01)/hslider("Factor", 2, 2, 8, 1)); template <class fVslider0, int fVslider1, typename REAL> struct LowPass6e : public Filter<fVslider0, fVslider1> { REAL fRec2[3]; REAL fRec1[3]; REAL fRec0[3]; inline REAL LowPass6e_faustpower2_f(REAL value) { return (value * value); } LowPass6e() { for (int l0 = 0; (l0 < 3); l0 = (l0 + 1)) { fRec2[l0] = 0.0; } for (int l1 = 0; (l1 < 3); l1 = (l1 + 1)) { fRec1[l1] = 0.0; } for (int l2 = 0; (l2 < 3); l2 = (l2 + 1)) { fRec0[l2] = 0.0; } } inline void compute(int count, FAUSTFLOAT* input0, FAUSTFLOAT* output0) { // Computed at template specialization time REAL fSlow0 = std::tan((3.1415926535897931 * (REAL(fVslider0::value()) / REAL(fVslider1)))); REAL fSlow1 = (1.0 / fSlow0); REAL fSlow2 = (1.0 / (((fSlow1 + 0.16840487111358901) / fSlow0) + 1.0693584077073119)); REAL fSlow3 = LowPass6e_faustpower2_f(fSlow0); REAL fSlow4 = (1.0 / fSlow3); REAL fSlow5 = (fSlow4 + 53.536152954556727); REAL fSlow6 = (1.0 / (((fSlow1 + 0.51247864188914105) / fSlow0) + 0.68962136448467504)); REAL fSlow7 = (fSlow4 + 7.6217312988706034); REAL fSlow8 = (1.0 / (((fSlow1 + 0.78241304682164503) / fSlow0) + 0.24529150870616001)); REAL fSlow9 = (9.9999997054999994e-05 / fSlow3); REAL fSlow10 = (fSlow9 + 0.00043322720055500002); REAL fSlow11 = (((fSlow1 + -0.78241304682164503) / fSlow0) + 0.24529150870616001); REAL fSlow12 = (2.0 * (0.24529150870616001 - fSlow4)); REAL fSlow13 = (2.0 * (0.00043322720055500002 - fSlow9)); REAL fSlow14 = (((fSlow1 + -0.51247864188914105) / fSlow0) + 0.68962136448467504); REAL fSlow15 = (2.0 * (0.68962136448467504 - fSlow4)); REAL fSlow16 = (2.0 * (7.6217312988706034 - fSlow4)); REAL fSlow17 = (((fSlow1 + -0.16840487111358901) / fSlow0) + 1.0693584077073119); REAL fSlow18 = (2.0 * (1.0693584077073119 - fSlow4)); REAL fSlow19 = (2.0 * (53.536152954556727 - fSlow4)); // Computed at runtime for (int i = 0; (i < count); i = (i + 1)) { fRec2[0] = (REAL(input0[i]) - (fSlow8 * ((fSlow11 * fRec2[2]) + (fSlow12 * fRec2[1])))); fRec1[0] = ((fSlow8 * (((fSlow10 * fRec2[0]) + (fSlow13 * fRec2[1])) + (fSlow10 * fRec2[2]))) - (fSlow6 * ((fSlow14 * fRec1[2]) + (fSlow15 * fRec1[1])))); fRec0[0] = ((fSlow6 * (((fSlow7 * fRec1[0]) + (fSlow16 * fRec1[1])) + (fSlow7 * fRec1[2]))) - (fSlow2 * ((fSlow17 * fRec0[2]) + (fSlow18 * fRec0[1])))); output0[i] = FAUSTFLOAT((fSlow2 * (((fSlow5 * fRec0[0]) + (fSlow19 * fRec0[1])) + (fSlow5 * fRec0[2])))); fRec2[2] = fRec2[1]; fRec2[1] = fRec2[0]; fRec1[2] = fRec1[1]; fRec1[1] = fRec1[0]; fRec0[2] = fRec0[1]; fRec0[1] = fRec0[0]; } } }; // A "si.bus(N)" like hard-coded class struct dsp_bus : public dsp { int fChannels; int fSampleRate; dsp_bus(int channels):fChannels(channels), fSampleRate(-1) {} virtual int getNumInputs() { return fChannels; } virtual int getNumOutputs() { return fChannels; } virtual int getSampleRate() { return fSampleRate; } virtual void buildUserInterface(UI* ui_interface) {} virtual void init(int sample_rate) { //classInit(sample_rate); instanceInit(sample_rate); } virtual void instanceInit(int sample_rate) { fSampleRate = sample_rate; instanceConstants(sample_rate); instanceResetUserInterface(); instanceClear(); } virtual void instanceConstants(int sample_rate) {} virtual void instanceResetUserInterface() {} virtual void instanceClear() {} virtual dsp* clone() { return new dsp_bus(fChannels); } virtual void metadata(Meta* m) {} virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { for (int chan = 0; chan < fChannels; chan++) { memcpy(outputs[chan], inputs[chan], sizeof(FAUSTFLOAT) * count); } } virtual void compute(double /*date_usec*/, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); } }; // Base class for sample-rate adapter template <typename FILTER> class sr_sampler : public decorator_dsp { protected: std::vector<FILTER> fInputLowPass; std::vector<FILTER> fOutputLowPass; inline int getFactor() { return this->fOutputLowPass[0].getFactor(); } public: sr_sampler(dsp* dsp):decorator_dsp(dsp) { for (int chan = 0; chan < fDSP->getNumInputs(); chan++) { fInputLowPass.push_back(FILTER()); } for (int chan = 0; chan < fDSP->getNumOutputs(); chan++) { fOutputLowPass.push_back(FILTER()); } } }; // Down sample-rate adapter template <typename FILTER> class dsp_down_sampler : public sr_sampler<FILTER> { public: dsp_down_sampler(dsp* dsp):sr_sampler<FILTER>(dsp) {} virtual void init(int sample_rate) { this->fDSP->init(sample_rate / this->getFactor()); } virtual void instanceInit(int sample_rate) { this->fDSP->instanceInit(sample_rate / this->getFactor()); } virtual void instanceConstants(int sample_rate) { this->fDSP->instanceConstants(sample_rate / this->getFactor()); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { int real_count = count / this->getFactor(); // Adapt inputs FAUSTFLOAT* fInputs[this->fDSP->getNumInputs()]; for (int chan = 0; chan < this->fDSP->getNumInputs(); chan++) { // Lowpass filtering in place on 'inputs' this->fInputLowPass[chan].compute(count, inputs[chan], inputs[chan]); // Allocate fInputs with 'real_count' frames fInputs[chan] = (FAUSTFLOAT*)alloca(sizeof(FAUSTFLOAT) * real_count); // Decimate for (int frame = 0; frame < real_count; frame++) { fInputs[chan][frame] = inputs[chan][frame * this->getFactor()]; } } // Allocate fOutputs with 'real_count' frames FAUSTFLOAT* fOutputs[this->fDSP->getNumOutputs()]; for (int chan = 0; chan < this->fDSP->getNumOutputs(); chan++) { fOutputs[chan] = (FAUSTFLOAT*)alloca(sizeof(FAUSTFLOAT) * real_count); } // Compute at lower rate this->fDSP->compute(real_count, fInputs, fOutputs); // Adapt outputs for (int chan = 0; chan < this->fDSP->getNumOutputs(); chan++) { // Puts zeros memset(outputs[chan], 0, sizeof(FAUSTFLOAT) * count); for (int frame = 0; frame < real_count; frame++) { // Copy one sample every 'DownFactor' // Apply volume //outputs[chan][frame * this->getFactor()] = fOutputs[chan][frame] * this->getFactor(); outputs[chan][frame * this->getFactor()] = fOutputs[chan][frame]; } // Lowpass filtering in place on 'outputs' this->fOutputLowPass[chan].compute(count, outputs[chan], outputs[chan]); } } virtual void compute(double /*date_usec*/, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); } }; // Up sample-rate adapter template <typename FILTER> class dsp_up_sampler : public sr_sampler<FILTER> { public: dsp_up_sampler(dsp* dsp):sr_sampler<FILTER>(dsp) {} virtual void init(int sample_rate) { this->fDSP->init(sample_rate * this->getFactor()); } virtual void instanceInit(int sample_rate) { this->fDSP->instanceInit(sample_rate * this->getFactor()); } virtual void instanceConstants(int sample_rate) { this->fDSP->instanceConstants(sample_rate * this->getFactor()); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { int real_count = count * this->getFactor(); // Adapt inputs FAUSTFLOAT** fInputs = (FAUSTFLOAT**)alloca(this->fDSP->getNumInputs() * sizeof(FAUSTFLOAT*)); for (int chan = 0; chan < this->fDSP->getNumInputs(); chan++) { // Allocate fInputs with 'real_count' frames fInputs[chan] = (FAUSTFLOAT*)alloca(sizeof(FAUSTFLOAT) * real_count); // Puts zeros memset(fInputs[chan], 0, sizeof(FAUSTFLOAT) * real_count); for (int frame = 0; frame < count; frame++) { // Copy one sample every 'UpFactor' fInputs[chan][frame * this->getFactor()] = inputs[chan][frame]; } // Lowpass filtering in place on 'fInputs' this->fInputLowPass[chan].compute(real_count, fInputs[chan], fInputs[chan]); } // Allocate fOutputs with 'real_count' frames FAUSTFLOAT** fOutputs = (FAUSTFLOAT**)alloca(this->fDSP->getNumOutputs() * sizeof(FAUSTFLOAT*)); for (int chan = 0; chan < this->fDSP->getNumOutputs(); chan++) { fOutputs[chan] = (FAUSTFLOAT*)alloca(sizeof(FAUSTFLOAT) * real_count); } // Compute at upper rate this->fDSP->compute(real_count, fInputs, fOutputs); // Adapt outputs for (int chan = 0; chan < this->fDSP->getNumOutputs(); chan++) { // Lowpass filtering in place on 'fOutputs' this->fOutputLowPass[chan].compute(real_count, fOutputs[chan], fOutputs[chan]); // Decimate for (int frame = 0; frame < count; frame++) { // Apply volume //outputs[chan][frame] = fOutputs[chan][frame * this->getFactor()] * this->getFactor(); outputs[chan][frame] = fOutputs[chan][frame * this->getFactor()]; } } } virtual void compute(double /*date_usec*/, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); } }; #endif /************************** END dsp-adapter.h **************************/ /************************** BEGIN misc.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __misc__ #define __misc__ #include <algorithm> #include <map> #include <cstdlib> #include <string.h> #include <fstream> #include <string> /************************** BEGIN meta.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __meta__ #define __meta__ struct Meta { virtual ~Meta() {}; virtual void declare(const char* key, const char* value) = 0; }; #endif /************************** END meta.h **************************/ using std::max; using std::min; struct XXXX_Meta : std::map<const char*, const char*> { void declare(const char* key, const char* value) { (*this)[key] = value; } }; struct MY_Meta : Meta, std::map<const char*, const char*> { void declare(const char* key, const char* value) { (*this)[key] = value; } }; static int lsr(int x, int n) { return int(((unsigned int)x) >> n); } static int int2pow2(int x) { int r = 0; while ((1<<r) < x) r++; return r; } static long lopt(char* argv[], const char* name, long def) { for (int i = 0; argv[i]; i++) if (!strcmp(argv[i], name)) return std::atoi(argv[i+1]); return def; } static long lopt1(int argc, char* argv[], const char* longname, const char* shortname, long def) { for (int i = 2; i < argc; i++) { if (strcmp(argv[i-1], shortname) == 0 || strcmp(argv[i-1], longname) == 0) { return atoi(argv[i]); } } return def; } static const char* lopts(char* argv[], const char* name, const char* def) { for (int i = 0; argv[i]; i++) if (!strcmp(argv[i], name)) return argv[i+1]; return def; } static const char* lopts1(int argc, char* argv[], const char* longname, const char* shortname, const char* def) { for (int i = 2; i < argc; i++) { if (strcmp(argv[i-1], shortname) == 0 || strcmp(argv[i-1], longname) == 0) { return argv[i]; } } return def; } static bool isopt(char* argv[], const char* name) { for (int i = 0; argv[i]; i++) if (!strcmp(argv[i], name)) return true; return false; } static std::string pathToContent(const std::string& path) { std::ifstream file(path.c_str(), std::ifstream::binary); file.seekg(0, file.end); int size = int(file.tellg()); file.seekg(0, file.beg); // And allocate buffer to that a single line can be read... char* buffer = new char[size + 1]; file.read(buffer, size); // Terminate the string buffer[size] = 0; std::string result = buffer; file.close(); delete [] buffer; return result; } #endif /************************** END misc.h **************************/ /************************** BEGIN SaveUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2019-2020 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef FAUST_SAVEUI_H #define FAUST_SAVEUI_H /************************** BEGIN DecoratorUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef Decorator_UI_H #define Decorator_UI_H //---------------------------------------------------------------- // Generic UI empty implementation //---------------------------------------------------------------- class GenericUI : public UI { public: GenericUI() {} virtual ~GenericUI() {} // -- widget's layouts virtual void openTabBox(const char* label) {} virtual void openHorizontalBox(const char* label) {} virtual void openVerticalBox(const char* label) {} virtual void closeBox() {} // -- active widgets virtual void addButton(const char* label, FAUSTFLOAT* zone) {} virtual void addCheckButton(const char* label, FAUSTFLOAT* zone) {} virtual void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {} virtual void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {} virtual void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {} // -- passive widgets virtual void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) {} virtual void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) {} // -- soundfiles virtual void addSoundfile(const char* label, const char* soundpath, Soundfile** sf_zone) {} virtual void declare(FAUSTFLOAT* zone, const char* key, const char* val) {} }; //---------------------------------------------------------------- // Generic UI decorator //---------------------------------------------------------------- class DecoratorUI : public UI { protected: UI* fUI; public: DecoratorUI(UI* ui = 0):fUI(ui) {} virtual ~DecoratorUI() { delete fUI; } // -- widget's layouts virtual void openTabBox(const char* label) { fUI->openTabBox(label); } virtual void openHorizontalBox(const char* label) { fUI->openHorizontalBox(label); } virtual void openVerticalBox(const char* label) { fUI->openVerticalBox(label); } virtual void closeBox() { fUI->closeBox(); } // -- active widgets virtual void addButton(const char* label, FAUSTFLOAT* zone) { fUI->addButton(label, zone); } virtual void addCheckButton(const char* label, FAUSTFLOAT* zone) { fUI->addCheckButton(label, zone); } virtual void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { fUI->addVerticalSlider(label, zone, init, min, max, step); } virtual void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { fUI->addHorizontalSlider(label, zone, init, min, max, step); } virtual void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { fUI->addNumEntry(label, zone, init, min, max, step); } // -- passive widgets virtual void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { fUI->addHorizontalBargraph(label, zone, min, max); } virtual void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { fUI->addVerticalBargraph(label, zone, min, max); } // -- soundfiles virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) { fUI->addSoundfile(label, filename, sf_zone); } virtual void declare(FAUSTFLOAT* zone, const char* key, const char* val) { fUI->declare(zone, key, val); } }; #endif /************************** END DecoratorUI.h **************************/ // Base class to handle controllers state save/load class SaveUI : public GenericUI { protected: struct SavedZone { FAUSTFLOAT* fZone; FAUSTFLOAT fCurrent; FAUSTFLOAT fInit; SavedZone():fZone(nullptr), fCurrent(FAUSTFLOAT(0)), fInit(FAUSTFLOAT(0)) {} SavedZone(FAUSTFLOAT* zone, FAUSTFLOAT current, FAUSTFLOAT init) :fZone(zone), fCurrent(current), fInit(init) { *fZone = current; } ~SavedZone() {} }; std::map<std::string, SavedZone> fName2Zone; virtual void addItem(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init) = 0; public: SaveUI() {} virtual ~SaveUI() {} void addButton(const char* label, FAUSTFLOAT* zone) { addItem(label, zone, FAUSTFLOAT(0)); } void addCheckButton(const char* label, FAUSTFLOAT* zone) { addItem(label, zone, FAUSTFLOAT(0)); } void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addItem(label, zone, init); } void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addItem(label, zone, init); } void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addItem(label, zone, init); } void reset() { for (auto& it : fName2Zone) { *it.second.fZone = it.second.fInit; } } void display() { for (auto& it : fName2Zone) { std::cout << "SaveUI::display path = " << it.first << " value = " << *it.second.fZone << std::endl; } } void save() { for (auto& it : fName2Zone) { it.second.fCurrent = *it.second.fZone; } } }; /* Save/load current value using the label, reset to init value */ class SaveLabelUI : public SaveUI { protected: void addItem(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init) { if (fName2Zone.find(label) != fName2Zone.end()) { FAUSTFLOAT current = fName2Zone[label].fCurrent; fName2Zone[label] = SavedZone(zone, current, init); } else { fName2Zone[label] = SavedZone(zone, init, init); } } public: SaveLabelUI() : SaveUI() {} virtual ~SaveLabelUI() {} }; /* Save/load current value using the complete path, reset to init value */ class SavePathUI : public SaveUI, public PathBuilder { protected: void openTabBox(const char* label) { pushLabel(label); } void openHorizontalBox(const char* label) { pushLabel(label);; } void openVerticalBox(const char* label) { pushLabel(label); } void closeBox() { popLabel(); }; void addItem(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init) { std::string path = buildPath(label); if (fName2Zone.find(path) != fName2Zone.end()) { FAUSTFLOAT current = fName2Zone[path].fCurrent; fName2Zone[path] = SavedZone(zone, current, init); } else { fName2Zone[path] = SavedZone(zone, init, init); } } public: SavePathUI(): SaveUI() {} virtual ~SavePathUI() {} }; #endif /************************** END SaveUI.h **************************/ // Always included /************************** BEGIN OSCUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __OSCUI__ #define __OSCUI__ #include <vector> #include <string> /* Faust Project Copyright (C) 2011 Grame This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France [email protected] */ #ifndef __OSCControler__ #define __OSCControler__ #include <string> /* Copyright (C) 2011 Grame This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France [email protected] */ #ifndef __FaustFactory__ #define __FaustFactory__ #include <stack> #include <string> #include <sstream> /* Copyright (C) 2011 Grame This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France [email protected] */ #ifndef __FaustNode__ #define __FaustNode__ #include <string> #include <vector> /* Copyright (C) 2011 Grame This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France [email protected] */ #ifndef __MessageDriven__ #define __MessageDriven__ #include <string> #include <vector> /* Copyright (C) 2010 Grame This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France [email protected] */ #ifndef __MessageProcessor__ #define __MessageProcessor__ namespace oscfaust { class Message; //-------------------------------------------------------------------------- /*! \brief an abstract class for objects able to process OSC messages */ class MessageProcessor { public: virtual ~MessageProcessor() {} virtual void processMessage( const Message* msg ) = 0; }; } // end namespoace #endif /* Copyright (C) 2011 Grame This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France [email protected] */ #ifndef __smartpointer__ #define __smartpointer__ #include <cassert> namespace oscfaust { /*! \brief the base class for smart pointers implementation Any object that want to support smart pointers should inherit from the smartable class which provides reference counting and automatic delete when the reference count drops to zero. */ class smartable { private: unsigned refCount; public: //! gives the reference count of the object unsigned refs() const { return refCount; } //! addReference increments the ref count and checks for refCount overflow void addReference() { refCount++; assert(refCount != 0); } //! removeReference delete the object when refCount is zero void removeReference() { if (--refCount == 0) delete this; } protected: smartable() : refCount(0) {} smartable(const smartable&): refCount(0) {} //! destructor checks for non-zero refCount virtual ~smartable() { /* See "Static SFaustNode create (const char* name, C* zone, C init, C min, C max, const char* prefix, GUI* ui)" comment. assert (refCount == 0); */ } smartable& operator=(const smartable&) { return *this; } }; /*! \brief the smart pointer implementation A smart pointer is in charge of maintaining the objects reference count by the way of pointers operators overloading. It supports class inheritance and conversion whenever possible. \n Instances of the SMARTP class are supposed to use \e smartable types (or at least objects that implements the \e addReference and \e removeReference methods in a consistent way). */ template<class T> class SMARTP { private: //! the actual pointer to the class T* fSmartPtr; public: //! an empty constructor - points to null SMARTP() : fSmartPtr(0) {} //! build a smart pointer from a class pointer SMARTP(T* rawptr) : fSmartPtr(rawptr) { if (fSmartPtr) fSmartPtr->addReference(); } //! build a smart pointer from an convertible class reference template<class T2> SMARTP(const SMARTP<T2>& ptr) : fSmartPtr((T*)ptr) { if (fSmartPtr) fSmartPtr->addReference(); } //! build a smart pointer from another smart pointer reference SMARTP(const SMARTP& ptr) : fSmartPtr((T*)ptr) { if (fSmartPtr) fSmartPtr->addReference(); } //! the smart pointer destructor: simply removes one reference count ~SMARTP() { if (fSmartPtr) fSmartPtr->removeReference(); } //! cast operator to retrieve the actual class pointer operator T*() const { return fSmartPtr; } //! '*' operator to access the actual class pointer T& operator*() const { // checks for null dereference assert (fSmartPtr != 0); return *fSmartPtr; } //! operator -> overloading to access the actual class pointer T* operator->() const { // checks for null dereference assert (fSmartPtr != 0); return fSmartPtr; } //! operator = that moves the actual class pointer template <class T2> SMARTP& operator=(T2 p1_) { *this=(T*)p1_; return *this; } //! operator = that moves the actual class pointer SMARTP& operator=(T* p_) { // check first that pointers differ if (fSmartPtr != p_) { // increments the ref count of the new pointer if not null if (p_ != 0) p_->addReference(); // decrements the ref count of the old pointer if not null if (fSmartPtr != 0) fSmartPtr->removeReference(); // and finally stores the new actual pointer fSmartPtr = p_; } return *this; } //! operator < to support SMARTP map with Visual C++ bool operator<(const SMARTP<T>& p_) const { return fSmartPtr < ((T *) p_); } //! operator = to support inherited class reference SMARTP& operator=(const SMARTP<T>& p_) { return operator=((T *) p_); } //! dynamic cast support template<class T2> SMARTP& cast(T2* p_) { return operator=(dynamic_cast<T*>(p_)); } //! dynamic cast support template<class T2> SMARTP& cast(const SMARTP<T2>& p_) { return operator=(dynamic_cast<T*>(p_)); } }; } #endif namespace oscfaust { class Message; class OSCRegexp; class MessageDriven; typedef class SMARTP<MessageDriven> SMessageDriven; //-------------------------------------------------------------------------- /*! \brief a base class for objects accepting OSC messages Message driven objects are hierarchically organized in a tree. They provides the necessary to dispatch an OSC message to its destination node, according to the message OSC address. The principle of the dispatch is the following: - first the processMessage() method should be called on the top level node - next processMessage call propose */ class MessageDriven : public MessageProcessor, public smartable { std::string fName; ///< the node name std::string fOSCPrefix; ///< the node OSC address prefix (OSCAddress = fOSCPrefix + '/' + fName) std::vector<SMessageDriven> fSubNodes; ///< the subnodes of the current node protected: MessageDriven(const char *name, const char *oscprefix) : fName (name), fOSCPrefix(oscprefix) {} virtual ~MessageDriven() {} public: static SMessageDriven create(const char* name, const char *oscprefix) { return new MessageDriven(name, oscprefix); } /*! \brief OSC message processing method. \param msg the osc message to be processed The method should be called on the top level node. */ virtual void processMessage(const Message* msg); /*! \brief propose an OSc message at a given hierarchy level. \param msg the osc message currently processed \param regexp a regular expression based on the osc address head \param addrTail the osc address tail The method first tries to match the regular expression with the object name. When it matches: - it calls \c accept when \c addrTail is empty - or it \c propose the message to its subnodes when \c addrTail is not empty. In this case a new \c regexp is computed with the head of \c addrTail and a new \c addrTail as well. */ virtual void propose(const Message* msg, const OSCRegexp* regexp, const std::string& addrTail); /*! \brief accept an OSC message. \param msg the osc message currently processed \return true when the message is processed by the node The method is called only for the destination nodes. The real message acceptance is the node responsability and may depend on the message content. */ virtual bool accept(const Message* msg); /*! \brief handler for the \c 'get' message \param ipdest the output message destination IP The \c 'get' message is supported by every node: - it is propagated to the subnodes until it reaches terminal nodes - a terminal node send its state on \c 'get' request to the IP address given as parameter. The \c get method is basically called by the accept method. */ virtual void get(unsigned long ipdest) const; /*! \brief handler for the \c 'get' 'attribute' message \param ipdest the output message destination IP \param what the requested attribute The \c 'get' message is supported by every node: - it is propagated to the subnodes until it reaches terminal nodes - a terminal node send its state on \c 'get' request to the IP address given as parameter. The \c get method is basically called by the accept method. */ virtual void get(unsigned long ipdest, const std::string& what) const {} void add(SMessageDriven node) { fSubNodes.push_back (node); } const char* getName() const { return fName.c_str(); } std::string getOSCAddress() const; int size() const { return (int)fSubNodes.size (); } const std::string& name() const { return fName; } SMessageDriven subnode(int i) { return fSubNodes[i]; } }; } // end namespoace #endif /* Copyright (C) 2011 Grame This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France [email protected] */ #ifndef __Message__ #define __Message__ #include <string> #include <vector> namespace oscfaust { class OSCStream; template <typename T> class MsgParam; class baseparam; typedef SMARTP<baseparam> Sbaseparam; //-------------------------------------------------------------------------- /*! \brief base class of a message parameters */ class baseparam : public smartable { public: virtual ~baseparam() {} /*! \brief utility for parameter type checking */ template<typename X> bool isType() const { return dynamic_cast<const MsgParam<X>*> (this) != 0; } /*! \brief utility for parameter convertion \param errvalue the returned value when no conversion applies \return the parameter value when the type matches */ template<typename X> X value(X errvalue) const { const MsgParam<X>* o = dynamic_cast<const MsgParam<X>*> (this); return o ? o->getValue() : errvalue; } /*! \brief utility for parameter comparison */ template<typename X> bool equal(const baseparam& p) const { const MsgParam<X>* a = dynamic_cast<const MsgParam<X>*> (this); const MsgParam<X>* b = dynamic_cast<const MsgParam<X>*> (&p); return a && b && (a->getValue() == b->getValue()); } /*! \brief utility for parameter comparison */ bool operator==(const baseparam& p) const { return equal<float>(p) || equal<int>(p) || equal<std::string>(p); } bool operator!=(const baseparam& p) const { return !equal<float>(p) && !equal<int>(p) && !equal<std::string>(p); } virtual SMARTP<baseparam> copy() const = 0; }; //-------------------------------------------------------------------------- /*! \brief template for a message parameter */ template <typename T> class MsgParam : public baseparam { T fParam; public: MsgParam(T val) : fParam(val) {} virtual ~MsgParam() {} T getValue() const { return fParam; } virtual Sbaseparam copy() const { return new MsgParam<T>(fParam); } }; //-------------------------------------------------------------------------- /*! \brief a message description A message is composed of an address (actually an OSC address), a message string that may be viewed as a method name and a list of message parameters. */ class Message { public: typedef SMARTP<baseparam> argPtr; ///< a message argument ptr type typedef std::vector<argPtr> argslist; ///< args list type private: unsigned long fSrcIP; ///< the message source IP number std::string fAddress; ///< the message osc destination address std::string fAlias; ///< the message alias osc destination address argslist fArguments; ///< the message arguments public: /*! \brief an empty message constructor */ Message() {} /*! \brief a message constructor \param address the message destination address */ Message(const std::string& address) : fAddress(address), fAlias("") {} Message(const std::string& address, const std::string& alias) : fAddress(address), fAlias(alias) {} /*! \brief a message constructor \param address the message destination address \param args the message parameters */ Message(const std::string& address, const argslist& args) : fAddress(address), fArguments(args) {} /*! \brief a message constructor \param msg a message */ Message(const Message& msg); virtual ~Message() {} //{ freed++; std::cout << "running messages: " << (allocated - freed) << std::endl; } /*! \brief adds a parameter to the message \param val the parameter */ template <typename T> void add(T val) { fArguments.push_back(new MsgParam<T>(val)); } /*! \brief adds a float parameter to the message \param val the parameter value */ void add(float val) { add<float>(val); } /*! \brief adds a double parameter to the message \param val the parameter value */ void add(double val) { add<double>(val); } /*! \brief adds an int parameter to the message \param val the parameter value */ void add(int val) { add<int>(val); } /*! \brief adds a string parameter to the message \param val the parameter value */ void add(const std::string& val) { add<std::string>(val); } /*! \brief adds a parameter to the message \param val the parameter */ void add(argPtr val) { fArguments.push_back( val ); } /*! \brief sets the message address \param addr the address */ void setSrcIP(unsigned long addr) { fSrcIP = addr; } /*! \brief sets the message address \param addr the address */ void setAddress(const std::string& addr) { fAddress = addr; } /*! \brief print the message \param out the output stream */ void print(std::ostream& out) const; /*! \brief send the message to OSC \param out the OSC output stream */ void print(OSCStream& out) const; /*! \brief print message arguments \param out the OSC output stream */ void printArgs(OSCStream& out) const; /// \brief gives the message address const std::string& address() const { return fAddress; } /// \brief gives the message alias const std::string& alias() const { return fAlias; } /// \brief gives the message parameters list const argslist& params() const { return fArguments; } /// \brief gives the message parameters list argslist& params() { return fArguments; } /// \brief gives the message source IP unsigned long src() const { return fSrcIP; } /// \brief gives the message parameters count int size() const { return (int)fArguments.size(); } bool operator == (const Message& other) const; /*! \brief gives a message float parameter \param i the parameter index (0 <= i < size()) \param val on output: the parameter value when the parameter type matches \return false when types don't match */ bool param(int i, float& val) const { val = params()[i]->value<float>(val); return params()[i]->isType<float>(); } /*! \brief gives a message double parameter \param i the parameter index (0 <= i < size()) \param val on output: the parameter value when the parameter type matches \return false when types don't match */ bool param(int i, double& val) const { val = params()[i]->value<double>(val); return params()[i]->isType<double>(); } /*! \brief gives a message int parameter \param i the parameter index (0 <= i < size()) \param val on output: the parameter value when the parameter type matches \return false when types don't match */ bool param(int i, int& val) const { val = params()[i]->value<int>(val); return params()[i]->isType<int>(); } /*! \brief gives a message int parameter \param i the parameter index (0 <= i < size()) \param val on output: the parameter value when the parameter type matches \return false when types don't match */ bool param(int i, unsigned int& val) const { val = params()[i]->value<int>(val); return params()[i]->isType<int>(); } /*! \brief gives a message int parameter \param i the parameter index (0 <= i < size()) \param val on output: the parameter value when the parameter type matches \return false when types don't match \note a boolean value is handled as integer */ bool param(int i, bool& val) const { int ival = 0; ival = params()[i]->value<int>(ival); val = ival!=0; return params()[i]->isType<int>(); } /*! \brief gives a message int parameter \param i the parameter index (0 <= i < size()) \param val on output: the parameter value when the parameter type matches \return false when types don't match */ bool param(int i, long int& val) const { val = long(params()[i]->value<int>(val)); return params()[i]->isType<int>(); } /*! \brief gives a message string parameter \param i the parameter index (0 <= i < size()) \param val on output: the parameter value when the parameter type matches \return false when types don't match */ bool param(int i, std::string& val) const { val = params()[i]->value<std::string>(val); return params()[i]->isType<std::string>(); } }; } // end namespoace #endif /************************** BEGIN GUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __GUI_H__ #define __GUI_H__ #include <list> #include <map> #include <vector> #include <iostream> #include <assert.h> #ifdef _WIN32 # pragma warning (disable: 4100) #else # pragma GCC diagnostic ignored "-Wunused-parameter" #endif /************************** BEGIN ValueConverter.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __ValueConverter__ #define __ValueConverter__ /*************************************************************************************** ValueConverter.h (GRAME, Copyright 2015-2019) Set of conversion objects used to map user interface values (for example a gui slider delivering values between 0 and 1) to faust values (for example a vslider between 20 and 20000) using a log scale. -- Utilities Range(lo,hi) : clip a value x between lo and hi Interpolator(lo,hi,v1,v2) : Maps a value x between lo and hi to a value y between v1 and v2 Interpolator3pt(lo,mi,hi,v1,vm,v2) : Map values between lo mid hi to values between v1 vm v2 -- Value Converters ValueConverter::ui2faust(x) ValueConverter::faust2ui(x) -- ValueConverters used for sliders depending of the scale LinearValueConverter(umin, umax, fmin, fmax) LinearValueConverter2(lo, mi, hi, v1, vm, v2) using 2 segments LogValueConverter(umin, umax, fmin, fmax) ExpValueConverter(umin, umax, fmin, fmax) -- ValueConverters used for accelerometers based on 3 points AccUpConverter(amin, amid, amax, fmin, fmid, fmax) -- curve 0 AccDownConverter(amin, amid, amax, fmin, fmid, fmax) -- curve 1 AccUpDownConverter(amin, amid, amax, fmin, fmid, fmax) -- curve 2 AccDownUpConverter(amin, amid, amax, fmin, fmid, fmax) -- curve 3 -- lists of ZoneControl are used to implement accelerometers metadata for each axes ZoneControl(zone, valueConverter) : a zone with an accelerometer data converter -- ZoneReader are used to implement screencolor metadata ZoneReader(zone, valueConverter) : a zone with a data converter ****************************************************************************************/ #include <float.h> #include <algorithm> // std::max #include <cmath> #include <vector> #include <assert.h> //-------------------------------------------------------------------------------------- // Interpolator(lo,hi,v1,v2) // Maps a value x between lo and hi to a value y between v1 and v2 // y = v1 + (x-lo)/(hi-lo)*(v2-v1) // y = v1 + (x-lo) * coef with coef = (v2-v1)/(hi-lo) // y = v1 + x*coef - lo*coef // y = v1 - lo*coef + x*coef // y = offset + x*coef with offset = v1 - lo*coef //-------------------------------------------------------------------------------------- class Interpolator { private: //-------------------------------------------------------------------------------------- // Range(lo,hi) clip a value between lo and hi //-------------------------------------------------------------------------------------- struct Range { double fLo; double fHi; Range(double x, double y) : fLo(std::min<double>(x,y)), fHi(std::max<double>(x,y)) {} double operator()(double x) { return (x<fLo) ? fLo : (x>fHi) ? fHi : x; } }; Range fRange; double fCoef; double fOffset; public: Interpolator(double lo, double hi, double v1, double v2) : fRange(lo,hi) { if (hi != lo) { // regular case fCoef = (v2-v1)/(hi-lo); fOffset = v1 - lo*fCoef; } else { // degenerate case, avoids division by zero fCoef = 0; fOffset = (v1+v2)/2; } } double operator()(double v) { double x = fRange(v); return fOffset + x*fCoef; } void getLowHigh(double& amin, double& amax) { amin = fRange.fLo; amax = fRange.fHi; } }; //-------------------------------------------------------------------------------------- // Interpolator3pt(lo,mi,hi,v1,vm,v2) // Map values between lo mid hi to values between v1 vm v2 //-------------------------------------------------------------------------------------- class Interpolator3pt { private: Interpolator fSegment1; Interpolator fSegment2; double fMid; public: Interpolator3pt(double lo, double mi, double hi, double v1, double vm, double v2) : fSegment1(lo, mi, v1, vm), fSegment2(mi, hi, vm, v2), fMid(mi) {} double operator()(double x) { return (x < fMid) ? fSegment1(x) : fSegment2(x); } void getMappingValues(double& amin, double& amid, double& amax) { fSegment1.getLowHigh(amin, amid); fSegment2.getLowHigh(amid, amax); } }; //-------------------------------------------------------------------------------------- // Abstract ValueConverter class. Converts values between UI and Faust representations //-------------------------------------------------------------------------------------- class ValueConverter { public: virtual ~ValueConverter() {} virtual double ui2faust(double x) = 0; virtual double faust2ui(double x) = 0; }; //-------------------------------------------------------------------------------------- // A converter than can be updated //-------------------------------------------------------------------------------------- class UpdatableValueConverter : public ValueConverter { protected: bool fActive; public: UpdatableValueConverter():fActive(true) {} virtual ~UpdatableValueConverter() {} virtual void setMappingValues(double amin, double amid, double amax, double min, double init, double max) = 0; virtual void getMappingValues(double& amin, double& amid, double& amax) = 0; void setActive(bool on_off) { fActive = on_off; } bool getActive() { return fActive; } }; //-------------------------------------------------------------------------------------- // Linear conversion between ui and Faust values //-------------------------------------------------------------------------------------- class LinearValueConverter : public ValueConverter { private: Interpolator fUI2F; Interpolator fF2UI; public: LinearValueConverter(double umin, double umax, double fmin, double fmax) : fUI2F(umin,umax,fmin,fmax), fF2UI(fmin,fmax,umin,umax) {} LinearValueConverter() : fUI2F(0.,0.,0.,0.), fF2UI(0.,0.,0.,0.) {} virtual double ui2faust(double x) { return fUI2F(x); } virtual double faust2ui(double x) { return fF2UI(x); } }; //-------------------------------------------------------------------------------------- // Two segments linear conversion between ui and Faust values //-------------------------------------------------------------------------------------- class LinearValueConverter2 : public UpdatableValueConverter { private: Interpolator3pt fUI2F; Interpolator3pt fF2UI; public: LinearValueConverter2(double amin, double amid, double amax, double min, double init, double max) : fUI2F(amin, amid, amax, min, init, max), fF2UI(min, init, max, amin, amid, amax) {} LinearValueConverter2() : fUI2F(0.,0.,0.,0.,0.,0.), fF2UI(0.,0.,0.,0.,0.,0.) {} virtual double ui2faust(double x) { return fUI2F(x); } virtual double faust2ui(double x) { return fF2UI(x); } virtual void setMappingValues(double amin, double amid, double amax, double min, double init, double max) { fUI2F = Interpolator3pt(amin, amid, amax, min, init, max); fF2UI = Interpolator3pt(min, init, max, amin, amid, amax); } virtual void getMappingValues(double& amin, double& amid, double& amax) { fUI2F.getMappingValues(amin, amid, amax); } }; //-------------------------------------------------------------------------------------- // Logarithmic conversion between ui and Faust values //-------------------------------------------------------------------------------------- class LogValueConverter : public LinearValueConverter { public: LogValueConverter(double umin, double umax, double fmin, double fmax) : LinearValueConverter(umin, umax, std::log(std::max<double>(DBL_MIN, fmin)), std::log(std::max<double>(DBL_MIN, fmax))) {} virtual double ui2faust(double x) { return std::exp(LinearValueConverter::ui2faust(x)); } virtual double faust2ui(double x) { return LinearValueConverter::faust2ui(std::log(std::max<double>(x, DBL_MIN))); } }; //-------------------------------------------------------------------------------------- // Exponential conversion between ui and Faust values //-------------------------------------------------------------------------------------- class ExpValueConverter : public LinearValueConverter { public: ExpValueConverter(double umin, double umax, double fmin, double fmax) : LinearValueConverter(umin, umax, std::min<double>(DBL_MAX, std::exp(fmin)), std::min<double>(DBL_MAX, std::exp(fmax))) {} virtual double ui2faust(double x) { return std::log(LinearValueConverter::ui2faust(x)); } virtual double faust2ui(double x) { return LinearValueConverter::faust2ui(std::min<double>(DBL_MAX, std::exp(x))); } }; //-------------------------------------------------------------------------------------- // Convert accelerometer or gyroscope values to Faust values // Using an Up curve (curve 0) //-------------------------------------------------------------------------------------- class AccUpConverter : public UpdatableValueConverter { private: Interpolator3pt fA2F; Interpolator3pt fF2A; public: AccUpConverter(double amin, double amid, double amax, double fmin, double fmid, double fmax) : fA2F(amin,amid,amax,fmin,fmid,fmax), fF2A(fmin,fmid,fmax,amin,amid,amax) {} virtual double ui2faust(double x) { return fA2F(x); } virtual double faust2ui(double x) { return fF2A(x); } virtual void setMappingValues(double amin, double amid, double amax, double fmin, double fmid, double fmax) { //__android_log_print(ANDROID_LOG_ERROR, "Faust", "AccUpConverter update %f %f %f %f %f %f", amin,amid,amax,fmin,fmid,fmax); fA2F = Interpolator3pt(amin, amid, amax, fmin, fmid, fmax); fF2A = Interpolator3pt(fmin, fmid, fmax, amin, amid, amax); } virtual void getMappingValues(double& amin, double& amid, double& amax) { fA2F.getMappingValues(amin, amid, amax); } }; //-------------------------------------------------------------------------------------- // Convert accelerometer or gyroscope values to Faust values // Using a Down curve (curve 1) //-------------------------------------------------------------------------------------- class AccDownConverter : public UpdatableValueConverter { private: Interpolator3pt fA2F; Interpolator3pt fF2A; public: AccDownConverter(double amin, double amid, double amax, double fmin, double fmid, double fmax) : fA2F(amin,amid,amax,fmax,fmid,fmin), fF2A(fmin,fmid,fmax,amax,amid,amin) {} virtual double ui2faust(double x) { return fA2F(x); } virtual double faust2ui(double x) { return fF2A(x); } virtual void setMappingValues(double amin, double amid, double amax, double fmin, double fmid, double fmax) { //__android_log_print(ANDROID_LOG_ERROR, "Faust", "AccDownConverter update %f %f %f %f %f %f", amin,amid,amax,fmin,fmid,fmax); fA2F = Interpolator3pt(amin, amid, amax, fmax, fmid, fmin); fF2A = Interpolator3pt(fmin, fmid, fmax, amax, amid, amin); } virtual void getMappingValues(double& amin, double& amid, double& amax) { fA2F.getMappingValues(amin, amid, amax); } }; //-------------------------------------------------------------------------------------- // Convert accelerometer or gyroscope values to Faust values // Using an Up-Down curve (curve 2) //-------------------------------------------------------------------------------------- class AccUpDownConverter : public UpdatableValueConverter { private: Interpolator3pt fA2F; Interpolator fF2A; public: AccUpDownConverter(double amin, double amid, double amax, double fmin, double fmid, double fmax) : fA2F(amin,amid,amax,fmin,fmax,fmin), fF2A(fmin,fmax,amin,amax) // Special, pseudo inverse of a non monotonic function {} virtual double ui2faust(double x) { return fA2F(x); } virtual double faust2ui(double x) { return fF2A(x); } virtual void setMappingValues(double amin, double amid, double amax, double fmin, double fmid, double fmax) { //__android_log_print(ANDROID_LOG_ERROR, "Faust", "AccUpDownConverter update %f %f %f %f %f %f", amin,amid,amax,fmin,fmid,fmax); fA2F = Interpolator3pt(amin, amid, amax, fmin, fmax, fmin); fF2A = Interpolator(fmin, fmax, amin, amax); } virtual void getMappingValues(double& amin, double& amid, double& amax) { fA2F.getMappingValues(amin, amid, amax); } }; //-------------------------------------------------------------------------------------- // Convert accelerometer or gyroscope values to Faust values // Using a Down-Up curve (curve 3) //-------------------------------------------------------------------------------------- class AccDownUpConverter : public UpdatableValueConverter { private: Interpolator3pt fA2F; Interpolator fF2A; public: AccDownUpConverter(double amin, double amid, double amax, double fmin, double fmid, double fmax) : fA2F(amin,amid,amax,fmax,fmin,fmax), fF2A(fmin,fmax,amin,amax) // Special, pseudo inverse of a non monotonic function {} virtual double ui2faust(double x) { return fA2F(x); } virtual double faust2ui(double x) { return fF2A(x); } virtual void setMappingValues(double amin, double amid, double amax, double fmin, double fmid, double fmax) { //__android_log_print(ANDROID_LOG_ERROR, "Faust", "AccDownUpConverter update %f %f %f %f %f %f", amin,amid,amax,fmin,fmid,fmax); fA2F = Interpolator3pt(amin, amid, amax, fmax, fmin, fmax); fF2A = Interpolator(fmin, fmax, amin, amax); } virtual void getMappingValues(double& amin, double& amid, double& amax) { fA2F.getMappingValues(amin, amid, amax); } }; //-------------------------------------------------------------------------------------- // Base class for ZoneControl //-------------------------------------------------------------------------------------- class ZoneControl { protected: FAUSTFLOAT* fZone; public: ZoneControl(FAUSTFLOAT* zone) : fZone(zone) {} virtual ~ZoneControl() {} virtual void update(double v) {} virtual void setMappingValues(int curve, double amin, double amid, double amax, double min, double init, double max) {} virtual void getMappingValues(double& amin, double& amid, double& amax) {} FAUSTFLOAT* getZone() { return fZone; } virtual void setActive(bool on_off) {} virtual bool getActive() { return false; } virtual int getCurve() { return -1; } }; //-------------------------------------------------------------------------------------- // Useful to implement accelerometers metadata as a list of ZoneControl for each axes //-------------------------------------------------------------------------------------- class ConverterZoneControl : public ZoneControl { protected: ValueConverter* fValueConverter; public: ConverterZoneControl(FAUSTFLOAT* zone, ValueConverter* converter) : ZoneControl(zone), fValueConverter(converter) {} virtual ~ConverterZoneControl() { delete fValueConverter; } // Assuming fValueConverter is not kept elsewhere... virtual void update(double v) { *fZone = fValueConverter->ui2faust(v); } ValueConverter* getConverter() { return fValueConverter; } }; //-------------------------------------------------------------------------------------- // Association of a zone and a four value converter, each one for each possible curve. // Useful to implement accelerometers metadata as a list of ZoneControl for each axes //-------------------------------------------------------------------------------------- class CurveZoneControl : public ZoneControl { private: std::vector<UpdatableValueConverter*> fValueConverters; int fCurve; public: CurveZoneControl(FAUSTFLOAT* zone, int curve, double amin, double amid, double amax, double min, double init, double max) : ZoneControl(zone), fCurve(0) { assert(curve >= 0 && curve <= 3); fValueConverters.push_back(new AccUpConverter(amin, amid, amax, min, init, max)); fValueConverters.push_back(new AccDownConverter(amin, amid, amax, min, init, max)); fValueConverters.push_back(new AccUpDownConverter(amin, amid, amax, min, init, max)); fValueConverters.push_back(new AccDownUpConverter(amin, amid, amax, min, init, max)); fCurve = curve; } virtual ~CurveZoneControl() { std::vector<UpdatableValueConverter*>::iterator it; for (it = fValueConverters.begin(); it != fValueConverters.end(); it++) { delete(*it); } } void update(double v) { if (fValueConverters[fCurve]->getActive()) *fZone = fValueConverters[fCurve]->ui2faust(v); } void setMappingValues(int curve, double amin, double amid, double amax, double min, double init, double max) { fValueConverters[curve]->setMappingValues(amin, amid, amax, min, init, max); fCurve = curve; } void getMappingValues(double& amin, double& amid, double& amax) { fValueConverters[fCurve]->getMappingValues(amin, amid, amax); } void setActive(bool on_off) { std::vector<UpdatableValueConverter*>::iterator it; for (it = fValueConverters.begin(); it != fValueConverters.end(); it++) { (*it)->setActive(on_off); } } int getCurve() { return fCurve; } }; class ZoneReader { private: FAUSTFLOAT* fZone; Interpolator fInterpolator; public: ZoneReader(FAUSTFLOAT* zone, double lo, double hi) : fZone(zone), fInterpolator(lo, hi, 0, 255) {} virtual ~ZoneReader() {} int getValue() { return (fZone != nullptr) ? int(fInterpolator(*fZone)) : 127; } }; #endif /************************** END ValueConverter.h **************************/ /************************** BEGIN MetaDataUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef MetaData_UI_H #define MetaData_UI_H #ifndef FAUSTFLOAT #define FAUSTFLOAT float #endif #include <map> #include <set> #include <string> #include <string.h> #include <assert.h> static bool startWith(const std::string& str, const std::string& prefix) { return (str.substr(0, prefix.size()) == prefix); } /** * Convert a dB value into a scale between 0 and 1 (following IEC standard ?) */ static FAUSTFLOAT dB2Scale(FAUSTFLOAT dB) { FAUSTFLOAT scale = FAUSTFLOAT(1.0); /*if (dB < -70.0f) scale = 0.0f; else*/ if (dB < FAUSTFLOAT(-60.0)) scale = (dB + FAUSTFLOAT(70.0)) * FAUSTFLOAT(0.0025); else if (dB < FAUSTFLOAT(-50.0)) scale = (dB + FAUSTFLOAT(60.0)) * FAUSTFLOAT(0.005) + FAUSTFLOAT(0.025); else if (dB < FAUSTFLOAT(-40.0)) scale = (dB + FAUSTFLOAT(50.0)) * FAUSTFLOAT(0.0075) + FAUSTFLOAT(0.075); else if (dB < FAUSTFLOAT(-30.0)) scale = (dB + FAUSTFLOAT(40.0)) * FAUSTFLOAT(0.015) + FAUSTFLOAT(0.15); else if (dB < FAUSTFLOAT(-20.0)) scale = (dB + FAUSTFLOAT(30.0)) * FAUSTFLOAT(0.02) + FAUSTFLOAT(0.3); else if (dB < FAUSTFLOAT(-0.001) || dB > FAUSTFLOAT(0.001)) /* if (dB < 0.0) */ scale = (dB + FAUSTFLOAT(20.0)) * FAUSTFLOAT(0.025) + FAUSTFLOAT(0.5); return scale; } /******************************************************************************* * MetaDataUI : Common class for MetaData handling ******************************************************************************/ //============================= BEGIN GROUP LABEL METADATA=========================== // Unlike widget's label, metadata inside group's label are not extracted directly by // the Faust compiler. Therefore they must be extracted within the architecture file //----------------------------------------------------------------------------------- class MetaDataUI { protected: std::string fGroupTooltip; std::map<FAUSTFLOAT*, FAUSTFLOAT> fGuiSize; // map widget zone with widget size coef std::map<FAUSTFLOAT*, std::string> fTooltip; // map widget zone with tooltip strings std::map<FAUSTFLOAT*, std::string> fUnit; // map widget zone to unit string (i.e. "dB") std::map<FAUSTFLOAT*, std::string> fRadioDescription; // map zone to {'low':440; ...; 'hi':1000.0} std::map<FAUSTFLOAT*, std::string> fMenuDescription; // map zone to {'low':440; ...; 'hi':1000.0} std::set<FAUSTFLOAT*> fKnobSet; // set of widget zone to be knobs std::set<FAUSTFLOAT*> fLedSet; // set of widget zone to be LEDs std::set<FAUSTFLOAT*> fNumSet; // set of widget zone to be numerical bargraphs std::set<FAUSTFLOAT*> fLogSet; // set of widget zone having a log UI scale std::set<FAUSTFLOAT*> fExpSet; // set of widget zone having an exp UI scale std::set<FAUSTFLOAT*> fHiddenSet; // set of hidden widget zone void clearMetadata() { fGuiSize.clear(); fTooltip.clear(); fUnit.clear(); fRadioDescription.clear(); fMenuDescription.clear(); fKnobSet.clear(); fLedSet.clear(); fNumSet.clear(); fLogSet.clear(); fExpSet.clear(); fHiddenSet.clear(); } /** * rmWhiteSpaces(): Remove the leading and trailing white spaces of a string * (but not those in the middle of the string) */ static std::string rmWhiteSpaces(const std::string& s) { size_t i = s.find_first_not_of(" \t"); size_t j = s.find_last_not_of(" \t"); if ((i != std::string::npos) && (j != std::string::npos)) { return s.substr(i, 1+j-i); } else { return ""; } } /** * Format tooltip string by replacing some white spaces by * return characters so that line width doesn't exceed n. * Limitation : long words exceeding n are not cut */ std::string formatTooltip(int n, const std::string& tt) { std::string ss = tt; // ss string we are going to format int lws = 0; // last white space encountered int lri = 0; // last return inserted for (int i = 0; i < (int)tt.size(); i++) { if (tt[i] == ' ') lws = i; if (((i-lri) >= n) && (lws > lri)) { // insert return here ss[lws] = '\n'; lri = lws; } } return ss; } public: virtual ~MetaDataUI() {} enum Scale { kLin, kLog, kExp }; Scale getScale(FAUSTFLOAT* zone) { if (fLogSet.count(zone) > 0) return kLog; if (fExpSet.count(zone) > 0) return kExp; return kLin; } bool isKnob(FAUSTFLOAT* zone) { return fKnobSet.count(zone) > 0; } bool isRadio(FAUSTFLOAT* zone) { return fRadioDescription.count(zone) > 0; } bool isMenu(FAUSTFLOAT* zone) { return fMenuDescription.count(zone) > 0; } bool isLed(FAUSTFLOAT* zone) { return fLedSet.count(zone) > 0; } bool isNumerical(FAUSTFLOAT* zone) { return fNumSet.count(zone) > 0; } bool isHidden(FAUSTFLOAT* zone) { return fHiddenSet.count(zone) > 0; } /** * Extracts metadata from a label : 'vol [unit: dB]' -> 'vol' + metadata(unit=dB) */ static void extractMetadata(const std::string& fulllabel, std::string& label, std::map<std::string, std::string>& metadata) { enum {kLabel, kEscape1, kEscape2, kEscape3, kKey, kValue}; int state = kLabel; int deep = 0; std::string key, value; for (unsigned int i = 0; i < fulllabel.size(); i++) { char c = fulllabel[i]; switch (state) { case kLabel : assert(deep == 0); switch (c) { case '\\' : state = kEscape1; break; case '[' : state = kKey; deep++; break; default : label += c; } break; case kEscape1: label += c; state = kLabel; break; case kEscape2: key += c; state = kKey; break; case kEscape3: value += c; state = kValue; break; case kKey: assert(deep > 0); switch (c) { case '\\': state = kEscape2; break; case '[': deep++; key += c; break; case ':': if (deep == 1) { state = kValue; } else { key += c; } break; case ']': deep--; if (deep < 1) { metadata[rmWhiteSpaces(key)] = ""; state = kLabel; key=""; value=""; } else { key += c; } break; default : key += c; } break; case kValue: assert(deep > 0); switch (c) { case '\\': state = kEscape3; break; case '[': deep++; value += c; break; case ']': deep--; if (deep < 1) { metadata[rmWhiteSpaces(key)] = rmWhiteSpaces(value); state = kLabel; key = ""; value = ""; } else { value += c; } break; default : value += c; } break; default: std::cerr << "ERROR unrecognized state " << state << std::endl; } } label = rmWhiteSpaces(label); } /** * Analyses the widget zone metadata declarations and takes appropriate actions */ void declare(FAUSTFLOAT* zone, const char* key, const char* value) { if (zone == 0) { // special zone 0 means group metadata if (strcmp(key, "tooltip") == 0) { // only group tooltip are currently implemented fGroupTooltip = formatTooltip(30, value); } else if (strcmp(key, "hidden") == 0) { fHiddenSet.insert(zone); } } else { if (strcmp(key, "size") == 0) { fGuiSize[zone] = atof(value); } else if (strcmp(key, "tooltip") == 0) { fTooltip[zone] = formatTooltip(30, value); } else if (strcmp(key, "unit") == 0) { fUnit[zone] = value; } else if (strcmp(key, "hidden") == 0) { fHiddenSet.insert(zone); } else if (strcmp(key, "scale") == 0) { if (strcmp(value, "log") == 0) { fLogSet.insert(zone); } else if (strcmp(value, "exp") == 0) { fExpSet.insert(zone); } } else if (strcmp(key, "style") == 0) { if (strcmp(value, "knob") == 0) { fKnobSet.insert(zone); } else if (strcmp(value, "led") == 0) { fLedSet.insert(zone); } else if (strcmp(value, "numerical") == 0) { fNumSet.insert(zone); } else { const char* p = value; if (parseWord(p, "radio")) { fRadioDescription[zone] = std::string(p); } else if (parseWord(p, "menu")) { fMenuDescription[zone] = std::string(p); } } } } } }; #endif /************************** END MetaDataUI.h **************************/ /************************** BEGIN ring-buffer.h **************************/ /* Copyright (C) 2000 Paul Davis Copyright (C) 2003 Rohan Drape Copyright (C) 2016 GRAME (renaming for internal use) This program is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ISO/POSIX C version of Paul Davis's lock free ringbuffer C++ code. This is safe for the case of one read thread and one write thread. */ #ifndef __ring_buffer__ #define __ring_buffer__ #include <stdlib.h> #include <string.h> #ifdef WIN32 # pragma warning (disable: 4334) #else # pragma GCC diagnostic ignored "-Wunused-function" #endif typedef struct { char *buf; size_t len; } ringbuffer_data_t; typedef struct { char *buf; volatile size_t write_ptr; volatile size_t read_ptr; size_t size; size_t size_mask; int mlocked; } ringbuffer_t; static ringbuffer_t *ringbuffer_create(size_t sz); static void ringbuffer_free(ringbuffer_t *rb); static void ringbuffer_get_read_vector(const ringbuffer_t *rb, ringbuffer_data_t *vec); static void ringbuffer_get_write_vector(const ringbuffer_t *rb, ringbuffer_data_t *vec); static size_t ringbuffer_read(ringbuffer_t *rb, char *dest, size_t cnt); static size_t ringbuffer_peek(ringbuffer_t *rb, char *dest, size_t cnt); static void ringbuffer_read_advance(ringbuffer_t *rb, size_t cnt); static size_t ringbuffer_read_space(const ringbuffer_t *rb); static int ringbuffer_mlock(ringbuffer_t *rb); static void ringbuffer_reset(ringbuffer_t *rb); static void ringbuffer_reset_size (ringbuffer_t * rb, size_t sz); static size_t ringbuffer_write(ringbuffer_t *rb, const char *src, size_t cnt); static void ringbuffer_write_advance(ringbuffer_t *rb, size_t cnt); static size_t ringbuffer_write_space(const ringbuffer_t *rb); /* Create a new ringbuffer to hold at least `sz' bytes of data. The actual buffer size is rounded up to the next power of two. */ static ringbuffer_t * ringbuffer_create (size_t sz) { size_t power_of_two; ringbuffer_t *rb; if ((rb = (ringbuffer_t *) malloc (sizeof (ringbuffer_t))) == NULL) { return NULL; } for (power_of_two = 1u; 1u << power_of_two < sz; power_of_two++); rb->size = 1u << power_of_two; rb->size_mask = rb->size; rb->size_mask -= 1; rb->write_ptr = 0; rb->read_ptr = 0; if ((rb->buf = (char *) malloc (rb->size)) == NULL) { free (rb); return NULL; } rb->mlocked = 0; return rb; } /* Free all data associated with the ringbuffer `rb'. */ static void ringbuffer_free (ringbuffer_t * rb) { #ifdef USE_MLOCK if (rb->mlocked) { munlock (rb->buf, rb->size); } #endif /* USE_MLOCK */ free (rb->buf); free (rb); } /* Lock the data block of `rb' using the system call 'mlock'. */ static int ringbuffer_mlock (ringbuffer_t * rb) { #ifdef USE_MLOCK if (mlock (rb->buf, rb->size)) { return -1; } #endif /* USE_MLOCK */ rb->mlocked = 1; return 0; } /* Reset the read and write pointers to zero. This is not thread safe. */ static void ringbuffer_reset (ringbuffer_t * rb) { rb->read_ptr = 0; rb->write_ptr = 0; memset(rb->buf, 0, rb->size); } /* Reset the read and write pointers to zero. This is not thread safe. */ static void ringbuffer_reset_size (ringbuffer_t * rb, size_t sz) { rb->size = sz; rb->size_mask = rb->size; rb->size_mask -= 1; rb->read_ptr = 0; rb->write_ptr = 0; } /* Return the number of bytes available for reading. This is the number of bytes in front of the read pointer and behind the write pointer. */ static size_t ringbuffer_read_space (const ringbuffer_t * rb) { size_t w, r; w = rb->write_ptr; r = rb->read_ptr; if (w > r) { return w - r; } else { return (w - r + rb->size) & rb->size_mask; } } /* Return the number of bytes available for writing. This is the number of bytes in front of the write pointer and behind the read pointer. */ static size_t ringbuffer_write_space (const ringbuffer_t * rb) { size_t w, r; w = rb->write_ptr; r = rb->read_ptr; if (w > r) { return ((r - w + rb->size) & rb->size_mask) - 1; } else if (w < r) { return (r - w) - 1; } else { return rb->size - 1; } } /* The copying data reader. Copy at most `cnt' bytes from `rb' to `dest'. Returns the actual number of bytes copied. */ static size_t ringbuffer_read (ringbuffer_t * rb, char *dest, size_t cnt) { size_t free_cnt; size_t cnt2; size_t to_read; size_t n1, n2; if ((free_cnt = ringbuffer_read_space (rb)) == 0) { return 0; } to_read = cnt > free_cnt ? free_cnt : cnt; cnt2 = rb->read_ptr + to_read; if (cnt2 > rb->size) { n1 = rb->size - rb->read_ptr; n2 = cnt2 & rb->size_mask; } else { n1 = to_read; n2 = 0; } memcpy (dest, &(rb->buf[rb->read_ptr]), n1); rb->read_ptr = (rb->read_ptr + n1) & rb->size_mask; if (n2) { memcpy (dest + n1, &(rb->buf[rb->read_ptr]), n2); rb->read_ptr = (rb->read_ptr + n2) & rb->size_mask; } return to_read; } /* The copying data reader w/o read pointer advance. Copy at most `cnt' bytes from `rb' to `dest'. Returns the actual number of bytes copied. */ static size_t ringbuffer_peek (ringbuffer_t * rb, char *dest, size_t cnt) { size_t free_cnt; size_t cnt2; size_t to_read; size_t n1, n2; size_t tmp_read_ptr; tmp_read_ptr = rb->read_ptr; if ((free_cnt = ringbuffer_read_space (rb)) == 0) { return 0; } to_read = cnt > free_cnt ? free_cnt : cnt; cnt2 = tmp_read_ptr + to_read; if (cnt2 > rb->size) { n1 = rb->size - tmp_read_ptr; n2 = cnt2 & rb->size_mask; } else { n1 = to_read; n2 = 0; } memcpy (dest, &(rb->buf[tmp_read_ptr]), n1); tmp_read_ptr = (tmp_read_ptr + n1) & rb->size_mask; if (n2) { memcpy (dest + n1, &(rb->buf[tmp_read_ptr]), n2); } return to_read; } /* The copying data writer. Copy at most `cnt' bytes to `rb' from `src'. Returns the actual number of bytes copied. */ static size_t ringbuffer_write (ringbuffer_t * rb, const char *src, size_t cnt) { size_t free_cnt; size_t cnt2; size_t to_write; size_t n1, n2; if ((free_cnt = ringbuffer_write_space (rb)) == 0) { return 0; } to_write = cnt > free_cnt ? free_cnt : cnt; cnt2 = rb->write_ptr + to_write; if (cnt2 > rb->size) { n1 = rb->size - rb->write_ptr; n2 = cnt2 & rb->size_mask; } else { n1 = to_write; n2 = 0; } memcpy (&(rb->buf[rb->write_ptr]), src, n1); rb->write_ptr = (rb->write_ptr + n1) & rb->size_mask; if (n2) { memcpy (&(rb->buf[rb->write_ptr]), src + n1, n2); rb->write_ptr = (rb->write_ptr + n2) & rb->size_mask; } return to_write; } /* Advance the read pointer `cnt' places. */ static void ringbuffer_read_advance (ringbuffer_t * rb, size_t cnt) { size_t tmp = (rb->read_ptr + cnt) & rb->size_mask; rb->read_ptr = tmp; } /* Advance the write pointer `cnt' places. */ static void ringbuffer_write_advance (ringbuffer_t * rb, size_t cnt) { size_t tmp = (rb->write_ptr + cnt) & rb->size_mask; rb->write_ptr = tmp; } /* The non-copying data reader. `vec' is an array of two places. Set the values at `vec' to hold the current readable data at `rb'. If the readable data is in one segment the second segment has zero length. */ static void ringbuffer_get_read_vector (const ringbuffer_t * rb, ringbuffer_data_t * vec) { size_t free_cnt; size_t cnt2; size_t w, r; w = rb->write_ptr; r = rb->read_ptr; if (w > r) { free_cnt = w - r; } else { free_cnt = (w - r + rb->size) & rb->size_mask; } cnt2 = r + free_cnt; if (cnt2 > rb->size) { /* Two part vector: the rest of the buffer after the current write ptr, plus some from the start of the buffer. */ vec[0].buf = &(rb->buf[r]); vec[0].len = rb->size - r; vec[1].buf = rb->buf; vec[1].len = cnt2 & rb->size_mask; } else { /* Single part vector: just the rest of the buffer */ vec[0].buf = &(rb->buf[r]); vec[0].len = free_cnt; vec[1].len = 0; } } /* The non-copying data writer. `vec' is an array of two places. Set the values at `vec' to hold the current writeable data at `rb'. If the writeable data is in one segment the second segment has zero length. */ static void ringbuffer_get_write_vector (const ringbuffer_t * rb, ringbuffer_data_t * vec) { size_t free_cnt; size_t cnt2; size_t w, r; w = rb->write_ptr; r = rb->read_ptr; if (w > r) { free_cnt = ((r - w + rb->size) & rb->size_mask) - 1; } else if (w < r) { free_cnt = (r - w) - 1; } else { free_cnt = rb->size - 1; } cnt2 = w + free_cnt; if (cnt2 > rb->size) { /* Two part vector: the rest of the buffer after the current write ptr, plus some from the start of the buffer. */ vec[0].buf = &(rb->buf[w]); vec[0].len = rb->size - w; vec[1].buf = rb->buf; vec[1].len = cnt2 & rb->size_mask; } else { vec[0].buf = &(rb->buf[w]); vec[0].len = free_cnt; vec[1].len = 0; } } #endif // __ring_buffer__ /************************** END ring-buffer.h **************************/ /******************************************************************************* * GUI : Abstract Graphic User Interface * Provides additional mechanisms to synchronize widgets and zones. Widgets * should both reflect the value of a zone and allow to change this value. ******************************************************************************/ class uiItem; class GUI; struct clist; typedef void (*uiCallback)(FAUSTFLOAT val, void* data); struct uiItemBase { uiItemBase(GUI* ui, FAUSTFLOAT* zone) { assert(ui); assert(zone); } virtual ~uiItemBase() {} virtual void modifyZone(FAUSTFLOAT v) = 0; virtual void modifyZone(double date, FAUSTFLOAT v) {} virtual double cache() = 0; virtual void reflectZone() = 0; }; // Declared as 'static' to avoid code duplication at link time static void deleteClist(clist* cl); struct clist : public std::list<uiItemBase*> { virtual ~clist() { deleteClist(this); } }; static void createUiCallbackItem(GUI* ui, FAUSTFLOAT* zone, uiCallback foo, void* data); typedef std::map<FAUSTFLOAT*, clist*> zmap; typedef std::map<FAUSTFLOAT*, ringbuffer_t*> ztimedmap; class GUI : public UI { private: static std::list<GUI*> fGuiList; zmap fZoneMap; bool fStopped; public: GUI():fStopped(false) { fGuiList.push_back(this); } virtual ~GUI() { // delete all items for (auto& it : fZoneMap) { delete it.second; } // suppress 'this' in static fGuiList fGuiList.remove(this); } // -- registerZone(z,c) : zone management void registerZone(FAUSTFLOAT* z, uiItemBase* c) { if (fZoneMap.find(z) == fZoneMap.end()) fZoneMap[z] = new clist(); fZoneMap[z]->push_back(c); } void updateZone(FAUSTFLOAT* z) { FAUSTFLOAT v = *z; clist* cl = fZoneMap[z]; for (auto& c : *cl) { if (c->cache() != v) c->reflectZone(); } } void updateAllZones() { for (auto& m : fZoneMap) { updateZone(m.first); } } static void updateAllGuis() { for (auto& g : fGuiList) { g->updateAllZones(); } } static void runAllGuis() { for (auto& g : fGuiList) { g->run(); } } void addCallback(FAUSTFLOAT* zone, uiCallback foo, void* data) { createUiCallbackItem(this, zone, foo, data); } virtual void show() {}; virtual bool run() { return false; }; virtual void stop() { fStopped = true; } bool stopped() { return fStopped; } // -- widget's layouts virtual void openTabBox(const char* label) {}; virtual void openHorizontalBox(const char* label) {} virtual void openVerticalBox(const char* label) {} virtual void closeBox() {} // -- active widgets virtual void addButton(const char* label, FAUSTFLOAT* zone) {} virtual void addCheckButton(const char* label, FAUSTFLOAT* zone) {} virtual void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {} virtual void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {} virtual void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) {} // -- passive widgets virtual void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) {} virtual void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) {} // -- soundfiles virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) {} // -- metadata declarations virtual void declare(FAUSTFLOAT*, const char*, const char*) {} // Static global for timed zones, shared between all UI that will set timed values static ztimedmap gTimedZoneMap; }; /** * User Interface Item: abstract definition */ template <typename REAL> class uiTypedItem : public uiItemBase { protected: GUI* fGUI; REAL* fZone; REAL fCache; uiTypedItem(GUI* ui, REAL* zone):uiItemBase(ui, static_cast<FAUSTFLOAT*>(zone)), fGUI(ui), fZone(zone), fCache(REAL(-123456.654321)) { ui->registerZone(zone, this); } public: virtual ~uiTypedItem() {} void modifyZone(REAL v) { fCache = v; if (*fZone != v) { *fZone = v; fGUI->updateZone(fZone); } } double cache() { return fCache; } }; class uiItem : public uiTypedItem<FAUSTFLOAT> { protected: uiItem(GUI* ui, FAUSTFLOAT* zone):uiTypedItem<FAUSTFLOAT>(ui, zone) {} public: virtual ~uiItem() {} void modifyZone(FAUSTFLOAT v) { fCache = v; if (*fZone != v) { *fZone = v; fGUI->updateZone(fZone); } } }; /** * Base class for items with a converter */ struct uiConverter { ValueConverter* fConverter; uiConverter(MetaDataUI::Scale scale, FAUSTFLOAT umin, FAUSTFLOAT umax, FAUSTFLOAT fmin, FAUSTFLOAT fmax) { // Select appropriate converter according to scale mode if (scale == MetaDataUI::kLog) { fConverter = new LogValueConverter(umin, umax, fmin, fmax); } else if (scale == MetaDataUI::kExp) { fConverter = new ExpValueConverter(umin, umax, fmin, fmax); } else { fConverter = new LinearValueConverter(umin, umax, fmin, fmax); } } virtual ~uiConverter() { delete fConverter; } }; /** * User Interface item owned (and so deleted) by external code */ class uiOwnedItem : public uiItem { protected: uiOwnedItem(GUI* ui, FAUSTFLOAT* zone):uiItem(ui, zone) {} public: virtual ~uiOwnedItem() {} virtual void reflectZone() {} }; /** * Callback Item */ class uiCallbackItem : public uiItem { protected: uiCallback fCallback; void* fData; public: uiCallbackItem(GUI* ui, FAUSTFLOAT* zone, uiCallback foo, void* data) : uiItem(ui, zone), fCallback(foo), fData(data) {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; fCallback(v, fData); } }; /** * For timestamped control */ struct DatedControl { double fDate; FAUSTFLOAT fValue; DatedControl(double d = 0., FAUSTFLOAT v = FAUSTFLOAT(0)):fDate(d), fValue(v) {} }; /** * Base class for timed items */ class uiTimedItem : public uiItem { protected: bool fDelete; public: using uiItem::modifyZone; uiTimedItem(GUI* ui, FAUSTFLOAT* zone):uiItem(ui, zone) { if (GUI::gTimedZoneMap.find(fZone) == GUI::gTimedZoneMap.end()) { GUI::gTimedZoneMap[fZone] = ringbuffer_create(8192); fDelete = true; } else { fDelete = false; } } virtual ~uiTimedItem() { ztimedmap::iterator it; if (fDelete && ((it = GUI::gTimedZoneMap.find(fZone)) != GUI::gTimedZoneMap.end())) { ringbuffer_free((*it).second); GUI::gTimedZoneMap.erase(it); } } virtual void modifyZone(double date, FAUSTFLOAT v) { size_t res; DatedControl dated_val(date, v); if ((res = ringbuffer_write(GUI::gTimedZoneMap[fZone], (const char*)&dated_val, sizeof(DatedControl))) != sizeof(DatedControl)) { std::cerr << "ringbuffer_write error DatedControl" << std::endl; } } }; /** * Allows to group a set of zones */ class uiGroupItem : public uiItem { protected: std::vector<FAUSTFLOAT*> fZoneMap; public: uiGroupItem(GUI* ui, FAUSTFLOAT* zone):uiItem(ui, zone) {} virtual ~uiGroupItem() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; // Update all zones of the same group for (auto& it : fZoneMap) { *it = v; } } void addZone(FAUSTFLOAT* zone) { fZoneMap.push_back(zone); } }; // Can not be defined as method in the classes static void createUiCallbackItem(GUI* ui, FAUSTFLOAT* zone, uiCallback foo, void* data) { new uiCallbackItem(ui, zone, foo, data); } static void deleteClist(clist* cl) { for (auto& it : *cl) { uiOwnedItem* owned = dynamic_cast<uiOwnedItem*>(it); // owned items are deleted by external code if (!owned) { delete it; } } } #endif /************************** END GUI.h **************************/ /* Copyright (C) 2011 Grame This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France [email protected] */ #ifndef __RootNode__ #define __RootNode__ #include <map> #include <string> #include <vector> /************************** BEGIN JSONUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef FAUST_JSONUI_H #define FAUST_JSONUI_H #include <vector> #include <map> #include <string> #include <iostream> #include <iomanip> #include <sstream> #include <algorithm> /******************************************************************************* * JSONUI : Faust User Interface * This class produce a complete JSON decription of the DSP instance. ******************************************************************************/ template <typename REAL> class JSONUIReal : public PathBuilder, public Meta, public UIReal<REAL> { protected: std::stringstream fUI; std::stringstream fMeta; std::vector<std::pair <std::string, std::string> > fMetaAux; std::string fVersion; // Compiler version std::string fCompileOptions; // Compilation options std::vector<std::string> fLibraryList; std::vector<std::string> fIncludePathnames; std::string fName; std::string fFileName; std::string fExpandedCode; std::string fSHAKey; int fDSPSize; // In bytes std::map<std::string, int> fPathTable; bool fExtended; char fCloseUIPar; char fCloseMetaPar; int fTab; int fInputs, fOutputs, fSRIndex; void tab(int n, std::ostream& fout) { fout << '\n'; while (n-- > 0) { fout << '\t'; } } std::string flatten(const std::string& src) { std::string dst; for (size_t i = 0; i < src.size(); i++) { switch (src[i]) { case '\n': case '\t': break; default: dst += src[i]; break; } } return dst; } void addMeta(int tab_val, bool quote = true) { if (fMetaAux.size() > 0) { tab(tab_val, fUI); fUI << "\"meta\": ["; std::string sep = ""; for (size_t i = 0; i < fMetaAux.size(); i++) { fUI << sep; tab(tab_val + 1, fUI); fUI << "{ \"" << fMetaAux[i].first << "\": \"" << fMetaAux[i].second << "\" }"; sep = ","; } tab(tab_val, fUI); fUI << ((quote) ? "],": "]"); fMetaAux.clear(); } } int getAddressIndex(const std::string& path) { return (fPathTable.find(path) != fPathTable.end()) ? fPathTable[path] : -1; } public: JSONUIReal(const std::string& name, const std::string& filename, int inputs, int outputs, int sr_index, const std::string& sha_key, const std::string& dsp_code, const std::string& version, const std::string& compile_options, const std::vector<std::string>& library_list, const std::vector<std::string>& include_pathnames, int size, const std::map<std::string, int>& path_table) { init(name, filename, inputs, outputs, sr_index, sha_key, dsp_code, version, compile_options, library_list, include_pathnames, size, path_table); } JSONUIReal(const std::string& name, const std::string& filename, int inputs, int outputs) { init(name, filename, inputs, outputs, -1, "", "", "", "", std::vector<std::string>(), std::vector<std::string>(), -1, std::map<std::string, int>()); } JSONUIReal(int inputs, int outputs) { init("", "", inputs, outputs, -1, "", "","", "", std::vector<std::string>(), std::vector<std::string>(), -1, std::map<std::string, int>()); } JSONUIReal() { init("", "", -1, -1, -1, "", "", "", "", std::vector<std::string>(), std::vector<std::string>(), -1, std::map<std::string, int>()); } virtual ~JSONUIReal() {} void setInputs(int inputs) { fInputs = inputs; } void setOutputs(int outputs) { fOutputs = outputs; } void setSRIndex(int sr_index) { fSRIndex = sr_index; } // Init may be called multiple times so fMeta and fUI are reinitialized void init(const std::string& name, const std::string& filename, int inputs, int outputs, int sr_index, const std::string& sha_key, const std::string& dsp_code, const std::string& version, const std::string& compile_options, const std::vector<std::string>& library_list, const std::vector<std::string>& include_pathnames, int size, const std::map<std::string, int>& path_table, bool extended = false) { fTab = 1; fExtended = extended; if (fExtended) { fUI << std::setprecision(std::numeric_limits<REAL>::max_digits10); fMeta << std::setprecision(std::numeric_limits<REAL>::max_digits10); } // Start Meta generation fMeta.str(""); tab(fTab, fMeta); fMeta << "\"meta\": ["; fCloseMetaPar = ' '; // Start UI generation fUI.str(""); tab(fTab, fUI); fUI << "\"ui\": ["; fCloseUIPar = ' '; fTab += 1; fName = name; fFileName = filename; fInputs = inputs; fOutputs = outputs; fSRIndex = sr_index; fExpandedCode = dsp_code; fSHAKey = sha_key; fDSPSize = size; fPathTable = path_table; fVersion = version; fCompileOptions = compile_options; fLibraryList = library_list; fIncludePathnames = include_pathnames; } // -- widget's layouts virtual void openGenericGroup(const char* label, const char* name) { pushLabel(label); fUI << fCloseUIPar; tab(fTab, fUI); fUI << "{"; fTab += 1; tab(fTab, fUI); fUI << "\"type\": \"" << name << "\","; tab(fTab, fUI); fUI << "\"label\": \"" << label << "\","; addMeta(fTab); tab(fTab, fUI); fUI << "\"items\": ["; fCloseUIPar = ' '; fTab += 1; } virtual void openTabBox(const char* label) { openGenericGroup(label, "tgroup"); } virtual void openHorizontalBox(const char* label) { openGenericGroup(label, "hgroup"); } virtual void openVerticalBox(const char* label) { openGenericGroup(label, "vgroup"); } virtual void closeBox() { popLabel(); fTab -= 1; tab(fTab, fUI); fUI << "]"; fTab -= 1; tab(fTab, fUI); fUI << "}"; fCloseUIPar = ','; } // -- active widgets virtual void addGenericButton(const char* label, const char* name) { std::string path = buildPath(label); fUI << fCloseUIPar; tab(fTab, fUI); fUI << "{"; fTab += 1; tab(fTab, fUI); fUI << "\"type\": \"" << name << "\","; tab(fTab, fUI); fUI << "\"label\": \"" << label << "\","; if (fPathTable.size() > 0) { tab(fTab, fUI); fUI << "\"address\": \"" << path << "\","; tab(fTab, fUI); fUI << "\"index\": " << getAddressIndex(path) << ((fMetaAux.size() > 0) ? "," : ""); } else { tab(fTab, fUI); fUI << "\"address\": \"" << path << "\"" << ((fMetaAux.size() > 0) ? "," : ""); } addMeta(fTab, false); fTab -= 1; tab(fTab, fUI); fUI << "}"; fCloseUIPar = ','; } virtual void addButton(const char* label, REAL* zone) { addGenericButton(label, "button"); } virtual void addCheckButton(const char* label, REAL* zone) { addGenericButton(label, "checkbox"); } virtual void addGenericEntry(const char* label, const char* name, REAL init, REAL min, REAL max, REAL step) { std::string path = buildPath(label); fUI << fCloseUIPar; tab(fTab, fUI); fUI << "{"; fTab += 1; tab(fTab, fUI); fUI << "\"type\": \"" << name << "\","; tab(fTab, fUI); fUI << "\"label\": \"" << label << "\","; tab(fTab, fUI); fUI << "\"address\": \"" << path << "\","; if (fPathTable.size() > 0) { tab(fTab, fUI); fUI << "\"index\": " << getAddressIndex(path) << ","; } addMeta(fTab); tab(fTab, fUI); fUI << "\"init\": " << init << ","; tab(fTab, fUI); fUI << "\"min\": " << min << ","; tab(fTab, fUI); fUI << "\"max\": " << max << ","; tab(fTab, fUI); fUI << "\"step\": " << step; fTab -= 1; tab(fTab, fUI); fUI << "}"; fCloseUIPar = ','; } virtual void addVerticalSlider(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) { addGenericEntry(label, "vslider", init, min, max, step); } virtual void addHorizontalSlider(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) { addGenericEntry(label, "hslider", init, min, max, step); } virtual void addNumEntry(const char* label, REAL* zone, REAL init, REAL min, REAL max, REAL step) { addGenericEntry(label, "nentry", init, min, max, step); } // -- passive widgets virtual void addGenericBargraph(const char* label, const char* name, REAL min, REAL max) { std::string path = buildPath(label); fUI << fCloseUIPar; tab(fTab, fUI); fUI << "{"; fTab += 1; tab(fTab, fUI); fUI << "\"type\": \"" << name << "\","; tab(fTab, fUI); fUI << "\"label\": \"" << label << "\","; tab(fTab, fUI); fUI << "\"address\": \"" << path << "\","; if (fPathTable.size() > 0) { tab(fTab, fUI); fUI << "\"index\": " << getAddressIndex(path) << ","; } addMeta(fTab); tab(fTab, fUI); fUI << "\"min\": " << min << ","; tab(fTab, fUI); fUI << "\"max\": " << max; fTab -= 1; tab(fTab, fUI); fUI << "}"; fCloseUIPar = ','; } virtual void addHorizontalBargraph(const char* label, REAL* zone, REAL min, REAL max) { addGenericBargraph(label, "hbargraph", min, max); } virtual void addVerticalBargraph(const char* label, REAL* zone, REAL min, REAL max) { addGenericBargraph(label, "vbargraph", min, max); } virtual void addSoundfile(const char* label, const char* url, Soundfile** zone) { std::string path = buildPath(label); fUI << fCloseUIPar; tab(fTab, fUI); fUI << "{"; fTab += 1; tab(fTab, fUI); fUI << "\"type\": \"" << "soundfile" << "\","; tab(fTab, fUI); fUI << "\"label\": \"" << label << "\"" << ","; tab(fTab, fUI); fUI << "\"url\": \"" << url << "\"" << ","; tab(fTab, fUI); fUI << "\"address\": \"" << path << "\"" << ((fPathTable.size() > 0) ? "," : ""); if (fPathTable.size() > 0) { tab(fTab, fUI); fUI << "\"index\": " << getAddressIndex(path); } fTab -= 1; tab(fTab, fUI); fUI << "}"; fCloseUIPar = ','; } // -- metadata declarations virtual void declare(REAL* zone, const char* key, const char* val) { fMetaAux.push_back(std::make_pair(key, val)); } // Meta interface virtual void declare(const char* key, const char* value) { fMeta << fCloseMetaPar; // fName found in metadata if ((strcmp(key, "name") == 0) && (fName == "")) fName = value; // fFileName found in metadata if ((strcmp(key, "filename") == 0) && (fFileName == "")) fFileName = value; tab(fTab, fMeta); fMeta << "{ " << "\"" << key << "\"" << ": " << "\"" << value << "\" }"; fCloseMetaPar = ','; } std::string JSON(bool flat = false) { fTab = 0; std::stringstream JSON; if (fExtended) { JSON << std::setprecision(std::numeric_limits<REAL>::max_digits10); } JSON << "{"; fTab += 1; tab(fTab, JSON); JSON << "\"name\": \"" << fName << "\","; tab(fTab, JSON); JSON << "\"filename\": \"" << fFileName << "\","; if (fVersion != "") { tab(fTab, JSON); JSON << "\"version\": \"" << fVersion << "\","; } if (fCompileOptions != "") { tab(fTab, JSON); JSON << "\"compile_options\": \"" << fCompileOptions << "\","; } if (fLibraryList.size() > 0) { tab(fTab, JSON); JSON << "\"library_list\": ["; for (size_t i = 0; i < fLibraryList.size(); i++) { JSON << "\"" << fLibraryList[i] << "\""; if (i < (fLibraryList.size() - 1)) JSON << ","; } JSON << "],"; } if (fIncludePathnames.size() > 0) { tab(fTab, JSON); JSON << "\"include_pathnames\": ["; for (size_t i = 0; i < fIncludePathnames.size(); i++) { JSON << "\"" << fIncludePathnames[i] << "\""; if (i < (fIncludePathnames.size() - 1)) JSON << ","; } JSON << "],"; } if (fDSPSize != -1) { tab(fTab, JSON); JSON << "\"size\": " << fDSPSize << ","; } if (fSHAKey != "") { tab(fTab, JSON); JSON << "\"sha_key\": \"" << fSHAKey << "\","; } if (fExpandedCode != "") { tab(fTab, JSON); JSON << "\"code\": \"" << fExpandedCode << "\","; } tab(fTab, JSON); JSON << "\"inputs\": " << fInputs << ","; tab(fTab, JSON); JSON << "\"outputs\": " << fOutputs << ","; if (fSRIndex != -1) { tab(fTab, JSON); JSON << "\"sr_index\": " << fSRIndex << ","; } tab(fTab, fMeta); fMeta << "],"; tab(fTab, fUI); fUI << "]"; fTab -= 1; if (fCloseMetaPar == ',') { // If "declare" has been called, fCloseMetaPar state is now ',' JSON << fMeta.str() << fUI.str(); } else { JSON << fUI.str(); } tab(fTab, JSON); JSON << "}"; return (flat) ? flatten(JSON.str()) : JSON.str(); } }; // Externally available class using FAUSTFLOAT struct JSONUI : public JSONUIReal<FAUSTFLOAT>, public UI { JSONUI(const std::string& name, const std::string& filename, int inputs, int outputs, int sr_index, const std::string& sha_key, const std::string& dsp_code, const std::string& version, const std::string& compile_options, const std::vector<std::string>& library_list, const std::vector<std::string>& include_pathnames, int size, const std::map<std::string, int>& path_table): JSONUIReal<FAUSTFLOAT>(name, filename, inputs, outputs, sr_index, sha_key, dsp_code, version, compile_options, library_list, include_pathnames, size, path_table) {} JSONUI(const std::string& name, const std::string& filename, int inputs, int outputs): JSONUIReal<FAUSTFLOAT>(name, filename, inputs, outputs) {} JSONUI(int inputs, int outputs):JSONUIReal<FAUSTFLOAT>(inputs, outputs) {} JSONUI():JSONUIReal<FAUSTFLOAT>() {} virtual void openTabBox(const char* label) { JSONUIReal<FAUSTFLOAT>::openTabBox(label); } virtual void openHorizontalBox(const char* label) { JSONUIReal<FAUSTFLOAT>::openHorizontalBox(label); } virtual void openVerticalBox(const char* label) { JSONUIReal<FAUSTFLOAT>::openVerticalBox(label); } virtual void closeBox() { JSONUIReal<FAUSTFLOAT>::closeBox(); } // -- active widgets virtual void addButton(const char* label, FAUSTFLOAT* zone) { JSONUIReal<FAUSTFLOAT>::addButton(label, zone); } virtual void addCheckButton(const char* label, FAUSTFLOAT* zone) { JSONUIReal<FAUSTFLOAT>::addCheckButton(label, zone); } virtual void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { JSONUIReal<FAUSTFLOAT>::addVerticalSlider(label, zone, init, min, max, step); } virtual void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { JSONUIReal<FAUSTFLOAT>::addHorizontalSlider(label, zone, init, min, max, step); } virtual void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { JSONUIReal<FAUSTFLOAT>::addNumEntry(label, zone, init, min, max, step); } // -- passive widgets virtual void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { JSONUIReal<FAUSTFLOAT>::addHorizontalBargraph(label, zone, min, max); } virtual void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { JSONUIReal<FAUSTFLOAT>::addVerticalBargraph(label, zone, min, max); } // -- soundfiles virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) { JSONUIReal<FAUSTFLOAT>::addSoundfile(label, filename, sf_zone); } // -- metadata declarations virtual void declare(FAUSTFLOAT* zone, const char* key, const char* val) { JSONUIReal<FAUSTFLOAT>::declare(zone, key, val); } virtual void declare(const char* key, const char* val) { JSONUIReal<FAUSTFLOAT>::declare(key, val); } virtual ~JSONUI() {} }; #endif // FAUST_JSONUI_H /************************** END JSONUI.h **************************/ namespace oscfaust { class OSCIO; class RootNode; typedef class SMARTP<RootNode> SRootNode; /** * an alias target includes a map to rescale input values to output values * and a target osc address. The input values can be given in reversed order * to reverse the control */ struct aliastarget { double fMinIn; double fMaxIn; double fMinOut; double fMaxOut; std::string fTarget; // the real osc address aliastarget(const char* address, double imin, double imax, double omin, double omax) : fMinIn(imin), fMaxIn(imax), fMinOut(omin), fMaxOut(omax), fTarget(address) {} aliastarget(const aliastarget& t) : fMinIn(t.fMinIn), fMaxIn(t.fMaxIn), fMinOut(t.fMinOut), fMaxOut(t.fMaxOut), fTarget(t.fTarget) {} double scale(double x) const { if (fMinIn < fMaxIn) { // increasing control double z = (x < fMinIn) ? fMinIn : (x > fMaxIn) ? fMaxIn : x; return fMinOut + (z-fMinIn)*(fMaxOut-fMinOut)/(fMaxIn-fMinIn); } else if (fMinIn > fMaxIn) { // reversed control double z = (x < fMaxIn) ? fMaxIn : (x > fMinIn) ? fMinIn : x; return fMinOut + (fMinIn-z)*(fMaxOut-fMinOut)/(fMinIn-fMaxIn); } else { // no control ! return (fMinOut+fMaxOut)/2.0f; } } double invscale(double x) const { if (fMinOut < fMaxOut) { // increasing control double z = (x < fMinOut) ? fMinOut : (x > fMaxOut) ? fMaxOut : x; return fMinIn + (z-fMinOut)*(fMaxIn-fMinIn)/(fMaxOut-fMinOut); } else if (fMinOut > fMaxOut) { // reversed control double z = (x < fMaxOut) ? fMaxOut : (x > fMinOut) ? fMinOut : x; return fMinIn + (fMinOut-z)*(fMaxIn-fMinIn)/(fMinOut-fMaxOut); } else { // no control ! return (fMinIn+fMaxIn)/2.0f; } } }; //-------------------------------------------------------------------------- /*! \brief a faust root node A Faust root node handles the \c 'hello' message and provides support for incoming osc signal data. */ class RootNode : public MessageDriven { private: int *fUPDIn, *fUDPOut, *fUDPErr; // the osc port numbers (required by the hello method) OSCIO* fIO; // an OSC IO controler JSONUI* fJSON; typedef std::map<std::string, std::vector<aliastarget> > TAliasMap; TAliasMap fAliases; template <typename T> void processAliasAux(const std::string& address, T val); void processAlias(const std::string& address, float val); void processAlias(const std::string& address, double val); void eraseAliases(const std::string& target); void eraseAlias(const std::string& target, const std::string& alias); bool aliasError(const Message* msg); protected: RootNode(const char *name, JSONUI* json, OSCIO* io = NULL) : MessageDriven(name, ""), fUPDIn(0), fUDPOut(0), fUDPErr(0), fIO(io), fJSON(json) {} virtual ~RootNode() {} public: static SRootNode create(const char* name, JSONUI* json, OSCIO* io = NULL) { return new RootNode(name, json, io); } virtual void processMessage(const Message* msg); virtual bool accept(const Message* msg); virtual void get(unsigned long ipdest) const; virtual void get(unsigned long ipdest, const std::string& what) const; template <typename T> bool aliasMsgAux(const Message* msg, T omin, T omax); bool aliasMsg(const Message* msg, double omin, double omax); bool aliasMsg(const Message* msg, float omin, float omax); template <typename T> void addAliasAux(const char* alias, const char* address, T imin, T imax, T omin, T omax); void addAlias(const char* alias, const char* address, float imin, float imax, float omin, float omax); void addAlias(const char* alias, const char* address, double imin, double imax, double omin, double omax); bool acceptSignal(const Message* msg); ///< handler for signal data void hello(unsigned long ipdest) const; ///< handler for the 'hello' message void setPorts(int* in, int* out, int* err); std::vector<std::pair<std::string, double> > getAliases(const std::string& address, double value); }; } // end namespoace #endif namespace oscfaust { /** * map (rescale) input values to output values */ template <typename C> struct mapping { const C fMinOut; const C fMaxOut; mapping(C omin, C omax) : fMinOut(omin), fMaxOut(omax) {} C clip (C x) { return (x < fMinOut) ? fMinOut : (x > fMaxOut) ? fMaxOut : x; } }; //-------------------------------------------------------------------------- /*! \brief a faust node is a terminal node and represents a faust parameter controler */ template <typename C> class FaustNode : public MessageDriven, public uiTypedItem<C> { mapping<C> fMapping; RootNode* fRoot; bool fInput; // true for input nodes (slider, button...) //--------------------------------------------------------------------- // Warning !!! // The cast (C*)fZone is necessary because the real size allocated is // only known at execution time. When the library is compiled, fZone is // uniquely defined by FAUSTFLOAT. //--------------------------------------------------------------------- bool store(C val) { *(C*)this->fZone = fMapping.clip(val); return true; } void sendOSC() const; protected: FaustNode(RootNode* root, const char *name, C* zone, C init, C min, C max, const char* prefix, GUI* ui, bool initZone, bool input) : MessageDriven(name, prefix), uiTypedItem<C>(ui, zone), fMapping(min, max), fRoot(root), fInput(input) { if (initZone) { *zone = init; } } virtual ~FaustNode() {} public: typedef SMARTP<FaustNode<C> > SFaustNode; static SFaustNode create(RootNode* root, const char* name, C* zone, C init, C min, C max, const char* prefix, GUI* ui, bool initZone, bool input) { SFaustNode node = new FaustNode(root, name, zone, init, min, max, prefix, ui, initZone, input); /* Since FaustNode is a subclass of uiItem, the pointer will also be kept in the GUI class, and it's desallocation will be done there. So we don't want to have smartpointer logic desallocate it and we increment the refcount. */ node->addReference(); return node; } bool accept(const Message* msg); void get(unsigned long ipdest) const; ///< handler for the 'get' message virtual void reflectZone() { sendOSC(); this->fCache = *this->fZone; } }; } // end namespace #endif class GUI; namespace oscfaust { class OSCIO; class RootNode; typedef class SMARTP<RootNode> SRootNode; class MessageDriven; typedef class SMARTP<MessageDriven> SMessageDriven; //-------------------------------------------------------------------------- /*! \brief a factory to build a OSC UI hierarchy Actually, makes use of a stack to build the UI hierarchy. It includes a pointer to a OSCIO controler, but just to give it to the root node. */ class FaustFactory { std::stack<SMessageDriven> fNodes; ///< maintains the current hierarchy level SRootNode fRoot; ///< keep track of the root node OSCIO* fIO; ///< hack to support audio IO via OSC, actually the field is given to the root node GUI* fGUI; ///< a GUI pointer to support updateAllGuis(), required for bi-directionnal OSC JSONUI* fJSON; private: std::string addressFirst(const std::string& address) const; std::string addressTail(const std::string& address) const; public: FaustFactory(GUI* ui, JSONUI* json, OSCIO * io = NULL); virtual ~FaustFactory(); template <typename C> void addnode(const char* label, C* zone, C init, C min, C max, bool initZone, bool input); template <typename C> void addAlias(const std::string& fullpath, C* zone, C imin, C imax, C init, C min, C max, const char* label); void addAlias(const char* alias, const char* address, float imin, float imax, float omin, float omax); void addAlias(const char* alias, const char* address, double imin, double imax, double omin, double omax); void opengroup(const char* label); void closegroup(); SRootNode root() const; }; /** * Add a node to the OSC UI tree in the current group at the top of the stack */ template <typename C> void FaustFactory::addnode(const char* label, C* zone, C init, C min, C max, bool initZone, bool input) { SMessageDriven top; if (fNodes.size()) top = fNodes.top(); if (top) { std::string prefix = top->getOSCAddress(); top->add(FaustNode<C>::create(root(), label, zone, init, min, max, prefix.c_str(), fGUI, initZone, input)); } } /** * Add an alias (actually stored and handled at root node level */ template <typename C> void FaustFactory::addAlias(const std::string& fullpath, C* zone, C imin, C imax, C init, C min, C max, const char* label) { std::istringstream ss(fullpath); std::string realpath; ss >> realpath >> imin >> imax; SMessageDriven top = fNodes.top(); if (top) { std::string target = top->getOSCAddress() + "/" + label; addAlias(realpath.c_str(), target.c_str(), C(imin), C(imax), C(min), C(max)); } } } // end namespoace #endif class GUI; typedef void (*ErrorCallback)(void*); namespace oscfaust { class OSCIO; class OSCSetup; class OSCRegexp; //-------------------------------------------------------------------------- /*! \brief the main Faust OSC Lib API The OSCControler is essentially a glue between the memory representation (in charge of the FaustFactory), and the network services (in charge of OSCSetup). */ class OSCControler { int fUDPPort, fUDPOut, fUPDErr; // the udp ports numbers std::string fDestAddress; // the osc messages destination address, used at initialization only // to collect the address from the command line std::string fBindAddress; // when non empty, the address used to bind the socket for listening OSCSetup* fOsc; // the network manager (handles the udp sockets) OSCIO* fIO; // hack for OSC IO support (actually only relayed to the factory) FaustFactory* fFactory; // a factory to build the memory representation bool fInit; public: /* base udp port is chosen in an unassigned range from IANA PORT NUMBERS (last updated 2011-01-24) see at http://www.iana.org/assignments/port-numbers 5507-5552 Unassigned */ enum { kUDPBasePort = 5510 }; OSCControler(int argc, char* argv[], GUI* ui, JSONUI* json, OSCIO* io = NULL, ErrorCallback errCallback = NULL, void* arg = NULL, bool init = true); virtual ~OSCControler(); //-------------------------------------------------------------------------- // addnode, opengroup and closegroup are simply relayed to the factory //-------------------------------------------------------------------------- // Add a node in the current group (top of the group stack) template <typename T> void addnode(const char* label, T* zone, T init, T min, T max, bool input = true) { fFactory->addnode(label, zone, init, min, max, fInit, input); } //-------------------------------------------------------------------------- // This method is used for alias messages. The arguments imin and imax allow // to map incomming values from the alias input range to the actual range template <typename T> void addAlias(const std::string& fullpath, T* zone, T imin, T imax, T init, T min, T max, const char* label) { fFactory->addAlias(fullpath, zone, imin, imax, init, min, max, label); } void opengroup(const char* label) { fFactory->opengroup(label); } void closegroup() { fFactory->closegroup(); } //-------------------------------------------------------------------------- void run(); // starts the network services void endBundle(); // when bundle mode is on, close and send the current bundle (if any) void stop(); // stop the network services std::string getInfos() const; // gives information about the current environment (version, port numbers,...) int getUDPPort() const { return fUDPPort; } int getUDPOut() const { return fUDPOut; } int getUDPErr() const { return fUPDErr; } const char* getDestAddress() const { return fDestAddress.c_str(); } const char* getRootName() const; // probably useless, introduced for UI extension experiments void setUDPPort(int port) { fUDPPort = port; } void setUDPOut(int port) { fUDPOut = port; } void setUDPErr(int port) { fUPDErr = port; } void setDestAddress(const char* address) { fDestAddress = address; } // By default, an osc interface emits all parameters. You can filter specific params dynamically. static std::vector<OSCRegexp*> fFilteredPaths; // filtered paths will not be emitted static void addFilteredPath(std::string path); static bool isPathFiltered(std::string path); static void resetFilteredPaths(); static float version(); // the Faust OSC library version number static const char* versionstr(); // the Faust OSC library version number as a string static int gXmit; // a static variable to control the transmission of values // i.e. the use of the interface as a controler static int gBundle; // a static variable to control the osc bundle mode }; #define kNoXmit 0 #define kAll 1 #define kAlias 2 } #endif #ifdef _WIN32 #define strcasecmp _stricmp #endif /****************************************************************************** ******************************************************************************* OSC (Open Sound Control) USER INTERFACE ******************************************************************************* *******************************************************************************/ /* Note about the OSC addresses and the Faust UI names: ---------------------------------------------------- There are potential conflicts between the Faust UI objects naming scheme and the OSC address space. An OSC symbolic names is an ASCII string consisting of printable characters other than the following: space # number sign * asterisk , comma / forward ? question mark [ open bracket ] close bracket { open curly brace } close curly brace a simple solution to address the problem consists in replacing space or tabulation with '_' (underscore) all the other osc excluded characters with '-' (hyphen) This solution is implemented in the proposed OSC UI; */ class OSCUI : public GUI { private: oscfaust::OSCControler* fCtrl; std::vector<const char*> fAlias; JSONUI fJSON; const char* tr(const char* label) const { static char buffer[1024]; char * ptr = buffer; int n=1; while (*label && (n++ < 1024)) { switch (*label) { case ' ': case ' ': *ptr++ = '_'; break; case '#': case '*': case ',': case '/': case '?': case '[': case ']': case '{': case '}': case '(': case ')': *ptr++ = '_'; break; default: *ptr++ = *label; } label++; } *ptr = 0; return buffer; } // add all accumulated alias void addalias(FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, const char* label) { for (unsigned int i = 0; i < fAlias.size(); i++) { fCtrl->addAlias(fAlias[i], zone, FAUSTFLOAT(0), FAUSTFLOAT(1), init, min, max, label); } fAlias.clear(); } public: OSCUI(const char* /*applicationname*/, int argc, char* argv[], oscfaust::OSCIO* io = NULL, ErrorCallback errCallback = NULL, void* arg = NULL, bool init = true) : GUI() { fCtrl = new oscfaust::OSCControler(argc, argv, this, &fJSON, io, errCallback, arg, init); // fCtrl->opengroup(applicationname); } virtual ~OSCUI() { delete fCtrl; } // -- widget's layouts virtual void openTabBox(const char* label) { fCtrl->opengroup(tr(label)); fJSON.openTabBox(label); } virtual void openHorizontalBox(const char* label) { fCtrl->opengroup(tr(label)); fJSON.openHorizontalBox(label); } virtual void openVerticalBox(const char* label) { fCtrl->opengroup(tr(label)); fJSON.openVerticalBox(label); } virtual void closeBox() { fCtrl->closegroup(); fJSON.closeBox(); } // -- active widgets virtual void addButton(const char* label, FAUSTFLOAT* zone) { const char* l = tr(label); addalias(zone, 0, 0, 1, l); fCtrl->addnode(l, zone, FAUSTFLOAT(0), FAUSTFLOAT(0), FAUSTFLOAT(1)); fJSON.addButton(label, zone); } virtual void addCheckButton(const char* label, FAUSTFLOAT* zone) { const char* l = tr(label); addalias(zone, 0, 0, 1, l); fCtrl->addnode(l, zone, FAUSTFLOAT(0), FAUSTFLOAT(0), FAUSTFLOAT(1)); fJSON.addCheckButton(label, zone); } virtual void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { const char* l = tr(label); addalias(zone, init, min, max, l); fCtrl->addnode(l, zone, init, min, max); fJSON.addVerticalSlider(label, zone, init, min, max, step); } virtual void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { const char* l = tr(label); addalias(zone, init, min, max, l); fCtrl->addnode(l, zone, init, min, max); fJSON.addHorizontalSlider(label, zone, init, min, max, step); } virtual void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { const char* l = tr(label); addalias(zone, init, min, max, l); fCtrl->addnode(l, zone, init, min, max); fJSON.addNumEntry(label, zone, init, min, max, step); } // -- passive widgets virtual void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { const char* l = tr(label); addalias(zone, 0, min, max, l); fCtrl->addnode(l, zone, FAUSTFLOAT(0), min, max, false); fJSON.addHorizontalBargraph(label, zone, min, max); } virtual void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { const char* l = tr(label); addalias(zone, 0, min, max, l); fCtrl->addnode(l, zone, FAUSTFLOAT(0), min, max, false); fJSON.addVerticalBargraph(label, zone, min, max); } // -- metadata declarations virtual void declare(FAUSTFLOAT* zone, const char* key, const char* alias) { if (strcasecmp(key, "OSC") == 0) fAlias.push_back(alias); fJSON.declare(zone, key, alias); } virtual void show() {} bool run() { fCtrl->run(); return true; } void stop() { fCtrl->stop(); } void endBundle() { fCtrl->endBundle(); } std::string getInfos() { return fCtrl->getInfos(); } const char* getRootName() { return fCtrl->getRootName(); } int getUDPPort() { return fCtrl->getUDPPort(); } int getUDPOut() { return fCtrl->getUDPOut(); } int getUDPErr() { return fCtrl->getUDPErr(); } const char* getDestAddress() { return fCtrl->getDestAddress(); } void setUDPPort(int port) { fCtrl->setUDPPort(port); } void setUDPOut(int port) { fCtrl->setUDPOut(port); } void setUDPErr(int port) { fCtrl->setUDPErr(port); } void setDestAddress(const char* address) { return fCtrl->setDestAddress(address); } }; #endif // __OSCUI__ /************************** END OSCUI.h **************************/ #ifdef POLY2 #include "effect.h" #endif #if SOUNDFILE /************************** BEGIN SoundUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2018 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __SoundUI_H__ #define __SoundUI_H__ #include <map> #include <vector> #include <string> #include <iostream> #ifdef __APPLE__ #include <CoreFoundation/CFBundle.h> #endif // Always included otherwise -i mode later on will not always include it (with the conditional includes) /************************** BEGIN Soundfile.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __Soundfile__ #define __Soundfile__ #include <iostream> #include <string.h> #ifndef FAUSTFLOAT #define FAUSTFLOAT float #endif #define BUFFER_SIZE 16384 #define SAMPLE_RATE 44100 #define MAX_CHAN 64 #define MAX_SOUNDFILE_PARTS 256 #ifdef _MSC_VER #define PRE_PACKED_STRUCTURE __pragma(pack(push, 1)) #define POST_PACKED_STRUCTURE \ ; \ __pragma(pack(pop)) #else #define PRE_PACKED_STRUCTURE #define POST_PACKED_STRUCTURE __attribute__((__packed__)) #endif /* The soundfile structure to be used by the DSP code. Soundfile has a MAX_SOUNDFILE_PARTS parts (even a single soundfile or an empty soundfile). fLength, fOffset and fSR fields are filled accordingly by repeating the actual parts if needed. It has to be 'packed' to that the LLVM backend can correctly access it. Index computation: - p is the current part number [0..MAX_SOUNDFILE_PARTS-1] (must be proved by the type system) - i is the current position in the part. It will be constrained between [0..length] - idx(p,i) = fOffset[p] + max(0, min(i, fLength[p])); */ PRE_PACKED_STRUCTURE struct Soundfile { FAUSTFLOAT** fBuffers; int* fLength; // length of each part int* fSR; // sample rate of each part int* fOffset; // offset of each part in the global buffer int fChannels; // max number of channels of all concatenated files Soundfile() { fBuffers = nullptr; fChannels = -1; fLength = new int[MAX_SOUNDFILE_PARTS]; fSR = new int[MAX_SOUNDFILE_PARTS]; fOffset = new int[MAX_SOUNDFILE_PARTS]; } ~Soundfile() { // Free the real channels only for (int chan = 0; chan < fChannels; chan++) { delete fBuffers[chan]; } delete[] fBuffers; delete[] fLength; delete[] fSR; delete[] fOffset; } } POST_PACKED_STRUCTURE; /* The generic soundfile reader. */ class SoundfileReader { protected: int fDriverSR; void emptyFile(Soundfile* soundfile, int part, int& offset) { soundfile->fLength[part] = BUFFER_SIZE; soundfile->fSR[part] = SAMPLE_RATE; soundfile->fOffset[part] = offset; // Update offset offset += soundfile->fLength[part]; } Soundfile* createSoundfile(int cur_chan, int length, int max_chan) { Soundfile* soundfile = new Soundfile(); soundfile->fBuffers = new FAUSTFLOAT*[max_chan]; for (int chan = 0; chan < cur_chan; chan++) { soundfile->fBuffers[chan] = new FAUSTFLOAT[length]; memset(soundfile->fBuffers[chan], 0, sizeof(FAUSTFLOAT) * length); } soundfile->fChannels = cur_chan; return soundfile; } void getBuffersOffset(Soundfile* soundfile, FAUSTFLOAT** buffers, int offset) { for (int chan = 0; chan < soundfile->fChannels; chan++) { buffers[chan] = &soundfile->fBuffers[chan][offset]; } } // Check if a soundfile exists and return its real path_name std::string checkFile(const std::vector<std::string>& sound_directories, const std::string& file_name) { if (checkFile(file_name)) { return file_name; } else { for (size_t i = 0; i < sound_directories.size(); i++) { std::string path_name = sound_directories[i] + "/" + file_name; if (checkFile(path_name)) { return path_name; } } return ""; } } bool isResampling(int sample_rate) { return (fDriverSR > 0 && fDriverSR != sample_rate); } // To be implemented by subclasses /** * Check the availability of a sound resource. * * @param path_name - the name of the file, or sound resource identified this way * * @return true if the sound resource is available, false otherwise. */ virtual bool checkFile(const std::string& path_name) = 0; /** * Check the availability of a sound resource. * * @param buffer - the sound buffer * @param buffer - the sound buffer length * * @return true if the sound resource is available, false otherwise. */ virtual bool checkFile(unsigned char* buffer, size_t length) { return true; } /** * Get the channels and length values of the given sound resource. * * @param path_name - the name of the file, or sound resource identified this way * @param channels - the channels value to be filled with the sound resource number of channels * @param length - the length value to be filled with the sound resource length in frames * */ virtual void getParamsFile(const std::string& path_name, int& channels, int& length) = 0; /** * Get the channels and length values of the given sound resource. * * @param buffer - the sound buffer * @param buffer - the sound buffer length * @param channels - the channels value to be filled with the sound resource number of channels * @param length - the length value to be filled with the sound resource length in frames * */ virtual void getParamsFile(unsigned char* buffer, size_t size, int& channels, int& length) {} /** * Read one sound resource and fill the 'soundfile' structure accordingly * * @param path_name - the name of the file, or sound resource identified this way * @param part - the part number to be filled in the soundfile * @param offset - the offset value to be incremented with the actual sound resource length in frames * @param max_chan - the maximum number of mono channels to fill * */ virtual void readFile(Soundfile* soundfile, const std::string& path_name, int part, int& offset, int max_chan) = 0; /** * Read one sound resource and fill the 'soundfile' structure accordingly * * @param buffer - the sound buffer * @param buffer - the sound buffer length * @param part - the part number to be filled in the soundfile * @param offset - the offset value to be incremented with the actual sound resource length in frames * @param max_chan - the maximum number of mono channels to fill * */ virtual void readFile(Soundfile* soundfile, unsigned char* buffer, size_t length, int part, int& offset, int max_chan) {} public: virtual ~SoundfileReader() {} void setSampleRate(int sample_rate) { fDriverSR = sample_rate; } Soundfile* createSoundfile(const std::vector<std::string>& path_name_list, int max_chan) { try { int cur_chan = 1; // At least one buffer int total_length = 0; // Compute total length and channels max of all files for (int i = 0; i < int(path_name_list.size()); i++) { int chan, length; if (path_name_list[i] == "__empty_sound__") { length = BUFFER_SIZE; chan = 1; } else { getParamsFile(path_name_list[i], chan, length); } cur_chan = std::max<int>(cur_chan, chan); total_length += length; } // Complete with empty parts total_length += (MAX_SOUNDFILE_PARTS - path_name_list.size()) * BUFFER_SIZE; // Create the soundfile Soundfile* soundfile = createSoundfile(cur_chan, total_length, max_chan); // Init offset int offset = 0; // Read all files for (int i = 0; i < int(path_name_list.size()); i++) { if (path_name_list[i] == "__empty_sound__") { emptyFile(soundfile, i, offset); } else { readFile(soundfile, path_name_list[i], i, offset, max_chan); } } // Complete with empty parts for (int i = int(path_name_list.size()); i < MAX_SOUNDFILE_PARTS; i++) { emptyFile(soundfile, i, offset); } // Share the same buffers for all other channels so that we have max_chan channels available for (int chan = cur_chan; chan < max_chan; chan++) { soundfile->fBuffers[chan] = soundfile->fBuffers[chan % cur_chan]; } return soundfile; } catch (...) { return nullptr; } } // Check if all soundfiles exist and return their real path_name std::vector<std::string> checkFiles(const std::vector<std::string>& sound_directories, const std::vector<std::string>& file_name_list) { std::vector<std::string> path_name_list; for (size_t i = 0; i < file_name_list.size(); i++) { std::string path_name = checkFile(sound_directories, file_name_list[i]); // If 'path_name' is not found, it is replaced by an empty sound (= silence) path_name_list.push_back((path_name == "") ? "__empty_sound__" : path_name); } return path_name_list; } }; #endif /************************** END Soundfile.h **************************/ #if defined(JUCE_32BIT) || defined(JUCE_64BIT) /************************** BEGIN JuceReader.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2018 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __JuceReader__ #define __JuceReader__ #include <assert.h> #include "../JuceLibraryCode/JuceHeader.h" struct JuceReader : public SoundfileReader { AudioFormatManager fFormatManager; JuceReader() { fFormatManager.registerBasicFormats(); } virtual ~JuceReader() {} bool checkFile(const std::string& path_name) { File file(path_name); if (file.existsAsFile()) { return true; } else { std::cerr << "ERROR : cannot open '" << path_name << "'" << std::endl; return false; } } void getParamsFile(const std::string& path_name, int& channels, int& length) { std::unique_ptr<AudioFormatReader> formatReader (fFormatManager.createReaderFor (File (path_name))); channels = int(formatReader->numChannels); length = int(formatReader->lengthInSamples); } void readFile(Soundfile* soundfile, const std::string& path_name, int part, int& offset, int max_chan) { std::unique_ptr<AudioFormatReader> formatReader (fFormatManager.createReaderFor (File (path_name))); soundfile->fLength[part] = int(formatReader->lengthInSamples); soundfile->fSR[part] = int(formatReader->sampleRate); soundfile->fOffset[part] = offset; FAUSTFLOAT** buffers = static_cast<FAUSTFLOAT**>(alloca(soundfile->fChannels * sizeof(FAUSTFLOAT*))); getBuffersOffset(soundfile, buffers, offset); if (formatReader->read(reinterpret_cast<int *const *>(buffers), int(formatReader->numChannels), 0, int(formatReader->lengthInSamples), false)) { // Possibly concert samples if (!formatReader->usesFloatingPointData) { for (int chan = 0; chan < int(formatReader->numChannels); ++chan) { FAUSTFLOAT* buffer = &soundfile->fBuffers[chan][soundfile->fOffset[part]]; FloatVectorOperations::convertFixedToFloat(buffer, reinterpret_cast<const int*>(buffer), 1.0f/0x7fffffff, int(formatReader->lengthInSamples)); } } } else { std::cerr << "Error reading the file : " << path_name << std::endl; } // Update offset offset += soundfile->fLength[part]; } }; #endif /************************** END JuceReader.h **************************/ JuceReader gReader; #elif defined(ESP32) /************************** BEGIN WaveReader.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2020 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __WaveReader__ #define __WaveReader__ #include <string.h> #include <assert.h> #include <iostream> // WAVE file description typedef struct { // The canonical WAVE format starts with the RIFF header /** Variable: chunk_id Contains the letters "RIFF" in ASCII form (0x52494646 big-endian form). **/ int chunk_id; /** Variable: chunk_size 36 + SubChunk2Size, or more precisely: 4 + (8 + SubChunk1Size) + (8 + SubChunk2Size) This is the size of the rest of the chunk following this number. This is the size of the entire file in bytes minus 8 bytes for the two fields not included in this count: ChunkID and ChunkSize. **/ int chunk_size; /** Variable: format Contains the letters "WAVE" (0x57415645 big-endian form). **/ int format; // The "WAVE" format consists of two subchunks: "fmt " and "data": // The "fmt " subchunk describes the sound data's format: /** Variable: subchunk_1_id Contains the letters "fmt " (0x666d7420 big-endian form). **/ int subchunk_1_id; /** Variable: subchunk_1_size 16 for PCM. This is the size of the rest of the Subchunk which follows this number. **/ int subchunk_1_size; /** Variable: audio_format PCM = 1 (i.e. Linear quantization) Values other than 1 indicate some form of compression. **/ short audio_format; /** Variable: num_channels Mono = 1, Stereo = 2, etc. **/ short num_channels; /** Variable: sample_rate 8000, 44100, etc. **/ int sample_rate; /** Variable: byte_rate == SampleRate * NumChannels * BitsPerSample/8 **/ int byte_rate; /** Variable: block_align == NumChannels * BitsPerSample/8 The number of bytes for one sample including all channels. I wonder what happens when this number isn't an integer? **/ short block_align; /** Variable: bits_per_sample 8 bits = 8, 16 bits = 16, etc. **/ short bits_per_sample; /** Here should come some extra parameters which i will avoid. **/ // The "data" subchunk contains the size of the data and the actual sound: /** Variable: subchunk_2_id Contains the letters "data" (0x64617461 big-endian form). **/ int subchunk_2_id; /** Variable: subchunk_2_size == NumSamples * NumChannels * BitsPerSample/8 This is the number of bytes in the data. You can also think of this as the size of the read of the subchunk following this number. **/ int subchunk_2_size; /** Variable: data The actual sound data. **/ char* data; } wave_t; // Base reader struct Reader { wave_t* fWave; inline int is_big_endian() { int a = 1; return !((char*)&a)[0]; } inline int convert_to_int(char* buffer, int len) { int a = 0; if (!is_big_endian()) { for(int i = 0; i < len; i++) { ((char*)&a)[i] = buffer[i]; } } else { for(int i = 0; i < len; i++) { ((char*)&a)[3-i] = buffer[i]; } } return a; } Reader() { fWave = (wave_t*)calloc(1, sizeof(wave_t)); } virtual ~Reader() { free(fWave->data); free(fWave); } bool load_wave_header() { char buffer[4]; read(buffer, 4); if (strncmp(buffer, "RIFF", 4) != 0) { std::cerr << "This is not valid WAV file!\n"; return false; } fWave->chunk_id = convert_to_int(buffer, 4); read(buffer, 4); fWave->chunk_size = convert_to_int(buffer, 4); read(buffer, 4); fWave->format = convert_to_int(buffer, 4); read(buffer, 4); fWave->subchunk_1_id = convert_to_int(buffer, 4); read(buffer, 4); fWave->subchunk_1_size = convert_to_int(buffer, 4); read(buffer, 2); fWave->audio_format = convert_to_int(buffer, 2); read(buffer, 2); fWave->num_channels = convert_to_int(buffer, 2); read(buffer, 4); fWave->sample_rate = convert_to_int(buffer, 4); read(buffer, 4); fWave->byte_rate = convert_to_int(buffer, 4); read(buffer, 2); fWave->block_align = convert_to_int(buffer, 2); read(buffer, 2); fWave->bits_per_sample = convert_to_int(buffer, 2); read(buffer, 4); if (strncmp(buffer, "data", 4) != 0) { read(buffer, 4); int _extra_size = convert_to_int(buffer, 4); char _extra_data[_extra_size]; read(_extra_data, _extra_size); read(buffer, 4); fWave->subchunk_2_id = convert_to_int(buffer, 4); } else { fWave->subchunk_2_id = convert_to_int(buffer, 4); } read(buffer, 4); fWave->subchunk_2_size = convert_to_int(buffer, 4); return true; } void load_wave() { // Read sound data fWave->data = (char*)malloc(fWave->subchunk_2_size); read(fWave->data, fWave->subchunk_2_size); } virtual void read(char* buffer, unsigned int size) = 0; }; struct FileReader : public Reader { FILE* fFile; FileReader(const std::string& file_path) { fFile = fopen(file_path.c_str(), "rb"); if (!fFile) { std::cerr << "FileReader : cannot open file!\n"; throw -1; } if (!load_wave_header()) { std::cerr << "FileReader : not a WAV file!\n"; throw -1; } } virtual ~FileReader() { fclose(fFile); } void read(char* buffer, unsigned int size) { fread(buffer, 1, size, fFile); } }; extern const uint8_t file_start[] asm("_binary_FILE_start"); extern const uint8_t file_end[] asm("_binary_FILE_end"); struct MemoryReader : public Reader { int fPos; const uint8_t* fStart; const uint8_t* fEnd; MemoryReader(const uint8_t* start, const uint8_t* end):fPos(0) { fStart = start; fEnd = end; if (!load_wave_header()) { std::cerr << "MemoryReader : not a WAV file!\n"; throw -1; } } virtual ~MemoryReader() {} void read(char* buffer, unsigned int size) { memcpy(buffer, fStart + fPos, size); fPos += size; } }; // Using a FileReader to implement SoundfileReader struct WaveReader : public SoundfileReader { WaveReader() {} bool checkFile(const std::string& path_name) { try { Reader* reader = new FileReader(path_name); delete reader; return true; } catch(...) { return false; } } void getParamsFile(const std::string& path_name, int& channels, int& length) { Reader* reader = new FileReader(path_name); assert(reader); channels = reader->fWave->num_channels; length = (reader->fWave->subchunk_2_size * 8) / (reader->fWave->num_channels * reader->fWave->bits_per_sample); delete reader; } void readFile(Soundfile* soundfile, const std::string& path_name, int part, int& offset, int max_chan) { Reader* reader = new FileReader(path_name); assert(reader); reader->load_wave(); soundfile->fLength[part] = (reader->fWave->subchunk_2_size * 8) / (reader->fWave->num_channels * reader->fWave->bits_per_sample); soundfile->fSR[part] = reader->fWave->sample_rate; soundfile->fOffset[part] = offset; // Audio frames have to be written for each chan if (reader->fWave->bits_per_sample == 16) { float factor = 1.f/32767.f; for (int sample = 0; sample < soundfile->fLength[part]; sample++) { short* frame = (short*)&reader->fWave->data[reader->fWave->block_align * sample]; for (int chan = 0; chan < reader->fWave->num_channels; chan++) { soundfile->fBuffers[chan][offset + sample] = frame[chan] * factor; } } } else if (reader->fWave->bits_per_sample == 32) { std::cerr << "readFile : not implemented \n"; } // Update offset offset += soundfile->fLength[part]; delete reader; } }; #endif /************************** END WaveReader.h **************************/ WaveReader gReader; #elif defined(MEMORY_READER) /************************** BEGIN MemoryReader.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2018 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __MemoryReader__ #define __MemoryReader__ /* A 'MemoryReader' object can be used to prepare a set of sound resources in memory, to be used by SoundUI::addSoundfile. A Soundfile* object will have to be filled with a list of sound resources: the fLength, fOffset, fSampleRate and fBuffers fields have to be completed with the appropriate values, and will be accessed in the DSP object while running. * */ // To adapt for a real case use #define SOUND_CHAN 2 #define SOUND_LENGTH 4096 #define SOUND_SR 40100 struct MemoryReader : public SoundfileReader { MemoryReader() {} /** * Check the availability of a sound resource. * * @param path_name - the name of the file, or sound resource identified this way * * @return true if the sound resource is available, false otherwise. */ virtual bool checkFile(const std::string& path_name) { return true; } /** * Get the channels and length values of the given sound resource. * * @param path_name - the name of the file, or sound resource identified this way * @param channels - the channels value to be filled with the sound resource number of channels * @param length - the length value to be filled with the sound resource length in frames * */ virtual void getParamsFile(const std::string& path_name, int& channels, int& length) { channels = SOUND_CHAN; length = SOUND_LENGTH; } /** * Read one sound resource and fill the 'soundfile' structure accordingly * * @param path_name - the name of the file, or sound resource identified this way * @param part - the part number to be filled in the soundfile * @param offset - the offset value to be incremented with the actual sound resource length in frames * @param max_chan - the maximum number of mono channels to fill * */ virtual void readFile(Soundfile* soundfile, const std::string& path_name, int part, int& offset, int max_chan) { soundfile->fLength[part] = SOUND_LENGTH; soundfile->fSR[part] = SOUND_SR; soundfile->fOffset[part] = offset; // Audio frames have to be written for each chan for (int sample = 0; sample < SOUND_LENGTH; sample++) { for (int chan = 0; chan < SOUND_CHAN; chan++) { soundfile->fBuffers[chan][offset + sample] = 0.f; } } // Update offset offset += SOUND_LENGTH; } }; #endif /************************** END MemoryReader.h **************************/ MemoryReader gReader; #else /************************** BEGIN LibsndfileReader.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2018 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __LibsndfileReader__ #define __LibsndfileReader__ #ifdef SAMPLERATE #include <samplerate.h> #endif #include <sndfile.h> #include <string.h> #include <assert.h> #include <iostream> struct VFLibsndfile { #define SIGNED_SIZEOF(x) ((int)sizeof(x)) unsigned char* fBuffer; size_t fLength; size_t fOffset; SF_VIRTUAL_IO fVIO; VFLibsndfile(unsigned char* buffer, size_t length):fBuffer(buffer), fLength(length), fOffset(0) { fVIO.get_filelen = vfget_filelen; fVIO.seek = vfseek; fVIO.read = vfread; fVIO.write = vfwrite; fVIO.tell = vftell; } static sf_count_t vfget_filelen(void* user_data) { VFLibsndfile* vf = static_cast<VFLibsndfile*>(user_data); return vf->fLength; } static sf_count_t vfseek(sf_count_t offset, int whence, void* user_data) { VFLibsndfile* vf = static_cast<VFLibsndfile*>(user_data); switch (whence) { case SEEK_SET: vf->fOffset = offset; break; case SEEK_CUR: vf->fOffset = vf->fOffset + offset; break; case SEEK_END: vf->fOffset = vf->fLength + offset; break; default: break; }; return vf->fOffset; } static sf_count_t vfread(void* ptr, sf_count_t count, void* user_data) { VFLibsndfile* vf = static_cast<VFLibsndfile*>(user_data); /* ** This will break badly for files over 2Gig in length, but ** is sufficient for testing. */ if (vf->fOffset + count > vf->fLength) { count = vf->fLength - vf->fOffset; } memcpy(ptr, vf->fBuffer + vf->fOffset, count); vf->fOffset += count; return count; } static sf_count_t vfwrite(const void* ptr, sf_count_t count, void* user_data) { VFLibsndfile* vf = static_cast<VFLibsndfile*>(user_data); /* ** This will break badly for files over 2Gig in length, but ** is sufficient for testing. */ if (vf->fOffset >= SIGNED_SIZEOF(vf->fBuffer)) { return 0; } if (vf->fOffset + count > SIGNED_SIZEOF(vf->fBuffer)) { count = sizeof (vf->fBuffer) - vf->fOffset; } memcpy(vf->fBuffer + vf->fOffset, ptr, (size_t)count); vf->fOffset += count; if (vf->fOffset > vf->fLength) { vf->fLength = vf->fOffset; } return count; } static sf_count_t vftell(void* user_data) { VFLibsndfile* vf = static_cast<VFLibsndfile*>(user_data); return vf->fOffset; } }; struct LibsndfileReader : public SoundfileReader { LibsndfileReader() {} typedef sf_count_t (* sample_read)(SNDFILE* sndfile, FAUSTFLOAT* ptr, sf_count_t frames); // Check file bool checkFile(const std::string& path_name) { SF_INFO snd_info; snd_info.format = 0; SNDFILE* snd_file = sf_open(path_name.c_str(), SFM_READ, &snd_info); return checkFileAux(snd_file, path_name); } bool checkFile(unsigned char* buffer, size_t length) { SF_INFO snd_info; snd_info.format = 0; VFLibsndfile vio(buffer, length); SNDFILE* snd_file = sf_open_virtual(&vio.fVIO, SFM_READ, &snd_info, &vio); return checkFileAux(snd_file, "virtual file"); } bool checkFileAux(SNDFILE* snd_file, const std::string& path_name) { if (snd_file) { sf_close(snd_file); return true; } else { std::cerr << "ERROR : cannot open '" << path_name << "' (" << sf_strerror(NULL) << ")" << std::endl; return false; } } // Open the file and returns its length and channels void getParamsFile(const std::string& path_name, int& channels, int& length) { SF_INFO snd_info; snd_info.format = 0; SNDFILE* snd_file = sf_open(path_name.c_str(), SFM_READ, &snd_info); getParamsFileAux(snd_file, snd_info, channels, length); } void getParamsFile(unsigned char* buffer, size_t size, int& channels, int& length) { SF_INFO snd_info; snd_info.format = 0; VFLibsndfile vio(buffer, size); SNDFILE* snd_file = sf_open_virtual(&vio.fVIO, SFM_READ, &snd_info, &vio); getParamsFileAux(snd_file, snd_info, channels, length); } void getParamsFileAux(SNDFILE* snd_file, const SF_INFO& snd_info, int& channels, int& length) { assert(snd_file); channels = int(snd_info.channels); #ifdef SAMPLERATE length = (isResampling(snd_info.samplerate)) ? ((double(snd_info.frames) * double(fDriverSR) / double(snd_info.samplerate)) + BUFFER_SIZE) : int(snd_info.frames); #else length = int(snd_info.frames); #endif sf_close(snd_file); } // Read the file void copyToOut(Soundfile* soundfile, int size, int channels, int max_channels, int offset, FAUSTFLOAT* buffer) { for (int sample = 0; sample < size; sample++) { for (int chan = 0; chan < channels; chan++) { soundfile->fBuffers[chan][offset + sample] = buffer[sample * max_channels + chan]; } } } void readFile(Soundfile* soundfile, const std::string& path_name, int part, int& offset, int max_chan) { SF_INFO snd_info; snd_info.format = 0; SNDFILE* snd_file = sf_open(path_name.c_str(), SFM_READ, &snd_info); readFileAux(soundfile, snd_file, snd_info, part, offset, max_chan); } void readFile(Soundfile* soundfile, unsigned char* buffer, size_t length, int part, int& offset, int max_chan) { SF_INFO snd_info; snd_info.format = 0; VFLibsndfile vio(buffer, length); SNDFILE* snd_file = sf_open_virtual(&vio.fVIO, SFM_READ, &snd_info, &vio); readFileAux(soundfile, snd_file, snd_info, part, offset, max_chan); } // Will be called to fill all parts from 0 to MAX_SOUNDFILE_PARTS-1 void readFileAux(Soundfile* soundfile, SNDFILE* snd_file, const SF_INFO& snd_info, int part, int& offset, int max_chan) { assert(snd_file); int channels = std::min<int>(max_chan, snd_info.channels); #ifdef SAMPLERATE if (isResampling(snd_info.samplerate)) { soundfile->fLength[part] = int(double(snd_info.frames) * double(fDriverSR) / double(snd_info.samplerate)); soundfile->fSR[part] = fDriverSR; } else { soundfile->fLength[part] = int(snd_info.frames); soundfile->fSR[part] = snd_info.samplerate; } #else soundfile->fLength[part] = int(snd_info.frames); soundfile->fSR[part] = snd_info.samplerate; #endif soundfile->fOffset[part] = offset; // Read and fill snd_info.channels number of channels sf_count_t nbf; FAUSTFLOAT* buffer_in = (FAUSTFLOAT*)alloca(BUFFER_SIZE * sizeof(FAUSTFLOAT) * snd_info.channels); sample_read reader; if (sizeof(FAUSTFLOAT) == 4) { reader = reinterpret_cast<sample_read>(sf_readf_float); } else { reader = reinterpret_cast<sample_read>(sf_readf_double); } #ifdef SAMPLERATE // Resampling SRC_STATE* resampler = nullptr; FAUSTFLOAT* buffer_out = nullptr; if (isResampling(snd_info.samplerate)) { int error; resampler = src_new(SRC_SINC_FASTEST, channels, &error); if (error != 0) { std::cerr << "ERROR : src_new " << src_strerror(error) << std::endl; throw -1; } buffer_out = (FAUSTFLOAT*)alloca(BUFFER_SIZE * sizeof(FAUSTFLOAT) * snd_info.channels); } #endif do { nbf = reader(snd_file, buffer_in, BUFFER_SIZE); #ifdef SAMPLERATE // Resampling if (isResampling(snd_info.samplerate)) { int in_offset = 0; SRC_DATA src_data; src_data.src_ratio = double(fDriverSR)/double(snd_info.samplerate); do { src_data.data_in = &buffer_in[in_offset * snd_info.channels]; src_data.data_out = buffer_out; src_data.input_frames = nbf - in_offset; src_data.output_frames = BUFFER_SIZE; src_data.end_of_input = (nbf < BUFFER_SIZE); int res = src_process(resampler, &src_data); if (res != 0) { std::cerr << "ERROR : src_process " << src_strerror(res) << std::endl; throw -1; } copyToOut(soundfile, src_data.output_frames_gen, channels, snd_info.channels, offset, buffer_out); in_offset += src_data.input_frames_used; // Update offset offset += src_data.output_frames_gen; } while (in_offset < nbf); } else { copyToOut(soundfile, nbf, channels, snd_info.channels, offset, buffer_in); // Update offset offset += nbf; } #else copyToOut(soundfile, nbf, channels, snd_info.channels, offset, buffer_in); // Update offset offset += nbf; #endif } while (nbf == BUFFER_SIZE); sf_close(snd_file); #ifdef SAMPLERATE if (resampler) src_delete(resampler); #endif } }; #endif /************************** END LibsndfileReader.h **************************/ LibsndfileReader gReader; #endif // To be used by DSP code if no SoundUI is used std::vector<std::string> path_name_list; Soundfile* defaultsound = gReader.createSoundfile(path_name_list, MAX_CHAN); class SoundUI : public GenericUI { private: std::vector<std::string> fSoundfileDir; // The soundfile directories std::map<std::string, Soundfile*> fSoundfileMap; // Map to share loaded soundfiles SoundfileReader* fSoundReader; public: /** * Create a soundfile loader which will typically use a concrete SoundfileReader like LibsndfileReader or JuceReader to load soundfiles. * * @param sound_directory - the base directory to look for files, which paths will be relative to this one * @param sample_rate - the audio driver SR which may be different from the file SR, to possibly resample files * @param reader - an alternative soundfile reader * * @return the soundfile loader. */ SoundUI(const std::string& sound_directory = "", int sample_rate = -1, SoundfileReader* reader = nullptr) { fSoundfileDir.push_back(sound_directory); fSoundReader = (reader) ? reader : &gReader; fSoundReader->setSampleRate(sample_rate); } /** * Create a soundfile loader which will typically use a concrete SoundfileReader like LibsndfileReader or JuceReader to load soundfiles. * * @param sound_directories - a vector of base directories to look for files, which paths will be relative to these ones * @param sample_rate - the audio driver SR which may be different from the file SR, to possibly resample files * @param reader - an alternative soundfile reader * * @return the soundfile loader. */ SoundUI(const std::vector<std::string>& sound_directories, int sample_rate = -1, SoundfileReader* reader = nullptr) :fSoundfileDir(sound_directories) { fSoundReader = (reader) ? reader : &gReader; fSoundReader->setSampleRate(sample_rate); } virtual ~SoundUI() { // Delete all soundfiles std::map<std::string, Soundfile*>::iterator it; for (it = fSoundfileMap.begin(); it != fSoundfileMap.end(); it++) { delete (*it).second; } } // -- soundfiles virtual void addSoundfile(const char* label, const char* url, Soundfile** sf_zone) { const char* saved_url = url; // 'url' is consumed by parseMenuList2 std::vector<std::string> file_name_list; bool menu = parseMenuList2(url, file_name_list, true); // If not a list, we have as single file if (!menu) { file_name_list.push_back(saved_url); } // Parse the possible list if (fSoundfileMap.find(saved_url) == fSoundfileMap.end()) { // Check all files and get their complete path std::vector<std::string> path_name_list = fSoundReader->checkFiles(fSoundfileDir, file_name_list); // Read them and create the Soundfile Soundfile* sound_file = fSoundReader->createSoundfile(path_name_list, MAX_CHAN); if (sound_file) { fSoundfileMap[saved_url] = sound_file; } else { // If failure, use 'defaultsound' std::cerr << "addSoundfile : soundfile for " << saved_url << " cannot be created !" << std::endl; *sf_zone = defaultsound; return; } } // Get the soundfile *sf_zone = fSoundfileMap[saved_url]; } /** * An OS dependant function to get the path of the running executable or plugin. * This will typically be used when creating a SoundUI soundfile loader, like new SoundUI(SoundUI::getBinaryPath()); * * @return the running executable or plugin path. */ static std::string getBinaryPath() { std::string bundle_path_str; #ifdef __APPLE__ CFURLRef bundle_ref = CFBundleCopyBundleURL(CFBundleGetMainBundle()); if (!bundle_ref) { std::cerr << "getBinaryPath CFBundleCopyBundleURL error\n"; return ""; } UInt8 bundle_path[1024]; if (CFURLGetFileSystemRepresentation(bundle_ref, true, bundle_path, 1024)) { bundle_path_str = std::string((char*)bundle_path); } else { std::cerr << "getBinaryPath CFURLGetFileSystemRepresentation error\n"; } #endif #ifdef ANDROID_DRIVER bundle_path_str = "/data/data/__CURRENT_ANDROID_PACKAGE__/files"; #endif return bundle_path_str; } /** * An OS dependant function to get the path of the running executable or plugin. * This will typically be used when creating a SoundUI soundfile loader, like new SoundUI(SoundUI::getBinaryPathFrom()); * * @param path - entry point to start getting the path of the running executable or plugin. * * @return the running executable or plugin path. */ static std::string getBinaryPathFrom(const std::string& path) { std::string bundle_path_str; #ifdef __APPLE__ CFBundleRef bundle = CFBundleGetBundleWithIdentifier(CFStringCreateWithCString(kCFAllocatorDefault, path.c_str(), CFStringGetSystemEncoding())); if (!bundle) { std::cerr << "getBinaryPathFrom CFBundleGetBundleWithIdentifier error '" << path << "'" << std::endl; return ""; } CFURLRef bundle_ref = CFBundleCopyBundleURL(bundle); if (!bundle_ref) { std::cerr << "getBinaryPathFrom CFBundleCopyBundleURL error\n"; return ""; } UInt8 bundle_path[1024]; if (CFURLGetFileSystemRepresentation(bundle_ref, true, bundle_path, 1024)) { bundle_path_str = std::string((char*)bundle_path); } else { std::cerr << "getBinaryPathFrom CFURLGetFileSystemRepresentation error\n"; } #endif #ifdef ANDROID_DRIVER bundle_path_str = "/data/data/__CURRENT_ANDROID_PACKAGE__/files"; #endif return bundle_path_str; } }; #endif /************************** END SoundUI.h **************************/ #endif // For FAUST_CLASS_NAME to be defined #define FAUST_UIMACROS // but we will ignore most of them #define FAUST_ADDBUTTON(l,f) #define FAUST_ADDCHECKBOX(l,f) #define FAUST_ADDVERTICALSLIDER(l,f,i,a,b,s) #define FAUST_ADDHORIZONTALSLIDER(l,f,i,a,b,s) #define FAUST_ADDNUMENTRY(l,f,i,a,b,s) #define FAUST_ADDVERTICALBARGRAPH(l,f,a,b) #define FAUST_ADDHORIZONTALBARGRAPH(l,f,a,b) #define FAUST_ADDSOUNDFILE(s,f) using namespace std; /****************************************************************************** ******************************************************************************* VECTOR INTRINSICS ******************************************************************************* *******************************************************************************/ /********************END ARCHITECTURE SECTION (part 1/2)****************/ /**************************BEGIN USER SECTION **************************/ #ifndef FAUSTFLOAT #define FAUSTFLOAT float #endif #include <algorithm> #include <cmath> #include <math.h> #ifndef FAUSTCLASS #define FAUSTCLASS ue_binaural_decoder #endif #ifdef __APPLE__ #define exp10f __exp10f #define exp10 __exp10 #endif class ue_binaural_decoder : public dsp { public: int fSampleRate; double fConst0; FAUSTFLOAT fVslider0; double fRec1[2]; FAUSTFLOAT fCheckbox0; FAUSTFLOAT fCheckbox1; FAUSTFLOAT fVslider1; double fRec3[2]; double fRec2[2]; FAUSTFLOAT fVbargraph0; int IOTA; double fVec0[128]; FAUSTFLOAT fCheckbox2; double fRec4[2]; FAUSTFLOAT fVbargraph1; double fVec1[128]; FAUSTFLOAT fCheckbox3; double fRec5[2]; FAUSTFLOAT fVbargraph2; double fVec2[128]; FAUSTFLOAT fCheckbox4; double fRec6[2]; FAUSTFLOAT fVbargraph3; double fVec3[128]; FAUSTFLOAT fCheckbox5; double fRec7[2]; FAUSTFLOAT fVbargraph4; double fVec4[128]; FAUSTFLOAT fCheckbox6; FAUSTFLOAT fCheckbox7; double fRec8[2]; FAUSTFLOAT fVbargraph5; double fVec5[128]; FAUSTFLOAT fCheckbox8; double fRec9[2]; FAUSTFLOAT fVbargraph6; double fVec6[128]; FAUSTFLOAT fCheckbox9; double fRec10[2]; FAUSTFLOAT fVbargraph7; double fVec7[128]; FAUSTFLOAT fCheckbox10; FAUSTFLOAT fCheckbox11; double fRec11[2]; FAUSTFLOAT fVbargraph8; double fVec8[128]; double fRec0[2]; FAUSTFLOAT fHbargraph0; double fRec12[2]; FAUSTFLOAT fHbargraph1; public: void metadata(Meta* m) { m->declare("author", "Pierre Lecomte"); m->declare("basics.lib/name", "Faust Basic Element Library"); m->declare("basics.lib/version", "0.1"); m->declare("copyright", "(c) Pierre Lecomte 2015"); m->declare("filename", "ue.binaural.decoder.dsp"); m->declare("filters.lib/fir:author", "Julius O. Smith III"); m->declare("filters.lib/fir:copyright", "Copyright (C) 2003-2019 by Julius O. Smith III <[email protected]>"); m->declare("filters.lib/fir:license", "MIT-style STK-4.3 license"); m->declare("filters.lib/lowpass0_highpass1", "Copyright (C) 2003-2019 by Julius O. Smith III <[email protected]>"); m->declare("filters.lib/name", "Faust Filters Library"); m->declare("gui.lib/author", "Pierre Lecomte"); m->declare("gui.lib/copyright", "(c) Pierre Lecomte 2016"); m->declare("gui.lib/license", "GPL"); m->declare("gui.lib/name", "GUI Library"); m->declare("gui.lib/version", "1.0"); m->declare("license", "GPL)"); m->declare("maths.lib/author", "GRAME"); m->declare("maths.lib/copyright", "GRAME"); m->declare("maths.lib/license", "LGPL with exception"); m->declare("maths.lib/name", "Faust Math Library"); m->declare("maths.lib/version", "2.3"); m->declare("name", "Binaural decoder"); m->declare("platform.lib/name", "Generic Platform Library"); m->declare("platform.lib/version", "0.1"); m->declare("signals.lib/name", "Faust Signal Routing Library"); m->declare("signals.lib/version", "0.0"); m->declare("version", "1.0"); } virtual int getNumInputs() { return 9; } virtual int getNumOutputs() { return 2; } virtual int getInputRate(int channel) { int rate; switch ((channel)) { case 0: { rate = 1; break; } case 1: { rate = 1; break; } case 2: { rate = 1; break; } case 3: { rate = 1; break; } case 4: { rate = 1; break; } case 5: { rate = 1; break; } case 6: { rate = 1; break; } case 7: { rate = 1; break; } case 8: { rate = 1; break; } default: { rate = -1; break; } } return rate; } virtual int getOutputRate(int channel) { int rate; switch ((channel)) { case 0: { rate = 1; break; } case 1: { rate = 1; break; } default: { rate = -1; break; } } return rate; } static void classInit(int sample_rate) { } virtual void instanceConstants(int sample_rate) { fSampleRate = sample_rate; fConst0 = (80.0 / std::min<double>(192000.0, std::max<double>(1.0, double(fSampleRate)))); } virtual void instanceResetUserInterface() { fVslider0 = FAUSTFLOAT(0.0); fCheckbox0 = FAUSTFLOAT(0.0); fCheckbox1 = FAUSTFLOAT(0.0); fVslider1 = FAUSTFLOAT(0.0); fCheckbox2 = FAUSTFLOAT(0.0); fCheckbox3 = FAUSTFLOAT(0.0); fCheckbox4 = FAUSTFLOAT(0.0); fCheckbox5 = FAUSTFLOAT(0.0); fCheckbox6 = FAUSTFLOAT(0.0); fCheckbox7 = FAUSTFLOAT(0.0); fCheckbox8 = FAUSTFLOAT(0.0); fCheckbox9 = FAUSTFLOAT(0.0); fCheckbox10 = FAUSTFLOAT(0.0); fCheckbox11 = FAUSTFLOAT(0.0); } virtual void instanceClear() { for (int l0 = 0; (l0 < 2); l0 = (l0 + 1)) { fRec1[l0] = 0.0; } for (int l1 = 0; (l1 < 2); l1 = (l1 + 1)) { fRec3[l1] = 0.0; } for (int l2 = 0; (l2 < 2); l2 = (l2 + 1)) { fRec2[l2] = 0.0; } IOTA = 0; for (int l3 = 0; (l3 < 128); l3 = (l3 + 1)) { fVec0[l3] = 0.0; } for (int l4 = 0; (l4 < 2); l4 = (l4 + 1)) { fRec4[l4] = 0.0; } for (int l5 = 0; (l5 < 128); l5 = (l5 + 1)) { fVec1[l5] = 0.0; } for (int l6 = 0; (l6 < 2); l6 = (l6 + 1)) { fRec5[l6] = 0.0; } for (int l7 = 0; (l7 < 128); l7 = (l7 + 1)) { fVec2[l7] = 0.0; } for (int l8 = 0; (l8 < 2); l8 = (l8 + 1)) { fRec6[l8] = 0.0; } for (int l9 = 0; (l9 < 128); l9 = (l9 + 1)) { fVec3[l9] = 0.0; } for (int l10 = 0; (l10 < 2); l10 = (l10 + 1)) { fRec7[l10] = 0.0; } for (int l11 = 0; (l11 < 128); l11 = (l11 + 1)) { fVec4[l11] = 0.0; } for (int l12 = 0; (l12 < 2); l12 = (l12 + 1)) { fRec8[l12] = 0.0; } for (int l13 = 0; (l13 < 128); l13 = (l13 + 1)) { fVec5[l13] = 0.0; } for (int l14 = 0; (l14 < 2); l14 = (l14 + 1)) { fRec9[l14] = 0.0; } for (int l15 = 0; (l15 < 128); l15 = (l15 + 1)) { fVec6[l15] = 0.0; } for (int l16 = 0; (l16 < 2); l16 = (l16 + 1)) { fRec10[l16] = 0.0; } for (int l17 = 0; (l17 < 128); l17 = (l17 + 1)) { fVec7[l17] = 0.0; } for (int l18 = 0; (l18 < 2); l18 = (l18 + 1)) { fRec11[l18] = 0.0; } for (int l19 = 0; (l19 < 128); l19 = (l19 + 1)) { fVec8[l19] = 0.0; } for (int l20 = 0; (l20 < 2); l20 = (l20 + 1)) { fRec0[l20] = 0.0; } for (int l21 = 0; (l21 < 2); l21 = (l21 + 1)) { fRec12[l21] = 0.0; } } virtual void init(int sample_rate) { classInit(sample_rate); instanceInit(sample_rate); } virtual void instanceInit(int sample_rate) { instanceConstants(sample_rate); instanceResetUserInterface(); instanceClear(); } virtual ue_binaural_decoder* clone() { return new ue_binaural_decoder(); } virtual int getSampleRate() { return fSampleRate; } virtual void buildUserInterface(UI* ui_interface) { ui_interface->openVerticalBox("Binaural decoder"); ui_interface->openHorizontalBox("Inputs"); ui_interface->openHorizontalBox("0"); ui_interface->openVerticalBox("0"); ui_interface->addCheckButton("Mute", &fCheckbox11); ui_interface->declare(&fVbargraph8, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86aec7ecc0", &fVbargraph8, -70.0, 6.0); ui_interface->closeBox(); ui_interface->addCheckButton("Mute", &fCheckbox10); ui_interface->closeBox(); ui_interface->openHorizontalBox("1"); ui_interface->openVerticalBox("1"); ui_interface->addCheckButton("Mute", &fCheckbox8); ui_interface->declare(&fVbargraph6, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86af00c9d0", &fVbargraph6, -70.0, 6.0); ui_interface->closeBox(); ui_interface->openVerticalBox("2"); ui_interface->addCheckButton("Mute", &fCheckbox9); ui_interface->declare(&fVbargraph7, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86af030f70", &fVbargraph7, -70.0, 6.0); ui_interface->closeBox(); ui_interface->openVerticalBox("3"); ui_interface->addCheckButton("Mute", &fCheckbox7); ui_interface->declare(&fVbargraph5, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86af2bdfb0", &fVbargraph5, -70.0, 6.0); ui_interface->closeBox(); ui_interface->addCheckButton("Mute", &fCheckbox6); ui_interface->closeBox(); ui_interface->openHorizontalBox("2"); ui_interface->openVerticalBox("4"); ui_interface->addCheckButton("Mute", &fCheckbox5); ui_interface->declare(&fVbargraph4, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86af28ef70", &fVbargraph4, -70.0, 6.0); ui_interface->closeBox(); ui_interface->openVerticalBox("5"); ui_interface->addCheckButton("Mute", &fCheckbox4); ui_interface->declare(&fVbargraph3, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86af24b780", &fVbargraph3, -70.0, 6.0); ui_interface->closeBox(); ui_interface->openVerticalBox("6"); ui_interface->addCheckButton("Mute", &fCheckbox3); ui_interface->declare(&fVbargraph2, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86af240d10", &fVbargraph2, -70.0, 6.0); ui_interface->closeBox(); ui_interface->openVerticalBox("7"); ui_interface->addCheckButton("Mute", &fCheckbox2); ui_interface->declare(&fVbargraph1, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86af218080", &fVbargraph1, -70.0, 6.0); ui_interface->closeBox(); ui_interface->openVerticalBox("8"); ui_interface->addCheckButton("Mute", &fCheckbox1); ui_interface->declare(&fVbargraph0, "unit", "dB"); ui_interface->addVerticalBargraph("0x7f86af20b8b0", &fVbargraph0, -70.0, 6.0); ui_interface->closeBox(); ui_interface->addCheckButton("Mute", &fCheckbox0); ui_interface->closeBox(); ui_interface->declare(&fVslider1, "1", ""); ui_interface->declare(&fVslider1, "osc", "/levelin -10 10"); ui_interface->declare(&fVslider1, "unit", "dB"); ui_interface->addVerticalSlider("Inputs Gain", &fVslider1, 0.0, -10.0, 10.0, 0.10000000000000001); ui_interface->declare(&fVslider0, "2", ""); ui_interface->declare(&fVslider0, "osc", "/levelout -10 10"); ui_interface->declare(&fVslider0, "unit", "dB"); ui_interface->addVerticalSlider("Outputs Gain", &fVslider0, 0.0, -10.0, 10.0, 0.10000000000000001); ui_interface->closeBox(); ui_interface->openVerticalBox("Outputs"); ui_interface->openHorizontalBox("Left"); ui_interface->declare(&fHbargraph0, "unit", "dB"); ui_interface->addHorizontalBargraph("0x7f86af061850", &fHbargraph0, -70.0, 6.0); ui_interface->closeBox(); ui_interface->openHorizontalBox("Right"); ui_interface->declare(&fHbargraph1, "unit", "dB"); ui_interface->addHorizontalBargraph("0x7f86af5b81e0", &fHbargraph1, -70.0, 6.0); ui_interface->closeBox(); ui_interface->closeBox(); ui_interface->closeBox(); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { FAUSTFLOAT* input0 = inputs[0]; FAUSTFLOAT* input1 = inputs[1]; FAUSTFLOAT* input2 = inputs[2]; FAUSTFLOAT* input3 = inputs[3]; FAUSTFLOAT* input4 = inputs[4]; FAUSTFLOAT* input5 = inputs[5]; FAUSTFLOAT* input6 = inputs[6]; FAUSTFLOAT* input7 = inputs[7]; FAUSTFLOAT* input8 = inputs[8]; FAUSTFLOAT* output0 = outputs[0]; FAUSTFLOAT* output1 = outputs[1]; double fSlow0 = (0.0010000000000000009 * std::pow(10.0, (0.050000000000000003 * double(fVslider0)))); double fSlow1 = (1.0 - double(fCheckbox0)); double fSlow2 = (fSlow1 * (1.0 - double(fCheckbox1))); double fSlow3 = (0.0010000000000000009 * std::pow(10.0, (0.050000000000000003 * double(fVslider1)))); double fSlow4 = (fSlow1 * (1.0 - double(fCheckbox2))); double fSlow5 = (fSlow1 * (1.0 - double(fCheckbox3))); double fSlow6 = (fSlow1 * (1.0 - double(fCheckbox4))); double fSlow7 = (fSlow1 * (1.0 - double(fCheckbox5))); double fSlow8 = (1.0 - double(fCheckbox6)); double fSlow9 = (fSlow8 * (1.0 - double(fCheckbox7))); double fSlow10 = (fSlow8 * (1.0 - double(fCheckbox8))); double fSlow11 = (fSlow8 * (1.0 - double(fCheckbox9))); double fSlow12 = ((1.0 - double(fCheckbox10)) * (1.0 - double(fCheckbox11))); for (int i = 0; (i < count); i = (i + 1)) { fRec1[0] = (fSlow0 + (0.999 * fRec1[1])); fRec3[0] = (fSlow3 + (0.999 * fRec3[1])); double fTemp0 = (fSlow2 * (double(input8[i]) * fRec3[0])); fRec2[0] = std::max<double>((fRec2[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp0)))))); fVbargraph0 = FAUSTFLOAT(fRec2[0]); fVec0[(IOTA & 127)] = fTemp0; double fTemp1 = fVec0[((IOTA - 121) & 127)]; double fTemp2 = fVec0[((IOTA - 110) & 127)]; double fTemp3 = fVec0[((IOTA - 75) & 127)]; double fTemp4 = fVec0[((IOTA - 74) & 127)]; double fTemp5 = fVec0[((IOTA - 70) & 127)]; double fTemp6 = fVec0[((IOTA - 72) & 127)]; double fTemp7 = fVec0[((IOTA - 71) & 127)]; double fTemp8 = fVec0[((IOTA - 53) & 127)]; double fTemp9 = fVec0[((IOTA - 42) & 127)]; double fTemp10 = fVec0[((IOTA - 38) & 127)]; double fTemp11 = (fSlow4 * (double(input7[i]) * fRec3[0])); fRec4[0] = std::max<double>((fRec4[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp11)))))); fVbargraph1 = FAUSTFLOAT(fRec4[0]); fVec1[(IOTA & 127)] = fTemp11; double fTemp12 = fVec1[((IOTA - 125) & 127)]; double fTemp13 = fVec1[((IOTA - 117) & 127)]; double fTemp14 = fVec1[((IOTA - 116) & 127)]; double fTemp15 = fVec1[((IOTA - 121) & 127)]; double fTemp16 = fVec1[((IOTA - 111) & 127)]; double fTemp17 = fVec1[((IOTA - 110) & 127)]; double fTemp18 = fVec1[((IOTA - 103) & 127)]; double fTemp19 = fVec1[((IOTA - 102) & 127)]; double fTemp20 = fVec1[((IOTA - 101) & 127)]; double fTemp21 = fVec1[((IOTA - 94) & 127)]; double fTemp22 = fVec1[((IOTA - 100) & 127)]; double fTemp23 = fVec1[((IOTA - 99) & 127)]; double fTemp24 = fVec1[((IOTA - 93) & 127)]; double fTemp25 = fVec1[((IOTA - 77) & 127)]; double fTemp26 = fVec1[((IOTA - 76) & 127)]; double fTemp27 = fVec1[((IOTA - 68) & 127)]; double fTemp28 = fVec1[((IOTA - 72) & 127)]; double fTemp29 = fVec1[((IOTA - 70) & 127)]; double fTemp30 = fVec1[((IOTA - 67) & 127)]; double fTemp31 = fVec1[((IOTA - 66) & 127)]; double fTemp32 = fVec1[((IOTA - 59) & 127)]; double fTemp33 = fVec1[((IOTA - 44) & 127)]; double fTemp34 = fVec1[((IOTA - 41) & 127)]; double fTemp35 = fVec1[((IOTA - 32) & 127)]; double fTemp36 = fVec1[((IOTA - 31) & 127)]; double fTemp37 = fVec1[((IOTA - 29) & 127)]; double fTemp38 = fVec1[((IOTA - 26) & 127)]; double fTemp39 = fVec1[((IOTA - 25) & 127)]; double fTemp40 = fVec0[((IOTA - 126) & 127)]; double fTemp41 = fVec0[((IOTA - 122) & 127)]; double fTemp42 = fVec0[((IOTA - 95) & 127)]; double fTemp43 = fVec0[((IOTA - 96) & 127)]; double fTemp44 = fVec0[((IOTA - 94) & 127)]; double fTemp45 = fVec0[((IOTA - 91) & 127)]; double fTemp46 = fVec0[((IOTA - 104) & 127)]; double fTemp47 = fVec0[((IOTA - 103) & 127)]; double fTemp48 = fVec0[((IOTA - 77) & 127)]; double fTemp49 = fVec0[((IOTA - 79) & 127)]; double fTemp50 = fVec0[((IOTA - 76) & 127)]; double fTemp51 = fVec0[((IOTA - 68) & 127)]; double fTemp52 = fVec0[((IOTA - 67) & 127)]; double fTemp53 = fVec0[((IOTA - 66) & 127)]; double fTemp54 = fVec0[((IOTA - 65) & 127)]; double fTemp55 = fVec0[((IOTA - 64) & 127)]; double fTemp56 = fVec0[((IOTA - 20) & 127)]; double fTemp57 = fVec0[((IOTA - 19) & 127)]; double fTemp58 = fVec0[((IOTA - 18) & 127)]; double fTemp59 = fVec0[((IOTA - 10) & 127)]; double fTemp60 = fVec0[((IOTA - 8) & 127)]; double fTemp61 = fVec0[((IOTA - 6) & 127)]; double fTemp62 = fVec0[((IOTA - 4) & 127)]; double fTemp63 = fVec0[((IOTA - 2) & 127)]; double fTemp64 = fVec1[((IOTA - 126) & 127)]; double fTemp65 = fVec1[((IOTA - 104) & 127)]; double fTemp66 = fVec1[((IOTA - 106) & 127)]; double fTemp67 = fVec1[((IOTA - 105) & 127)]; double fTemp68 = fVec1[((IOTA - 98) & 127)]; double fTemp69 = fVec1[((IOTA - 97) & 127)]; double fTemp70 = fVec1[((IOTA - 50) & 127)]; double fTemp71 = (fSlow5 * (double(input6[i]) * fRec3[0])); fRec5[0] = std::max<double>((fRec5[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp71)))))); fVbargraph2 = FAUSTFLOAT(fRec5[0]); fVec2[(IOTA & 127)] = fTemp71; double fTemp72 = fVec2[((IOTA - 94) & 127)]; double fTemp73 = fVec2[((IOTA - 93) & 127)]; double fTemp74 = fVec2[((IOTA - 92) & 127)]; double fTemp75 = fVec2[((IOTA - 110) & 127)]; double fTemp76 = fVec2[((IOTA - 91) & 127)]; double fTemp77 = fVec2[((IOTA - 109) & 127)]; double fTemp78 = fVec2[((IOTA - 90) & 127)]; double fTemp79 = fVec2[((IOTA - 22) & 127)]; double fTemp80 = (fSlow6 * (double(input5[i]) * fRec3[0])); fRec6[0] = std::max<double>((fRec6[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp80)))))); fVbargraph3 = FAUSTFLOAT(fRec6[0]); fVec3[(IOTA & 127)] = fTemp80; double fTemp81 = fVec3[((IOTA - 123) & 127)]; double fTemp82 = fVec2[((IOTA - 24) & 127)]; double fTemp83 = fVec3[((IOTA - 107) & 127)]; double fTemp84 = fVec3[((IOTA - 104) & 127)]; double fTemp85 = fVec3[((IOTA - 103) & 127)]; double fTemp86 = fVec3[((IOTA - 102) & 127)]; double fTemp87 = fVec3[((IOTA - 106) & 127)]; double fTemp88 = fVec3[((IOTA - 105) & 127)]; double fTemp89 = fVec2[((IOTA - 26) & 127)]; double fTemp90 = fVec2[((IOTA - 25) & 127)]; double fTemp91 = fVec3[((IOTA - 99) & 127)]; double fTemp92 = fVec1[((IOTA - 18) & 127)]; double fTemp93 = fVec1[((IOTA - 19) & 127)]; double fTemp94 = fVec1[((IOTA - 15) & 127)]; double fTemp95 = fVec1[((IOTA - 12) & 127)]; double fTemp96 = fVec1[((IOTA - 11) & 127)]; double fTemp97 = fVec1[((IOTA - 9) & 127)]; double fTemp98 = fVec1[((IOTA - 10) & 127)]; double fTemp99 = fVec1[((IOTA - 3) & 127)]; double fTemp100 = fVec1[((IOTA - 2) & 127)]; double fTemp101 = fVec1[((IOTA - 7) & 127)]; double fTemp102 = fVec1[((IOTA - 6) & 127)]; double fTemp103 = fVec2[((IOTA - 118) & 127)]; double fTemp104 = fVec2[((IOTA - 108) & 127)]; double fTemp105 = fVec2[((IOTA - 107) & 127)]; double fTemp106 = fVec2[((IOTA - 105) & 127)]; double fTemp107 = fVec2[((IOTA - 104) & 127)]; double fTemp108 = fVec2[((IOTA - 102) & 127)]; double fTemp109 = fVec2[((IOTA - 101) & 127)]; double fTemp110 = fVec2[((IOTA - 100) & 127)]; double fTemp111 = fVec2[((IOTA - 99) & 127)]; double fTemp112 = fVec2[((IOTA - 98) & 127)]; double fTemp113 = fVec2[((IOTA - 106) & 127)]; double fTemp114 = fVec2[((IOTA - 119) & 127)]; double fTemp115 = fVec2[((IOTA - 126) & 127)]; double fTemp116 = fVec2[((IOTA - 88) & 127)]; double fTemp117 = fVec2[((IOTA - 97) & 127)]; double fTemp118 = fVec2[((IOTA - 87) & 127)]; double fTemp119 = fVec2[((IOTA - 84) & 127)]; double fTemp120 = fVec2[((IOTA - 83) & 127)]; double fTemp121 = fVec2[((IOTA - 79) & 127)]; double fTemp122 = fVec2[((IOTA - 82) & 127)]; double fTemp123 = fVec2[((IOTA - 75) & 127)]; double fTemp124 = fVec2[((IOTA - 72) & 127)]; double fTemp125 = fVec2[((IOTA - 71) & 127)]; double fTemp126 = fVec2[((IOTA - 70) & 127)]; double fTemp127 = fVec2[((IOTA - 66) & 127)]; double fTemp128 = fVec2[((IOTA - 64) & 127)]; double fTemp129 = fVec2[((IOTA - 60) & 127)]; double fTemp130 = fVec2[((IOTA - 52) & 127)]; double fTemp131 = fVec2[((IOTA - 63) & 127)]; double fTemp132 = fVec2[((IOTA - 65) & 127)]; double fTemp133 = fVec3[((IOTA - 126) & 127)]; double fTemp134 = fVec3[((IOTA - 125) & 127)]; double fTemp135 = fVec3[((IOTA - 124) & 127)]; double fTemp136 = fVec3[((IOTA - 116) & 127)]; double fTemp137 = fVec3[((IOTA - 113) & 127)]; double fTemp138 = fVec3[((IOTA - 110) & 127)]; double fTemp139 = fVec3[((IOTA - 108) & 127)]; double fTemp140 = fVec3[((IOTA - 109) & 127)]; double fTemp141 = fVec3[((IOTA - 98) & 127)]; double fTemp142 = fVec3[((IOTA - 97) & 127)]; double fTemp143 = fVec3[((IOTA - 96) & 127)]; double fTemp144 = fVec3[((IOTA - 95) & 127)]; double fTemp145 = fVec3[((IOTA - 94) & 127)]; double fTemp146 = fVec3[((IOTA - 93) & 127)]; double fTemp147 = fVec3[((IOTA - 92) & 127)]; double fTemp148 = fVec3[((IOTA - 91) & 127)]; double fTemp149 = fVec3[((IOTA - 90) & 127)]; double fTemp150 = fVec3[((IOTA - 89) & 127)]; double fTemp151 = fVec3[((IOTA - 88) & 127)]; double fTemp152 = fVec3[((IOTA - 115) & 127)]; double fTemp153 = fVec3[((IOTA - 114) & 127)]; double fTemp154 = fVec3[((IOTA - 86) & 127)]; double fTemp155 = fVec3[((IOTA - 85) & 127)]; double fTemp156 = fVec3[((IOTA - 83) & 127)]; double fTemp157 = fVec3[((IOTA - 77) & 127)]; double fTemp158 = fVec3[((IOTA - 76) & 127)]; double fTemp159 = fVec3[((IOTA - 87) & 127)]; double fTemp160 = fVec3[((IOTA - 75) & 127)]; double fTemp161 = fVec3[((IOTA - 78) & 127)]; double fTemp162 = fVec3[((IOTA - 74) & 127)]; double fTemp163 = fVec3[((IOTA - 73) & 127)]; double fTemp164 = fVec3[((IOTA - 71) & 127)]; double fTemp165 = fVec3[((IOTA - 72) & 127)]; double fTemp166 = fVec3[((IOTA - 64) & 127)]; double fTemp167 = fVec3[((IOTA - 60) & 127)]; double fTemp168 = fVec3[((IOTA - 35) & 127)]; double fTemp169 = fVec3[((IOTA - 38) & 127)]; double fTemp170 = fVec3[((IOTA - 33) & 127)]; double fTemp171 = fVec3[((IOTA - 32) & 127)]; double fTemp172 = fVec3[((IOTA - 36) & 127)]; double fTemp173 = fVec3[((IOTA - 29) & 127)]; double fTemp174 = fVec3[((IOTA - 28) & 127)]; double fTemp175 = fVec3[((IOTA - 23) & 127)]; double fTemp176 = fVec3[((IOTA - 24) & 127)]; double fTemp177 = fVec3[((IOTA - 21) & 127)]; double fTemp178 = fVec3[((IOTA - 22) & 127)]; double fTemp179 = fVec3[((IOTA - 20) & 127)]; double fTemp180 = fVec3[((IOTA - 17) & 127)]; double fTemp181 = fVec3[((IOTA - 13) & 127)]; double fTemp182 = fVec3[((IOTA - 14) & 127)]; double fTemp183 = fVec3[((IOTA - 10) & 127)]; double fTemp184 = fVec3[((IOTA - 8) & 127)]; double fTemp185 = fVec3[((IOTA - 6) & 127)]; double fTemp186 = fVec3[((IOTA - 5) & 127)]; double fTemp187 = fVec3[((IOTA - 4) & 127)]; double fTemp188 = fVec3[((IOTA - 2) & 127)]; double fTemp189 = fVec3[((IOTA - 1) & 127)]; double fTemp190 = fVec3[((IOTA - 39) & 127)]; double fTemp191 = (fSlow7 * (double(input4[i]) * fRec3[0])); fRec7[0] = std::max<double>((fRec7[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp191)))))); fVbargraph4 = FAUSTFLOAT(fRec7[0]); fVec4[(IOTA & 127)] = fTemp191; double fTemp192 = fVec4[((IOTA - 119) & 127)]; double fTemp193 = fVec3[((IOTA - 40) & 127)]; double fTemp194 = fVec4[((IOTA - 117) & 127)]; double fTemp195 = fVec4[((IOTA - 116) & 127)]; double fTemp196 = fVec4[((IOTA - 113) & 127)]; double fTemp197 = fVec4[((IOTA - 125) & 127)]; double fTemp198 = fVec4[((IOTA - 114) & 127)]; double fTemp199 = fVec4[((IOTA - 111) & 127)]; double fTemp200 = fVec4[((IOTA - 110) & 127)]; double fTemp201 = fVec4[((IOTA - 112) & 127)]; double fTemp202 = fVec4[((IOTA - 106) & 127)]; double fTemp203 = fVec4[((IOTA - 105) & 127)]; double fTemp204 = fVec4[((IOTA - 108) & 127)]; double fTemp205 = fVec4[((IOTA - 104) & 127)]; double fTemp206 = fVec4[((IOTA - 126) & 127)]; double fTemp207 = fVec4[((IOTA - 124) & 127)]; double fTemp208 = fVec4[((IOTA - 101) & 127)]; double fTemp209 = fVec4[((IOTA - 98) & 127)]; double fTemp210 = fVec4[((IOTA - 97) & 127)]; double fTemp211 = fVec4[((IOTA - 93) & 127)]; double fTemp212 = fVec4[((IOTA - 95) & 127)]; double fTemp213 = fVec4[((IOTA - 87) & 127)]; double fTemp214 = fVec4[((IOTA - 86) & 127)]; double fTemp215 = fVec4[((IOTA - 75) & 127)]; double fTemp216 = fVec4[((IOTA - 83) & 127)]; double fTemp217 = fVec4[((IOTA - 94) & 127)]; double fTemp218 = fVec4[((IOTA - 107) & 127)]; double fTemp219 = fVec4[((IOTA - 74) & 127)]; double fTemp220 = fVec4[((IOTA - 62) & 127)]; double fTemp221 = fVec4[((IOTA - 50) & 127)]; double fTemp222 = fVec4[((IOTA - 48) & 127)]; double fTemp223 = fVec4[((IOTA - 49) & 127)]; double fTemp224 = fVec4[((IOTA - 45) & 127)]; double fTemp225 = fVec4[((IOTA - 42) & 127)]; double fTemp226 = fVec4[((IOTA - 44) & 127)]; double fTemp227 = fVec4[((IOTA - 40) & 127)]; double fTemp228 = fVec4[((IOTA - 38) & 127)]; double fTemp229 = fVec4[((IOTA - 39) & 127)]; double fTemp230 = fVec4[((IOTA - 37) & 127)]; double fTemp231 = fVec4[((IOTA - 36) & 127)]; double fTemp232 = fVec4[((IOTA - 35) & 127)]; double fTemp233 = fVec4[((IOTA - 31) & 127)]; double fTemp234 = fVec4[((IOTA - 30) & 127)]; double fTemp235 = fVec0[((IOTA - 117) & 127)]; double fTemp236 = fVec0[((IOTA - 33) & 127)]; double fTemp237 = fVec0[((IOTA - 34) & 127)]; double fTemp238 = fVec1[((IOTA - 64) & 127)]; double fTemp239 = fVec1[((IOTA - 86) & 127)]; double fTemp240 = fVec1[((IOTA - 85) & 127)]; double fTemp241 = fVec1[((IOTA - 63) & 127)]; double fTemp242 = fVec1[((IOTA - 62) & 127)]; double fTemp243 = fVec1[((IOTA - 58) & 127)]; double fTemp244 = fVec1[((IOTA - 57) & 127)]; double fTemp245 = fVec1[((IOTA - 54) & 127)]; double fTemp246 = fVec1[((IOTA - 55) & 127)]; double fTemp247 = fVec1[((IOTA - 56) & 127)]; double fTemp248 = fVec1[((IOTA - 36) & 127)]; double fTemp249 = fVec1[((IOTA - 38) & 127)]; double fTemp250 = fVec1[((IOTA - 35) & 127)]; double fTemp251 = fVec2[((IOTA - 20) & 127)]; double fTemp252 = fVec2[((IOTA - 21) & 127)]; double fTemp253 = fVec2[((IOTA - 19) & 127)]; double fTemp254 = fVec2[((IOTA - 18) & 127)]; double fTemp255 = fVec2[((IOTA - 10) & 127)]; double fTemp256 = fVec2[((IOTA - 8) & 127)]; double fTemp257 = fVec2[((IOTA - 6) & 127)]; double fTemp258 = fVec2[((IOTA - 2) & 127)]; double fTemp259 = fVec4[((IOTA - 123) & 127)]; double fTemp260 = fVec4[((IOTA - 92) & 127)]; double fTemp261 = fVec4[((IOTA - 78) & 127)]; double fTemp262 = fVec4[((IOTA - 59) & 127)]; double fTemp263 = fVec4[((IOTA - 58) & 127)]; double fTemp264 = fVec4[((IOTA - 52) & 127)]; double fTemp265 = (fSlow9 * (double(input3[i]) * fRec3[0])); fRec8[0] = std::max<double>((fRec8[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp265)))))); fVbargraph5 = FAUSTFLOAT(fRec8[0]); fVec5[(IOTA & 127)] = fTemp265; double fTemp266 = fVec5[((IOTA - 125) & 127)]; double fTemp267 = fVec4[((IOTA - 57) & 127)]; double fTemp268 = fVec4[((IOTA - 56) & 127)]; double fTemp269 = fVec5[((IOTA - 123) & 127)]; double fTemp270 = fVec0[((IOTA - 120) & 127)]; double fTemp271 = fVec0[((IOTA - 86) & 127)]; double fTemp272 = fVec0[((IOTA - 69) & 127)]; double fTemp273 = fVec0[((IOTA - 28) & 127)]; double fTemp274 = fVec0[((IOTA - 30) & 127)]; double fTemp275 = fVec0[((IOTA - 29) & 127)]; double fTemp276 = fVec0[((IOTA - 27) & 127)]; double fTemp277 = fVec0[((IOTA - 24) & 127)]; double fTemp278 = fVec0[((IOTA - 23) & 127)]; double fTemp279 = fVec0[((IOTA - 26) & 127)]; double fTemp280 = fVec1[((IOTA - 108) & 127)]; double fTemp281 = fVec1[((IOTA - 107) & 127)]; double fTemp282 = fVec1[((IOTA - 71) & 127)]; double fTemp283 = fVec1[((IOTA - 61) & 127)]; double fTemp284 = fVec1[((IOTA - 51) & 127)]; double fTemp285 = fVec3[((IOTA - 67) & 127)]; double fTemp286 = (fSlow10 * (double(input1[i]) * fRec3[0])); fRec9[0] = std::max<double>((fRec9[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp286)))))); fVbargraph6 = FAUSTFLOAT(fRec9[0]); fVec6[(IOTA & 127)] = fTemp286; double fTemp287 = fVec6[((IOTA - 99) & 127)]; double fTemp288 = fVec4[((IOTA - 61) & 127)]; double fTemp289 = fVec4[((IOTA - 4) & 127)]; double fTemp290 = fVec4[((IOTA - 2) & 127)]; double fTemp291 = fVec4[((IOTA - 1) & 127)]; double fTemp292 = fVec4[((IOTA - 18) & 127)]; double fTemp293 = fVec4[((IOTA - 17) & 127)]; double fTemp294 = fVec4[((IOTA - 16) & 127)]; double fTemp295 = fVec4[((IOTA - 15) & 127)]; double fTemp296 = fVec4[((IOTA - 13) & 127)]; double fTemp297 = fVec4[((IOTA - 10) & 127)]; double fTemp298 = fVec4[((IOTA - 8) & 127)]; double fTemp299 = fVec4[((IOTA - 6) & 127)]; double fTemp300 = fVec5[((IOTA - 121) & 127)]; double fTemp301 = fVec5[((IOTA - 126) & 127)]; double fTemp302 = fVec4[((IOTA - 26) & 127)]; double fTemp303 = fVec4[((IOTA - 25) & 127)]; double fTemp304 = fVec5[((IOTA - 120) & 127)]; double fTemp305 = fVec5[((IOTA - 119) & 127)]; double fTemp306 = fVec5[((IOTA - 117) & 127)]; double fTemp307 = fVec5[((IOTA - 116) & 127)]; double fTemp308 = fVec5[((IOTA - 95) & 127)]; double fTemp309 = fVec5[((IOTA - 96) & 127)]; double fTemp310 = fVec5[((IOTA - 94) & 127)]; double fTemp311 = fVec5[((IOTA - 91) & 127)]; double fTemp312 = fVec5[((IOTA - 90) & 127)]; double fTemp313 = fVec5[((IOTA - 85) & 127)]; double fTemp314 = fVec5[((IOTA - 84) & 127)]; double fTemp315 = fVec5[((IOTA - 87) & 127)]; double fTemp316 = fVec5[((IOTA - 83) & 127)]; double fTemp317 = fVec5[((IOTA - 64) & 127)]; double fTemp318 = fVec5[((IOTA - 62) & 127)]; double fTemp319 = fVec5[((IOTA - 57) & 127)]; double fTemp320 = fVec5[((IOTA - 56) & 127)]; double fTemp321 = fVec5[((IOTA - 63) & 127)]; double fTemp322 = fVec5[((IOTA - 65) & 127)]; double fTemp323 = fVec5[((IOTA - 52) & 127)]; double fTemp324 = fVec5[((IOTA - 51) & 127)]; double fTemp325 = fVec5[((IOTA - 53) & 127)]; double fTemp326 = fVec5[((IOTA - 55) & 127)]; double fTemp327 = fVec5[((IOTA - 54) & 127)]; double fTemp328 = fVec5[((IOTA - 43) & 127)]; double fTemp329 = fVec5[((IOTA - 49) & 127)]; double fTemp330 = fVec5[((IOTA - 48) & 127)]; double fTemp331 = fVec5[((IOTA - 42) & 127)]; double fTemp332 = fVec5[((IOTA - 39) & 127)]; double fTemp333 = fVec5[((IOTA - 37) & 127)]; double fTemp334 = fVec5[((IOTA - 36) & 127)]; double fTemp335 = fVec5[((IOTA - 33) & 127)]; double fTemp336 = fVec5[((IOTA - 34) & 127)]; double fTemp337 = fVec5[((IOTA - 38) & 127)]; double fTemp338 = fVec5[((IOTA - 29) & 127)]; double fTemp339 = fVec5[((IOTA - 26) & 127)]; double fTemp340 = fVec5[((IOTA - 23) & 127)]; double fTemp341 = fVec5[((IOTA - 22) & 127)]; double fTemp342 = fVec5[((IOTA - 45) & 127)]; double fTemp343 = fVec5[((IOTA - 44) & 127)]; double fTemp344 = (fSlow11 * (double(input2[i]) * fRec3[0])); fRec10[0] = std::max<double>((fRec10[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp344)))))); fVbargraph7 = FAUSTFLOAT(fRec10[0]); fVec7[(IOTA & 127)] = fTemp344; double fTemp345 = fVec7[((IOTA - 122) & 127)]; double fTemp346 = fVec7[((IOTA - 121) & 127)]; double fTemp347 = fVec7[((IOTA - 119) & 127)]; double fTemp348 = fVec7[((IOTA - 120) & 127)]; double fTemp349 = fVec7[((IOTA - 118) & 127)]; double fTemp350 = fVec7[((IOTA - 116) & 127)]; double fTemp351 = fVec7[((IOTA - 117) & 127)]; double fTemp352 = fVec7[((IOTA - 125) & 127)]; double fTemp353 = fVec7[((IOTA - 98) & 127)]; double fTemp354 = fVec7[((IOTA - 97) & 127)]; double fTemp355 = fVec7[((IOTA - 94) & 127)]; double fTemp356 = fVec7[((IOTA - 93) & 127)]; double fTemp357 = fVec7[((IOTA - 90) & 127)]; double fTemp358 = fVec7[((IOTA - 92) & 127)]; double fTemp359 = fVec7[((IOTA - 89) & 127)]; double fTemp360 = fVec7[((IOTA - 88) & 127)]; double fTemp361 = fVec7[((IOTA - 87) & 127)]; double fTemp362 = fVec7[((IOTA - 86) & 127)]; double fTemp363 = fVec7[((IOTA - 85) & 127)]; double fTemp364 = fVec7[((IOTA - 77) & 127)]; double fTemp365 = fVec7[((IOTA - 78) & 127)]; double fTemp366 = fVec7[((IOTA - 75) & 127)]; double fTemp367 = fVec7[((IOTA - 84) & 127)]; double fTemp368 = fVec7[((IOTA - 62) & 127)]; double fTemp369 = fVec7[((IOTA - 63) & 127)]; double fTemp370 = fVec7[((IOTA - 58) & 127)]; double fTemp371 = fVec7[((IOTA - 60) & 127)]; double fTemp372 = fVec7[((IOTA - 59) & 127)]; double fTemp373 = fVec7[((IOTA - 83) & 127)]; double fTemp374 = fVec7[((IOTA - 54) & 127)]; double fTemp375 = fVec7[((IOTA - 52) & 127)]; double fTemp376 = fVec7[((IOTA - 48) & 127)]; double fTemp377 = fVec7[((IOTA - 47) & 127)]; double fTemp378 = fVec7[((IOTA - 53) & 127)]; double fTemp379 = fVec7[((IOTA - 50) & 127)]; double fTemp380 = fVec7[((IOTA - 51) & 127)]; double fTemp381 = fVec7[((IOTA - 45) & 127)]; double fTemp382 = fVec7[((IOTA - 42) & 127)]; double fTemp383 = fVec7[((IOTA - 46) & 127)]; double fTemp384 = fVec7[((IOTA - 44) & 127)]; double fTemp385 = fVec7[((IOTA - 40) & 127)]; double fTemp386 = fVec7[((IOTA - 39) & 127)]; double fTemp387 = fVec7[((IOTA - 41) & 127)]; double fTemp388 = fVec7[((IOTA - 33) & 127)]; double fTemp389 = fVec7[((IOTA - 36) & 127)]; double fTemp390 = fVec7[((IOTA - 35) & 127)]; double fTemp391 = fVec7[((IOTA - 32) & 127)]; double fTemp392 = fVec7[((IOTA - 29) & 127)]; double fTemp393 = fVec7[((IOTA - 28) & 127)]; double fTemp394 = fVec7[((IOTA - 24) & 127)]; double fTemp395 = fVec7[((IOTA - 26) & 127)]; double fTemp396 = fVec7[((IOTA - 21) & 127)]; double fTemp397 = fVec7[((IOTA - 20) & 127)]; double fTemp398 = fVec7[((IOTA - 17) & 127)]; double fTemp399 = fVec7[((IOTA - 14) & 127)]; double fTemp400 = fVec7[((IOTA - 13) & 127)]; double fTemp401 = fVec7[((IOTA - 8) & 127)]; double fTemp402 = fVec7[((IOTA - 5) & 127)]; double fTemp403 = fVec7[((IOTA - 4) & 127)]; double fTemp404 = fVec7[((IOTA - 2) & 127)]; double fTemp405 = fVec7[((IOTA - 1) & 127)]; double fTemp406 = fVec6[((IOTA - 114) & 127)]; double fTemp407 = fVec6[((IOTA - 105) & 127)]; double fTemp408 = fVec6[((IOTA - 103) & 127)]; double fTemp409 = fVec6[((IOTA - 102) & 127)]; double fTemp410 = fVec6[((IOTA - 104) & 127)]; double fTemp411 = fVec6[((IOTA - 98) & 127)]; double fTemp412 = fVec6[((IOTA - 95) & 127)]; double fTemp413 = fVec6[((IOTA - 92) & 127)]; double fTemp414 = fVec6[((IOTA - 90) & 127)]; double fTemp415 = fVec6[((IOTA - 101) & 127)]; double fTemp416 = fVec6[((IOTA - 100) & 127)]; double fTemp417 = fVec6[((IOTA - 88) & 127)]; double fTemp418 = fVec6[((IOTA - 87) & 127)]; double fTemp419 = fVec6[((IOTA - 86) & 127)]; double fTemp420 = fVec6[((IOTA - 85) & 127)]; double fTemp421 = fVec6[((IOTA - 97) & 127)]; double fTemp422 = fVec6[((IOTA - 84) & 127)]; double fTemp423 = fVec6[((IOTA - 83) & 127)]; double fTemp424 = fVec6[((IOTA - 94) & 127)]; double fTemp425 = fVec6[((IOTA - 80) & 127)]; double fTemp426 = fVec6[((IOTA - 79) & 127)]; double fTemp427 = fVec6[((IOTA - 77) & 127)]; double fTemp428 = fVec6[((IOTA - 89) & 127)]; double fTemp429 = fVec6[((IOTA - 96) & 127)]; double fTemp430 = fVec6[((IOTA - 82) & 127)]; double fTemp431 = fVec6[((IOTA - 93) & 127)]; double fTemp432 = (fSlow12 * (double(input0[i]) * fRec3[0])); fRec11[0] = std::max<double>((fRec11[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp432)))))); fVbargraph8 = FAUSTFLOAT(fRec11[0]); fVec8[(IOTA & 127)] = fTemp432; double fTemp433 = fVec8[((IOTA - 125) & 127)]; double fTemp434 = fVec8[((IOTA - 121) & 127)]; double fTemp435 = fVec8[((IOTA - 124) & 127)]; double fTemp436 = fVec8[((IOTA - 119) & 127)]; double fTemp437 = fVec8[((IOTA - 120) & 127)]; double fTemp438 = fVec8[((IOTA - 122) & 127)]; double fTemp439 = fVec8[((IOTA - 118) & 127)]; double fTemp440 = fVec8[((IOTA - 111) & 127)]; double fTemp441 = fVec8[((IOTA - 113) & 127)]; double fTemp442 = fVec8[((IOTA - 109) & 127)]; double fTemp443 = fVec8[((IOTA - 110) & 127)]; double fTemp444 = fVec8[((IOTA - 112) & 127)]; double fTemp445 = fVec8[((IOTA - 114) & 127)]; double fTemp446 = fVec8[((IOTA - 108) & 127)]; double fTemp447 = fVec8[((IOTA - 105) & 127)]; double fTemp448 = fVec8[((IOTA - 104) & 127)]; double fTemp449 = fVec8[((IOTA - 102) & 127)]; double fTemp450 = fVec8[((IOTA - 103) & 127)]; double fTemp451 = fVec8[((IOTA - 98) & 127)]; double fTemp452 = fVec8[((IOTA - 100) & 127)]; double fTemp453 = fVec8[((IOTA - 101) & 127)]; double fTemp454 = fVec8[((IOTA - 96) & 127)]; double fTemp455 = fVec8[((IOTA - 95) & 127)]; double fTemp456 = fVec8[((IOTA - 93) & 127)]; double fTemp457 = fVec8[((IOTA - 94) & 127)]; double fTemp458 = fVec8[((IOTA - 99) & 127)]; double fTemp459 = fVec8[((IOTA - 87) & 127)]; double fTemp460 = fVec8[((IOTA - 85) & 127)]; double fTemp461 = fVec8[((IOTA - 86) & 127)]; double fTemp462 = fVec8[((IOTA - 90) & 127)]; double fTemp463 = fVec8[((IOTA - 76) & 127)]; double fTemp464 = fVec8[((IOTA - 82) & 127)]; double fTemp465 = fVec8[((IOTA - 83) & 127)]; double fTemp466 = fVec8[((IOTA - 75) & 127)]; double fTemp467 = fVec8[((IOTA - 72) & 127)]; double fTemp468 = fVec8[((IOTA - 74) & 127)]; double fTemp469 = fVec8[((IOTA - 71) & 127)]; double fTemp470 = fVec8[((IOTA - 73) & 127)]; double fTemp471 = fVec8[((IOTA - 70) & 127)]; double fTemp472 = fVec8[((IOTA - 69) & 127)]; double fTemp473 = fVec8[((IOTA - 68) & 127)]; double fTemp474 = fVec8[((IOTA - 67) & 127)]; double fTemp475 = fVec8[((IOTA - 66) & 127)]; double fTemp476 = fVec8[((IOTA - 65) & 127)]; double fTemp477 = fVec8[((IOTA - 64) & 127)]; double fTemp478 = fVec8[((IOTA - 62) & 127)]; double fTemp479 = fVec8[((IOTA - 63) & 127)]; double fTemp480 = fVec8[((IOTA - 61) & 127)]; double fTemp481 = fVec8[((IOTA - 60) & 127)]; double fTemp482 = fVec8[((IOTA - 59) & 127)]; double fTemp483 = fVec8[((IOTA - 55) & 127)]; double fTemp484 = fVec8[((IOTA - 56) & 127)]; double fTemp485 = fVec8[((IOTA - 54) & 127)]; double fTemp486 = fVec8[((IOTA - 53) & 127)]; double fTemp487 = fVec8[((IOTA - 52) & 127)]; double fTemp488 = fVec8[((IOTA - 44) & 127)]; double fTemp489 = fVec8[((IOTA - 45) & 127)]; double fTemp490 = fVec8[((IOTA - 43) & 127)]; double fTemp491 = fVec8[((IOTA - 42) & 127)]; double fTemp492 = fVec8[((IOTA - 41) & 127)]; double fTemp493 = fVec8[((IOTA - 40) & 127)]; double fTemp494 = fVec8[((IOTA - 39) & 127)]; double fTemp495 = fVec8[((IOTA - 38) & 127)]; double fTemp496 = fVec8[((IOTA - 29) & 127)]; double fTemp497 = fVec8[((IOTA - 30) & 127)]; double fTemp498 = fVec8[((IOTA - 25) & 127)]; double fTemp499 = fVec8[((IOTA - 27) & 127)]; double fTemp500 = fVec8[((IOTA - 26) & 127)]; double fTemp501 = fVec8[((IOTA - 23) & 127)]; double fTemp502 = fVec8[((IOTA - 22) & 127)]; double fTemp503 = fVec8[((IOTA - 21) & 127)]; double fTemp504 = fVec8[((IOTA - 20) & 127)]; double fTemp505 = fVec8[((IOTA - 19) & 127)]; double fTemp506 = fVec8[((IOTA - 18) & 127)]; double fTemp507 = fVec8[((IOTA - 16) & 127)]; double fTemp508 = fVec8[((IOTA - 17) & 127)]; double fTemp509 = fVec8[((IOTA - 15) & 127)]; double fTemp510 = fVec8[((IOTA - 14) & 127)]; double fTemp511 = fVec3[((IOTA - 84) & 127)]; double fTemp512 = fVec3[((IOTA - 101) & 127)]; double fTemp513 = fVec3[((IOTA - 100) & 127)]; double fTemp514 = fVec3[((IOTA - 119) & 127)]; double fTemp515 = fVec3[((IOTA - 54) & 127)]; double fTemp516 = fVec3[((IOTA - 49) & 127)]; double fTemp517 = fVec3[((IOTA - 47) & 127)]; double fTemp518 = fVec3[((IOTA - 48) & 127)]; double fTemp519 = fVec3[((IOTA - 45) & 127)]; double fTemp520 = fVec3[((IOTA - 51) & 127)]; double fTemp521 = fVec3[((IOTA - 52) & 127)]; double fTemp522 = fVec3[((IOTA - 42) & 127)]; double fTemp523 = fVec4[((IOTA - 120) & 127)]; double fTemp524 = fVec4[((IOTA - 121) & 127)]; double fTemp525 = fVec4[((IOTA - 67) & 127)]; double fTemp526 = fVec4[((IOTA - 66) & 127)]; double fTemp527 = fVec4[((IOTA - 68) & 127)]; double fTemp528 = fVec5[((IOTA - 20) & 127)]; double fTemp529 = fVec5[((IOTA - 18) & 127)]; double fTemp530 = fVec5[((IOTA - 17) & 127)]; double fTemp531 = fVec5[((IOTA - 16) & 127)]; double fTemp532 = fVec5[((IOTA - 15) & 127)]; double fTemp533 = fVec5[((IOTA - 13) & 127)]; double fTemp534 = fVec5[((IOTA - 10) & 127)]; double fTemp535 = fVec5[((IOTA - 8) & 127)]; double fTemp536 = fVec5[((IOTA - 6) & 127)]; double fTemp537 = fVec5[((IOTA - 4) & 127)]; double fTemp538 = fVec5[((IOTA - 2) & 127)]; double fTemp539 = fVec5[((IOTA - 1) & 127)]; double fTemp540 = fVec6[((IOTA - 78) & 127)]; double fTemp541 = fVec7[((IOTA - 80) & 127)]; double fTemp542 = fVec7[((IOTA - 79) & 127)]; double fTemp543 = fVec6[((IOTA - 73) & 127)]; double fTemp544 = fVec6[((IOTA - 72) & 127)]; double fTemp545 = fVec6[((IOTA - 71) & 127)]; double fTemp546 = fVec8[((IOTA - 80) & 127)]; double fTemp547 = fVec8[((IOTA - 126) & 127)]; double fTemp548 = fVec8[((IOTA - 123) & 127)]; double fTemp549 = fVec8[((IOTA - 79) & 127)]; double fTemp550 = fVec8[((IOTA - 78) & 127)]; double fTemp551 = fVec8[((IOTA - 77) & 127)]; double fTemp552 = fVec8[((IOTA - 48) & 127)]; double fTemp553 = fVec8[((IOTA - 49) & 127)]; double fTemp554 = fVec8[((IOTA - 46) & 127)]; double fTemp555 = fVec8[((IOTA - 13) & 127)]; double fTemp556 = fVec8[((IOTA - 12) & 127)]; double fTemp557 = fVec8[((IOTA - 11) & 127)]; double fTemp558 = fVec8[((IOTA - 10) & 127)]; double fTemp559 = fVec8[((IOTA - 9) & 127)]; double fTemp560 = fVec8[((IOTA - 8) & 127)]; double fTemp561 = fVec8[((IOTA - 7) & 127)]; double fTemp562 = fVec8[((IOTA - 6) & 127)]; double fTemp563 = fVec8[((IOTA - 5) & 127)]; double fTemp564 = fVec8[((IOTA - 4) & 127)]; double fTemp565 = fVec8[((IOTA - 3) & 127)]; double fTemp566 = fVec8[((IOTA - 1) & 127)]; double fTemp567 = fVec5[((IOTA - 122) & 127)]; double fTemp568 = fVec5[((IOTA - 30) & 127)]; double fTemp569 = fVec5[((IOTA - 115) & 127)]; double fTemp570 = fVec5[((IOTA - 86) & 127)]; double fTemp571 = fVec7[((IOTA - 124) & 127)]; double fTemp572 = fVec7[((IOTA - 123) & 127)]; double fTemp573 = fVec7[((IOTA - 126) & 127)]; double fTemp574 = fVec6[((IOTA - 107) & 127)]; double fTemp575 = fVec8[((IOTA - 117) & 127)]; double fTemp576 = fVec8[((IOTA - 116) & 127)]; double fTemp577 = fVec8[((IOTA - 50) & 127)]; double fTemp578 = fVec8[((IOTA - 51) & 127)]; double fTemp579 = fVec6[((IOTA - 22) & 127)]; double fTemp580 = fVec6[((IOTA - 19) & 127)]; double fTemp581 = fVec6[((IOTA - 20) & 127)]; double fTemp582 = fVec6[((IOTA - 21) & 127)]; double fTemp583 = fVec6[((IOTA - 17) & 127)]; double fTemp584 = fVec6[((IOTA - 18) & 127)]; double fTemp585 = fVec6[((IOTA - 16) & 127)]; double fTemp586 = fVec6[((IOTA - 15) & 127)]; double fTemp587 = fVec6[((IOTA - 13) & 127)]; double fTemp588 = fVec6[((IOTA - 14) & 127)]; double fTemp589 = fVec6[((IOTA - 11) & 127)]; double fTemp590 = fVec6[((IOTA - 12) & 127)]; double fTemp591 = fVec6[((IOTA - 9) & 127)]; double fTemp592 = fVec6[((IOTA - 7) & 127)]; double fTemp593 = fVec6[((IOTA - 5) & 127)]; double fTemp594 = fVec6[((IOTA - 4) & 127)]; double fTemp595 = fVec6[((IOTA - 3) & 127)]; double fTemp596 = fVec6[((IOTA - 1) & 127)]; double fTemp597 = fVec8[((IOTA - 107) & 127)]; double fTemp598 = fVec8[((IOTA - 106) & 127)]; double fTemp599 = fVec8[((IOTA - 115) & 127)]; double fTemp600 = fVec8[((IOTA - 58) & 127)]; double fTemp601 = fVec8[((IOTA - 57) & 127)]; double fTemp602 = fVec8[((IOTA - 37) & 127)]; double fTemp603 = fVec8[((IOTA - 35) & 127)]; double fTemp604 = fVec8[((IOTA - 36) & 127)]; double fTemp605 = fVec8[((IOTA - 34) & 127)]; double fTemp606 = fVec8[((IOTA - 33) & 127)]; double fTemp607 = fVec8[((IOTA - 32) & 127)]; double fTemp608 = fVec8[((IOTA - 31) & 127)]; double fTemp609 = fVec2[((IOTA - 39) & 127)]; double fTemp610 = fVec2[((IOTA - 37) & 127)]; double fTemp611 = fVec2[((IOTA - 36) & 127)]; double fTemp612 = fVec2[((IOTA - 32) & 127)]; double fTemp613 = fVec2[((IOTA - 33) & 127)]; double fTemp614 = fVec2[((IOTA - 29) & 127)]; double fTemp615 = fVec2[((IOTA - 30) & 127)]; double fTemp616 = fVec3[((IOTA - 65) & 127)]; double fTemp617 = fVec2[((IOTA - 28) & 127)]; double fTemp618 = fVec1[((IOTA - 112) & 127)]; double fTemp619 = fVec0[((IOTA - 22) & 127)]; double fTemp620 = fVec0[((IOTA - 125) & 127)]; double fTemp621 = fVec0[((IOTA - 116) & 127)]; double fTemp622 = fVec0[((IOTA - 124) & 127)]; double fTemp623 = fVec0[((IOTA - 123) & 127)]; double fTemp624 = fVec0[((IOTA - 111) & 127)]; double fTemp625 = fVec4[((IOTA - 109) & 127)]; double fTemp626 = fVec1[((IOTA - 78) & 127)]; double fTemp627 = fVec0[((IOTA - 112) & 127)]; double fTemp628 = fVec0[((IOTA - 101) & 127)]; double fTemp629 = fVec0[((IOTA - 100) & 127)]; double fTemp630 = fVec0[((IOTA - 115) & 127)]; double fTemp631 = fVec0[((IOTA - 114) & 127)]; double fTemp632 = fVec0[((IOTA - 99) & 127)]; double fTemp633 = fVec0[((IOTA - 98) & 127)]; double fTemp634 = fVec0[((IOTA - 85) & 127)]; double fTemp635 = fVec0[((IOTA - 73) & 127)]; double fTemp636 = fVec0[((IOTA - 63) & 127)]; double fTemp637 = fVec0[((IOTA - 62) & 127)]; double fTemp638 = fVec0[((IOTA - 59) & 127)]; double fTemp639 = fVec0[((IOTA - 61) & 127)]; double fTemp640 = fVec0[((IOTA - 54) & 127)]; double fTemp641 = fVec0[((IOTA - 55) & 127)]; double fTemp642 = fVec0[((IOTA - 56) & 127)]; double fTemp643 = fVec0[((IOTA - 58) & 127)]; double fTemp644 = fVec0[((IOTA - 57) & 127)]; double fTemp645 = fVec0[((IOTA - 60) & 127)]; double fTemp646 = fVec0[((IOTA - 52) & 127)]; double fTemp647 = fVec0[((IOTA - 51) & 127)]; double fTemp648 = fVec0[((IOTA - 50) & 127)]; double fTemp649 = fVec0[((IOTA - 39) & 127)]; double fTemp650 = fVec0[((IOTA - 40) & 127)]; double fTemp651 = fVec0[((IOTA - 41) & 127)]; double fTemp652 = fVec0[((IOTA - 37) & 127)]; double fTemp653 = fVec0[((IOTA - 36) & 127)]; double fTemp654 = fVec1[((IOTA - 123) & 127)]; double fTemp655 = fVec1[((IOTA - 115) & 127)]; double fTemp656 = fVec1[((IOTA - 114) & 127)]; double fTemp657 = fVec1[((IOTA - 113) & 127)]; double fTemp658 = fVec1[((IOTA - 95) & 127)]; double fTemp659 = fVec1[((IOTA - 109) & 127)]; double fTemp660 = fVec1[((IOTA - 80) & 127)]; double fTemp661 = fVec1[((IOTA - 81) & 127)]; double fTemp662 = fVec1[((IOTA - 79) & 127)]; double fTemp663 = fVec1[((IOTA - 75) & 127)]; double fTemp664 = fVec1[((IOTA - 74) & 127)]; double fTemp665 = fVec1[((IOTA - 73) & 127)]; double fTemp666 = fVec1[((IOTA - 69) & 127)]; double fTemp667 = fVec1[((IOTA - 60) & 127)]; double fTemp668 = fVec1[((IOTA - 49) & 127)]; double fTemp669 = fVec1[((IOTA - 48) & 127)]; double fTemp670 = fVec1[((IOTA - 47) & 127)]; double fTemp671 = fVec1[((IOTA - 46) & 127)]; double fTemp672 = fVec1[((IOTA - 45) & 127)]; double fTemp673 = fVec1[((IOTA - 43) & 127)]; double fTemp674 = fVec1[((IOTA - 40) & 127)]; double fTemp675 = fVec1[((IOTA - 42) & 127)]; double fTemp676 = fVec1[((IOTA - 39) & 127)]; double fTemp677 = fVec1[((IOTA - 34) & 127)]; double fTemp678 = fVec1[((IOTA - 33) & 127)]; double fTemp679 = fVec1[((IOTA - 30) & 127)]; double fTemp680 = fVec1[((IOTA - 27) & 127)]; double fTemp681 = fVec1[((IOTA - 28) & 127)]; double fTemp682 = fVec0[((IOTA - 119) & 127)]; double fTemp683 = fVec0[((IOTA - 97) & 127)]; double fTemp684 = fVec0[((IOTA - 93) & 127)]; double fTemp685 = fVec0[((IOTA - 90) & 127)]; double fTemp686 = fVec0[((IOTA - 92) & 127)]; double fTemp687 = fVec0[((IOTA - 78) & 127)]; double fTemp688 = fVec0[((IOTA - 83) & 127)]; double fTemp689 = fVec0[((IOTA - 82) & 127)]; double fTemp690 = fVec0[((IOTA - 89) & 127)]; double fTemp691 = fVec0[((IOTA - 88) & 127)]; double fTemp692 = fVec0[((IOTA - 44) & 127)]; double fTemp693 = fVec0[((IOTA - 43) & 127)]; double fTemp694 = fVec0[((IOTA - 31) & 127)]; double fTemp695 = fVec0[((IOTA - 21) & 127)]; double fTemp696 = fVec0[((IOTA - 17) & 127)]; double fTemp697 = fVec0[((IOTA - 16) & 127)]; double fTemp698 = fVec0[((IOTA - 15) & 127)]; double fTemp699 = fVec0[((IOTA - 14) & 127)]; double fTemp700 = fVec0[((IOTA - 13) & 127)]; double fTemp701 = fVec0[((IOTA - 12) & 127)]; double fTemp702 = fVec0[((IOTA - 11) & 127)]; double fTemp703 = fVec0[((IOTA - 9) & 127)]; double fTemp704 = fVec0[((IOTA - 7) & 127)]; double fTemp705 = fVec0[((IOTA - 5) & 127)]; double fTemp706 = fVec0[((IOTA - 3) & 127)]; double fTemp707 = fVec0[((IOTA - 1) & 127)]; double fTemp708 = fVec1[((IOTA - 118) & 127)]; double fTemp709 = fVec1[((IOTA - 83) & 127)]; double fTemp710 = fVec1[((IOTA - 88) & 127)]; double fTemp711 = fVec1[((IOTA - 84) & 127)]; double fTemp712 = fVec1[((IOTA - 82) & 127)]; double fTemp713 = fVec2[((IOTA - 117) & 127)]; double fTemp714 = fVec2[((IOTA - 116) & 127)]; double fTemp715 = fVec2[((IOTA - 95) & 127)]; double fTemp716 = fVec2[((IOTA - 23) & 127)]; double fTemp717 = fVec2[((IOTA - 27) & 127)]; double fTemp718 = fVec3[((IOTA - 117) & 127)]; double fTemp719 = fVec3[((IOTA - 118) & 127)]; double fTemp720 = fVec2[((IOTA - 89) & 127)]; double fTemp721 = fVec1[((IOTA - 24) & 127)]; double fTemp722 = fVec1[((IOTA - 23) & 127)]; double fTemp723 = fVec1[((IOTA - 22) & 127)]; double fTemp724 = fVec1[((IOTA - 21) & 127)]; double fTemp725 = fVec1[((IOTA - 20) & 127)]; double fTemp726 = fVec1[((IOTA - 17) & 127)]; double fTemp727 = fVec1[((IOTA - 16) & 127)]; double fTemp728 = fVec1[((IOTA - 14) & 127)]; double fTemp729 = fVec1[((IOTA - 13) & 127)]; double fTemp730 = fVec1[((IOTA - 8) & 127)]; double fTemp731 = fVec1[((IOTA - 1) & 127)]; double fTemp732 = fVec1[((IOTA - 5) & 127)]; double fTemp733 = fVec1[((IOTA - 4) & 127)]; double fTemp734 = fVec2[((IOTA - 124) & 127)]; double fTemp735 = fVec2[((IOTA - 122) & 127)]; double fTemp736 = fVec2[((IOTA - 120) & 127)]; double fTemp737 = fVec2[((IOTA - 123) & 127)]; double fTemp738 = fVec2[((IOTA - 113) & 127)]; double fTemp739 = fVec2[((IOTA - 114) & 127)]; double fTemp740 = fVec2[((IOTA - 103) & 127)]; double fTemp741 = fVec2[((IOTA - 111) & 127)]; double fTemp742 = fVec2[((IOTA - 112) & 127)]; double fTemp743 = fVec2[((IOTA - 121) & 127)]; double fTemp744 = fVec2[((IOTA - 85) & 127)]; double fTemp745 = fVec2[((IOTA - 81) & 127)]; double fTemp746 = fVec2[((IOTA - 78) & 127)]; double fTemp747 = fVec2[((IOTA - 80) & 127)]; double fTemp748 = fVec2[((IOTA - 86) & 127)]; double fTemp749 = fVec2[((IOTA - 77) & 127)]; double fTemp750 = fVec2[((IOTA - 76) & 127)]; double fTemp751 = fVec2[((IOTA - 73) & 127)]; double fTemp752 = fVec2[((IOTA - 74) & 127)]; double fTemp753 = fVec2[((IOTA - 68) & 127)]; double fTemp754 = fVec2[((IOTA - 67) & 127)]; double fTemp755 = fVec2[((IOTA - 62) & 127)]; double fTemp756 = fVec2[((IOTA - 59) & 127)]; double fTemp757 = fVec2[((IOTA - 61) & 127)]; double fTemp758 = fVec2[((IOTA - 58) & 127)]; double fTemp759 = fVec2[((IOTA - 69) & 127)]; double fTemp760 = fVec2[((IOTA - 57) & 127)]; double fTemp761 = fVec2[((IOTA - 54) & 127)]; double fTemp762 = fVec2[((IOTA - 55) & 127)]; double fTemp763 = fVec2[((IOTA - 56) & 127)]; double fTemp764 = fVec2[((IOTA - 51) & 127)]; double fTemp765 = fVec2[((IOTA - 50) & 127)]; double fTemp766 = fVec2[((IOTA - 53) & 127)]; double fTemp767 = fVec2[((IOTA - 47) & 127)]; double fTemp768 = fVec2[((IOTA - 49) & 127)]; double fTemp769 = fVec2[((IOTA - 48) & 127)]; double fTemp770 = fVec2[((IOTA - 46) & 127)]; double fTemp771 = fVec2[((IOTA - 45) & 127)]; double fTemp772 = fVec2[((IOTA - 44) & 127)]; double fTemp773 = fVec2[((IOTA - 43) & 127)]; double fTemp774 = fVec2[((IOTA - 42) & 127)]; double fTemp775 = fVec3[((IOTA - 122) & 127)]; double fTemp776 = fVec3[((IOTA - 121) & 127)]; double fTemp777 = fVec3[((IOTA - 112) & 127)]; double fTemp778 = fVec3[((IOTA - 111) & 127)]; double fTemp779 = fVec3[((IOTA - 120) & 127)]; double fTemp780 = fVec3[((IOTA - 79) & 127)]; double fTemp781 = fVec3[((IOTA - 81) & 127)]; double fTemp782 = fVec3[((IOTA - 82) & 127)]; double fTemp783 = fVec3[((IOTA - 80) & 127)]; double fTemp784 = fVec3[((IOTA - 70) & 127)]; double fTemp785 = fVec3[((IOTA - 69) & 127)]; double fTemp786 = fVec3[((IOTA - 63) & 127)]; double fTemp787 = fVec3[((IOTA - 61) & 127)]; double fTemp788 = fVec3[((IOTA - 68) & 127)]; double fTemp789 = fVec3[((IOTA - 62) & 127)]; double fTemp790 = fVec3[((IOTA - 34) & 127)]; double fTemp791 = fVec3[((IOTA - 30) & 127)]; double fTemp792 = fVec3[((IOTA - 31) & 127)]; double fTemp793 = fVec3[((IOTA - 27) & 127)]; double fTemp794 = fVec3[((IOTA - 26) & 127)]; double fTemp795 = fVec3[((IOTA - 25) & 127)]; double fTemp796 = fVec3[((IOTA - 19) & 127)]; double fTemp797 = fVec3[((IOTA - 18) & 127)]; double fTemp798 = fVec3[((IOTA - 16) & 127)]; double fTemp799 = fVec3[((IOTA - 15) & 127)]; double fTemp800 = fVec3[((IOTA - 12) & 127)]; double fTemp801 = fVec3[((IOTA - 11) & 127)]; double fTemp802 = fVec3[((IOTA - 9) & 127)]; double fTemp803 = fVec3[((IOTA - 7) & 127)]; double fTemp804 = fVec3[((IOTA - 3) & 127)]; double fTemp805 = fVec3[((IOTA - 37) & 127)]; double fTemp806 = fVec4[((IOTA - 118) & 127)]; double fTemp807 = fVec4[((IOTA - 115) & 127)]; double fTemp808 = fVec4[((IOTA - 100) & 127)]; double fTemp809 = fVec4[((IOTA - 99) & 127)]; double fTemp810 = fVec4[((IOTA - 102) & 127)]; double fTemp811 = fVec3[((IOTA - 59) & 127)]; double fTemp812 = fVec4[((IOTA - 96) & 127)]; double fTemp813 = fVec4[((IOTA - 88) & 127)]; double fTemp814 = fVec4[((IOTA - 89) & 127)]; double fTemp815 = fVec4[((IOTA - 85) & 127)]; double fTemp816 = fVec4[((IOTA - 90) & 127)]; double fTemp817 = fVec4[((IOTA - 76) & 127)]; double fTemp818 = fVec4[((IOTA - 84) & 127)]; double fTemp819 = fVec4[((IOTA - 82) & 127)]; double fTemp820 = fVec4[((IOTA - 103) & 127)]; double fTemp821 = fVec4[((IOTA - 64) & 127)]; double fTemp822 = fVec4[((IOTA - 73) & 127)]; double fTemp823 = fVec4[((IOTA - 63) & 127)]; double fTemp824 = fVec4[((IOTA - 60) & 127)]; double fTemp825 = fVec4[((IOTA - 47) & 127)]; double fTemp826 = fVec4[((IOTA - 46) & 127)]; double fTemp827 = fVec4[((IOTA - 43) & 127)]; double fTemp828 = fVec4[((IOTA - 41) & 127)]; double fTemp829 = fVec4[((IOTA - 34) & 127)]; double fTemp830 = fVec4[((IOTA - 32) & 127)]; double fTemp831 = fVec4[((IOTA - 33) & 127)]; double fTemp832 = fVec4[((IOTA - 29) & 127)]; double fTemp833 = fVec4[((IOTA - 27) & 127)]; double fTemp834 = fVec0[((IOTA - 108) & 127)]; double fTemp835 = fVec0[((IOTA - 107) & 127)]; double fTemp836 = fVec0[((IOTA - 105) & 127)]; double fTemp837 = fVec0[((IOTA - 102) & 127)]; double fTemp838 = fVec0[((IOTA - 87) & 127)]; double fTemp839 = fVec0[((IOTA - 80) & 127)]; double fTemp840 = fVec0[((IOTA - 48) & 127)]; double fTemp841 = fVec0[((IOTA - 47) & 127)]; double fTemp842 = fVec0[((IOTA - 46) & 127)]; double fTemp843 = fVec0[((IOTA - 35) & 127)]; double fTemp844 = fVec0[((IOTA - 45) & 127)]; double fTemp845 = fVec0[((IOTA - 32) & 127)]; double fTemp846 = fVec1[((IOTA - 122) & 127)]; double fTemp847 = fVec1[((IOTA - 96) & 127)]; double fTemp848 = fVec1[((IOTA - 90) & 127)]; double fTemp849 = fVec1[((IOTA - 89) & 127)]; double fTemp850 = fVec1[((IOTA - 65) & 127)]; double fTemp851 = fVec1[((IOTA - 87) & 127)]; double fTemp852 = fVec1[((IOTA - 53) & 127)]; double fTemp853 = fVec1[((IOTA - 37) & 127)]; double fTemp854 = fVec1[((IOTA - 52) & 127)]; double fTemp855 = fVec2[((IOTA - 17) & 127)]; double fTemp856 = fVec2[((IOTA - 16) & 127)]; double fTemp857 = fVec2[((IOTA - 15) & 127)]; double fTemp858 = fVec2[((IOTA - 14) & 127)]; double fTemp859 = fVec2[((IOTA - 13) & 127)]; double fTemp860 = fVec2[((IOTA - 12) & 127)]; double fTemp861 = fVec2[((IOTA - 11) & 127)]; double fTemp862 = fVec2[((IOTA - 9) & 127)]; double fTemp863 = fVec2[((IOTA - 7) & 127)]; double fTemp864 = fVec2[((IOTA - 5) & 127)]; double fTemp865 = fVec2[((IOTA - 4) & 127)]; double fTemp866 = fVec2[((IOTA - 3) & 127)]; double fTemp867 = fVec2[((IOTA - 1) & 127)]; double fTemp868 = fVec4[((IOTA - 122) & 127)]; double fTemp869 = fVec4[((IOTA - 91) & 127)]; double fTemp870 = fVec4[((IOTA - 81) & 127)]; double fTemp871 = fVec4[((IOTA - 80) & 127)]; double fTemp872 = fVec4[((IOTA - 77) & 127)]; double fTemp873 = fVec4[((IOTA - 79) & 127)]; double fTemp874 = fVec4[((IOTA - 54) & 127)]; double fTemp875 = fVec4[((IOTA - 51) & 127)]; double fTemp876 = fVec4[((IOTA - 55) & 127)]; double fTemp877 = fVec0[((IOTA - 118) & 127)]; double fTemp878 = fVec0[((IOTA - 113) & 127)]; double fTemp879 = fVec0[((IOTA - 109) & 127)]; double fTemp880 = fVec0[((IOTA - 106) & 127)]; double fTemp881 = fVec0[((IOTA - 84) & 127)]; double fTemp882 = fVec0[((IOTA - 81) & 127)]; double fTemp883 = fVec0[((IOTA - 25) & 127)]; double fTemp884 = fVec1[((IOTA - 124) & 127)]; double fTemp885 = fVec1[((IOTA - 120) & 127)]; double fTemp886 = fVec1[((IOTA - 92) & 127)]; double fTemp887 = fVec1[((IOTA - 91) & 127)]; double fTemp888 = fVec2[((IOTA - 125) & 127)]; double fTemp889 = fVec2[((IOTA - 115) & 127)]; double fTemp890 = fVec1[((IOTA - 119) & 127)]; double fTemp891 = fVec2[((IOTA - 96) & 127)]; double fTemp892 = fVec6[((IOTA - 48) & 127)]; double fTemp893 = fVec6[((IOTA - 47) & 127)]; double fTemp894 = fVec6[((IOTA - 46) & 127)]; double fTemp895 = fVec6[((IOTA - 45) & 127)]; double fTemp896 = fVec6[((IOTA - 42) & 127)]; double fTemp897 = fVec4[((IOTA - 5) & 127)]; double fTemp898 = fVec4[((IOTA - 3) & 127)]; double fTemp899 = fVec4[((IOTA - 23) & 127)]; double fTemp900 = fVec4[((IOTA - 24) & 127)]; double fTemp901 = fVec4[((IOTA - 22) & 127)]; double fTemp902 = fVec4[((IOTA - 21) & 127)]; double fTemp903 = fVec4[((IOTA - 20) & 127)]; double fTemp904 = fVec4[((IOTA - 19) & 127)]; double fTemp905 = fVec4[((IOTA - 14) & 127)]; double fTemp906 = fVec4[((IOTA - 12) & 127)]; double fTemp907 = fVec4[((IOTA - 11) & 127)]; double fTemp908 = fVec4[((IOTA - 9) & 127)]; double fTemp909 = fVec4[((IOTA - 7) & 127)]; double fTemp910 = fVec5[((IOTA - 124) & 127)]; double fTemp911 = fVec4[((IOTA - 28) & 127)]; double fTemp912 = fVec5[((IOTA - 118) & 127)]; double fTemp913 = fVec5[((IOTA - 114) & 127)]; double fTemp914 = fVec5[((IOTA - 113) & 127)]; double fTemp915 = fVec5[((IOTA - 111) & 127)]; double fTemp916 = fVec5[((IOTA - 107) & 127)]; double fTemp917 = fVec5[((IOTA - 106) & 127)]; double fTemp918 = fVec5[((IOTA - 104) & 127)]; double fTemp919 = fVec5[((IOTA - 103) & 127)]; double fTemp920 = fVec5[((IOTA - 102) & 127)]; double fTemp921 = fVec5[((IOTA - 100) & 127)]; double fTemp922 = fVec5[((IOTA - 101) & 127)]; double fTemp923 = fVec5[((IOTA - 98) & 127)]; double fTemp924 = fVec5[((IOTA - 92) & 127)]; double fTemp925 = fVec5[((IOTA - 93) & 127)]; double fTemp926 = fVec5[((IOTA - 99) & 127)]; double fTemp927 = fVec5[((IOTA - 97) & 127)]; double fTemp928 = fVec5[((IOTA - 105) & 127)]; double fTemp929 = fVec5[((IOTA - 109) & 127)]; double fTemp930 = fVec5[((IOTA - 108) & 127)]; double fTemp931 = fVec5[((IOTA - 88) & 127)]; double fTemp932 = fVec5[((IOTA - 81) & 127)]; double fTemp933 = fVec5[((IOTA - 80) & 127)]; double fTemp934 = fVec5[((IOTA - 82) & 127)]; double fTemp935 = fVec5[((IOTA - 76) & 127)]; double fTemp936 = fVec5[((IOTA - 75) & 127)]; double fTemp937 = fVec5[((IOTA - 79) & 127)]; double fTemp938 = fVec5[((IOTA - 78) & 127)]; double fTemp939 = fVec5[((IOTA - 77) & 127)]; double fTemp940 = fVec5[((IOTA - 68) & 127)]; double fTemp941 = fVec5[((IOTA - 74) & 127)]; double fTemp942 = fVec5[((IOTA - 66) & 127)]; double fTemp943 = fVec5[((IOTA - 61) & 127)]; double fTemp944 = fVec5[((IOTA - 67) & 127)]; double fTemp945 = fVec5[((IOTA - 73) & 127)]; double fTemp946 = fVec5[((IOTA - 59) & 127)]; double fTemp947 = fVec5[((IOTA - 58) & 127)]; double fTemp948 = fVec5[((IOTA - 60) & 127)]; double fTemp949 = fVec5[((IOTA - 41) & 127)]; double fTemp950 = fVec5[((IOTA - 40) & 127)]; double fTemp951 = fVec5[((IOTA - 47) & 127)]; double fTemp952 = fVec5[((IOTA - 35) & 127)]; double fTemp953 = fVec5[((IOTA - 32) & 127)]; double fTemp954 = fVec5[((IOTA - 28) & 127)]; double fTemp955 = fVec5[((IOTA - 27) & 127)]; double fTemp956 = fVec5[((IOTA - 25) & 127)]; double fTemp957 = fVec5[((IOTA - 24) & 127)]; double fTemp958 = fVec5[((IOTA - 50) & 127)]; double fTemp959 = fVec5[((IOTA - 46) & 127)]; double fTemp960 = fVec7[((IOTA - 115) & 127)]; double fTemp961 = fVec7[((IOTA - 114) & 127)]; double fTemp962 = fVec7[((IOTA - 113) & 127)]; double fTemp963 = fVec7[((IOTA - 110) & 127)]; double fTemp964 = fVec7[((IOTA - 106) & 127)]; double fTemp965 = fVec7[((IOTA - 103) & 127)]; double fTemp966 = fVec7[((IOTA - 105) & 127)]; double fTemp967 = fVec7[((IOTA - 104) & 127)]; double fTemp968 = fVec7[((IOTA - 101) & 127)]; double fTemp969 = fVec7[((IOTA - 99) & 127)]; double fTemp970 = fVec7[((IOTA - 96) & 127)]; double fTemp971 = fVec7[((IOTA - 95) & 127)]; double fTemp972 = fVec7[((IOTA - 91) & 127)]; double fTemp973 = fVec7[((IOTA - 102) & 127)]; double fTemp974 = fVec7[((IOTA - 107) & 127)]; double fTemp975 = fVec7[((IOTA - 111) & 127)]; double fTemp976 = fVec7[((IOTA - 100) & 127)]; double fTemp977 = fVec7[((IOTA - 74) & 127)]; double fTemp978 = fVec7[((IOTA - 73) & 127)]; double fTemp979 = fVec7[((IOTA - 76) & 127)]; double fTemp980 = fVec7[((IOTA - 71) & 127)]; double fTemp981 = fVec7[((IOTA - 70) & 127)]; double fTemp982 = fVec7[((IOTA - 69) & 127)]; double fTemp983 = fVec7[((IOTA - 72) & 127)]; double fTemp984 = fVec7[((IOTA - 65) & 127)]; double fTemp985 = fVec7[((IOTA - 66) & 127)]; double fTemp986 = fVec7[((IOTA - 64) & 127)]; double fTemp987 = fVec7[((IOTA - 61) & 127)]; double fTemp988 = fVec7[((IOTA - 68) & 127)]; double fTemp989 = fVec7[((IOTA - 67) & 127)]; double fTemp990 = fVec7[((IOTA - 57) & 127)]; double fTemp991 = fVec7[((IOTA - 55) & 127)]; double fTemp992 = fVec7[((IOTA - 56) & 127)]; double fTemp993 = fVec7[((IOTA - 49) & 127)]; double fTemp994 = fVec7[((IOTA - 43) & 127)]; double fTemp995 = fVec7[((IOTA - 38) & 127)]; double fTemp996 = fVec7[((IOTA - 37) & 127)]; double fTemp997 = fVec7[((IOTA - 34) & 127)]; double fTemp998 = fVec7[((IOTA - 31) & 127)]; double fTemp999 = fVec7[((IOTA - 30) & 127)]; double fTemp1000 = fVec7[((IOTA - 27) & 127)]; double fTemp1001 = fVec7[((IOTA - 25) & 127)]; double fTemp1002 = fVec7[((IOTA - 23) & 127)]; double fTemp1003 = fVec7[((IOTA - 22) & 127)]; double fTemp1004 = fVec7[((IOTA - 19) & 127)]; double fTemp1005 = fVec7[((IOTA - 18) & 127)]; double fTemp1006 = fVec7[((IOTA - 16) & 127)]; double fTemp1007 = fVec7[((IOTA - 15) & 127)]; double fTemp1008 = fVec7[((IOTA - 12) & 127)]; double fTemp1009 = fVec7[((IOTA - 11) & 127)]; double fTemp1010 = fVec7[((IOTA - 10) & 127)]; double fTemp1011 = fVec7[((IOTA - 9) & 127)]; double fTemp1012 = fVec7[((IOTA - 7) & 127)]; double fTemp1013 = fVec7[((IOTA - 6) & 127)]; double fTemp1014 = fVec7[((IOTA - 3) & 127)]; double fTemp1015 = fVec6[((IOTA - 123) & 127)]; double fTemp1016 = fVec6[((IOTA - 122) & 127)]; double fTemp1017 = fVec6[((IOTA - 121) & 127)]; double fTemp1018 = fVec6[((IOTA - 120) & 127)]; double fTemp1019 = fVec6[((IOTA - 116) & 127)]; double fTemp1020 = fVec6[((IOTA - 117) & 127)]; double fTemp1021 = fVec6[((IOTA - 112) & 127)]; double fTemp1022 = fVec6[((IOTA - 113) & 127)]; double fTemp1023 = fVec6[((IOTA - 111) & 127)]; double fTemp1024 = fVec6[((IOTA - 124) & 127)]; double fTemp1025 = fVec6[((IOTA - 119) & 127)]; double fTemp1026 = fVec6[((IOTA - 115) & 127)]; double fTemp1027 = fVec6[((IOTA - 109) & 127)]; double fTemp1028 = fVec6[((IOTA - 108) & 127)]; double fTemp1029 = fVec6[((IOTA - 118) & 127)]; double fTemp1030 = fVec6[((IOTA - 110) & 127)]; double fTemp1031 = fVec6[((IOTA - 106) & 127)]; double fTemp1032 = fVec6[((IOTA - 125) & 127)]; double fTemp1033 = fVec6[((IOTA - 81) & 127)]; double fTemp1034 = fVec6[((IOTA - 91) & 127)]; double fTemp1035 = fVec6[((IOTA - 76) & 127)]; double fTemp1036 = fVec6[((IOTA - 75) & 127)]; double fTemp1037 = fVec6[((IOTA - 67) & 127)]; double fTemp1038 = fVec6[((IOTA - 64) & 127)]; double fTemp1039 = fVec6[((IOTA - 63) & 127)]; double fTemp1040 = fVec6[((IOTA - 61) & 127)]; double fTemp1041 = fVec6[((IOTA - 56) & 127)]; double fTemp1042 = fVec6[((IOTA - 62) & 127)]; double fTemp1043 = fVec6[((IOTA - 55) & 127)]; double fTemp1044 = fVec6[((IOTA - 49) & 127)]; double fTemp1045 = fVec6[((IOTA - 50) & 127)]; double fTemp1046 = fVec6[((IOTA - 44) & 127)]; double fTemp1047 = fVec6[((IOTA - 51) & 127)]; double fTemp1048 = fVec6[((IOTA - 54) & 127)]; double fTemp1049 = fVec6[((IOTA - 53) & 127)]; double fTemp1050 = fVec6[((IOTA - 52) & 127)]; double fTemp1051 = fVec8[((IOTA - 92) & 127)]; double fTemp1052 = fVec8[((IOTA - 91) & 127)]; double fTemp1053 = fVec8[((IOTA - 84) & 127)]; double fTemp1054 = fVec8[((IOTA - 97) & 127)]; double fTemp1055 = fVec8[((IOTA - 28) & 127)]; double fTemp1056 = fVec8[((IOTA - 24) & 127)]; double fTemp1057 = fVec3[((IOTA - 57) & 127)]; double fTemp1058 = fVec3[((IOTA - 58) & 127)]; double fTemp1059 = fVec3[((IOTA - 56) & 127)]; double fTemp1060 = fVec3[((IOTA - 50) & 127)]; double fTemp1061 = fVec3[((IOTA - 53) & 127)]; double fTemp1062 = fVec3[((IOTA - 55) & 127)]; double fTemp1063 = fVec3[((IOTA - 46) & 127)]; double fTemp1064 = fVec3[((IOTA - 44) & 127)]; double fTemp1065 = fVec3[((IOTA - 43) & 127)]; double fTemp1066 = fVec3[((IOTA - 41) & 127)]; double fTemp1067 = fVec4[((IOTA - 72) & 127)]; double fTemp1068 = fVec4[((IOTA - 71) & 127)]; double fTemp1069 = fVec4[((IOTA - 70) & 127)]; double fTemp1070 = fVec4[((IOTA - 65) & 127)]; double fTemp1071 = fVec4[((IOTA - 69) & 127)]; double fTemp1072 = fVec5[((IOTA - 72) & 127)]; double fTemp1073 = fVec5[((IOTA - 71) & 127)]; double fTemp1074 = fVec5[((IOTA - 70) & 127)]; double fTemp1075 = fVec5[((IOTA - 69) & 127)]; double fTemp1076 = fVec5[((IOTA - 21) & 127)]; double fTemp1077 = fVec5[((IOTA - 19) & 127)]; double fTemp1078 = fVec5[((IOTA - 14) & 127)]; double fTemp1079 = fVec5[((IOTA - 12) & 127)]; double fTemp1080 = fVec5[((IOTA - 11) & 127)]; double fTemp1081 = fVec5[((IOTA - 9) & 127)]; double fTemp1082 = fVec5[((IOTA - 7) & 127)]; double fTemp1083 = fVec5[((IOTA - 5) & 127)]; double fTemp1084 = fVec5[((IOTA - 3) & 127)]; double fTemp1085 = fVec7[((IOTA - 81) & 127)]; double fTemp1086 = fVec7[((IOTA - 82) & 127)]; double fTemp1087 = fVec6[((IOTA - 70) & 127)]; double fTemp1088 = fVec6[((IOTA - 68) & 127)]; double fTemp1089 = fVec8[((IOTA - 81) & 127)]; double fTemp1090 = fVec8[((IOTA - 47) & 127)]; double fTemp1091 = fVec6[((IOTA - 69) & 127)]; double fTemp1092 = fVec8[((IOTA - 2) & 127)]; double fTemp1093 = fVec5[((IOTA - 110) & 127)]; double fTemp1094 = fVec5[((IOTA - 112) & 127)]; double fTemp1095 = fVec5[((IOTA - 89) & 127)]; double fTemp1096 = fVec5[((IOTA - 31) & 127)]; double fTemp1097 = fVec4[((IOTA - 53) & 127)]; double fTemp1098 = fVec7[((IOTA - 112) & 127)]; double fTemp1099 = fVec7[((IOTA - 109) & 127)]; double fTemp1100 = fVec7[((IOTA - 108) & 127)]; double fTemp1101 = fVec6[((IOTA - 126) & 127)]; double fTemp1102 = fVec6[((IOTA - 43) & 127)]; double fTemp1103 = fVec6[((IOTA - 60) & 127)]; double fTemp1104 = fVec6[((IOTA - 59) & 127)]; double fTemp1105 = fVec6[((IOTA - 58) & 127)]; double fTemp1106 = fVec6[((IOTA - 57) & 127)]; double fTemp1107 = fVec8[((IOTA - 88) & 127)]; double fTemp1108 = fVec8[((IOTA - 89) & 127)]; double fTemp1109 = fVec6[((IOTA - 41) & 127)]; double fTemp1110 = fVec6[((IOTA - 40) & 127)]; double fTemp1111 = fVec6[((IOTA - 39) & 127)]; double fTemp1112 = fVec6[((IOTA - 37) & 127)]; double fTemp1113 = fVec6[((IOTA - 36) & 127)]; double fTemp1114 = fVec6[((IOTA - 38) & 127)]; double fTemp1115 = fVec6[((IOTA - 32) & 127)]; double fTemp1116 = fVec6[((IOTA - 31) & 127)]; double fTemp1117 = fVec6[((IOTA - 30) & 127)]; double fTemp1118 = fVec6[((IOTA - 29) & 127)]; double fTemp1119 = fVec6[((IOTA - 28) & 127)]; double fTemp1120 = fVec6[((IOTA - 27) & 127)]; double fTemp1121 = fVec6[((IOTA - 33) & 127)]; double fTemp1122 = fVec6[((IOTA - 34) & 127)]; double fTemp1123 = fVec6[((IOTA - 35) & 127)]; double fTemp1124 = fVec6[((IOTA - 25) & 127)]; double fTemp1125 = fVec6[((IOTA - 24) & 127)]; double fTemp1126 = fVec6[((IOTA - 23) & 127)]; double fTemp1127 = fVec6[((IOTA - 26) & 127)]; double fTemp1128 = fVec6[((IOTA - 10) & 127)]; double fTemp1129 = fVec6[((IOTA - 8) & 127)]; double fTemp1130 = fVec6[((IOTA - 6) & 127)]; double fTemp1131 = fVec6[((IOTA - 2) & 127)]; double fTemp1132 = fVec6[((IOTA - 66) & 127)]; double fTemp1133 = fVec6[((IOTA - 65) & 127)]; double fTemp1134 = fVec6[((IOTA - 74) & 127)]; double fTemp1135 = fVec2[((IOTA - 41) & 127)]; double fTemp1136 = fVec2[((IOTA - 40) & 127)]; double fTemp1137 = fVec2[((IOTA - 34) & 127)]; double fTemp1138 = fVec2[((IOTA - 38) & 127)]; double fTemp1139 = fVec2[((IOTA - 35) & 127)]; double fTemp1140 = fVec2[((IOTA - 31) & 127)]; double fTemp1141 = fVec3[((IOTA - 66) & 127)]; double fTemp1142 = fVec0[((IOTA - 49) & 127)]; double fTemp1143 = (fRec1[0] * (((5.611290000000001e-05 * fTemp1) + ((0.000144938 * fTemp2) + ((0.00098582100000000001 * fTemp3) + ((0.0010638000000000002 * fTemp4) + ((0.0018535400000000001 * fTemp5) + ((0.0020713300000000001 * fTemp6) + ((0.00287405 * fTemp7) + ((0.00066612700000000008 * fTemp8) + ((0.00021471700000000001 * fTemp9) + ((0.0083305600000000007 * fTemp10) + ((2.773e-06 * fTemp12) + ((2.8457499999999998e-06 * fTemp13) + ((2.4558300000000005e-05 * fTemp14) + ((5.3135e-06 * fTemp15) + ((0.00024796200000000001 * fTemp16) + ((0.00014221200000000001 * fTemp17) + ((0.00028535700000000003 * fTemp18) + ((0.00070562000000000001 * fTemp19) + ((0.0005151 * fTemp20) + ((0.00124614 * fTemp21) + ((0.00032077100000000002 * fTemp22) + ((9.0654800000000018e-05 * fTemp23) + ((0.0022713 * fTemp24) + ((6.2936500000000003e-05 * fTemp25) + ((2.0687900000000002e-05 * fTemp26) + ((0.00221192 * fTemp27) + ((0.00074920100000000001 * fTemp28) + ((0.00066226100000000003 * fTemp29) + ((0.0036181899999999999 * fTemp30) + ((3.8066800000000006e-05 * fTemp31) + ((0.0022166500000000001 * fTemp32) + ((0.0021549399999999997 * fTemp33) + ((0.0013761300000000001 * fTemp34) + ((0.023527200000000002 * fTemp35) + ((0.0021948500000000004 * fTemp36) + ((0.00051807200000000006 * fTemp37) + ((0.024944000000000001 * fTemp38) + ((0.0035849099999999997 * fTemp39) + ((1.06705e-06 * fTemp40) + ((3.8319600000000005e-05 * fTemp41) + ((0.0031629900000000001 * fTemp42) + ((0.0011606799999999999 * fTemp43) + ((0.00078389600000000007 * fTemp44) + ((3.61728e-05 * fTemp45) + ((7.2644700000000013e-05 * fTemp46) + ((1.0278999999999999e-06 * fTemp47) + ((0.00053547700000000002 * fTemp48) + ((0.00078204200000000005 * fTemp49) + ((0.00089492 * fTemp50) + ((0.0054627 * fTemp51) + ((0.0053478500000000003 * fTemp52) + ((0.0036506200000000003 * fTemp53) + ((0.0039108500000000004 * fTemp54) + ((0.00124406 * fTemp55) + ((0.041771900000000008 * fTemp56) + ((0.055177400000000001 * fTemp57) + ((0.0108086 * fTemp58) + ((0.0026607500000000004 * fTemp59) + ((0.00066903899999999996 * fTemp60) + ((0.0013556799999999999 * fTemp61) + ((0.00012807300000000001 * fTemp62) + ((0.000378556 * fTemp63) + ((4.9495899999999995e-07 * fTemp64) + ((0.00025383300000000002 * fTemp65) + ((0.00035608600000000003 * fTemp66) + ((0.00034403800000000002 * fTemp67) + ((0.00071143700000000009 * fTemp68) + ((0.0014366699999999999 * fTemp69) + ((0.0045955500000000003 * fTemp70) + ((0.00058266999999999998 * fTemp72) + ((0.00082486899999999999 * fTemp73) + ((0.0011506799999999998 * fTemp74) + ((0.00010084700000000001 * fTemp75) + ((3.5632800000000002e-05 * fTemp76) + ((0.00034166200000000001 * fTemp77) + ((3.64663e-05 * fTemp78) + ((0.035996800000000002 * fTemp79) + ((2.0105900000000003e-05 * fTemp81) + ((0.0124978 * fTemp82) + ((0.00053009599999999997 * fTemp83) + ((0.0011330000000000001 * fTemp84) + ((0.0016271899999999999 * fTemp85) + ((0.00069229100000000004 * fTemp86) + ((0.00050674400000000005 * fTemp87) + ((0.00049718700000000006 * fTemp88) + ((0.023463500000000002 * fTemp89) + ((0.052758300000000001 * fTemp90) + ((0.00038071900000000001 * fTemp91) + ((0.0094331200000000014 * fTemp92) + ((0.011300600000000001 * fTemp93) + ((0.0071840999999999997 * fTemp94) + ((0.00027813700000000002 * fTemp95) + ((0.00027818999999999999 * fTemp96) + ((0.00022609 * fTemp97) + ((0.00033955200000000002 * fTemp98) + ((2.4972599999999999e-05 * fTemp99) + ((5.2352700000000004e-05 * fTemp100) + ((4.2462999999999995e-06 * fTemp11) + ((0.00016021500000000001 * fTemp101) + ((0.000240886 * fTemp102) + ((3.0215200000000005e-05 * fTemp103) + ((0.000204718 * fTemp104) + ((0.00033797299999999998 * fTemp105) + ((0.00013590400000000001 * fTemp106) + ((6.0929900000000008e-05 * fTemp107) + ((0.000208667 * fTemp108) + ((0.00030785900000000001 * fTemp109) + ((0.00026147399999999998 * fTemp110) + ((0.00048677700000000003 * fTemp111) + ((0.0012107800000000001 * fTemp112) + ((0.00045785700000000004 * fTemp113) + ((4.86084e-05 * fTemp114) + ((8.9630500000000016e-08 * fTemp115) + ((0.00056137899999999998 * fTemp116) + ((0.00076490500000000008 * fTemp117) + ((0.00015598000000000001 * fTemp118) + ((0.00076870700000000009 * fTemp119) + ((0.0014322200000000001 * fTemp120) + ((0.00064690400000000001 * fTemp121) + ((0.00046067700000000005 * fTemp122) + ((0.00271718 * fTemp123) + ((6.2586200000000001e-05 * fTemp124) + ((0.00117567 * fTemp125) + ((0.0012521400000000001 * fTemp126) + ((0.00055114699999999999 * fTemp127) + ((0.0016155 * fTemp128) + ((0.0019438999999999999 * fTemp129) + ((0.00122438 * fTemp130) + ((0.0021511500000000001 * fTemp131) + ((0.00110439 * fTemp132) + ((3.43292e-08 * fTemp133) + ((3.3588899999999999e-06 * fTemp134) + ((3.9804799999999997e-06 * fTemp135) + ((5.0789799999999999e-05 * fTemp136) + ((3.2623300000000003e-05 * fTemp137) + ((0.00026027500000000002 * fTemp138) + ((0.00040571999999999998 * fTemp139) + ((0.00020187200000000002 * fTemp140) + ((0.00084254300000000007 * fTemp141) + ((0.00156339 * fTemp142) + ((0.0034697200000000004 * fTemp143) + ((0.0030116200000000004 * fTemp144) + ((0.00075465500000000002 * fTemp145) + ((0.00068181600000000002 * fTemp146) + ((0.00071934100000000008 * fTemp147) + ((0.00040184499999999996 * fTemp148) + ((0.00055143000000000011 * fTemp149) + ((0.0016723300000000001 * fTemp150) + ((0.0017063 * fTemp151) + ((0.00020361699999999999 * fTemp152) + ((0.00030080800000000001 * fTemp153) + ((0.0026214800000000003 * fTemp154) + ((0.0034494400000000002 * fTemp155) + ((0.0014532900000000001 * fTemp156) + ((0.0011545000000000001 * fTemp157) + ((0.00061171300000000006 * fTemp158) + ((0.0013395900000000001 * fTemp159) + ((0.00020694100000000001 * fTemp160) + ((0.00127111 * fTemp161) + ((0.00064708400000000003 * fTemp162) + ((0.0010632999999999999 * fTemp163) + ((0.00058977500000000006 * fTemp164) + ((0.000609699 * fTemp165) + ((0.00150508 * fTemp166) + ((0.0014054500000000001 * fTemp167) + ((0.0060181399999999999 * fTemp168) + ((0.0038672100000000003 * fTemp169) + ((0.0049045500000000006 * fTemp170) + ((0.0091428700000000009 * fTemp171) + ((4.1971900000000004e-05 * fTemp172) + ((0.0099856200000000006 * fTemp173) + ((0.010922899999999999 * fTemp174) + ((0.0016006100000000001 * fTemp175) + ((0.0013328999999999999 * fTemp176) + ((0.013603000000000001 * fTemp177) + ((0.0099153599999999998 * fTemp178) + ((0.016723499999999999 * fTemp179) + ((0.045127499999999994 * fTemp180) + ((0.0027371000000000001 * fTemp181) + ((0.0059659600000000002 * fTemp182) + ((4.6184399999999998e-05 * fTemp183) + ((0.0025209700000000004 * fTemp184) + ((0.00036855699999999999 * fTemp185) + ((0.00070276500000000005 * fTemp186) + ((0.00090358699999999997 * fTemp187) + ((0.000231406 * fTemp188) + ((4.4178200000000003e-05 * fTemp189) + ((1.57811e-05 * fTemp80) + ((0.0047945900000000005 * fTemp190) + ((8.2140799999999984e-06 * fTemp192) + ((0.0029068700000000002 * fTemp193) + ((3.8470500000000004e-05 * fTemp194) + ((9.096330000000001e-05 * fTemp195) + ((0.000227166 * fTemp196) + ((6.1820100000000001e-06 * fTemp197) + ((8.7317000000000004e-05 * fTemp198) + ((8.2866000000000002e-05 * fTemp199) + ((0.00014514899999999999 * fTemp200) + ((8.3273200000000014e-05 * fTemp201) + ((5.2586900000000003e-05 * fTemp202) + ((0.00036701000000000003 * fTemp203) + ((0.00010655300000000001 * fTemp204) + ((0.00050770799999999994 * fTemp205) + ((2.5137800000000002e-07 * fTemp206) + ((3.82797e-06 * fTemp207) + ((0.00025426099999999998 * fTemp208) + ((0.00018379600000000001 * fTemp209) + ((0.00035138200000000002 * fTemp210) + ((0.00063264199999999999 * fTemp211) + ((7.6149300000000013e-05 * fTemp212) + ((0.00086251900000000007 * fTemp213) + ((0.0019024199999999999 * fTemp214) + ((0.0013118799999999999 * fTemp215) + ((0.00129144 * fTemp216) + ((0.0015575400000000001 * fTemp217) + ((0.00020428199999999999 * fTemp218) + ((0.0011614100000000001 * fTemp219) + ((0.0020513699999999998 * fTemp220) + ((0.0016051100000000001 * fTemp221) + ((0.00196889 * fTemp222) + ((0.0079808199999999996 * fTemp223) + ((0.0044432300000000003 * fTemp224) + ((0.0013145500000000001 * fTemp225) + ((0.000208879 * fTemp226) + ((9.226730000000001e-05 * fTemp227) + ((0.0053043999999999999 * fTemp228) + ((0.0053560100000000005 * fTemp229) + ((0.00291413 * fTemp230) + ((0.010230900000000001 * fTemp231) + ((0.0073240200000000005 * fTemp232) + ((0.0073238899999999996 * fTemp233) + ((0.0105234 * fTemp234) + ((4.8748200000000002e-05 * fTemp235) + ((0.018119700000000002 * fTemp236) + ((0.0016041499999999999 * fTemp237) + ((2.7286800000000004e-05 * fTemp238) + ((0.00127749 * fTemp239) + ((0.00070097300000000003 * fTemp240) + ((0.0014662800000000001 * fTemp241) + ((0.0025716599999999999 * fTemp242) + ((0.0027539400000000003 * fTemp243) + ((0.000547636 * fTemp244) + ((0.00020467599999999999 * fTemp245) + ((0.0028814800000000001 * fTemp246) + ((0.0034324300000000002 * fTemp247) + ((0.0030387000000000001 * fTemp248) + ((0.002183 * fTemp249) + ((0.021556799999999997 * fTemp250) + ((0.0018844000000000001 * fTemp251) + ((0.013752100000000001 * fTemp252) + ((0.0448946 * fTemp253) + ((0.00033159299999999998 * fTemp254) + ((0.00255288 * fTemp255) + ((0.00094661300000000001 * fTemp256) + ((0.0010133200000000001 * fTemp257) + ((0.00025746299999999998 * fTemp258) + ((2.1185900000000001e-06 * fTemp259) + ((0.00014839199999999998 * fTemp260) + ((0.00047882000000000003 * fTemp261) + ((0.00147938 * fTemp262) + ((0.00013115699999999999 * fTemp263) + ((0.0011073599999999999 * fTemp264) + ((1.70273e-06 * fTemp266) + ((0.00050519600000000007 * fTemp267) + ((0.0016339300000000002 * fTemp268) + ((8.0341699999999997e-06 * fTemp269) + ((4.3469500000000001e-05 * fTemp270) + ((0.0022532999999999997 * fTemp271) + ((0.0024114399999999999 * fTemp272) + ((0.0048108300000000003 * fTemp273) + ((0.036438700000000004 * fTemp274) + ((0.027385400000000001 * fTemp275) + ((0.040978300000000002 * fTemp276) + ((0.038770699999999998 * fTemp277) + ((0.10758200000000001 * fTemp278) + ((0.049985600000000005 * fTemp279) + (((0.00010309 * fTemp280) + ((0.00018337600000000001 * fTemp281) + ((0.00108661 * fTemp282) + ((0.00040080500000000001 * fTemp283) + ((0.0025276200000000004 * fTemp284) + ((0.0005591420000000001 * fTemp285) + ((0.00045614100000000008 * fTemp287) + ((0.00160801 * fTemp288) + ((0.00084856599999999993 * fTemp289) + ((0.00020222799999999999 * fTemp290) + ((2.0016700000000001e-05 * fTemp291) + ((1.4622100000000002e-05 * fTemp191) + ((0.031673199999999999 * fTemp292) + ((0.0274497 * fTemp293) + ((0.0030908899999999998 * fTemp294) + ((0.0103427 * fTemp295) + ((0.0120915 * fTemp296) + ((0.0038904299999999998 * fTemp297) + ((0.0024724199999999999 * fTemp298) + ((0.0012886100000000001 * fTemp299) + ((0.000101833 * fTemp300) + ((2.4533100000000001e-06 * fTemp301) + ((0.0034125200000000005 * fTemp302) + ((0.0069197900000000003 * fTemp303) + ((0.000105639 * fTemp304) + ((3.9296600000000006e-05 * fTemp305) + ((3.85491e-05 * fTemp306) + ((0.00018456300000000003 * fTemp307) + ((0.0031713800000000001 * fTemp308) + ((0.0019589099999999999 * fTemp309) + ((0.00068253400000000005 * fTemp310) + ((0.00056285600000000003 * fTemp311) + ((0.0014036900000000002 * fTemp312) + ((0.0015441700000000001 * fTemp313) + ((0.00036768800000000002 * fTemp314) + ((0.00337025 * fTemp315) + ((0.00069545300000000007 * fTemp316) + ((0.00113331 * fTemp317) + ((0.00070883900000000006 * fTemp318) + ((0.0020663499999999998 * fTemp319) + ((0.00288332 * fTemp320) + ((0.0014698599999999999 * fTemp321) + ((0.0010311999999999999 * fTemp322) + ((0.0012247 * fTemp323) + ((0.00117636 * fTemp324) + ((0.0016634199999999999 * fTemp325) + ((0.0008817050000000001 * fTemp326) + ((0.0035919900000000002 * fTemp327) + ((0.0033690899999999999 * fTemp328) + ((0.0053477200000000003 * fTemp329) + ((0.00571347 * fTemp330) + ((0.0081425600000000001 * fTemp331) + ((0.0048383499999999999 * fTemp332) + ((0.0011593500000000002 * fTemp333) + ((0.00341282 * fTemp334) + ((0.0060068300000000003 * fTemp335) + ((0.0053672899999999994 * fTemp336) + ((1.73416e-05 * fTemp337) + ((0.0096774400000000007 * fTemp338) + ((0.03066 * fTemp339) + ((0.0019489700000000002 * fTemp340) + ((9.4065400000000002e-05 * fTemp341) + ((0.0068109299999999998 * fTemp342) + ((0.00503769 * fTemp343) + ((2.4375700000000001e-05 * fTemp345) + ((8.0066800000000004e-05 * fTemp346) + ((9.0816700000000014e-05 * fTemp347) + ((9.9426100000000014e-05 * fTemp348) + ((5.80835e-05 * fTemp349) + ((9.5024799999999997e-07 * fTemp350) + ((7.7452699999999998e-05 * fTemp351) + ((8.464169999999999e-06 * fTemp352) + ((5.1149400000000002e-05 * fTemp353) + ((0.00032476299999999999 * fTemp354) + ((0.0012872900000000002 * fTemp355) + ((0.0022912900000000001 * fTemp356) + ((0.0019518999999999999 * fTemp357) + ((0.00119739 * fTemp358) + ((0.0043689900000000005 * fTemp359) + ((0.00375801 * fTemp360) + ((0.0016994499999999999 * fTemp361) + ((0.0032713800000000004 * fTemp362) + ((0.0036832600000000003 * fTemp363) + ((0.00028545500000000005 * fTemp364) + ((0.0020680200000000003 * fTemp365) + ((0.00025900400000000002 * fTemp366) + ((0.00089328000000000009 * fTemp367) + ((0.0016691100000000001 * fTemp368) + ((3.3718100000000005e-05 * fTemp369) + ((0.00099548200000000001 * fTemp370) + ((0.00089519800000000015 * fTemp371) + ((0.00079125400000000002 * fTemp372) + ((0.00072158200000000002 * fTemp373) + ((0.0024358800000000001 * fTemp374) + ((0.0027909200000000001 * fTemp375) + ((0.0042173100000000002 * fTemp376) + ((0.0091871399999999999 * fTemp377) + ((0.0056765999999999995 * fTemp378) + ((0.0016214599999999999 * fTemp379) + ((0.00077908600000000012 * fTemp380) + ((0.0021427500000000001 * fTemp381) + ((0.0028589500000000003 * fTemp382) + ((0.0013077200000000001 * fTemp383) + ((0.0022329500000000005 * fTemp384) + ((0.0053105900000000004 * fTemp385) + ((0.0030150300000000001 * fTemp386) + ((0.0070971000000000003 * fTemp387) + ((0.0037660800000000002 * fTemp388) + ((0.00053429399999999994 * fTemp389) + ((0.0164669 * fTemp390) + ((0.0086483100000000011 * fTemp391) + ((0.021576300000000003 * fTemp392) + ((0.021685099999999999 * fTemp393) + ((0.0057622799999999998 * fTemp394) + ((0.0057969700000000002 * fTemp395) + ((0.0197594 * fTemp396) + ((0.0121098 * fTemp397) + ((0.032535399999999999 * fTemp398) + ((0.00050339700000000005 * fTemp399) + ((0.00086802899999999998 * fTemp400) + ((0.0016583500000000001 * fTemp401) + ((0.00031507000000000003 * fTemp402) + ((0.00049461800000000005 * fTemp403) + ((0.00015840400000000001 * fTemp404) + ((2.8519800000000004e-05 * fTemp405) + ((4.4578800000000004e-06 * fTemp344) + ((1.1796500000000001e-05 * fTemp406) + ((5.3605900000000008e-05 * fTemp407) + ((0.00047704000000000008 * fTemp408) + ((0.00043236800000000009 * fTemp409) + ((0.00046969700000000004 * fTemp410) + ((0.00092227100000000001 * fTemp411) + ((0.0013659500000000001 * fTemp412) + ((0.00108099 * fTemp413) + ((6.7984800000000007e-05 * fTemp414) + ((0.00070973900000000003 * fTemp415) + ((0.000705385 * fTemp416) + ((0.00045975200000000007 * fTemp417) + ((0.0013345100000000001 * fTemp418) + ((0.0013671599999999999 * fTemp419) + ((0.00088433700000000001 * fTemp420) + ((0.00081300600000000002 * fTemp421) + ((0.0010498400000000002 * fTemp422) + ((0.00300031 * fTemp423) + ((0.00214314 * fTemp424) + ((2.3648600000000003e-05 * fTemp425) + ((0.00058793100000000009 * fTemp426) + ((0.0017765299999999999 * fTemp427) + ((0.000264467 * fTemp428) + ((0.000623519 * fTemp429) + ((0.00033132700000000002 * fTemp430) + ((0.0016777999999999999 * fTemp431) + ((5.0813899999999995e-06 * fTemp433) + ((4.2541300000000006e-05 * fTemp434) + ((5.7126099999999992e-06 * fTemp435) + ((0.00016404399999999999 * fTemp436) + ((0.00010654600000000001 * fTemp437) + ((1.8717900000000003e-05 * fTemp438) + ((0.00016872499999999999 * fTemp439) + ((0.00067625599999999997 * fTemp440) + ((0.00053358400000000003 * fTemp441) + ((0.00083451500000000008 * fTemp442) + ((0.00098166300000000002 * fTemp443) + ((0.00050102000000000002 * fTemp444) + ((0.00054736599999999998 * fTemp445) + ((0.0009436510000000001 * fTemp446) + ((0.0014059200000000002 * fTemp447) + ((0.0012065399999999999 * fTemp448) + ((0.00154024 * fTemp449) + ((0.00185348 * fTemp450) + ((0.00058470199999999999 * fTemp451) + ((0.00050683400000000006 * fTemp452) + ((0.00087727600000000008 * fTemp453) + ((0.00054874000000000004 * fTemp454) + ((0.00272945 * fTemp455) + ((2.3955000000000004e-05 * fTemp456) + ((0.0021461499999999999 * fTemp457) + ((0.00061282500000000011 * fTemp458) + ((0.0037083100000000003 * fTemp459) + ((0.0016799500000000001 * fTemp460) + ((0.0051757600000000006 * fTemp461) + ((0.00041329900000000006 * fTemp462) + ((0.0041945800000000007 * fTemp463) + ((0.00056369199999999997 * fTemp464) + ((0.0015701700000000001 * fTemp465) + ((0.0063743100000000002 * fTemp466) + ((0.0052356299999999998 * fTemp467) + ((0.0029129100000000003 * fTemp468) + ((0.0032107500000000001 * fTemp469) + ((0.0030868900000000001 * fTemp470) + ((0.00185049 * fTemp471) + ((0.0014647 * fTemp472) + ((0.0022559300000000002 * fTemp473) + ((0.0034284599999999999 * fTemp474) + ((0.0023089200000000003 * fTemp475) + ((0.0027403499999999999 * fTemp476) + ((0.0042152999999999999 * fTemp477) + ((0.0068040700000000006 * fTemp478) + ((0.0062385100000000001 * fTemp479) + ((0.0035775299999999998 * fTemp480) + ((0.0042250600000000001 * fTemp481) + ((0.0031211899999999998 * fTemp482) + ((0.0012461600000000001 * fTemp483) + ((0.0012118500000000002 * fTemp484) + ((0.00305273 * fTemp485) + ((0.00325793 * fTemp486) + ((0.0028833999999999999 * fTemp487) + ((0.0079248200000000008 * fTemp488) + ((0.015005800000000001 * fTemp489) + ((0.0028857800000000001 * fTemp490) + ((0.0074329900000000004 * fTemp491) + ((0.0056945699999999995 * fTemp492) + ((0.0064973000000000001 * fTemp493) + ((0.011589100000000001 * fTemp494) + ((0.0069301900000000001 * fTemp495) + ((0.0087064099999999995 * fTemp496) + ((0.0266261 * fTemp497) + ((0.031746299999999998 * fTemp498) + ((0.030624600000000002 * fTemp499) + ((0.0528391 * fTemp500) + ((0.021260899999999999 * fTemp501) + ((0.096895100000000012 * fTemp502) + ((0.057809200000000005 * fTemp503) + ((0.06596840000000001 * fTemp504) + ((0.055772500000000003 * fTemp505) + ((0.034514800000000005 * fTemp506) + ((0.059606500000000007 * fTemp507) + ((0.073495100000000008 * fTemp508) + ((0.064749100000000004 * fTemp509) + ((0.0449074 * fTemp510) + ((0.0025590399999999998 * fTemp511) + ((0.00046662400000000006 * fTemp512) + ((0.00069381500000000008 * fTemp513) + ((7.7608600000000008e-05 * fTemp514) + ((0.00215198 * fTemp515) + ((0.000292148 * fTemp516) + ((0.00055458199999999997 * fTemp517) + ((0.00356967 * fTemp518) + ((0.0018462400000000001 * fTemp519) + ((0.0017431900000000001 * fTemp520) + ((0.000219724 * fTemp521) + ((0.0038023500000000003 * fTemp522) + ((3.8722400000000007e-05 * fTemp523) + ((2.7248300000000001e-05 * fTemp524) + ((0.0026238199999999998 * fTemp525) + ((8.7116700000000006e-05 * fTemp526) + ((0.0014712700000000002 * fTemp527) + ((0.000702438 * fTemp528) + ((0.0174746 * fTemp529) + ((0.021190899999999999 * fTemp530) + ((0.0025345699999999999 * fTemp531) + ((0.0025992000000000003 * fTemp532) + ((0.0061892400000000004 * fTemp533) + ((0.0020100199999999999 * fTemp534) + ((0.00148817 * fTemp535) + ((0.00053443399999999997 * fTemp536) + ((0.00069470999999999997 * fTemp537) + ((0.00013874000000000002 * fTemp538) + ((2.49699e-05 * fTemp539) + ((9.9362800000000004e-06 * fTemp265) + ((0.0027816299999999998 * fTemp540) + ((0.00038337700000000001 * fTemp541) + ((0.0016079900000000001 * fTemp542) + ((0.00046795000000000002 * fTemp543) + ((0.0016152100000000002 * fTemp544) + ((0.00010376700000000001 * fTemp545) + ((0.0024365300000000001 * fTemp546) + ((2.0625300000000001e-06 * fTemp547) + ((2.09787e-05 * fTemp548) + ((0.0041905200000000005 * fTemp549) + ((0.0024405 * fTemp550) + ((0.00082847699999999999 * fTemp551) + ((0.00306785 * fTemp552) + ((0.00175234 * fTemp553) + ((0.00250454 * fTemp554) + ((0.049342300000000006 * fTemp555) + ((0.056510400000000002 * fTemp556) + ((0.0036302599999999997 * fTemp557) + ((0.00050879500000000004 * fTemp558) + ((0.0011589199999999999 * fTemp559) + ((0.00024957099999999997 * fTemp560) + ((0.0018634200000000002 * fTemp561) + ((0.00014117900000000001 * fTemp562) + ((0.00076772799999999997 * fTemp563) + ((0.00059949000000000005 * fTemp564) + ((0.00096838400000000008 * fTemp565) + ((0.00012370799999999999 * fTemp566) + ((2.5118200000000003e-05 * fTemp432) + ((3.8827600000000008e-05 * fTemp567) + ((0.036282299999999996 * fTemp568) + ((0.000184012 * fTemp569) + ((0.0052786200000000004 * fTemp570) + ((8.8836499999999992e-06 * fTemp571) + ((8.7967399999999994e-06 * fTemp572) + ((2.4082099999999999e-06 * fTemp573) + ((0.00041981599999999999 * fTemp574) + ((0.00025855300000000002 * fTemp575) + ((0.00034160000000000001 * fTemp576) + ((0.00086377000000000014 * fTemp577) + ((0.0036652500000000001 * fTemp578) + ((0.058508199999999996 * fTemp579) + ((0.0214629 * fTemp580) + ((0.041341200000000002 * fTemp581) + ((0.050635700000000006 * fTemp582) + ((0.088954799999999987 * fTemp583) + ((0.029345699999999999 * fTemp584) + ((0.063658400000000004 * fTemp585) + ((0.078143400000000002 * fTemp586) + ((0.077131900000000003 * fTemp587) + ((0.060886200000000001 * fTemp588) + ((0.0054581200000000003 * fTemp589) + ((0.090551499999999993 * fTemp590) + ((0.0018110400000000001 * fTemp591) + ((0.00194177 * fTemp592) + ((0.00114689 * fTemp593) + ((0.00058690300000000006 * fTemp594) + ((0.0012299100000000001 * fTemp595) + ((0.00015469 * fTemp596) + ((3.3955100000000003e-05 * fTemp286) + ((0.0012923000000000001 * fTemp597) + ((0.00136699 * fTemp598) + ((0.00045382400000000002 * fTemp599) + ((0.0036129299999999999 * fTemp600) + ((0.0050028199999999998 * fTemp601) + ((0.0079812000000000008 * fTemp602) + ((0.0044680700000000002 * fTemp603) + ((0.0141227 * fTemp604) + ((0.020023599999999999 * fTemp605) + ((0.023001999999999998 * fTemp606) + ((0.0057082499999999998 * fTemp607) + ((0.011366300000000001 * fTemp608) + (((0.0070393900000000004 * fTemp609) + ((0.0048936500000000003 * fTemp610) + ((0.0095701499999999995 * fTemp611) + ((0.011886499999999999 * fTemp612) + ((0.015800600000000001 * fTemp613) + ((0.024750999999999999 * fTemp614) + ((0.0058739299999999994 * fTemp615) + ((8.8419900000000004e-05 * fTemp616) + (0.0086730599999999998 * fTemp617))))))))) + (5.2591200000000006e-05 * fTemp618))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) + (0.021392099999999997 * fTemp619)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) - ((2.1103299999999999e-06 * fTemp620) + ((1.9649999999999998e-06 * fTemp621) + ((5.5217400000000003e-06 * fTemp622) + ((3.11789e-06 * fTemp623) + ((0.00016924900000000001 * fTemp624) + ((0.00014172800000000001 * (fTemp625 - fTemp626)) + ((0.00016311100000000002 * fTemp627) + ((0.000138245 * fTemp628) + ((0.000478309 * fTemp629) + ((0.00021442500000000002 * fTemp630) + ((0.00030905200000000004 * fTemp631) + ((0.00091847499999999998 * fTemp632) + ((0.0013005599999999999 * fTemp633) + ((0.0010940099999999999 * fTemp634) + ((0.00026133000000000005 * fTemp635) + ((0.0020077300000000001 * fTemp636) + ((0.0032089100000000001 * fTemp637) + ((0.0044288800000000005 * fTemp638) + ((0.0010079800000000001 * fTemp639) + ((0.00761051 * fTemp640) + ((0.0075612199999999996 * fTemp641) + ((0.00277838 * fTemp642) + ((0.0047678900000000003 * fTemp643) + ((0.0024688500000000003 * fTemp644) + ((0.00063087099999999997 * fTemp645) + ((0.0018776900000000002 * fTemp646) + ((0.0082384199999999998 * fTemp647) + ((0.0050166199999999994 * fTemp648) + ((0.0028042699999999998 * fTemp649) + ((0.0249734 * fTemp650) + ((0.0102805 * fTemp651) + ((0.0112762 * fTemp652) + ((0.0070063399999999998 * fTemp653) + ((9.6015999999999997e-06 * fTemp654) + ((0.00016569499999999999 * fTemp655) + ((0.000131304 * fTemp656) + ((7.4421400000000012e-05 * fTemp657) + ((0.0015964400000000002 * fTemp658) + ((9.0750500000000005e-05 * fTemp659) + ((0.0023870700000000003 * fTemp660) + ((0.0018691199999999999 * fTemp661) + ((0.0014690600000000001 * fTemp662) + ((0.00020293100000000003 * fTemp663) + ((0.00042256999999999999 * fTemp664) + ((4.8196899999999999e-05 * fTemp665) + ((0.00081876599999999996 * fTemp666) + ((0.0012919000000000001 * fTemp667) + ((0.00164123 * fTemp668) + ((0.0035543000000000003 * fTemp669) + ((0.0019447000000000002 * fTemp670) + ((0.0045421799999999998 * fTemp671) + ((0.0032057800000000001 * fTemp672) + ((0.0098560599999999998 * fTemp673) + ((0.0039102499999999997 * fTemp674) + ((0.0055212400000000002 * fTemp675) + ((0.0014029000000000001 * fTemp676) + ((0.015326500000000002 * fTemp677) + ((0.0039000900000000002 * fTemp678) + ((0.0107983 * fTemp679) + ((0.0115642 * fTemp680) + ((0.0016720200000000002 * fTemp681) + ((9.0368300000000007e-05 * fTemp682) + ((0.00113754 * fTemp683) + ((0.0026714199999999999 * fTemp684) + ((0.00024966300000000001 * fTemp685) + ((0.0021342599999999998 * fTemp686) + ((0.00060378299999999999 * fTemp687) + ((0.00040582000000000004 * fTemp688) + ((0.00225807 * fTemp689) + ((0.0023507699999999999 * fTemp690) + ((0.0046170200000000003 * fTemp691) + ((0.015667299999999999 * fTemp692) + ((0.0121152 * fTemp693) + ((0.0031788599999999999 * fTemp694) + ((0.014456700000000001 * fTemp695) + ((0.043969699999999994 * fTemp696) + ((0.010103500000000001 * fTemp697) + ((0.026084999999999997 * fTemp698) + ((0.040577500000000002 * fTemp699) + ((0.0703236 * fTemp700) + ((0.086424600000000004 * fTemp701) + ((0.00526349 * fTemp702) + ((0.0021171000000000002 * fTemp703) + ((0.00027211800000000001 * fTemp704) + ((0.00074305500000000006 * fTemp705) + ((0.00070165199999999998 * fTemp706) + ((7.2115300000000004e-05 * fTemp707) + ((1.68655e-05 * fTemp0) + ((9.8288800000000007e-05 * fTemp708) + ((0.00119961 * fTemp709) + ((0.0011488700000000002 * fTemp710) + ((0.0028610799999999998 * fTemp711) + ((0.0011123800000000001 * fTemp712) + ((0.00013187999999999999 * fTemp713) + ((9.0214000000000001e-05 * fTemp714) + ((0.00048376700000000002 * fTemp715) + ((0.0128167 * fTemp716) + ((0.0026388100000000001 * fTemp717) + ((8.3314900000000018e-05 * fTemp718) + ((1.03751e-05 * fTemp719) + ((0.00040982500000000005 * fTemp720) + ((0.0083424600000000012 * fTemp721) + ((0.0016058699999999999 * fTemp722) + ((0.00574575 * fTemp723) + ((0.0048227900000000004 * fTemp724) + ((0.0053663600000000006 * fTemp725) + ((0.0110708 * fTemp726) + ((0.0074311999999999998 * fTemp727) + ((0.00037238400000000002 * fTemp728) + ((0.00252045 * fTemp729) + ((0.00052853700000000004 * fTemp730) + ((2.8269799999999997e-06 * fTemp731) + ((0.00017706000000000002 * fTemp732) + ((0.00017067000000000002 * fTemp733) + ((4.1155299999999994e-06 * fTemp734) + ((2.8368800000000002e-05 * fTemp735) + ((4.5063100000000006e-05 * fTemp736) + ((8.4151000000000001e-06 * fTemp737) + ((0.00012787900000000001 * fTemp738) + ((0.00010922300000000001 * fTemp739) + ((0.00014129499999999999 * fTemp740) + ((8.4602100000000008e-05 * fTemp741) + ((0.00010810400000000001 * fTemp742) + ((6.1171800000000003e-05 * fTemp743) + ((0.00102436 * fTemp744) + ((0.00100778 * fTemp745) + ((0.00108387 * fTemp746) + ((0.00035581800000000004 * fTemp747) + ((0.00192194 * fTemp748) + ((0.00355741 * fTemp749) + ((0.00203951 * fTemp750) + ((0.0044921400000000004 * fTemp751) + ((0.00099792900000000005 * fTemp752) + ((0.0026953699999999999 * fTemp753) + ((0.00069267700000000005 * fTemp754) + ((0.0014122200000000001 * fTemp755) + ((0.00053443700000000002 * fTemp756) + ((0.00059297400000000002 * fTemp757) + ((0.0013940900000000002 * fTemp758) + ((0.00086068200000000009 * fTemp759) + ((0.0012833600000000001 * fTemp760) + ((0.0050443700000000003 * fTemp761) + ((0.0050713199999999998 * fTemp762) + ((0.0031110899999999999 * fTemp763) + ((0.0032877399999999999 * fTemp764) + ((0.00909628 * fTemp765) + ((0.00419002 * fTemp766) + ((0.0073180300000000005 * fTemp767) + ((0.0036924600000000003 * fTemp768) + ((0.0046017100000000002 * fTemp769) + ((0.0070144200000000004 * fTemp770) + ((0.0020962000000000003 * fTemp771) + ((0.0052343400000000005 * fTemp772) + ((0.0071723899999999998 * fTemp773) + ((0.0036162899999999999 * fTemp774) + ((1.70851e-05 * fTemp775) + ((3.0657300000000002e-05 * fTemp776) + ((9.1851000000000012e-05 * fTemp777) + ((2.7205700000000003e-05 * fTemp778) + ((5.3340699999999993e-07 * fTemp779) + ((0.00062551900000000005 * fTemp780) + ((0.0032921200000000004 * fTemp781) + ((0.00152143 * fTemp782) + ((0.00193753 * fTemp783) + ((0.00096127300000000012 * fTemp784) + ((0.0042903999999999998 * fTemp785) + ((0.00047510500000000003 * fTemp786) + ((0.0013881099999999999 * fTemp787) + ((0.0037726500000000002 * fTemp788) + ((0.0017495700000000002 * fTemp789) + ((0.0095376600000000016 * fTemp790) + ((0.0099954400000000013 * fTemp791) + ((0.00354222 * fTemp792) + ((0.00581921 * fTemp793) + ((0.00064315100000000001 * fTemp794) + ((0.016502200000000002 * fTemp795) + ((0.026153100000000002 * fTemp796) + ((0.015518799999999999 * fTemp797) + ((0.011748099999999999 * fTemp798) + ((0.024044800000000002 * fTemp799) + ((0.011073200000000002 * fTemp800) + ((0.00016208700000000002 * fTemp801) + ((0.00023927800000000002 * fTemp802) + ((0.00099840900000000002 * fTemp803) + ((0.00026075800000000004 * fTemp804) + ((0.0017748 * fTemp805) + ((1.9893500000000002e-05 * fTemp806) + ((3.7877500000000005e-05 * fTemp807) + ((0.00031515600000000003 * fTemp808) + ((0.00068420899999999997 * fTemp809) + ((0.00044415800000000005 * fTemp810) + ((0.00142376 * fTemp811) + ((0.00049268100000000002 * fTemp812) + ((0.00166752 * fTemp813) + ((0.00127253 * fTemp814) + ((0.00033490500000000003 * fTemp815) + ((0.0017284399999999999 * fTemp816) + ((0.0014551499999999999 * fTemp817) + ((0.0011273899999999998 * fTemp818) + ((6.2119200000000007e-05 * fTemp819) + ((0.00027007400000000003 * fTemp820) + ((0.0019003900000000001 * fTemp821) + ((0.00078290800000000002 * fTemp822) + ((5.8659000000000002e-05 * fTemp823) + ((0.00034302399999999999 * fTemp824) + ((0.0030454200000000001 * fTemp825) + ((0.0010344 * fTemp826) + ((0.0021753000000000002 * fTemp827) + ((0.00241033 * fTemp828) + ((0.0054447699999999998 * fTemp829) + ((0.00192986 * fTemp830) + ((0.0027451799999999998 * fTemp831) + ((0.0050891900000000004 * fTemp832) + ((0.0039649200000000002 * fTemp833) + ((0.00053920599999999997 * fTemp834) + ((0.00034291200000000001 * fTemp835) + ((0.00023320700000000001 * fTemp836) + ((0.00041387999999999999 * fTemp837) + ((0.0013482500000000001 * fTemp838) + ((0.000120611 * fTemp839) + ((0.0040625900000000005 * fTemp840) + ((0.011856999999999999 * fTemp841) + ((0.0091953899999999995 * fTemp842) + ((0.0037140800000000002 * fTemp843) + ((0.0061361499999999999 * fTemp844) + ((0.0077227400000000005 * fTemp845) + ((2.6161300000000003e-05 * fTemp846) + ((0.00081881900000000014 * fTemp847) + ((0.00050415000000000008 * fTemp848) + ((0.00041316100000000005 * fTemp849) + ((0.00116132 * fTemp850) + ((0.0011271300000000001 * fTemp851) + ((0.0018522 * fTemp852) + ((0.00081971100000000009 * fTemp853) + ((0.0040265300000000004 * fTemp854) + ((0.011590800000000002 * fTemp855) + ((0.0038800599999999998 * fTemp856) + ((0.022263399999999999 * fTemp857) + ((0.020153300000000002 * fTemp858) + ((0.042437800000000005 * fTemp859) + ((0.047133599999999998 * fTemp860) + ((0.00567696 * fTemp861) + ((0.00143681 * fTemp862) + ((0.00086101400000000001 * fTemp863) + ((0.00058492199999999998 * fTemp864) + ((6.7829099999999997e-06 * fTemp865) + ((0.00025529600000000002 * fTemp866) + ((2.9285600000000003e-05 * fTemp867) + ((3.8661599999999993e-06 * fTemp71) + ((9.0296599999999999e-06 * fTemp868) + ((0.0015305800000000001 * fTemp869) + ((0.0017261400000000001 * fTemp870) + ((0.00048162000000000004 * fTemp871) + ((1.14088e-05 * fTemp872) + ((0.00071563500000000006 * fTemp873) + ((0.0038506399999999998 * fTemp874) + ((0.00191281 * fTemp875) + ((0.0015042599999999999 * fTemp876) + ((0.00011532 * fTemp877) + ((4.7581900000000006e-05 * fTemp878) + ((3.0118399999999995e-06 * fTemp879) + ((0.00026214100000000002 * fTemp880) + ((0.0017591500000000001 * fTemp881) + ((0.00237535 * fTemp882) + ((0.0055445599999999996 * fTemp883) + ((6.8184199999999995e-06 * fTemp884) + ((7.66841e-06 * fTemp885) + ((3.5872199999999999e-05 * fTemp886) + ((0.0020068299999999998 * fTemp887) + ((3.5305499999999996e-06 * fTemp888) + ((4.5684500000000006e-05 * fTemp889) + ((9.9956200000000017e-05 * fTemp890) + ((0.0011713800000000001 * fTemp891) + ((0.016606200000000002 * fTemp892) + ((0.016194200000000002 * fTemp893) + ((0.0116756 * fTemp894) + ((0.008875280000000001 * fTemp895) + ((0.022184499999999999 * fTemp896) + ((0.00091979399999999993 * fTemp897) + ((0.00050699800000000004 * fTemp898) + ((0.010792999999999999 * fTemp899) + ((0.014927200000000002 * fTemp900) + ((0.008510160000000001 * fTemp901) + ((0.0223719 * fTemp902) + ((0.0123166 * fTemp903) + ((0.017947399999999999 * fTemp904) + ((0.0073694100000000007 * fTemp905) + ((0.0142655 * fTemp906) + ((0.0067548000000000009 * fTemp907) + ((0.0025108100000000005 * fTemp908) + ((0.00235191 * fTemp909) + ((6.9716599999999994e-06 * fTemp910) + ((0.010143899999999999 * fTemp911) + ((9.8485200000000004e-06 * fTemp912) + ((0.00010357900000000001 * fTemp913) + ((0.00042897299999999997 * fTemp914) + ((9.8297200000000012e-05 * fTemp915) + ((0.00056389100000000007 * fTemp916) + ((0.00051816800000000006 * fTemp917) + ((0.00088825400000000011 * fTemp918) + ((0.000446193 * fTemp919) + ((0.00071199100000000003 * fTemp920) + ((0.0012435300000000001 * fTemp921) + ((0.0012468500000000001 * fTemp922) + ((0.00170268 * fTemp923) + ((0.0020163799999999999 * fTemp924) + ((0.0013548899999999999 * fTemp925) + ((0.0010388900000000002 * fTemp926) + ((0.00126004 * fTemp927) + ((0.00065456900000000003 * fTemp928) + ((0.00054109500000000001 * fTemp929) + ((0.00083962700000000002 * fTemp930) + ((0.00142103 * fTemp931) + ((0.0030592000000000002 * fTemp932) + ((0.00082976100000000015 * fTemp933) + ((0.0020040399999999999 * fTemp934) + ((0.0019008400000000002 * fTemp935) + ((0.00032308700000000001 * fTemp936) + ((0.00083032800000000008 * fTemp937) + ((0.00146794 * fTemp938) + ((0.0029912300000000001 * fTemp939) + ((4.5241600000000004e-05 * fTemp940) + ((0.00121188 * fTemp941) + ((0.00103439 * fTemp942) + ((0.00025587599999999999 * fTemp943) + ((0.00193403 * fTemp944) + ((0.0015286800000000001 * fTemp945) + ((0.000502175 * fTemp946) + ((0.00055048599999999999 * fTemp947) + ((0.0014905299999999999 * fTemp948) + ((0.0030320900000000003 * fTemp949) + ((0.0076587399999999998 * fTemp950) + ((0.0029968600000000001 * fTemp951) + ((0.010064699999999999 * fTemp952) + ((0.030136699999999999 * fTemp953) + ((0.039170099999999999 * fTemp954) + ((0.00031563800000000003 * fTemp955) + ((0.00069887100000000011 * fTemp956) + ((0.025458500000000002 * fTemp957) + ((0.00049892100000000004 * fTemp958) + ((0.0024887899999999998 * fTemp959) + ((6.574880000000001e-05 * fTemp960) + ((7.5893800000000015e-05 * fTemp961) + ((0.00055035400000000008 * fTemp962) + ((0.00038355300000000002 * fTemp963) + ((0.00064190699999999994 * fTemp964) + ((0.00096466700000000011 * fTemp965) + ((0.0012643700000000001 * fTemp966) + ((0.0014951399999999998 * fTemp967) + ((0.0013151 * fTemp968) + ((0.00147963 * fTemp969) + ((0.0012132899999999999 * fTemp970) + ((0.0010497099999999999 * fTemp971) + ((5.4447799999999994e-06 * fTemp972) + ((0.00062200899999999997 * fTemp973) + ((0.00026040700000000004 * fTemp974) + ((0.00038862600000000004 * fTemp975) + ((0.00155276 * fTemp976) + ((0.00031511100000000003 * fTemp977) + ((0.0011385200000000001 * fTemp978) + ((4.1098800000000007e-05 * fTemp979) + ((0.00191902 * fTemp980) + ((0.00073584900000000001 * fTemp981) + ((0.0033698500000000002 * fTemp982) + ((0.0023925600000000002 * fTemp983) + ((0.00177024 * fTemp984) + ((0.0015381499999999998 * fTemp985) + ((0.0027169400000000002 * fTemp986) + ((0.0011334100000000001 * fTemp987) + ((0.0046562499999999998 * fTemp988) + ((0.0026088700000000001 * fTemp989) + ((0.0012374899999999999 * fTemp990) + ((0.00029472900000000003 * fTemp991) + ((0.00350462 * fTemp992) + ((0.00161133 * fTemp993) + ((0.0043256300000000004 * fTemp994) + ((0.0039263700000000002 * fTemp995) + ((0.0193136 * fTemp996) + ((0.0137585 * fTemp997) + ((0.016165499999999999 * fTemp998) + ((0.0200181 * fTemp999) + ((0.00436148 * fTemp1000) + ((0.0115485 * fTemp1001) + ((0.0032127699999999998 * fTemp1002) + ((0.0057804000000000006 * fTemp1003) + ((0.037111700000000004 * fTemp1004) + ((0.014907300000000002 * fTemp1005) + ((0.0092683000000000001 * fTemp1006) + ((0.0158698 * fTemp1007) + ((0.00489909 * fTemp1008) + ((0.00036272099999999999 * fTemp1009) + ((0.00043871700000000003 * fTemp1010) + ((0.00018132700000000001 * fTemp1011) + ((0.00097058900000000011 * fTemp1012) + ((0.00016036100000000001 * fTemp1013) + ((0.00019245000000000002 * fTemp1014) + ((3.8801999999999999e-05 * fTemp1015) + ((6.5230500000000005e-05 * fTemp1016) + ((4.81323e-05 * fTemp1017) + ((3.1175000000000006e-05 * fTemp1018) + ((9.139900000000001e-05 * fTemp1019) + ((0.000137362 * fTemp1020) + ((0.000272806 * fTemp1021) + ((0.00025063300000000005 * fTemp1022) + ((0.000314307 * fTemp1023) + ((8.3185099999999991e-06 * fTemp1024) + ((1.1129000000000001e-05 * fTemp1025) + ((0.00012562199999999998 * fTemp1026) + ((0.00027303400000000002 * fTemp1027) + ((8.74662e-06 * fTemp1028) + ((0.00016385400000000001 * fTemp1029) + ((0.00026935700000000002 * fTemp1030) + ((0.00035653000000000003 * fTemp1031) + ((2.5639300000000001e-06 * fTemp1032) + ((0.0011749499999999999 * fTemp1033) + ((0.000138672 * fTemp1034) + ((0.00092974400000000003 * fTemp1035) + ((0.00189912 * fTemp1036) + ((0.00157916 * fTemp1037) + ((0.0017056100000000002 * fTemp1038) + ((0.00246014 * fTemp1039) + ((0.0047484400000000005 * fTemp1040) + ((0.010441600000000001 * fTemp1041) + ((0.0044470300000000003 * fTemp1042) + ((0.0100582 * fTemp1043) + ((0.0128559 * fTemp1044) + ((0.015119400000000002 * fTemp1045) + ((0.016079200000000002 * fTemp1046) + ((0.015913200000000002 * fTemp1047) + ((0.0076609499999999997 * fTemp1048) + ((0.0068764300000000002 * fTemp1049) + ((0.0095819500000000005 * fTemp1050) + ((0.0024969700000000003 * fTemp1051) + ((0.0014838199999999998 * fTemp1052) + ((0.000311911 * fTemp1053) + ((0.00054486499999999995 * fTemp1054) + ((0.0114164 * fTemp1055) + ((0.015415000000000002 * fTemp1056) + ((0.0023363800000000003 * fTemp1057) + ((0.0013234399999999999 * fTemp1058) + ((0.0047624399999999997 * fTemp1059) + ((0.0035146700000000001 * fTemp1060) + ((0.0014325799999999999 * fTemp1061) + ((0.00035963800000000001 * fTemp1062) + ((0.00013482199999999999 * fTemp1063) + ((0.0031359700000000001 * fTemp1064) + ((0.0033774600000000001 * fTemp1065) + ((0.00043131800000000003 * fTemp1066) + ((0.0013603899999999999 * fTemp1067) + ((0.00076972400000000006 * fTemp1068) + ((0.0011577500000000001 * fTemp1069) + ((0.0011045300000000001 * fTemp1070) + ((0.0027559100000000003 * fTemp1071) + ((0.0016313200000000001 * fTemp1072) + ((0.0019843199999999999 * fTemp1073) + ((0.0031219500000000001 * fTemp1074) + ((0.0017147500000000001 * fTemp1075) + ((0.0120184 * fTemp1076) + ((0.011691100000000001 * fTemp1077) + ((0.0053095800000000004 * fTemp1078) + ((0.0072171800000000001 * fTemp1079) + ((0.0030320200000000003 * fTemp1080) + ((0.00131485 * fTemp1081) + ((0.0011081700000000001 * fTemp1082) + ((0.00036208399999999998 * fTemp1083) + ((0.00017773600000000001 * fTemp1084) + ((0.00073753600000000001 * fTemp1085) + ((0.00060830200000000002 * fTemp1086) + ((0.00102903 * fTemp1087) + ((0.0030104600000000004 * fTemp1088) + ((0.0010694400000000001 * fTemp1089) + ((0.0029673899999999999 * fTemp1090) + ((0.0023879000000000001 * fTemp1091) + ((0.00017378000000000001 * fTemp1092) + ((0.00020804999999999999 * fTemp1093) + ((0.00029024100000000006 * fTemp1094) + ((0.0010302600000000001 * fTemp1095) + ((0.017341200000000001 * fTemp1096) + ((0.00280679 * fTemp1097) + ((0.00054230400000000007 * fTemp1098) + ((0.0010789999999999999 * fTemp1099) + ((0.00127535 * fTemp1100) + ((1.8656099999999998e-06 * fTemp1101) + ((0.0188738 * fTemp1102) + ((0.0027951100000000004 * fTemp1103) + ((0.0047547600000000002 * fTemp1104) + ((0.0037710400000000002 * fTemp1105) + ((0.0045419900000000001 * fTemp1106) + ((0.00141242 * fTemp1107) + ((0.00134669 * fTemp1108) + ((0.020373700000000002 * fTemp1109) + ((0.0086227300000000003 * fTemp1110) + ((0.015368999999999999 * fTemp1111) + ((0.026966700000000003 * fTemp1112) + ((0.023967600000000002 * fTemp1113) + ((0.025263300000000002 * fTemp1114) + ((0.019380700000000001 * fTemp1115) + ((0.0052166499999999998 * fTemp1116) + ((0.012525700000000001 * fTemp1117) + ((0.039007399999999998 * fTemp1118) + ((0.039406500000000004 * fTemp1119) + ((0.0160175 * fTemp1120) + ((0.035762599999999999 * fTemp1121) + ((0.026436999999999999 * fTemp1122) + ((0.0180915 * fTemp1123) + ((0.00060328500000000006 * fTemp1124) + ((0.042794800000000008 * fTemp1125) + ((0.034687500000000003 * fTemp1126) + ((0.0095142000000000004 * fTemp1127) + ((0.0011779100000000001 * fTemp1128) + ((0.000167329 * fTemp1129) + ((0.00041459900000000003 * fTemp1130) + ((0.00031506200000000001 * fTemp1131) + ((0.0021747000000000003 * fTemp1132) + ((0.0024374800000000001 * fTemp1133) + ((0.0018498099999999999 * fTemp1134) + ((0.010498400000000001 * fTemp1135) + ((0.0021260799999999998 * fTemp1136) + ((0.0010427100000000001 * fTemp1137) + ((0.0065524800000000003 * fTemp1138) + ((0.011496599999999999 * fTemp1139) + ((0.0092546800000000012 * fTemp1140) + ((0.00041918000000000001 * fTemp1141) + (0.0032369600000000001 * fTemp1142)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))); fRec0[0] = std::max<double>((fRec0[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp1143)))))); fHbargraph0 = FAUSTFLOAT(fRec0[0]); output0[i] = FAUSTFLOAT(fTemp1143); double fTemp1144 = (fRec1[0] * (((1.07578e-06 * fTemp622) + ((1.0896600000000002e-05 * fTemp623) + ((5.7825300000000005e-06 * fTemp1) + ((3.3373e-05 * fTemp628) + ((0.0044664700000000002 * fTemp5) + ((0.0013042499999999999 * fTemp6) + ((0.0025056699999999998 * fTemp7) + ((0.0014331000000000001 * fTemp653) + ((3.3066799999999999e-06 * fTemp12) + ((9.6444300000000008e-05 * fTemp17) + ((0.00063805800000000005 * fTemp19) + ((0.0011957500000000002 * fTemp20) + ((0.00034096799999999998 * fTemp659) + ((0.0010047600000000002 * fTemp22) + ((0.00095472699999999994 * fTemp23) + ((0.0011230999999999999 * fTemp24) + ((0.000103257 * fTemp26) + ((0.00171093 * fTemp665) + ((0.0024843999999999999 * fTemp27) + ((0.0013637999999999999 * fTemp666) + ((0.0020383699999999999 * fTemp28) + ((0.00292619 * fTemp667) + ((0.00074355600000000003 * fTemp30) + ((0.0039499399999999999 * fTemp32) + ((0.0064549899999999999 * fTemp672) + ((0.0094244500000000009 * fTemp676) + ((0.019293299999999999 * fTemp35) + ((0.019155500000000002 * fTemp678) + ((0.0068834500000000002 * fTemp37) + ((0.036199000000000002 * fTemp38) + ((1.0336899999999999e-06 * fTemp40) + ((0.0020205099999999997 * fTemp42) + ((0.0022768000000000003 * fTemp43) + ((0.00027500499999999999 * fTemp45) + ((0.00010999399999999999 * fTemp46) + ((1.2511200000000001e-05 * fTemp47) + ((0.0018692700000000001 * fTemp48) + ((0.000129173 * fTemp49) + ((0.0010500000000000002 * fTemp50) + ((0.0037914799999999999 * fTemp51) + ((0.0063763400000000003 * fTemp52) + ((0.0065615300000000003 * fTemp53) + ((0.00222449 * fTemp54) + ((0.049093400000000002 * fTemp56) + ((0.009442299999999999 * fTemp694) + ((0.00046772600000000007 * fTemp695) + ((0.054047100000000001 * fTemp57) + ((0.0108471 * fTemp697) + ((0.0010471900000000001 * fTemp704) + ((0.00047446700000000006 * fTemp61) + ((0.00031437800000000003 * fTemp63) + ((1.5753899999999999e-07 * fTemp64) + ((0.00036215100000000001 * fTemp65) + ((0.00023396100000000001 * fTemp66) + ((0.00052374700000000008 * fTemp67) + ((0.00092775000000000008 * fTemp68) + ((0.00122649 * fTemp69) + ((0.00050830900000000008 * fTemp709) + ((0.00015973800000000001 * fTemp72) + ((0.00065440400000000003 * fTemp73) + ((0.00025875799999999999 * fTemp75) + ((0.00049362799999999997 * fTemp76) + ((0.00016541 * fTemp77) + ((0.0010192300000000001 * fTemp78) + ((0.00032049699999999999 * fTemp716) + ((0.034925999999999999 * fTemp79) + ((3.4760399999999997e-08 * fTemp81) + ((0.020153599999999997 * fTemp82) + ((0.015254500000000001 * fTemp717) + ((4.4900900000000009e-05 * fTemp718) + ((1.2673900000000001e-05 * fTemp719) + ((0.0099207400000000008 * fTemp89) + ((0.041638400000000006 * fTemp90) + ((0.028412400000000001 * fTemp722) + ((0.016930500000000001 * fTemp725) + ((0.0106017 * fTemp93) + ((0.000263627 * fTemp726) + ((0.00025129900000000002 * fTemp94) + ((0.00047378999999999998 * fTemp728) + ((0.000359551 * fTemp96) + ((0.00050858999999999995 * fTemp98) + ((0.00025865000000000003 * fTemp730) + ((5.1984399999999995e-06 * fTemp100) + ((2.0081900000000002e-05 * fTemp731) + ((5.35095e-06 * fTemp11) + ((0.00030013000000000001 * fTemp101) + ((0.00012962100000000001 * fTemp733) + ((0.00012994100000000001 * fTemp104) + ((0.000501459 * fTemp105) + ((0.00041380000000000003 * fTemp106) + ((4.2136500000000006e-05 * fTemp108) + ((1.1025e-06 * fTemp109) + ((0.000102185 * fTemp110) + ((0.0010346200000000002 * fTemp111) + ((0.0015065 * fTemp112) + ((2.1505000000000002e-05 * fTemp741) + ((0.00061807300000000002 * fTemp113) + ((6.5997900000000001e-08 * fTemp115) + ((7.1971000000000006e-05 * fTemp744) + ((0.00051516900000000011 * fTemp119) + ((0.00076406400000000006 * fTemp120) + ((9.4944000000000018e-05 * fTemp745) + ((0.00095418100000000002 * fTemp747) + ((0.00034814200000000002 * fTemp750) + ((8.0286900000000005e-05 * fTemp125) + ((0.00159566 * fTemp126) + ((0.0016114299999999999 * fTemp127) + ((1.1146700000000001e-05 * fTemp754) + ((0.0029336900000000001 * fTemp128) + ((0.0015251900000000001 * fTemp129) + ((0.00063413500000000008 * fTemp756) + ((0.00021672300000000002 * fTemp757) + ((0.0030693399999999998 * fTemp132) + ((7.2115600000000003e-07 * fTemp133) + ((2.0505700000000003e-05 * fTemp775) + ((7.2276399999999995e-06 * fTemp776) + ((4.1691399999999999e-05 * fTemp138) + ((0.00027668200000000005 * fTemp147) + ((1.3220600000000002e-05 * fTemp779) + ((0.0002275 * fTemp780) + ((0.0020786799999999999 * fTemp781) + ((0.00280241 * fTemp782) + ((0.00091981900000000011 * fTemp783) + ((7.5101900000000007e-05 * fTemp158) + ((0.0026788099999999998 * fTemp784) + ((0.0036546199999999999 * fTemp785) + ((0.00063752100000000005 * fTemp164) + ((0.00050336900000000004 * fTemp786) + ((0.0013227800000000002 * fTemp787) + ((7.3547000000000006e-05 * fTemp788) + ((0.00076943900000000002 * fTemp165) + ((0.00033734999999999999 * fTemp166) + ((0.0013802 * fTemp167) + ((0.0050838799999999998 * fTemp168) + ((0.013509400000000001 * fTemp171) + ((0.015784800000000002 * fTemp793) + ((0.00206245 * fTemp175) + ((0.0024348900000000003 * fTemp795) + ((0.0034120499999999998 * fTemp176) + ((0.036800600000000003 * fTemp796) + ((0.016894100000000002 * fTemp798) + ((0.015907999999999999 * fTemp799) + ((0.00139284 * fTemp181) + ((0.0111489 * fTemp800) + ((0.00048254200000000003 * fTemp183) + ((0.00084440200000000006 * fTemp803) + ((0.00014837300000000001 * fTemp804) + ((2.2315100000000003e-05 * fTemp806) + ((4.6366800000000005e-05 * fTemp625) + ((0.00015426800000000002 * fTemp204) + ((2.9996500000000003e-05 * fTemp205) + ((0.00011103000000000001 * fTemp808) + ((0.00013601100000000001 * fTemp208) + ((0.00055044600000000001 * fTemp209) + ((0.00044798200000000004 * fTemp210) + ((0.00057507100000000002 * fTemp811) + ((0.00032662200000000005 * fTemp812) + ((4.4411900000000001e-05 * fTemp814) + ((0.000103707 * fTemp815) + ((0.00100478 * fTemp816) + ((0.00012959000000000001 * fTemp818) + ((0.0012166300000000002 * fTemp819) + ((0.00022863600000000002 * fTemp820) + ((0.00033440100000000001 * fTemp219) + ((0.00098071900000000012 * fTemp821) + ((0.00040021800000000004 * fTemp823) + ((0.0016816299999999999 * fTemp222) + ((0.00099638500000000002 * fTemp825) + ((0.0034718700000000002 * fTemp827) + ((0.0068587300000000004 * fTemp225) + ((0.0058219500000000002 * fTemp829) + ((0.00087088200000000001 * fTemp234) + ((0.017078900000000001 * fTemp831) + ((0.027225600000000003 * fTemp832) + ((9.9177200000000003e-05 * fTemp838) + ((0.0006416280000000001 * fTemp839) + ((0.0071496000000000007 * fTemp236) + ((0.0043624700000000002 * fTemp237) + ((0.00055969600000000004 * fTemp849) + ((0.0028104300000000005 * fTemp238) + ((0.00089791299999999997 * fTemp850) + ((0.0015055300000000001 * fTemp241) + ((0.00129704 * fTemp242) + ((0.00042873700000000005 * fTemp244) + ((0.00077501600000000001 * fTemp247) + ((0.0177702 * fTemp248) + ((0.0011423000000000002 * fTemp249) + ((0.0057435900000000007 * fTemp854) + ((0.0096359600000000007 * fTemp250) + ((0.0037277 * fTemp251) + ((0.0069752599999999996 * fTemp252) + ((0.045202099999999995 * fTemp253) + ((0.00526948 * fTemp856) + ((0.000358363 * fTemp255) + ((0.00023124899999999999 * fTemp863) + ((0.00020135900000000002 * fTemp257) + ((0.00015575000000000002 * fTemp258) + ((6.1446399999999998e-06 * fTemp259) + ((8.1741199999999999e-06 * fTemp868) + ((0.0011816700000000001 * fTemp869) + ((0.00073013500000000003 * fTemp870) + ((0.00065044300000000001 * fTemp260) + ((0.0015448500000000002 * fTemp871) + ((0.00041635900000000004 * fTemp872) + ((0.00109789 * fTemp873) + ((0.0026210900000000004 * fTemp874) + ((0.0018869100000000001 * fTemp875) + ((3.3187600000000001e-06 * fTemp266) + ((0.0024495200000000002 * fTemp268) + ((0.0022621500000000001 * fTemp876) + ((8.7600299999999995e-06 * fTemp269) + ((2.9587800000000002e-05 * fTemp270) + ((0.0047280300000000003 * fTemp272) + ((0.0056186100000000004 * fTemp273) + ((0.041430000000000002 * fTemp274) + ((0.032932100000000006 * fTemp275) + ((0.028794800000000002 * fTemp883) + ((0.024621200000000003 * fTemp276) + ((0.06345640000000001 * fTemp277) + ((0.07541260000000001 * fTemp278) + (((1.0190999999999999e-05 * fTemp280) + ((0.00125953 * fTemp886) + ((0.00019295400000000001 * fTemp887) + (((0.0020002800000000001 * fTemp288) + ((0.0121522 * fTemp892) + ((0.011685700000000002 * fTemp893) + ((0.0122635 * fTemp894) + ((0.017027300000000002 * fTemp895) + ((0.017569399999999999 * fTemp896) + ((0.00062478100000000003 * fTemp897) + ((0.00028939400000000006 * fTemp898) + ((0.0047823300000000004 * fTemp899) + ((0.048044200000000002 * fTemp900) + ((0.031593799999999998 * fTemp902) + ((0.0092093100000000001 * fTemp903) + ((0.0182515 * fTemp904) + ((0.0125871 * fTemp294) + ((0.0010793700000000001 * fTemp905) + ((0.0061485900000000007 * fTemp906) + ((0.00108131 * fTemp907) + ((0.00149292 * fTemp909) + ((5.1482899999999996e-06 * fTemp910) + ((5.530960000000001e-05 * fTemp300) + ((1.4188099999999999e-06 * fTemp301) + ((0.00946403 * fTemp911) + ((0.0038781100000000002 * fTemp303) + ((0.00011918500000000002 * fTemp304) + ((9.8678100000000013e-05 * fTemp305) + ((4.2207000000000004e-05 * fTemp912) + ((3.2490500000000003e-05 * fTemp306) + ((0.00011697900000000002 * fTemp307) + ((0.000115798 * fTemp915) + ((0.0027517499999999999 * fTemp308) + ((0.0037339199999999999 * fTemp309) + ((0.00065997500000000004 * fTemp924) + ((0.0016790700000000002 * fTemp311) + ((0.0019817300000000001 * fTemp931) + ((0.0015044699999999999 * fTemp313) + ((0.0010922900000000001 * fTemp314) + ((0.0040626200000000003 * fTemp315) + ((0.0012104800000000001 * fTemp317) + ((0.00102589 * fTemp318) + ((0.0011136799999999999 * fTemp319) + ((0.0035448200000000002 * fTemp320) + ((0.0039074399999999999 * fTemp321) + ((0.00070128400000000004 * fTemp946) + ((0.00040873600000000004 * fTemp947) + ((0.00017855099999999999 * fTemp323) + ((0.0020778099999999998 * fTemp324) + ((0.0011952499999999999 * fTemp325) + ((0.0022150400000000002 * fTemp326) + ((3.8517100000000004e-05 * fTemp327) + ((0.011077500000000001 * fTemp328) + ((0.0020168600000000001 * fTemp329) + ((0.0022290399999999998 * fTemp331) + ((0.0084232300000000003 * fTemp332) + ((0.0011997199999999998 * fTemp951) + ((0.0125606 * fTemp336) + ((0.00127378 * fTemp337) + ((0.0537481 * fTemp339) + ((0.013059400000000001 * fTemp340) + ((0.021176 * fTemp341) + ((0.0048699899999999994 * fTemp958) + ((0.0061526599999999999 * fTemp959) + ((0.0028706900000000004 * fTemp343) + ((3.4954000000000004e-05 * fTemp345) + ((9.3229500000000019e-05 * fTemp346) + ((9.5701199999999998e-05 * fTemp347) + ((0.00012240800000000001 * fTemp348) + ((5.5900900000000005e-05 * fTemp960) + ((1.0045e-05 * fTemp352) + ((1.9102600000000002e-05 * fTemp961) + ((0.0020406000000000001 * fTemp357) + ((0.000876507 * fTemp972) + ((0.0013280499999999999 * fTemp359) + ((0.0017303100000000001 * fTemp360) + ((0.0029776099999999999 * fTemp361) + ((0.0025195700000000001 * fTemp362) + ((0.00102092 * fTemp977) + ((0.00082739399999999996 * fTemp365) + ((0.00174807 * fTemp366) + ((0.00013990400000000002 * fTemp979) + ((0.0021519 * fTemp368) + ((0.00235812 * fTemp369) + ((7.6654099999999985e-06 * fTemp987) + ((0.0022741699999999998 * fTemp991) + ((0.0011889400000000001 * fTemp373) + ((0.0042530099999999998 * fTemp374) + ((0.0079603199999999999 * fTemp376) + ((0.0030812000000000001 * fTemp377) + ((0.0075640600000000001 * fTemp993) + ((0.0032282000000000001 * fTemp378) + ((0.0041592900000000004 * fTemp379) + ((0.00033097600000000002 * fTemp994) + ((0.0066906600000000002 * fTemp382) + ((0.00018497500000000001 * fTemp383) + ((0.00108066 * fTemp385) + ((0.0081795500000000007 * fTemp387) + ((0.0040393699999999996 * fTemp388) + ((0.0088403900000000001 * fTemp389) + ((0.0054466000000000002 * fTemp390) + ((0.033863999999999998 * fTemp392) + ((0.0092350000000000002 * fTemp393) + ((0.0043864799999999999 * fTemp394) + ((0.00053732699999999999 * fTemp395) + ((0.0027836500000000004 * fTemp1002) + ((0.0092729000000000006 * fTemp1003) + ((0.022299000000000003 * fTemp396) + ((0.0012059800000000002 * fTemp397) + ((0.025815500000000002 * fTemp398) + ((7.0800700000000008e-05 * fTemp1011) + ((0.00076956600000000007 * fTemp401) + ((0.000231146 * fTemp402) + ((0.00014766099999999999 * fTemp403) + ((4.1470500000000002e-05 * fTemp1015) + ((7.1901800000000003e-05 * fTemp1016) + ((3.71676e-05 * fTemp1017) + ((0.00011888700000000002 * fTemp1019) + ((0.00015893600000000001 * fTemp1020) + ((1.5261800000000004e-05 * fTemp406) + ((0.00036830800000000003 * fTemp1021) + ((0.00030627700000000004 * fTemp1022) + ((0.000251322 * fTemp1023) + ((8.5058500000000009e-06 * fTemp1024) + ((3.3982700000000002e-05 * fTemp1025) + ((2.6751600000000003e-05 * fTemp1026) + ((0.000239084 * fTemp1027) + ((9.1238799999999995e-06 * fTemp1028) + ((0.00016550199999999999 * fTemp1029) + ((0.00022708 * fTemp1030) + ((3.6973199999999999e-06 * fTemp1032) + ((0.00015429699999999999 * fTemp414) + ((0.00065994200000000006 * fTemp427) + ((0.00021972700000000002 * fTemp428) + ((0.0011643300000000001 * fTemp430) + ((0.0017905 * fTemp1035) + ((0.00164631 * fTemp1037) + ((0.00227327 * fTemp1038) + ((0.0030369999999999998 * fTemp1039) + ((0.0020450900000000003 * fTemp1040) + ((0.010980500000000001 * fTemp1041) + ((0.0023284899999999999 * fTemp1042) + ((0.0074067100000000004 * fTemp1043) + ((0.016699200000000001 * fTemp1044) + ((0.018899099999999999 * fTemp1045) + ((0.019806900000000002 * fTemp1046) + ((7.1374800000000001e-06 * fTemp433) + ((5.5996800000000006e-05 * fTemp434) + ((1.69708e-05 * fTemp435) + ((0.000195057 * fTemp436) + ((0.000117308 * fTemp437) + ((0.0143637 * fTemp1047) + ((0.0058000299999999994 * fTemp1048) + ((0.0046881500000000003 * fTemp1049) + ((0.0079024400000000002 * fTemp1050) + ((0.00020216400000000001 * fTemp439) + ((0.0010336799999999999 * fTemp440) + ((0.00042659700000000002 * fTemp441) + ((0.000779071 * fTemp442) + ((0.00070924500000000006 * fTemp443) + ((0.00050421999999999999 * fTemp444) + ((0.00050803600000000001 * fTemp445) + ((0.00095978899999999995 * fTemp446) + ((0.00100501 * fTemp447) + ((0.0012236 * fTemp448) + ((0.00147426 * fTemp449) + ((0.0018419899999999999 * fTemp450) + ((0.00094503799999999993 * fTemp452) + ((0.0013272 * fTemp453) + ((0.0025739000000000001 * fTemp454) + ((0.0033512100000000003 * fTemp455) + ((0.00059498000000000005 * fTemp458) + ((0.00365475 * fTemp459) + ((0.0017505699999999999 * fTemp460) + ((0.0026745600000000003 * fTemp461) + ((0.0010550900000000001 * fTemp1053) + ((0.0046326400000000004 * fTemp463) + ((2.5156400000000002e-05 * fTemp465) + ((0.0053821700000000004 * fTemp466) + ((0.0039087499999999999 * fTemp467) + ((0.0036032700000000004 * fTemp468) + ((0.0019828699999999999 * fTemp469) + ((0.0053022700000000004 * fTemp470) + ((0.00072404000000000001 * fTemp471) + ((0.0033726400000000001 * fTemp473) + ((0.0028127900000000003 * fTemp474) + ((0.0016933400000000002 * fTemp475) + ((0.0029381799999999999 * fTemp476) + ((0.0038801100000000004 * fTemp477) + ((0.0064815100000000002 * fTemp478) + ((0.0067297599999999996 * fTemp479) + ((0.00338193 * fTemp480) + ((0.0026122100000000002 * fTemp481) + ((0.0038020800000000002 * fTemp482) + ((0.0039973999999999999 * fTemp483) + ((4.49754e-06 * fTemp484) + ((0.0042595000000000003 * fTemp485) + ((0.0029229899999999999 * fTemp486) + ((0.00139635 * fTemp487) + ((0.00431154 * fTemp489) + ((0.0105579 * fTemp490) + ((0.014038399999999999 * fTemp491) + ((0.0049862900000000009 * fTemp492) + ((0.0014525200000000001 * fTemp493) + ((0.0072938400000000002 * fTemp494) + ((0.0060665699999999994 * fTemp495) + ((0.0216826 * fTemp496) + ((0.017730600000000003 * fTemp497) + ((0.0123141 * fTemp1055) + ((0.036801199999999999 * fTemp498) + ((0.0075229400000000005 * fTemp499) + ((0.042423700000000002 * fTemp500) + ((0.054464300000000007 * fTemp501) + ((0.111697 * fTemp502) + ((0.050380599999999998 * fTemp503) + ((0.069732299999999997 * fTemp504) + ((0.041405900000000002 * fTemp505) + ((0.047424299999999996 * fTemp506) + ((0.043948600000000004 * fTemp507) + ((0.081345899999999999 * fTemp508) + ((0.062211200000000001 * fTemp509) + ((0.046698700000000003 * fTemp510) + ((0.0034082300000000004 * fTemp1057) + ((0.0017853699999999999 * fTemp1058) + ((0.00345985 * fTemp1059) + ((0.00155444 * fTemp1061) + ((0.000148231 * fTemp517) + ((0.00053192199999999999 * fTemp518) + ((0.0072206400000000004 * fTemp1064) + ((0.0011467599999999999 * fTemp1065) + ((0.0018625499999999999 * fTemp520) + ((0.0014091100000000001 * fTemp521) + ((0.00171149 * fTemp1068) + ((0.0032145400000000001 * fTemp1069) + ((0.0009296310000000001 * fTemp525) + ((0.00017575500000000001 * fTemp526) + ((0.000234556 * fTemp1071) + ((0.0292041 * fTemp529) + ((0.015611 * fTemp530) + ((0.0131959 * fTemp532) + ((0.0033820999999999999 * fTemp533) + ((0.00065433400000000001 * fTemp534) + ((0.00012754700000000002 * fTemp1081) + ((0.00028600400000000002 * fTemp535) + ((0.00056964699999999995 * fTemp536) + ((0.00055874899999999999 * fTemp537) + ((0.000107706 * fTemp538) + ((2.3258800000000005e-05 * fTemp539) + ((1.5002200000000002e-05 * fTemp265) + ((0.000386788 * fTemp1085) + ((0.00090610300000000012 * fTemp541) + ((0.0014508500000000001 * fTemp542) + ((0.0044549899999999998 * fTemp1087) + ((0.00015571700000000001 * fTemp545) + ((0.00054205300000000002 * fTemp1088) + ((0.0015368900000000002 * fTemp1089) + ((0.0026692399999999998 * fTemp546) + ((1.74779e-06 * fTemp547) + ((7.3980599999999995e-07 * fTemp548) + ((0.00144247 * fTemp549) + ((0.0020409600000000001 * fTemp550) + ((0.0020199900000000002 * fTemp551) + ((0.00067166600000000002 * fTemp552) + ((0.0046483699999999998 * fTemp553) + ((0.0007157 * fTemp1090) + ((0.0039002500000000005 * fTemp1091) + ((0.0084629900000000001 * fTemp554) + ((0.053001199999999998 * fTemp555) + ((0.048941400000000003 * fTemp556) + ((0.0007391530000000001 * fTemp557) + ((0.0020685400000000002 * fTemp558) + ((0.00055752700000000004 * fTemp559) + ((0.00107368 * fTemp560) + ((0.00105561 * fTemp561) + ((0.00064681700000000005 * fTemp562) + ((0.00078251799999999995 * fTemp563) + ((0.00084005400000000002 * fTemp564) + ((0.00072445800000000009 * fTemp565) + ((0.00012713900000000002 * fTemp566) + ((1.96889e-05 * fTemp432) + ((5.5660599999999997e-06 * fTemp567) + ((5.6691300000000004e-05 * fTemp1094) + ((0.024367400000000001 * fTemp568) + ((0.011542200000000001 * fTemp1096) + ((0.0023261500000000004 * fTemp570) + ((1.8977800000000003e-05 * fTemp571) + ((1.9873400000000002e-05 * fTemp572) + ((0.00107755 * fTemp1097) + ((1.8648999999999999e-06 * fTemp573) + ((1.4833700000000001e-06 * fTemp1101) + ((0.00016114100000000001 * fTemp575) + ((0.017303499999999999 * fTemp1102) + ((0.0038926099999999999 * fTemp1103) + ((0.0051357799999999995 * fTemp1104) + ((0.0057548899999999995 * fTemp1105) + ((0.0110121 * fTemp1106) + ((0.00038352400000000005 * fTemp576) + ((0.00193882 * fTemp1107) + ((0.0014356600000000001 * fTemp577) + ((0.00020930100000000001 * fTemp578) + ((0.016072400000000001 * fTemp1109) + ((0.0227996 * fTemp1110) + ((0.016965000000000001 * fTemp1111) + ((0.033336499999999998 * fTemp1112) + ((0.029073099999999998 * fTemp1113) + ((0.017693 * fTemp1114) + ((0.023498000000000002 * fTemp1115) + ((0.012867100000000001 * fTemp1116) + ((0.024658199999999998 * fTemp1117) + ((0.033071500000000004 * fTemp1118) + ((0.023601800000000003 * fTemp1119) + ((0.025422899999999998 * fTemp1120) + ((0.030269900000000002 * fTemp1121) + ((0.023295900000000001 * fTemp1122) + ((0.018621700000000001 * fTemp1123) + ((0.010567 * fTemp1124) + ((0.056895100000000004 * fTemp1125) + ((0.014210199999999999 * fTemp1127) + ((0.00027516900000000002 * fTemp1131) + ((0.00128867 * fTemp1132) + ((0.0013097499999999999 * fTemp597) + ((0.0016259900000000001 * fTemp598) + ((0.00050261399999999997 * fTemp599) + ((0.00278079 * fTemp600) + ((0.0081598500000000015 * fTemp602) + ((0.0056564199999999997 * fTemp603) + ((0.010539099999999999 * fTemp604) + ((0.0272114 * fTemp605) + ((0.021074000000000002 * fTemp606) + ((0.0080194200000000011 * fTemp608) + ((0.000377902 * fTemp1133) + ((0.0015717800000000001 * fTemp1136) + ((0.0086705299999999992 * fTemp610) + ((0.00411948 * fTemp1137) + ((0.0029588800000000001 * fTemp612) + ((0.0107584 * fTemp613) + ((0.0093965200000000002 * fTemp614) + ((0.0139764 * fTemp615) + ((0.0010616200000000001 * fTemp1141) + (0.016385799999999999 * fTemp617))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) + (0.00045463200000000001 * fTemp283))))) + (0.042141200000000004 * fTemp279)))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))) - ((9.8664600000000001e-07 * fTemp620) + ((0.000106835 * fTemp621) + ((3.4608100000000005e-05 * fTemp624) + ((0.00011808300000000001 * fTemp627) + ((0.00015213499999999999 * fTemp629) + ((0.00018018099999999999 * fTemp630) + ((0.00022798800000000001 * fTemp631) + ((5.723480000000001e-05 * fTemp2) + ((0.0010091500000000001 * fTemp632) + ((0.0015510600000000002 * fTemp633) + ((0.00097602600000000006 * fTemp634) + ((0.000712925 * fTemp3) + ((0.00090846500000000001 * fTemp4) + ((0.000274135 * fTemp635) + ((0.0024532300000000003 * fTemp636) + ((0.00327984 * fTemp637) + ((0.00165106 * fTemp638) + ((0.0016773199999999999 * fTemp639) + ((0.00626758 * fTemp640) + ((0.0045976600000000008 * fTemp641) + ((0.0023563100000000003 * fTemp642) + ((0.0048987900000000001 * fTemp643) + ((0.0034805299999999999 * fTemp644) + ((0.0026557099999999999 * fTemp8) + ((0.00044967800000000007 * fTemp645) + ((0.0043297500000000003 * fTemp646) + ((0.009209740000000001 * fTemp647) + ((0.0029224400000000001 * fTemp648) + ((0.0105223 * fTemp9) + ((0.0026383800000000001 * fTemp649) + ((0.0080828600000000007 * fTemp650) + ((0.022465099999999998 * fTemp651) + ((0.0090530699999999999 * fTemp10) + ((0.0048908699999999994 * fTemp652) + ((1.6838600000000002e-05 * fTemp654) + ((0.00013637100000000001 * fTemp13) + ((9.7487500000000005e-05 * fTemp14) + ((2.2899500000000003e-05 * fTemp655) + ((1.3387100000000001e-05 * fTemp656) + ((1.9403399999999997e-06 * fTemp15) + ((0.00034909600000000002 * fTemp16) + ((8.3318600000000019e-05 * fTemp657) + ((0.00019838400000000002 * fTemp18) + ((0.0012272400000000001 * fTemp658) + ((0.00020233 * fTemp21) + ((0.00257691 * fTemp660) + ((0.0010732299999999999 * fTemp661) + ((0.0017717799999999999 * fTemp662) + ((0.000561862 * fTemp626) + ((0.000172719 * fTemp25) + ((0.0028482099999999999 * fTemp663) + ((0.00218125 * fTemp664) + ((0.00186575 * fTemp29) + ((0.000588187 * fTemp31) + ((0.00392757 * fTemp668) + ((0.0028865100000000001 * fTemp669) + ((0.0056144999999999997 * fTemp670) + ((0.0026402700000000001 * fTemp671) + ((0.0042838500000000005 * fTemp33) + ((0.0034927700000000001 * fTemp673) + ((0.0065811400000000009 * fTemp34) + ((0.0015727 * fTemp674) + ((0.00038527200000000003 * fTemp675) + ((0.027060000000000001 * fTemp677) + ((0.0063968899999999997 * fTemp36) + ((0.011650000000000001 * fTemp679) + ((0.0078633899999999996 * fTemp680) + ((0.0092220099999999992 * fTemp681) + ((0.029293300000000001 * fTemp39) + ((6.1935700000000003e-07 * fTemp41) + ((4.9322600000000008e-05 * fTemp682) + ((0.00028692799999999999 * fTemp683) + ((0.00133293 * fTemp44) + ((0.0028975800000000003 * fTemp684) + ((0.00187875 * fTemp685) + ((0.00088707100000000013 * fTemp686) + ((0.00020890300000000003 * fTemp687) + ((0.00237411 * fTemp688) + ((0.00112458 * fTemp689) + ((0.0031641300000000002 * fTemp690) + ((0.0018413699999999999 * fTemp691) + ((0.00090694700000000018 * fTemp55) + ((0.014119 * fTemp692) + ((0.0021459299999999999 * fTemp693) + ((0.015390200000000001 * fTemp58) + ((0.045964499999999998 * fTemp696) + ((0.028787799999999999 * fTemp698) + ((0.048319200000000007 * fTemp699) + ((0.076845299999999991 * fTemp700) + ((0.074437400000000001 * fTemp701) + ((0.0013813599999999999 * fTemp702) + ((9.4869000000000016e-05 * fTemp59) + ((0.00097653599999999996 * fTemp703) + ((0.00011001600000000001 * fTemp60) + ((0.00063438600000000002 * fTemp705) + ((0.00012589200000000001 * fTemp62) + ((0.00040925999999999999 * fTemp706) + ((6.4495100000000005e-05 * fTemp707) + ((1.3287400000000001e-05 * fTemp0) + ((0.00016574 * fTemp708) + ((0.00020847000000000004 * fTemp710) + ((0.00035920700000000001 * fTemp711) + ((0.00031580000000000003 * fTemp712) + ((0.0055766799999999997 * fTemp70) + ((1.6980200000000004e-05 * fTemp713) + ((3.2223700000000001e-05 * fTemp714) + ((0.00013887600000000002 * fTemp715) + ((0.00019982600000000001 * fTemp74) + ((0.00027277099999999999 * fTemp83) + ((0.000964846 * fTemp84) + ((0.0012146699999999999 * fTemp85) + ((0.00057145600000000003 * fTemp86) + ((0.00092367899999999995 * fTemp87) + ((0.0007145500000000001 * fTemp88) + ((0.00031649800000000002 * fTemp720) + ((0.0012203400000000001 * fTemp91) + ((0.0096560400000000012 * fTemp721) + ((0.0144406 * fTemp723) + ((0.013951100000000001 * fTemp724) + ((0.0084374500000000009 * fTemp92) + ((0.0039648399999999999 * fTemp727) + ((0.00036303800000000004 * fTemp95) + ((0.0014542699999999999 * fTemp729) + ((0.00064008700000000001 * fTemp97) + ((7.4982900000000003e-05 * fTemp99) + ((6.501340000000001e-05 * fTemp102) + ((0.00011503900000000001 * fTemp732) + ((7.9125199999999989e-06 * fTemp734) + ((1.1654000000000001e-05 * fTemp735) + ((6.8685100000000004e-05 * fTemp736) + ((8.4929499999999997e-06 * fTemp737) + ((1.41509e-05 * fTemp103) + ((0.00013697000000000001 * fTemp738) + ((0.00010523700000000001 * fTemp739) + ((3.2479200000000006e-05 * fTemp107) + ((7.9775300000000009e-05 * fTemp740) + ((0.00010184400000000001 * fTemp742) + ((5.1085100000000003e-05 * fTemp743) + ((3.2896299999999998e-06 * fTemp114) + ((0.00037059799999999998 * fTemp116) + ((0.000178013 * fTemp117) + ((0.0012454300000000001 * fTemp118) + ((0.0013326899999999999 * fTemp121) + ((0.00140716 * fTemp746) + ((0.00049063800000000005 * fTemp122) + ((0.00084652999999999996 * fTemp748) + ((0.00036433400000000001 * fTemp749) + ((0.001299 * fTemp123) + ((0.00067232300000000006 * fTemp751) + ((0.000145224 * fTemp124) + ((0.0033552399999999998 * fTemp752) + ((0.0029169900000000004 * fTemp753) + ((0.0019041500000000001 * fTemp755) + ((0.0020271300000000003 * fTemp758) + ((0.00118198 * fTemp759) + ((0.0037510500000000001 * fTemp760) + ((0.0044053800000000004 * fTemp761) + ((0.0050914999999999997 * fTemp762) + ((0.0046006600000000003 * fTemp763) + ((0.0069039700000000006 * fTemp764) + ((0.0058685200000000003 * fTemp765) + ((0.0011063700000000002 * fTemp766) + ((0.0019731900000000001 * fTemp130) + ((0.0051318099999999997 * fTemp767) + ((0.0061875000000000003 * fTemp768) + ((0.0086182900000000007 * fTemp769) + ((0.00066500800000000003 * fTemp770) + ((0.0054012200000000008 * fTemp771) + ((0.000641773 * fTemp131) + ((0.0077257100000000002 * fTemp772) + ((0.0049702700000000006 * fTemp773) + ((0.0075730000000000007 * fTemp774) + ((5.7104899999999999e-06 * fTemp134) + ((1.32724e-05 * fTemp135) + ((0.00015924 * fTemp136) + ((3.6292700000000006e-05 * fTemp137) + ((2.5843400000000004e-05 * fTemp777) + ((0.00024267500000000003 * fTemp778) + ((0.00039582199999999999 * fTemp139) + ((0.00031903100000000006 * fTemp140) + ((0.0011941500000000002 * fTemp141) + ((0.00106711 * fTemp142) + ((0.00308618 * fTemp143) + ((0.0032894199999999999 * fTemp144) + ((0.00149796 * fTemp145) + ((0.00068249900000000004 * fTemp146) + ((0.00078510099999999996 * fTemp148) + ((0.00096550100000000012 * fTemp149) + ((0.00058387599999999999 * fTemp150) + ((0.0013118799999999999 * fTemp151) + ((7.6537400000000003e-05 * fTemp152) + ((6.5009300000000008e-05 * fTemp153) + ((0.0031734000000000003 * fTemp154) + ((0.0023903100000000001 * fTemp155) + ((0.00058356200000000003 * fTemp156) + ((1.7606500000000002e-05 * fTemp157) + ((0.0027314400000000003 * fTemp159) + ((0.0017979000000000001 * fTemp160) + ((0.0013939500000000001 * fTemp161) + ((0.00191797 * fTemp162) + ((0.00034747700000000001 * fTemp163) + ((0.0011524899999999999 * fTemp789) + ((0.000320157 * fTemp169) + ((0.0075314300000000004 * fTemp170) + ((0.0020659800000000002 * fTemp172) + ((0.0049689600000000006 * fTemp790) + ((0.00801492 * fTemp791) + ((0.0022648999999999998 * fTemp792) + ((0.0110397 * fTemp173) + ((0.0010152000000000002 * fTemp174) + ((0.00287375 * fTemp794) + ((0.026332300000000003 * fTemp177) + ((0.0161706 * fTemp178) + ((0.0079993000000000009 * fTemp179) + ((0.00082163500000000003 * fTemp797) + ((0.035125400000000001 * fTemp180) + ((0.0032833199999999997 * fTemp182) + ((0.00033950300000000006 * fTemp801) + ((0.00046365600000000006 * fTemp802) + ((0.0019217200000000002 * fTemp184) + ((0.00055710700000000004 * fTemp185) + ((0.00078591400000000008 * fTemp186) + ((0.00067488200000000002 * fTemp187) + ((0.00020588500000000003 * fTemp188) + ((3.4700500000000004e-05 * fTemp189) + ((1.2413700000000001e-05 * fTemp80) + ((0.00022045699999999999 * fTemp805) + ((0.00380796 * fTemp190) + ((3.5918100000000004e-05 * fTemp192) + ((0.0026392099999999999 * fTemp193) + ((5.5551700000000006e-05 * fTemp807) + ((2.5941400000000002e-05 * fTemp194) + ((8.6548500000000007e-05 * fTemp195) + ((4.2405400000000006e-05 * fTemp196) + ((3.5255099999999998e-06 * fTemp197) + ((3.6866300000000003e-05 * fTemp198) + ((4.85157e-05 * fTemp199) + ((7.4248300000000005e-05 * fTemp200) + ((8.1096800000000013e-05 * fTemp201) + ((0.00033669 * fTemp202) + ((0.00035192300000000003 * fTemp203) + ((4.8744899999999996e-07 * fTemp206) + ((3.2621699999999995e-06 * fTemp207) + ((5.5010100000000004e-05 * fTemp809) + ((0.000181368 * fTemp810) + ((0.0012369000000000002 * fTemp211) + ((0.000181872 * fTemp212) + ((0.00084541900000000014 * fTemp813) + ((0.00030825999999999998 * fTemp213) + ((0.000991956 * fTemp214) + ((0.00076287399999999997 * fTemp215) + ((0.00098188600000000017 * fTemp817) + ((0.00039449500000000002 * fTemp216) + ((0.0012472700000000002 * fTemp217) + ((6.1852800000000005e-05 * fTemp218) + ((0.00122741 * fTemp220) + ((0.00019696800000000003 * fTemp822) + ((0.00051085000000000008 * fTemp824) + ((0.0048162999999999999 * fTemp221) + ((0.0040944599999999994 * fTemp223) + ((0.0041798500000000006 * fTemp826) + ((0.0073487099999999996 * fTemp224) + ((0.00164357 * fTemp828) + ((0.0047594300000000003 * fTemp226) + ((0.0066234300000000005 * fTemp227) + ((0.0021625699999999999 * fTemp228) + ((0.0107364 * fTemp229) + ((0.00078494800000000005 * fTemp230) + ((0.008554550000000001 * fTemp231) + ((0.0087573399999999989 * fTemp232) + ((0.0022028300000000002 * fTemp830) + ((0.026865800000000002 * fTemp233) + ((0.0066563000000000004 * fTemp833) + ((4.2778300000000003e-05 * fTemp235) + ((9.4569700000000004e-05 * fTemp834) + ((0.000158107 * fTemp835) + ((0.00048340500000000007 * fTemp836) + ((0.00023814000000000002 * fTemp837) + ((0.010395300000000001 * fTemp840) + ((0.0093701299999999991 * fTemp841) + ((0.0063169100000000002 * fTemp842) + ((0.0060908100000000003 * fTemp843) + ((0.013098200000000001 * fTemp844) + ((0.0095365099999999998 * fTemp845) + ((4.9636399999999996e-06 * fTemp846) + ((0.000168486 * fTemp847) + ((0.00017177199999999999 * fTemp848) + ((0.0011732700000000001 * fTemp851) + ((0.00090841200000000004 * fTemp239) + ((0.0016132899999999999 * fTemp240) + ((0.00080033999999999997 * fTemp243) + ((0.00113243 * fTemp245) + ((2.5690700000000001e-05 * fTemp246) + ((0.0016462200000000001 * fTemp852) + ((0.0158301 * fTemp853) + ((0.0126207 * fTemp254) + ((0.015590100000000001 * fTemp855) + ((0.027497799999999999 * fTemp857) + ((0.019302299999999998 * fTemp858) + ((0.044481599999999996 * fTemp859) + ((0.042276800000000003 * fTemp860) + ((0.0021177600000000002 * fTemp861) + ((0.00027291300000000001 * fTemp862) + ((6.1550000000000005e-05 * fTemp256) + ((0.000175224 * fTemp864) + ((0.00022650199999999998 * fTemp865) + ((5.7022700000000005e-05 * fTemp866) + ((2.0383200000000002e-05 * fTemp867) + ((4.9413399999999999e-06 * fTemp71) + ((0.00042647700000000008 * fTemp261) + ((0.0042857099999999999 * fTemp262) + ((0.0037509800000000001 * fTemp263) + ((0.000469171 * fTemp264) + ((0.0013037700000000001 * fTemp267) + ((6.2934400000000005e-05 * fTemp877) + ((0.000195522 * fTemp878) + ((0.00010142800000000001 * fTemp879) + ((0.00070563799999999997 * fTemp880) + ((0.00031068799999999999 * fTemp271) + ((0.0015255399999999999 * fTemp881) + ((0.000380057 * fTemp882) + ((0.00093046600000000002 * fTemp619) + ((7.7027e-06 * fTemp884) + ((5.28142e-05 * fTemp885) + ((0.00019374600000000001 * fTemp281) + ((0.00024288000000000001 * fTemp282) + ((0.00086436100000000012 * fTemp284) + ((5.3978799999999999e-06 * fTemp888) + ((5.8471100000000003e-05 * fTemp889) + ((0.00011763 * fTemp890) + ((0.00096584900000000007 * fTemp891) + ((0.000544179 * fTemp285) + ((0.00077855999999999997 * fTemp287) + ((0.00043610699999999998 * fTemp289) + ((0.000204336 * fTemp290) + ((2.2571e-06 * fTemp291) + ((1.2883700000000002e-05 * fTemp191) + ((0.0065755600000000003 * fTemp901) + ((0.044476699999999994 * fTemp292) + ((0.019425600000000001 * fTemp293) + ((0.0258357 * fTemp295) + ((0.00505303 * fTemp296) + ((0.00065851199999999999 * fTemp297) + ((6.4017400000000008e-05 * fTemp908) + ((0.00033249800000000003 * fTemp298) + ((0.00114682 * fTemp299) + ((0.0173968 * fTemp302) + ((0.00029377599999999999 * fTemp913) + ((0.000280439 * fTemp914) + ((0.000643591 * fTemp916) + ((0.00081294000000000006 * fTemp917) + ((0.00023107600000000004 * fTemp918) + ((0.00064061300000000005 * fTemp919) + ((0.00091664000000000003 * fTemp920) + ((0.00059890600000000007 * fTemp921) + ((0.00073955600000000005 * fTemp922) + ((0.0027768799999999998 * fTemp923) + ((0.0022861500000000002 * fTemp925) + ((0.0013073099999999999 * fTemp926) + ((0.00145302 * fTemp310) + ((0.00040949500000000001 * fTemp927) + ((0.00082950500000000002 * fTemp928) + ((0.00070229999999999999 * fTemp929) + ((0.00080632699999999991 * fTemp930) + ((0.001377 * fTemp312) + ((0.00016274 * fTemp316) + ((0.0028667500000000004 * fTemp932) + ((0.0011399600000000002 * fTemp933) + ((0.0027307400000000002 * fTemp934) + ((0.00100318 * fTemp935) + ((0.0022987899999999998 * fTemp936) + ((0.00110995 * fTemp937) + ((0.00124602 * fTemp938) + ((0.00129805 * fTemp939) + ((0.0023355800000000003 * fTemp940) + ((0.0019049100000000001 * fTemp941) + ((0.00050953999999999995 * fTemp942) + ((0.0038312400000000001 * fTemp943) + ((0.0011070699999999999 * fTemp944) + ((0.00059075000000000002 * fTemp945) + ((0.00044511000000000003 * fTemp322) + ((0.0016638 * fTemp948) + ((0.0043739400000000006 * fTemp330) + ((0.0106382 * fTemp949) + ((0.0043469900000000002 * fTemp950) + ((0.0015759000000000001 * fTemp333) + ((0.0073185999999999998 * fTemp334) + ((0.0045973800000000007 * fTemp952) + ((0.013183400000000001 * fTemp335) + ((0.028645500000000001 * fTemp953) + ((0.0092487699999999999 * fTemp338) + ((0.039121700000000002 * fTemp954) + ((0.00144425 * fTemp955) + ((0.0060285 * fTemp956) + ((0.057524800000000001 * fTemp957) + ((0.0013932899999999999 * fTemp342) + ((7.8904099999999995e-07 * fTemp349) + ((3.48346e-05 * fTemp350) + ((5.1851200000000009e-05 * fTemp351) + ((0.000263489 * fTemp962) + ((0.00072508600000000011 * fTemp963) + ((0.00110553 * fTemp964) + ((0.0018638400000000001 * fTemp965) + ((0.00082826600000000003 * fTemp966) + ((0.0013655500000000001 * fTemp967) + ((0.0013615999999999999 * fTemp968) + ((0.00103053 * fTemp969) + ((0.00040302800000000005 * fTemp353) + ((0.0012814900000000001 * fTemp354) + ((0.0015273399999999999 * fTemp970) + ((0.00046550599999999997 * fTemp971) + ((0.00038473700000000001 * fTemp355) + ((0.0010250300000000001 * fTemp356) + ((0.0011346700000000002 * fTemp358) + ((0.00043984100000000006 * fTemp363) + ((0.0016748900000000001 * fTemp973) + ((0.00097958799999999999 * fTemp974) + ((0.00066577900000000002 * fTemp975) + ((0.00120272 * fTemp976) + ((0.0010960700000000002 * fTemp364) + ((0.0013700399999999999 * fTemp978) + ((0.0019637600000000002 * fTemp980) + ((0.0018260300000000002 * fTemp981) + ((0.00238017 * fTemp982) + ((0.0030635300000000001 * fTemp983) + ((0.00021673800000000001 * fTemp367) + ((0.0025982900000000001 * fTemp984) + ((0.0016457800000000001 * fTemp985) + ((0.0013408299999999999 * fTemp986) + ((0.0031654200000000004 * fTemp988) + ((0.00275033 * fTemp989) + ((0.00152893 * fTemp370) + ((0.00068048499999999999 * fTemp371) + ((0.0022063899999999999 * fTemp990) + ((0.00122218 * fTemp372) + ((0.00078379700000000003 * fTemp992) + ((0.00022987799999999998 * fTemp375) + ((0.00078511300000000004 * fTemp380) + ((0.0012260999999999999 * fTemp381) + ((0.0026344099999999998 * fTemp384) + ((0.0038961999999999998 * fTemp386) + ((0.011467400000000001 * fTemp995) + ((0.0078678299999999993 * fTemp996) + ((0.0089890100000000004 * fTemp391) + ((0.0013363100000000001 * fTemp997) + ((0.0143689 * fTemp998) + ((0.0049334100000000001 * fTemp999) + ((0.019686699999999998 * fTemp1000) + ((0.0086390499999999988 * fTemp1001) + ((0.043355600000000001 * fTemp1004) + ((0.00249322 * fTemp1005) + ((0.0141169 * fTemp1006) + ((0.0111431 * fTemp1007) + ((0.0018486100000000001 * fTemp399) + ((0.000976993 * fTemp400) + ((0.0056459800000000001 * fTemp1008) + ((0.00021246900000000004 * fTemp1009) + ((0.00095016999999999996 * fTemp1010) + ((0.0010622000000000001 * fTemp1012) + ((0.00024919200000000002 * fTemp1013) + ((0.00027049600000000001 * fTemp1014) + ((5.1123399999999996e-06 * fTemp404) + ((3.7580000000000003e-05 * fTemp405) + ((1.0426200000000002e-05 * fTemp344) + ((2.5019199999999998e-06 * fTemp1018) + ((0.00041578400000000004 * fTemp407) + ((2.3801800000000003e-05 * fTemp1031) + ((0.00042180200000000004 * fTemp408) + ((0.00064933700000000005 * fTemp409) + ((0.00040693400000000007 * fTemp410) + ((0.00073777800000000002 * fTemp411) + ((0.0013956400000000001 * fTemp412) + ((0.0012716300000000002 * fTemp413) + ((0.0010572399999999999 * fTemp415) + ((0.00096599000000000012 * fTemp416) + ((0.00161012 * fTemp417) + ((0.0016711600000000001 * fTemp418) + ((0.00075290600000000002 * fTemp419) + ((0.00144013 * fTemp420) + ((0.00065036 * fTemp421) + ((0.0021273399999999997 * fTemp422) + ((0.00061597300000000002 * fTemp423) + ((0.0020596199999999999 * fTemp424) + ((0.00011313 * fTemp1033) + ((0.0017438199999999999 * fTemp425) + ((0.0024799100000000001 * fTemp426) + ((0.00130908 * fTemp1034) + ((0.00069698000000000004 * fTemp429) + ((0.0017169000000000002 * fTemp431) + ((0.0011552999999999999 * fTemp1036) + ((1.47262e-06 * fTemp438) + ((0.00048385000000000002 * fTemp451) + ((0.0023706000000000001 * fTemp456) + ((9.940880000000001e-05 * fTemp457) + ((0.00196204 * fTemp1051) + ((1.7742000000000001e-05 * fTemp1052) + ((0.000611186 * fTemp462) + ((0.00047365100000000001 * fTemp1054) + ((0.000687957 * fTemp464) + ((0.00036222200000000004 * fTemp472) + ((0.00092078700000000006 * fTemp488) + ((0.021295600000000001 * fTemp1056) + ((0.0025833200000000001 * fTemp511) + ((0.00054242299999999999 * fTemp512) + ((0.00061493000000000008 * fTemp513) + ((2.9137400000000003e-05 * fTemp514) + ((0.0015830800000000002 * fTemp515) + ((0.0017704200000000002 * fTemp1060) + ((0.0019330199999999999 * fTemp516) + ((0.00156606 * fTemp1062) + ((0.00266146 * fTemp1063) + ((0.0011897800000000001 * fTemp519) + ((0.00307881 * fTemp522) + ((0.0024114100000000001 * fTemp1066) + ((6.3317800000000006e-05 * fTemp523) + ((0.00026003500000000004 * fTemp1067) + ((4.06072e-05 * fTemp524) + ((0.000175864 * fTemp1070) + ((0.000162845 * fTemp527) + ((0.00103864 * fTemp1072) + ((0.0013787300000000001 * fTemp1073) + ((0.00181733 * fTemp1074) + ((0.00293582 * fTemp1075) + ((0.0014793400000000002 * fTemp528) + ((0.021570599999999999 * fTemp1076) + ((0.0043988899999999999 * fTemp1077) + ((0.0073680199999999994 * fTemp531) + ((0.00058021900000000009 * fTemp1078) + ((0.0037306700000000002 * fTemp1079) + ((0.000216524 * fTemp1080) + ((0.00050577300000000005 * fTemp1082) + ((0.00019702400000000002 * fTemp1083) + ((6.4290300000000003e-05 * fTemp1084) + ((0.00256507 * fTemp540) + ((0.000597807 * fTemp543) + ((2.74177e-05 * fTemp1086) + ((0.0018893200000000001 * fTemp544) + ((0.00016075400000000001 * fTemp1092) + ((0.00052814500000000005 * fTemp1093) + ((0.0017080400000000001 * fTemp1095) + ((7.4329200000000013e-05 * fTemp569) + ((0.00048678400000000003 * fTemp1098) + ((0.00094771800000000006 * fTemp1099) + ((0.00085589900000000003 * fTemp1100) + ((0.00015476800000000001 * fTemp574) + ((0.00087519700000000008 * fTemp1108) + ((0.00092920600000000002 * fTemp1126) + ((0.080136100000000002 * fTemp579) + ((0.0088175100000000006 * fTemp580) + ((0.042661300000000006 * fTemp581) + ((0.041393800000000001 * fTemp582) + ((0.097787600000000002 * fTemp583) + ((0.053196100000000003 * fTemp584) + ((0.040092800000000005 * fTemp585) + ((0.077296500000000004 * fTemp586) + ((0.082935599999999998 * fTemp587) + ((0.064767000000000005 * fTemp588) + ((0.00067357800000000009 * fTemp589) + ((0.078489900000000001 * fTemp590) + ((0.00149621 * fTemp1128) + ((0.00072128000000000003 * fTemp591) + ((0.00101019 * fTemp1129) + ((0.000453602 * fTemp592) + ((0.00042969900000000002 * fTemp1130) + ((0.0010723199999999999 * fTemp593) + ((0.00084950300000000004 * fTemp594) + ((0.00085153200000000001 * fTemp595) + ((0.00015027000000000001 * fTemp596) + ((2.4709800000000002e-05 * fTemp286) + ((0.00063317100000000008 * fTemp601) + ((0.0029395300000000001 * fTemp607) + ((0.00025527000000000004 * fTemp618) + ((0.00098456699999999999 * fTemp1134) + ((0.0060422599999999998 * fTemp1135) + ((0.0027149600000000002 * fTemp609) + ((5.1858400000000005e-05 * fTemp611) + ((0.00081970899999999995 * fTemp1138) + ((0.0045739400000000003 * fTemp1139) + ((0.00060354400000000002 * fTemp1140) + ((5.63033e-05 * fTemp616) + (0.0033351100000000001 * fTemp1142))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))); fRec12[0] = std::max<double>((fRec12[1] - fConst0), std::min<double>(6.0, (20.0 * std::log10(std::max<double>(0.00031622776601683794, std::fabs(fTemp1144)))))); fHbargraph1 = FAUSTFLOAT(fRec12[0]); output1[i] = FAUSTFLOAT(fTemp1144); fRec1[1] = fRec1[0]; fRec3[1] = fRec3[0]; fRec2[1] = fRec2[0]; IOTA = (IOTA + 1); fRec4[1] = fRec4[0]; fRec5[1] = fRec5[0]; fRec6[1] = fRec6[0]; fRec7[1] = fRec7[0]; fRec8[1] = fRec8[0]; fRec9[1] = fRec9[0]; fRec10[1] = fRec10[0]; fRec11[1] = fRec11[0]; fRec0[1] = fRec0[0]; fRec12[1] = fRec12[0]; } } }; #ifdef FAUST_UIMACROS #define FAUST_FILE_NAME "ue.binaural.decoder.dsp" #define FAUST_CLASS_NAME "ue_binaural_decoder" #define FAUST_INPUTS 9 #define FAUST_OUTPUTS 2 #define FAUST_ACTIVES 14 #define FAUST_PASSIVES 11 FAUST_ADDCHECKBOX("Inputs/0/ 0/Mute", fCheckbox11); FAUST_ADDVERTICALBARGRAPH("Inputs/0/ 0/", fVbargraph8, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/0/Mute", fCheckbox10); FAUST_ADDCHECKBOX("Inputs/1/ 1/Mute", fCheckbox8); FAUST_ADDVERTICALBARGRAPH("Inputs/1/ 1/", fVbargraph6, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/1/ 2/Mute", fCheckbox9); FAUST_ADDVERTICALBARGRAPH("Inputs/1/ 2/", fVbargraph7, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/1/ 3/Mute", fCheckbox7); FAUST_ADDVERTICALBARGRAPH("Inputs/1/ 3/", fVbargraph5, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/1/Mute", fCheckbox6); FAUST_ADDCHECKBOX("Inputs/2/ 4/Mute", fCheckbox5); FAUST_ADDVERTICALBARGRAPH("Inputs/2/ 4/", fVbargraph4, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/2/ 5/Mute", fCheckbox4); FAUST_ADDVERTICALBARGRAPH("Inputs/2/ 5/", fVbargraph3, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/2/ 6/Mute", fCheckbox3); FAUST_ADDVERTICALBARGRAPH("Inputs/2/ 6/", fVbargraph2, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/2/ 7/Mute", fCheckbox2); FAUST_ADDVERTICALBARGRAPH("Inputs/2/ 7/", fVbargraph1, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/2/ 8/Mute", fCheckbox1); FAUST_ADDVERTICALBARGRAPH("Inputs/2/ 8/", fVbargraph0, -70.0, 6.0); FAUST_ADDCHECKBOX("Inputs/2/Mute", fCheckbox0); FAUST_ADDVERTICALSLIDER("Inputs/Inputs Gain", fVslider1, 0.0, -10.0, 10.0, 0.10000000000000001); FAUST_ADDVERTICALSLIDER("Inputs/Outputs Gain", fVslider0, 0.0, -10.0, 10.0, 0.10000000000000001); FAUST_ADDHORIZONTALBARGRAPH("Outputs/Left/", fHbargraph0, -70.0, 6.0); FAUST_ADDHORIZONTALBARGRAPH("Outputs/Right/", fHbargraph1, -70.0, 6.0); #define FAUST_LIST_ACTIVES(p) \ p(CHECKBOX, Mute, "Inputs/0/ 0/Mute", fCheckbox11, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/0/Mute", fCheckbox10, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/1/ 1/Mute", fCheckbox8, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/1/ 2/Mute", fCheckbox9, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/1/ 3/Mute", fCheckbox7, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/1/Mute", fCheckbox6, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/2/ 4/Mute", fCheckbox5, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/2/ 5/Mute", fCheckbox4, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/2/ 6/Mute", fCheckbox3, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/2/ 7/Mute", fCheckbox2, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/2/ 8/Mute", fCheckbox1, 0.0, 0.0, 1.0, 1.0) \ p(CHECKBOX, Mute, "Inputs/2/Mute", fCheckbox0, 0.0, 0.0, 1.0, 1.0) \ p(VERTICALSLIDER, Inputs_Gain, "Inputs/Inputs Gain", fVslider1, 0.0, -10.0, 10.0, 0.10000000000000001) \ p(VERTICALSLIDER, Outputs_Gain, "Inputs/Outputs Gain", fVslider0, 0.0, -10.0, 10.0, 0.10000000000000001) \ #define FAUST_LIST_PASSIVES(p) \ p(VERTICALBARGRAPH, , "Inputs/0/ 0/", fVbargraph8, 0.0, -70.0, 6.0, 0.0) \ p(VERTICALBARGRAPH, , "Inputs/1/ 1/", fVbargraph6, 0.0, -70.0, 6.0, 0.0) \ p(VERTICALBARGRAPH, , "Inputs/1/ 2/", fVbargraph7, 0.0, -70.0, 6.0, 0.0) \ p(VERTICALBARGRAPH, , "Inputs/1/ 3/", fVbargraph5, 0.0, -70.0, 6.0, 0.0) \ p(VERTICALBARGRAPH, , "Inputs/2/ 4/", fVbargraph4, 0.0, -70.0, 6.0, 0.0) \ p(VERTICALBARGRAPH, , "Inputs/2/ 5/", fVbargraph3, 0.0, -70.0, 6.0, 0.0) \ p(VERTICALBARGRAPH, , "Inputs/2/ 6/", fVbargraph2, 0.0, -70.0, 6.0, 0.0) \ p(VERTICALBARGRAPH, , "Inputs/2/ 7/", fVbargraph1, 0.0, -70.0, 6.0, 0.0) \ p(VERTICALBARGRAPH, , "Inputs/2/ 8/", fVbargraph0, 0.0, -70.0, 6.0, 0.0) \ p(HORIZONTALBARGRAPH, , "Outputs/Left/", fHbargraph0, 0.0, -70.0, 6.0, 0.0) \ p(HORIZONTALBARGRAPH, , "Outputs/Right/", fHbargraph1, 0.0, -70.0, 6.0, 0.0) \ #endif /***************************END USER SECTION ***************************/ /*******************BEGIN ARCHITECTURE SECTION (part 2/2)***************/ /* Faust code wrapper ------- */ #include "ext.h" #include "ext_obex.h" #include "z_dsp.h" #include "jpatcher_api.h" #include <string.h> #define ASSIST_INLET 1 #define ASSIST_OUTLET 2 #define EXTERNAL_VERSION "0.77" #define STR_SIZE 512 /************************** BEGIN MidiUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef FAUST_MIDIUI_H #define FAUST_MIDIUI_H #include <vector> #include <string> #include <utility> #include <iostream> #include <cstdlib> #include <cmath> /************************** BEGIN MapUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef FAUST_MAPUI_H #define FAUST_MAPUI_H #include <vector> #include <map> #include <string> /******************************************************************************* * MapUI : Faust User Interface * This class creates a map of complete hierarchical path and zones for each UI items. ******************************************************************************/ class MapUI : public UI, public PathBuilder { protected: // Complete path map std::map<std::string, FAUSTFLOAT*> fPathZoneMap; // Label zone map std::map<std::string, FAUSTFLOAT*> fLabelZoneMap; public: MapUI() {} virtual ~MapUI() {} // -- widget's layouts void openTabBox(const char* label) { pushLabel(label); } void openHorizontalBox(const char* label) { pushLabel(label); } void openVerticalBox(const char* label) { pushLabel(label); } void closeBox() { popLabel(); } // -- active widgets void addButton(const char* label, FAUSTFLOAT* zone) { fPathZoneMap[buildPath(label)] = zone; fLabelZoneMap[label] = zone; } void addCheckButton(const char* label, FAUSTFLOAT* zone) { fPathZoneMap[buildPath(label)] = zone; fLabelZoneMap[label] = zone; } void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { fPathZoneMap[buildPath(label)] = zone; fLabelZoneMap[label] = zone; } void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { fPathZoneMap[buildPath(label)] = zone; fLabelZoneMap[label] = zone; } void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { fPathZoneMap[buildPath(label)] = zone; fLabelZoneMap[label] = zone; } // -- passive widgets void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax) { fPathZoneMap[buildPath(label)] = zone; fLabelZoneMap[label] = zone; } void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax) { fPathZoneMap[buildPath(label)] = zone; fLabelZoneMap[label] = zone; } // -- soundfiles virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) {} // -- metadata declarations void declare(FAUSTFLOAT* zone, const char* key, const char* val) {} // set/get void setParamValue(const std::string& path, FAUSTFLOAT value) { if (fPathZoneMap.find(path) != fPathZoneMap.end()) { *fPathZoneMap[path] = value; } else if (fLabelZoneMap.find(path) != fLabelZoneMap.end()) { *fLabelZoneMap[path] = value; } } FAUSTFLOAT getParamValue(const std::string& path) { if (fPathZoneMap.find(path) != fPathZoneMap.end()) { return *fPathZoneMap[path]; } else if (fLabelZoneMap.find(path) != fLabelZoneMap.end()) { return *fLabelZoneMap[path]; } else { return FAUSTFLOAT(0); } } // map access std::map<std::string, FAUSTFLOAT*>& getMap() { return fPathZoneMap; } int getParamsCount() { return int(fPathZoneMap.size()); } std::string getParamAddress(int index) { std::map<std::string, FAUSTFLOAT*>::iterator it = fPathZoneMap.begin(); while (index-- > 0 && it++ != fPathZoneMap.end()) {} return (*it).first; } std::string getParamAddress(FAUSTFLOAT* zone) { std::map<std::string, FAUSTFLOAT*>::iterator it = fPathZoneMap.begin(); do { if ((*it).second == zone) return (*it).first; } while (it++ != fPathZoneMap.end()); return ""; } static bool endsWith(std::string const& str, std::string const& end) { size_t l1 = str.length(); size_t l2 = end.length(); return (l1 >= l2) && (0 == str.compare(l1 - l2, l2, end)); } }; #endif // FAUST_MAPUI_H /************************** END MapUI.h **************************/ /************************** BEGIN midi.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __midi__ #define __midi__ #include <vector> #include <string> #include <algorithm> #include <assert.h> class MapUI; /************************************* A time-stamped short MIDI message **************************************/ // Force contiguous memory layout #pragma pack (push, 1) struct MIDIMessage { uint32_t frameIndex; uint8_t byte0, byte1, byte2; }; #pragma pack (pop) /******************************************************************************* * MIDI processor definition. * * MIDI input or output handling classes will implement this interface, * so the same method names (keyOn, ctrlChange...) will be used either * when decoding MIDI input or encoding MIDI output events. *******************************************************************************/ class midi { public: midi() {} virtual ~midi() {} // Additional time-stamped API for MIDI input virtual MapUI* keyOn(double, int channel, int pitch, int velocity) { return keyOn(channel, pitch, velocity); } virtual void keyOff(double, int channel, int pitch, int velocity = 127) { keyOff(channel, pitch, velocity); } virtual void keyPress(double, int channel, int pitch, int press) { keyPress(channel, pitch, press); } virtual void chanPress(double date, int channel, int press) { chanPress(channel, press); } virtual void pitchWheel(double, int channel, int wheel) { pitchWheel(channel, wheel); } virtual void ctrlChange(double, int channel, int ctrl, int value) { ctrlChange(channel, ctrl, value); } virtual void ctrlChange14bits(double, int channel, int ctrl, int value) { ctrlChange14bits(channel, ctrl, value); } virtual void rpn(double, int channel, int ctrl, int value) { rpn(channel, ctrl, value); } virtual void progChange(double, int channel, int pgm) { progChange(channel, pgm); } virtual void sysEx(double, std::vector<unsigned char>& message) { sysEx(message); } // MIDI sync virtual void startSync(double date) {} virtual void stopSync(double date) {} virtual void clock(double date) {} // Standard MIDI API virtual MapUI* keyOn(int channel, int pitch, int velocity) { return nullptr; } virtual void keyOff(int channel, int pitch, int velocity) {} virtual void keyPress(int channel, int pitch, int press) {} virtual void chanPress(int channel, int press) {} virtual void ctrlChange(int channel, int ctrl, int value) {} virtual void ctrlChange14bits(int channel, int ctrl, int value) {} virtual void rpn(int channel, int ctrl, int value) {} virtual void pitchWheel(int channel, int wheel) {} virtual void progChange(int channel, int pgm) {} virtual void sysEx(std::vector<unsigned char>& message) {} enum MidiStatus { // channel voice messages MIDI_NOTE_OFF = 0x80, MIDI_NOTE_ON = 0x90, MIDI_CONTROL_CHANGE = 0xB0, MIDI_PROGRAM_CHANGE = 0xC0, MIDI_PITCH_BEND = 0xE0, MIDI_AFTERTOUCH = 0xD0, // aka channel pressure MIDI_POLY_AFTERTOUCH = 0xA0, // aka key pressure MIDI_CLOCK = 0xF8, MIDI_START = 0xFA, MIDI_CONT = 0xFB, MIDI_STOP = 0xFC, MIDI_SYSEX_START = 0xF0, MIDI_SYSEX_STOP = 0xF7 }; enum MidiCtrl { ALL_NOTES_OFF = 123, ALL_SOUND_OFF = 120 }; enum MidiNPN { PITCH_BEND_RANGE = 0 }; }; /* A class to decode NRPN and RPN messages, adapted from JUCE forum message: https://forum.juce.com/t/14bit-midi-controller-support/11517 */ class MidiNRPN { private: bool ctrlnew; int ctrlnum; int ctrlval; int nrpn_lsb, nrpn_msb; int data_lsb, data_msb; enum { midi_nrpn_lsb = 98, midi_nrpn_msb = 99, midi_rpn_lsb = 100, midi_rpn_msb = 101, midi_data_lsb = 38, midi_data_msb = 6 }; public: MidiNRPN(): ctrlnew(false), nrpn_lsb(-1), nrpn_msb(-1), data_lsb(-1), data_msb(-1) {} // return true if the message has been filtered bool process(int data1, int data2) { switch (data1) { case midi_nrpn_lsb: nrpn_lsb = data2; return true; case midi_nrpn_msb: nrpn_msb = data2; return true; case midi_rpn_lsb: { if (data2 == 127) { nrpn_lsb = data_lsb = -1; } else { nrpn_lsb = 0; data_lsb = -1; } return true; } case midi_rpn_msb: { if (data2 == 127) { nrpn_msb = data_msb = -1; } else { nrpn_msb = 0; data_msb = -1; } return true; } case midi_data_lsb: case midi_data_msb: { if (data1 == midi_data_msb) { if (nrpn_msb < 0) { return false; } data_msb = data2; } else { // midi_data_lsb if (nrpn_lsb < 0) { return false; } data_lsb = data2; } if (data_lsb >= 0 && data_msb >= 0) { ctrlnum = (nrpn_msb << 7) | nrpn_lsb; ctrlval = (data_msb << 7) | data_lsb; data_lsb = data_msb = -1; nrpn_msb = nrpn_lsb = -1; ctrlnew = true; } return true; } default: return false; }; } bool hasNewNRPN() { bool res = ctrlnew; ctrlnew = false; return res; } // results in [0, 16383] int getCtrl() const { return ctrlnum; } int getVal() const { return ctrlval; } }; /**************************************************** * Base class for MIDI input handling. * * Shared common code used for input handling: * - decoding Real-Time messages: handleSync * - decoding one data byte messages: handleData1 * - decoding two data byte messages: handleData2 * - getting ready messages in polling mode ****************************************************/ class midi_handler : public midi { protected: std::vector<midi*> fMidiInputs; std::string fName; MidiNRPN fNRPN; int range(int min, int max, int val) { return (val < min) ? min : ((val >= max) ? max : val); } public: midi_handler(const std::string& name = "MIDIHandler"):fName(name) {} virtual ~midi_handler() {} void addMidiIn(midi* midi_dsp) { if (midi_dsp) fMidiInputs.push_back(midi_dsp); } void removeMidiIn(midi* midi_dsp) { std::vector<midi*>::iterator it = std::find(fMidiInputs.begin(), fMidiInputs.end(), midi_dsp); if (it != fMidiInputs.end()) { fMidiInputs.erase(it); } } // Those 2 methods have to be implemented by subclasses virtual bool startMidi() { return true; } virtual void stopMidi() {} void setName(const std::string& name) { fName = name; } std::string getName() { return fName; } // To be used in polling mode virtual int recvMessages(std::vector<MIDIMessage>* message) { return 0; } virtual void sendMessages(std::vector<MIDIMessage>* message, int count) {} // MIDI Real-Time void handleClock(double time) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->clock(time); } } void handleStart(double time) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->startSync(time); } } void handleStop(double time) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->stopSync(time); } } void handleSync(double time, int type) { if (type == MIDI_CLOCK) { handleClock(time); // We can consider start and continue as identical messages } else if ((type == MIDI_START) || (type == MIDI_CONT)) { handleStart(time); } else if (type == MIDI_STOP) { handleStop(time); } } // MIDI 1 data void handleProgChange(double time, int channel, int data1) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->progChange(time, channel, data1); } } void handleAfterTouch(double time, int channel, int data1) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->chanPress(time, channel, data1); } } void handleData1(double time, int type, int channel, int data1) { if (type == MIDI_PROGRAM_CHANGE) { handleProgChange(time, channel, data1); } else if (type == MIDI_AFTERTOUCH) { handleAfterTouch(time, channel, data1); } } // MIDI 2 datas void handleKeyOff(double time, int channel, int data1, int data2) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->keyOff(time, channel, data1, data2); } } void handleKeyOn(double time, int channel, int data1, int data2) { if (data2 == 0) { handleKeyOff(time, channel, data1, data2); } else { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->keyOn(time, channel, data1, data2); } } } void handleCtrlChange(double time, int channel, int data1, int data2) { // Special processing for NRPN and RPN if (fNRPN.process(data1, data2)) { if (fNRPN.hasNewNRPN()) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->rpn(time, channel, fNRPN.getCtrl(), fNRPN.getVal()); } } } else { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->ctrlChange(time, channel, data1, data2); } } } void handlePitchWheel(double time, int channel, int data1, int data2) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->pitchWheel(time, channel, (data2 << 7) + data1); } } void handlePitchWheel(double time, int channel, int bend) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->pitchWheel(time, channel, bend); } } void handlePolyAfterTouch(double time, int channel, int data1, int data2) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->keyPress(time, channel, data1, data2); } } void handleData2(double time, int type, int channel, int data1, int data2) { if (type == MIDI_NOTE_OFF) { handleKeyOff(time, channel, data1, data2); } else if (type == MIDI_NOTE_ON) { handleKeyOn(time, channel, data1, data2); } else if (type == MIDI_CONTROL_CHANGE) { handleCtrlChange(time, channel, data1, data2); } else if (type == MIDI_PITCH_BEND) { handlePitchWheel(time, channel, data1, data2); } else if (type == MIDI_POLY_AFTERTOUCH) { handlePolyAfterTouch(time, channel, data1, data2); } } // SysEx void handleSysex(double time, std::vector<unsigned char>& message) { for (unsigned int i = 0; i < fMidiInputs.size(); i++) { fMidiInputs[i]->sysEx(time, message); } } void handleMessage(double time, int type, std::vector<unsigned char>& message) { if (type == MIDI_SYSEX_START) { handleSysex(time, message); } } }; //------------------------------- // For timestamped MIDI messages //------------------------------- struct DatedMessage { double fDate; unsigned char fBuffer[3]; size_t fSize; DatedMessage(double date, unsigned char* buffer, size_t size) :fDate(date), fSize(size) { assert(size <= 3); memcpy(fBuffer, buffer, size); } DatedMessage():fDate(0.0), fSize(0) {} }; #endif // __midi__ /************************** END midi.h **************************/ #ifdef _MSC_VER #define gsscanf sscanf_s #else #define gsscanf sscanf #endif /***************************************************************************** * Helper code for MIDI meta and polyphonic 'nvoices' parsing ******************************************************************************/ struct MidiMeta : public Meta, public std::map<std::string, std::string> { void declare(const char* key, const char* value) { (*this)[key] = value; } const std::string get(const char* key, const char* def) { return (this->find(key) != this->end()) ? (*this)[key] : def; } static void analyse(dsp* mono_dsp, bool& midi_sync, int& nvoices) { JSONUI jsonui; mono_dsp->buildUserInterface(&jsonui); std::string json = jsonui.JSON(); midi_sync = ((json.find("midi") != std::string::npos) && ((json.find("start") != std::string::npos) || (json.find("stop") != std::string::npos) || (json.find("clock") != std::string::npos) || (json.find("timestamp") != std::string::npos))); #if defined(NVOICES) && NVOICES!=NUM_VOICES nvoices = NVOICES; #else MidiMeta meta; mono_dsp->metadata(&meta); bool found_voices = false; // If "options" metadata is used std::string options = meta.get("options", ""); if (options != "") { std::map<std::string, std::string> metadata; std::string res; MetaDataUI::extractMetadata(options, res, metadata); if (metadata.find("nvoices") != metadata.end()) { nvoices = std::atoi(metadata["nvoices"].c_str()); found_voices = true; } } // Otherwise test for "nvoices" metadata if (!found_voices) { std::string numVoices = meta.get("nvoices", "0"); nvoices = std::atoi(numVoices.c_str()); } nvoices = std::max<int>(0, nvoices); #endif } static bool checkPolyphony(dsp* mono_dsp) { MapUI map_ui; mono_dsp->buildUserInterface(&map_ui); bool has_freq = false; bool has_gate = false; bool has_gain = false; for (int i = 0; i < map_ui.getParamsCount(); i++) { std::string path = map_ui.getParamAddress(i); has_freq |= MapUI::endsWith(path, "/freq"); has_gate |= MapUI::endsWith(path, "/gate"); has_gain |= MapUI::endsWith(path, "/gain"); } return (has_freq && has_gate && has_gain); } }; /******************************************************************************* * MidiUI : Faust User Interface * This class decodes MIDI meta data and maps incoming MIDI messages to them. * Currently ctrl, keyon/keyoff, keypress, pgm, chanpress, pitchwheel/pitchbend * start/stop/clock meta data is handled. ******************************************************************************/ class uiMidi { friend class MidiUI; protected: midi* fMidiOut; bool fInputCtrl; int fChan; // To be used when sending messages, returns the effective chan, or 0 when fChan is initialized with -1 (means 'all chans') int rangeChan() { return (((fChan < 0) || (fChan > 15)) ? 0 : fChan); } bool inRange(FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT v) { return (min <= v && v <= max); } public: uiMidi(midi* midi_out, bool input, int chan = -1):fMidiOut(midi_out), fInputCtrl(input), fChan(chan) {} virtual ~uiMidi() {} }; /***************************************************************************** * Base class for MIDI aware UI items ******************************************************************************/ class uiMidiItem : public uiMidi, public uiItem { public: uiMidiItem(midi* midi_out, GUI* ui, FAUSTFLOAT* zone, bool input = true, int chan = -1) :uiMidi(midi_out, input, chan), uiItem(ui, zone) {} virtual ~uiMidiItem() {} virtual void reflectZone() {} }; /***************************************************************************** * Base class for MIDI aware UI items with timestamp support ******************************************************************************/ class uiMidiTimedItem : public uiMidi, public uiTimedItem { public: uiMidiTimedItem(midi* midi_out, GUI* ui, FAUSTFLOAT* zone, bool input = true, int chan = -1) :uiMidi(midi_out, input, chan), uiTimedItem(ui, zone) {} virtual ~uiMidiTimedItem() {} virtual void reflectZone() {} }; //----------- // MIDI sync //----------- class uiMidiStart : public uiMidiTimedItem { public: uiMidiStart(midi* midi_out, GUI* ui, FAUSTFLOAT* zone, bool input = true) :uiMidiTimedItem(midi_out, ui, zone, input) {} virtual ~uiMidiStart() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; if (v != FAUSTFLOAT(0)) { fMidiOut->startSync(0); } } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl) { uiItem::modifyZone(FAUSTFLOAT(v)); } } }; class uiMidiStop : public uiMidiTimedItem { public: uiMidiStop(midi* midi_out, GUI* ui, FAUSTFLOAT* zone, bool input = true) :uiMidiTimedItem(midi_out, ui, zone, input) {} virtual ~uiMidiStop() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; if (v != FAUSTFLOAT(1)) { fMidiOut->stopSync(0); } } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl) { uiItem::modifyZone(FAUSTFLOAT(v)); } } }; class uiMidiClock : public uiMidiTimedItem { private: bool fState; public: uiMidiClock(midi* midi_out, GUI* ui, FAUSTFLOAT* zone, bool input = true) :uiMidiTimedItem(midi_out, ui, zone, input), fState(false) {} virtual ~uiMidiClock() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; fMidiOut->clock(0); } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl) { fState = !fState; uiMidiTimedItem::modifyZone(date, FAUSTFLOAT(fState)); } } }; //---------------------- // Standard MIDI events //---------------------- //--------------------------------------------- // uiMidiProgChange uses the [min...max] range //--------------------------------------------- class uiMidiProgChange : public uiMidiTimedItem { public: FAUSTFLOAT fMin, fMax; uiMidiProgChange(midi* midi_out, GUI* ui, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max, bool input = true, int chan = -1) :uiMidiTimedItem(midi_out, ui, zone, input, chan), fMin(min), fMax(max) {} virtual ~uiMidiProgChange() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; if (inRange(fMin, fMax, v)) { fMidiOut->progChange(rangeChan(), v); } } void modifyZone(FAUSTFLOAT v) { if (fInputCtrl && inRange(fMin, fMax, v)) { uiItem::modifyZone(v); } } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl && inRange(fMin, fMax, v)) { uiMidiTimedItem::modifyZone(date, v); } } }; class uiMidiChanPress : public uiMidiTimedItem { private: int fPress; public: uiMidiChanPress(midi* midi_out, int press, GUI* ui, FAUSTFLOAT* zone, bool input = true, int chan = -1) :uiMidiTimedItem(midi_out, ui, zone, input, chan), fPress(press) {} virtual ~uiMidiChanPress() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; if (v != FAUSTFLOAT(0)) { fMidiOut->chanPress(rangeChan(), fPress); } } }; //------------------------------------------------------ // uiMidiCtrlChange does scale (kLin/kLog/kExp) mapping //------------------------------------------------------ class uiMidiCtrlChange : public uiMidiTimedItem, public uiConverter { private: int fCtrl; public: uiMidiCtrlChange(midi* midi_out, int ctrl, GUI* ui, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max, bool input = true, MetaDataUI::Scale scale = MetaDataUI::kLin, int chan = -1) :uiMidiTimedItem(midi_out, ui, zone, input, chan), uiConverter(scale, 0., 127., min, max), fCtrl(ctrl) {} virtual ~uiMidiCtrlChange() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; fMidiOut->ctrlChange(rangeChan(), fCtrl, fConverter->faust2ui(v)); } void modifyZone(FAUSTFLOAT v) { if (fInputCtrl) { uiItem::modifyZone(FAUSTFLOAT(fConverter->ui2faust(v))); } } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl) { uiMidiTimedItem::modifyZone(date, FAUSTFLOAT(fConverter->ui2faust(v))); } } }; class uiMidiPitchWheel : public uiMidiTimedItem { private: LinearValueConverter2 fConverter; public: uiMidiPitchWheel(midi* midi_out, GUI* ui, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max, bool input = true, int chan = -1) :uiMidiTimedItem(midi_out, ui, zone, input, chan) { if (min <= 0 && max >= 0) { fConverter = LinearValueConverter2(0., 8191., 16383., double(min), 0., double(max)); } else { // Degenerated case... fConverter = LinearValueConverter2(0., 8191., 16383., double(min),double(min + (max - min)/FAUSTFLOAT(2)), double(max)); } } virtual ~uiMidiPitchWheel() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; fMidiOut->pitchWheel(rangeChan(), fConverter.faust2ui(v)); } void modifyZone(FAUSTFLOAT v) { if (fInputCtrl) { uiItem::modifyZone(FAUSTFLOAT(fConverter.ui2faust(v))); } } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl) { uiMidiTimedItem::modifyZone(FAUSTFLOAT(fConverter.ui2faust(v))); } } void setRange(int val) { double semi = (val / 128) + ((val % 128) / 100.); fConverter.setMappingValues(0., 8191., 16383., -semi, 0., semi); } }; //-------------------------------------------------------------- // uiMidiKeyOn does scale (kLin/kLog/kExp) mapping for velocity //-------------------------------------------------------------- class uiMidiKeyOn : public uiMidiTimedItem, public uiConverter { private: int fKeyOn; public: uiMidiKeyOn(midi* midi_out, int key, GUI* ui, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max, bool input = true, MetaDataUI::Scale scale = MetaDataUI::kLin, int chan = -1) :uiMidiTimedItem(midi_out, ui, zone, input, chan), uiConverter(scale, 0., 127., min, max), fKeyOn(key) {} virtual ~uiMidiKeyOn() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; fMidiOut->keyOn(rangeChan(), fKeyOn, fConverter->faust2ui(v)); } void modifyZone(FAUSTFLOAT v) { if (fInputCtrl) { uiItem::modifyZone(FAUSTFLOAT(fConverter->ui2faust(v))); } } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl) { uiMidiTimedItem::modifyZone(date, FAUSTFLOAT(fConverter->ui2faust(v))); } } }; //--------------------------------------------------------------- // uiMidiKeyOff does scale (kLin/kLog/kExp) mapping for velocity //--------------------------------------------------------------- class uiMidiKeyOff : public uiMidiTimedItem, public uiConverter { private: int fKeyOff; public: uiMidiKeyOff(midi* midi_out, int key, GUI* ui, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max, bool input = true, MetaDataUI::Scale scale = MetaDataUI::kLin, int chan = -1) :uiMidiTimedItem(midi_out, ui, zone, input, chan), uiConverter(scale, 0., 127., min, max), fKeyOff(key) {} virtual ~uiMidiKeyOff() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; fMidiOut->keyOff(rangeChan(), fKeyOff, fConverter->faust2ui(v)); } void modifyZone(FAUSTFLOAT v) { if (fInputCtrl) { uiItem::modifyZone(FAUSTFLOAT(fConverter->ui2faust(v))); } } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl) { uiMidiTimedItem::modifyZone(date, FAUSTFLOAT(fConverter->ui2faust(v))); } } }; //----------------------------------------------------------------- // uiMidiKeyPress does scale (kLin/kLog/kExp) mapping for velocity //----------------------------------------------------------------- class uiMidiKeyPress : public uiMidiTimedItem, public uiConverter { private: int fKey; public: uiMidiKeyPress(midi* midi_out, int key, GUI* ui, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max, bool input = true, MetaDataUI::Scale scale = MetaDataUI::kLin, int chan = -1) :uiMidiTimedItem(midi_out, ui, zone, input, chan), uiConverter(scale, 0., 127., min, max), fKey(key) {} virtual ~uiMidiKeyPress() {} virtual void reflectZone() { FAUSTFLOAT v = *fZone; fCache = v; fMidiOut->keyPress(rangeChan(), fKey, fConverter->faust2ui(v)); } void modifyZone(FAUSTFLOAT v) { if (fInputCtrl) { uiItem::modifyZone(FAUSTFLOAT(fConverter->ui2faust(v))); } } void modifyZone(double date, FAUSTFLOAT v) { if (fInputCtrl) { uiMidiTimedItem::modifyZone(date, FAUSTFLOAT(fConverter->ui2faust(v))); } } }; /****************************************************************************************** * MidiUI : Faust User Interface * This class decodes MIDI metadata and maps incoming MIDI messages to them. * Currently ctrl, keyon/keyoff, keypress, pgm, chanpress, pitchwheel/pitchbend * start/stop/clock meta data are handled. * * Maps associating MIDI event ID (like each ctrl number) with all MIDI aware UI items * are defined and progressively filled when decoding MIDI related metadata. * MIDI aware UI items are used in both directions: * - modifying their internal state when receving MIDI input events * - sending their internal state as MIDI output events *******************************************************************************************/ class MidiUI : public GUI, public midi, public MetaDataUI { // Add uiItem subclasses objects are deallocated by the inherited GUI class typedef std::map <int, std::vector<uiMidiCtrlChange*> > TCtrlChangeTable; typedef std::vector<uiMidiProgChange*> TProgChangeTable; typedef std::map <int, std::vector<uiMidiChanPress*> > TChanPressTable; typedef std::map <int, std::vector<uiMidiKeyOn*> > TKeyOnTable; typedef std::map <int, std::vector<uiMidiKeyOff*> > TKeyOffTable; typedef std::map <int, std::vector<uiMidiKeyPress*> > TKeyPressTable; typedef std::vector<uiMidiPitchWheel*> TPitchWheelTable; protected: TCtrlChangeTable fCtrlChangeTable; TProgChangeTable fProgChangeTable; TChanPressTable fChanPressTable; TKeyOnTable fKeyOnTable; TKeyOffTable fKeyOffTable; TKeyOnTable fKeyTable; TKeyPressTable fKeyPressTable; TPitchWheelTable fPitchWheelTable; std::vector<uiMidiStart*> fStartTable; std::vector<uiMidiStop*> fStopTable; std::vector<uiMidiClock*> fClockTable; std::vector<std::pair <std::string, std::string> > fMetaAux; midi_handler* fMidiHandler; bool fDelete; bool fTimeStamp; void addGenericZone(FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max, bool input = true) { if (fMetaAux.size() > 0) { for (size_t i = 0; i < fMetaAux.size(); i++) { unsigned num; unsigned chan; if (fMetaAux[i].first == "midi") { if (gsscanf(fMetaAux[i].second.c_str(), "ctrl %u %u", &num, &chan) == 2) { fCtrlChangeTable[num].push_back(new uiMidiCtrlChange(fMidiHandler, num, this, zone, min, max, input, getScale(zone), chan)); } else if (gsscanf(fMetaAux[i].second.c_str(), "ctrl %u", &num) == 1) { fCtrlChangeTable[num].push_back(new uiMidiCtrlChange(fMidiHandler, num, this, zone, min, max, input, getScale(zone))); } else if (gsscanf(fMetaAux[i].second.c_str(), "keyon %u %u", &num, &chan) == 2) { fKeyOnTable[num].push_back(new uiMidiKeyOn(fMidiHandler, num, this, zone, min, max, input, getScale(zone), chan)); } else if (gsscanf(fMetaAux[i].second.c_str(), "keyon %u", &num) == 1) { fKeyOnTable[num].push_back(new uiMidiKeyOn(fMidiHandler, num, this, zone, min, max, input, getScale(zone))); } else if (gsscanf(fMetaAux[i].second.c_str(), "keyoff %u %u", &num, &chan) == 2) { fKeyOffTable[num].push_back(new uiMidiKeyOff(fMidiHandler, num, this, zone, min, max, input, getScale(zone), chan)); } else if (gsscanf(fMetaAux[i].second.c_str(), "keyoff %u", &num) == 1) { fKeyOffTable[num].push_back(new uiMidiKeyOff(fMidiHandler, num, this, zone, min, max, input, getScale(zone))); } else if (gsscanf(fMetaAux[i].second.c_str(), "key %u %u", &num, &chan) == 2) { fKeyTable[num].push_back(new uiMidiKeyOn(fMidiHandler, num, this, zone, min, max, input, getScale(zone), chan)); } else if (gsscanf(fMetaAux[i].second.c_str(), "key %u", &num) == 1) { fKeyTable[num].push_back(new uiMidiKeyOn(fMidiHandler, num, this, zone, min, max, input, getScale(zone))); } else if (gsscanf(fMetaAux[i].second.c_str(), "keypress %u %u", &num, &chan) == 2) { fKeyPressTable[num].push_back(new uiMidiKeyPress(fMidiHandler, num, this, zone, min, max, input, getScale(zone), chan)); } else if (gsscanf(fMetaAux[i].second.c_str(), "keypress %u", &num) == 1) { fKeyPressTable[num].push_back(new uiMidiKeyPress(fMidiHandler, num, this, zone, min, max, input, getScale(zone))); } else if (gsscanf(fMetaAux[i].second.c_str(), "pgm %u", &chan) == 1) { fProgChangeTable.push_back(new uiMidiProgChange(fMidiHandler, this, zone, min, max, input, chan)); } else if (strcmp(fMetaAux[i].second.c_str(), "pgm") == 0) { fProgChangeTable.push_back(new uiMidiProgChange(fMidiHandler, this, zone, min, max, input)); } else if (gsscanf(fMetaAux[i].second.c_str(), "chanpress %u %u", &num, &chan) == 2) { fChanPressTable[num].push_back(new uiMidiChanPress(fMidiHandler, num, this, zone, input, chan)); } else if (gsscanf(fMetaAux[i].second.c_str(), "chanpress %u", &num) == 1) { fChanPressTable[num].push_back(new uiMidiChanPress(fMidiHandler, num, this, zone, input)); } else if ((gsscanf(fMetaAux[i].second.c_str(), "pitchwheel %u", &chan) == 1) || (gsscanf(fMetaAux[i].second.c_str(), "pitchbend %u", &chan) == 1)) { fPitchWheelTable.push_back(new uiMidiPitchWheel(fMidiHandler, this, zone, min, max, input, chan)); } else if ((fMetaAux[i].second == "pitchwheel") || (fMetaAux[i].second == "pitchbend")) { fPitchWheelTable.push_back(new uiMidiPitchWheel(fMidiHandler, this, zone, min, max, input)); // MIDI sync } else if (fMetaAux[i].second == "start") { fStartTable.push_back(new uiMidiStart(fMidiHandler, this, zone, input)); } else if (fMetaAux[i].second == "stop") { fStopTable.push_back(new uiMidiStop(fMidiHandler, this, zone, input)); } else if (fMetaAux[i].second == "clock") { fClockTable.push_back(new uiMidiClock(fMidiHandler, this, zone, input)); // Explicit metadata to activate 'timestamp' mode } else if (fMetaAux[i].second == "timestamp") { fTimeStamp = true; } } } } fMetaAux.clear(); } template <typename TABLE> void updateTable1(TABLE& table, double date, int channel, int val1) { for (size_t i = 0; i < table.size(); i++) { int channel_aux = table[i]->fChan; if (channel_aux == -1 || channel == channel_aux) { if (fTimeStamp) { table[i]->modifyZone(date, FAUSTFLOAT(val1)); } else { table[i]->modifyZone(FAUSTFLOAT(val1)); } } } } template <typename TABLE> void updateTable2(TABLE& table, double date, int channel, int val1, int val2) { if (table.find(val1) != table.end()) { for (size_t i = 0; i < table[val1].size(); i++) { int channel_aux = table[val1][i]->fChan; if (channel_aux == -1 || channel == channel_aux) { if (fTimeStamp) { table[val1][i]->modifyZone(date, FAUSTFLOAT(val2)); } else { table[val1][i]->modifyZone(FAUSTFLOAT(val2)); } } } } } public: MidiUI(midi_handler* midi_handler, bool delete_handler = false) { fMidiHandler = midi_handler; fMidiHandler->addMidiIn(this); fDelete = delete_handler; fTimeStamp = false; } virtual ~MidiUI() { fMidiHandler->removeMidiIn(this); if (fDelete) delete fMidiHandler; } bool run() { return fMidiHandler->startMidi(); } void stop() { fMidiHandler->stopMidi(); } void addMidiIn(midi* midi_dsp) { fMidiHandler->addMidiIn(midi_dsp); } void removeMidiIn(midi* midi_dsp) { fMidiHandler->removeMidiIn(midi_dsp); } // -- active widgets virtual void addButton(const char* label, FAUSTFLOAT* zone) { addGenericZone(zone, FAUSTFLOAT(0), FAUSTFLOAT(1)); } virtual void addCheckButton(const char* label, FAUSTFLOAT* zone) { addGenericZone(zone, FAUSTFLOAT(0), FAUSTFLOAT(1)); } virtual void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addGenericZone(zone, min, max); } virtual void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addGenericZone(zone, min, max); } virtual void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addGenericZone(zone, min, max); } // -- passive widgets virtual void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { addGenericZone(zone, min, max, false); } virtual void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { addGenericZone(zone, min, max, false); } // -- metadata declarations virtual void declare(FAUSTFLOAT* zone, const char* key, const char* val) { MetaDataUI::declare(zone, key, val); fMetaAux.push_back(std::make_pair(key, val)); } // -- MIDI API void key(double date, int channel, int note, int velocity) { updateTable2<TKeyOnTable>(fKeyTable, date, channel, note, velocity); } MapUI* keyOn(double date, int channel, int note, int velocity) { updateTable2<TKeyOnTable>(fKeyOnTable, date, channel, note, velocity); // If note is in fKeyTable, handle it as a keyOn key(date, channel, note, velocity); return nullptr; } void keyOff(double date, int channel, int note, int velocity) { updateTable2<TKeyOffTable>(fKeyOffTable, date, channel, note, velocity); // If note is in fKeyTable, handle it as a keyOff with a 0 velocity key(date, channel, note, 0); } void ctrlChange(double date, int channel, int ctrl, int value) { updateTable2<TCtrlChangeTable>(fCtrlChangeTable, date, channel, ctrl, value); } void rpn(double date, int channel, int ctrl, int value) { if (ctrl == midi::PITCH_BEND_RANGE) { for (size_t i = 0; i < fPitchWheelTable.size(); i++) { int channel_aux = fPitchWheelTable[i]->fChan; if (channel_aux == -1 || channel == channel_aux) { fPitchWheelTable[i]->setRange(value); } } } } void progChange(double date, int channel, int pgm) { updateTable1<TProgChangeTable>(fProgChangeTable, date, channel, pgm); } void pitchWheel(double date, int channel, int wheel) { updateTable1<TPitchWheelTable>(fPitchWheelTable, date, channel, wheel); } void keyPress(double date, int channel, int pitch, int press) { updateTable2<TKeyPressTable>(fKeyPressTable, date, channel, pitch, press); } void chanPress(double date, int channel, int press) { updateTable2<TChanPressTable>(fChanPressTable, date, channel, press, FAUSTFLOAT(1)); } void ctrlChange14bits(double date, int channel, int ctrl, int value) {} // MIDI sync void startSync(double date) { for (size_t i = 0; i < fStartTable.size(); i++) { fStartTable[i]->modifyZone(date, FAUSTFLOAT(1)); } } void stopSync(double date) { for (size_t i = 0; i < fStopTable.size(); i++) { fStopTable[i]->modifyZone(date, FAUSTFLOAT(0)); } } void clock(double date) { for (size_t i = 0; i < fClockTable.size(); i++) { fClockTable[i]->modifyZone(date, FAUSTFLOAT(1)); } } }; #endif // FAUST_MIDIUI_H /************************** END MidiUI.h **************************/ /************************** BEGIN mspUI.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2018 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ // // mspUI.h for static Max/MSP externals and faustgen~ // // Created by Martin Di Rollo on 18/04/12. // Copyright (c) 2012-2019 Grame. All rights reserved. // #ifndef _mspUI_h #define _mspUI_h #include <math.h> #include <string> #include <map> #define STR_SIZE 512 #define MULTI_SIZE 256 #ifdef WIN32 #include <stdio.h> #define snprintf _snprintf #ifndef NAN static const unsigned long __nan[2] = {0xffffffff, 0x7fffffff}; #define NAN (*(const float *) __nan) #endif #endif using namespace std; struct Max_Meta1 : Meta { int fCount; Max_Meta1():fCount(0) {} void declare(const char* key, const char* value) { if ((strcmp("name", key) == 0) || (strcmp("author", key) == 0)) { fCount++; } } }; struct Max_Meta2 : Meta { void declare(const char* key, const char* value) { if ((strcmp("name", key) == 0) || (strcmp("author", key) == 0)) { post("%s : %s", key, value); } } }; struct Max_Meta3 : Meta { string fName; bool endWith(const string& str, const string& suffix) { size_t i = str.rfind(suffix); return (i != string::npos) && (i == (str.length() - suffix.length())); } void declare(const char* key, const char* value) { if ((strcmp("filename", key) == 0)) { string val = value; if (endWith(value, ".dsp")) { fName = "com.grame." + val.substr(0, val.size() - 4) + "~"; } else { fName = "com.grame." + val + "~"; } } } }; class mspUIObject { protected: string fLabel; FAUSTFLOAT* fZone; FAUSTFLOAT range(FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT val) {return (val < min) ? min : (val > max) ? max : val;} public: mspUIObject(const string& label, FAUSTFLOAT* zone):fLabel(label),fZone(zone) {} virtual ~mspUIObject() {} virtual void setValue(FAUSTFLOAT f) { *fZone = range(0.0, 1.0, f); } virtual FAUSTFLOAT getValue() { return *fZone; } virtual FAUSTFLOAT getInitValue() { return FAUSTFLOAT(0); } virtual FAUSTFLOAT getMinValue() { return FAUSTFLOAT(0); } virtual FAUSTFLOAT getMaxValue() { return FAUSTFLOAT(0); } virtual void toString(char* buffer) {} virtual string getName() { return fLabel; } }; class mspCheckButton : public mspUIObject { public: mspCheckButton(const string& label, FAUSTFLOAT* zone):mspUIObject(label,zone) {} virtual ~mspCheckButton() {} void toString(char* buffer) { snprintf(buffer, STR_SIZE, "CheckButton(float): %s", fLabel.c_str()); } }; class mspButton : public mspUIObject { public: mspButton(const string& label, FAUSTFLOAT* zone):mspUIObject(label,zone) {} virtual ~mspButton() {} void toString(char* buffer) { snprintf(buffer, STR_SIZE, "Button(float): %s", fLabel.c_str()); } }; class mspSlider : public mspUIObject { private: FAUSTFLOAT fInit; FAUSTFLOAT fMin; FAUSTFLOAT fMax; FAUSTFLOAT fStep; public: mspSlider(const string& label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) :mspUIObject(label,zone),fInit(init),fMin(min),fMax(max),fStep(step) {} virtual ~mspSlider() {} void toString(char* buffer) { stringstream str; str << "Slider(float): " << fLabel << " [init=" << fInit << ":min=" << fMin << ":max=" << fMax << ":step=" << fStep << ":cur=" << *fZone << "]"; string res = str.str(); snprintf(buffer, STR_SIZE, "%s", res.c_str()); } void setValue(FAUSTFLOAT f) { *fZone = range(fMin, fMax, f); } virtual FAUSTFLOAT getInitValue() { return fInit; } virtual FAUSTFLOAT getMinValue() { return fMin; } virtual FAUSTFLOAT getMaxValue() { return fMax; } }; class mspBargraph : public mspUIObject { private: FAUSTFLOAT fMin; FAUSTFLOAT fMax; FAUSTFLOAT fCurrent; public: mspBargraph(const string& label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) :mspUIObject(label,zone), fMin(min), fMax(max), fCurrent(*zone) {} virtual ~mspBargraph() {} void toString(char* buffer) { stringstream str; str << "Bargraph(float): " << fLabel << " [min=" << fMin << ":max=" << fMax << ":cur=" << *fZone << "]"; string res = str.str(); snprintf(buffer, STR_SIZE, "%s", res.c_str()); } // special version virtual FAUSTFLOAT getValue(bool& new_val) { if (*fZone != fCurrent) { fCurrent = *fZone; new_val = true; } else { new_val = false; } return fCurrent; } virtual FAUSTFLOAT getMinValue() { return fMin; } virtual FAUSTFLOAT getMaxValue() { return fMax; } }; class mspUI : public UI, public PathBuilder { private: map<string, mspUIObject*> fInputLabelTable; // Input table using labels map<string, mspUIObject*> fInputPathTable; // Input table using paths map<string, mspUIObject*> fOutputLabelTable; // Table containing bargraph with labels map<string, mspUIObject*> fOutputPathTable; // Table containing bargraph with paths map<const char*, const char*> fDeclareTable; FAUSTFLOAT* fMultiTable[MULTI_SIZE]; int fMultiIndex; int fMultiControl; string createLabel(const char* label) { map<const char*, const char*>::reverse_iterator it; if (fDeclareTable.size() > 0) { unsigned int i = 0; string res = string(label); char sep = '['; for (it = fDeclareTable.rbegin(); it != fDeclareTable.rend(); it++, i++) { res = res + sep + (*it).first + ":" + (*it).second; sep = ','; } res += ']'; fDeclareTable.clear(); return res; } else { return string(label); } } void addSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { mspUIObject* obj = new mspSlider(createLabel(label), zone, init, min, max, step); fInputLabelTable[string(label)] = obj; fInputPathTable[buildPath(label)] = obj; fDeclareTable.clear(); } void addBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { mspUIObject* obj = new mspBargraph(createLabel(label), zone, min, max); fOutputLabelTable[string(label)] = obj; fOutputPathTable[buildPath(label)] = obj; fDeclareTable.clear(); } public: typedef map<string, mspUIObject*>::iterator iterator; mspUI() { for (int i = 0; i < MULTI_SIZE; i++) { fMultiTable[i] = 0; } fMultiIndex = fMultiControl = 0; } virtual ~mspUI() { clear(); } void addButton(const char* label, FAUSTFLOAT* zone) { mspUIObject* obj = new mspButton(createLabel(label), zone); fInputLabelTable[string(label)] = obj; fInputPathTable[buildPath(label)] = obj; } void addCheckButton(const char* label, FAUSTFLOAT* zone) { mspUIObject* obj = new mspCheckButton(createLabel(label), zone); fInputLabelTable[string(label)] = obj; fInputPathTable[buildPath(label)] = obj; } void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addSlider(label, zone, init, min, max, step); } void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addSlider(label, zone, init, min, max, step); } void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step) { addSlider(label, zone, init, min, max, step); } void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { addBargraph(label, zone, min, max); } void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max) { addBargraph(label, zone, min, max); } void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) {} void openTabBox(const char* label) { pushLabel(label); fDeclareTable.clear(); } void openHorizontalBox(const char* label) { pushLabel(label); fDeclareTable.clear(); } void openVerticalBox(const char* label) { pushLabel(label); fDeclareTable.clear(); } void closeBox() { popLabel(); fDeclareTable.clear(); } virtual void declare(FAUSTFLOAT* zone, const char* key, const char* val) { if (strcmp(key, "multi") == 0) { int index = atoi(val); if (index >= 0 && index < MULTI_SIZE) { fMultiTable[index] = zone; fMultiControl++; } else { post("Invalid multi index = %d", index); } } fDeclareTable[key] = val; } void setMultiValues(FAUSTFLOAT* multi, int buffer_size) { for (int read = 0; read < buffer_size; read++) { int write = (fMultiIndex + read) & (MULTI_SIZE - 1); if (fMultiTable[write]) { *fMultiTable[write] = multi[read]; } } fMultiIndex += buffer_size; } bool isMulti() { return fMultiControl > 0; } bool isValue(const string& name) { return (fInputLabelTable.count(name) || fInputPathTable.count(name)); } bool isOutputValue(const string& name) { return fOutputPathTable.count(name); } bool isInputValue(const string& name) { return fInputPathTable.count(name); } bool setValue(const string& name, FAUSTFLOAT val) { if (fInputLabelTable.count(name)) { fInputLabelTable[name]->setValue(val); return true; } else if (fInputPathTable.count(name)) { fInputPathTable[name]->setValue(val); return true; } else { return false; } } FAUSTFLOAT getOutputValue(const string& name, bool& new_val) { return static_cast<mspBargraph*>(fOutputPathTable[name])->getValue(new_val); } iterator begin1() { return fInputLabelTable.begin(); } iterator end1() { return fInputLabelTable.end(); } iterator begin2() { return fInputPathTable.begin(); } iterator end2() { return fInputPathTable.end(); } iterator begin3() { return fOutputLabelTable.begin(); } iterator end3() { return fOutputLabelTable.end(); } iterator begin4() { return fOutputPathTable.begin(); } iterator end4() { return fOutputPathTable.end(); } int inputItemsCount() { return fInputLabelTable.size(); } int outputItemsCount() { return fOutputLabelTable.size(); } void clear() { for (auto& it : fInputLabelTable) { delete it.second; } fInputLabelTable.clear(); fInputPathTable.clear(); for (auto& it : fOutputLabelTable) { delete it.second; } fOutputLabelTable.clear(); fOutputPathTable.clear(); } void displayControls() { post("------- Range and path ----------"); for (auto& it : fInputPathTable) { char param[STR_SIZE]; it.second->toString(param); post(param); string path = "Complete path: " + it.first; post(path.c_str()); } post("---------------------------------"); } static bool checkDigit(const string& name) { for (int i = name.size() - 1; i >= 0; i--) { if (isdigit(name[i])) { return true; } } return false; } static int countDigit(const string& name) { int count = 0; for (int i = name.size() - 1; i >= 0; i--) { if (isdigit(name[i])) { count++; } } return count; } }; #endif /************************** END mspUI.h **************************/ /************************** BEGIN poly-dsp.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __poly_dsp__ #define __poly_dsp__ #include <stdio.h> #include <string> #include <cmath> #include <algorithm> #include <ostream> #include <sstream> #include <vector> #include <limits.h> #include <float.h> #include <assert.h> /************************** BEGIN proxy-dsp.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2017 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __proxy_dsp__ #define __proxy_dsp__ #include <vector> #include <map> /************************** BEGIN JSONUIDecoder.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2003-2020 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __JSONUIDecoder__ #define __JSONUIDecoder__ #include <vector> #include <map> #include <utility> #include <cstdlib> #include <sstream> #include <functional> /************************** BEGIN CGlue.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2018 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef CGLUE_H #define CGLUE_H /************************** BEGIN CInterface.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2018 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef CINTERFACE_H #define CINTERFACE_H #ifndef FAUSTFLOAT #define FAUSTFLOAT float #endif #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif struct Soundfile; /******************************************************************************* * UI, Meta and MemoryManager structures for C code. ******************************************************************************/ // -- widget's layouts typedef void (* openTabBoxFun) (void* ui_interface, const char* label); typedef void (* openHorizontalBoxFun) (void* ui_interface, const char* label); typedef void (* openVerticalBoxFun) (void* ui_interface, const char* label); typedef void (* closeBoxFun) (void* ui_interface); // -- active widgets typedef void (* addButtonFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone); typedef void (* addCheckButtonFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone); typedef void (* addVerticalSliderFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step); typedef void (* addHorizontalSliderFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step); typedef void (* addNumEntryFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT min, FAUSTFLOAT max, FAUSTFLOAT step); // -- passive widgets typedef void (* addHorizontalBargraphFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max); typedef void (* addVerticalBargraphFun) (void* ui_interface, const char* label, FAUSTFLOAT* zone, FAUSTFLOAT min, FAUSTFLOAT max); // -- soundfiles typedef void (* addSoundfileFun) (void* ui_interface, const char* label, const char* url, struct Soundfile** sf_zone); typedef void (* declareFun) (void* ui_interface, FAUSTFLOAT* zone, const char* key, const char* value); typedef struct { void* uiInterface; openTabBoxFun openTabBox; openHorizontalBoxFun openHorizontalBox; openVerticalBoxFun openVerticalBox; closeBoxFun closeBox; addButtonFun addButton; addCheckButtonFun addCheckButton; addVerticalSliderFun addVerticalSlider; addHorizontalSliderFun addHorizontalSlider; addNumEntryFun addNumEntry; addHorizontalBargraphFun addHorizontalBargraph; addVerticalBargraphFun addVerticalBargraph; addSoundfileFun addSoundfile; declareFun declare; } UIGlue; typedef void (* metaDeclareFun) (void* ui_interface, const char* key, const char* value); typedef struct { void* metaInterface; metaDeclareFun declare; } MetaGlue; /*************************************** * Interface for the DSP object ***************************************/ typedef char dsp_imp; typedef dsp_imp* (* newDspFun) (); typedef void (* destroyDspFun) (dsp_imp* dsp); typedef int (* getNumInputsFun) (dsp_imp* dsp); typedef int (* getNumOutputsFun) (dsp_imp* dsp); typedef void (* buildUserInterfaceFun) (dsp_imp* dsp, UIGlue* ui); typedef int (* getSampleRateFun) (dsp_imp* dsp); typedef void (* initFun) (dsp_imp* dsp, int sample_rate); typedef void (* classInitFun) (int sample_rate); typedef void (* instanceInitFun) (dsp_imp* dsp, int sample_rate); typedef void (* instanceConstantsFun) (dsp_imp* dsp, int sample_rate); typedef void (* instanceResetUserInterfaceFun) (dsp_imp* dsp); typedef void (* instanceClearFun) (dsp_imp* dsp); typedef void (* computeFun) (dsp_imp* dsp, int len, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs); typedef void (* metadataFun) (MetaGlue* meta); /*************************************** * DSP memory manager functions ***************************************/ typedef void* (* allocateFun) (void* manager_interface, size_t size); typedef void (* destroyFun) (void* manager_interface, void* ptr); typedef struct { void* managerInterface; allocateFun allocate; destroyFun destroy; } MemoryManagerGlue; #ifdef __cplusplus } #endif #endif /************************** END CInterface.h **************************/ #ifdef __cplusplus extern "C" { #endif /******************************************************************************* * UI glue code ******************************************************************************/ class UIFloat { public: UIFloat() {} virtual ~UIFloat() {} // -- widget's layouts virtual void openTabBox(const char* label) = 0; virtual void openHorizontalBox(const char* label) = 0; virtual void openVerticalBox(const char* label) = 0; virtual void closeBox() = 0; // -- active widgets virtual void addButton(const char* label, float* zone) = 0; virtual void addCheckButton(const char* label, float* zone) = 0; virtual void addVerticalSlider(const char* label, float* zone, float init, float min, float max, float step) = 0; virtual void addHorizontalSlider(const char* label, float* zone, float init, float min, float max, float step) = 0; virtual void addNumEntry(const char* label, float* zone, float init, float min, float max, float step) = 0; // -- passive widgets virtual void addHorizontalBargraph(const char* label, float* zone, float min, float max) = 0; virtual void addVerticalBargraph(const char* label, float* zone, float min, float max) = 0; // -- soundfiles virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) = 0; // -- metadata declarations virtual void declare(float* zone, const char* key, const char* val) {} }; static void openTabBoxGlueFloat(void* cpp_interface, const char* label) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->openTabBox(label); } static void openHorizontalBoxGlueFloat(void* cpp_interface, const char* label) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->openHorizontalBox(label); } static void openVerticalBoxGlueFloat(void* cpp_interface, const char* label) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->openVerticalBox(label); } static void closeBoxGlueFloat(void* cpp_interface) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->closeBox(); } static void addButtonGlueFloat(void* cpp_interface, const char* label, float* zone) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->addButton(label, zone); } static void addCheckButtonGlueFloat(void* cpp_interface, const char* label, float* zone) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->addCheckButton(label, zone); } static void addVerticalSliderGlueFloat(void* cpp_interface, const char* label, float* zone, float init, float min, float max, float step) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->addVerticalSlider(label, zone, init, min, max, step); } static void addHorizontalSliderGlueFloat(void* cpp_interface, const char* label, float* zone, float init, float min, float max, float step) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->addHorizontalSlider(label, zone, init, min, max, step); } static void addNumEntryGlueFloat(void* cpp_interface, const char* label, float* zone, float init, float min, float max, float step) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->addNumEntry(label, zone, init, min, max, step); } static void addHorizontalBargraphGlueFloat(void* cpp_interface, const char* label, float* zone, float min, float max) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->addHorizontalBargraph(label, zone, min, max); } static void addVerticalBargraphGlueFloat(void* cpp_interface, const char* label, float* zone, float min, float max) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->addVerticalBargraph(label, zone, min, max); } static void addSoundfileGlueFloat(void* cpp_interface, const char* label, const char* url, Soundfile** sf_zone) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->addSoundfile(label, url, sf_zone); } static void declareGlueFloat(void* cpp_interface, float* zone, const char* key, const char* value) { UIFloat* ui_interface = static_cast<UIFloat*>(cpp_interface); ui_interface->declare(zone, key, value); } class UIDouble { public: UIDouble() {} virtual ~UIDouble() {} // -- widget's layouts virtual void openTabBox(const char* label) = 0; virtual void openHorizontalBox(const char* label) = 0; virtual void openVerticalBox(const char* label) = 0; virtual void closeBox() = 0; // -- active widgets virtual void addButton(const char* label, double* zone) = 0; virtual void addCheckButton(const char* label, double* zone) = 0; virtual void addVerticalSlider(const char* label, double* zone, double init, double min, double max, double step) = 0; virtual void addHorizontalSlider(const char* label, double* zone, double init, double min, double max, double step) = 0; virtual void addNumEntry(const char* label, double* zone, double init, double min, double max, double step) = 0; // -- passive widgets virtual void addHorizontalBargraph(const char* label, double* zone, double min, double max) = 0; virtual void addVerticalBargraph(const char* label, double* zone, double min, double max) = 0; // -- soundfiles virtual void addSoundfile(const char* label, const char* filename, Soundfile** sf_zone) = 0; // -- metadata declarations virtual void declare(double* zone, const char* key, const char* val) {} }; static void openTabBoxGlueDouble(void* cpp_interface, const char* label) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->openTabBox(label); } static void openHorizontalBoxGlueDouble(void* cpp_interface, const char* label) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->openHorizontalBox(label); } static void openVerticalBoxGlueDouble(void* cpp_interface, const char* label) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->openVerticalBox(label); } static void closeBoxGlueDouble(void* cpp_interface) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->closeBox(); } static void addButtonGlueDouble(void* cpp_interface, const char* label, double* zone) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->addButton(label, zone); } static void addCheckButtonGlueDouble(void* cpp_interface, const char* label, double* zone) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->addCheckButton(label, zone); } static void addVerticalSliderGlueDouble(void* cpp_interface, const char* label, double* zone, double init, double min, double max, double step) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->addVerticalSlider(label, zone, init, min, max, step); } static void addHorizontalSliderGlueDouble(void* cpp_interface, const char* label, double* zone, double init, double min, double max, double step) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->addHorizontalSlider(label, zone, init, min, max, step); } static void addNumEntryGlueDouble(void* cpp_interface, const char* label, double* zone, double init, double min, double max, double step) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->addNumEntry(label, zone, init, min, max, step); } static void addHorizontalBargraphGlueDouble(void* cpp_interface, const char* label, double* zone, double min, double max) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->addHorizontalBargraph(label, zone, min, max); } static void addVerticalBargraphGlueDouble(void* cpp_interface, const char* label, double* zone, double min, double max) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->addVerticalBargraph(label, zone, min, max); } static void addSoundfileGlueDouble(void* cpp_interface, const char* label, const char* url, Soundfile** sf_zone) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->addSoundfile(label, url, sf_zone); } static void declareGlueDouble(void* cpp_interface, double* zone, const char* key, const char* value) { UIDouble* ui_interface = static_cast<UIDouble*>(cpp_interface); ui_interface->declare(zone, key, value); } static void buildUIGlue(UIGlue* glue, UI* ui_interface, bool is_double) { glue->uiInterface = ui_interface; if (is_double) { glue->openTabBox = reinterpret_cast<openTabBoxFun>(openTabBoxGlueDouble); glue->openHorizontalBox = reinterpret_cast<openHorizontalBoxFun>(openHorizontalBoxGlueDouble); glue->openVerticalBox = reinterpret_cast<openVerticalBoxFun>(openVerticalBoxGlueDouble); glue->closeBox = reinterpret_cast<closeBoxFun>(closeBoxGlueDouble); glue->addButton = reinterpret_cast<addButtonFun>(addButtonGlueDouble); glue->addCheckButton = reinterpret_cast<addCheckButtonFun>(addCheckButtonGlueDouble); glue->addVerticalSlider = reinterpret_cast<addVerticalSliderFun>(addVerticalSliderGlueDouble); glue->addHorizontalSlider = reinterpret_cast<addHorizontalSliderFun>(addHorizontalSliderGlueDouble); glue->addNumEntry = reinterpret_cast<addNumEntryFun>(addNumEntryGlueDouble); glue->addHorizontalBargraph = reinterpret_cast<addHorizontalBargraphFun>(addHorizontalBargraphGlueDouble); glue->addVerticalBargraph = reinterpret_cast<addVerticalBargraphFun>(addVerticalBargraphGlueDouble); glue->addSoundfile = reinterpret_cast<addSoundfileFun>(addSoundfileGlueDouble); glue->declare = reinterpret_cast<declareFun>(declareGlueDouble); } else { glue->openTabBox = reinterpret_cast<openTabBoxFun>(openTabBoxGlueFloat); glue->openHorizontalBox = reinterpret_cast<openHorizontalBoxFun>(openHorizontalBoxGlueFloat); glue->openVerticalBox = reinterpret_cast<openVerticalBoxFun>(openVerticalBoxGlueFloat); glue->closeBox = reinterpret_cast<closeBoxFun>(closeBoxGlueFloat); glue->addButton = reinterpret_cast<addButtonFun>(addButtonGlueFloat); glue->addCheckButton = reinterpret_cast<addCheckButtonFun>(addCheckButtonGlueFloat); glue->addVerticalSlider = reinterpret_cast<addVerticalSliderFun>(addVerticalSliderGlueFloat); glue->addHorizontalSlider = reinterpret_cast<addHorizontalSliderFun>(addHorizontalSliderGlueFloat); glue->addNumEntry = reinterpret_cast<addNumEntryFun>(addNumEntryGlueFloat); glue->addHorizontalBargraph = reinterpret_cast<addHorizontalBargraphFun>(addHorizontalBargraphGlueFloat); glue->addVerticalBargraph = reinterpret_cast<addVerticalBargraphFun>(addVerticalBargraphGlueFloat); glue->addSoundfile = reinterpret_cast<addSoundfileFun>(addSoundfileGlueFloat); glue->declare = reinterpret_cast<declareFun>(declareGlueFloat); } } class UITemplate { private: void* fCPPInterface; public: UITemplate(void* cpp_interface):fCPPInterface(cpp_interface) {} virtual ~UITemplate() {} // -- widget's layouts virtual void openTabBox(const char* label) { openTabBoxGlueFloat(fCPPInterface, label); } virtual void openHorizontalBox(const char* label) { openHorizontalBoxGlueFloat(fCPPInterface, label); } virtual void openVerticalBox(const char* label) { openVerticalBoxGlueFloat(fCPPInterface, label); } virtual void closeBox() { closeBoxGlueFloat(fCPPInterface); } // float version // -- active widgets virtual void addButton(const char* label, float* zone) { addButtonGlueFloat(fCPPInterface, label, zone); } virtual void addCheckButton(const char* label, float* zone) { addCheckButtonGlueFloat(fCPPInterface, label, zone); } virtual void addVerticalSlider(const char* label, float* zone, float init, float min, float max, float step) { addVerticalSliderGlueFloat(fCPPInterface, label, zone, init, min, max, step); } virtual void addHorizontalSlider(const char* label, float* zone, float init, float min, float max, float step) { addHorizontalSliderGlueFloat(fCPPInterface, label, zone, init, min, max, step); } virtual void addNumEntry(const char* label, float* zone, float init, float min, float max, float step) { addNumEntryGlueFloat(fCPPInterface, label, zone, init, min, max, step); } // -- passive widgets virtual void addHorizontalBargraph(const char* label, float* zone, float min, float max) { addHorizontalBargraphGlueFloat(fCPPInterface, label, zone, min, max); } virtual void addVerticalBargraph(const char* label, float* zone, float min, float max) { addVerticalBargraphGlueFloat(fCPPInterface, label, zone, min, max); } // -- metadata declarations virtual void declare(float* zone, const char* key, const char* val) { declareGlueFloat(fCPPInterface, zone, key, val); } // double version virtual void addButton(const char* label, double* zone) { addButtonGlueDouble(fCPPInterface, label, zone); } virtual void addCheckButton(const char* label, double* zone) { addCheckButtonGlueDouble(fCPPInterface, label, zone); } virtual void addVerticalSlider(const char* label, double* zone, double init, double min, double max, double step) { addVerticalSliderGlueDouble(fCPPInterface, label, zone, init, min, max, step); } virtual void addHorizontalSlider(const char* label, double* zone, double init, double min, double max, double step) { addHorizontalSliderGlueDouble(fCPPInterface, label, zone, init, min, max, step); } virtual void addNumEntry(const char* label, double* zone, double init, double min, double max, double step) { addNumEntryGlueDouble(fCPPInterface, label, zone, init, min, max, step); } // -- soundfiles virtual void addSoundfile(const char* label, const char* url, Soundfile** sf_zone) { addSoundfileGlueFloat(fCPPInterface, label, url, sf_zone); } // -- passive widgets virtual void addHorizontalBargraph(const char* label, double* zone, double min, double max) { addHorizontalBargraphGlueDouble(fCPPInterface, label, zone, min, max); } virtual void addVerticalBargraph(const char* label, double* zone, double min, double max) { addVerticalBargraphGlueDouble(fCPPInterface, label, zone, min, max); } // -- metadata declarations virtual void declare(double* zone, const char* key, const char* val) { declareGlueDouble(fCPPInterface, zone, key, val); } }; /******************************************************************************* * Meta glue code ******************************************************************************/ static void declareMetaGlue(void* cpp_interface, const char* key, const char* value) { Meta* meta_interface = static_cast<Meta*>(cpp_interface); meta_interface->declare(key, value); } static void buildMetaGlue(MetaGlue* glue, Meta* meta) { glue->metaInterface = meta; glue->declare = declareMetaGlue; } /******************************************************************************* * Memory manager glue code ******************************************************************************/ static void* allocateMemoryManagerGlue(void* cpp_interface, size_t size) { dsp_memory_manager* manager_interface = static_cast<dsp_memory_manager*>(cpp_interface); return manager_interface->allocate(size); } static void destroyMemoryManagerGlue(void* cpp_interface, void* ptr) { dsp_memory_manager* manager_interface = static_cast<dsp_memory_manager*>(cpp_interface); manager_interface->destroy(ptr); } static void buildManagerGlue(MemoryManagerGlue* glue, dsp_memory_manager* manager) { glue->managerInterface = manager; glue->allocate = allocateMemoryManagerGlue; glue->destroy = destroyMemoryManagerGlue; } #ifdef __cplusplus } #endif #endif /************************** END CGlue.h **************************/ #ifdef _WIN32 #include <windows.h> #define snprintf _snprintf #endif //------------------------------------------------------------------- // Decode a dsp JSON description and implement 'buildUserInterface' //------------------------------------------------------------------- #define REAL_UI(ui_interface) reinterpret_cast<UIReal<REAL>*>(ui_interface) #define REAL_ADR(offset) reinterpret_cast<REAL*>(&memory_block[offset]) #define REAL_EXT_ADR(offset) reinterpret_cast<FAUSTFLOAT*>(&memory_block[offset]) #define SOUNDFILE_ADR(offset) reinterpret_cast<Soundfile**>(&memory_block[offset]) typedef std::function<void(double)> ReflectFunction; typedef std::function<double()> ModifyFunction; struct ExtZoneParam { virtual void reflectZone() = 0; virtual void modifyZone() = 0; virtual void setReflectZoneFun(ReflectFunction reflect) = 0; virtual void setModifyZoneFun(ModifyFunction modify) = 0; virtual ~ExtZoneParam() {} }; template <typename REAL> struct JSONUIDecoderReal { struct ZoneParam : public ExtZoneParam { REAL fZone; int fIndex; ReflectFunction fReflect; ModifyFunction fModify; #if defined(TARGET_OS_IPHONE) || defined(WIN32) ZoneParam(int index, ReflectFunction reflect = nullptr, ModifyFunction modify = nullptr) :fIndex(index), fReflect(reflect), fModify(modify) {} void reflectZone() { if (fReflect) fReflect(fZone); } void modifyZone() { if (fModify) fZone = fModify(); } #else ZoneParam(int index, ReflectFunction reflect = [](REAL value) {}, ModifyFunction modify = []() { return REAL(-1); }) :fIndex(index), fReflect(reflect), fModify(modify) {} void reflectZone() { fReflect(fZone); } void modifyZone() { fZone = fModify(); } #endif void setReflectZoneFun(ReflectFunction reflect) { fReflect = reflect; } void setModifyZoneFun(ModifyFunction modify) { fModify = modify; } }; typedef std::vector<ExtZoneParam*> controlMap; std::string fName; std::string fFileName; std::string fJSON; std::string fVersion; std::string fCompileOptions; std::map<std::string, std::string> fMetadata; std::vector<itemInfo> fUiItems; std::vector<std::string> fLibraryList; std::vector<std::string> fIncludePathnames; Soundfile** fSoundfiles; int fNumInputs, fNumOutputs, fSRIndex; int fSoundfileItems; int fDSPSize; controlMap fPathInputTable; // [path, ZoneParam] controlMap fPathOutputTable; // [path, ZoneParam] bool isInput(const std::string& type) { return (type == "vslider" || type == "hslider" || type == "nentry" || type == "button" || type == "checkbox"); } bool isOutput(const std::string& type) { return (type == "hbargraph" || type == "vbargraph"); } bool isSoundfile(const std::string& type) { return (type == "soundfile"); } std::string getString(std::map<std::string, std::pair<std::string, double> >& map, const std::string& key) { return (map.find(key) != map.end()) ? map[key].first : ""; } int getInt(std::map<std::string, std::pair<std::string, double> >& map, const std::string& key) { return (map.find(key) != map.end()) ? int(map[key].second) : -1; } void setReflectZoneFun(int index, ReflectFunction fun) { fPathInputTable[index]->setReflectZoneFun(fun); } void setModifyZoneFun(int index, ModifyFunction fun) { fPathOutputTable[index]->setModifyZoneFun(fun); } JSONUIDecoderReal(const std::string& json) { fJSON = json; const char* p = fJSON.c_str(); std::map<std::string, std::pair<std::string, double> > meta_data1; std::map<std::string, std::vector<std::string> > meta_data2; parseJson(p, meta_data1, fMetadata, meta_data2, fUiItems); // meta_data1 contains <name : val>, <inputs : val>, <ouputs : val> pairs etc... fName = getString(meta_data1, "name"); fFileName = getString(meta_data1, "filename"); fVersion = getString(meta_data1, "version"); fCompileOptions = getString(meta_data1, "compile_options"); if (meta_data2.find("library_list") != meta_data2.end()) { fLibraryList = meta_data2["library_list"]; } if (meta_data2.find("include_pathnames") != meta_data2.end()) { fIncludePathnames = meta_data2["include_pathnames"]; } fDSPSize = getInt(meta_data1, "size"); fNumInputs = getInt(meta_data1, "inputs"); fNumOutputs = getInt(meta_data1, "outputs"); fSRIndex = getInt(meta_data1, "sr_index"); fSoundfileItems = 0; for (auto& it : fUiItems) { std::string type = it.type; if (isSoundfile(type)) { fSoundfileItems++; } } fSoundfiles = new Soundfile*[fSoundfileItems]; // Prepare the fPathTable and init zone for (auto& it : fUiItems) { std::string type = it.type; // Meta data declaration for input items if (isInput(type)) { ZoneParam* param = new ZoneParam(it.index); fPathInputTable.push_back(param); param->fZone = it.init; } // Meta data declaration for output items else if (isOutput(type)) { ZoneParam* param = new ZoneParam(it.index); fPathOutputTable.push_back(param); param->fZone = REAL(0); } } } virtual ~JSONUIDecoderReal() { delete [] fSoundfiles; for (auto& it : fPathInputTable) { delete it; } for (auto& it : fPathOutputTable) { delete it; } } void metadata(Meta* m) { for (auto& it : fMetadata) { m->declare(it.first.c_str(), it.second.c_str()); } } void metadata(MetaGlue* m) { for (auto& it : fMetadata) { m->declare(m->metaInterface, it.first.c_str(), it.second.c_str()); } } void resetUserInterface() { int item = 0; for (auto& it : fUiItems) { if (isInput(it.type)) { static_cast<ZoneParam*>(fPathInputTable[item++])->fZone = it.init; } } } void resetUserInterface(char* memory_block, Soundfile* defaultsound = nullptr) { for (auto& it : fUiItems) { int offset = it.index; if (isInput(it.type)) { *REAL_ADR(offset) = it.init; } else if (isSoundfile(it.type)) { if (*SOUNDFILE_ADR(offset) == nullptr) { *SOUNDFILE_ADR(offset) = defaultsound; } } } } int getSampleRate(char* memory_block) { return *reinterpret_cast<int*>(&memory_block[fSRIndex]); } void buildUserInterface(UI* ui_interface) { // MANDATORY: to be sure floats or double are correctly parsed char* tmp_local = setlocale(LC_ALL, nullptr); if (tmp_local != NULL) { tmp_local = strdup(tmp_local); } setlocale(LC_ALL, "C"); int countIn = 0; int countOut = 0; int countSound = 0; for (auto& it : fUiItems) { std::string type = it.type; REAL init = REAL(it.init); REAL min = REAL(it.min); REAL max = REAL(it.max); REAL step = REAL(it.step); // Meta data declaration for input items if (isInput(type)) { for (size_t i = 0; i < it.meta.size(); i++) { REAL_UI(ui_interface)->declare(&static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone, it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } // Meta data declaration for output items else if (isOutput(type)) { for (size_t i = 0; i < it.meta.size(); i++) { REAL_UI(ui_interface)->declare(&static_cast<ZoneParam*>(fPathOutputTable[countOut])->fZone, it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } // Meta data declaration for group opening or closing else { for (size_t i = 0; i < it.meta.size(); i++) { REAL_UI(ui_interface)->declare(0, it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } if (type == "hgroup") { REAL_UI(ui_interface)->openHorizontalBox(it.label.c_str()); } else if (type == "vgroup") { REAL_UI(ui_interface)->openVerticalBox(it.label.c_str()); } else if (type == "tgroup") { REAL_UI(ui_interface)->openTabBox(it.label.c_str()); } else if (type == "vslider") { REAL_UI(ui_interface)->addVerticalSlider(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone, init, min, max, step); } else if (type == "hslider") { REAL_UI(ui_interface)->addHorizontalSlider(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone, init, min, max, step); } else if (type == "checkbox") { REAL_UI(ui_interface)->addCheckButton(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone); } else if (type == "soundfile") { REAL_UI(ui_interface)->addSoundfile(it.label.c_str(), it.url.c_str(), &fSoundfiles[countSound]); } else if (type == "hbargraph") { REAL_UI(ui_interface)->addHorizontalBargraph(it.label.c_str(), &static_cast<ZoneParam*>(fPathOutputTable[countOut])->fZone, min, max); } else if (type == "vbargraph") { REAL_UI(ui_interface)->addVerticalBargraph(it.label.c_str(), &static_cast<ZoneParam*>(fPathOutputTable[countOut])->fZone, min, max); } else if (type == "nentry") { REAL_UI(ui_interface)->addNumEntry(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone, init, min, max, step); } else if (type == "button") { REAL_UI(ui_interface)->addButton(it.label.c_str(), &static_cast<ZoneParam*>(fPathInputTable[countIn])->fZone); } else if (type == "close") { REAL_UI(ui_interface)->closeBox(); } if (isInput(type)) { countIn++; } else if (isOutput(type)) { countOut++; } else if (isSoundfile(type)) { countSound++; } } if (tmp_local != NULL) { setlocale(LC_ALL, tmp_local); free(tmp_local); } } void buildUserInterface(UI* ui_interface, char* memory_block) { // MANDATORY: to be sure floats or double are correctly parsed char* tmp_local = setlocale(LC_ALL, nullptr); if (tmp_local != NULL) { tmp_local = strdup(tmp_local); } setlocale(LC_ALL, "C"); for (auto& it : fUiItems) { std::string type = it.type; int offset = it.index; REAL init = REAL(it.init); REAL min = REAL(it.min); REAL max = REAL(it.max); REAL step = REAL(it.step); // Meta data declaration for input items if (isInput(type)) { for (size_t i = 0; i < it.meta.size(); i++) { REAL_UI(ui_interface)->declare(REAL_ADR(offset), it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } // Meta data declaration for output items else if (isOutput(type)) { for (size_t i = 0; i < it.meta.size(); i++) { REAL_UI(ui_interface)->declare(REAL_ADR(offset), it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } // Meta data declaration for group opening or closing else { for (size_t i = 0; i < it.meta.size(); i++) { REAL_UI(ui_interface)->declare(0, it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } if (type == "hgroup") { REAL_UI(ui_interface)->openHorizontalBox(it.label.c_str()); } else if (type == "vgroup") { REAL_UI(ui_interface)->openVerticalBox(it.label.c_str()); } else if (type == "tgroup") { REAL_UI(ui_interface)->openTabBox(it.label.c_str()); } else if (type == "vslider") { REAL_UI(ui_interface)->addVerticalSlider(it.label.c_str(), REAL_ADR(offset), init, min, max, step); } else if (type == "hslider") { REAL_UI(ui_interface)->addHorizontalSlider(it.label.c_str(), REAL_ADR(offset), init, min, max, step); } else if (type == "checkbox") { REAL_UI(ui_interface)->addCheckButton(it.label.c_str(), REAL_ADR(offset)); } else if (type == "soundfile") { REAL_UI(ui_interface)->addSoundfile(it.label.c_str(), it.url.c_str(), SOUNDFILE_ADR(offset)); } else if (type == "hbargraph") { REAL_UI(ui_interface)->addHorizontalBargraph(it.label.c_str(), REAL_ADR(offset), min, max); } else if (type == "vbargraph") { REAL_UI(ui_interface)->addVerticalBargraph(it.label.c_str(), REAL_ADR(offset), min, max); } else if (type == "nentry") { REAL_UI(ui_interface)->addNumEntry(it.label.c_str(), REAL_ADR(offset), init, min, max, step); } else if (type == "button") { REAL_UI(ui_interface)->addButton(it.label.c_str(), REAL_ADR(offset)); } else if (type == "close") { REAL_UI(ui_interface)->closeBox(); } } if (tmp_local != NULL) { setlocale(LC_ALL, tmp_local); free(tmp_local); } } void buildUserInterface(UIGlue* ui_interface, char* memory_block) { // MANDATORY: to be sure floats or double are correctly parsed char* tmp_local = setlocale(LC_ALL, nullptr); if (tmp_local != NULL) { tmp_local = strdup(tmp_local); } setlocale(LC_ALL, "C"); for (auto& it : fUiItems) { std::string type = it.type; int offset = it.index; REAL init = REAL(it.init); REAL min = REAL(it.min); REAL max = REAL(it.max); REAL step = REAL(it.step); // Meta data declaration for input items if (isInput(type)) { for (size_t i = 0; i < it.meta.size(); i++) { ui_interface->declare(ui_interface->uiInterface, REAL_EXT_ADR(offset), it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } // Meta data declaration for output items else if (isOutput(type)) { for (size_t i = 0; i < it.meta.size(); i++) { ui_interface->declare(ui_interface->uiInterface, REAL_EXT_ADR(offset), it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } // Meta data declaration for group opening or closing else { for (size_t i = 0; i < it.meta.size(); i++) { ui_interface->declare(ui_interface->uiInterface, 0, it.meta[i].first.c_str(), it.meta[i].second.c_str()); } } if (type == "hgroup") { ui_interface->openHorizontalBox(ui_interface->uiInterface, it.label.c_str()); } else if (type == "vgroup") { ui_interface->openVerticalBox(ui_interface->uiInterface, it.label.c_str()); } else if (type == "tgroup") { ui_interface->openTabBox(ui_interface->uiInterface, it.label.c_str()); } else if (type == "vslider") { ui_interface->addVerticalSlider(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), init, min, max, step); } else if (type == "hslider") { ui_interface->addHorizontalSlider(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), init, min, max, step); } else if (type == "checkbox") { ui_interface->addCheckButton(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset)); } else if (type == "soundfile") { ui_interface->addSoundfile(ui_interface->uiInterface, it.label.c_str(), it.url.c_str(), SOUNDFILE_ADR(offset)); } else if (type == "hbargraph") { ui_interface->addHorizontalBargraph(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), min, max); } else if (type == "vbargraph") { ui_interface->addVerticalBargraph(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), min, max); } else if (type == "nentry") { ui_interface->addNumEntry(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset), init, min, max, step); } else if (type == "button") { ui_interface->addButton(ui_interface->uiInterface, it.label.c_str(), REAL_EXT_ADR(offset)); } else if (type == "close") { ui_interface->closeBox(ui_interface->uiInterface); } } if (tmp_local != NULL) { setlocale(LC_ALL, tmp_local); free(tmp_local); } } bool hasCompileOption(const std::string& option) { std::istringstream iss(fCompileOptions); std::string token; while (std::getline(iss, token, ' ')) { if (token == option) return true; } return false; } }; // Templated decoder struct JSONUITemplatedDecoder { virtual ~JSONUITemplatedDecoder() {} virtual void metadata(Meta* m) = 0; virtual void metadata(MetaGlue* glue) = 0; virtual int getDSPSize() = 0; virtual std::string getName() = 0; virtual std::string getLibVersion() = 0; virtual std::string getCompileOptions() = 0; virtual std::vector<std::string> getLibraryList() = 0; virtual std::vector<std::string> getIncludePathnames() = 0; virtual int getNumInputs() = 0; virtual int getNumOutputs() = 0; virtual int getSampleRate(char* memory_block) = 0; virtual void setReflectZoneFun(int index, ReflectFunction fun) = 0; virtual void setModifyZoneFun(int index, ModifyFunction fun) = 0; virtual std::vector<ExtZoneParam*>& getInputControls() = 0; virtual std::vector<ExtZoneParam*>& getOutputControls() = 0; virtual void resetUserInterface(char* memory_block, Soundfile* defaultsound = nullptr) = 0; virtual void buildUserInterface(UI* ui_interface) = 0; virtual void buildUserInterface(UI* ui_interface, char* memory_block) = 0; virtual void buildUserInterface(UIGlue* ui_interface, char* memory_block) = 0; virtual bool hasCompileOption(const std::string& option) = 0; }; // Float templated decoder struct JSONUIFloatDecoder : public JSONUIDecoderReal<float>, public JSONUITemplatedDecoder { JSONUIFloatDecoder(const std::string& json):JSONUIDecoderReal<float>(json) {} void metadata(Meta* m) { JSONUIDecoderReal<float>::metadata(m); } void metadata(MetaGlue* glue) { JSONUIDecoderReal<float>::metadata(glue); } int getDSPSize() { return fDSPSize; } std::string getName() { return fName; } std::string getLibVersion() { return fVersion; } std::string getCompileOptions() { return fCompileOptions; } std::vector<std::string> getLibraryList() { return fLibraryList; } std::vector<std::string> getIncludePathnames() { return fIncludePathnames; } int getNumInputs() { return fNumInputs; } int getNumOutputs() { return fNumOutputs; } int getSampleRate(char* memory_block) { return JSONUIDecoderReal<float>::getSampleRate(memory_block); } void setReflectZoneFun(int index, ReflectFunction fun) { JSONUIDecoderReal<float>::setReflectZoneFun(index, fun); } void setModifyZoneFun(int index, ModifyFunction fun) { JSONUIDecoderReal<float>::setModifyZoneFun(index, fun); } std::vector<ExtZoneParam*>& getInputControls() { return fPathInputTable; } std::vector<ExtZoneParam*>& getOutputControls() { return fPathOutputTable; } void resetUserInterface(char* memory_block, Soundfile* defaultsound = nullptr) { JSONUIDecoderReal<float>::resetUserInterface(memory_block, defaultsound); } void buildUserInterface(UI* ui_interface) { JSONUIDecoderReal<float>::buildUserInterface(ui_interface); } void buildUserInterface(UI* ui_interface, char* memory_block) { JSONUIDecoderReal<float>::buildUserInterface(ui_interface, memory_block); } void buildUserInterface(UIGlue* ui_interface, char* memory_block) { JSONUIDecoderReal<float>::buildUserInterface(ui_interface, memory_block); } bool hasCompileOption(const std::string& option) { return JSONUIDecoderReal<float>::hasCompileOption(option); } }; // Double templated decoder struct JSONUIDoubleDecoder : public JSONUIDecoderReal<double>, public JSONUITemplatedDecoder { JSONUIDoubleDecoder(const std::string& json):JSONUIDecoderReal<double>(json) {} void metadata(Meta* m) { JSONUIDecoderReal<double>::metadata(m); } void metadata(MetaGlue* glue) { JSONUIDecoderReal<double>::metadata(glue); } int getDSPSize() { return fDSPSize; } std::string getName() { return fName; } std::string getLibVersion() { return fVersion; } std::string getCompileOptions() { return fCompileOptions; } std::vector<std::string> getLibraryList() { return fLibraryList; } std::vector<std::string> getIncludePathnames() { return fIncludePathnames; } int getNumInputs() { return fNumInputs; } int getNumOutputs() { return fNumOutputs; } int getSampleRate(char* memory_block) { return JSONUIDecoderReal<double>::getSampleRate(memory_block); } void setReflectZoneFun(int index, ReflectFunction fun) { JSONUIDecoderReal<double>::setReflectZoneFun(index, fun); } void setModifyZoneFun(int index, ModifyFunction fun) { JSONUIDecoderReal<double>::setModifyZoneFun(index, fun); } std::vector<ExtZoneParam*>& getInputControls() { return fPathInputTable; } std::vector<ExtZoneParam*>& getOutputControls() { return fPathOutputTable; } void resetUserInterface(char* memory_block, Soundfile* defaultsound = nullptr) { JSONUIDecoderReal<double>::resetUserInterface(memory_block, defaultsound); } void buildUserInterface(UI* ui_interface) { JSONUIDecoderReal<double>::buildUserInterface(ui_interface); } void buildUserInterface(UI* ui_interface, char* memory_block) { JSONUIDecoderReal<double>::buildUserInterface(ui_interface, memory_block); } void buildUserInterface(UIGlue* ui_interface, char* memory_block) { JSONUIDecoderReal<double>::buildUserInterface(ui_interface, memory_block); } bool hasCompileOption(const std::string& option) { return JSONUIDecoderReal<double>::hasCompileOption(option); } }; // FAUSTFLOAT templated decoder struct JSONUIDecoder : public JSONUIDecoderReal<FAUSTFLOAT> { JSONUIDecoder(const std::string& json):JSONUIDecoderReal<FAUSTFLOAT>(json) {} }; // Generic factory static JSONUITemplatedDecoder* createJSONUIDecoder(const std::string& json) { JSONUIDecoder decoder(json); if (decoder.hasCompileOption("-double")) { return new JSONUIDoubleDecoder(json); } else { return new JSONUIFloatDecoder(json); } } #endif /************************** END JSONUIDecoder.h **************************/ //---------------------------------------------------------------- // Proxy dsp definition created from the DSP JSON description // This class allows a 'proxy' dsp to control a real dsp // possibly running somewhere else. //---------------------------------------------------------------- class proxy_dsp : public dsp { private: JSONUIDecoder* fDecoder; int fSampleRate; public: proxy_dsp():fDecoder(nullptr), fSampleRate(-1) {} proxy_dsp(const std::string& json) { init(json); } void init(const std::string& json) { fDecoder = new JSONUIDecoder(json); fSampleRate = -1; } proxy_dsp(dsp* dsp) { JSONUI builder(dsp->getNumInputs(), dsp->getNumOutputs()); dsp->metadata(&builder); dsp->buildUserInterface(&builder); fSampleRate = dsp->getSampleRate(); fDecoder = new JSONUIDecoder(builder.JSON()); } virtual ~proxy_dsp() { delete fDecoder; } virtual int getNumInputs() { return fDecoder->fNumInputs; } virtual int getNumOutputs() { return fDecoder->fNumOutputs; } virtual void buildUserInterface(UI* ui) { fDecoder->buildUserInterface(ui); } // To possibly implement in a concrete proxy dsp virtual void init(int sample_rate) { instanceInit(sample_rate); } virtual void instanceInit(int sample_rate) { instanceConstants(sample_rate); instanceResetUserInterface(); instanceClear(); } virtual void instanceConstants(int sample_rate) { fSampleRate = sample_rate; } virtual void instanceResetUserInterface() { fDecoder->resetUserInterface(); } virtual void instanceClear() {} virtual int getSampleRate() { return fSampleRate; } virtual proxy_dsp* clone() { return new proxy_dsp(fDecoder->fJSON); } virtual void metadata(Meta* m) { fDecoder->metadata(m); } virtual void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) {} virtual void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) {} }; #endif /************************** END proxy-dsp.h **************************/ /************************** BEGIN JSONControl.h **************************/ /************************************************************************ FAUST Architecture File Copyright (C) 2019 GRAME, Centre National de Creation Musicale --------------------------------------------------------------------- This Architecture section is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; If not, see <http://www.gnu.org/licenses/>. EXCEPTION : As a special exception, you may create a larger work that contains this FAUST architecture section and distribute that work under terms of your choice, so long as this FAUST architecture section is not modified. ************************************************************************/ #ifndef __JSON_CONTROL__ #define __JSON_CONTROL__ #include <string> #ifndef FAUSTFLOAT #define FAUSTFLOAT float #endif struct JSONControl { virtual std::string getJSON() { return ""; } virtual void setParamValue(const std::string& path, FAUSTFLOAT value) {} virtual FAUSTFLOAT getParamValue(const std::string& path) { return 0; } virtual ~JSONControl() {} }; #endif /************************** END JSONControl.h **************************/ #define kActiveVoice 0 #define kFreeVoice -1 #define kReleaseVoice -2 #define kNoVoice -3 #define VOICE_STOP_LEVEL 0.0005 // -70 db #define MIX_BUFFER_SIZE 4096 // endsWith(<str>,<end>) : returns true if <str> ends with <end> static double midiToFreq(double note) { return 440.0 * std::pow(2.0, (note-69.0)/12.0); } /** * Allows to control zones in a grouped manner. */ class GroupUI : public GUI, public PathBuilder { private: std::map<std::string, uiGroupItem*> fLabelZoneMap; void insertMap(std::string label, FAUSTFLOAT* zone) { if (!MapUI::endsWith(label, "/gate") && !MapUI::endsWith(label, "/freq") && !MapUI::endsWith(label, "/gain")) { // Groups all controller except 'freq', 'gate', and 'gain' if (fLabelZoneMap.find(label) != fLabelZoneMap.end()) { fLabelZoneMap[label]->addZone(zone); } else { fLabelZoneMap[label] = new uiGroupItem(this, zone); } } } uiCallbackItem* fPanic; public: GroupUI(FAUSTFLOAT* zone, uiCallback cb, void* arg) { fPanic = new uiCallbackItem(this, zone, cb, arg); } virtual ~GroupUI() { // 'fPanic' is kept and deleted in GUI, so do not delete here } // -- widget's layouts void openTabBox(const char* label) { pushLabel(label); } void openHorizontalBox(const char* label) { pushLabel(label); } void openVerticalBox(const char* label) { pushLabel(label); } void closeBox() { popLabel(); } // -- active widgets void addButton(const char* label, FAUSTFLOAT* zone) { insertMap(buildPath(label), zone); } void addCheckButton(const char* label, FAUSTFLOAT* zone) { insertMap(buildPath(label), zone); } void addVerticalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { insertMap(buildPath(label), zone); } void addHorizontalSlider(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { insertMap(buildPath(label), zone); } void addNumEntry(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT init, FAUSTFLOAT fmin, FAUSTFLOAT fmax, FAUSTFLOAT step) { insertMap(buildPath(label), zone); } // -- passive widgets void addHorizontalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax) { insertMap(buildPath(label), zone); } void addVerticalBargraph(const char* label, FAUSTFLOAT* zone, FAUSTFLOAT fmin, FAUSTFLOAT fmax) { insertMap(buildPath(label), zone); } }; /** * One voice of polyphony. */ struct dsp_voice : public MapUI, public decorator_dsp { int fNote; // Playing note actual pitch int fDate; // KeyOn date int fRelease; // Current number of samples used in release mode to detect end of note int fMinRelease; // Max of samples used in release mode to detect end of note FAUSTFLOAT fLevel; // Last audio block level std::vector<std::string> fGatePath; // Paths of 'gate' control std::vector<std::string> fGainPath; // Paths of 'gain' control std::vector<std::string> fFreqPath; // Paths of 'freq' control dsp_voice(dsp* dsp):decorator_dsp(dsp) { dsp->buildUserInterface(this); fNote = kFreeVoice; fLevel = FAUSTFLOAT(0); fDate = 0; fMinRelease = dsp->getSampleRate()/2; // One 1/2 sec used in release mode to detect end of note extractPaths(fGatePath, fFreqPath, fGainPath); } virtual ~dsp_voice() {} void extractPaths(std::vector<std::string>& gate, std::vector<std::string>& freq, std::vector<std::string>& gain) { // Keep gain, freq and gate labels std::map<std::string, FAUSTFLOAT*>::iterator it; for (it = getMap().begin(); it != getMap().end(); it++) { std::string path = (*it).first; if (endsWith(path, "/gate")) { gate.push_back(path); } else if (endsWith(path, "/freq")) { freq.push_back(path); } else if (endsWith(path, "/gain")) { gain.push_back(path); } } } // MIDI velocity [0..127] void keyOn(int pitch, int velocity, bool trigger) { keyOn(pitch, float(velocity)/127.f, trigger); } // Normalized MIDI velocity [0..1] void keyOn(int pitch, float velocity, bool trigger) { // So that DSP state is always re-initialized fDSP->instanceClear(); for (size_t i = 0; i < fFreqPath.size(); i++) { setParamValue(fFreqPath[i], midiToFreq(pitch)); } for (size_t i = 0; i < fGatePath.size(); i++) { setParamValue(fGatePath[i], FAUSTFLOAT(1)); } for (size_t i = 0; i < fGainPath.size(); i++) { setParamValue(fGainPath[i], velocity); } fNote = pitch; } void keyOff(bool hard = false) { // No use of velocity for now... for (size_t i = 0; i < fGatePath.size(); i++) { setParamValue(fGatePath[i], FAUSTFLOAT(0)); } if (hard) { // Immediately stop voice fNote = kFreeVoice; } else { // Release voice fRelease = fMinRelease; fNote = kReleaseVoice; } } }; /** * A group of voices. */ struct dsp_voice_group { GroupUI fGroups; std::vector<dsp_voice*> fVoiceTable; // Individual voices dsp* fVoiceGroup; // Voices group to be used for GUI grouped control FAUSTFLOAT fPanic; bool fVoiceControl; bool fGroupControl; dsp_voice_group(uiCallback cb, void* arg, bool control, bool group) :fGroups(&fPanic, cb, arg), fVoiceGroup(0), fPanic(FAUSTFLOAT(0)), fVoiceControl(control), fGroupControl(group) {} virtual ~dsp_voice_group() { for (size_t i = 0; i < fVoiceTable.size(); i++) { delete fVoiceTable[i]; } delete fVoiceGroup; } void addVoice(dsp_voice* voice) { fVoiceTable.push_back(voice); } void clearVoices() { fVoiceTable.clear(); } void init() { // Groups all uiItem for a given path fVoiceGroup = new proxy_dsp(fVoiceTable[0]); fVoiceGroup->buildUserInterface(&fGroups); for (size_t i = 0; i < fVoiceTable.size(); i++) { fVoiceTable[i]->buildUserInterface(&fGroups); } } void instanceResetUserInterface() { for (size_t i = 0; i < fVoiceTable.size(); i++) { fVoiceTable[i]->instanceResetUserInterface(); } } void buildUserInterface(UI* ui_interface) { if (fVoiceTable.size() > 1) { ui_interface->openTabBox("Polyphonic"); // Grouped voices UI ui_interface->openVerticalBox("Voices"); ui_interface->addButton("Panic", &fPanic); fVoiceGroup->buildUserInterface(ui_interface); ui_interface->closeBox(); // If not grouped, also add individual voices UI if (!fGroupControl) { for (size_t i = 0; i < fVoiceTable.size(); i++) { char buffer[32]; snprintf(buffer, 32, ((fVoiceTable.size() < 8) ? "Voice%ld" : "V%ld"), long(i+1)); ui_interface->openHorizontalBox(buffer); fVoiceTable[i]->buildUserInterface(ui_interface); ui_interface->closeBox(); } } ui_interface->closeBox(); } else { fVoiceTable[0]->buildUserInterface(ui_interface); } } }; /** * Base class for MIDI controllable DSP. */ #ifdef EMCC #endif class dsp_poly : public decorator_dsp, public midi, public JSONControl { protected: #ifdef EMCC MapUI fMapUI; std::string fJSON; midi_handler fMIDIHandler; MidiUI fMIDIUI; #endif public: #ifdef EMCC dsp_poly(dsp* dsp):decorator_dsp(dsp), fMIDIUI(&fMIDIHandler) { JSONUI jsonui(getNumInputs(), getNumOutputs()); buildUserInterface(&jsonui); fJSON = jsonui.JSON(true); buildUserInterface(&fMapUI); buildUserInterface(&fMIDIUI); } #else dsp_poly(dsp* dsp):decorator_dsp(dsp) {} #endif virtual ~dsp_poly() {} // Reimplemented for EMCC #ifdef EMCC virtual int getNumInputs() { return decorator_dsp::getNumInputs(); } virtual int getNumOutputs() { return decorator_dsp::getNumOutputs(); } virtual void buildUserInterface(UI* ui_interface) { decorator_dsp::buildUserInterface(ui_interface); } virtual int getSampleRate() { return decorator_dsp::getSampleRate(); } virtual void init(int sample_rate) { decorator_dsp::init(sample_rate); } virtual void instanceInit(int sample_rate) { decorator_dsp::instanceInit(sample_rate); } virtual void instanceConstants(int sample_rate) { decorator_dsp::instanceConstants(sample_rate); } virtual void instanceResetUserInterface() { decorator_dsp::instanceResetUserInterface(); } virtual void instanceClear() { decorator_dsp::instanceClear(); } virtual dsp_poly* clone() { return new dsp_poly(fDSP->clone()); } virtual void metadata(Meta* m) { decorator_dsp::metadata(m); } // Additional API std::string getJSON() { return fJSON; } virtual void setParamValue(const std::string& path, FAUSTFLOAT value) { fMapUI.setParamValue(path, value); GUI::updateAllGuis(); } virtual FAUSTFLOAT getParamValue(const std::string& path) { return fMapUI.getParamValue(path); } virtual void computeJS(int count, uintptr_t inputs, uintptr_t outputs) { decorator_dsp::compute(count, reinterpret_cast<FAUSTFLOAT**>(inputs),reinterpret_cast<FAUSTFLOAT**>(outputs)); } #endif virtual MapUI* keyOn(int channel, int pitch, int velocity) { return midi::keyOn(channel, pitch, velocity); } virtual void keyOff(int channel, int pitch, int velocity) { midi::keyOff(channel, pitch, velocity); } virtual void keyPress(int channel, int pitch, int press) { midi::keyPress(channel, pitch, press); } virtual void chanPress(int channel, int press) { midi::chanPress(channel, press); } virtual void ctrlChange(int channel, int ctrl, int value) { midi::ctrlChange(channel, ctrl, value); } virtual void ctrlChange14bits(int channel, int ctrl, int value) { midi::ctrlChange14bits(channel, ctrl, value); } virtual void pitchWheel(int channel, int wheel) { #ifdef EMCC fMIDIUI.pitchWheel(0., channel, wheel); GUI::updateAllGuis(); #else midi::pitchWheel(channel, wheel); #endif } virtual void progChange(int channel, int pgm) { midi::progChange(channel, pgm); } // Group API virtual void setGroup(bool group) {} virtual bool getGroup() { return false; } }; /** * Polyphonic DSP: groups a set of DSP to be played together or triggered by MIDI. * * All voices are preallocated by cloning the single DSP voice given at creation time. * Dynamic voice allocation is done in 'getFreeVoice' */ class ue_binaural_decoder_poly : public dsp_voice_group, public dsp_poly { private: FAUSTFLOAT** fMixBuffer; int fDate; FAUSTFLOAT mixCheckVoice(int count, FAUSTFLOAT** outputBuffer, FAUSTFLOAT** mixBuffer) { FAUSTFLOAT level = 0; for (int i = 0; i < getNumOutputs(); i++) { FAUSTFLOAT* mixChannel = mixBuffer[i]; FAUSTFLOAT* outChannel = outputBuffer[i]; for (int j = 0; j < count; j++) { level = std::max<FAUSTFLOAT>(level, (FAUSTFLOAT)fabs(outChannel[j])); mixChannel[j] += outChannel[j]; } } return level; } void mixVoice(int count, FAUSTFLOAT** outputBuffer, FAUSTFLOAT** mixBuffer) { for (int i = 0; i < getNumOutputs(); i++) { FAUSTFLOAT* mixChannel = mixBuffer[i]; FAUSTFLOAT* outChannel = outputBuffer[i]; for (int j = 0; j < count; j++) { mixChannel[j] += outChannel[j]; } } } void clearOutput(int count, FAUSTFLOAT** mixBuffer) { for (int i = 0; i < getNumOutputs(); i++) { memset(mixBuffer[i], 0, count * sizeof(FAUSTFLOAT)); } } int getPlayingVoice(int pitch) { int voice_playing = kNoVoice; int oldest_date_playing = INT_MAX; for (size_t i = 0; i < fVoiceTable.size(); i++) { if (fVoiceTable[i]->fNote == pitch) { // Keeps oldest playing voice if (fVoiceTable[i]->fDate < oldest_date_playing) { oldest_date_playing = fVoiceTable[i]->fDate; voice_playing = int(i); } } } return voice_playing; } // Always returns a voice int getFreeVoice() { int voice = kNoVoice; // Looks for the first available voice for (size_t i = 0; i < fVoiceTable.size(); i++) { if (fVoiceTable[i]->fNote == kFreeVoice) { voice = int(i); goto result; } } { // Otherwise steal one int voice_release = kNoVoice; int voice_playing = kNoVoice; int oldest_date_release = INT_MAX; int oldest_date_playing = INT_MAX; // Scan all voices for (size_t i = 0; i < fVoiceTable.size(); i++) { if (fVoiceTable[i]->fNote == kReleaseVoice) { // Keeps oldest release voice if (fVoiceTable[i]->fDate < oldest_date_release) { oldest_date_release = fVoiceTable[i]->fDate; voice_release = int(i); } } else { // Otherwise keeps oldest playing voice if (fVoiceTable[i]->fDate < oldest_date_playing) { oldest_date_playing = fVoiceTable[i]->fDate; voice_playing = int(i); } } } // Then decide which one to steal if (oldest_date_release != INT_MAX) { std::cout << "Steal release voice : voice_date " << fVoiceTable[voice_release]->fDate << " cur_date = " << fDate << " voice = " << voice_release << std::endl; voice = voice_release; goto result; } else if (oldest_date_playing != INT_MAX) { std::cout << "Steal playing voice : voice_date " << fVoiceTable[voice_playing]->fDate << " cur_date = " << fDate << " voice = " << voice_playing << std::endl; voice = voice_playing; goto result; } else { assert(false); return kNoVoice; } } result: fVoiceTable[voice]->fDate = fDate++; fVoiceTable[voice]->fNote = kActiveVoice; return voice; } static void panic(FAUSTFLOAT val, void* arg) { if (val == FAUSTFLOAT(1)) { static_cast<ue_binaural_decoder_poly*>(arg)->allNotesOff(true); } } bool checkPolyphony() { if (fVoiceTable.size() > 0) { return true; } else { std::cout << "DSP is not polyphonic...\n"; return false; } } public: /** * Constructor. * * @param dsp - the dsp to be used for one voice. Beware: ue_binaural_decoder_poly will use and finally delete the pointer. * @param nvoices - number of polyphony voices, should be at least 1 * @param control - whether voices will be dynamically allocated and controlled (typically by a MIDI controler). * If false all voices are always running. * @param group - if true, voices are not individually accessible, a global "Voices" tab will automatically dispatch * a given control on all voices, assuming GUI::updateAllGuis() is called. * If false, all voices can be individually controlled. * setGroup/getGroup methods can be used to set/get the group state. * */ ue_binaural_decoder_poly(dsp* dsp, int nvoices, bool control = false, bool group = true) : dsp_voice_group(panic, this, control, group), dsp_poly(dsp) // dsp parameter is deallocated by ~dsp_poly { fDate = 0; // Create voices assert(nvoices > 0); for (int i = 0; i < nvoices; i++) { addVoice(new dsp_voice(dsp->clone())); } // Init audio output buffers fMixBuffer = new FAUSTFLOAT*[getNumOutputs()]; for (int i = 0; i < getNumOutputs(); i++) { fMixBuffer[i] = new FAUSTFLOAT[MIX_BUFFER_SIZE]; } dsp_voice_group::init(); } virtual ~ue_binaural_decoder_poly() { for (int i = 0; i < getNumOutputs(); i++) { delete[] fMixBuffer[i]; } delete[] fMixBuffer; } // DSP API void buildUserInterface(UI* ui_interface) { dsp_voice_group::buildUserInterface(ui_interface); } void init(int sample_rate) { decorator_dsp::init(sample_rate); fVoiceGroup->init(sample_rate); fPanic = FAUSTFLOAT(0); // Init voices for (size_t i = 0; i < fVoiceTable.size(); i++) { fVoiceTable[i]->init(sample_rate); } } void instanceInit(int samplingFreq) { instanceConstants(samplingFreq); instanceResetUserInterface(); instanceClear(); } void instanceConstants(int sample_rate) { decorator_dsp::instanceConstants(sample_rate); fVoiceGroup->instanceConstants(sample_rate); // Init voices for (size_t i = 0; i < fVoiceTable.size(); i++) { fVoiceTable[i]->instanceConstants(sample_rate); } } void instanceResetUserInterface() { decorator_dsp::instanceResetUserInterface(); fVoiceGroup->instanceResetUserInterface(); fPanic = FAUSTFLOAT(0); for (size_t i = 0; i < fVoiceTable.size(); i++) { fVoiceTable[i]->instanceResetUserInterface(); } } void instanceClear() { decorator_dsp::instanceClear(); fVoiceGroup->instanceClear(); for (size_t i = 0; i < fVoiceTable.size(); i++) { fVoiceTable[i]->instanceClear(); } } virtual ue_binaural_decoder_poly* clone() { return new ue_binaural_decoder_poly(fDSP->clone(), int(fVoiceTable.size()), fVoiceControl, fGroupControl); } void compute(int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { assert(count <= MIX_BUFFER_SIZE); // First clear the outputs clearOutput(count, outputs); if (fVoiceControl) { // Mix all playing voices for (size_t i = 0; i < fVoiceTable.size(); i++) { dsp_voice* voice = fVoiceTable[i]; if (voice->fNote != kFreeVoice) { voice->compute(count, inputs, fMixBuffer); // Mix it in result voice->fLevel = mixCheckVoice(count, fMixBuffer, outputs); // Check the level to possibly set the voice in kFreeVoice again voice->fRelease -= count; if ((voice->fNote == kReleaseVoice) && (voice->fRelease < 0) && (voice->fLevel < VOICE_STOP_LEVEL)) { voice->fNote = kFreeVoice; } } } } else { // Mix all voices for (size_t i = 0; i < fVoiceTable.size(); i++) { fVoiceTable[i]->compute(count, inputs, fMixBuffer); mixVoice(count, fMixBuffer, outputs); } } } void compute(double date_usec, int count, FAUSTFLOAT** inputs, FAUSTFLOAT** outputs) { compute(count, inputs, outputs); } // Terminate all active voices, gently or immediately (depending of 'hard' value) void allNotesOff(bool hard = false) { for (size_t i = 0; i < fVoiceTable.size(); i++) { fVoiceTable[i]->keyOff(hard); } } // Additional polyphonic API MapUI* newVoice() { int voice = getFreeVoice(); // So that DSP state is always re-initialized fVoiceTable[voice]->instanceClear(); return fVoiceTable[voice]; } void deleteVoice(MapUI* voice) { std::vector<dsp_voice*>::iterator it = find(fVoiceTable.begin(), fVoiceTable.end(), reinterpret_cast<dsp_voice*>(voice)); if (it != fVoiceTable.end()) { (*it)->keyOff(); } else { std::cout << "Voice not found\n"; } } // Group API void setGroup(bool group) { fGroupControl = group; } bool getGroup() { return fGroupControl; } // MIDI API MapUI* keyOn(int channel, int pitch, int velocity) { if (checkPolyphony()) { int voice = getFreeVoice(); fVoiceTable[voice]->keyOn(pitch, velocity, true); return fVoiceTable[voice]; } else { return 0; } } void keyOff(int channel, int pitch, int velocity = 127) { if (checkPolyphony()) { int voice = getPlayingVoice(pitch); if (voice != kNoVoice) { fVoiceTable[voice]->keyOff(); } else { std::cout << "Playing pitch = " << pitch << " not found\n"; } } } void ctrlChange(int channel, int ctrl, int value) { if (ctrl == ALL_NOTES_OFF || ctrl == ALL_SOUND_OFF) { allNotesOff(); } } }; /** * Polyphonic DSP with an integrated effect. fPolyDSP will respond to MIDI messages. */ class dsp_poly_effect : public dsp_poly { private: dsp_poly* fPolyDSP; public: dsp_poly_effect(dsp_poly* dsp1, dsp* dsp2) :dsp_poly(dsp2), fPolyDSP(dsp1) {} virtual ~dsp_poly_effect() { // dsp_poly_effect is also a decorator_dsp, which will free fPolyDSP } // MIDI API MapUI* keyOn(int channel, int pitch, int velocity) { return fPolyDSP->keyOn(channel, pitch, velocity); } void keyOff(int channel, int pitch, int velocity) { fPolyDSP->keyOff(channel, pitch, velocity); } void keyPress(int channel, int pitch, int press) { fPolyDSP->keyPress(channel, pitch, press); } void chanPress(int channel, int press) { fPolyDSP->chanPress(channel, press); } void ctrlChange(int channel, int ctrl, int value) { fPolyDSP->ctrlChange(channel, ctrl, value); } void ctrlChange14bits(int channel, int ctrl, int value) { fPolyDSP->ctrlChange14bits(channel, ctrl, value); } void pitchWheel(int channel, int wheel) { fPolyDSP->pitchWheel(channel, wheel); } void progChange(int channel, int pgm) { fPolyDSP->progChange(channel, pgm); } // Group API void setGroup(bool group) { fPolyDSP->setGroup(group); } bool getGroup() { return fPolyDSP->getGroup(); } }; /** * Polyphonic DSP factory class. Helper code to support polyphonic DSP source with an integrated effect. */ struct dsp_poly_factory : public dsp_factory { dsp_factory* fProcessFactory; dsp_factory* fEffectFactory; std::string getEffectCode(const std::string& dsp_content) { std::stringstream effect_code; effect_code << "adapt(1,1) = _; adapt(2,2) = _,_; adapt(1,2) = _ <: _,_; adapt(2,1) = _,_ :> _;"; effect_code << "adaptor(F,G) = adapt(outputs(F),inputs(G)); dsp_code = environment{ " << dsp_content << " };"; effect_code << "process = adaptor(dsp_code.process, dsp_code.effect) : dsp_code.effect;"; return effect_code.str(); } dsp_poly_factory(dsp_factory* process_factory = NULL, dsp_factory* effect_factory = NULL): fProcessFactory(process_factory) ,fEffectFactory(effect_factory) {} virtual ~dsp_poly_factory() {} virtual std::string getName() { return fProcessFactory->getName(); } virtual std::string getSHAKey() { return fProcessFactory->getSHAKey(); } virtual std::string getDSPCode() { return fProcessFactory->getDSPCode(); } virtual std::string getCompileOptions() { return fProcessFactory->getCompileOptions(); } virtual std::vector<std::string> getLibraryList() { return fProcessFactory->getLibraryList(); } virtual std::vector<std::string> getIncludePathnames() { return fProcessFactory->getIncludePathnames(); } virtual void setMemoryManager(dsp_memory_manager* manager) { fProcessFactory->setMemoryManager(manager); if (fEffectFactory) { fEffectFactory->setMemoryManager(manager); } } virtual dsp_memory_manager* getMemoryManager() { return fProcessFactory->getMemoryManager(); } /* Create a new polyphonic DSP instance with global effect, to be deleted with C++ 'delete' * * @param nvoices - number of polyphony voices, should be at least 1 * @param control - whether voices will be dynamically allocated and controlled (typically by a MIDI controler). * If false all voices are always running. * @param group - if true, voices are not individually accessible, a global "Voices" tab will automatically dispatch * a given control on all voices, assuming GUI::updateAllGuis() is called. * If false, all voices can be individually controlled. */ dsp_poly* createPolyDSPInstance(int nvoices, bool control, bool group) { dsp_poly* dsp_poly = new ue_binaural_decoder_poly(fProcessFactory->createDSPInstance(), nvoices, control, group); if (fEffectFactory) { // the 'dsp_poly' object has to be controlled with MIDI, so kept separated from new dsp_sequencer(...) object return new dsp_poly_effect(dsp_poly, new dsp_sequencer(dsp_poly, fEffectFactory->createDSPInstance())); } else { return new dsp_poly_effect(dsp_poly, dsp_poly); } } /* Create a new DSP instance, to be deleted with C++ 'delete' */ dsp* createDSPInstance() { return fProcessFactory->createDSPInstance(); } }; #endif // __poly_dsp__ /************************** END poly-dsp.h **************************/ std::list<GUI*> GUI::fGuiList; ztimedmap GUI::gTimedZoneMap; static t_class* faust_class; /*--------------------------------------------------------------------------*/ static const char* getCodeSize() { int tmp; return (sizeof(&tmp) == 8) ? "64 bits" : "32 bits"; } /*--------------------------------------------------------------------------*/ typedef struct faust { t_pxobject m_ob; t_atom *m_seen, *m_want; map<string, vector<t_object*> > m_output_table; short m_where; bool m_mute; void** m_args; mspUI* m_dspUI; dsp* m_dsp; ue_binaural_decoder_poly* m_dsp_poly; void* m_control_outlet; char* m_json; t_systhread_mutex m_mutex; int m_Inputs; int m_Outputs; SaveUI* m_savedUI; #ifdef MIDICTRL MidiUI* m_midiUI; midi_handler* m_midiHandler; #endif #ifdef SOUNDFILE SoundUI* m_soundInterface; #endif #ifdef OSCCTRL OSCUI* m_oscInterface; #endif } t_faust; void faust_create_jsui(t_faust* x); void faust_make_json(t_faust* x); /*--------------------------------------------------------------------------*/ void faust_allocate(t_faust* x, int nvoices) { // Delete old delete x->m_dsp; x->m_dspUI->clear(); if (nvoices > 0) { #ifdef POST post("polyphonic DSP voices = %d", nvoices); #endif x->m_dsp_poly = new ue_binaural_decoder_poly(new ue_binaural_decoder(), nvoices, true, true); #ifdef POLY2 x->m_dsp = new dsp_sequencer(x->m_dsp_poly, new effect()); #else x->m_dsp = x->m_dsp_poly; #endif #ifdef MIDICTRL x->m_midiHandler->addMidiIn(x->m_dsp_poly); #endif } else { #ifdef POST post("monophonic DSP"); #endif #if (DOWN_SAMPLING > 0) #if (FILTER_TYPE == 0) x->m_dsp = new dsp_down_sampler<Identity<Double<1,1>, DOWN_SAMPLING>>(new ue_binaural_decoder()); #elif (FILTER_TYPE == 1) x->m_dsp = new dsp_down_sampler<LowPass3<Double<45,100>, DOWN_SAMPLING, double>>(new ue_binaural_decoder()); #elif (FILTER_TYPE == 2) x->m_dsp = new dsp_down_sampler<LowPass4<Double<45,100>, DOWN_SAMPLING, double>>(new ue_binaural_decoder()); #elif (FILTER_TYPE == 3) x->m_dsp = new dsp_down_sampler<LowPass3e<Double<45,100>, DOWN_SAMPLING, double>>(new ue_binaural_decoder()); #elif (FILTER_TYPE == 4) x->m_dsp = new dsp_down_sampler<LowPass6eé<Double<45,100>, DOWN_SAMPLING, double>>(new ue_binaural_decoder()); #else #error "ERROR : Filter type must be in [0..4] range" #endif #elif (UP_SAMPLING > 0) #if (FILTER_TYPE == 0) x->m_dsp = new dsp_up_sampler<Identity<Double<1,1>, UP_SAMPLING>>(new ue_binaural_decoder()); #elif (FILTER_TYPE == 1) x->m_dsp = new dsp_up_sampler<LowPass3<Double<45,100>, UP_SAMPLING, double>>(new ue_binaural_decoder()); #elif (FILTER_TYPE == 2) x->m_dsp = new dsp_up_sampler<LowPass4<Double<45,100>, UP_SAMPLING, double>>(new ue_binaural_decoder()); #elif (FILTER_TYPE == 3) x->m_dsp = new dsp_up_sampler<LowPass3e<Double<45,100>, UP_SAMPLING, double>>(new ue_binaural_decoder()); #elif (FILTER_TYPE == 4) x->m_dsp = new dsp_up_sampler<LowPass6e<Double<45,100>, UP_SAMPLING, double>>(new ue_binaural_decoder()); #else #error "ERROR : Filter type must be in [0..4] range" #endif #else x->m_dsp = new ue_binaural_decoder(); #endif } #ifdef MIDICTRL x->m_dsp->buildUserInterface(x->m_midiUI); #endif // Possible sample adaptation if (sizeof(FAUSTFLOAT) == 4) { x->m_dsp = new dsp_sample_adapter<FAUSTFLOAT, double>(x->m_dsp); } } /*--------------------------------------------------------------------------*/ void faust_anything(t_faust* obj, t_symbol* s, short ac, t_atom* av) { bool res = false; string name = string((s)->s_name); // If no argument is there, consider it as a toggle message for a button if (ac == 0 && obj->m_dspUI->isValue(name)) { FAUSTFLOAT off = FAUSTFLOAT(0.0); FAUSTFLOAT on = FAUSTFLOAT(1.0); obj->m_dspUI->setValue(name, off); obj->m_dspUI->setValue(name, on); av[0].a_type = A_FLOAT; av[0].a_w.w_float = off; faust_anything(obj, s, 1, av); } else if (mspUI::checkDigit(name)) { // List of values int pos, ndigit = 0; for (pos = name.size() - 1; pos >= 0; pos--) { if (isdigit(name[pos]) || name[pos] == ' ') { ndigit++; } else { break; } } pos++; string prefix = name.substr(0, pos); string num_base = name.substr(pos); int num = atoi(num_base.c_str()); int i; t_atom* ap; // Increment ap each time to get to the next atom for (i = 0, ap = av; i < ac; i++, ap++) { FAUSTFLOAT value; switch (atom_gettype(ap)) { case A_LONG: value = FAUSTFLOAT(ap[0].a_w.w_long); break; case A_FLOAT: value = FAUSTFLOAT(ap[0].a_w.w_float); break; default: post("Invalid argument in parameter setting"); return; } string num_val = to_string(num + i); stringstream param_name; param_name << prefix; for (int i = 0; i < ndigit - mspUI::countDigit(num_val); i++) { param_name << ' '; } param_name << num_val; // Try special naming scheme for list of parameters res = obj->m_dspUI->setValue(param_name.str(), value); // Otherwise try standard name if (!res) { res = obj->m_dspUI->setValue(name, value); } if (!res) { post("Unknown parameter : %s", (s)->s_name); } } } else { // Standard parameter name FAUSTFLOAT value = (av[0].a_type == A_LONG) ? FAUSTFLOAT(av[0].a_w.w_long) : FAUSTFLOAT(av[0].a_w.w_float); res = obj->m_dspUI->setValue(name, value); if (!res) { post("Unknown parameter : %s", (s)->s_name); } } } /*--------------------------------------------------------------------------*/ void faust_polyphony(t_faust* x, t_symbol* s, short ac, t_atom* av) { if (systhread_mutex_lock(x->m_mutex) == MAX_ERR_NONE) { #ifdef MIDICTRL if (x->m_dsp_poly) { x->m_midiHandler->removeMidiIn(x->m_dsp_poly); } #endif faust_allocate(x, av[0].a_w.w_long); // Initialize at the system's sampling rate x->m_dsp->init(long(sys_getsr())); // Initialize User Interface (here connnection with controls) x->m_dsp->buildUserInterface(x->m_dspUI); // Prepare JSON faust_make_json(x); // Send JSON to JS script faust_create_jsui(x); // Load old controller state x->m_dsp->buildUserInterface(x->m_savedUI); systhread_mutex_unlock(x->m_mutex); } else { post("Mutex lock cannot be taken..."); } } /*--------------------------------------------------------------------------*/ #ifdef MIDICTRL void faust_midievent(t_faust* x, t_symbol* s, short ac, t_atom* av) { if (ac > 0) { int type = (int)av[0].a_w.w_long & 0xf0; int channel = (int)av[0].a_w.w_long & 0x0f; if (ac == 1) { x->m_midiHandler->handleSync(0.0, av[0].a_w.w_long); } else if (ac == 2) { x->m_midiHandler->handleData1(0.0, type, channel, av[1].a_w.w_long); } else if (ac == 3) { x->m_midiHandler->handleData2(0.0, type, channel, av[1].a_w.w_long, av[2].a_w.w_long); } } } #endif /*--------------------------------------------------------------------------*/ void faust_create_jsui(t_faust* x) { t_object *patcher, *box, *obj; object_obex_lookup((t_object*)x, gensym("#P"), &patcher); for (box = jpatcher_get_firstobject(patcher); box; box = jbox_get_nextobject(box)) { obj = jbox_get_object(box); // Notify JSON if (obj && strcmp(object_classname(obj)->s_name, "js") == 0) { t_atom json; atom_setsym(&json, gensym(x->m_json)); object_method_typed(obj, gensym("anything"), 1, &json, 0); } } // Keep all outputs to be notified in update_outputs x->m_output_table.clear(); for (box = jpatcher_get_firstobject(patcher); box; box = jbox_get_nextobject(box)) { obj = jbox_get_object(box); t_symbol* scriptingname = jbox_get_varname(obj); // scripting name // Keep control outputs if (scriptingname && x->m_dspUI->isOutputValue(scriptingname->s_name)) { x->m_output_table[scriptingname->s_name].push_back(obj); } } } /*--------------------------------------------------------------------------*/ void faust_update_outputs(t_faust* x) { for (auto& it1 : x->m_output_table) { bool new_val = false; FAUSTFLOAT value = x->m_dspUI->getOutputValue(it1.first, new_val); if (new_val) { t_atom at_value; atom_setfloat(&at_value, value); for (auto& it2 : it1.second) { object_method_typed(it2, gensym("float"), 1, &at_value, 0); } } } } /*--------------------------------------------------------------------------*/ void faust_make_json(t_faust* x) { // Prepare JSON if (x->m_json) free(x->m_json); JSONUI builder(x->m_dsp->getNumInputs(), x->m_dsp->getNumOutputs()); x->m_dsp->metadata(&builder); x->m_dsp->buildUserInterface(&builder); x->m_json = strdup(builder.JSON().c_str()); } /*--------------------------------------------------------------------------*/ void* faust_new(t_symbol* s, short ac, t_atom* av) { bool midi_sync = false; int nvoices = 0; ue_binaural_decoder* tmp_dsp = new ue_binaural_decoder(); MidiMeta::analyse(tmp_dsp, midi_sync, nvoices); delete tmp_dsp; t_faust* x = (t_faust*)object_alloc(faust_class); x->m_savedUI = new SaveLabelUI(); x->m_dspUI = NULL; x->m_dsp = NULL; x->m_dsp_poly = NULL; x->m_json = NULL; x->m_mute = false; #ifdef MIDICTRL x->m_midiHandler = new midi_handler(); x->m_midiUI = new MidiUI(x->m_midiHandler); #endif x->m_dspUI = new mspUI(); faust_allocate(x, nvoices); x->m_Inputs = x->m_dsp->getNumInputs(); x->m_Outputs = x->m_dsp->getNumOutputs(); x->m_control_outlet = outlet_new((t_pxobject*)x, (char*)"list"); // Initialize at the system's sampling rate x->m_dsp->init(long(sys_getsr())); // Initialize User Interface (here connnection with controls) x->m_dsp->buildUserInterface(x->m_dspUI); t_max_err err = systhread_mutex_new(&x->m_mutex, SYSTHREAD_MUTEX_NORMAL); if (err != MAX_ERR_NONE) { post("Cannot allocate mutex..."); } // Prepare JSON faust_make_json(x); int num_input; if (x->m_dspUI->isMulti()) { num_input = x->m_dsp->getNumInputs() + 1; } else { num_input = x->m_dsp->getNumInputs(); } x->m_args = (void**)calloc((num_input + x->m_dsp->getNumOutputs()) + 2, sizeof(void*)); /* Multi in */ dsp_setup((t_pxobject*)x, num_input); /* Multi out */ for (int i = 0; i < x->m_dsp->getNumOutputs(); i++) { outlet_new((t_pxobject*)x, (char*)"signal"); } ((t_pxobject*)x)->z_misc = Z_NO_INPLACE; // To assure input and output buffers are actually different #ifdef SOUNDFILE Max_Meta3 meta3; x->m_dsp->metadata(&meta3); string bundle_path_str = SoundUI::getBinaryPathFrom(meta3.fName); if (bundle_path_str == "") { post("Bundle_path '%s' cannot be found!", meta3.fName.c_str()); } x->m_soundInterface = new SoundUI(bundle_path_str); // SoundUI has to be dispatched on all internal voices if (x->m_dsp_poly) x->m_dsp_poly->setGroup(false); x->m_dsp->buildUserInterface(x->m_soundInterface); if (x->m_dsp_poly) x->m_dsp_poly->setGroup(true); #endif #ifdef OSCCTRL x->m_oscInterface = NULL; #endif // Send JSON to JS script faust_create_jsui(x); // Load old controller state x->m_dsp->buildUserInterface(x->m_savedUI); // Display controls #ifdef POST x->m_dspUI->displayControls(); #endif // Get attributes values attr_args_process(x, ac, av); return x; } #ifdef OSCCTRL // osc 'IP inport outport xmit bundle' /*--------------------------------------------------------------------------*/ void faust_osc(t_faust* x, t_symbol* s, short ac, t_atom* av) { if (ac == 5) { if (systhread_mutex_lock(x->m_mutex) == MAX_ERR_NONE) { delete x->m_oscInterface; const char* argv1[32]; int argc1 = 0; argv1[argc1++] = "Faust"; argv1[argc1++] = "-desthost"; argv1[argc1++] = atom_getsym(&av[0])->s_name; char inport[32]; snprintf(inport, 32, "%ld", long(av[1].a_w.w_long)); argv1[argc1++] = "-port"; argv1[argc1++] = inport; char outport[32]; snprintf(outport, 32, "%ld", long(av[2].a_w.w_long)); argv1[argc1++] = "-outport"; argv1[argc1++] = outport; char xmit[32]; snprintf(xmit, 32, "%ld", long(av[3].a_w.w_long)); argv1[argc1++] = "-xmit"; argv1[argc1++] = xmit; char bundle[32]; snprintf(bundle, 32, "%ld", long(av[4].a_w.w_long)); argv1[argc1++] = "-bundle"; argv1[argc1++] = bundle; x->m_oscInterface = new OSCUI("Faust", argc1, (char**)argv1); x->m_dsp->buildUserInterface(x->m_oscInterface); x->m_oscInterface->run(); post(x->m_oscInterface->getInfos().c_str()); systhread_mutex_unlock(x->m_mutex); } else { post("Mutex lock cannot be taken..."); } } else { post("Should be : osc 'IP inport outport xmit(0|1|2) bundle(0|1)'"); } } #endif /*--------------------------------------------------------------------------*/ // Reset controllers to init value and send [path, init, min, max] void faust_init(t_faust* x, t_symbol* s, short ac, t_atom* av) { // Reset internal state x->m_savedUI->reset(); // Input controllers for (mspUI::iterator it = x->m_dspUI->begin2(); it != x->m_dspUI->end2(); it++) { t_atom myList[4]; atom_setsym(&myList[0], gensym((*it).first.c_str())); atom_setfloat(&myList[1], (*it).second->getInitValue()); // init value atom_setfloat(&myList[2], (*it).second->getMinValue()); atom_setfloat(&myList[3], (*it).second->getMaxValue()); outlet_list(x->m_control_outlet, 0, 4, myList); } // Output controllers for (mspUI::iterator it = x->m_dspUI->begin4(); it != x->m_dspUI->end4(); it++) { t_atom myList[4]; atom_setsym(&myList[0], gensym((*it).first.c_str())); atom_setfloat(&myList[1], (*it).second->getInitValue()); // init value atom_setfloat(&myList[2], (*it).second->getMinValue()); atom_setfloat(&myList[3], (*it).second->getMaxValue()); outlet_list(x->m_control_outlet, 0, 4, myList); } } /*--------------------------------------------------------------------------*/ // Dump controllers as list of: [path, cur, init, min, max] void faust_dump(t_faust* x, t_symbol* s, short ac, t_atom* av) { // Input controllers for (mspUI::iterator it = x->m_dspUI->begin2(); it != x->m_dspUI->end2(); it++) { t_atom myList[4]; atom_setsym(&myList[0], gensym((*it).first.c_str())); atom_setfloat(&myList[1], (*it).second->getValue()); // cur value atom_setfloat(&myList[2], (*it).second->getMinValue()); atom_setfloat(&myList[3], (*it).second->getMaxValue()); outlet_list(x->m_control_outlet, 0, 4, myList); } // Output controllers for (mspUI::iterator it = x->m_dspUI->begin4(); it != x->m_dspUI->end4(); it++) { t_atom myList[4]; atom_setsym(&myList[0], gensym((*it).first.c_str())); atom_setfloat(&myList[1], (*it).second->getValue()); // cur value atom_setfloat(&myList[2], (*it).second->getMinValue()); atom_setfloat(&myList[3], (*it).second->getMaxValue()); outlet_list(x->m_control_outlet, 0, 4, myList); } } /*--------------------------------------------------------------------------*/ void faust_dblclick(t_faust* x, long inlet) { x->m_dspUI->displayControls(); } /*--------------------------------------------------------------------------*/ //11/13/2015 : faust_assist is actually called at each click in the patcher, so we now use 'faust_dblclick' to display the parameters... void faust_assist(t_faust* x, void* b, long msg, long a, char* dst) { if (msg == ASSIST_INLET) { if (a == 0) { if (x->m_dsp->getNumInputs() == 0) { sprintf(dst, "(message) : Unused Input"); } else { sprintf(dst, "(signal) : Audio Input %ld", (a+1)); } } else if (a < x->m_dsp->getNumInputs()) { sprintf(dst, "(signal) : Audio Input %ld", (a+1)); } } else if (msg == ASSIST_OUTLET) { if (a < x->m_dsp->getNumOutputs()) { sprintf(dst, "(signal) : Audio Output %ld", (a+1)); } else { sprintf(dst, "(list) : [path, cur|init, min, max]*"); } } } /*--------------------------------------------------------------------------*/ void faust_mute(t_faust* obj, t_symbol* s, short ac, t_atom* at) { if (atom_gettype(at) == A_LONG) { obj->m_mute = atom_getlong(at); } } /*--------------------------------------------------------------------------*/ void faust_free(t_faust* x) { dsp_free((t_pxobject*)x); delete x->m_dsp; delete x->m_dspUI; delete x->m_savedUI; if (x->m_args) free(x->m_args); if (x->m_json) free(x->m_json); systhread_mutex_free(x->m_mutex); #ifdef MIDICTRL // m_midiUI *must* be deleted before m_midiHandler delete x->m_midiUI; delete x->m_midiHandler; #endif #ifdef SOUNDFILE delete x->m_soundInterface; #endif #ifdef OSCCTRL delete x->m_oscInterface; #endif } /*--------------------------------------------------------------------------*/ void faust_perform64(t_faust* x, t_object* dsp64, double** ins, long numins, double** outs, long numouts, long sampleframes, long flags, void* userparam) { AVOIDDENORMALS; if (!x->m_mute && systhread_mutex_trylock(x->m_mutex) == MAX_ERR_NONE) { if (x->m_dsp) { if (x->m_dspUI->isMulti()) { x->m_dspUI->setMultiValues(reinterpret_cast<FAUSTFLOAT*>(ins[0]), sampleframes); x->m_dsp->compute(sampleframes, reinterpret_cast<FAUSTFLOAT**>(++ins), reinterpret_cast<FAUSTFLOAT**>(outs)); } else { x->m_dsp->compute(sampleframes, reinterpret_cast<FAUSTFLOAT**>(ins), reinterpret_cast<FAUSTFLOAT**>(outs)); } #ifdef OSCCTRL if (x->m_oscInterface) x->m_oscInterface->endBundle(); #endif faust_update_outputs(x); } #if defined(MIDICTRL) || defined(OSCCTRL) GUI::updateAllGuis(); #endif systhread_mutex_unlock(x->m_mutex); } else { // Write null buffers to outs for (int i = 0; i < numouts; i++) { memset(outs[i], 0, sizeof(double) * sampleframes); } } } /*--------------------------------------------------------------------------*/ void faust_dsp64(t_faust* x, t_object* dsp64, short* count, double samplerate, long maxvectorsize, long flags) { object_method(dsp64, gensym("dsp_add64"), x, faust_perform64, 0, NULL); } /*--------------------------------------------------------------------------*/ t_max_err faust_attr_set(t_faust* x, t_object* attr, long ac, t_atom* av) { if (ac && av) { t_symbol* attrname = (t_symbol*)object_method(attr, gensym("getname")); // Redirect on the generic message handling method faust_anything(x, attrname, ac, av); } return MAX_ERR_NONE; } /*--------------------------------------------------------------------------*/ #ifdef _WIN32 extern "C" int main(void) #else void ext_main(void* r) #endif { string file_name = string(FAUST_FILE_NAME); // Remove ".dsp" ending string class_name = file_name.erase(file_name.size()-4) + "~"; t_class* c = class_new(class_name.c_str(), (method)faust_new, (method)faust_free, sizeof(t_faust), 0L, A_GIMME, 0); class_addmethod(c, (method)faust_anything, "anything", A_GIMME, 0); class_addmethod(c, (method)faust_polyphony, "polyphony", A_GIMME, 0); #ifdef OSCCTRL class_addmethod(c, (method)faust_osc, "osc", A_GIMME, 0); #endif class_addmethod(c, (method)faust_init, "init", A_GIMME, 0); class_addmethod(c, (method)faust_dump, "dump", A_GIMME, 0); #ifdef MIDICTRL class_addmethod(c, (method)faust_midievent, "midievent", A_GIMME, 0); #endif class_addmethod(c, (method)faust_dsp64, "dsp64", A_CANT, 0); class_addmethod(c, (method)faust_dblclick, "dblclick", A_CANT, 0); class_addmethod(c, (method)faust_assist, "assist", A_CANT, 0); class_addmethod(c, (method)faust_mute, "mute", A_GIMME, 0); dsp* tmp_dsp = new ue_binaural_decoder(); mspUI tmp_UI; tmp_dsp->buildUserInterface(&tmp_UI); // Setup attributes int i = 0; if (sizeof(FAUSTFLOAT) == 4) { for (mspUI::iterator it = tmp_UI.begin1(); it != tmp_UI.end1(); it++, i++) { CLASS_ATTR_FLOAT(c, (*it).first.c_str(), 0, t_faust, m_ob); CLASS_ATTR_ACCESSORS(c, (*it).first.c_str(), NULL, (method)faust_attr_set); } } else { for (mspUI::iterator it = tmp_UI.begin1(); it != tmp_UI.end1(); it++, i++) { CLASS_ATTR_DOUBLE(c, (*it).first.c_str(), 0, t_faust, m_ob); CLASS_ATTR_ACCESSORS(c, (*it).first.c_str(), NULL, (method)faust_attr_set); } } class_dspinit(c); class_register(CLASS_BOX, c); faust_class = c; #ifdef POST post((char*)"Faust DSP object v%s (sample = %s bits code = %s)", EXTERNAL_VERSION, ((sizeof(FAUSTFLOAT) == 4) ? "32" : "64"), getCodeSize()); post((char*)"Copyright (c) 2012-2020 Grame"); #endif Max_Meta1 meta1; tmp_dsp->metadata(&meta1); if (meta1.fCount > 0) { #ifdef POST Max_Meta2 meta2; post("------------------------------"); tmp_dsp->metadata(&meta2); post("------------------------------"); #endif } delete(tmp_dsp); #ifdef _WIN32 return 0; #endif } /********************END ARCHITECTURE SECTION (part 2/2)****************/ #endif
230f1b9c314506328dab84d3f41c115654df9ff7
7c6d70f9fb2bc1aae675e6359f8bcc3026aef7f7
/engine/sdk/inc/RenderTextParam.h
8e53a0b6ff138fd834ad87dfc38ed1b38b6f3fa1
[]
no_license
lxq2537664558/RushGame
1143d05fbf5cba43ff81d350caca5134a9f7dfdd
361ecd2d44c80194460770d3c81355191b5f79eb
refs/heads/master
2020-05-16T23:51:15.655169
2014-04-25T03:43:35
2014-04-25T03:43:35
null
0
0
null
null
null
null
GB18030
C++
false
false
8,046
h
#pragma once #include "CColor.h" #include "CVector3.h" #include "CRectangle.h" #include "CGraphicMallocObject.h" namespace sqr { /// 字体绘制效果.表情是一种特殊的字体 struct FontEffect { enum { Italic = 1<<0, ///< 斜体 Outline = 1<<1, ///< 描边 Shadow = 1<<2, ///< 阴影 Gradual = 1<<3, ///< 渐变色 Vertical = 1<<29, ///< 文字竖排 AutoAdapy = 1<<30, ///< 表情自适应 Multiline = 1<<31, ///< 多行 }; typedef uint32 Mask; }; struct RenderTextParam : public CGraphicMallocObject { public: RenderTextParam(float size); RenderTextParam(); public: void SetPosition(float x, float y, float z = 0.0f, float offset = 0.0f); void SetPosition(const CVector3f& pos); void SetOffset(float offset); const CVector3f& GetPosition() const; float GetSize() const; void SetText(const char* text); void SetText(const char* text, size_t length); void SetText(const string& text); void SetText(const wstring& text); const wchar_t* GetText() const; void SetColor(const CColor& color); const CColor& GetColor() const; void SetGradualColor(const CColor& color); const CColor& GetGradualColor() const; void SetBackColor(const CColor& color); const CColor& GetBackColor() const; void SetRect(const CFRect& rect); const CFRect& GetRect() const; void SetMultiline(bool multiline); bool IsMultiline() const; void SetVertical(bool Vertical); bool IsVertical() const; void SetOutline(bool outline); bool IsOutline() const; void SetShadow(bool shadow); bool IsShadow() const; void SetItalic(bool italic); bool IsItalic() const; void SetFontEffect(FontEffect::Mask mask); FontEffect::Mask GetFontEffect() const; void SetIdx(uint8 idx); const uint8 GetIdx() const; private: CVector3f m_position; CFRect m_rect; GWString m_text; CColor m_color; CColor m_gradualColor; CColor m_backColor; float m_size; uint8 m_idx; FontEffect::Mask m_effectMask; }; //------------------------------------------------------------------------------ inline void RenderTextParam::SetText( const string& text ) { SetText(text.c_str()); } //------------------------------------------------------------------------------ inline void RenderTextParam::SetText( const char* text, size_t length ) { if(length != -1) SetText(string(text, length)); else SetText(text); } //------------------------------------------------------------------------------ inline void RenderTextParam::SetText( const wstring& text ) { m_text = text.c_str(); } //------------------------------------------------------------------------------ inline float RenderTextParam::GetSize() const { return m_size; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetPosition( float x, float y, float z /*= 0.0f*/, float offset /*= 0.0f*/ ) { m_position.Init(x - offset, y, z); } //------------------------------------------------------------------------------ inline void RenderTextParam::SetOffset( float offset ) { m_position.x -= offset; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetGradualColor( const CColor& color ) { m_gradualColor = color; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetBackColor( const CColor& color ) { m_backColor = color; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetRect( const CFRect& rect ) { m_rect = rect; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetMultiline( bool multiline ) { if (multiline) m_effectMask |= FontEffect::Multiline; else m_effectMask &= ~FontEffect::Multiline; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetVertical( bool Vertical ) { if (Vertical) m_effectMask |= FontEffect::Vertical; else m_effectMask &= ~FontEffect::Vertical; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetOutline( bool outline ) { if (outline) m_effectMask |= FontEffect::Outline; else m_effectMask &= ~FontEffect::Outline; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetShadow( bool shadow ) { if (shadow) m_effectMask |= FontEffect::Shadow; else m_effectMask &= ~FontEffect::Shadow; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetItalic( bool italic ) { if (italic) m_effectMask |= FontEffect::Italic; else m_effectMask &= ~FontEffect::Italic; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetPosition( const CVector3f& pos ) { m_position = pos; } //------------------------------------------------------------------------------ inline const CVector3f& RenderTextParam::GetPosition() const { return m_position; } //------------------------------------------------------------------------------ inline const wchar_t* RenderTextParam::GetText() const { return m_text.c_str(); } //------------------------------------------------------------------------------ inline const CColor& RenderTextParam::GetColor() const { return m_color; } //------------------------------------------------------------------------------ inline void RenderTextParam::SetColor( const CColor& color) { m_color = color; } //------------------------------------------------------------------------------ inline const CColor& RenderTextParam::GetGradualColor() const { if (0 == m_gradualColor || (0 == (m_effectMask & FontEffect::Gradual))) return m_color; return m_gradualColor; } //------------------------------------------------------------------------------ inline const CColor& RenderTextParam::GetBackColor() const { return m_backColor; } //------------------------------------------------------------------------------ inline const CFRect& RenderTextParam::GetRect() const { return m_rect; } //------------------------------------------------------------------------------ inline bool RenderTextParam::IsMultiline() const { return 0 != (m_effectMask & FontEffect::Multiline); } //------------------------------------------------------------------------------ inline bool RenderTextParam::IsVertical() const { return 0 != (m_effectMask & FontEffect::Vertical); } //------------------------------------------------------------------------------ inline bool RenderTextParam::IsOutline() const { return 0 != (m_effectMask & FontEffect::Outline); } //------------------------------------------------------------------------------ inline bool RenderTextParam::IsShadow() const { return 0 != (m_effectMask & FontEffect::Shadow); } //------------------------------------------------------------------------------ inline bool RenderTextParam::IsItalic() const { return 0 != (m_effectMask & FontEffect::Italic); } //------------------------------------------------------------------------------ inline void RenderTextParam::SetFontEffect( FontEffect::Mask mask ) { m_effectMask = mask; } //------------------------------------------------------------------------------ inline FontEffect::Mask RenderTextParam::GetFontEffect() const { return m_effectMask; } //------------------------------------------------------------------------------- inline void RenderTextParam::SetIdx(uint8 idx) { m_idx = idx; } //------------------------------------------------------------------------------- inline const uint8 RenderTextParam::GetIdx() const { return m_idx; } }
11d9b20d9d50292749ac4697b42ce887bedf30d9
2f814827ffab9d8d9cc23cb4c3622feb45fa5770
/PWGGA/GammaConv/AliAnalysisTaskElectronStudies.cxx
4cd2ba5d738b167d721896605d7bdad0d9121ec4
[]
permissive
urasantonio/AliPhysics
dd3a851f84674846e45f4b1fdea65700dee80223
8ca4a9abc72a6b94e75048d08748a1debf41873e
refs/heads/master
2022-12-17T21:54:22.246566
2020-09-11T14:04:20
2020-09-11T14:04:20
268,796,481
1
0
BSD-3-Clause
2020-09-11T13:50:03
2020-06-02T12:35:23
C++
UTF-8
C++
false
false
40,561
cxx
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Authors: Florian Jonas * * Version 1.0 * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #include "AliAnalysisTaskElectronStudies.h" #include "TChain.h" #include "TRandom.h" #include "AliAnalysisManager.h" #include "TParticle.h" #include "TVectorF.h" #include "AliPIDResponse.h" #include "TFile.h" #include "AliESDtrackCuts.h" #include "AliAODMCParticle.h" #include "AliAODConversionPhoton.h" #include "AliAODMCHeader.h" #include "AliAODEvent.h" #include "AliMultSelection.h" #include "AliAODCaloCluster.h" #include "AliAODTrack.h" #include "AliVTrack.h" #include "AliEMCALRecoUtilsBase.h" #include "AliAODConversionMother.h" #include "TObjectTable.h" ClassImp(AliAnalysisTaskElectronStudies) //________________________________________________________________________ AliAnalysisTaskElectronStudies::AliAnalysisTaskElectronStudies() : AliAnalysisTaskSE(), fInputEvent(NULL), fMCEvent(NULL), fWeightJetJetMC(1), fOutputList(NULL), fAnalysisTree(NULL), fIsMC(0), fIsHeavyIon(0), fV0Reader(NULL), fV0ReaderName(""), fPIDResponse(NULL), fReaderGammas(NULL), fAODMCTrackArray(NULL), fGeomEMCAL(NULL), fCorrTaskSetting(""), fEventCuts(NULL), fClusterCutsEMC(NULL), fTMCuts(NULL), fConvCuts(NULL), fCaloUtils(NULL), fMinClsTPC(0), fChi2PerClsTPC(9999), fMinClsITS(0), fEtaCut(9999), fPtCut(0), fYMCCut(9999), fMinNsigmaElec(-1), fMaxNsigmaElec(3), fMatchingParamsPhi(), fMatchingParamsEta(), fUseRTrackMatching(kFALSE), fRTrackMatching(999), fHistoNEvents(NULL), fHistoNEventsWOWeight(NULL), fPtElectronTrack(NULL), fPtElectronTrackInEmcalAcc(NULL), fTruePtCluster(NULL), fTruePtElectronCluster(NULL), fTruePtElectronClusterMatchedWithTrack(NULL), fTruePtElectronTrack(NULL), fTruePtElectronTrackInEmcalAcc(NULL), fGenPtElectrons(NULL), fGenPtElectronsInEmcalAcc(NULL), fTreeBuffSize(60*1024*1024), fMemCountAOD(0), fTrackMatcherRunningMode(0), fBuffer_ClusterE(0), fBuffer_ClusterEta(0), fBuffer_ClusterPhi(0), fBuffer_ClusterM02(0), fBuffer_ClusterM20(0), fBuffer_Track_Pt(0), fBuffer_Track_P(0), fBuffer_Track_Eta(0), fBuffer_Track_Phi(0), fBuffer_Track_NSigmaElec(0), fBuffer_Track_IsFromV0(0), fBuffer_MC_True_Cluster_E(0), fBuffer_MC_True_Track_E(0), fBuffer_MC_True_Track_Pt(0), fBuffer_MC_True_Track_P(0), fBuffer_MC_Track_Is_Electron(0), fBuffer_MC_Cluster_Is_Electron(0), fBuffer_MC_ClusterTrack_Same_Electron(0), fBuffer_MC_JetJetWeight(1) { SetEtaMatching(0.010,4.07,-2.5); SetPhiMatching(0.015,3.65,3.65); } AliAnalysisTaskElectronStudies::AliAnalysisTaskElectronStudies(const char *name) : AliAnalysisTaskSE(name), fInputEvent(NULL), fMCEvent(NULL), fWeightJetJetMC(1), fOutputList(NULL), fAnalysisTree(NULL), fIsMC(0), fIsHeavyIon(0), fV0Reader(NULL), fV0ReaderName(""), fPIDResponse(NULL), fReaderGammas(NULL), fAODMCTrackArray(NULL), fGeomEMCAL(NULL), fCorrTaskSetting(""), fEventCuts(NULL), fClusterCutsEMC(NULL), fTMCuts(NULL), fConvCuts(NULL), fCaloUtils(NULL), fMinClsTPC(0), fChi2PerClsTPC(9999), fMinClsITS(0), fEtaCut(9999), fPtCut(0), fYMCCut(9999), fMinNsigmaElec(-1), fMaxNsigmaElec(3), fMatchingParamsPhi(), fMatchingParamsEta(), fUseRTrackMatching(kFALSE), fRTrackMatching(999), fHistoNEvents(NULL), fHistoNEventsWOWeight(NULL), fPtElectronTrack(NULL), fPtElectronTrackInEmcalAcc(NULL), fTruePtCluster(NULL), fTruePtElectronCluster(NULL), fTruePtElectronClusterMatchedWithTrack(NULL), fTruePtElectronTrack(NULL), fTruePtElectronTrackInEmcalAcc(NULL), fGenPtElectrons(NULL), fGenPtElectronsInEmcalAcc(NULL), fTreeBuffSize(60*1024*1024), fMemCountAOD(0), fTrackMatcherRunningMode(0), fBuffer_ClusterE(0), fBuffer_ClusterEta(0), fBuffer_ClusterPhi(0), fBuffer_ClusterM02(0), fBuffer_ClusterM20(0), fBuffer_Track_Pt(0), fBuffer_Track_P(0), fBuffer_Track_Eta(0), fBuffer_Track_Phi(0), fBuffer_Track_NSigmaElec(0), fBuffer_Track_IsFromV0(0), fBuffer_MC_True_Cluster_E(0), fBuffer_MC_True_Track_E(0), fBuffer_MC_True_Track_Pt(0), fBuffer_MC_True_Track_P(0), fBuffer_MC_Track_Is_Electron(0), fBuffer_MC_Cluster_Is_Electron(0), fBuffer_MC_ClusterTrack_Same_Electron(0), fBuffer_MC_JetJetWeight(1.) { DefineInput(0, TChain::Class()); DefineOutput(1, TList::Class()); DefineOutput(2, TTree::Class()); SetEtaMatching(0.010,4.07,-2.5); SetPhiMatching(0.015,3.65,3.65); } //________________________________________________________________________ AliAnalysisTaskElectronStudies::~AliAnalysisTaskElectronStudies() { // default deconstructor } //________________________________________________________________________ void AliAnalysisTaskElectronStudies::UserCreateOutputObjects() { // Create User Output Objects fOutputList = new TList(); fOutputList->SetOwner(kTRUE); if(((AliConvEventCuts*)fEventCuts)->GetCutHistograms()){ fOutputList->Add(((AliConvEventCuts*)fEventCuts)->GetCutHistograms()); } if(((AliCaloPhotonCuts*)fClusterCutsEMC)->GetCutHistograms()){ fOutputList->Add(((AliCaloPhotonCuts*)fClusterCutsEMC)->GetCutHistograms()); } if(((AliCaloPhotonCuts*)fTMCuts)->GetCutHistograms()){ fOutputList->Add(((AliCaloPhotonCuts*)fTMCuts)->GetCutHistograms()); } if(((AliConversionPhotonCuts*)fConvCuts)->GetCutHistograms()){ fOutputList->Add(((AliConversionPhotonCuts*)fConvCuts)->GetCutHistograms()); } for(Int_t iMatcherTask = 0; iMatcherTask < 5; iMatcherTask++){ AliCaloTrackMatcher* temp = 0x0; if(!fCorrTaskSetting.CompareTo("")){ temp = (AliCaloTrackMatcher*) (AliAnalysisManager::GetAnalysisManager()->GetTask(Form("CaloTrackMatcherSignal_%i_%i",iMatcherTask,fTrackMatcherRunningMode))); } else { temp = (AliCaloTrackMatcher*) (AliAnalysisManager::GetAnalysisManager()->GetTask(Form("CaloTrackMatcherSignal_%i_%i_%s",iMatcherTask,fTrackMatcherRunningMode,fCorrTaskSetting.Data()))); } if(temp) fOutputList->Add(temp->GetCaloTrackMatcherHistograms()); } fHistoNEvents = new TH1F("NEvents","NEvents",14,-0.5,13.5); fHistoNEvents->GetXaxis()->SetBinLabel(1,"Accepted"); fHistoNEvents->GetXaxis()->SetBinLabel(2,"Centrality"); fHistoNEvents->GetXaxis()->SetBinLabel(3,"Miss. MC or inc. ev."); if (((AliConvEventCuts*)fEventCuts)->IsSpecialTrigger() > 1 ){ TString TriggerNames = "Not Trigger: "; TriggerNames = TriggerNames+ ( (AliConvEventCuts*)fEventCuts)->GetSpecialTriggerName(); fHistoNEvents->GetXaxis()->SetBinLabel(4,TriggerNames.Data()); } else { fHistoNEvents->GetXaxis()->SetBinLabel(4,"Trigger"); } fHistoNEvents->GetXaxis()->SetBinLabel(5,"Vertex Z"); fHistoNEvents->GetXaxis()->SetBinLabel(6,"Cont. Vertex"); fHistoNEvents->GetXaxis()->SetBinLabel(7,"Pile-Up"); fHistoNEvents->GetXaxis()->SetBinLabel(8,"no SDD"); fHistoNEvents->GetXaxis()->SetBinLabel(9,"no V0AND"); fHistoNEvents->GetXaxis()->SetBinLabel(10,"EMCAL/TPC problem"); fHistoNEvents->GetXaxis()->SetBinLabel(12,"SPD hits vs tracklet"); fHistoNEvents->GetXaxis()->SetBinLabel(13,"Out-of-Bunch pileup Past-Future"); fHistoNEvents->GetXaxis()->SetBinLabel(14,"Pileup V0M-TPCout Tracks"); fHistoNEvents->GetYaxis()->SetTitle("N_{events}"); fOutputList->Add(fHistoNEvents); fPtElectronTrack = new TH1F("fPtElectronTrack","fPtElectronTrack;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fPtElectronTrack); fPtElectronTrackInEmcalAcc = new TH1F("fPtElectronTrackInEmcalAcc","fPtElectronTrackInEmcalAcc;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fPtElectronTrackInEmcalAcc); if(fIsMC > 1){ fHistoNEventsWOWeight = new TH1F("NEventsWOWeight","NEventsWOWeight",14,-0.5,13.5); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(1,"Accepted"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(2,"Centrality"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(3,"Miss. MC or inc. ev."); if (((AliConvEventCuts*)fEventCuts)->IsSpecialTrigger() > 1 ){ TString TriggerNames = "Not Trigger: "; TriggerNames = TriggerNames+ ( (AliConvEventCuts*)fEventCuts)->GetSpecialTriggerName(); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(4,TriggerNames.Data()); } else { fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(4,"Trigger"); } fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(5,"Vertex Z"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(6,"Cont. Vertex"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(7,"Pile-Up"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(8,"no SDD"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(9,"no V0AND"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(10,"EMCAL problem"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(12,"SPD hits vs tracklet"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(13,"Out-of-Bunch pileup Past-Future"); fHistoNEventsWOWeight->GetXaxis()->SetBinLabel(14,"Pileup V0M-TPCout Tracks"); fHistoNEventsWOWeight->GetYaxis()->SetTitle("N_{events}"); fOutputList->Add(fHistoNEventsWOWeight); } if(fIsMC){ fTruePtCluster = new TH1F("fTruePtCluster","fTruePtCluster;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fTruePtCluster); fTruePtElectronCluster = new TH1F("fTruePtElectronCluster","fTruePtElectronCluster;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fTruePtElectronCluster); fTruePtElectronClusterMatchedWithTrack = new TH1F("fTruePtElectronClusterMatchedWithTrack","fTruePtElectronClusterMatchedWithTrack;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fTruePtElectronClusterMatchedWithTrack); fTruePtElectronTrack = new TH1F("fTruePtElectronTrack","fTruePtElectronTrack;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fTruePtElectronTrack); fTruePtElectronTrackInEmcalAcc = new TH1F("fTruePtElectronTrackInEmcalAcc","fTruePtElectronTrackInEmcalAcc;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fTruePtElectronTrackInEmcalAcc); fGenPtElectrons = new TH1F("fGenPtElectrons","fGenPtElectrons;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fGenPtElectrons); fGenPtElectronsInEmcalAcc = new TH1F("fGenPtElectronsInEmcalAcc","fGenPtElectronsInEmcalAcc;p_{T} (GeV/c; counts",200,0.,50.); fOutputList->Add(fGenPtElectronsInEmcalAcc); } PostData(1, fOutputList); OpenFile(2); fAnalysisTree = new TTree(Form("AnalysisTree_%s",fCorrTaskSetting.Data()),Form("AnalysisTree_%s",fCorrTaskSetting.Data())); fAnalysisTree->Branch("Cluster_E", &fBuffer_ClusterE, "Cluster_E/F"); fAnalysisTree->Branch("Cluster_Eta", &fBuffer_ClusterEta, "Cluster_Eta/F"); fAnalysisTree->Branch("Cluster_Phi", &fBuffer_ClusterPhi, "Cluster_Phi/F"); fAnalysisTree->Branch("Cluster_M02", &fBuffer_ClusterM02, "Cluster_M02/F"); fAnalysisTree->Branch("Cluster_M20", &fBuffer_ClusterM20, "Cluster_M20/F"); fAnalysisTree->Branch("Track_Pt", &fBuffer_Track_Pt, "Track_Pt/F"); fAnalysisTree->Branch("Track_P", &fBuffer_Track_P, "Track_P/F"); fAnalysisTree->Branch("Track_Eta", &fBuffer_Track_Eta, "Track_Eta/F"); fAnalysisTree->Branch("Track_Phi", &fBuffer_Track_Phi, "Track_Phi/F"); fAnalysisTree->Branch("Track_NSigmaElec", &fBuffer_Track_NSigmaElec, "Track_NSigmaElec/F"); fAnalysisTree->Branch("Track_IsFromV0", &fBuffer_Track_IsFromV0, "Track_Track_IsFromV0/I"); if(fIsMC>0){ fAnalysisTree->Branch("MC_True_Cluster_E", &fBuffer_MC_True_Cluster_E, "MC_True_Cluster_E/F"); fAnalysisTree->Branch("MC_True_Track_E", &fBuffer_MC_True_Track_E, "MC_True_Track_E/F"); fAnalysisTree->Branch("MC_True_Track_Pt", &fBuffer_MC_True_Track_Pt, "MC_True_Track_Pt/F"); fAnalysisTree->Branch("MC_True_Track_P", &fBuffer_MC_True_Track_P, "MC_True_Track_P/F"); fAnalysisTree->Branch("MC_Track_Is_Electron", &fBuffer_MC_Track_Is_Electron, "MC_Track_Is_Electron/I"); fAnalysisTree->Branch("MC_Cluster_Is_Electron", &fBuffer_MC_Cluster_Is_Electron, "MC_Cluster_Is_Electron/I"); fAnalysisTree->Branch("MC_ClusterTrack_Same_Electron", &fBuffer_MC_ClusterTrack_Same_Electron, "MC_ClusterTrack_Same_Electron/I"); fAnalysisTree->Branch("MC_JetJetWeight", &fBuffer_MC_JetJetWeight, "MC_JetJetWeight/F"); } PostData(2, fAnalysisTree); } //_____________________________________________________________________________ Bool_t AliAnalysisTaskElectronStudies::Notify() { return kTRUE; } //________________________________________________________________________ void AliAnalysisTaskElectronStudies::UserExec(Option_t *){ fInputEvent = InputEvent(); ((AliCaloPhotonCuts*)fClusterCutsEMC)->InitializeEMCAL(fInputEvent); //((AliCaloPhotonCuts*)fTMCuts)->InitializeEMCAL(fInputEvent); if(fIsMC>0) fMCEvent = MCEvent(); if((fIsMC) > 0 && (!fMCEvent)) {printf("Error: No MC Event");return;} // Get V0 reader fV0Reader=(AliV0ReaderV1*)AliAnalysisManager::GetAnalysisManager()->GetTask(fV0ReaderName.Data()); if(!fV0Reader){printf("Error: No V0 Reader");return;} // GetV0Reader if(fIsMC > 0 && fInputEvent->IsA()==AliAODEvent::Class() && !(fV0Reader->AreAODsRelabeled())){ RelabelAODPhotonCandidates(kTRUE); // In case of AODMC relabeling MC fV0Reader->RelabelAODs(kTRUE); } Int_t eventQuality = ((AliConvEventCuts*)fV0Reader->GetEventCuts())->GetEventQuality(); if(InputEvent()->IsIncompleteDAQ()==kTRUE) eventQuality = 2; // incomplete event if(eventQuality == 2 || eventQuality == 3){// Event Not Accepted due to MC event missing or wrong trigger for V0ReaderV1 or because it is incomplete fHistoNEvents->Fill(eventQuality); if (fIsMC>1) fHistoNEventsWOWeight->Fill(eventQuality); return; } Int_t eventNotAccepted = fEventCuts->IsEventAcceptedByCut(fV0Reader->GetEventCuts(),fInputEvent,fMCEvent,fIsHeavyIon,kFALSE); if(eventNotAccepted) return; // Check Centrality, PileUp, SDD and V0AND --> Not Accepted => eventQuality = 1 if (fIsMC > 1){ fWeightJetJetMC = 1; Float_t maxjetpt = -1.; Float_t pthard = -1; Bool_t isMCJet = ((AliConvEventCuts*)fEventCuts)->IsJetJetMCEventAccepted( fMCEvent, fWeightJetJetMC ,pthard, fInputEvent, maxjetpt); if (!isMCJet){ fHistoNEvents->Fill(10,fWeightJetJetMC); if (fIsMC>1) fHistoNEventsWOWeight->Fill(10); return; } } AliInputEventHandler *inputHandler=dynamic_cast<AliInputEventHandler*>(AliAnalysisManager::GetAnalysisManager()->GetInputEventHandler()); fPIDResponse = inputHandler->GetPIDResponse(); if (!fPIDResponse){AliFatal("fPIDResponse does not exist!"); return;} if (fIsMC > 1){ fWeightJetJetMC = 1; Float_t maxjetpt = -1.; Float_t pthard = -1; Bool_t isMCJet = ((AliConvEventCuts*)fEventCuts)->IsJetJetMCEventAccepted( fMCEvent, fWeightJetJetMC ,pthard, fInputEvent, maxjetpt); if (fIsMC == 3){ Double_t weightMult = ((AliConvEventCuts*)fEventCuts)->GetWeightForMultiplicity(fV0Reader->GetNumberOfPrimaryTracks()); fWeightJetJetMC = fWeightJetJetMC*weightMult; } if (!isMCJet){ fHistoNEvents->Fill(10,fWeightJetJetMC); if (fIsMC>1) fHistoNEventsWOWeight->Fill(10); return; } } Bool_t triggered = kTRUE; if(eventNotAccepted!=0){ fHistoNEvents->Fill(eventNotAccepted,fWeightJetJetMC); // Check Centrality, PileUp, SDD and V0AND --> Not Accepted => eventQuality = 1 if (fIsMC>1) fHistoNEventsWOWeight->Fill(eventNotAccepted); if (eventNotAccepted==3 && fIsMC > 0){ triggered = kFALSE; }else { return; } } if(eventQuality != 0 && triggered== kTRUE){// Event Not Accepted fHistoNEvents->Fill(eventQuality, fWeightJetJetMC); if (fIsMC>1) fHistoNEventsWOWeight->Fill(eventQuality); // Should be 0 here return; } if (triggered == kTRUE) { fHistoNEvents->Fill(eventQuality,fWeightJetJetMC); if (fIsMC>1) fHistoNEventsWOWeight->Fill(eventQuality); // Should be 0 here } fGeomEMCAL = AliEMCALGeometry::GetInstance(); if(!fGeomEMCAL){ AliFatal("EMCal geometry not initialized!");} fBuffer_MC_JetJetWeight = fWeightJetJetMC; // // ─── MAIN PROCESSING ──────────────────────────────────────────────────────────── // if (triggered==kFALSE) return; ProcessCaloPhotons(); // track matching is done here as well ProcessTracks(); if(fIsMC>0) ProcessMCParticles(); // vertex Double_t vertex[3] = {0}; InputEvent()->GetPrimaryVertex()->GetXYZ(vertex); if( fIsMC > 0 && fInputEvent->IsA()==AliAODEvent::Class() && !(fV0Reader->AreAODsRelabeled())){ RelabelAODPhotonCandidates(kFALSE); // Back to ESDMC Label fV0Reader->RelabelAODs(kFALSE); } // fill output PostData(2, fAnalysisTree); ResetBuffer(); //gObjectTable->Print(); PostData(1,fOutputList); } //________________________________________________________________________ void AliAnalysisTaskElectronStudies::Terminate(Option_t *){ } //________________________________________________________________________ void AliAnalysisTaskElectronStudies::ResetBuffer(){ } //________________________________________________________________________ void AliAnalysisTaskElectronStudies::ProcessCaloPhotons(){ Int_t nclus = 0; Int_t nclusCorr = 0; if(fIsMC && !fAODMCTrackArray) fAODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName())); TClonesArray * arrClustersProcess = NULL; if(!fCorrTaskSetting.CompareTo("")){ nclus = fInputEvent->GetNumberOfCaloClusters(); nclusCorr = nclus; } else { arrClustersProcess = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(Form("%sClustersBranch",fCorrTaskSetting.Data()))); if(!arrClustersProcess) AliFatal(Form("%sClustersBranch was not found in AliAnalysisTaskGammaCalo! Check the correction framework settings!",fCorrTaskSetting.Data())); nclusCorr = arrClustersProcess->GetEntries(); nclus = fInputEvent->GetNumberOfCaloClusters(); } if(nclus == 0) return; // ((AliCaloPhotonCuts*)fClusterCutsEMC)->FillHistogramsExtendedQA(fInputEvent,fIsMC); // ((AliCaloPhotonCuts*)fClusterCutsPHOS)->FillHistogramsExtendedQA(fInputEvent,fIsMC); // in case user wants to use default track matching fTMCuts->MatchTracksToClusters(fInputEvent,fWeightJetJetMC,kTRUE, fMCEvent); AliAODCaloCluster* clus = NULL; if(arrClustersProcess){ // EMCal correction framework was used // we need to loop over this for EMCal clusters and // over the others for PHOS cluster // Loop over EMCal clusters for(Long_t i = 0; i < nclusCorr; i++){ Double_t tempClusterWeight = fWeightJetJetMC; clus = new AliAODCaloCluster(*(AliAODCaloCluster*)arrClustersProcess->At(i)); if(!clus) continue; if ( !clus->IsEMCAL()){ // for PHOS: cluster->GetType() == AliVCluster::kPHOSNeutral delete clus; continue; } // check if given EMC cuts are fulfilled if(!((AliCaloPhotonCuts*)fClusterCutsEMC)->ClusterIsSelected(clus,fInputEvent,fMCEvent,fIsMC, tempClusterWeight,i)){ delete clus; continue; } if(fIsMC){ Int_t *mclabelsCluster = clus->GetLabels(); if (clus->GetNLabels() > 0) { if(mclabelsCluster[0]!=-1){ AliAODMCParticle* clusterMother = (AliAODMCParticle* )fAODMCTrackArray->At(mclabelsCluster[0]); fTruePtCluster->Fill(clusterMother->Pt(),fWeightJetJetMC); if (TMath::Abs(clusterMother->PdgCode()) == 11) { fTruePtElectronCluster->Fill(clusterMother->Pt(),fWeightJetJetMC); } } } } AliAODTrack *aodt = NULL; //ProcessTrackMatching(clus); if(fTMCuts->CheckClusterForTrackMatch(clus)){ Int_t labelTrack = -1; if(fTMCuts->GetClosestMatchedTrackToCluster(fInputEvent,clus,labelTrack)){ Int_t properLabel = labelTrack; // if(labelTrack<0) properLabel = (-1 * labelTrack) - 1; // conversion hybrid none hybrid aodt = dynamic_cast<AliAODTrack*> (fInputEvent->GetTrack(properLabel)); if(aodt) ProcessMatchedTrack(aodt,clus,kFALSE); } } delete clus; } // end of initial cluster loop } // no need to loop over normal clusters as well if(arrClustersProcess) return; // Loop over normal clusters for(Long_t i = 0; i < nclus; i++){ Double_t tempClusterWeight = fWeightJetJetMC; clus = new AliAODCaloCluster(*(AliAODCaloCluster*)fInputEvent->GetCaloCluster(i)); if(!clus) continue; if(clus->IsEMCAL()){ // if is was not saved already if(!((AliCaloPhotonCuts*)fClusterCutsEMC)->ClusterIsSelected(clus,fInputEvent,fMCEvent,fIsMC, tempClusterWeight,i)){ delete clus; continue; } if(fIsMC){ Int_t *mclabelsCluster = clus->GetLabels(); if (clus->GetNLabels() > 0) { if(mclabelsCluster[0]!=-1){ AliAODMCParticle* clusterMother = (AliAODMCParticle* )fAODMCTrackArray->At(mclabelsCluster[0]); fTruePtCluster->Fill(clusterMother->Pt(),fWeightJetJetMC); if (TMath::Abs(clusterMother->PdgCode()) == 11) { fTruePtElectronCluster->Fill(clusterMother->Pt(),fWeightJetJetMC); } } } } AliAODTrack *aodt = NULL; //ProcessTrackMatching(clus); if(fTMCuts->CheckClusterForTrackMatch(clus)){ Int_t labelTrack = -1; if(fTMCuts->GetClosestMatchedTrackToCluster(fInputEvent,clus,labelTrack)){ Int_t properLabel = labelTrack; // if(labelTrack<0) properLabel = (-1 * labelTrack) - 1; // conversion hybrid none hybrid aodt = dynamic_cast<AliAODTrack*> (fInputEvent->GetTrack(properLabel)); if(aodt) ProcessMatchedTrack(aodt,clus,kFALSE); } } //ProcessTrackMatching(clus); // tree filling done here too delete clus; continue; } delete clus; } } //________________________________________________________________________ void AliAnalysisTaskElectronStudies::ProcessTracks(){ for(Int_t t=0;t<fInputEvent->GetNumberOfTracks();t++){ AliAODTrack *aodt = dynamic_cast<AliAODTrack*> (fInputEvent->GetTrack(t)); if(!aodt) continue; if(!TrackIsSelectedAOD(aodt)) continue; // apply electron PID cut Float_t nsigmaelec = fPIDResponse->NumberOfSigmasTPC(aodt,AliPID::kElectron); if ((nsigmaelec > fMaxNsigmaElec) || (nsigmaelec < fMinNsigmaElec)) continue; fPtElectronTrack->Fill(aodt->Pt(),fWeightJetJetMC); if(IsInEMCalAcceptance(aodt)) fPtElectronTrackInEmcalAcc->Fill(aodt->Pt(),fWeightJetJetMC); if(fIsMC){ Int_t mclabel = aodt->GetLabel(); if(mclabel != -1){ if(mclabel<0) mclabel = (-1 * mclabel) - 1; AliAODMCParticle* particle = static_cast<AliAODMCParticle*>(fAODMCTrackArray->At(mclabel)); if(particle){ if(TMath::Abs(particle->GetPdgCode())== 11){ fTruePtElectronTrack->Fill(particle->Pt(),fWeightJetJetMC); if(IsInEMCalAcceptance(particle)) fTruePtElectronTrackInEmcalAcc->Fill(particle->Pt(),fWeightJetJetMC); } } } } } } ///________________________________________________________________________ Bool_t AliAnalysisTaskElectronStudies::TrackIsSelectedAOD(AliAODTrack* lTrack) { // apply filter bits if( ! lTrack->IsHybridGlobalConstrainedGlobal()){ return kFALSE; } // Absolute TPC Cluster cut if(lTrack->GetTPCNcls()<fMinClsTPC) return kFALSE; if(lTrack->GetTPCchi2perCluster()>fChi2PerClsTPC) return kFALSE; // DCA cut //if(!IsDCACutAccepted(lTrack)) return kFALSE; // ITS Cluster Cut // SetClusterRequirementITS and SetRequireITSRefit can // not be set for AODs after filtering if(lTrack->GetITSNcls()<fMinClsITS) return kFALSE; if( TMath::Abs(lTrack->Eta()) > fEtaCut ) { return kFALSE; } if( lTrack->Pt() < fPtCut ) { return kFALSE; } // n sigma preselection Float_t nsigmaelec = fPIDResponse->NumberOfSigmasTPC(lTrack,AliPID::kElectron); if ((nsigmaelec > 10) || (nsigmaelec < -10)) return kFALSE; return kTRUE; } //_____________________________________________________________________________ void AliAnalysisTaskElectronStudies::ProcessMatchedTrack(AliAODTrack* track, AliAODCaloCluster* clus, Bool_t isV0){ Float_t clusPos[3] = { 0,0,0 }; clus->GetPosition(clusPos); TVector3 clusterVector(clusPos[0],clusPos[1],clusPos[2]); fBuffer_ClusterE = clus->E(); fBuffer_ClusterEta = clusterVector.Eta(); fBuffer_ClusterPhi = clusterVector.Phi(); fBuffer_ClusterM02 = clus->GetM02(); fBuffer_ClusterM20 = clus->GetM20(); fBuffer_Track_Pt = track->Pt(); fBuffer_Track_P = track->P(); fBuffer_Track_Eta = track->Eta(); fBuffer_Track_Phi = track->Phi(); fBuffer_Track_NSigmaElec = fPIDResponse->NumberOfSigmasTPC(track,AliPID::kElectron); fBuffer_Track_IsFromV0 = (Int_t) isV0; fBuffer_MC_True_Cluster_E = 0; fBuffer_MC_True_Track_E = 0; fBuffer_MC_True_Track_Pt = 0; fBuffer_MC_True_Track_P = 0; fBuffer_MC_Track_Is_Electron= 0; fBuffer_MC_Cluster_Is_Electron= 0; fBuffer_MC_ClusterTrack_Same_Electron= 0; if(fIsMC){ // check if leading contribution is electron Int_t *mclabelsCluster = clus->GetLabels(); AliAODMCParticle* clusterMother = NULL; if (clus->GetNLabels() > 0) { // for (Int_t k = 0; k < (Int_t)clusterE->GetNLabels(); k++) // { if(mclabelsCluster[0]!=-1){ clusterMother = (AliAODMCParticle* )fAODMCTrackArray->At(mclabelsCluster[0]); if (TMath::Abs(clusterMother->PdgCode()) == 11) { fBuffer_MC_Cluster_Is_Electron = 1; fBuffer_MC_True_Cluster_E = clusterMother->E(); fTruePtElectronClusterMatchedWithTrack->Fill(clusterMother->Pt(),fWeightJetJetMC); } } } // Check Track Int_t trackMCLabel = track->GetLabel(); AliAODMCParticle* trackMother = NULL; if(trackMCLabel>-1){ trackMother = (AliAODMCParticle* )fAODMCTrackArray->At(trackMCLabel); if(TMath::Abs(trackMother->GetPdgCode()) == 11){ fBuffer_MC_Track_Is_Electron = 1; fBuffer_MC_True_Track_E = trackMother->E(); fBuffer_MC_True_Track_Pt = trackMother->Pt(); fBuffer_MC_True_Track_P = trackMother->P(); } } if((clus->GetNLabels()>0) && (mclabelsCluster[0] == trackMCLabel) && (fBuffer_MC_Track_Is_Electron ==1)){ fBuffer_MC_ClusterTrack_Same_Electron = 1; } // } } // end is MC fAnalysisTree->Fill(); } //_____________________________________________________________________________ void AliAnalysisTaskElectronStudies::ProcessMCParticles(){ // Loop over all primary MC particle if(!fAODMCTrackArray) fAODMCTrackArray = dynamic_cast<TClonesArray*>(fInputEvent->FindListObject(AliAODMCParticle::StdBranchName())); if (fAODMCTrackArray){ for(Int_t i = 0; i < fAODMCTrackArray->GetEntriesFast(); i++) { AliAODMCParticle* particle = static_cast<AliAODMCParticle*>(fAODMCTrackArray->At(i)); if(!particle) continue; if(particle->MCStatusCode() != 1 || !particle->IsPhysicalPrimary()) continue; if(TMath::Abs(particle->PdgCode()) != 11 ) continue; fGenPtElectrons->Fill(particle->Pt(),fWeightJetJetMC); if(IsInEMCalAcceptance(particle)){ fGenPtElectronsInEmcalAcc->Fill(particle->Pt(),fWeightJetJetMC); } } } } //_____________________________________________________________________________ void AliAnalysisTaskElectronStudies::ProcessTrackMatching(AliAODCaloCluster* clus){ Int_t nModules = fGeomEMCAL->GetNumberOfSuperModules(); AliExternalTrackParam *trackParam = 0; for(Int_t t=0;t<fInputEvent->GetNumberOfTracks();t++){ AliAODTrack *aodt = dynamic_cast<AliAODTrack*> (fInputEvent->GetTrack(t)); if(!aodt) continue; if(!TrackIsSelectedAOD(aodt)) continue; Double_t xyz[3] = {0}, pxpypz[3] = {0}, cv[21] = {0}; aodt->GetPxPyPz(pxpypz); aodt->GetXYZ(xyz); aodt->GetCovarianceXYZPxPyPz(cv); trackParam = new AliExternalTrackParam(xyz,pxpypz,cv,aodt->Charge()); AliExternalTrackParam emcParam(*trackParam); Float_t eta, phi, pt; //propagate tracks to emc surfaces if (!AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(&emcParam, 440., 0.139, 20., eta, phi, pt)) { delete trackParam; continue; } if( TMath::Abs(eta) > 0.75 ) { delete trackParam; continue; } // Save some time and memory in case of no DCal present if( nModules < 13 && ( phi < 70*TMath::DegToRad() || phi > 190*TMath::DegToRad())){ delete trackParam; continue; } // Save some time and memory in case of run2 if( nModules > 12 ){ if (( phi < 70*TMath::DegToRad() || phi > 190*TMath::DegToRad()) && ( phi < 250*TMath::DegToRad() || phi > 340*TMath::DegToRad())){ delete trackParam; continue; } } Float_t dEta=-999, dPhi=-999; Double_t trkPos[3] = {0.,0.,0.}; if (!emcParam.GetXYZ(trkPos)){ delete trackParam; continue; } AliExternalTrackParam trackParamTmp(emcParam);//Retrieve the starting point every time before the extrapolation if(!AliEMCALRecoUtils::ExtrapolateTrackToCluster(&trackParamTmp, clus, 0.139, 5., dEta, dPhi)){ delete trackParam; continue; } if(!fUseRTrackMatching){ if(TMath::Abs(dEta) > (fMatchingParamsEta[0] + pow(aodt->Pt() + fMatchingParamsEta[1],fMatchingParamsEta[2]))){ delete trackParam; continue; } if(TMath::Abs(dPhi) > (fMatchingParamsPhi[0] + pow(aodt->Pt() + fMatchingParamsPhi[1],fMatchingParamsPhi[2]))){ delete trackParam; continue; } } else{ // use R track matching Double_t dR = TMath::Sqrt(dEta*dEta + dPhi*dPhi); if(dR > fRTrackMatching){ delete trackParam; continue; } } // track is matched ProcessMatchedTrack(aodt,clus,kFALSE); delete trackParam; } // check also conversion sample to be sure nothing from there is missing if(!fReaderGammas) fReaderGammas = fV0Reader->GetReconstructedGammas(); for (Int_t c = 0; c < fReaderGammas->GetEntriesFast(); c++) { AliAODConversionPhoton* photon = (AliAODConversionPhoton*) fReaderGammas->At(c); if(!photon) continue; if(!((AliConversionPhotonCuts*)fConvCuts)->PhotonIsSelected(photon,fInputEvent)) continue; for (Int_t iElec = 0;iElec < 2;iElec++){ Int_t tracklabel = photon->GetLabel(iElec); AliAODTrack *convtrack = dynamic_cast<AliAODTrack*> (fInputEvent->GetTrack(tracklabel)); if(!convtrack) continue; if(convtrack->IsHybridGlobalConstrainedGlobal()) continue; // that means we already treated it; Double_t xyz[3] = {0}, pxpypz[3] = {0}, cv[21] = {0}; convtrack->GetPxPyPz(pxpypz); convtrack->GetXYZ(xyz); convtrack->GetCovarianceXYZPxPyPz(cv); trackParam = new AliExternalTrackParam(xyz,pxpypz,cv,convtrack->Charge()); AliExternalTrackParam emcParam(*trackParam); Float_t eta, phi, pt; //propagate tracks to emc surfaces if (!AliEMCALRecoUtils::ExtrapolateTrackToEMCalSurface(&emcParam, 440., 0.139, 20., eta, phi, pt)) { delete trackParam; continue; } if( TMath::Abs(eta) > 0.75 ) { delete trackParam; continue; } // Save some time and memory in case of no DCal present if( nModules < 13 && ( phi < 70*TMath::DegToRad() || phi > 190*TMath::DegToRad())){ delete trackParam; continue; } // Save some time and memory in case of run2 if( nModules > 12 ){ if (( phi < 70*TMath::DegToRad() || phi > 190*TMath::DegToRad()) && ( phi < 250*TMath::DegToRad() || phi > 340*TMath::DegToRad())){ delete trackParam; continue; } } Float_t dEta=-999, dPhi=-999; Double_t trkPos[3] = {0.,0.,0.}; if (!emcParam.GetXYZ(trkPos)){ delete trackParam; continue; } AliExternalTrackParam trackParamTmp(emcParam);//Retrieve the starting point every time before the extrapolation if(!AliEMCALRecoUtils::ExtrapolateTrackToCluster(&trackParamTmp, clus, 0.139, 5., dEta, dPhi)){ delete trackParam; continue; } if(TMath::Abs(dEta) > (fMatchingParamsEta[0] + pow(convtrack->Pt() + fMatchingParamsEta[1],fMatchingParamsEta[2]))){ delete trackParam; continue; } if(TMath::Abs(dPhi) > (fMatchingParamsPhi[0] + pow(convtrack->Pt() + fMatchingParamsPhi[1],fMatchingParamsPhi[2]))){ delete trackParam; continue; } // track is matched ProcessMatchedTrack(convtrack,clus,kTRUE); delete trackParam; } } // return highestMatchIndex; } Bool_t AliAnalysisTaskElectronStudies::IsSameTrack(Int_t id1, Int_t id2){ if((id1 == -999) || (id2 == -999)){ cout << "ERROR: Track info is missing for one track!" << endl; return kFALSE; } Int_t esdID1 = id1; Int_t esdID2 = id2; if(id1<0) esdID1 = (-1 * id1) - 1; if(id2<0) esdID2 = (-1 * id2) - 1; if(esdID1 == esdID2){ return kTRUE; } else{ return kFALSE; } } Bool_t AliAnalysisTaskElectronStudies::IsInEMCalAcceptance(AliAODConversionPhoton *photon) { Double_t eta = photon->GetPhotonEta(); Double_t phi = photon->GetPhotonPhi(); // cout << phi << endl; // cout << eta << endl; if (phi < 0) phi += 2 * TMath::Pi(); if ((eta < -0.6687) || (eta > 0.66465)) return kFALSE; if ((phi < 1.39626) || (phi > 3.15)) return kFALSE; return kTRUE; } Bool_t AliAnalysisTaskElectronStudies::IsInEMCalAcceptance(AliAODMCParticle *part) { Double_t eta = part->Eta(); Double_t phi = part->Phi(); if (phi < 0) phi += 2 * TMath::Pi(); // cout << phi << endl; // cout << eta << endl; if ((eta < -0.6687) || (eta > 0.66465)) return kFALSE; if ((phi < 1.39626) || (phi > 3.15)) return kFALSE; return kTRUE; } Bool_t AliAnalysisTaskElectronStudies::IsInEMCalAcceptance(AliAODTrack *part) { Double_t eta = part->Eta(); Double_t phi = part->Phi(); if (phi < 0) phi += 2 * TMath::Pi(); // cout << phi << endl; // cout << eta << endl; if ((eta < -0.6687) || (eta > 0.66465)) return kFALSE; if ((phi < 1.39626) || (phi > 3.15)) return kFALSE; return kTRUE; } Int_t AliAnalysisTaskElectronStudies::CheckClustersForMCContribution(Int_t mclabel, TClonesArray *vclus) { Int_t clusterLabel = -1; // position of cluster in array where mc label was found as contribution for (Int_t p = 0; p < vclus->GetEntriesFast(); p++) { AliAODCaloCluster *clus = (AliAODCaloCluster *)vclus->At(p); if (!clus) continue; Int_t *mclabelsCluster = clus->GetLabels(); if (clus->GetNLabels() > 0) { for (Int_t k = 0; k < (Int_t)clus->GetNLabels(); k++) { if (mclabelsCluster[p] == mclabel) clusterLabel = p; } } } return clusterLabel; } //________________________________________________________________________ void AliAnalysisTaskElectronStudies::RelabelAODPhotonCandidates(Bool_t mode){ // Relabeling For AOD Event // ESDiD -> AODiD // MCLabel -> AODMCLabel Int_t* fMCEventPos = nullptr; Int_t* fMCEventNeg = nullptr; Int_t* fESDArrayPos = nullptr; Int_t* fESDArrayNeg = nullptr; if(mode){ fMCEventPos = new Int_t[fReaderGammas->GetEntries()]; fMCEventNeg = new Int_t[fReaderGammas->GetEntries()]; fESDArrayPos = new Int_t[fReaderGammas->GetEntries()]; fESDArrayNeg = new Int_t[fReaderGammas->GetEntries()]; } for(Int_t iGamma = 0;iGamma<fReaderGammas->GetEntries();iGamma++){ AliAODConversionPhoton* PhotonCandidate = (AliAODConversionPhoton*) fReaderGammas->At(iGamma); if(!PhotonCandidate) continue; if(!mode){// Back to ESD Labels PhotonCandidate->SetMCLabelPositive(fMCEventPos[iGamma]); PhotonCandidate->SetMCLabelNegative(fMCEventNeg[iGamma]); PhotonCandidate->SetLabelPositive(fESDArrayPos[iGamma]); PhotonCandidate->SetLabelNegative(fESDArrayNeg[iGamma]); continue; } fMCEventPos[iGamma] = PhotonCandidate->GetMCLabelPositive(); fMCEventNeg[iGamma] = PhotonCandidate->GetMCLabelNegative(); fESDArrayPos[iGamma] = PhotonCandidate->GetTrackLabelPositive(); fESDArrayNeg[iGamma] = PhotonCandidate->GetTrackLabelNegative(); Bool_t AODLabelPos = kFALSE; Bool_t AODLabelNeg = kFALSE; for(Int_t i = 0; i<fInputEvent->GetNumberOfTracks();i++){ AliAODTrack *tempDaughter = static_cast<AliAODTrack*>(fInputEvent->GetTrack(i)); if(!AODLabelPos){ if( tempDaughter->GetID() == PhotonCandidate->GetTrackLabelPositive() ){ PhotonCandidate->SetMCLabelPositive(TMath::Abs(tempDaughter->GetLabel())); PhotonCandidate->SetLabelPositive(i); AODLabelPos = kTRUE; } } if(!AODLabelNeg){ if( tempDaughter->GetID() == PhotonCandidate->GetTrackLabelNegative()){ PhotonCandidate->SetMCLabelNegative(TMath::Abs(tempDaughter->GetLabel())); PhotonCandidate->SetLabelNegative(i); AODLabelNeg = kTRUE; } } if(AODLabelNeg && AODLabelPos){ break; } } if(!AODLabelPos || !AODLabelNeg){ cout<<"WARNING!!! AOD TRACKS NOT FOUND FOR"<<endl; if(!AODLabelNeg){ PhotonCandidate->SetMCLabelNegative(-999999); PhotonCandidate->SetLabelNegative(-999999); } if(!AODLabelPos){ PhotonCandidate->SetMCLabelPositive(-999999); PhotonCandidate->SetLabelPositive(-999999); } } } if(!mode){ delete[] fMCEventPos; delete[] fMCEventNeg; delete[] fESDArrayPos; delete[] fESDArrayNeg; } }
370a78de4bafa6fc8d647a8a287479af88ab7965
3912e69afbe91860a09bab2d8fa3d31263055766
/test_3_4_2_1.cpp
0dccd9b00179aea10e0ac7bf193106d0c5d2f263
[]
no_license
MagicSen/C_Plus_Plus_Primer
db4faa61d94aabc6c2ca6d66f9c93882ee7b573a
31d5ef74ebe143228ce71579ebd32eb5f1850896
refs/heads/master
2016-09-05T15:54:24.761932
2014-10-18T07:43:57
2014-10-18T07:43:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
581
cpp
#include <iostream> #include <vector> #include <string> using std::cout; using std::cin; using std::endl; using std::vector; using std::string; int main() { // vector<int> tm(10,42); // vector<int> tm{42 ... 42}; // vector<int> tm = {42 ... 42}; vector<int> sm; int temp=0; while(cin >> temp){ sm.push_back(temp); } for(auto i = sm.begin(),j = sm.end(); i != sm.begin() + sm.size()/2; i++,j--) { cout << *i + *(j-1) << " " ; } if(sm.size()%2 != 0) cout << *(sm.begin() + sm.size()/2) << " " ; cout << endl << "Vector's Size: " << sm.size() << endl; return 0; }
c22c1fe3a1a2b3916f0fb5e6a9cd679f2353c418
8ab64d4f95421180c7238a707a59753eb7102428
/chrome/browser/chromeos/policy/remote_commands/device_command_start_crd_session_job.h
76c4b2daeb37787393d28d8e7f7f6eddda3f2aec
[ "BSD-3-Clause" ]
permissive
cyCao350/chromium
3400144ab22bde9ca179547602857cc3306de857
90ed3e55ebf1db93db956c753f48d692e8f46c8b
refs/heads/master
2023-01-09T13:09:00.816731
2018-08-02T06:33:19
2018-08-02T06:33:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,078
h
// Copyright 2018 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 CHROME_BROWSER_CHROMEOS_POLICY_REMOTE_COMMANDS_DEVICE_COMMAND_START_CRD_SESSION_JOB_H_ #define CHROME_BROWSER_CHROMEOS_POLICY_REMOTE_COMMANDS_DEVICE_COMMAND_START_CRD_SESSION_JOB_H_ #include <string> #include "base/callback.h" #include "base/macros.h" #include "base/memory/weak_ptr.h" #include "base/time/time.h" #include "base/values.h" #include "components/policy/core/common/remote_commands/remote_command_job.h" namespace policy { // Remote command that would start Chrome Remote Desktop host and return auth // code. This command is usable only for devices running Kiosk sessions. class DeviceCommandStartCRDSessionJob : public RemoteCommandJob { public: enum ResultCode { // Successfully obtained access code. SUCCESS = 0, // Failed as required services are not launched on the device. FAILURE_SERVICES_NOT_READY = 1, // Failed as device is not running in Kiosk mode. FAILURE_NOT_A_KIOSK = 2, // Failed as device is currently in use and no interruptUser flag is set. FAILURE_NOT_IDLE = 3, // Failed as we could not get OAuth token for whatever reason. FAILURE_NO_OAUTH_TOKEN = 4, // Failed as we could not get ICE configuration for whatever reason. FAILURE_NO_ICE_CONFIG = 5, // Failure during attempt to start CRD host and obtain CRD token. FAILURE_CRD_HOST_ERROR = 6, }; using OAuthTokenCallback = base::OnceCallback<void(const std::string&)>; using AuthCodeCallback = base::OnceCallback<void(const std::string&)>; using ICEConfigCallback = base::OnceCallback<void(base::Value)>; using ErrorCallback = base::OnceCallback<void(ResultCode, const std::string&)>; // A delegate interface used by DeviceCommandStartCRDSessionJob to retrieve // its dependencies. class Delegate { public: virtual ~Delegate() {} // Check if there exists an active CRD session. virtual bool HasActiveSession() = 0; // Run |callback| once active CRD session is terminated. virtual void TerminateSession(base::OnceClosure callback) = 0; // Check if required system services are ready. virtual bool AreServicesReady() = 0; // Check if device is running in Kiosk mode. virtual bool IsRunningKiosk() = 0; // Return current user idleness period. virtual base::TimeDelta GetIdlenessPeriod() = 0; // Attempts to get OAuth token for CRD Host. virtual void FetchOAuthToken(OAuthTokenCallback success_callback, ErrorCallback error_callback) = 0; // Attempts to get ICE configuration for CRD Host. virtual void FetchICEConfig(const std::string& oauth_token, ICEConfigCallback success_callback, ErrorCallback error_callback) = 0; // Attempts to start CRD host and get Auth Code. virtual void StartCRDHostAndGetCode(const std::string& directory_bot_jid, const std::string& oauth_token, base::Value ice_config, AuthCodeCallback success_callback, ErrorCallback error_callback) = 0; }; explicit DeviceCommandStartCRDSessionJob(Delegate* crd_host_delegate); ~DeviceCommandStartCRDSessionJob() override; // RemoteCommandJob: enterprise_management::RemoteCommand_Type GetType() const override; protected: // RemoteCommandJob: bool ParseCommandPayload(const std::string& command_payload) override; void RunImpl(CallbackWithResult succeeded_callback, CallbackWithResult failed_callback) override; void TerminateImpl() override; private: class ResultPayload; // Finishes command with error code and optional message. void FinishWithError(ResultCode result_code, const std::string& message); void OnOAuthTokenReceived(const std::string& token); void OnICEConfigReceived(base::Value ice_config); void OnAuthCodeReceived(const std::string& token); // The callback that will be called when the access code was successfully // obtained. CallbackWithResult succeeded_callback_; // The callback that will be called when this command failed. CallbackWithResult failed_callback_; // -- Command parameters -- // Defines whether connection attempt to active user should succeed or fail. base::TimeDelta idleness_cutoff_; std::string oauth_token_; std::string directory_bot_jid_; base::Value ice_config_; // The Delegate is used to interact with chrome services and CRD host. // Owned by DeviceCommandsFactoryChromeOS. Delegate* delegate_; bool terminate_session_attemtpted_; base::WeakPtrFactory<DeviceCommandStartCRDSessionJob> weak_factory_; DISALLOW_COPY_AND_ASSIGN(DeviceCommandStartCRDSessionJob); }; } // namespace policy #endif // CHROME_BROWSER_CHROMEOS_POLICY_REMOTE_COMMANDS_DEVICE_COMMAND_START_CRD_SESSION_JOB_H_
366187213f3110a6521e6bea5c0bae6ba4e7ffc1
019d64d5fb05b266dc6e4f281403ae9ba1b9a0be
/src/lib/sparse_matrix/msr_matrix.h
fde6f89897f3f191f56bcf08ef6d0a7151f19e28
[]
no_license
mrFlatiron/3d_interpol
590f8a57b625b79fb59ec3d556bdbd87210bfc83
5780b28ad07af32fbc0c77227abac6cf2f096d29
refs/heads/master
2021-01-20T13:44:17.368731
2017-05-30T23:21:04
2017-05-30T23:21:04
90,523,814
0
0
null
null
null
null
UTF-8
C++
false
false
1,069
h
#ifndef MSR_MATRIX_H #define MSR_MATRIX_H #include "containers/simple_vector.h" #include <cstdio> #include <vector> class msr_thread_dqgmres_solver; class msr_matrix { private: int m_n; int m_arr_size; simple_vector m_aa; std::vector<int> m_ja; public: friend class msr_thread_dqgmres_solver; msr_matrix (); ~msr_matrix (); void dump (FILE *fout = stdout); void convert (const int n, simple_vector matrix); int n () const; void set_n (const int n); int arr_size () const; void set_arr_size (const int size); double aa (const int i) const; void aa (const int i, const double val); int ja (const int i) const; void ja (const int i, const int val); void set_diagonal (const simple_vector &diag_vals); void mult_vector (const simple_vector &in, simple_vector &out); bool is_symmetrical () const; double ij (const int i, const int j) const; private: void print_row (FILE *fout, const int i, const int row_begin, const int row_end); void get_ja_row_bounds (const int i, int &begin, int &end) const; }; #endif // MSR_MATRIX_H
8e865311140b493eab6287c49553ba57a4195c95
54fae68239e935143f77e3bca9513cb0a0263476
/Chapter20/exercises/20.09/ex_2009.cpp
4f8d747c089b0280a1ffda39468279fb6245835c
[]
no_license
CHENGCHANGHU/Cpp-How-To-Program-9E
9e3406c0079960b366f6c636ab56caed807e3ac7
e9a37f2717e17dd5b37f80e27ab52b7f664853be
refs/heads/master
2021-04-03T05:38:48.952450
2018-02-20T23:10:50
2018-02-20T23:10:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,209
cpp
/* * ===================================================================================== * * Filename: ex_2009.cpp * * Description: Exercise 20.09 - Copying a List in Reverse Order * * Version: 1.0 * Created: 13/06/17 12:12:56 * Revision: none * Compiler: g++ * * Author: Siidney Watson - [email protected] * Organization: LolaDog Studio * * ===================================================================================== */ #include <iostream> #include "List.hpp" int main(int argc, const char* argv[]) { List<char> charList; List<char> charListRev; // populate base list for (char c = 'a'; c <= 'j'; ++c) { charList.insertAtBack(c); } // iterate over base insert at front on charListRev auto iter = charList.begin(); while (iter != charList.end()) { charListRev.insertAtFront(iter->getData()); iter = iter->next(); // copy last element if (iter == charList.end()) { charListRev.insertAtFront(iter->getData()); } } charList.print(); std::cout << std::endl; charListRev.print(); std::cout << std::endl; return 0; }
1f319770ce89cd6e26c16890f54679399916ff81
515289d2bf3171001efa6d9676207c2dbf7edd3f
/Game/Stage8.cpp
45f2b5e16d9e9ef564d34af5f9b5b579cc4380ac
[ "MIT" ]
permissive
Gutt4N/Synchro
a3231a9c9e46023231b3c283cdb0e6d5fe59473e
e4c882078d361dc656139c926a96d7806fbd4b74
refs/heads/master
2021-01-13T01:07:42.478114
2017-02-09T04:34:34
2017-02-09T04:34:34
81,408,289
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,666
cpp
//__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/ //! @file Stage8.cpp //! //! @brief Map関連のソースファイル //! //! @date 日付 //! //! @author GF3_01_安藤 祥大 //__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/__/ // ヘッダファイルの読み込み ================================================ #include "AllStage.h" #include "define.h" #include "Player.h" #include "Player2.h" #include "Object.h" void Stage8(); // グローバル ================================================ //*†*:;;;:*†*:;;;:*†*:;;;:*†*:;;;:*†*:;;;:*†*// // 関数名:MapFirstInit // // 概要 :マップデータ読み込み // // 引数 :省略 // // 戻り値:省略 // //*†*:;;;:*†*:;;;:*†*:;;;:*†*:;;;:*†*:;;;:*†*// void Stage8Init(void) { FILE *fp = NULL; char buf[512]; char *tok; char *next_token = NULL; int i, j; switch (MapFlagNumber) { case 8: //マップファイいるをオープンする switch (MapChange) { case 0: fopen_s(&fp, "Map\\MapEighth\\Map.csv", "r"); break; case 1: fopen_s(&fp, "Map\\MapEighth\\Map2.csv", "r"); break; } break; } //マップの読み込み for (i = 0; i < MAP_H; i++) { fgets(buf, sizeof(buf), fp); for (j = 0; j < MAP_W; j++) { if (j == 0) { tok = strtok_s(buf, ",", &next_token); } else { tok = strtok_s(NULL, ",", &next_token); } StageMap[i][j] = atoi(tok); } } fclose(fp); } ///////////////////////////////////////Stage8の初期化 void Stage8() { if (Scene == Game && MapFlagNumber == 8) { S_init = 0; //時間の初期化 Time = 0; STime = 0; DTime = 0; TTime = 0; FTime = 0; //表示の初期化 DrawSTime = 0; DrawDTime = 0; DrawTTime = 0; DrawFTime = 0; Player.Down = 0; //カウンター系の初期化 MapChange = 0; count = 0; muinit = 0; g_mCnt = 0; //プレイヤーの初期化 FirstMapPlayer(); FirstMapPlayer2(); //ゴール、パーツの初期化 InitGoalPartsFirst1(); InitGoalPartsSecond1(); InitGoalPartsThird1(); InitGoalPartsFourth1(); InitGoal1(); InitZanzo1(); //デバッグ GameScene = STAGE8; } } //*†*:;;;:*†*:;;;:*†*:;;;:*†*:;;;:*†*:;;;:*†*// // 関数名:MapLoad1 // // 概要 :マップデータ読み込み // // 引数 :省略 // // 戻り値:省略 // //*†*:;;;:*†*:;;;:*†*:;;;:*†*:;;;:*†*:;;;:*†*// void Stage8Load() { //map読み込み Stage8Init(); //マップ表示 DrawStageMap(); }
cb8530ce9488d87560491483ce3e980948394be2
c22c9454f6e31d94c24f8ee914a4985dd2836a05
/Vuforia HoloLens Sample (1)/test1/Il2CppOutputProject/Source/il2cppOutput/Bulk_UnityEngine.UnityWebRequestModule_0.cpp
b340d6f48793d55194540981b4e6b3df68592677
[]
no_license
carlosfelipetorres/GuitarAR
e3f4ae2b557700cb1e673fe694305d275c1ff027
e284d22a1e129ee4595e42359a7da513942ee1a6
refs/heads/master
2020-03-20T02:56:08.339018
2018-06-12T21:33:48
2018-06-12T21:34:13
137,125,726
0
0
null
null
null
null
UTF-8
C++
false
false
57,106
cpp
#include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <cstring> #include <string.h> #include <stdio.h> #include <cmath> #include <limits> #include <assert.h> #include <stdint.h> #include "class-internals.h" #include "codegen/il2cpp-codegen.h" #include "object-internals.h" // UnityEngine.Networking.DownloadHandler struct DownloadHandler_t1216180266; // System.String struct String_t; // System.Uri struct Uri_t19570940; // System.Text.RegularExpressions.Regex struct Regex_t1803876613; // System.Char[] struct CharU5BU5D_t1328083999; // System.Void struct Void_t1841601450; // System.Byte[] struct ByteU5BU5D_t3397334013; // System.UriParser struct UriParser_t1012511323; // System.Uri/UriInfo struct UriInfo_t4047916940; // System.Text.RegularExpressions.RegexRunnerFactory struct RegexRunnerFactory_t3902733837; // System.Collections.Hashtable struct Hashtable_t909839986; // System.String[] struct StringU5BU5D_t1642385972; // System.Text.RegularExpressions.ExclusiveReference struct ExclusiveReference_t708182869; // System.Text.RegularExpressions.SharedReference struct SharedReference_t2137668360; // System.Text.RegularExpressions.RegexCode struct RegexCode_t2469392150; // System.Collections.Generic.LinkedList`1<System.Text.RegularExpressions.CachedCodeEntry> struct LinkedList_1_t3858529280; extern RuntimeClass* GC_t2902933594_il2cpp_TypeInfo_var; extern const uint32_t DownloadHandler_Dispose_m918842992_MetadataUsageId; extern RuntimeClass* Uri_t19570940_il2cpp_TypeInfo_var; extern const uint32_t WebRequestUtils_RedirectTo_m675215376_MetadataUsageId; extern RuntimeClass* Regex_t1803876613_il2cpp_TypeInfo_var; extern RuntimeClass* WebRequestUtils_t4100941042_il2cpp_TypeInfo_var; extern Il2CppCodeGenString* _stringLiteral4071228867; extern const uint32_t WebRequestUtils__cctor_m4149625601_MetadataUsageId; #ifndef U3CMODULEU3E_T3783534225_H #define U3CMODULEU3E_T3783534225_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // <Module> struct U3CModuleU3E_t3783534225 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // U3CMODULEU3E_T3783534225_H #ifndef RUNTIMEOBJECT_H #define RUNTIMEOBJECT_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Object #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEOBJECT_H #ifndef WEBREQUESTUTILS_T4100941042_H #define WEBREQUESTUTILS_T4100941042_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngineInternal.WebRequestUtils struct WebRequestUtils_t4100941042 : public RuntimeObject { public: public: }; struct WebRequestUtils_t4100941042_StaticFields { public: // System.Text.RegularExpressions.Regex UnityEngineInternal.WebRequestUtils::domainRegex Regex_t1803876613 * ___domainRegex_0; public: inline static int32_t get_offset_of_domainRegex_0() { return static_cast<int32_t>(offsetof(WebRequestUtils_t4100941042_StaticFields, ___domainRegex_0)); } inline Regex_t1803876613 * get_domainRegex_0() const { return ___domainRegex_0; } inline Regex_t1803876613 ** get_address_of_domainRegex_0() { return &___domainRegex_0; } inline void set_domainRegex_0(Regex_t1803876613 * value) { ___domainRegex_0 = value; Il2CppCodeGenWriteBarrier((&___domainRegex_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // WEBREQUESTUTILS_T4100941042_H #ifndef STRING_T_H #define STRING_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.String struct String_t : public RuntimeObject { public: // System.Int32 System.String::m_stringLength int32_t ___m_stringLength_0; // System.Char System.String::m_firstChar Il2CppChar ___m_firstChar_1; public: inline static int32_t get_offset_of_m_stringLength_0() { return static_cast<int32_t>(offsetof(String_t, ___m_stringLength_0)); } inline int32_t get_m_stringLength_0() const { return ___m_stringLength_0; } inline int32_t* get_address_of_m_stringLength_0() { return &___m_stringLength_0; } inline void set_m_stringLength_0(int32_t value) { ___m_stringLength_0 = value; } inline static int32_t get_offset_of_m_firstChar_1() { return static_cast<int32_t>(offsetof(String_t, ___m_firstChar_1)); } inline Il2CppChar get_m_firstChar_1() const { return ___m_firstChar_1; } inline Il2CppChar* get_address_of_m_firstChar_1() { return &___m_firstChar_1; } inline void set_m_firstChar_1(Il2CppChar value) { ___m_firstChar_1 = value; } }; struct String_t_StaticFields { public: // System.String System.String::Empty String_t* ___Empty_5; public: inline static int32_t get_offset_of_Empty_5() { return static_cast<int32_t>(offsetof(String_t_StaticFields, ___Empty_5)); } inline String_t* get_Empty_5() const { return ___Empty_5; } inline String_t** get_address_of_Empty_5() { return &___Empty_5; } inline void set_Empty_5(String_t* value) { ___Empty_5 = value; Il2CppCodeGenWriteBarrier((&___Empty_5), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // STRING_T_H struct Il2CppArrayBounds; #ifndef RUNTIMEARRAY_H #define RUNTIMEARRAY_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Array #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // RUNTIMEARRAY_H #ifndef VALUETYPE_T3507792607_H #define VALUETYPE_T3507792607_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.ValueType struct ValueType_t3507792607 : public RuntimeObject { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.ValueType struct ValueType_t3507792607_marshaled_pinvoke { }; // Native definition for COM marshalling of System.ValueType struct ValueType_t3507792607_marshaled_com { }; #endif // VALUETYPE_T3507792607_H #ifndef BOOLEAN_T3825574718_H #define BOOLEAN_T3825574718_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Boolean struct Boolean_t3825574718 { public: // System.Boolean System.Boolean::m_value bool ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Boolean_t3825574718, ___m_value_0)); } inline bool get_m_value_0() const { return ___m_value_0; } inline bool* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(bool value) { ___m_value_0 = value; } }; struct Boolean_t3825574718_StaticFields { public: // System.String System.Boolean::TrueString String_t* ___TrueString_5; // System.String System.Boolean::FalseString String_t* ___FalseString_6; public: inline static int32_t get_offset_of_TrueString_5() { return static_cast<int32_t>(offsetof(Boolean_t3825574718_StaticFields, ___TrueString_5)); } inline String_t* get_TrueString_5() const { return ___TrueString_5; } inline String_t** get_address_of_TrueString_5() { return &___TrueString_5; } inline void set_TrueString_5(String_t* value) { ___TrueString_5 = value; Il2CppCodeGenWriteBarrier((&___TrueString_5), value); } inline static int32_t get_offset_of_FalseString_6() { return static_cast<int32_t>(offsetof(Boolean_t3825574718_StaticFields, ___FalseString_6)); } inline String_t* get_FalseString_6() const { return ___FalseString_6; } inline String_t** get_address_of_FalseString_6() { return &___FalseString_6; } inline void set_FalseString_6(String_t* value) { ___FalseString_6 = value; Il2CppCodeGenWriteBarrier((&___FalseString_6), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // BOOLEAN_T3825574718_H #ifndef INT32_T2071877448_H #define INT32_T2071877448_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Int32 struct Int32_t2071877448 { public: // System.Int32 System.Int32::m_value int32_t ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Int32_t2071877448, ___m_value_0)); } inline int32_t get_m_value_0() const { return ___m_value_0; } inline int32_t* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(int32_t value) { ___m_value_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INT32_T2071877448_H #ifndef ENUM_T2459695545_H #define ENUM_T2459695545_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Enum struct Enum_t2459695545 : public ValueType_t3507792607 { public: public: }; struct Enum_t2459695545_StaticFields { public: // System.Char[] System.Enum::enumSeperatorCharArray CharU5BU5D_t1328083999* ___enumSeperatorCharArray_0; public: inline static int32_t get_offset_of_enumSeperatorCharArray_0() { return static_cast<int32_t>(offsetof(Enum_t2459695545_StaticFields, ___enumSeperatorCharArray_0)); } inline CharU5BU5D_t1328083999* get_enumSeperatorCharArray_0() const { return ___enumSeperatorCharArray_0; } inline CharU5BU5D_t1328083999** get_address_of_enumSeperatorCharArray_0() { return &___enumSeperatorCharArray_0; } inline void set_enumSeperatorCharArray_0(CharU5BU5D_t1328083999* value) { ___enumSeperatorCharArray_0 = value; Il2CppCodeGenWriteBarrier((&___enumSeperatorCharArray_0), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of System.Enum struct Enum_t2459695545_marshaled_pinvoke { }; // Native definition for COM marshalling of System.Enum struct Enum_t2459695545_marshaled_com { }; #endif // ENUM_T2459695545_H #ifndef INTPTR_T_H #define INTPTR_T_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.IntPtr struct IntPtr_t { public: // System.Void* System.IntPtr::m_value void* ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(IntPtr_t, ___m_value_0)); } inline void* get_m_value_0() const { return ___m_value_0; } inline void** get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(void* value) { ___m_value_0 = value; } }; struct IntPtr_t_StaticFields { public: // System.IntPtr System.IntPtr::Zero intptr_t ___Zero_1; public: inline static int32_t get_offset_of_Zero_1() { return static_cast<int32_t>(offsetof(IntPtr_t_StaticFields, ___Zero_1)); } inline intptr_t get_Zero_1() const { return ___Zero_1; } inline intptr_t* get_address_of_Zero_1() { return &___Zero_1; } inline void set_Zero_1(intptr_t value) { ___Zero_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // INTPTR_T_H #ifndef VOID_T1841601450_H #define VOID_T1841601450_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Void struct Void_t1841601450 { public: union { struct { }; uint8_t Void_t1841601450__padding[1]; }; public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // VOID_T1841601450_H #ifndef CHAR_T3454481338_H #define CHAR_T3454481338_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Char struct Char_t3454481338 { public: // System.Char System.Char::m_value Il2CppChar ___m_value_0; public: inline static int32_t get_offset_of_m_value_0() { return static_cast<int32_t>(offsetof(Char_t3454481338, ___m_value_0)); } inline Il2CppChar get_m_value_0() const { return ___m_value_0; } inline Il2CppChar* get_address_of_m_value_0() { return &___m_value_0; } inline void set_m_value_0(Il2CppChar value) { ___m_value_0 = value; } }; struct Char_t3454481338_StaticFields { public: // System.Byte[] System.Char::categoryForLatin1 ByteU5BU5D_t3397334013* ___categoryForLatin1_3; public: inline static int32_t get_offset_of_categoryForLatin1_3() { return static_cast<int32_t>(offsetof(Char_t3454481338_StaticFields, ___categoryForLatin1_3)); } inline ByteU5BU5D_t3397334013* get_categoryForLatin1_3() const { return ___categoryForLatin1_3; } inline ByteU5BU5D_t3397334013** get_address_of_categoryForLatin1_3() { return &___categoryForLatin1_3; } inline void set_categoryForLatin1_3(ByteU5BU5D_t3397334013* value) { ___categoryForLatin1_3 = value; Il2CppCodeGenWriteBarrier((&___categoryForLatin1_3), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // CHAR_T3454481338_H #ifndef REGEXOPTIONS_T2418259727_H #define REGEXOPTIONS_T2418259727_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.RegexOptions struct RegexOptions_t2418259727 { public: // System.Int32 System.Text.RegularExpressions.RegexOptions::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(RegexOptions_t2418259727, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEXOPTIONS_T2418259727_H #ifndef FLAGS_T455382755_H #define FLAGS_T455382755_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Uri/Flags struct Flags_t455382755 { public: // System.UInt64 System.Uri/Flags::value__ uint64_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(Flags_t455382755, ___value___2)); } inline uint64_t get_value___2() const { return ___value___2; } inline uint64_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(uint64_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // FLAGS_T455382755_H #ifndef URIIDNSCOPE_T761062207_H #define URIIDNSCOPE_T761062207_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UriIdnScope struct UriIdnScope_t761062207 { public: // System.Int32 System.UriIdnScope::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(UriIdnScope_t761062207, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // URIIDNSCOPE_T761062207_H #ifndef TIMESPAN_T3430258949_H #define TIMESPAN_T3430258949_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.TimeSpan struct TimeSpan_t3430258949 { public: // System.Int64 System.TimeSpan::_ticks int64_t ____ticks_3; public: inline static int32_t get_offset_of__ticks_3() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949, ____ticks_3)); } inline int64_t get__ticks_3() const { return ____ticks_3; } inline int64_t* get_address_of__ticks_3() { return &____ticks_3; } inline void set__ticks_3(int64_t value) { ____ticks_3 = value; } }; struct TimeSpan_t3430258949_StaticFields { public: // System.TimeSpan System.TimeSpan::Zero TimeSpan_t3430258949 ___Zero_0; // System.TimeSpan System.TimeSpan::MaxValue TimeSpan_t3430258949 ___MaxValue_1; // System.TimeSpan System.TimeSpan::MinValue TimeSpan_t3430258949 ___MinValue_2; // System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.TimeSpan::_legacyConfigChecked bool ____legacyConfigChecked_4; // System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.TimeSpan::_legacyMode bool ____legacyMode_5; public: inline static int32_t get_offset_of_Zero_0() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ___Zero_0)); } inline TimeSpan_t3430258949 get_Zero_0() const { return ___Zero_0; } inline TimeSpan_t3430258949 * get_address_of_Zero_0() { return &___Zero_0; } inline void set_Zero_0(TimeSpan_t3430258949 value) { ___Zero_0 = value; } inline static int32_t get_offset_of_MaxValue_1() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ___MaxValue_1)); } inline TimeSpan_t3430258949 get_MaxValue_1() const { return ___MaxValue_1; } inline TimeSpan_t3430258949 * get_address_of_MaxValue_1() { return &___MaxValue_1; } inline void set_MaxValue_1(TimeSpan_t3430258949 value) { ___MaxValue_1 = value; } inline static int32_t get_offset_of_MinValue_2() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ___MinValue_2)); } inline TimeSpan_t3430258949 get_MinValue_2() const { return ___MinValue_2; } inline TimeSpan_t3430258949 * get_address_of_MinValue_2() { return &___MinValue_2; } inline void set_MinValue_2(TimeSpan_t3430258949 value) { ___MinValue_2 = value; } inline static int32_t get_offset_of__legacyConfigChecked_4() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ____legacyConfigChecked_4)); } inline bool get__legacyConfigChecked_4() const { return ____legacyConfigChecked_4; } inline bool* get_address_of__legacyConfigChecked_4() { return &____legacyConfigChecked_4; } inline void set__legacyConfigChecked_4(bool value) { ____legacyConfigChecked_4 = value; } inline static int32_t get_offset_of__legacyMode_5() { return static_cast<int32_t>(offsetof(TimeSpan_t3430258949_StaticFields, ____legacyMode_5)); } inline bool get__legacyMode_5() const { return ____legacyMode_5; } inline bool* get_address_of__legacyMode_5() { return &____legacyMode_5; } inline void set__legacyMode_5(bool value) { ____legacyMode_5 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // TIMESPAN_T3430258949_H #ifndef DOWNLOADHANDLER_T1216180266_H #define DOWNLOADHANDLER_T1216180266_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // UnityEngine.Networking.DownloadHandler struct DownloadHandler_t1216180266 : public RuntimeObject { public: // System.IntPtr UnityEngine.Networking.DownloadHandler::m_Ptr intptr_t ___m_Ptr_0; public: inline static int32_t get_offset_of_m_Ptr_0() { return static_cast<int32_t>(offsetof(DownloadHandler_t1216180266, ___m_Ptr_0)); } inline intptr_t get_m_Ptr_0() const { return ___m_Ptr_0; } inline intptr_t* get_address_of_m_Ptr_0() { return &___m_Ptr_0; } inline void set_m_Ptr_0(intptr_t value) { ___m_Ptr_0 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif // Native definition for P/Invoke marshalling of UnityEngine.Networking.DownloadHandler struct DownloadHandler_t1216180266_marshaled_pinvoke { intptr_t ___m_Ptr_0; }; // Native definition for COM marshalling of UnityEngine.Networking.DownloadHandler struct DownloadHandler_t1216180266_marshaled_com { intptr_t ___m_Ptr_0; }; #endif // DOWNLOADHANDLER_T1216180266_H #ifndef URIKIND_T1128731744_H #define URIKIND_T1128731744_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.UriKind struct UriKind_t1128731744 { public: // System.Int32 System.UriKind::value__ int32_t ___value___2; public: inline static int32_t get_offset_of_value___2() { return static_cast<int32_t>(offsetof(UriKind_t1128731744, ___value___2)); } inline int32_t get_value___2() const { return ___value___2; } inline int32_t* get_address_of_value___2() { return &___value___2; } inline void set_value___2(int32_t value) { ___value___2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // URIKIND_T1128731744_H #ifndef URI_T19570940_H #define URI_T19570940_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Uri struct Uri_t19570940 : public RuntimeObject { public: // System.String System.Uri::m_String String_t* ___m_String_13; // System.String System.Uri::m_originalUnicodeString String_t* ___m_originalUnicodeString_14; // System.UriParser System.Uri::m_Syntax UriParser_t1012511323 * ___m_Syntax_15; // System.String System.Uri::m_DnsSafeHost String_t* ___m_DnsSafeHost_16; // System.Uri/Flags System.Uri::m_Flags uint64_t ___m_Flags_17; // System.Uri/UriInfo System.Uri::m_Info UriInfo_t4047916940 * ___m_Info_18; // System.Boolean System.Uri::m_iriParsing bool ___m_iriParsing_19; public: inline static int32_t get_offset_of_m_String_13() { return static_cast<int32_t>(offsetof(Uri_t19570940, ___m_String_13)); } inline String_t* get_m_String_13() const { return ___m_String_13; } inline String_t** get_address_of_m_String_13() { return &___m_String_13; } inline void set_m_String_13(String_t* value) { ___m_String_13 = value; Il2CppCodeGenWriteBarrier((&___m_String_13), value); } inline static int32_t get_offset_of_m_originalUnicodeString_14() { return static_cast<int32_t>(offsetof(Uri_t19570940, ___m_originalUnicodeString_14)); } inline String_t* get_m_originalUnicodeString_14() const { return ___m_originalUnicodeString_14; } inline String_t** get_address_of_m_originalUnicodeString_14() { return &___m_originalUnicodeString_14; } inline void set_m_originalUnicodeString_14(String_t* value) { ___m_originalUnicodeString_14 = value; Il2CppCodeGenWriteBarrier((&___m_originalUnicodeString_14), value); } inline static int32_t get_offset_of_m_Syntax_15() { return static_cast<int32_t>(offsetof(Uri_t19570940, ___m_Syntax_15)); } inline UriParser_t1012511323 * get_m_Syntax_15() const { return ___m_Syntax_15; } inline UriParser_t1012511323 ** get_address_of_m_Syntax_15() { return &___m_Syntax_15; } inline void set_m_Syntax_15(UriParser_t1012511323 * value) { ___m_Syntax_15 = value; Il2CppCodeGenWriteBarrier((&___m_Syntax_15), value); } inline static int32_t get_offset_of_m_DnsSafeHost_16() { return static_cast<int32_t>(offsetof(Uri_t19570940, ___m_DnsSafeHost_16)); } inline String_t* get_m_DnsSafeHost_16() const { return ___m_DnsSafeHost_16; } inline String_t** get_address_of_m_DnsSafeHost_16() { return &___m_DnsSafeHost_16; } inline void set_m_DnsSafeHost_16(String_t* value) { ___m_DnsSafeHost_16 = value; Il2CppCodeGenWriteBarrier((&___m_DnsSafeHost_16), value); } inline static int32_t get_offset_of_m_Flags_17() { return static_cast<int32_t>(offsetof(Uri_t19570940, ___m_Flags_17)); } inline uint64_t get_m_Flags_17() const { return ___m_Flags_17; } inline uint64_t* get_address_of_m_Flags_17() { return &___m_Flags_17; } inline void set_m_Flags_17(uint64_t value) { ___m_Flags_17 = value; } inline static int32_t get_offset_of_m_Info_18() { return static_cast<int32_t>(offsetof(Uri_t19570940, ___m_Info_18)); } inline UriInfo_t4047916940 * get_m_Info_18() const { return ___m_Info_18; } inline UriInfo_t4047916940 ** get_address_of_m_Info_18() { return &___m_Info_18; } inline void set_m_Info_18(UriInfo_t4047916940 * value) { ___m_Info_18 = value; Il2CppCodeGenWriteBarrier((&___m_Info_18), value); } inline static int32_t get_offset_of_m_iriParsing_19() { return static_cast<int32_t>(offsetof(Uri_t19570940, ___m_iriParsing_19)); } inline bool get_m_iriParsing_19() const { return ___m_iriParsing_19; } inline bool* get_address_of_m_iriParsing_19() { return &___m_iriParsing_19; } inline void set_m_iriParsing_19(bool value) { ___m_iriParsing_19 = value; } }; struct Uri_t19570940_StaticFields { public: // System.String System.Uri::UriSchemeFile String_t* ___UriSchemeFile_0; // System.String System.Uri::UriSchemeFtp String_t* ___UriSchemeFtp_1; // System.String System.Uri::UriSchemeGopher String_t* ___UriSchemeGopher_2; // System.String System.Uri::UriSchemeHttp String_t* ___UriSchemeHttp_3; // System.String System.Uri::UriSchemeHttps String_t* ___UriSchemeHttps_4; // System.String System.Uri::UriSchemeWs String_t* ___UriSchemeWs_5; // System.String System.Uri::UriSchemeWss String_t* ___UriSchemeWss_6; // System.String System.Uri::UriSchemeMailto String_t* ___UriSchemeMailto_7; // System.String System.Uri::UriSchemeNews String_t* ___UriSchemeNews_8; // System.String System.Uri::UriSchemeNntp String_t* ___UriSchemeNntp_9; // System.String System.Uri::UriSchemeNetTcp String_t* ___UriSchemeNetTcp_10; // System.String System.Uri::UriSchemeNetPipe String_t* ___UriSchemeNetPipe_11; // System.String System.Uri::SchemeDelimiter String_t* ___SchemeDelimiter_12; // System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.Uri::s_ConfigInitialized bool ___s_ConfigInitialized_20; // System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.Uri::s_ConfigInitializing bool ___s_ConfigInitializing_21; // System.UriIdnScope modreq(System.Runtime.CompilerServices.IsVolatile) System.Uri::s_IdnScope int32_t ___s_IdnScope_22; // System.Boolean modreq(System.Runtime.CompilerServices.IsVolatile) System.Uri::s_IriParsing bool ___s_IriParsing_23; // System.Boolean System.Uri::useDotNetRelativeOrAbsolute bool ___useDotNetRelativeOrAbsolute_24; // System.Boolean System.Uri::IsWindowsFileSystem bool ___IsWindowsFileSystem_25; // System.Object System.Uri::s_initLock RuntimeObject * ___s_initLock_26; // System.Char[] System.Uri::HexLowerChars CharU5BU5D_t1328083999* ___HexLowerChars_27; // System.Char[] System.Uri::_WSchars CharU5BU5D_t1328083999* ____WSchars_28; public: inline static int32_t get_offset_of_UriSchemeFile_0() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeFile_0)); } inline String_t* get_UriSchemeFile_0() const { return ___UriSchemeFile_0; } inline String_t** get_address_of_UriSchemeFile_0() { return &___UriSchemeFile_0; } inline void set_UriSchemeFile_0(String_t* value) { ___UriSchemeFile_0 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeFile_0), value); } inline static int32_t get_offset_of_UriSchemeFtp_1() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeFtp_1)); } inline String_t* get_UriSchemeFtp_1() const { return ___UriSchemeFtp_1; } inline String_t** get_address_of_UriSchemeFtp_1() { return &___UriSchemeFtp_1; } inline void set_UriSchemeFtp_1(String_t* value) { ___UriSchemeFtp_1 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeFtp_1), value); } inline static int32_t get_offset_of_UriSchemeGopher_2() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeGopher_2)); } inline String_t* get_UriSchemeGopher_2() const { return ___UriSchemeGopher_2; } inline String_t** get_address_of_UriSchemeGopher_2() { return &___UriSchemeGopher_2; } inline void set_UriSchemeGopher_2(String_t* value) { ___UriSchemeGopher_2 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeGopher_2), value); } inline static int32_t get_offset_of_UriSchemeHttp_3() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeHttp_3)); } inline String_t* get_UriSchemeHttp_3() const { return ___UriSchemeHttp_3; } inline String_t** get_address_of_UriSchemeHttp_3() { return &___UriSchemeHttp_3; } inline void set_UriSchemeHttp_3(String_t* value) { ___UriSchemeHttp_3 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeHttp_3), value); } inline static int32_t get_offset_of_UriSchemeHttps_4() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeHttps_4)); } inline String_t* get_UriSchemeHttps_4() const { return ___UriSchemeHttps_4; } inline String_t** get_address_of_UriSchemeHttps_4() { return &___UriSchemeHttps_4; } inline void set_UriSchemeHttps_4(String_t* value) { ___UriSchemeHttps_4 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeHttps_4), value); } inline static int32_t get_offset_of_UriSchemeWs_5() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeWs_5)); } inline String_t* get_UriSchemeWs_5() const { return ___UriSchemeWs_5; } inline String_t** get_address_of_UriSchemeWs_5() { return &___UriSchemeWs_5; } inline void set_UriSchemeWs_5(String_t* value) { ___UriSchemeWs_5 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeWs_5), value); } inline static int32_t get_offset_of_UriSchemeWss_6() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeWss_6)); } inline String_t* get_UriSchemeWss_6() const { return ___UriSchemeWss_6; } inline String_t** get_address_of_UriSchemeWss_6() { return &___UriSchemeWss_6; } inline void set_UriSchemeWss_6(String_t* value) { ___UriSchemeWss_6 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeWss_6), value); } inline static int32_t get_offset_of_UriSchemeMailto_7() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeMailto_7)); } inline String_t* get_UriSchemeMailto_7() const { return ___UriSchemeMailto_7; } inline String_t** get_address_of_UriSchemeMailto_7() { return &___UriSchemeMailto_7; } inline void set_UriSchemeMailto_7(String_t* value) { ___UriSchemeMailto_7 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeMailto_7), value); } inline static int32_t get_offset_of_UriSchemeNews_8() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeNews_8)); } inline String_t* get_UriSchemeNews_8() const { return ___UriSchemeNews_8; } inline String_t** get_address_of_UriSchemeNews_8() { return &___UriSchemeNews_8; } inline void set_UriSchemeNews_8(String_t* value) { ___UriSchemeNews_8 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeNews_8), value); } inline static int32_t get_offset_of_UriSchemeNntp_9() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeNntp_9)); } inline String_t* get_UriSchemeNntp_9() const { return ___UriSchemeNntp_9; } inline String_t** get_address_of_UriSchemeNntp_9() { return &___UriSchemeNntp_9; } inline void set_UriSchemeNntp_9(String_t* value) { ___UriSchemeNntp_9 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeNntp_9), value); } inline static int32_t get_offset_of_UriSchemeNetTcp_10() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeNetTcp_10)); } inline String_t* get_UriSchemeNetTcp_10() const { return ___UriSchemeNetTcp_10; } inline String_t** get_address_of_UriSchemeNetTcp_10() { return &___UriSchemeNetTcp_10; } inline void set_UriSchemeNetTcp_10(String_t* value) { ___UriSchemeNetTcp_10 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeNetTcp_10), value); } inline static int32_t get_offset_of_UriSchemeNetPipe_11() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___UriSchemeNetPipe_11)); } inline String_t* get_UriSchemeNetPipe_11() const { return ___UriSchemeNetPipe_11; } inline String_t** get_address_of_UriSchemeNetPipe_11() { return &___UriSchemeNetPipe_11; } inline void set_UriSchemeNetPipe_11(String_t* value) { ___UriSchemeNetPipe_11 = value; Il2CppCodeGenWriteBarrier((&___UriSchemeNetPipe_11), value); } inline static int32_t get_offset_of_SchemeDelimiter_12() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___SchemeDelimiter_12)); } inline String_t* get_SchemeDelimiter_12() const { return ___SchemeDelimiter_12; } inline String_t** get_address_of_SchemeDelimiter_12() { return &___SchemeDelimiter_12; } inline void set_SchemeDelimiter_12(String_t* value) { ___SchemeDelimiter_12 = value; Il2CppCodeGenWriteBarrier((&___SchemeDelimiter_12), value); } inline static int32_t get_offset_of_s_ConfigInitialized_20() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___s_ConfigInitialized_20)); } inline bool get_s_ConfigInitialized_20() const { return ___s_ConfigInitialized_20; } inline bool* get_address_of_s_ConfigInitialized_20() { return &___s_ConfigInitialized_20; } inline void set_s_ConfigInitialized_20(bool value) { ___s_ConfigInitialized_20 = value; } inline static int32_t get_offset_of_s_ConfigInitializing_21() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___s_ConfigInitializing_21)); } inline bool get_s_ConfigInitializing_21() const { return ___s_ConfigInitializing_21; } inline bool* get_address_of_s_ConfigInitializing_21() { return &___s_ConfigInitializing_21; } inline void set_s_ConfigInitializing_21(bool value) { ___s_ConfigInitializing_21 = value; } inline static int32_t get_offset_of_s_IdnScope_22() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___s_IdnScope_22)); } inline int32_t get_s_IdnScope_22() const { return ___s_IdnScope_22; } inline int32_t* get_address_of_s_IdnScope_22() { return &___s_IdnScope_22; } inline void set_s_IdnScope_22(int32_t value) { ___s_IdnScope_22 = value; } inline static int32_t get_offset_of_s_IriParsing_23() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___s_IriParsing_23)); } inline bool get_s_IriParsing_23() const { return ___s_IriParsing_23; } inline bool* get_address_of_s_IriParsing_23() { return &___s_IriParsing_23; } inline void set_s_IriParsing_23(bool value) { ___s_IriParsing_23 = value; } inline static int32_t get_offset_of_useDotNetRelativeOrAbsolute_24() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___useDotNetRelativeOrAbsolute_24)); } inline bool get_useDotNetRelativeOrAbsolute_24() const { return ___useDotNetRelativeOrAbsolute_24; } inline bool* get_address_of_useDotNetRelativeOrAbsolute_24() { return &___useDotNetRelativeOrAbsolute_24; } inline void set_useDotNetRelativeOrAbsolute_24(bool value) { ___useDotNetRelativeOrAbsolute_24 = value; } inline static int32_t get_offset_of_IsWindowsFileSystem_25() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___IsWindowsFileSystem_25)); } inline bool get_IsWindowsFileSystem_25() const { return ___IsWindowsFileSystem_25; } inline bool* get_address_of_IsWindowsFileSystem_25() { return &___IsWindowsFileSystem_25; } inline void set_IsWindowsFileSystem_25(bool value) { ___IsWindowsFileSystem_25 = value; } inline static int32_t get_offset_of_s_initLock_26() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___s_initLock_26)); } inline RuntimeObject * get_s_initLock_26() const { return ___s_initLock_26; } inline RuntimeObject ** get_address_of_s_initLock_26() { return &___s_initLock_26; } inline void set_s_initLock_26(RuntimeObject * value) { ___s_initLock_26 = value; Il2CppCodeGenWriteBarrier((&___s_initLock_26), value); } inline static int32_t get_offset_of_HexLowerChars_27() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ___HexLowerChars_27)); } inline CharU5BU5D_t1328083999* get_HexLowerChars_27() const { return ___HexLowerChars_27; } inline CharU5BU5D_t1328083999** get_address_of_HexLowerChars_27() { return &___HexLowerChars_27; } inline void set_HexLowerChars_27(CharU5BU5D_t1328083999* value) { ___HexLowerChars_27 = value; Il2CppCodeGenWriteBarrier((&___HexLowerChars_27), value); } inline static int32_t get_offset_of__WSchars_28() { return static_cast<int32_t>(offsetof(Uri_t19570940_StaticFields, ____WSchars_28)); } inline CharU5BU5D_t1328083999* get__WSchars_28() const { return ____WSchars_28; } inline CharU5BU5D_t1328083999** get_address_of__WSchars_28() { return &____WSchars_28; } inline void set__WSchars_28(CharU5BU5D_t1328083999* value) { ____WSchars_28 = value; Il2CppCodeGenWriteBarrier((&____WSchars_28), value); } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // URI_T19570940_H #ifndef REGEX_T1803876613_H #define REGEX_T1803876613_H #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Text.RegularExpressions.Regex struct Regex_t1803876613 : public RuntimeObject { public: // System.String System.Text.RegularExpressions.Regex::pattern String_t* ___pattern_0; // System.Text.RegularExpressions.RegexRunnerFactory System.Text.RegularExpressions.Regex::factory RegexRunnerFactory_t3902733837 * ___factory_1; // System.Text.RegularExpressions.RegexOptions System.Text.RegularExpressions.Regex::roptions int32_t ___roptions_2; // System.TimeSpan System.Text.RegularExpressions.Regex::internalMatchTimeout TimeSpan_t3430258949 ___internalMatchTimeout_5; // System.Collections.Hashtable System.Text.RegularExpressions.Regex::caps Hashtable_t909839986 * ___caps_8; // System.Collections.Hashtable System.Text.RegularExpressions.Regex::capnames Hashtable_t909839986 * ___capnames_9; // System.String[] System.Text.RegularExpressions.Regex::capslist StringU5BU5D_t1642385972* ___capslist_10; // System.Int32 System.Text.RegularExpressions.Regex::capsize int32_t ___capsize_11; // System.Text.RegularExpressions.ExclusiveReference System.Text.RegularExpressions.Regex::runnerref ExclusiveReference_t708182869 * ___runnerref_12; // System.Text.RegularExpressions.SharedReference System.Text.RegularExpressions.Regex::replref SharedReference_t2137668360 * ___replref_13; // System.Text.RegularExpressions.RegexCode System.Text.RegularExpressions.Regex::code RegexCode_t2469392150 * ___code_14; // System.Boolean System.Text.RegularExpressions.Regex::refsInitialized bool ___refsInitialized_15; public: inline static int32_t get_offset_of_pattern_0() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___pattern_0)); } inline String_t* get_pattern_0() const { return ___pattern_0; } inline String_t** get_address_of_pattern_0() { return &___pattern_0; } inline void set_pattern_0(String_t* value) { ___pattern_0 = value; Il2CppCodeGenWriteBarrier((&___pattern_0), value); } inline static int32_t get_offset_of_factory_1() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___factory_1)); } inline RegexRunnerFactory_t3902733837 * get_factory_1() const { return ___factory_1; } inline RegexRunnerFactory_t3902733837 ** get_address_of_factory_1() { return &___factory_1; } inline void set_factory_1(RegexRunnerFactory_t3902733837 * value) { ___factory_1 = value; Il2CppCodeGenWriteBarrier((&___factory_1), value); } inline static int32_t get_offset_of_roptions_2() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___roptions_2)); } inline int32_t get_roptions_2() const { return ___roptions_2; } inline int32_t* get_address_of_roptions_2() { return &___roptions_2; } inline void set_roptions_2(int32_t value) { ___roptions_2 = value; } inline static int32_t get_offset_of_internalMatchTimeout_5() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___internalMatchTimeout_5)); } inline TimeSpan_t3430258949 get_internalMatchTimeout_5() const { return ___internalMatchTimeout_5; } inline TimeSpan_t3430258949 * get_address_of_internalMatchTimeout_5() { return &___internalMatchTimeout_5; } inline void set_internalMatchTimeout_5(TimeSpan_t3430258949 value) { ___internalMatchTimeout_5 = value; } inline static int32_t get_offset_of_caps_8() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___caps_8)); } inline Hashtable_t909839986 * get_caps_8() const { return ___caps_8; } inline Hashtable_t909839986 ** get_address_of_caps_8() { return &___caps_8; } inline void set_caps_8(Hashtable_t909839986 * value) { ___caps_8 = value; Il2CppCodeGenWriteBarrier((&___caps_8), value); } inline static int32_t get_offset_of_capnames_9() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___capnames_9)); } inline Hashtable_t909839986 * get_capnames_9() const { return ___capnames_9; } inline Hashtable_t909839986 ** get_address_of_capnames_9() { return &___capnames_9; } inline void set_capnames_9(Hashtable_t909839986 * value) { ___capnames_9 = value; Il2CppCodeGenWriteBarrier((&___capnames_9), value); } inline static int32_t get_offset_of_capslist_10() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___capslist_10)); } inline StringU5BU5D_t1642385972* get_capslist_10() const { return ___capslist_10; } inline StringU5BU5D_t1642385972** get_address_of_capslist_10() { return &___capslist_10; } inline void set_capslist_10(StringU5BU5D_t1642385972* value) { ___capslist_10 = value; Il2CppCodeGenWriteBarrier((&___capslist_10), value); } inline static int32_t get_offset_of_capsize_11() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___capsize_11)); } inline int32_t get_capsize_11() const { return ___capsize_11; } inline int32_t* get_address_of_capsize_11() { return &___capsize_11; } inline void set_capsize_11(int32_t value) { ___capsize_11 = value; } inline static int32_t get_offset_of_runnerref_12() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___runnerref_12)); } inline ExclusiveReference_t708182869 * get_runnerref_12() const { return ___runnerref_12; } inline ExclusiveReference_t708182869 ** get_address_of_runnerref_12() { return &___runnerref_12; } inline void set_runnerref_12(ExclusiveReference_t708182869 * value) { ___runnerref_12 = value; Il2CppCodeGenWriteBarrier((&___runnerref_12), value); } inline static int32_t get_offset_of_replref_13() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___replref_13)); } inline SharedReference_t2137668360 * get_replref_13() const { return ___replref_13; } inline SharedReference_t2137668360 ** get_address_of_replref_13() { return &___replref_13; } inline void set_replref_13(SharedReference_t2137668360 * value) { ___replref_13 = value; Il2CppCodeGenWriteBarrier((&___replref_13), value); } inline static int32_t get_offset_of_code_14() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___code_14)); } inline RegexCode_t2469392150 * get_code_14() const { return ___code_14; } inline RegexCode_t2469392150 ** get_address_of_code_14() { return &___code_14; } inline void set_code_14(RegexCode_t2469392150 * value) { ___code_14 = value; Il2CppCodeGenWriteBarrier((&___code_14), value); } inline static int32_t get_offset_of_refsInitialized_15() { return static_cast<int32_t>(offsetof(Regex_t1803876613, ___refsInitialized_15)); } inline bool get_refsInitialized_15() const { return ___refsInitialized_15; } inline bool* get_address_of_refsInitialized_15() { return &___refsInitialized_15; } inline void set_refsInitialized_15(bool value) { ___refsInitialized_15 = value; } }; struct Regex_t1803876613_StaticFields { public: // System.TimeSpan System.Text.RegularExpressions.Regex::MaximumMatchTimeout TimeSpan_t3430258949 ___MaximumMatchTimeout_3; // System.TimeSpan System.Text.RegularExpressions.Regex::InfiniteMatchTimeout TimeSpan_t3430258949 ___InfiniteMatchTimeout_4; // System.TimeSpan System.Text.RegularExpressions.Regex::FallbackDefaultMatchTimeout TimeSpan_t3430258949 ___FallbackDefaultMatchTimeout_6; // System.TimeSpan System.Text.RegularExpressions.Regex::DefaultMatchTimeout TimeSpan_t3430258949 ___DefaultMatchTimeout_7; // System.Collections.Generic.LinkedList`1<System.Text.RegularExpressions.CachedCodeEntry> System.Text.RegularExpressions.Regex::livecode LinkedList_1_t3858529280 * ___livecode_16; // System.Int32 System.Text.RegularExpressions.Regex::cacheSize int32_t ___cacheSize_17; public: inline static int32_t get_offset_of_MaximumMatchTimeout_3() { return static_cast<int32_t>(offsetof(Regex_t1803876613_StaticFields, ___MaximumMatchTimeout_3)); } inline TimeSpan_t3430258949 get_MaximumMatchTimeout_3() const { return ___MaximumMatchTimeout_3; } inline TimeSpan_t3430258949 * get_address_of_MaximumMatchTimeout_3() { return &___MaximumMatchTimeout_3; } inline void set_MaximumMatchTimeout_3(TimeSpan_t3430258949 value) { ___MaximumMatchTimeout_3 = value; } inline static int32_t get_offset_of_InfiniteMatchTimeout_4() { return static_cast<int32_t>(offsetof(Regex_t1803876613_StaticFields, ___InfiniteMatchTimeout_4)); } inline TimeSpan_t3430258949 get_InfiniteMatchTimeout_4() const { return ___InfiniteMatchTimeout_4; } inline TimeSpan_t3430258949 * get_address_of_InfiniteMatchTimeout_4() { return &___InfiniteMatchTimeout_4; } inline void set_InfiniteMatchTimeout_4(TimeSpan_t3430258949 value) { ___InfiniteMatchTimeout_4 = value; } inline static int32_t get_offset_of_FallbackDefaultMatchTimeout_6() { return static_cast<int32_t>(offsetof(Regex_t1803876613_StaticFields, ___FallbackDefaultMatchTimeout_6)); } inline TimeSpan_t3430258949 get_FallbackDefaultMatchTimeout_6() const { return ___FallbackDefaultMatchTimeout_6; } inline TimeSpan_t3430258949 * get_address_of_FallbackDefaultMatchTimeout_6() { return &___FallbackDefaultMatchTimeout_6; } inline void set_FallbackDefaultMatchTimeout_6(TimeSpan_t3430258949 value) { ___FallbackDefaultMatchTimeout_6 = value; } inline static int32_t get_offset_of_DefaultMatchTimeout_7() { return static_cast<int32_t>(offsetof(Regex_t1803876613_StaticFields, ___DefaultMatchTimeout_7)); } inline TimeSpan_t3430258949 get_DefaultMatchTimeout_7() const { return ___DefaultMatchTimeout_7; } inline TimeSpan_t3430258949 * get_address_of_DefaultMatchTimeout_7() { return &___DefaultMatchTimeout_7; } inline void set_DefaultMatchTimeout_7(TimeSpan_t3430258949 value) { ___DefaultMatchTimeout_7 = value; } inline static int32_t get_offset_of_livecode_16() { return static_cast<int32_t>(offsetof(Regex_t1803876613_StaticFields, ___livecode_16)); } inline LinkedList_1_t3858529280 * get_livecode_16() const { return ___livecode_16; } inline LinkedList_1_t3858529280 ** get_address_of_livecode_16() { return &___livecode_16; } inline void set_livecode_16(LinkedList_1_t3858529280 * value) { ___livecode_16 = value; Il2CppCodeGenWriteBarrier((&___livecode_16), value); } inline static int32_t get_offset_of_cacheSize_17() { return static_cast<int32_t>(offsetof(Regex_t1803876613_StaticFields, ___cacheSize_17)); } inline int32_t get_cacheSize_17() const { return ___cacheSize_17; } inline int32_t* get_address_of_cacheSize_17() { return &___cacheSize_17; } inline void set_cacheSize_17(int32_t value) { ___cacheSize_17 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif // REGEX_T1803876613_H // System.Void System.Object::.ctor() extern "C" void Object__ctor_m2551263788 (RuntimeObject * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void UnityEngine.Networking.DownloadHandler::InternalDestroy() extern "C" void DownloadHandler_InternalDestroy_m1591990468 (DownloadHandler_t1216180266 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Object::Finalize() extern "C" void Object_Finalize_m4087144328 (RuntimeObject * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.GC::SuppressFinalize(System.Object) extern "C" void GC_SuppressFinalize_m953228702 (RuntimeObject * __this /* static, unused */, RuntimeObject * p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Char System.String::get_Chars(System.Int32) extern "C" Il2CppChar String_get_Chars_m4230566705 (String_t* __this, int32_t p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Uri::.ctor(System.String,System.UriKind) extern "C" void Uri__ctor_m1528033823 (Uri_t19570940 * __this, String_t* p0, int32_t p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Boolean System.Uri::get_IsAbsoluteUri() extern "C" bool Uri_get_IsAbsoluteUri_m615473366 (Uri_t19570940 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.String System.Uri::get_AbsoluteUri() extern "C" String_t* Uri_get_AbsoluteUri_m656589005 (Uri_t19570940 * __this, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Uri::.ctor(System.Uri,System.Uri) extern "C" void Uri__ctor_m371762263 (Uri_t19570940 * __this, Uri_t19570940 * p0, Uri_t19570940 * p1, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; // System.Void System.Text.RegularExpressions.Regex::.ctor(System.String) extern "C" void Regex__ctor_m1229307206 (Regex_t1803876613 * __this, String_t* p0, const RuntimeMethod* method) IL2CPP_METHOD_ATTR; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // Conversion methods for marshalling of: UnityEngine.Networking.DownloadHandler extern "C" void DownloadHandler_t1216180266_marshal_pinvoke(const DownloadHandler_t1216180266& unmarshaled, DownloadHandler_t1216180266_marshaled_pinvoke& marshaled) { marshaled.___m_Ptr_0 = unmarshaled.get_m_Ptr_0(); } extern "C" void DownloadHandler_t1216180266_marshal_pinvoke_back(const DownloadHandler_t1216180266_marshaled_pinvoke& marshaled, DownloadHandler_t1216180266& unmarshaled) { intptr_t unmarshaled_m_Ptr_temp_0; memset(&unmarshaled_m_Ptr_temp_0, 0, sizeof(unmarshaled_m_Ptr_temp_0)); unmarshaled_m_Ptr_temp_0 = marshaled.___m_Ptr_0; unmarshaled.set_m_Ptr_0(unmarshaled_m_Ptr_temp_0); } // Conversion method for clean up from marshalling of: UnityEngine.Networking.DownloadHandler extern "C" void DownloadHandler_t1216180266_marshal_pinvoke_cleanup(DownloadHandler_t1216180266_marshaled_pinvoke& marshaled) { } // Conversion methods for marshalling of: UnityEngine.Networking.DownloadHandler extern "C" void DownloadHandler_t1216180266_marshal_com(const DownloadHandler_t1216180266& unmarshaled, DownloadHandler_t1216180266_marshaled_com& marshaled) { marshaled.___m_Ptr_0 = unmarshaled.get_m_Ptr_0(); } extern "C" void DownloadHandler_t1216180266_marshal_com_back(const DownloadHandler_t1216180266_marshaled_com& marshaled, DownloadHandler_t1216180266& unmarshaled) { intptr_t unmarshaled_m_Ptr_temp_0; memset(&unmarshaled_m_Ptr_temp_0, 0, sizeof(unmarshaled_m_Ptr_temp_0)); unmarshaled_m_Ptr_temp_0 = marshaled.___m_Ptr_0; unmarshaled.set_m_Ptr_0(unmarshaled_m_Ptr_temp_0); } // Conversion method for clean up from marshalling of: UnityEngine.Networking.DownloadHandler extern "C" void DownloadHandler_t1216180266_marshal_com_cleanup(DownloadHandler_t1216180266_marshaled_com& marshaled) { } // System.Void UnityEngine.Networking.DownloadHandler::.ctor() extern "C" void DownloadHandler__ctor_m1584617735 (DownloadHandler_t1216180266 * __this, const RuntimeMethod* method) { { Object__ctor_m2551263788(__this, /*hidden argument*/NULL); return; } } // System.Void UnityEngine.Networking.DownloadHandler::InternalDestroy() extern "C" void DownloadHandler_InternalDestroy_m1591990468 (DownloadHandler_t1216180266 * __this, const RuntimeMethod* method) { typedef void (*DownloadHandler_InternalDestroy_m1591990468_ftn) (DownloadHandler_t1216180266 *); static DownloadHandler_InternalDestroy_m1591990468_ftn _il2cpp_icall_func; if (!_il2cpp_icall_func) _il2cpp_icall_func = (DownloadHandler_InternalDestroy_m1591990468_ftn)il2cpp_codegen_resolve_icall ("UnityEngine.Networking.DownloadHandler::InternalDestroy()"); _il2cpp_icall_func(__this); } // System.Void UnityEngine.Networking.DownloadHandler::Finalize() extern "C" void DownloadHandler_Finalize_m1928784109 (DownloadHandler_t1216180266 * __this, const RuntimeMethod* method) { Exception_t1927440687 * __last_unhandled_exception = 0; NO_UNUSED_WARNING (__last_unhandled_exception); Exception_t1927440687 * __exception_local = 0; NO_UNUSED_WARNING (__exception_local); int32_t __leave_target = 0; NO_UNUSED_WARNING (__leave_target); { } IL_0001: try { // begin try (depth: 1) DownloadHandler_InternalDestroy_m1591990468(__this, /*hidden argument*/NULL); IL2CPP_LEAVE(0x13, FINALLY_000c); } // end try (depth: 1) catch(Il2CppExceptionWrapper& e) { __last_unhandled_exception = (Exception_t1927440687 *)e.ex; goto FINALLY_000c; } FINALLY_000c: { // begin finally (depth: 1) Object_Finalize_m4087144328(__this, /*hidden argument*/NULL); IL2CPP_END_FINALLY(12) } // end finally (depth: 1) IL2CPP_CLEANUP(12) { IL2CPP_JUMP_TBL(0x13, IL_0013) IL2CPP_RETHROW_IF_UNHANDLED(Exception_t1927440687 *) } IL_0013: { return; } } // System.Void UnityEngine.Networking.DownloadHandler::Dispose() extern "C" void DownloadHandler_Dispose_m918842992 (DownloadHandler_t1216180266 * __this, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (DownloadHandler_Dispose_m918842992_MetadataUsageId); s_Il2CppMethodInitialized = true; } { DownloadHandler_InternalDestroy_m1591990468(__this, /*hidden argument*/NULL); IL2CPP_RUNTIME_CLASS_INIT(GC_t2902933594_il2cpp_TypeInfo_var); GC_SuppressFinalize_m953228702(NULL /*static, unused*/, __this, /*hidden argument*/NULL); return; } } // System.String UnityEngineInternal.WebRequestUtils::RedirectTo(System.String,System.String) extern "C" String_t* WebRequestUtils_RedirectTo_m675215376 (RuntimeObject * __this /* static, unused */, String_t* ___baseUri0, String_t* ___redirectUri1, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WebRequestUtils_RedirectTo_m675215376_MetadataUsageId); s_Il2CppMethodInitialized = true; } Uri_t19570940 * V_0 = NULL; String_t* V_1 = NULL; Uri_t19570940 * V_2 = NULL; Uri_t19570940 * V_3 = NULL; { String_t* L_0 = ___redirectUri1; NullCheck(L_0); Il2CppChar L_1 = String_get_Chars_m4230566705(L_0, 0, /*hidden argument*/NULL); if ((!(((uint32_t)L_1) == ((uint32_t)((int32_t)47))))) { goto IL_001c; } } { String_t* L_2 = ___redirectUri1; Uri_t19570940 * L_3 = (Uri_t19570940 *)il2cpp_codegen_object_new(Uri_t19570940_il2cpp_TypeInfo_var); Uri__ctor_m1528033823(L_3, L_2, 2, /*hidden argument*/NULL); V_0 = L_3; goto IL_0024; } IL_001c: { String_t* L_4 = ___redirectUri1; Uri_t19570940 * L_5 = (Uri_t19570940 *)il2cpp_codegen_object_new(Uri_t19570940_il2cpp_TypeInfo_var); Uri__ctor_m1528033823(L_5, L_4, 0, /*hidden argument*/NULL); V_0 = L_5; } IL_0024: { Uri_t19570940 * L_6 = V_0; NullCheck(L_6); bool L_7 = Uri_get_IsAbsoluteUri_m615473366(L_6, /*hidden argument*/NULL); if (!L_7) { goto IL_003b; } } { Uri_t19570940 * L_8 = V_0; NullCheck(L_8); String_t* L_9 = Uri_get_AbsoluteUri_m656589005(L_8, /*hidden argument*/NULL); V_1 = L_9; goto IL_0057; } IL_003b: { String_t* L_10 = ___baseUri0; Uri_t19570940 * L_11 = (Uri_t19570940 *)il2cpp_codegen_object_new(Uri_t19570940_il2cpp_TypeInfo_var); Uri__ctor_m1528033823(L_11, L_10, 1, /*hidden argument*/NULL); V_2 = L_11; Uri_t19570940 * L_12 = V_2; Uri_t19570940 * L_13 = V_0; Uri_t19570940 * L_14 = (Uri_t19570940 *)il2cpp_codegen_object_new(Uri_t19570940_il2cpp_TypeInfo_var); Uri__ctor_m371762263(L_14, L_12, L_13, /*hidden argument*/NULL); V_3 = L_14; Uri_t19570940 * L_15 = V_3; NullCheck(L_15); String_t* L_16 = Uri_get_AbsoluteUri_m656589005(L_15, /*hidden argument*/NULL); V_1 = L_16; goto IL_0057; } IL_0057: { String_t* L_17 = V_1; return L_17; } } // System.Void UnityEngineInternal.WebRequestUtils::.cctor() extern "C" void WebRequestUtils__cctor_m4149625601 (RuntimeObject * __this /* static, unused */, const RuntimeMethod* method) { static bool s_Il2CppMethodInitialized; if (!s_Il2CppMethodInitialized) { il2cpp_codegen_initialize_method (WebRequestUtils__cctor_m4149625601_MetadataUsageId); s_Il2CppMethodInitialized = true; } { Regex_t1803876613 * L_0 = (Regex_t1803876613 *)il2cpp_codegen_object_new(Regex_t1803876613_il2cpp_TypeInfo_var); Regex__ctor_m1229307206(L_0, _stringLiteral4071228867, /*hidden argument*/NULL); ((WebRequestUtils_t4100941042_StaticFields*)il2cpp_codegen_static_fields_for(WebRequestUtils_t4100941042_il2cpp_TypeInfo_var))->set_domainRegex_0(L_0); return; } } #ifdef __clang__ #pragma clang diagnostic pop #endif
07bb1f6083086356842b64afc58add57c8ddadc6
c2f436afd2fbce2d20caf001b5ff93519b5e7ee8
/flashlight/autograd/Functions.cpp
1dcb2e083e767eb7601d0815db6df5c0d10783fd
[ "MIT" ]
permissive
pzelasko/flashlight
395fd62348f477f4ecad8cc76bf0508b057a05ca
ea702c05403600d1339d0744a456f68694553187
refs/heads/master
2020-04-13T03:20:09.335863
2018-12-23T01:15:23
2018-12-23T01:17:19
162,928,354
0
1
MIT
2018-12-23T22:31:24
2018-12-23T22:31:24
null
UTF-8
C++
false
false
33,216
cpp
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ /******************************************************* * Copyright (c) 2017, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <algorithm> #include <array> #include <stdexcept> #include <af/internal.h> #include "Functions.h" #include "Variable.h" namespace fl { namespace detail { af::array tileAs(const af::array& input, const af::dim4& rdims) { af::dim4 dims(1, 1, 1, 1); af::dim4 idims = input.dims(); for (int i = 0; i < 4; i++) { dims[i] = rdims[i] / idims[i]; } return tile(input, dims); } af::array sumAs(const af::array& input, const af::dim4& rdims) { af::dim4 idims = input.dims(); auto result = input; for (int i = 0; i < 4; i++) { if (idims[i] != rdims[i]) { result = sum(result, i); } } return result; } } // namespace detail Variable operator+(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() + rhs.array(); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(grad_output.array(), false)); inputs[1].addGrad(Variable(grad_output.array(), false)); }; return Variable(result, {lhs.withoutData(), rhs.withoutData()}, gradFunc); } Variable operator+(const Variable& lhs, const double& rhs_val) { auto result = lhs.array() + rhs_val; auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(grad_output.array(), false)); }; return Variable(result, {lhs.withoutData()}, gradFunc); } Variable operator+(const double& lhs_val, const Variable& rhs) { return rhs + lhs_val; } Variable operator-(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() - rhs.array(); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(grad_output.array(), false)); inputs[1].addGrad(Variable(negate(grad_output).array(), false)); }; return Variable(result, {lhs.withoutData(), rhs.withoutData()}, gradFunc); } Variable operator-(const Variable& lhs, const double& rhs_val) { auto result = lhs.array() - rhs_val; auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(grad_output.array(), false)); }; return Variable(result, {lhs.withoutData()}, gradFunc); } Variable operator-(const double& lhs_val, const Variable& rhs) { auto result = lhs_val - rhs.array(); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(negate(grad_output).array(), false)); }; return Variable(result, {rhs.withoutData()}, gradFunc); } Variable operator*(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() * rhs.array(); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { if (inputs[0].isCalcGrad()) { inputs[0].addGrad(Variable((grad_output * inputs[1]).array(), false)); } if (inputs[1].isCalcGrad()) { inputs[1].addGrad(Variable((grad_output * inputs[0]).array(), false)); } }; return Variable( result, {rhs.isCalcGrad() ? lhs : lhs.withoutData(), lhs.isCalcGrad() ? rhs : rhs.withoutData()}, gradFunc); } Variable operator*(const Variable& lhs, const double& rhs_val) { auto result = lhs.array() * rhs_val; auto gradFunc = [rhs_val](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable((grad_output * rhs_val).array(), false)); }; return Variable(result, {lhs.withoutData()}, gradFunc); } Variable operator*(const double& lhs_val, const Variable& rhs) { return rhs * lhs_val; } Variable operator/(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() / rhs.array(); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { auto inputs_1_rec = reciprocal(inputs[1]); auto grad_input_0 = grad_output * inputs_1_rec; if (inputs[0].isCalcGrad()) { inputs[0].addGrad(Variable(grad_input_0.array(), false)); } if (inputs[1].isCalcGrad()) { inputs[1].addGrad(Variable( (grad_input_0 * negate(inputs[0]) * inputs_1_rec).array(), false)); } }; return Variable( result, {rhs.isCalcGrad() ? lhs : lhs.withoutData(), rhs}, gradFunc); } Variable operator/(const Variable& lhs, const double& rhs_val) { auto result = lhs.array() / rhs_val; auto gradFunc = [rhs_val](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable((grad_output / rhs_val).array(), false)); }; return Variable(result, {lhs.withoutData()}, gradFunc); } Variable operator/(const double& lhs_val, const Variable& rhs) { auto result = lhs_val / rhs.array(); auto gradFunc = [lhs_val]( std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable( (grad_output * (-lhs_val) / (inputs[0] * inputs[0])).array(), false)); }; return Variable(result, {rhs}, gradFunc); } Variable operator>(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() > rhs.array(); return Variable(result, false); } Variable operator>(const Variable& lhs, const double& rhs_val) { auto result = lhs.array() > rhs_val; return Variable(result, false); } Variable operator>(const double& lhs_val, const Variable& rhs) { auto result = lhs_val > rhs.array(); return Variable(result, false); } Variable operator<(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() < rhs.array(); return Variable(result, false); } Variable operator<(const Variable& lhs, const double& rhs_val) { auto result = lhs.array() < rhs_val; return Variable(result, false); } Variable operator<(const double& lhs_val, const Variable& rhs) { auto result = lhs_val < rhs.array(); return Variable(result, false); } Variable operator>=(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() >= rhs.array(); return Variable(result, false); } Variable operator>=(const Variable& lhs, const double& rhs_val) { auto result = lhs.array() >= rhs_val; return Variable(result, false); } Variable operator>=(const double& lhs_val, const Variable& rhs) { auto result = lhs_val >= rhs.array(); return Variable(result, false); } Variable operator<=(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() <= rhs.array(); return Variable(result, false); } Variable operator<=(const Variable& lhs, const double& rhs_val) { auto result = lhs.array() <= rhs_val; return Variable(result, false); } Variable operator<=(const double& lhs_val, const Variable& rhs) { auto result = lhs_val <= rhs.array(); return Variable(result, false); } Variable operator&&(const Variable& lhs, const Variable& rhs) { auto result = lhs.array() && rhs.array(); return Variable(result, false); } Variable operator!(const Variable& input) { auto result = !input.array(); return Variable(result, false); } Variable max(const Variable& lhs, const Variable& rhs) { auto result = max(lhs.array(), rhs.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { auto mask = Variable(inputs[0].array() > inputs[1].array(), false); inputs[0].addGrad(Variable((mask * grad_output).array(), false)); inputs[1].addGrad(Variable((!mask * grad_output).array(), false)); }; return Variable(result, {lhs, rhs}, gradFunc); } Variable max(const Variable& lhs, const double& rhs_val) { auto result = max(lhs.array(), rhs_val); auto gradFunc = [rhs_val](std::vector<Variable>& inputs, const Variable& grad_output) { auto mask = Variable(inputs[0].array() > rhs_val, false); inputs[0].addGrad(Variable((mask * grad_output).array(), false)); }; return Variable(result, {lhs}, gradFunc); } Variable max(const double& lhs_val, const Variable& rhs) { return max(rhs, lhs_val); } Variable min(const Variable& lhs, const Variable& rhs) { auto result = min(lhs.array(), rhs.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { auto mask = Variable(inputs[0].array() < inputs[1].array(), false); inputs[0].addGrad(Variable((mask * grad_output).array(), false)); inputs[1].addGrad(Variable((!mask * grad_output).array(), false)); }; return Variable(result, {lhs, rhs}, gradFunc); } Variable min(const Variable& lhs, const double& rhs_val) { auto result = min(lhs.array(), rhs_val); auto gradFunc = [rhs_val](std::vector<Variable>& inputs, const Variable& grad_output) { auto mask = Variable(inputs[0].array() < rhs_val, false); inputs[0].addGrad(Variable((mask * grad_output).array(), false)); }; return Variable(result, {lhs}, gradFunc); } Variable min(const double& lhs_val, const Variable& rhs) { return min(rhs, lhs_val); } Variable negate(const Variable& input) { auto result = 0.0 - input.array(); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(negate(grad_output).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable reciprocal(const Variable& input) { auto result = 1.0 / input.array(); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { auto res = reciprocal(inputs[0]); inputs[0].addGrad( Variable((negate(grad_output) * res * res).array(), false)); }; return Variable(result, {input}, gradFunc); } Variable exp(const Variable& input) { auto result = exp(input.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable((grad_output * exp(inputs[0])).array(), false)); }; return Variable(result, {input}, gradFunc); } Variable log(const Variable& input) { auto result = log(input.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable((grad_output / inputs[0]).array(), false)); }; return Variable(result, {input}, gradFunc); } Variable sin(const Variable& input) { auto result = sin(input.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable((grad_output * cos(inputs[0])).array(), false)); }; return Variable(result, {input}, gradFunc); } Variable cos(const Variable& input) { auto result = cos(input.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad( Variable((grad_output * negate(sin(inputs[0]))).array(), false)); }; return Variable(result, {input}, gradFunc); } Variable tanh(const Variable& input) { auto result = tanh(input.array()); auto gradFunc = [result](std::vector<Variable>& inputs, const Variable& grad_output) { auto grad = Variable((1.0 - result * result) * grad_output.array(), false); inputs[0].addGrad(Variable(grad.array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable clamp(const Variable& input, const double lo, const double hi) { auto result = clamp(input.array(), lo, hi); auto gradFunc = [lo, hi, result]( std::vector<Variable>& inputs, const Variable& grad_output) { af::array grad_mask = grad_output.array(); replace(grad_mask, (result > lo) && (result < hi), 0); inputs[0].addGrad(Variable(grad_mask, false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable sqrt(const Variable& input) { auto result = af::sqrt(input.array()); auto gradFunc = [result]( std::vector<Variable>& inputs, const Variable& grad_output) { auto output = Variable(result, false); inputs[0].addGrad(Variable((grad_output / (2 * output)).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable sigmoid(const Variable& input) { auto result = sigmoid(input.array()); auto gradFunc = [result](std::vector<Variable>& inputs, const Variable& grad_output) { auto grad = grad_output.array() * result * (1 - result); inputs[0].addGrad(Variable(grad, false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable transpose(const Variable& input) { auto result = transpose(input.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(transpose(grad_output).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable tileAs(const Variable& input, const af::dim4& rdims) { auto result = detail::tileAs(input.array(), rdims); af::dim4 in_dims = input.dims(); auto gradFunc = [in_dims](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(sumAs(grad_output, in_dims).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable tileAs(const Variable& input, const Variable& reference) { return tileAs(input, reference.dims()); } Variable sumAs(const Variable& input, const af::dim4& rdims) { auto result = detail::sumAs(input.array(), rdims); auto idims = input.dims(); auto gradFunc = [idims](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(tileAs(grad_output, idims).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable sumAs(const Variable& input, const Variable& reference) { return sumAs(input, reference.dims()); } Variable concatenate(const std::vector<Variable>& concatInputs, int dim) { if (concatInputs.empty()) { throw std::invalid_argument("cannot concatenate zero variables"); } if (dim < 0 || dim > 3) { throw std::invalid_argument("invalid dimension to concatenate along"); } auto dims = concatInputs[0].dims(); int concat_size = dims[dim]; for (int i = 1; i < concatInputs.size(); i++) { concat_size += concatInputs[i].dims(dim); for (int d = 0; d < 4; d++) { if (dim != d && concatInputs[i].dims(d) != dims[d]) { throw std::invalid_argument( "mismatch in dimension not being concatenated"); } } } dims[dim] = concat_size; af::array result(dims, concatInputs[0].type()); std::array<af::index, 4> slice{af::span, af::span, af::span, af::span}; int start = 0; for (const auto& input : concatInputs) { slice[dim] = af::seq(start, start + input.dims(dim) - 1); result(slice[0], slice[1], slice[2], slice[3]) = input.array(); start += input.dims(dim); } std::vector<Variable> inputs_nodata; std::vector<af::dim4> in_dims; for (const auto& in : concatInputs) { inputs_nodata.push_back(in.withoutData()); in_dims.push_back(in.dims()); } auto gradFunc = [dim, in_dims]( std::vector<Variable>& inputs, const Variable& grad_output) { std::array<af::index, 4> sx{af::span, af::span, af::span, af::span}; int s = 0; for (size_t i = 0; i < inputs.size(); ++i) { sx[dim] = af::seq(s, s + in_dims[i][dim] - 1); inputs[i].addGrad( Variable(grad_output.array()(sx[0], sx[1], sx[2], sx[3]), false)); s += in_dims[i][dim]; } }; return Variable(result, inputs_nodata, gradFunc); } Variable tile(const Variable& input, const af::dim4& dims) { auto result = tile(input.array(), dims); af::dim4 idims = input.dims(); auto gradFunc = [idims](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(sumAs(grad_output, idims).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable sum(const Variable& input, const std::vector<int>& axes) { auto result = input.array(); for (size_t i = 0; i < axes.size(); i++) { result = sum(result, axes[i]); } af::dim4 indims = input.dims(); auto gradFunc = [indims](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(tileAs(grad_output, indims).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable mean(const Variable& input, const std::vector<int>& axes) { auto result = input.array(); for (size_t i = 0; i < axes.size(); i++) { result = mean(result, axes[i]); } af::dim4 idims = input.dims(); auto gradFunc = [idims](std::vector<Variable>& inputs, const Variable& grad_output) { af::dim4 odims = grad_output.dims(); dim_t count = 1; for (int i = 0; i < 4; i++) { count *= idims[i] / odims[i]; } inputs[0].addGrad( Variable((tileAs(grad_output, idims) / count).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable var( const Variable& input, const std::vector<int>& axes, const bool isbiased /* = false */) { auto result = sum(input * input, axes); auto avg = mean(input, axes); auto n = 1; for (auto ax : axes) { n *= input.dims(ax); } if (!isbiased && n == 1) { throw std::invalid_argument( "cannot compute unbiased variance with only one sample"); } auto val = 1.0 / (isbiased ? n : n - 1); result = val * (result - n * avg * avg); auto gradFunc = [val, axes](std::vector<Variable>& inputs, const Variable& grad_output) { af::dim4 tiledims(1, 1, 1, 1); for (auto ax : axes) { tiledims[ax] = inputs[0].dims(ax); } inputs[0].addGrad(Variable( (2 * val * tile(grad_output, tiledims) * (inputs[0] - tile(mean(inputs[0], axes), tiledims))) .array(), false)); }; return Variable(result.array(), {input}, gradFunc); } Variable norm(const Variable& input, const std::vector<int>& axes) { auto result = input.array() * input.array(); for (size_t i = 0; i < axes.size(); i++) { result = sum(result, axes[i]); } result = af::sqrt(result); result.eval(); auto gradFunc = [result]( std::vector<Variable>& inputs, const Variable& grad_output) { auto output = Variable(result, false); inputs[0].addGrad(Variable( (inputs[0] * tileAs(grad_output / output, inputs[0])).array(), false)); }; return Variable(result, {input}, gradFunc); } Variable matmul(const Variable& lhs, const Variable& rhs) { // lhs:Input[0] -- [M, N] // rhs:Input[1] -- [N, K] // matmul(lhs, rhs) // -- matmul([M, N], [N, K]) -- [M, K] // result:grad_output -- [M, K] auto result = matmul(lhs.array(), rhs.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { if (inputs[0].isCalcGrad()) { // matmulNT(grad_output, inputs[1]) // -- matmulNT([M, K], [N, K]) // -- matmul([M, K], [K, N]) -- [M, K] inputs[0].addGrad( Variable(matmulNT(grad_output, inputs[1]).array(), false)); } if (inputs[1].isCalcGrad()) { // matmulTN(inputs[0], grad_output) // -- matmulTN([M, N], [M, K]) // -- matmul([N, M], [M, K]) -- [N, K] inputs[1].addGrad( Variable(matmulTN(inputs[0], grad_output).array(), false)); } }; return Variable(result, {lhs, rhs}, gradFunc); } Variable matmulTN(const Variable& lhs, const Variable& rhs) { // lhs:Input[0] -- [N, M] // rhs:Input[1] -- [N, K] // matmulTN(lhs, rhs) // -- matmulTN([N, M], [N, K]) // -- matmul([M, N], [N, K]) -- [M, K] // result:grad_output -- [M, K] auto result = matmulTN(lhs.array(), rhs.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { if (inputs[0].isCalcGrad()) { // matmulNT(inputs[1], grad_output) // -- matmulNT([N, K], [M, K]) // -- matmul([N, K], [K, M]) -- [N, M] inputs[0].addGrad( Variable(matmulNT(inputs[1], grad_output).array(), false)); } if (inputs[1].isCalcGrad()) { // matmul(inputs[0], grad_output) // -- matmulNT([N, M], [M, K]) -- [N, K] inputs[1].addGrad( Variable(matmul(inputs[0], grad_output).array(), false)); } }; return Variable(result, {lhs, rhs}, gradFunc); } Variable matmulNT(const Variable& lhs, const Variable& rhs) { // lhs:Input[0] -- [M, N] // rhs:Input[1] -- [K, N] // matmulNT(lhs, rhs) // -- matmulNT([M, N], [K, N]) // -- matmul([M, N], [N, K]) -- [M, K] // result:grad_output -- [M, K] auto result = matmulNT(lhs.array(), rhs.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { if (inputs[0].isCalcGrad()) { // matmul(grad_output, inputs[1]) // -- matmul([M, K], [K, N]) -- [M, N] inputs[0].addGrad( Variable(matmul(grad_output, inputs[1]).array(), false)); } if (inputs[1].isCalcGrad()) { // matmulTN(grad_output, inputs[0]) // -- matmulTN([M, K], [M, N]) // -- matmul([K, M], [M, N]) -- [K, N] inputs[1].addGrad( Variable(matmulTN(grad_output, inputs[0]).array(), false)); } }; return Variable(result, {lhs, rhs}, gradFunc); } Variable abs(const Variable& input) { auto result = af::abs(input.array()); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { // af::sign returns signbit // Convert it into -1, 1 auto sign = Variable(1 - 2 * af::sign(inputs[0].array()), false); inputs[0].addGrad(Variable((sign * grad_output).array(), false)); }; return Variable(result, {input}, gradFunc); } Variable flat(const Variable& input) { auto result = af::flat(input.array()); af::dim4 idims = input.dims(); auto gradFunc = [idims](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(moddims(grad_output, idims).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable moddims(const Variable& input, const af::dim4& dims) { af::dim4 infer_dims = dims; // Infer any 0 dim for (int i = 0; i < 4; ++i) { if (infer_dims[i] == 0) { infer_dims[i] = input.dims(i); } } // Infer any -1 dim int n_infer = 0; for (int i = 0; i < 4; i++) { if (infer_dims[i] == -1) { n_infer++; infer_dims[i] = -(input.elements() / infer_dims.elements()); } } if (n_infer > 1) { throw std::invalid_argument("too many dimensions for moddims to infer"); } if (infer_dims.elements() != input.elements()) { throw std::invalid_argument("mismatched # of elements in moddims"); } auto result = af::moddims(input.array(), infer_dims); af::dim4 in_dims = input.dims(); auto gradFunc = [in_dims]( std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable(moddims(grad_output, in_dims).array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable softmax(const Variable& input, const int dim) { auto maxvals = max((input.array()), dim); af::dim4 tiledims(1, 1, 1, 1); tiledims[dim] = input.dims(dim); auto exp_input = exp(input.array() - tile(maxvals, tiledims)); auto result = exp_input / tile(sum(exp_input, dim), tiledims); result.eval(); auto gradFunc = [dim, tiledims, result]( std::vector<Variable>& inputs, const Variable& grad_output) { auto rbyg = grad_output.array() * result; auto grad_sm = rbyg - result * tile(sum(rbyg, dim), tiledims); inputs[0].addGrad(Variable(grad_sm, false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable logSoftmax(const Variable& input, const int dim) { auto maxvals = max((input.array()), dim); af::dim4 tiledims(1, 1, 1, 1); tiledims[dim] = input.dims(dim); auto result = input.array() - tile(log(sum(exp(input.array() - tile(maxvals, tiledims)), dim)) + maxvals, tiledims); result.eval(); auto gradFunc = [dim, tiledims, result]( std::vector<Variable>& inputs, const Variable& grad_output) { auto grad_lsm = grad_output.array() - exp(result) * tile(sum(grad_output.array(), dim), tiledims); inputs[0].addGrad(Variable(grad_lsm, false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable binaryCrossEntropy(const Variable& inputs, const Variable& targets) { return negate(targets * log(inputs) + (1 - targets) * log(1 - inputs)); } Variable categoricalCrossEntropy( const Variable& input, const Variable& targets, ReduceMode reduction /* =ReduceMode::MEAN */) { // input -- [C, X1, X2, X3] // target -- [X1, X2, X3, 1] for (int i = 1; i < 4; i++) { if (input.dims(i) != targets.dims(i - 1)) { throw std::invalid_argument( "dimension mismatch in categorical cross entropy"); } } if (targets.dims(3) != 1) { throw std::invalid_argument( "dimension mismatch in categorical cross entropy"); } int categories = input.dims(0); int num_elems = input.elements() / categories; af::array A = af::range(af::dim4(categories, num_elems)); af::array B = af::moddims(targets.array(), af::dim4(1, targets.elements())); B = tile(B, af::dim4(categories, 1, 1, 1)); auto mask = -(A == B); auto result = mask * af::moddims(input.array(), af::dim4(categories, num_elems)); result = af::sum(result, 0); if (reduction == ReduceMode::NONE) { result = af::moddims(result, targets.dims()); } else if (reduction == ReduceMode::MEAN) { result = af::mean(result, 1); } else if (reduction == ReduceMode::SUM) { result = af::sum(result, 1); } else { throw std::invalid_argument( "unknown reduction method for categorical cross entropy"); } af::dim4 in_dims = input.dims(); auto gradFunc = [mask, reduction, num_elems, in_dims]( std::vector<Variable>& inputs, const Variable& grad_output) { auto grad = grad_output; if (reduction == ReduceMode::NONE) { grad = moddims(grad, af::dim4(1, num_elems)); } grad = Variable(detail::tileAs(grad.array(), mask.dims()) * mask, false); if (reduction == ReduceMode::MEAN) { grad = grad / num_elems; } inputs[0].addGrad(Variable(moddims(grad, in_dims).array(), false)); }; return Variable(result, {input.withoutData(), targets}, gradFunc); } Variable reorder( const Variable& input, const int dim0, const int dim1, const int dim2, const int dim3) { auto result = reorder(input.array(), dim0, dim1, dim2, dim3); if (!af::isLinear(result)) { auto tmp = af::array(result.dims(), input.type()); af::copy(tmp, result, af::span); result = tmp; } std::vector<std::pair<int, int>> dimgrad = { {dim0, 0}, {dim1, 1}, {dim2, 2}, {dim3, 3}}; std::sort(dimgrad.begin(), dimgrad.end()); auto gradFunc = [dimgrad](std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(Variable( reorder( grad_output, dimgrad[0].second, dimgrad[1].second, dimgrad[2].second, dimgrad[3].second) .array(), false)); }; return Variable(result, {input.withoutData()}, gradFunc); } Variable linear(const Variable& input, const Variable& weight) { auto dummy_bias = Variable(af::array(), false); return linear(input, weight, dummy_bias); } Variable linear(const Variable& input, const Variable& weight, const Variable& bias) { auto has_bias = bias.elements() > 0; af::dim4 to2d(input.dims(0), input.elements() / input.dims(0)); auto to4d = input.dims(); to4d[0] = weight.dims(0); auto output = moddims(matmul(weight.array(), moddims(input.array(), to2d)), to4d); if (has_bias) { auto tiledims = output.dims(); tiledims[0] = 1; output = output + tile(bias.array(), tiledims); } auto gradFunc = [has_bias]( std::vector<Variable>& inputs, const Variable& grad_output) { auto& in = inputs[0]; auto& wt = inputs[1]; auto nframes = in.elements() / in.dims(0); if (has_bias && inputs[2].isCalcGrad()) { auto& bs = inputs[2]; bs.addGrad(Variable(sumAs(grad_output, bs).array(), false)); } if (in.isCalcGrad()) { af::dim4 to2dout(wt.dims(0), nframes); in.addGrad(Variable( moddims(matmulTN(wt, moddims(grad_output, to2dout)), in.dims()) .array(), false)); } if (wt.isCalcGrad()) { af::dim4 to2din(wt.dims(1), nframes); af::dim4 to2dout(wt.dims(0), nframes); wt.addGrad(Variable( matmulNT(moddims(grad_output, to2dout), moddims(in, to2din)).array(), false)); } }; if (has_bias) { return Variable(output, {input, weight, bias}, gradFunc); } return Variable(output, {input, weight}, gradFunc); } Variable gatedlinearunit(const Variable& input, const int dim) { auto in_size = input.dims(dim); if (in_size % 2 == 1) { throw std::invalid_argument("halving dimension must be even for GLU"); } std::array<af::seq, 4> fhalf = {af::span, af::span, af::span, af::span}; fhalf[dim] = af::seq(in_size / 2); std::array<af::seq, 4> shalf = {af::span, af::span, af::span, af::span}; shalf[dim] = af::seq(in_size / 2, in_size - 1); auto result = input.array()(fhalf[0], fhalf[1], fhalf[2], fhalf[3]) * sigmoid(input.array()(shalf[0], shalf[1], shalf[2], shalf[3])); auto gradFunc = [fhalf, shalf]( std::vector<Variable>& inputs, const Variable& grad_output) { auto& input = inputs[0]; auto grad_glu = af::array(input.dims(), input.type()); auto shalfout = sigmoid(input.array()(shalf[0], shalf[1], shalf[2], shalf[3])); grad_glu(fhalf[0], fhalf[1], fhalf[2], fhalf[3]) = shalfout * grad_output.array(); grad_glu(shalf[0], shalf[1], shalf[2], shalf[3]) = shalfout * (1.0 - shalfout) * input.array()(fhalf[0], fhalf[1], fhalf[2], fhalf[3]) * grad_output.array(); inputs[0].addGrad(Variable(grad_glu, false)); }; return Variable(result, {input}, gradFunc); } Variable embedding(const Variable& input, const Variable& embeddings) { if (input.numdims() >= 4) { throw std::invalid_argument("embedding input must have 3 or fewer dims"); } auto idxs = af::flat(input.array()); Variable result = Variable(embeddings.array()(af::span, idxs), false); auto in_dims = input.dims(); af::dim4 result_dims = { embeddings.dims(0), in_dims[0], in_dims[1], in_dims[2]}; result = moddims(result, result_dims); auto gradFunc = [](std::vector<Variable>& inputs, const Variable& grad_output) { auto& w = inputs[1]; if (!w.isCalcGrad()) { return; } auto ip = af::flat(inputs[0].array()); auto deltas = af::moddims(grad_output.array(), w.dims(0), ip.elements()); auto sp = sparse( ip.elements(), w.dims(1), af::constant(1, ip.elements(), deltas.type()), af::range(af::dim4(ip.elements() + 1), 0, s32), ip.as(s32), AF_STORAGE_CSR); auto grad = transpose(matmulTN(sp, transpose(deltas))); w.addGrad(Variable(grad, false)); }; return Variable(result.array(), {input, embeddings}, gradFunc); } Variable padding( const Variable& input, std::vector<std::pair<int, int>> pad, double val) { af::dim4 op_dims = input.dims(); std::array<af::seq, 4> in_seq = {af::span, af::span, af::span, af::span}; for (int i = 0; i < pad.size(); ++i) { op_dims[i] += (pad[i].first + pad[i].second); in_seq[i] = af::seq(pad[i].first, op_dims[i] - pad[i].second - 1); } af::array result = af::constant(val, op_dims, input.type()); result(in_seq[0], in_seq[1], in_seq[2], in_seq[3]) = input.array(); auto gradFunc = [in_seq]( std::vector<Variable>& inputs, const Variable& grad_output) { inputs[0].addGrad(grad_output(in_seq[0], in_seq[1], in_seq[2], in_seq[3])); }; return Variable(result, {input.withoutData()}, gradFunc); } } // namespace fl
21e557b437cb374995727fd2939cf2330f321082
72d44d01083aeb66606cecd9d84dbb0eb17b0acb
/leetcode/leetcode173/leetcode173/main.cpp
481a449b8e4c57cca58be4c5dc3365ebe5602e19
[]
no_license
danache/coding
e3d704b6302acb913d3f58ea1dfe9e126d1b0f39
ef798534e8412eb81f31318244305e1a6110ea72
refs/heads/master
2020-04-19T15:12:56.562307
2018-06-03T06:24:37
2018-06-03T06:24:37
66,996,085
2
0
null
null
null
null
UTF-8
C++
false
false
1,217
cpp
// // main.cpp // leetcode173 // // Created by 萧天牧 on 17/4/23. // Copyright © 2017年 萧天牧. All rights reserved. // #include <iostream> #include <stack> #include <vector> using namespace std; /** * Definition for binary tree */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class BSTIterator { stack<TreeNode *> myStack; public: BSTIterator(TreeNode *root) { pushAll(root); } /** @return whether we have a next smallest number */ bool hasNext() { return !myStack.empty(); } /** @return the next smallest number */ int next() { TreeNode *tmpNode = myStack.top(); myStack.pop(); pushAll(tmpNode->right); return tmpNode->val; } private: void pushAll(TreeNode *node) { for(; node!= NULL; myStack.push(node), node = node -> left); } }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */ int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }