hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
c0c57e7b9aa81e7b7b64a21952ddb9edc5c10a23
2,832
cpp
C++
src/Rips_complex/example/example_rips_complex_from_csv_distance_matrix_file.cpp
m0baxter/gudhi-devel
6e14ef1f31e09f3875316440303450ff870d9881
[ "MIT" ]
146
2019-03-15T14:10:31.000Z
2022-03-23T21:14:52.000Z
src/Rips_complex/example/example_rips_complex_from_csv_distance_matrix_file.cpp
m0baxter/gudhi-devel
6e14ef1f31e09f3875316440303450ff870d9881
[ "MIT" ]
398
2019-03-07T14:55:22.000Z
2022-03-31T14:50:40.000Z
src/Rips_complex/example/example_rips_complex_from_csv_distance_matrix_file.cpp
m0baxter/gudhi-devel
6e14ef1f31e09f3875316440303450ff870d9881
[ "MIT" ]
51
2019-03-08T15:58:48.000Z
2022-03-14T10:23:23.000Z
#include <gudhi/Rips_complex.h> // to construct Rips_complex from a csv file representing a distance matrix #include <gudhi/reader_utils.h> #include <gudhi/Simplex_tree.h> #include <gudhi/distance_functions.h> #include <iostream> #include <string> #include <vector> void usage(int nbArgs, char * const progName) { std::cerr << "Error: Number of arguments (" << nbArgs << ") is not correct\n"; std::cerr << "Usage: " << progName << " filename.csv threshold dim_max [ouput_file.txt]\n"; std::cerr << " i.e.: " << progName << " ../../data/distance_matrix/full_square_distance_matrix.csv 1.0 3\n"; exit(-1); // ----- >> } int main(int argc, char **argv) { if ((argc != 4) && (argc != 5)) usage(argc, (argv[0] - 1)); std::string csv_file_name(argv[1]); double threshold = atof(argv[2]); int dim_max = atoi(argv[3]); // Type definitions using Simplex_tree = Gudhi::Simplex_tree<>; using Filtration_value = Simplex_tree::Filtration_value; using Rips_complex = Gudhi::rips_complex::Rips_complex<Filtration_value>; using Distance_matrix = std::vector<std::vector<Filtration_value>>; // ---------------------------------------------------------------------------- // Init of a Rips complex from a distance matrix in a csv file // Default separator is ';' // ---------------------------------------------------------------------------- Distance_matrix distances = Gudhi::read_lower_triangular_matrix_from_csv_file<Filtration_value>(csv_file_name); Rips_complex rips_complex_from_file(distances, threshold); std::streambuf* streambuffer; std::ofstream ouput_file_stream; if (argc == 5) { ouput_file_stream.open(std::string(argv[4])); streambuffer = ouput_file_stream.rdbuf(); } else { streambuffer = std::clog.rdbuf(); } Simplex_tree stree; rips_complex_from_file.create_complex(stree, dim_max); std::ostream output_stream(streambuffer); // ---------------------------------------------------------------------------- // Display information about the Rips complex // ---------------------------------------------------------------------------- output_stream << "Rips complex is of dimension " << stree.dimension() << " - " << stree.num_simplices() << " simplices - " << stree.num_vertices() << " vertices." << std::endl; output_stream << "Iterator on Rips complex simplices in the filtration order, with [filtration value]:" << std::endl; for (auto f_simplex : stree.filtration_simplex_range()) { output_stream << " ( "; for (auto vertex : stree.simplex_vertex_range(f_simplex)) { output_stream << vertex << " "; } output_stream << ") -> " << "[" << stree.filtration(f_simplex) << "] "; output_stream << std::endl; } ouput_file_stream.close(); return 0; }
38.794521
116
0.59322
[ "vector" ]
c0c99e1e379ffc2c6be8ebbcad0ee26596375756
3,709
cpp
C++
Spoj/Spoj_AC/MKTHNUM - K-th Number.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
3
2018-05-11T07:33:20.000Z
2020-08-30T11:02:02.000Z
Spoj/Spoj_AC/MKTHNUM - K-th Number.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
1
2018-05-11T18:10:26.000Z
2018-05-12T18:00:28.000Z
Spoj/Spoj_AC/MKTHNUM - K-th Number.cpp
Saikat-S/acm-problems-solutions
921c0f3e508e1ee8cd14be867587952d5f67bbb9
[ "MIT" ]
null
null
null
/*************************************************** * Problem Name : MKTHNUM - K-th Number.cpp * Problem Link : https://www.spoj.com/problems/MKTHNUM/ * OJ : Spoj * Verdict : AC * Date : 2019-03-07 * Problem Type : Segment Tree * Author Name : Saikat Sharma * University : CSE, MBSTU ***************************************************/ #include<iostream> #include<cstdio> #include<algorithm> #include<climits> #include<cstring> #include<string> #include<sstream> #include<cmath> #include<vector> #include<queue> #include<cstdlib> #include<deque> #include<stack> #include<map> #include<set> #define __FastIO ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0) #define __FileRead freopen ("/home/saikat/Desktop/logN/input.txt", "r", stdin); #define __FileWrite freopen ("/home/saikat/Desktop/logN/output.txt", "w", stdout); #define SET(a,v) memset(a,v,sizeof(a)) #define pii pair<int,int> #define pll pair <ll, ll> #define debug cout <<"#########\n"; #define nl cout << "\n"; #define sp cout << " "; #define sl(n) scanf("%lld", &n) #define sf(n) scanf("%lf", &n) #define si(n) scanf("%d", &n) #define ss(n) scanf("%s", n) #define pf(n) scanf("%d", n) #define pfl(n) scanf("%lld", n) #define all(v) v.begin(), v.end() #define Pow2(x) ((x)*(x)) #define Mod(x, m) ((((x) % (m)) + (m)) % (m)) #define Max3(a, b, c) max(a, max(b, c)) #define Min3(a, b, c) min(a, min(b, c)) #define pb push_back #define mk make_pair #define MAX 100005 #define INF 1000000000 #define MOD 1000000007 using namespace std; typedef long long ll; typedef unsigned long long ull; template <typename T> std::string NumberToString ( T Number ) { std::ostringstream ss; ss << Number; return ss.str(); } ll lcm (ll a, ll b) { return a * b / __gcd (a, b); } /************************************ Code Start Here ******************************************************/ int ar[MAX]; vector<vector<int> >tree (MAX * 4); vector<int>qr; vector<int> mergeTree (int left, int right) { vector<int>vec ( (int) tree[left].size() + (int) tree[right].size() ); merge (all (tree[left]), all (tree[right]), vec.begin() ); return vec; } void build (int nod, int low, int high) { if (low == high) { tree[nod].pb (ar[low]); return; } int mid = (high + low) / 2; build (nod * 2, low, mid); build (nod * 2 + 1, mid + 1, high); tree[nod] = mergeTree (nod * 2, nod * 2 + 1); } void query (int nod, int low, int high, int qlow, int qhigh) { if (qlow > high || qhigh < low) { return; } if (qlow <= low && qhigh >= high) { qr.pb (nod); return; } int mid = (high + low) / 2; query (nod * 2, low, mid, qlow, qhigh); query (nod * 2 + 1, mid + 1, high, qlow, qhigh); } int binary (int l, int r, int n, int kth) { int low = 0, high = n - 1; int pos = 0; while (high >= low) { int mid = (high + low) / 2; int sum = 0; for (int i = 0; i < (int) qr.size(); i++) { int nod = qr[i]; int x = upper_bound (all (tree[nod]), tree[1][mid] - 1) - tree[nod].begin(); sum += x; } if (sum >= kth) { high = mid - 1; } else { pos = mid; low = mid + 1; } } return pos; } int main () { __FastIO; int n, q; cin >> n >> q; for (int i = 0; i < n; i++) { cin >> ar[i]; } build (1, 0, n - 1); while (q--) { int l, r, kth; cin >> l >> r >> kth; qr.clear(); query (1, 0, n - 1, l - 1, r - 1); int pos = binary (l - 1, r - 1, n, kth); cout << tree[1][pos] << "\n"; } return 0; }
24.726667
109
0.508223
[ "vector" ]
c0cc57ceb6c1759a05d121beadedbf95949c8058
1,193
cpp
C++
Algorithms/1293.Shortest_Path_in_a_Grid_with_Obstacles_Elimination.cpp
metehkaya/LeetCode
52f4a1497758c6f996d515ced151e8783ae4d4d2
[ "MIT" ]
2
2020-07-20T06:40:22.000Z
2021-11-20T01:23:26.000Z
Problems/LeetCode/Problems/1293.Shortest_Path_in_a_Grid_with_Obstacles_Elimination.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
Problems/LeetCode/Problems/1293.Shortest_Path_in_a_Grid_with_Obstacles_Elimination.cpp
metehkaya/Algo-Archive
03b5fdcf06f84a03125c57762c36a4e03ca6e756
[ "MIT" ]
null
null
null
#define fi first #define se second typedef pair<int,int> pi; typedef pair<pi,int> pii; class Solution { public: const int DIR[4][2] = {{0,1},{0,-1},{1,0},{-1,0}}; int shortestPath(vector<vector<int>>& ar, int k) { int n = ar.size(); int m = ar[0].size(); queue<pii> Q; int dist[n][m][k+1]; memset(dist,-1,sizeof(dist)); dist[0][0][0] = 0; Q.push(pii(pi(0,0),0)); while(!Q.empty()) { pii temp = Q.front(); Q.pop(); int r = temp.fi.fi; int c = temp.fi.se; int a = temp.se; if(r == n-1 && c == m-1) return dist[r][c][a]; for( int i = 0 ; i < 4 ; i++ ) { int x = r + DIR[i][0]; int y = c + DIR[i][1]; if(x < 0 || x >= n || y < 0 || y >= m) continue; int b = a + ar[x][y]; if(b > k) continue; if(dist[x][y][b] != -1) continue; Q.push(pii(pi(x,y),b)); dist[x][y][b] = dist[r][c][a] + 1; } } return -1; } };
29.097561
54
0.360436
[ "vector" ]
c0d42980b44e96e5d2a1686db824b91913d91cf0
46,421
cpp
C++
src/eng/ldtran.cpp
onecoolx/xpoly
0476208738795f7c23ea4b701e03ee7cd6d33e10
[ "BSD-3-Clause" ]
21
2015-02-01T11:28:39.000Z
2021-11-12T06:44:53.000Z
src/eng/ldtran.cpp
onecoolx/xpoly
0476208738795f7c23ea4b701e03ee7cd6d33e10
[ "BSD-3-Clause" ]
1
2016-02-19T03:21:39.000Z
2017-02-13T03:11:21.000Z
src/eng/ldtran.cpp
onecoolx/xpoly
0476208738795f7c23ea4b701e03ee7cd6d33e10
[ "BSD-3-Clause" ]
8
2015-03-02T11:09:25.000Z
2021-12-09T06:10:44.000Z
/*@ Copyright (c) 2013-2014, Su Zhenyu steven.known@gmail.com 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 Su Zhenyu 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 "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 "ltype.h" #include "comf.h" #include "strbuf.h" #include "smempool.h" #include "rational.h" #include "flty.h" #include "sstl.h" #include "matt.h" #include "bs.h" #include "sbs.h" #include "sgraph.h" #include "xmat.h" #include "linsys.h" using namespace xcom; #include "depvecs.h" #include "ldtran.h" // //START LoopTran // //Set coeff matrix and index of start column of constant term. void LoopTran::set_param(RMat * m, INT rhs_idx) { ASSERT(m && m->get_col_size() > 0, ("coeff mat is empty")); m_a = m; if (rhs_idx == -1) { m_rhs_idx = m->get_col_size() -1; return; } ASSERT(rhs_idx < (INT)m->get_col_size() && rhs_idx >= 1, ("out of bound")); m_rhs_idx = rhs_idx; } //Nonsingular Transformation Model is a framework that allows transformations //of loops using non-singular matrix based transformations of the iteration //space and loop bounds. This allows compositions of skewing, scaling, //interchange, and reversal transformations. These transformations are often //used to improve cache behavior or remove inner loop dependencies to allow //parallelization and vectorization to take place. //The function transform original loop bounds to new loop bounds. //Return true if transformation is unimodular, otherwise return false. // //'t': transforming matrix, must be nonsingular. //'stride': row vector, elements from first to last // indicates new strides for each loop index variables. // e.g: If the stride is [1,2,4,1], that means // do i1... by 1 // do i2 ... by 2 // do i3 ... by 4 // do i4 ... by 1 //'idx_map': matrix(nvar,nvar), the relation between original // index variable and new index variable. // And following code generation will subject to the // represetation of 'idx_map'. // e.g: idx_map is [1, 2] // [0, -1] // assuming that original index is (i,j), // new index is (x, y), that will generated new mapping // code and it should be inserted in original loop body: // i = 1*x + 2*y; // j = 0*x + -1*y; // ... //'aux_limits': New loop bound that represent limits of each loop // index variable in auxiliary iteration space. Head node shows // limits of outermost loop, tail node shows the innermost. //'ofst': Offset vectors of new iteration space is corresponding to // 'auxiliary iteration space'. Since the first variable does not // need offset, the first row will be zero. Each row indicates the // relevant offset vector of loop index. So 'ofst' is low trapezoid // matrix. // // e.g: u, v, w are loop indices of iter-space. // x, y, z are loop indices of auxiliary iter-space. // Assuming 'ofst' is 3*3 rational matrix as followed: // [0, 0, 0] // [-2, 0, 0] // [2, 1/3, 0] // That means the offset of u, v, w are: // offset(u) = 0 // offset(v) = -2*u // offset(w) = 2*u + (1/3)*v //'mul': If 't' is nonunimodular matrix, but nonsingular, loop scaling // would be performed, auxiliary iteration space would be stretched. // // e.g: Given 'mul' is [2,3], and loop limits of auxiliary iter-space is // L<=u<=U // f(u)<=v<=g(u), // then new loop limits will be: // 2*L<=u<=2*U // 3*f(u)<=v<=3*g(u), //'trA': record the full-dimension transformed iteration space. // //NOTICE: // If 't' is not unimodular(nonsingular) matrix, new iteration // space may include some points which not in original iteration // space, we need to find the points within the limits that are // in the lattice generated by 't', and the relevant 'stride' as // well to keep the injection from points in new space to points // in original space. bool LoopTran::transformIterSpace(IN RMat & t, OUT RMat & stride, OUT RMat & idx_map, OUT List<RMat*> & aux_limits, OUT RMat & ofst, OUT RMat & mul, OUT RMat * trA) { ASSERT(aux_limits.get_elem_count() == (UINT)m_rhs_idx, ("unmatch coeff matrix info")); RMat * A, tmpA, C, Ui, invt; if (trA != NULL) { A = trA; } else { A = &tmpA; } Rational det = t.det(); ASSERT(det != 0, ("T is singular!!")); UINT vars = m_rhs_idx; //number of variables ASSERT(vars == t.get_row_size(), ("loop nest only %d indices",vars)); bool is_uni; if (t.abs(det) == 1) { //unimodular tran ofst.reinit(0,0); mul.reinit(0,0); //Given A*i <= C, j = T*i, further in the new inequality derivable, //that is (A*T^(-1))*j <= C. //Appling fme to new system of inequalities to generate target limit. t.inv(invt); //m_a->innerColumn(A, 0, 0, m_a->get_row_size() - 1, m_rhs_idx - 1); m_a->innerColumn(*A, 0, m_rhs_idx - 1); *A = *A * invt; INT i; //The stride of result loop limits always be one in unimodular tran. stride.reinit(1, m_rhs_idx); for (i = 0; i < m_rhs_idx; i++) { stride.set(0, i, 1); } m_a->inner(C, 0, m_rhs_idx, m_a->get_row_size() - 1, m_a->get_col_size() - 1); A->grow_col(C, 0, C.get_col_size() -1); //Computes new loop limits Lineq lineq(A, m_rhs_idx); RMat * newb = aux_limits.get_tail(); RMat res; //Eliminating each variable from inner most loop to outer loop, //except the outer most loop. for (i = m_rhs_idx - 1; i > 0; i--) { *newb = *A; if (!lineq.fme(i, res, false)) { ASSERT(0, ("system inconsistency!")); } *A = res; newb = aux_limits.get_prev(); ASSERT(newb != NULL, ("miss buf to hold transformed " "boundary of dimension %d", i)); } //Record outermost loop bound. *newb = *A; if (A == trA) { //return the transformed iteration space. *A = *aux_limits.get_tail(); } aux_limits.get_tail(); is_uni = true; } else { //Nonsingular trans RMat H, Hi; INTMat tmph,tmpu; INTMat it; //HNF is one method of INTMat. it.copy(t); it.hnf(tmph, tmpu); //tmph = it * tmpu Ui.copy(tmpu); H.copy(tmph); { #ifdef _DEBUG_ RMat U; Ui.inv(U); // it = tmph * Ui; U = H * U; ASSERT(t==U, ("illegal inv")); #endif } H.getdiag(stride); mul.copy(stride); H.inv(Hi); invt = Ui * Hi; #ifdef _DEBUG_ RMat invt2, e(t.get_row_size(), t.get_col_size()); e.eye(1); t.inv(invt2); ASSERT(e==t*invt2, ("illegal inv")); #endif //A*i <= C, k = U*i => A*U^(-1)*k <= C m_a->inner(*A, 0, 0, m_a->get_row_size() - 1, m_rhs_idx - 1); *A = *A * Ui; //Compute loop limits for auxiliary iteration space. m_a->inner(C, 0, m_rhs_idx, m_a->get_row_size() - 1, m_a->get_col_size() - 1); A->grow_col(C, 0, C.get_col_size() -1); Lineq lineq(A, m_rhs_idx); RMat * newb = aux_limits.get_tail(); //Eliminating each variable from inner most loop to outer loop, //except the outer most loop. for (INT i = m_rhs_idx - 1; i > 0; i--) { *newb = *A; RMat res; if (!lineq.fme(i, res, false)) { ASSERT(0, ("system inconsistency!")); } *A = res; newb = aux_limits.get_prev(); } //Record outermost loop bound. *newb = *A; if (A == trA) { //return the transformed iteration space. *A = *aux_limits.get_tail(); } //J = H*K => K = H^(-1)*J //In the sake of H is hnf, H^(-1) also be low triangular, hence, //k1 = hi1*J, k2 = hi2 * J, k3 = hi3 * J, ..., //where hi indicate row of H^(-1), it means that we can replace kp by //H^(-1)[p]*J, the result as following: // A * U^(-1) * K <= C //becomes // K = H^(-1) * J ofst.reinit(1, vars); //Ofst of first var is zero. ofst.set_row(0, (Rational)0); for (UINT i = 1; i < vars; i++) { //Backward subsititutes new index variable for orig index variable. RMat newofst; for (UINT j = 0; j < i; j++) { Rational t2 = H.get(i, j); RMat hirow; Hi.innerRow(hirow, j, j); hirow.mul(t2); if (j == 0) { newofst.grow_row(hirow); } else { //'newofst' always be vector. newofst.addRowToRow(hirow, 0, 0); } } ofst.grow_row(newofst); } is_uni = false; } if (idx_map.size() > 0) { ASSERT0(idx_map.get_col_size() == invt.get_col_size()); idx_map = idx_map * invt; } else { idx_map.copy(invt); } return is_uni; } //Generate loop trans matrix, and return true if success. //Using delta-multiplier. // //'t': loop transforming matrix generated. //'dvec': dependence vector matrix. // //NOTICE: // This function generates transforming matrix in order to // parallel innermost loop of DO loop nest. // ONLY supports distance dependence so far. bool LoopTran::parallelInnerLoops( OUT RMat & t, DVECS const& dvec, UINT dep_level, UINT option) { ASSERT(dep_level < dvec.get_row_size(), ("out of rowsize")); if (!FullyPermute(t, dvec)) { return false; } ASSERT(is_fully_permutable(t * dvec), ("illegal func")); if (is_innermost_loop_parallelizable(t * dvec)) { return true; } //Premultiplication by matrix DELTA to make all of outermost dep //entries(first row) positive, or each of column elements should be zero. //CASE:Given dvec as: // [0, 1, 0] // [0, -2, 0] // [0, 3, 4] //The first dependent vector only has zero entry. if (ONLY_HAVE_FLAG(option, OP_DELTA)) { //Premultipling delta. RMat delta(t.get_row_size(), t.get_col_size()); delta.eye(1); delta.set_row(dep_level, 1); t = delta * t; return true; } else if (ONLY_HAVE_FLAG(option, OP_PERM)) { //Permuation RMat perm(t.get_row_size(), t.get_col_size()); perm.eye(1); INT cand_row = dvec.get_row_size() - 1; //Interchange as many as zero row to inner to obtain maximum inner //loop parallism. for (UINT i = 0; i < dvec.get_row_size(); i++) { if (i >= (UINT)cand_row) { break; } //Find zero row to interchange if (dvec.is_rowequ(i, DD(0))) { perm.interch_row(i, cand_row); cand_row--; } } //Not any of row be interchanged. if (cand_row == (INT)dvec.get_row_size() - 1) { return false; } t = perm * t; return true; } //Attempt to find innermost parallism by applying permuation and //delta transformation. RMat perm(t.get_row_size(), t.get_col_size()); perm.eye(1); //First try to permutate. //Interchange as many as zero row to inner to obtain maximum inner //loop parallism. INT cand_perm_row = dvec.get_row_size() - 1; for (UINT i = 0; i < dvec.get_row_size(); i++) { if (i >= (UINT)cand_perm_row) { break; } //Find zero row to interchange if (dvec.is_rowequ(i, DD(0))) { perm.interch_row(i, cand_perm_row); cand_perm_row--; } } //Not any of row be interchanged. Try DELTA transformation. if (cand_perm_row == (INT)dvec.get_row_size() - 1) { //Build DELTA mulplifier. perm.set_row(dep_level, 1); } t = perm * t; return true; } //Generating transforming matrix to parallel outer loops. //Maximum degree of parallelism of outer loops could be //'dvec.rowsize - rank(dvec)'. // //'t': nonsingular transforming matrix. //'d': dependence matrix, that uses column convention. // Each column represented dependence vector. // //The method generates trans-matrix that reducing the rows of 'd' be zero as //much as possible. // e.g: Given nested loops as: // for L1 // for L2 // for L3 // Pretending dependence matrix d(3*4) whose rank is 1 as follwing: // [a1,b1,c1,d1] //for L1 // [a2,b2,c2,d2] //for L2 // [a3,b3,c3,d3] //for L3 // after transformation, the new depdence matrix could be // [0,0,0,0] //for L1 // [0,0,0,0] //for L2 // [w,x,y,z] //for L3 // This illustates two outer loops L1 and L2 are parallelled. // //NOTICE: // The case that only can be handled is that 'dvec' is singular! // This function also can be used to transform loop nest to gain the // most spacial locality since all dependencies are represented by // inner loops. bool LoopTran::parallelOuterLoops(OUT RMat & t, DVECS const& dvec) { //1. Fully permutability. 'dvec' should be column convention. if (!FullyPermute(t, dvec)) { return false; } DVECS tdvec = t * dvec; ASSERT(is_fully_permutable(tdvec), ("illegal func")); RMat d; if (!tdvec.cvt_to(d)) { return false; } if (d.rank() == d.get_row_size()) { return false; } //2. Computs null space of trans(d) that be row convention. //Each column of 'x' with nonzero elements represents a basis of null //space of 'd'. d.trans(); RMat x; d.null(x); //For test //RMat d2; //d2 = d * x; //Dx=0 // //3. Extracting columns with nonzero elements. RMat tt; for (UINT i = 0; i < x.get_col_size(); i++) { if (!x.is_colequ(i, 0)) { RMat tmp; x.innerColumn(tmp, i, i); tt.grow_row(tmp); } } tt.intlize(); //Scaling rational number to integer. //For test //tt.trans(); //d2 = d * tt; //tt.trans(); // // 4. Completion to make trans-matrix nonsingluar. // 'tt' must be row convention. tt.padding(); //5. Permuting rows with only zero ones to prior. RMat perm; d.trans(); //Transforming 'd' that outer loop deps being zero. RMat trd = tt * d; if (permuteOutZeroRows(perm, trd)) { tt = perm * tt; } t = tt * t; return true; } //Paralleling outer and inner loops as much as possible. //Algorithm to maximize degrees of parallelism. bool LoopTran::parallelMostLoops(OUT RMat & t, DVECS const& dvec) { UINT dep_level = 0; DVECS const * pdvec = &dvec; DVECS tdvec; //'tdvec' for temp use bool res = false; if (parallelOuterLoops(t, dvec)) { res = true; tdvec = t * dvec; pdvec = &tdvec; RMat rd; tdvec.cvt_to(rd); dep_level = dvec.get_row_size() - rd.rank(); } if (res == false) { t.reinit(dvec.get_row_size(), dvec.get_row_size()); t.eye(1); } //Parallel inner nested loop RMat t2; if (parallelInnerLoops(t2, *pdvec, dep_level)) { res = true; } if (res == true) { t = t2 * t; } return res; } //Generating transforming matrix in order to permute zero row out from //inner. // e.g: Given row vector matrix: // [2,0,0] // [0,0,0] // [0,1,1] // t * m will be: // [0,0,0] // [2,0,0] // [0,1,1] //Return true if permutation is necessary, otherwise return false. // //'t': matrix that right by 'm' in order to permute zero dep level from the // inside out. //'m': dependence matrix, that columns indicate depedence vector. bool LoopTran::permuteOutZeroRows(OUT RMat & t, RMat const& m) { BMat zerorow(m.get_row_size(), 1); //column vector bool has_nonzero = false; for (UINT i = 0; i < m.get_row_size(); i++) { if (m.is_rowequ(i, 0)) { zerorow.set(i, 0, true); } else { has_nonzero = true; } } if (!has_nonzero) { //All elements be zero. return false; } t.reinit(m.get_row_size(), m.get_row_size()); t.eye(1); //Bubble sorting like method bool is_swap = false; for (UINT i = 0; i < zerorow.get_row_size() - 1; i++) { bool do_perm = false; if (zerorow.get(i, 0)) { continue; } UINT tmpi = i; //row tmpi has nonzero elements. for (UINT j = i + 1; j < zerorow.get_row_size(); j++) { if (!zerorow.get(j, 0)) { continue; } //Elements of row j all be zero. //Do permtation between tmpi and j. t.interch_row(tmpi, j); zerorow.interch_row(tmpi, j); tmpi = j; do_perm = true; } if (!do_perm) { goto FIN; } is_swap = true; } FIN: return is_swap; } //Generate matrix to perform fully permutable transformation. //Return true if the transforming matrix has found, otherwise return false. // //'dvec': dependence matrix, each column indicates dependence vector, and // each row represents nested loops. //'t': transforming matrix generated. // //NOTICE: // 'dvec' use column convention. bool LoopTran::FullyPermute(OUT RMat & t, DVECS const& dvec) { t.reinit(dvec.get_row_size(), dvec.get_row_size()); if (is_fully_permutable(dvec)) { t.eye(1); return true; } bool first = true; bool change = false; RMat *pt = &t; RMat tmpres; //Accumulating transforming matrix has generated. DVECS const* pdvec = &dvec; DVECS tmpt; AGAIN: pt->eye(1); for (UINT i = 0; i < pdvec->get_row_size(); i++) { for (UINT j = 0; j < pdvec->get_col_size(); j++) { DD dd_inner_loop = pdvec->get(i,j); if (dd_inner_loop.dir == DT_NEG || dd_inner_loop.dir == DT_MISC) { //Cannot handle these case. t.reinit(0,0); return false; } //Attempting work out skewing factor to make 'dd' is positive. //At the present method, we can only handle constant elements. if (dd_inner_loop.dir == DT_DIS && dd_inner_loop.dis < 0) { bool done = false; for (UINT k = 0; k < i; k++) { DD dd_outer_loop = pdvec->get(k,j); //CASE1. Outer loop dependence is constant distance //Computs factor = Ceil(abs(inner's distance) , // outer's distance ), //to make inner distance nonnegative. if (dd_outer_loop.dir == DT_DIS) { ASSERT(dd_outer_loop.dis >= 0, ("miss one negative candidate")); if (dd_outer_loop.dis > 0) { INT factor = xceiling(-dd_inner_loop.dis, dd_outer_loop.dis); pt->set(i, k, MAX(t.getr(i, k), factor)); done = true; break; } else { //dis may be zero! } } //CASE2. Outer loop dependence is positive //direction, assuming that the least distance //is d(d>0), then outer direction is '>=d'. //Although it is not constant distance, the //skewing factor is computed by d. //e.g: [>=1, -2] if (dd_outer_loop.dir == DT_POS && dd_outer_loop.dis > 0) { INT factor = xceiling(-dd_inner_loop.dis, dd_outer_loop.dis); if ((factor * dd_outer_loop.dis + dd_inner_loop.dis) == 0) { //Here we are preferred to generate factor that //make inner loop dependence positive, //scince positive direction may privode an //opportunity of computing nonnegative entry //for succedent negative elements. factor++; } pt->set(i, k, MAX(t.getr(i, k), factor)); done = true; break; } } if (!done) { //Could not find a skewing factor to skew this dependence //to positive or zero. t.reinit(0,0); return false; } change = true; }//end if }//end for }//end for bool neg_dis = false; if (false == change) { goto FIN; } //Generate new temporal Dependent Vectors Matrix. tmpt = *pt * *pdvec; //Checking for the product of T*D if there are new negative distant entries. for (UINT i = 0; i < tmpt.get_row_size(); i++) { for (UINT j = 0; j < tmpt.get_col_size(); j++) { DD dd = tmpt.get(i,j); if (dd.dir == DT_NEG || dd.dir == DT_MISC) { //Cannot handle these case. t.reinit(0,0); return false; } if (dd.dir == DT_DIS && dd.dis < 0) { neg_dis = true; goto OUT_OF_LOOP; } }//end for }//end for OUT_OF_LOOP: if (neg_dis) { // We need do processing iteratively. Method applied: // res = E; // AGAIN: // Computs T from D; // D = T*D; // res = T * res; // if (D has negative dis) // goto AGAIN; // T = res; // return T neg_dis = false; pdvec = &tmpt; if (first) { first = false; tmpres.reinit(dvec.get_row_size(), dvec.get_row_size()); pt = &tmpres; } else { t = *pt * t; } goto AGAIN; } FIN: if (pt != &t) { t = *pt * t; } return true; } //Return true if all elements are greater than or equals 0. //'dvec': dependence matrix, each column indicate dependence vector. bool LoopTran::is_fully_permutable(DVECS const& dvec) { for (UINT i = 0; i < dvec.get_row_size(); i++) { for (UINT j = 0; j < dvec.get_col_size(); j++) { DD dd = dvec.get(i,j); if (!((dd.dir == DT_DIS && dd.dis >= 0) || dd.dir == DT_POS)) { return false; } } } return true; } //Check dependence vectors if innermost loop parallelizable. bool LoopTran::is_innermost_loop_parallelizable(DVECS const& dvec) { for (INT j = 0; j < (INT)dvec.get_col_size(); j++) { DD dd = dvec.get(dvec.get_row_size() - 1,j); if (dd.dir == DT_DIS && dd.dis == 0) { continue; } INT dep_level = dvec.get_row_size() - 1; for (INT i = dvec.get_row_size()- 2; i >= 0; i--) { DD dd2 = dvec.get(i,j); if ((dd2.dir == DT_DIS && dd2.dis > 0) || (dd2.dir == DT_POS && dd2.dis > 0)) { dep_level = i; break; } } if (dep_level == (INT)dvec.get_row_size() - 1) { return false; } } return true; } //Return true if dependence matrix is legal in which elements is //lexicographically positive. //'dvec': dependence matrix, each column indicate dependence vector. bool LoopTran::is_legal(DVECS const& dvec) { for (UINT j = 0; j < dvec.get_col_size(); j++) { for (UINT i = 0; i < dvec.get_row_size(); i++) { DD dd = dvec.get(i,j); if ((dd.dir == DT_DIS && dd.dis < 0) || dd.dir == DT_NEG || dd.dir == DT_MISC) { return false; } if ((dd.dir == DT_DIS && dd.dis > 0) || dd.dir == DT_POS) { break; } } } return true; } //END LoopTran // //START GEN_C // GEN_C::GEN_C(RMat * m, INT rhs_idx) : m_sbuf(128) { m_is_init = false; m_rhs_idx = -1; m_a = NULL; init(m, rhs_idx); } GEN_C::~GEN_C() { destroy(); } void * GEN_C::xmalloc(size_t size) { ASSERT(m_is_init, ("not yet initialized.")); void * p = smpoolMalloc(size,m_pool); ASSERT0(p); memset(p,0,size); return p; } void GEN_C::init(RMat * m, INT rhs_idx) { if (m_is_init) return; m_pool = smpoolCreate(16, MEM_COMM); /// m_cst_sym = NULL; m_var_sym = NULL; m_org_sym = NULL; if (m != NULL) { set_param(m, rhs_idx); } /// m_is_init = true; } void GEN_C::destroy() { if (!m_is_init) return; /// m_a = NULL; m_rhs_idx = -1; m_cst_sym = NULL; m_var_sym = NULL; m_org_sym = NULL; /// smpoolDelete(m_pool); m_pool = NULL; m_is_init = false; } //Set coeff matrix and index of start column of constant term. void GEN_C::set_param(RMat * m, INT rhs_idx) { ASSERT(m && m->get_col_size() > 0, ("coeff mat is empty")); m_a = m; if (rhs_idx == -1) { m_rhs_idx = m->get_col_size() -1; return; } ASSERT(rhs_idx < (INT)m->get_col_size() && rhs_idx >= 1, ("out of bound")); m_rhs_idx = rhs_idx; } //Set customised symbol for symbolic constant-variable and general variable. void GEN_C::set_sym(CHAR ** tgtvar_sym, CHAR ** orgvar_sym, CHAR ** cst_sym) { m_cst_sym = cst_sym; m_var_sym = tgtvar_sym; m_org_sym = orgvar_sym; } //Prints placeholer into buf. void GEN_C::gen_ppl(OUT StrBuf & sbuf, INT num) { for (INT k = 0; k < num; k++) { sbuf.strcat(" "); } } CHAR const* GEN_C::get_orgvar_sym(OUT StrBuf & sbuf, INT varid) { ASSERT(m_is_init, ("not yet initialized")); if (m_org_sym != NULL && m_org_sym[varid] != NULL) { sbuf.sprint("%s", m_org_sym[varid]); } else { sbuf.sprint("%s%d", ORG_VAR_PREFIX, varid); } return sbuf.buf; } CHAR const* GEN_C::get_cst_sym(OUT StrBuf & sbuf, INT cstid) { ASSERT(m_is_init, ("not yet initialized")); if (m_cst_sym != NULL && m_cst_sym[cstid] != NULL) { sbuf.sprint("%s", m_cst_sym[cstid]); } else { sbuf.sprint("%s%d", CST_SYM_PREFIX, cstid); } return sbuf.buf; } CHAR const* GEN_C::get_newvar_sym(OUT StrBuf & sbuf, INT varid) { ASSERT(m_is_init, ("not yet initialized")); if (m_var_sym != NULL && m_var_sym[varid] != NULL) { sbuf.sprint("%s", m_var_sym[varid]); } else { sbuf.sprint("%s%d", TGT_VAR_PREFIX, varid); } return sbuf.buf; } //Generate linear expression //'is_lb': it is true was said that the expression contained in lower bound, // or false is in the upper bound. //'num_sc': the number of symbolic constants //'sym_start_cl': the start column of constant symbol in right hand // side of expression. // Given i < 1 + 2*M + 3*N // First column indicate the unknown 'i', second column indicate // constant value, namely the literal '1'. So the column of constant // symbol start is the third one. void GEN_C::genlinexp( OUT StrBuf & sbuf, IN RMat & coeff_vec, INT ivar, INT comden, bool is_lb, UINT sym_start_cl, UINT num_sc) { UNUSED(comden); ASSERT(m_is_init, ("not yet initialized")); StrBuf tmpbuf(64); //Constant value column bool hasv = false; INT n = coeff_vec.get(0, 1).num(); if (is_lb) { //expression is : -i <= -10 + ..., the output will be //i >= 10 - ... n = -n; } if (n != 0) { sbuf.strcat("%d", n); hasv = true; } else { //Not has any of constant value } //Prints others loop index variable name. for (UINT j = sym_start_cl; j < coeff_vec.get_col_size(); j++) { ASSERT(comden == coeff_vec.get(0, j).den(), ("should be reduced to common denominator at first")); INT coeff = coeff_vec.get(0, j).num(); if (coeff == 0) { continue; } if (is_lb) { //expression is : -i <= -10 + -M + ..., the output will be //i >= 10 + M - ... coeff = -coeff; } //Choose symbol to print CHAR const* sym = NULL; if (num_sc > 0 && j >= sym_start_cl && j < sym_start_cl + num_sc) { //Prints symbolic constant sym = get_cst_sym(tmpbuf, j - sym_start_cl); } else { //Prints symbol of other index variables INT tmpj = j - (sym_start_cl + num_sc); ASSERT0(tmpj < m_rhs_idx); if (tmpj != ivar) { sym = get_newvar_sym(tmpbuf, tmpj); } else { sym = get_newvar_sym(tmpbuf, tmpj + 1); } } // if (hasv) { sbuf.strcat("+"); } if (coeff == 1) { sbuf.strcat("%s", sym); } else if (coeff == -1) { sbuf.strcat("(-%s)", sym); } else { sbuf.strcat("(%d*%s)", coeff, sym); } hasv = true; } //CASE: bound is zero! // e.g: Given upper bound is [1 0 1 -1], variable index is 2, // and there are 3 loop index variable x0,x1,x2, // the upper bound will be x2 <= 0 + x0 - x1 // // If all elements of the row 'ub' be zero, that means // the upper bound is zero. if (!hasv) { sbuf.strcat("0 "); } } void GEN_C::genub(OUT StrBuf & sbuf, IN RMat * limits, INT ub, INT ivar) { ASSERT(m_is_init, ("not yet initialized")); ASSERT(m_a && m_rhs_idx >= 0, ("not yet initialized")); //Given i < 1 + 2*M + 3*N //First column indicate the unknown 'i', second column indicate //constant value, namely the '1'. So the column of constant //symbol start is the third one. UINT sym_start_cl = 2; //The number of symbolic constants UINT sc_count = 0; if (m_rhs_idx != (INT)m_a->get_col_size() - 1) { sc_count = m_a->get_col_size() - m_rhs_idx - 1; } INT comden = limits->get(ub, sym_start_cl).den(); ASSERT(comden > 0, ("denominator must larger than zero")); if (comden != 1) { sbuf.strcat("%s(", TGT_FLOOR); } RMat coeff_vec; limits->innerRow(coeff_vec, ub, ub); genlinexp(sbuf, coeff_vec, ivar, comden, false, sym_start_cl, sc_count); if (comden != 1) { sbuf.strcat(", %d) ", comden); } } //Prints low bound of loop index variable 'ivar'. // //'limits': represent loop limit. //'lb': row index of loop limit, and that row describing low bound. // e.g: // [-1 0] means -x <= 0 //'ivar': variable index. void GEN_C::genlb(OUT StrBuf & sbuf, IN RMat * limits, INT lb, INT ivar) { ASSERT(m_is_init, ("not yet initialized")); ASSERT(m_a && m_rhs_idx >= 0, ("not yet initialized")); //Given i < 1 + 2*M + 3*N //First column indicate the unknown 'i', second column indicate //constant value, namely the '1'. So the column of constant //symbol start is the third one. UINT sym_start_cl = 2; //The number of symbolic constants UINT sc_count = 0; if (m_rhs_idx != (INT)m_a->get_col_size() - 1) { sc_count = m_a->get_col_size() - m_rhs_idx - 1; } INT comden = limits->get(lb, sym_start_cl).den(); ASSERT(comden > 0, ("denominator must larger than zero")); if (comden != 1) { //Generate CEIL operation. Constant value is rational. sbuf.strcat("%s(", TGT_CEIL); } RMat coeff_vec; limits->innerRow(coeff_vec, lb, lb); genlinexp(sbuf, coeff_vec, ivar, comden, true, sym_start_cl, sc_count); if (comden != 1) { sbuf.strcat(", %d) ", comden); } } //Generate for max(a,b) that operation with two operands. void GEN_C::genmin(OUT StrBuf & sbuf, IN RMat * limits, INT ub1, INT ub2, INT ivar) { ASSERT(m_is_init, ("not yet initialized")); sbuf.strcat("min( "); genub(sbuf, limits, ub1, ivar); sbuf.strcat(", "); genub(sbuf, limits, ub2, ivar); sbuf.strcat(" )"); } //Generate for max(a,b) that operation with two operands. void GEN_C::genmax(OUT StrBuf & sbuf, IN RMat * limits, INT lb1, INT lb2, INT ivar) { ASSERT(m_is_init, ("not yet initialized")); sbuf.strcat("max( "); genlb(sbuf, limits, lb1, ivar); sbuf.strcat(", "); genlb(sbuf, limits, lb2, ivar); sbuf.strcat(" )"); } //Generate for max(a,b,c...) that operation with multiple operands. void GEN_C::genmaxs(OUT StrBuf & sbuf, IN RMat * limits, INT lbnum, INT * lb, INT ivar) { ASSERT(m_is_init, ("not yet initialized")); if (lbnum > 2) { StrBuf locbuf(64); genmaxs(locbuf, limits, lbnum-1, lb+1, ivar); sbuf.strcat("max( "); genlb(sbuf, limits, lb[0], ivar); sbuf.strcat(", %s)", locbuf.buf); } else { ASSERT(lbnum == 2, ("at least two elems")); genmax(sbuf, limits, lb[0], lb[1], ivar); } } //Generate for min(a,b,c...) that operation with multiple operands. void GEN_C::genmins(OUT StrBuf & sbuf, IN RMat * limits, INT ubnum, INT * ub, INT ivar) { ASSERT(m_is_init, ("not yet initialized")); if (ubnum > 2) { StrBuf locbuf(64); genmins(locbuf, limits, ubnum-1, ub+1, ivar); sbuf.strcat("min("); genub(sbuf, limits, ub[0], ivar); sbuf.strcat(", %s)", locbuf.buf); } else { ASSERT(ubnum == 2, ("at least two elems")); genmin(sbuf, limits, ub[0], ub[1], ivar); } } //Generate offset of bound bool GEN_C::genofst(OUT StrBuf & sbuf, IN RMat & ofst) { ASSERT(m_is_init, ("not yet initialized")); if (ofst.size() == 0 || ofst.is_rowequ(0, 0)) { return false; } ASSERT(ofst.is_rowvec(), ("should be only one-dimension for each of loop level")); StrBuf tmpbuf(64); //Common low denominator to reduce division //e.g: Given expression is i + (3/2)*j + (1/2)*k, then transformed to // (2*i + 3*j + k) / 2 // //CASE: The method may incur integer overflow exception. //e.g: i is a larger number, and 1/2*i + 1/30*j will be transformed to // (15*i + j)/30, notes that 15*i may cause integer overflow but the // old code is not. ofst.comden(0, 0); INT comden = ofst.get(0,0).den(); ASSERT(comden > 0, ("unnormalized")); if (comden != 1) { sbuf.strcat("("); } bool hasv = false; for (UINT j = 0; j < ofst.get_col_size(); j++) { Rational o = ofst.get(0, j); if (o == 0) { continue; } ASSERT(comden == o.den() && o.den() > 0, ("should be equal")); if (hasv) { sbuf.strcat("+"); } if (o.num() == 1) { sbuf.strcat("%s", get_newvar_sym(tmpbuf, j)); } else if (o.num() == -1) { sbuf.strcat("(-%s)", get_newvar_sym(tmpbuf, j)); } else { sbuf.strcat("(%d*%s)", o.num(), get_newvar_sym(tmpbuf, j)); } hasv = true; } if (comden != 1) { sbuf.strcat(")/%d", comden); } return hasv; } void GEN_C::genidxm(OUT StrBuf & sbuf, IN RMat & idx_map) { ASSERT(m_is_init, ("not yet initialized")); if (idx_map.size() == 0) { return; } StrBuf tmpbuf(64); //Common low denominator to reduce division //e.g: Given expression is i + (3/2)*j + (1/2)*k, then transformed to // (2*i + 3*j + k) / 2 bool allzero = true; for (UINT i = 0; i < idx_map.get_row_size(); i++) { idx_map.comden(i, 0); if (!idx_map.is_rowequ(i, 0)) { allzero = false; } } UNUSED(allzero); ASSERT(!allzero, ("idx mapping is NULL")); //Walk through each of level loop nest for (UINT i = 0; i < idx_map.get_row_size(); i++) { if (idx_map.is_rowequ(i, 0)) { continue; } gen_ppl(sbuf, idx_map.get_row_size()); sbuf.strcat("%s = ", get_orgvar_sym(tmpbuf, i)); INT comden = idx_map.get(i,0).den(); ASSERT(comden > 0, ("unnormalized")); if (comden != 1) { sbuf.strcat("("); } bool hasv = false; for (UINT j = 0; j < idx_map.get_col_size(); j++) { INT num = idx_map.get(i,j).num(); if (num == 0) { continue; } ASSERT(comden == idx_map.get(i,j).den(), ("should be equal")); if (hasv) { sbuf.strcat("+"); } if (num == 1) { sbuf.strcat("%s", get_newvar_sym(tmpbuf, j)); } else if (num == -1) { sbuf.strcat("(-%s)", get_newvar_sym(tmpbuf, j)); } else { sbuf.strcat("(%d*%s)", num, get_newvar_sym(tmpbuf, j)); } hasv = true; } //for each of column if (comden != 1) { sbuf.strcat(")/%d", comden); } sbuf.strcat(";\n"); } } //Generate low bound void GEN_C::gen_loop_start( OUT StrBuf & sbuf, INT stride, IN RMat * limits, IN RMat & ofst, INT mul, INT ivar, INT * lb, INT lbnum) { UNUSED(stride); //Generate ofst of low bound if (genofst(sbuf, ofst) != false) { sbuf.strcat(" + "); } //Generate multiple of low bound of aux-limit if (mul != 1) { ASSERT(mul > 0, ("illegal mul")); sbuf.strcat("%d*(", mul); } if (lbnum > 1) { //low bound need max operations genmaxs(sbuf, limits, lbnum, lb, ivar); } else { genlb(sbuf, limits, lb[0], ivar); } if (mul != 1) { sbuf.strcat(")"); } } //Generate uppper bound void GEN_C::gen_loop_end( OUT StrBuf & sbuf, INT stride, IN RMat * limits, IN RMat & ofst, INT mul, INT ivar, INT * ub, INT ubnum) { UNUSED(stride); StrBuf tmpbuf(64); sbuf.strcat("; %s <= ", get_newvar_sym(tmpbuf, ivar)); //Generate ofst of upper bound if (genofst(sbuf, ofst) != false) { sbuf.strcat(" + "); } //Generate multiple of upper bound of aux-limit if (mul != 1) { sbuf.strcat("%d*(", mul); } if (ubnum > 1) { //upper bound need min operations genmins(sbuf, limits, ubnum, ub, ivar); } else { genub(sbuf, limits, ub[0], ivar); } if (mul != 1) { sbuf.strcat(")"); } } //Generate loop step void GEN_C::gen_loop_step( OUT StrBuf & sbuf, INT stride, IN RMat * limits, IN RMat & ofst, INT mul, INT ivar) { UNUSED(mul); UNUSED(ofst); UNUSED(limits); StrBuf tmpbuf(64); ASSERT(stride >= 1, ("illegal stride")); if (stride == 1) { sbuf.strcat("; %s++", get_newvar_sym(tmpbuf, ivar)); } else { sbuf.strcat("; %s+=%d", get_newvar_sym(tmpbuf, ivar), stride); } sbuf.strcat(")"); } //Generate loop limit of target iteration space. void GEN_C::genlimit(OUT StrBuf & sbuf, INT stride, IN RMat * limits, IN RMat & ofst, INT mul, INT ivar) { ASSERT(m_is_init, ("not yet initialized")); StrBuf var(64); get_newvar_sym(var, ivar); sbuf.strcat("for (%s = ", var.buf); //start of loop INT lb[256], lbnum = 0; INT ub[256], ubnum = 0; //Record number of inequations of low and upper bound. for (UINT i = 0; i < limits->get_row_size(); i++) { if (limits->get(i, 0) == 1) { ub[ubnum++] = i; } else { ASSERT(limits->get(i, 0) == -1, ("unmatch info")); lb[lbnum++] = i; } } gen_loop_start(sbuf, stride, limits, ofst, mul, ivar, lb, lbnum); gen_loop_end(sbuf, stride, limits, ofst, mul, ivar, ub, ubnum); gen_loop_step(sbuf, stride, limits, ofst, mul, ivar); } //Prints out C codes. //'stride','idx_map','limits',ofst','mul' see details in manual of // transformIterSpace(). //'name': file name to dump. //'is_del': creates new dump file void GEN_C::genlimits(IN List<RMat*> & limits, IN RMat * pstride, IN RMat * pidx_map, IN RMat * pofst, IN RMat * pmul, IN CHAR * name, bool is_del) { ASSERT(m_is_init, ("not yet initialized")); ASSERT(limits.get_elem_count() > 0, ("unmatch coeff matrix info")); static UINT g_count = 0; StrBuf tmpbuf(64); UINT const varnum = limits.get_elem_count(); RMat stride, idx_map, ofst, mul; if (pstride != NULL) { stride = *pstride; } else { stride.reinit(1, varnum); stride.set_all(1); } if (pidx_map != NULL) { idx_map = *pidx_map; } if (pofst != NULL) { ofst = *pofst; } if (pmul != NULL) { mul = *pmul; } if (mul.size() != 0) { ASSERT(ofst.is_quad() && idx_map.is_quad(), ("ofst and idx_map must be square")); ASSERT(varnum == mul.get_col_size() && varnum == ofst.get_row_size() && varnum == stride.get_col_size() && varnum == idx_map.get_col_size(), ("unmatch matrix info")); } //Open a dump file for trace purpose if (name == NULL) { name = TGT_LP; } if (is_del) { unlink(name); } FILE * h = fopen(name, "a+"); ASSERT(h, ("%s create failed!!!", name)); fprintf(h, "\nTarget loop nest id:%u\n", g_count++); //Print new loop index initializing code. //That may be dispensible during code generation of compiler //intermedia language. m_sbuf.sprint("int "); for (UINT u = 0; u < varnum; u++) { m_sbuf.strcat("%s", get_newvar_sym(tmpbuf, u)); if (u != varnum - 1) { m_sbuf.strcat(", "); } } fprintf(h, "%s;\n", m_sbuf.buf); //Generate loop bound from outer most to inner loop. Lineq lineq(NULL); INT ivar = 0; C<RMat*> * ct; for (limits.get_head(&ct); ct != limits.end(); ct = limits.get_next(ct), ivar++) { RMat * ineq = ct->val(); ASSERT0(ineq); if (ineq->size() == 0) { continue; } RMat o; m_sbuf.clean(); gen_ppl(m_sbuf, ivar); lineq.set_param(ineq, m_rhs_idx); //Format form of code such that it observe to engine require //e.g original bound is i + j < 100, transformed to i < 100 + (-j) RMat formed; lineq.formatBound(ivar, formed); //The condition is not meet if there is not ivar in ineqalities. if (formed.size() > 0) { if (ofst.size() != 0) { //What one needs to pay attention is that 'mul' may not be one //iff 'ofst' is zero. ofst.innerRow(o, ivar, ivar); ASSERT(stride.get(0, ivar).den() == 1 && mul.get(0, ivar).den() == 1, ("stride and mul is rational")); genlimit(m_sbuf, stride.get(0, ivar).num(), &formed, o, mul.get(0, ivar).num(), ivar); } else { genlimit(m_sbuf, stride.get(0, ivar).num(), &formed, o, 1, ivar); } fprintf(h, "%s\n", m_sbuf.buf); } } //Generate index mapping from new loop index to original ones. m_sbuf.clean(); genidxm(m_sbuf, idx_map); fprintf(h, "%s\n", m_sbuf.buf); fprintf(h, "\n"); fclose(h); } //END GEN_C
29.699936
81
0.527218
[ "vector", "model", "transform" ]
c0d7abd35f09f032d0a92c70b49d9f8a0b1a71c3
13,794
cpp
C++
OpenTESArena/src/Assets/MIFFile.cpp
faha223/OpenTESArena
ae8f704bd4d10a478aef890b26903bee1f5dd01f
[ "MIT" ]
null
null
null
OpenTESArena/src/Assets/MIFFile.cpp
faha223/OpenTESArena
ae8f704bd4d10a478aef890b26903bee1f5dd01f
[ "MIT" ]
null
null
null
OpenTESArena/src/Assets/MIFFile.cpp
faha223/OpenTESArena
ae8f704bd4d10a478aef890b26903bee1f5dd01f
[ "MIT" ]
null
null
null
#include <algorithm> #include <tuple> #include <unordered_map> #include "Compression.h" #include "MIFFile.h" #include "components/debug/Debug.h" #include "components/utilities/Bytes.h" #include "components/vfs/manager.hpp" namespace { const std::string Tag_FLAT = "FLAT"; const std::string Tag_FLOR = "FLOR"; const std::string Tag_INFO = "INFO"; const std::string Tag_INNS = "INNS"; const std::string Tag_LEVL = "LEVL"; const std::string Tag_LOCK = "LOCK"; const std::string Tag_LOOT = "LOOT"; const std::string Tag_MAP1 = "MAP1"; const std::string Tag_MAP2 = "MAP2"; const std::string Tag_NAME = "NAME"; const std::string Tag_NUMF = "NUMF"; const std::string Tag_STOR = "STOR"; const std::string Tag_TARG = "TARG"; const std::string Tag_TRIG = "TRIG"; // Mappings of .MIF level tags to functions for decoding data, excluding "LEVL". const std::unordered_map<std::string, int(*)(MIFFile::Level&, const uint8_t*)> MIFLevelTags = { { Tag_FLAT, MIFFile::Level::loadFLAT }, { Tag_FLOR, MIFFile::Level::loadFLOR }, { Tag_INFO, MIFFile::Level::loadINFO }, { Tag_INNS, MIFFile::Level::loadINNS }, { Tag_LOCK, MIFFile::Level::loadLOCK }, { Tag_LOOT, MIFFile::Level::loadLOOT }, { Tag_MAP1, MIFFile::Level::loadMAP1 }, { Tag_MAP2, MIFFile::Level::loadMAP2 }, { Tag_NAME, MIFFile::Level::loadNAME }, { Tag_NUMF, MIFFile::Level::loadNUMF }, { Tag_STOR, MIFFile::Level::loadSTOR }, { Tag_TARG, MIFFile::Level::loadTARG }, { Tag_TRIG, MIFFile::Level::loadTRIG } }; // City block generation data, used by city generation. The order of data is tightly coupled // with the original generation algorithm. const std::array<std::string, 7> CityBlockCodes = { "EQ", "MG", "NB", "TP", "TV", "TS", "BS" }; const std::array<int, 7> CityBlockVariations = { 13, 11, 10, 12, 15, 11, 20 }; const std::array<std::string, 4> CityBlockRotations = { "A", "B", "C", "D" }; } MIFFile::Level::Level() { this->numf = 0; } const uint8_t MIFFile::DRY_CHASM = 0xC; const uint8_t MIFFile::WET_CHASM = 0xD; const uint8_t MIFFile::LAVA_CHASM = 0xE; bool MIFFile::init(const char *filename) { Buffer<std::byte> src; if (!VFS::Manager::get().read(filename, &src)) { DebugLogError("Could not read \"" + std::string(filename) + "\"."); return false; } const uint8_t *srcPtr = reinterpret_cast<const uint8_t*>(src.get()); const uint16_t headerSize = Bytes::getLE16(srcPtr + 4); // Get data from the header (after "MHDR"). Constant for all levels. The header // size should be 61. ArenaTypes::MIFHeader mifHeader; mifHeader.init(srcPtr + 6); // Load start locations from the header. Not all are set (i.e., some are (0, 0)). for (size_t i = 0; i < this->startPoints.size(); i++) { static_assert(std::tuple_size<decltype(mifHeader.startX)>::value == std::tuple_size<decltype(this->startPoints)>::value); static_assert(std::tuple_size<decltype(mifHeader.startY)>::value == std::tuple_size<decltype(this->startPoints)>::value); const uint16_t mifX = mifHeader.startX[i]; const uint16_t mifY = mifHeader.startY[i]; // Convert the coordinates from .MIF format to voxel format. The remainder // of the division is used for positioning within the voxel. const double x = static_cast<double>(mifX) / MIFFile::ARENA_UNITS; const double y = static_cast<double>(mifY) / MIFFile::ARENA_UNITS; this->startPoints[i] = Double2(x, y); } // Start of the level data (at each "LEVL"). Some .MIF files have multiple levels, // so this needs to be in a loop. int levelOffset = headerSize + 6; // The level count is unused since it's inferred by this level loading loop. while (levelOffset < src.getCount()) { MIFFile::Level level; // Begin loading the level data at the current LEVL, and get the offset // to the next LEVL. const uint8_t *levelStart = srcPtr + levelOffset; levelOffset += level.load(levelStart); // Add to list of levels. this->levels.push_back(std::move(level)); } this->width = mifHeader.mapWidth; this->depth = mifHeader.mapHeight; this->startingLevelIndex = mifHeader.startingLevelIndex; this->name = filename; return true; } std::string MIFFile::mainQuestDungeonFilename(int dungeonX, int dungeonY, int provinceID) { uint32_t mifID = (dungeonY << 16) + dungeonX + provinceID; mifID = static_cast<uint32_t>(-static_cast<int32_t>(Bytes::rol(mifID, 5))); const std::string mifName = std::to_string(mifID) + ".MIF"; return mifName; } int MIFFile::getCityBlockCodeCount() { return static_cast<int>(CityBlockCodes.size()); } int MIFFile::getCityBlockVariationsCount() { return static_cast<int>(CityBlockVariations.size()); } int MIFFile::getCityBlockRotationCount() { return static_cast<int>(CityBlockRotations.size()); } const std::string &MIFFile::getCityBlockCode(int index) { DebugAssertIndex(CityBlockCodes, index); return CityBlockCodes[index]; } int MIFFile::getCityBlockVariations(int index) { DebugAssertIndex(CityBlockVariations, index); return CityBlockVariations[index]; } const std::string &MIFFile::getCityBlockRotation(int index) { DebugAssertIndex(CityBlockRotations, index); return CityBlockRotations[index]; } std::string MIFFile::makeCityBlockMifName(const std::string &code, int variation, const std::string &rotation) { return code + "BD" + std::to_string(variation) + rotation + ".MIF"; } int MIFFile::getWidth() const { return this->width; } int MIFFile::getHeight(int levelIndex) const { return this->levels.at(levelIndex).getHeight(); } int MIFFile::getDepth() const { return this->depth; } int MIFFile::getStartingLevelIndex() const { return this->startingLevelIndex; } const std::string &MIFFile::getName() const { return this->name; } const std::array<Double2, 4> &MIFFile::getStartPoints() const { return this->startPoints; } const std::vector<MIFFile::Level> &MIFFile::getLevels() const { return this->levels; } int MIFFile::Level::load(const uint8_t *levelStart) { // Get the size of the level data. const uint16_t levelSize = Bytes::getLE16(levelStart + 4); // Move the tag pointer while there are tags to read in the current level. const uint8_t *tagStart = levelStart + 6; const uint8_t *levelEnd = tagStart + levelSize; while (tagStart < levelEnd) { // Check what the four letter tag is (FLOR, MAP1, etc., never LEVL). const std::string tag(tagStart, tagStart + 4); // Find the function associated with the tag. const auto tagIter = MIFLevelTags.find(tag); if (tagIter != MIFLevelTags.end()) { // Load the data and move the offset to the beginning of the next tag. auto *loadingFn = tagIter->second; tagStart += loadingFn(*this, tagStart); } else { // This can only be reached if the .MIF file is corrupted. DebugCrash("Unrecognized .MIF tag \"" + tag + "\"."); } } // Use the updated tag start instead of the level end due to a bug with the LEVL // size in WILD.MIF (six bytes short of where it should be, probably due to FLAT // tag and size not being accounted for, causing this loader to incorrectly start // a second level six bytes from the end of the file). return static_cast<int>(std::distance(levelStart, tagStart)); } int MIFFile::Level::getHeight() const { // If there is MAP2 data, then check through each voxel to find the highest point. if (this->map2.size() > 0) { // @todo: look at MAP2 voxels and determine highest column. return 6; } else { // Use the default height -- ground, main floor, and ceiling. return 3; } } int MIFFile::Level::loadFLAT(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); const uint8_t *tagDataStart = tagStart + 6; // Currently unknown. level.flat = std::vector<uint8_t>(size); std::copy(tagDataStart, tagDataStart + level.flat.size(), level.flat.begin()); return size + 6; } int MIFFile::Level::loadFLOR(MIFFile::Level &level, const uint8_t *tagStart) { // Compressed size is in chunks and contains a 2 byte decompressed length after it, which // should not be included when determining the end of the compressed range. const uint16_t compressedSize = Bytes::getLE16(tagStart + 4); const uint16_t uncompressedSize = Bytes::getLE16(tagStart + 6); // Allocate space for this floor, using 2 bytes per voxel. std::vector<uint8_t> decomp(uncompressedSize, 0); // Decode the data with type 8 decompression. const uint8_t *tagDataStart = tagStart + 8; const uint8_t *tagDataEnd = tagStart + 6 + compressedSize; Compression::decodeType08(tagDataStart, tagDataEnd, decomp); // Write into 16-bit vector (in little-endian). level.flor.resize(decomp.size() / 2); std::copy(decomp.begin(), decomp.end(), reinterpret_cast<uint8_t*>(level.flor.data())); return compressedSize + 6; } int MIFFile::Level::loadINFO(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); const uint8_t *tagDataStart = tagStart + 6; // Using the size might include some unnecessary empty space, so assume it's // null-terminated instead. level.info = std::string(reinterpret_cast<const char*>(tagDataStart)); return size + 6; } int MIFFile::Level::loadINNS(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); const uint8_t *tagDataStart = tagStart + 6; // Currently unknown. level.inns = std::vector<uint8_t>(size); std::copy(tagDataStart, tagDataStart + level.inns.size(), level.inns.begin()); return size + 6; } int MIFFile::Level::loadLOCK(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); // Each lock record is 3 bytes. const int lockCount = size / 3; level.lock = std::vector<ArenaTypes::MIFLock>(lockCount); const uint8_t *tagDataStart = tagStart + 6; for (int i = 0; i < lockCount; i++) { const int offset = i * 3; ArenaTypes::MIFLock &lock = level.lock.at(i); lock.init(tagDataStart + offset); } return size + 6; } int MIFFile::Level::loadLOOT(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); const uint8_t *tagDataStart = tagStart + 6; // Currently unknown. level.loot = std::vector<uint8_t>(size); std::copy(tagDataStart, tagDataStart + level.loot.size(), level.loot.begin()); return size + 6; } int MIFFile::Level::loadMAP1(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t compressedSize = Bytes::getLE16(tagStart + 4); const uint16_t uncompressedSize = Bytes::getLE16(tagStart + 6); // Allocate space for this floor, using 2 bytes per voxel. std::vector<uint8_t> decomp(uncompressedSize, 0); // Decode the data with type 8 decompression. const uint8_t *tagDataStart = tagStart + 8; const uint8_t *tagDataEnd = tagStart + 6 + compressedSize; Compression::decodeType08(tagDataStart, tagDataEnd, decomp); // Write into 16-bit vector (in little-endian). level.map1.resize(decomp.size() / 2); std::copy(decomp.begin(), decomp.end(), reinterpret_cast<uint8_t*>(level.map1.data())); return compressedSize + 6; } int MIFFile::Level::loadMAP2(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t compressedSize = Bytes::getLE16(tagStart + 4); const uint16_t uncompressedSize = Bytes::getLE16(tagStart + 6); // Allocate space for this floor, using 2 bytes per voxel. std::vector<uint8_t> decomp(uncompressedSize, 0); // Decode the data with type 8 decompression. const uint8_t *tagDataStart = tagStart + 8; const uint8_t *tagDataEnd = tagStart + 6 + compressedSize; Compression::decodeType08(tagDataStart, tagDataEnd, decomp); // Write into 16-bit vector (in little-endian). level.map2.resize(decomp.size() / 2); std::copy(decomp.begin(), decomp.end(), reinterpret_cast<uint8_t*>(level.map2.data())); return compressedSize + 6; } int MIFFile::Level::loadNAME(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); const uint8_t *tagDataStart = tagStart + 6; // Using the size might include some unnecessary empty space, so assume it's // null-terminated instead. level.name = std::string(reinterpret_cast<const char*>(tagDataStart)); return size + 6; } int MIFFile::Level::loadNUMF(MIFFile::Level &level, const uint8_t *tagStart) { // Size should always be 1. const uint16_t size = Bytes::getLE16(tagStart + 4); const uint8_t *tagDataStart = tagStart + 6; // Just one byte. level.numf = *tagDataStart; return size + 6; } int MIFFile::Level::loadSTOR(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); const uint8_t *tagDataStart = tagStart + 6; // Currently unknown. Only present in the demo? level.stor = std::vector<uint8_t>(size); std::copy(tagDataStart, tagDataStart + level.stor.size(), level.stor.begin()); return size + 6; } int MIFFile::Level::loadTARG(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); // Each target record is 2 bytes. const int targetCount = size / 2; level.targ = std::vector<ArenaTypes::MIFTarget>(targetCount); const uint8_t *tagDataStart = tagStart + 6; for (int i = 0; i < targetCount; i++) { const int offset = i * 2; ArenaTypes::MIFTarget &target = level.targ.at(i); target.init(tagDataStart + offset); } return size + 6; } int MIFFile::Level::loadTRIG(MIFFile::Level &level, const uint8_t *tagStart) { const uint16_t size = Bytes::getLE16(tagStart + 4); // Each trigger record is 4 bytes. const int triggerCount = size / 4; level.trig = std::vector<ArenaTypes::MIFTrigger>(triggerCount); const uint8_t *tagDataStart = tagStart + 6; for (int i = 0; i < triggerCount; i++) { const int offset = i * 4; ArenaTypes::MIFTrigger &trigger = level.trig.at(i); trigger.init(tagDataStart + offset); } return size + 6; }
29.986957
110
0.710889
[ "vector" ]
c0d81ac0d8559d4a8b5b429ea31a1cfb356bddd2
263
cpp
C++
Sandbox/src/Game/Items/Item.cpp
Benner727/SquareRPG
9333ff8417cf1bb74e215ab671554b9708551b64
[ "Apache-2.0" ]
null
null
null
Sandbox/src/Game/Items/Item.cpp
Benner727/SquareRPG
9333ff8417cf1bb74e215ab671554b9708551b64
[ "Apache-2.0" ]
2
2020-05-15T22:20:54.000Z
2020-05-24T06:49:52.000Z
Sandbox/src/Game/Items/Item.cpp
Benner727/SquareRPG
9333ff8417cf1bb74e215ab671554b9708551b64
[ "Apache-2.0" ]
null
null
null
#include "Game/Items/Item.h" Item::Item(int index, int amount) { mIndex = index; mAmount = amount; mSprite = nullptr; mItemDefinition = nullptr; } Item::~Item() { delete mSprite; } void Item::Render(bool ignoreCamera) { mSprite->Render(ignoreCamera); }
12.52381
36
0.692015
[ "render" ]
c0dba174f4b9e87769e19e3b446d2f9f4e661597
8,508
cpp
C++
experimental/graphite/src/UploadTask.cpp
twinsunllc/skia
8318cc9928ef12577f249f49250dd94ee2bc1d28
[ "BSD-3-Clause" ]
null
null
null
experimental/graphite/src/UploadTask.cpp
twinsunllc/skia
8318cc9928ef12577f249f49250dd94ee2bc1d28
[ "BSD-3-Clause" ]
null
null
null
experimental/graphite/src/UploadTask.cpp
twinsunllc/skia
8318cc9928ef12577f249f49250dd94ee2bc1d28
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2022 Google LLC * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "experimental/graphite/src/UploadTask.h" #include "experimental/graphite/include/Recorder.h" #include "experimental/graphite/src/Buffer.h" #include "experimental/graphite/src/Caps.h" #include "experimental/graphite/src/CommandBuffer.h" #include "experimental/graphite/src/Log.h" #include "experimental/graphite/src/RecorderPriv.h" #include "experimental/graphite/src/ResourceProvider.h" #include "experimental/graphite/src/Texture.h" #include "experimental/graphite/src/TextureProxy.h" #include "src/core/SkConvertPixels.h" #include "src/core/SkTraceEvent.h" namespace skgpu { UploadInstance::UploadInstance(sk_sp<Buffer> buffer, sk_sp<TextureProxy> textureProxy, std::vector<BufferTextureCopyData> copyData) : fBuffer(buffer) , fTextureProxy(textureProxy) , fCopyData(copyData) {} size_t compute_combined_buffer_size(int mipLevelCount, size_t bytesPerPixel, size_t minTransferBufferAlignment, const SkISize& baseDimensions, SkTArray<size_t>* individualMipOffsets) { SkASSERT(individualMipOffsets && !individualMipOffsets->count()); SkASSERT(mipLevelCount >= 1); individualMipOffsets->push_back(0); size_t combinedBufferSize = baseDimensions.width() * bytesPerPixel * baseDimensions.height(); SkISize levelDimensions = baseDimensions; for (int currentMipLevel = 1; currentMipLevel < mipLevelCount; ++currentMipLevel) { levelDimensions = {std::max(1, levelDimensions.width() /2), std::max(1, levelDimensions.height()/2)}; size_t trimmedSize = levelDimensions.area() * bytesPerPixel; combinedBufferSize = SkAlignTo(combinedBufferSize, minTransferBufferAlignment); SkASSERT((0 == combinedBufferSize % 4) && (0 == combinedBufferSize % bytesPerPixel)); individualMipOffsets->push_back(combinedBufferSize); combinedBufferSize += trimmedSize; } SkASSERT(individualMipOffsets->count() == mipLevelCount); return combinedBufferSize; } UploadInstance UploadInstance::Make(Recorder* recorder, sk_sp<TextureProxy> textureProxy, SkColorType dataColorType, const std::vector<MipLevel>& levels, const SkIRect& dstRect) { const Caps* caps = recorder->priv().caps(); SkASSERT(caps->isTexturable(textureProxy->textureInfo())); unsigned int mipLevelCount = levels.size(); // The assumption is either that we have no mipmaps, or that our rect is the entire texture SkASSERT(mipLevelCount == 1 || dstRect == SkIRect::MakeSize(textureProxy->dimensions())); // We assume that if the texture has mip levels, we either upload to all the levels or just the // first. SkASSERT(mipLevelCount == 1 || mipLevelCount == textureProxy->textureInfo().numMipLevels()); if (dstRect.isEmpty()) { return {}; } SkASSERT(caps->areColorTypeAndTextureInfoCompatible(dataColorType, textureProxy->textureInfo())); if (mipLevelCount == 1 && !levels[0].fPixels) { return {}; // no data to upload } for (unsigned int i = 0; i < mipLevelCount; ++i) { // We do not allow any gaps in the mip data if (!levels[i].fPixels) { return {}; } } size_t bpp = SkColorTypeBytesPerPixel(dataColorType); size_t minAlignment = caps->getTransferBufferAlignment(bpp); SkTArray<size_t> individualMipOffsets(mipLevelCount); size_t combinedBufferSize = compute_combined_buffer_size(mipLevelCount, bpp, minAlignment, dstRect.size(), &individualMipOffsets); SkASSERT(combinedBufferSize); // TODO: get staging buffer or {void* offset, sk_sp<Buffer> buffer} pair. ResourceProvider* resourceProvider = recorder->priv().resourceProvider(); sk_sp<Buffer> buffer = resourceProvider->findOrCreateBuffer(combinedBufferSize, BufferType::kXferCpuToGpu, PrioritizeGpuReads::kNo); std::vector<BufferTextureCopyData> copyData(mipLevelCount); if (!buffer) { return {}; } char* bufferData = (char*) buffer->map(); // TODO: get from staging buffer instead size_t baseOffset = 0; int currentWidth = dstRect.width(); int currentHeight = dstRect.height(); for (unsigned int currentMipLevel = 0; currentMipLevel < mipLevelCount; currentMipLevel++) { const size_t trimRowBytes = currentWidth * bpp; const size_t rowBytes = levels[currentMipLevel].fRowBytes; // copy data into the buffer, skipping any trailing bytes char* dst = bufferData + individualMipOffsets[currentMipLevel]; const char* src = (const char*)levels[currentMipLevel].fPixels; SkRectMemcpy(dst, trimRowBytes, src, rowBytes, trimRowBytes, currentHeight); copyData[currentMipLevel].fBufferOffset = baseOffset + individualMipOffsets[currentMipLevel]; copyData[currentMipLevel].fBufferRowBytes = trimRowBytes; copyData[currentMipLevel].fRect = { dstRect.left(), dstRect.top(), // TODO: can we recompute this for mips? dstRect.left() + currentWidth, dstRect.top() + currentHeight }; copyData[currentMipLevel].fMipLevel = currentMipLevel; currentWidth = std::max(1, currentWidth/2); currentHeight = std::max(1, currentHeight/2); } buffer->unmap(); ATRACE_ANDROID_FRAMEWORK("Upload %sTexture [%ux%u]", mipLevelCount > 1 ? "MipMap " : "", dstRect.width(), dstRect.height()); return {std::move(buffer), std::move(textureProxy), std::move(copyData)}; } void UploadInstance::addCommand(ResourceProvider* resourceProvider, CommandBuffer* commandBuffer) const { if (!fTextureProxy) { SKGPU_LOG_E("No texture proxy specified for UploadTask"); return; } if (!fTextureProxy->instantiate(resourceProvider)) { SKGPU_LOG_E("Could not instantiate texture proxy for UploadTask!"); return; } commandBuffer->copyBufferToTexture(std::move(fBuffer), fTextureProxy->refTexture(), fCopyData.data(), fCopyData.size()); } //--------------------------------------------------------------------------- bool UploadList::appendUpload(Recorder* recorder, sk_sp<TextureProxy> textureProxy, SkColorType dataColorType, const std::vector<MipLevel>& levels, const SkIRect& dstRect) { UploadInstance instance = UploadInstance::Make(recorder, textureProxy, dataColorType, levels, dstRect); if (!instance.isValid()) { return false; } fInstances.push_back(instance); return true; } //--------------------------------------------------------------------------- sk_sp<UploadTask> UploadTask::Make(UploadList* uploadList) { SkASSERT(uploadList && uploadList->fInstances.size() > 0); return sk_sp<UploadTask>(new UploadTask(std::move(uploadList->fInstances))); } sk_sp<UploadTask> UploadTask::Make(const UploadInstance& instance) { if (!instance.isValid()) { return nullptr; } return sk_sp<UploadTask>(new UploadTask(instance)); } UploadTask::UploadTask(std::vector<UploadInstance> instances) : fInstances(std::move(instances)) {} UploadTask::UploadTask(const UploadInstance& instance) { fInstances.push_back(instance); } UploadTask::~UploadTask() {} void UploadTask::addCommands(ResourceProvider* resourceProvider, CommandBuffer* commandBuffer) { for (unsigned int i = 0; i < fInstances.size(); ++i) { fInstances[i].addCommand(resourceProvider, commandBuffer); } } } // namespace skgpu
40.132075
100
0.615656
[ "vector" ]
c0df11cf6a1f998de673d8ca298b1c97eff0232d
1,538
cpp
C++
leetcode/15.3sum/15.3Sum_henrytine.cpp
henrytien/AlgorithmSolutions
62339269f4fa698ddd2e73458caef875af05af8f
[ "MIT" ]
15
2020-06-27T03:28:39.000Z
2021-08-13T10:42:24.000Z
leetcode/15.3sum/15.3Sum_henrytine.cpp
henrytien/AlgorithmSolutions
62339269f4fa698ddd2e73458caef875af05af8f
[ "MIT" ]
40
2020-06-27T03:29:53.000Z
2020-11-05T12:29:49.000Z
leetcode/15.3sum/15.3Sum_henrytine.cpp
henrytien/AlgorithmSolutions
62339269f4fa698ddd2e73458caef875af05af8f
[ "MIT" ]
22
2020-07-16T03:23:43.000Z
2022-02-19T16:00:55.000Z
// Source : https://leetcode.com/problems/3sum/ // Author : henrytine // Date : 2020-08-17 /***************************************************************************************************** * * Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find * all unique triplets in the array which gives the sum of zero. * * Note: * * The solution set must not contain duplicate triplets. * * Example: * * Given array nums = [-1, 0, 1, 2, -1, -4], * * A solution set is: * [ * [-1, 0, 1], * [-1, -1, 2] * ] * ******************************************************************************************************/ class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { sort(nums.begin(),nums.end()); vector<vector<int>> res; for (int i = 0; i < nums.size() && nums[i] <= 0; ++i) { if (i == 0 || nums[i - 1] != nums[i]) { twoSum(nums, i, res); } } return res; } void twoSum(vector<int>& nums, int i, vector<vector<int>> &res) { unordered_set<int> seen; for (int j = i + 1; j < nums.size(); ++j) { int complement = -nums[i] - nums[j]; if (seen.count (complement)) { res.push_back({nums[i], complement, nums[j]}); while (j + 1 < nums.size() && nums[j] == nums[j+1]) { ++j; } } seen.insert(nums[j]); } } };
29.576923
104
0.410273
[ "vector" ]
c0e019bd44d52c9a13bfa1e16210ac3fbc33b3d8
1,733
cpp
C++
src/removeshard.cpp
vaelen/mongo-utils
5c710e62bb878f47f9cf7e1ab54236414f637ba0
[ "Apache-2.0" ]
null
null
null
src/removeshard.cpp
vaelen/mongo-utils
5c710e62bb878f47f9cf7e1ab54236414f637ba0
[ "Apache-2.0" ]
null
null
null
src/removeshard.cpp
vaelen/mongo-utils
5c710e62bb878f47f9cf7e1ab54236414f637ba0
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016 Andrew Young <andrew@vaelen.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include <iostream> #include "Client.hpp" using namespace std; using namespace MongoUtils; int main(int argc, char** argv) { string uri_string = "mongodb://localhost"; if (argc > 1) { uri_string = argv[1]; } try { Client client{uri_string}; client.connect(); vector<Shard> shards = client.shards(); if(shards.empty()) { cout << "No Shards" << endl; } else { string shard_name = ""; bool found_shard = false; for(Shard shard : shards) { cout << "Shard: " << shard.name << "\tHost: " << shard.host << "\tDraining: " << (shard.is_draining ? "Yes" : "No") << endl; if(!found_shard && shard.is_draining) { cout << "\tFound Draining Shard" << endl; shard_name = shard.name; found_shard = true; } } if(!found_shard) { // TODO: Remove this debug line later shard_name = shards[0].name; cout << "No Draining Shards. Removing Shard " << shard_name << endl; } client.remove_shard(shard_name); } } catch (const exception &ex) { cout << "Exception: " << ex.what() << endl; } }
30.946429
132
0.631852
[ "vector" ]
c0e66bce57f889a267f2c207b52440a4c144b071
1,491
cpp
C++
src/Math.cpp
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
src/Math.cpp
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
src/Math.cpp
Tastyep/cpp-rt
c274e86a2fe158746c6a9381c73cf55344823f4e
[ "MIT" ]
null
null
null
#include "Math.hh" #include <cmath> #include <iostream> double Math::getPositiveMin(const auto &array) const { bool set = false; double smallest; for (const auto &elem : array) { if (elem > Math::zero && (set == false || elem < smallest)) { set = true; smallest = elem; } } return smallest; } double Math::solveSecond(const Vector &coefs, std::array<double, 2> solutions) const { double delta; double sqrtDelta; delta = coefs.y * coefs.y - (4.0 * coefs.x * coefs.z); if (delta < 0) return -1; if (coefs.x == 0) return -1; if (delta == 0) return (-coefs.y / (2.0 * coefs.x)); sqrtDelta = std::sqrt(delta); solutions[0] = (-coefs.y + sqrtDelta) / (2.0 * coefs.x); solutions[1] = (-coefs.y - sqrtDelta) / (2.0 * coefs.x); return getPositiveMin(solutions); } Vector Math::calcReflectedVector(const Vector &ray, const Vector &normal) const { double cosAngle; Vector copyRay = ray; copyRay.makeUnit(); cosAngle = copyRay.dot(normal); return (copyRay - 2.0 * cosAngle * normal); } Vector Math::calcNormalVector(Position pos, std::shared_ptr<SceneObj> obj, Vector rayVec, double k, Position &impact) const { const Position &objPos = obj->getPosition(); Vector normal; impact.x = pos.x + k * rayVec.x; impact.y = pos.y + k * rayVec.y; impact.z = pos.z + k * rayVec.z; obj->calcNormal(normal, impact); return normal; }
26.157895
80
0.600939
[ "vector" ]
c0ea1c0a69e7580a2d8eb62843400a15bf5af129
575
cpp
C++
libs/phoenix/example/generator2.cpp
jmuskaan72/Boost
047e36c01841a8cd6a5c74d4e3034da46e327bc1
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/phoenix/example/generator2.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
4
2015-03-19T08:23:23.000Z
2019-06-24T07:48:47.000Z
libs/phoenix/example/generator2.cpp
xiaoliang2121/Boost
fc90c3fde129c62565c023f091eddc4a7ed9902b
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
#include <boost/phoenix.hpp> #include <boost/typeof/typeof.hpp> #include <iostream> #include <vector> #include <algorithm> int main() { using boost::phoenix::lambda; using boost::phoenix::let; using boost::phoenix::ref; using boost::phoenix::construct; using boost::phoenix::local_names::_a; using boost::phoenix::arg_names::_1; BOOST_AUTO( generator , (lambda ( _a = val(_1) ) [ std::cout << _a << " " , _a++ ]) ); int i = 0; std::vector<int> v(10); std::for_each(v.begin(), v.end(), generator(0)); }
17.424242
50
0.593043
[ "vector" ]
c0ec76523c44667c5e56431b34eb4ab698ff807a
20,416
cpp
C++
vegastrike/src/XMLDocument.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/XMLDocument.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
vegastrike/src/XMLDocument.cpp
Ezeer/VegaStrike_win32FR
75891b9ccbdb95e48e15d3b4a9cd977955b97d1f
[ "MIT" ]
null
null
null
#include "XMLDocument.h" #include <assert.h> #include <fstream> #include <expat.h> #include <algorithm> #define PARSING_BUFFER_SIZE 4096 namespace XMLDOM { /****************************************************************** * * * * * XMLElement implementation * * * * * ******************************************************************/ XMLElement::XMLElement() : mType( XET_CDATA ) , mAttributes() , mParent( 0 ) , mDocument( 0 ) , mIdAttribute( mAttributes.end() ) , mNameAttribute( mAttributes.end() ) {} XMLElement::XMLElement( const std::string &cdata ) : mType( XET_CDATA ) , mContents( cdata ) , mAttributes() , mParent( 0 ) , mDocument( 0 ) , mIdAttribute( mAttributes.end() ) , mNameAttribute( mAttributes.end() ) {} XMLElement::XMLElement( Type type, const std::string &data ) : mType( type ) , mContents( (type == XET_CDATA || type == XET_COMMENT) ? data : std::string() ), mAttributes(), mParent( 0 ), mDocument( 0 ), mIdAttribute( mAttributes.end() ), mNameAttribute( mAttributes.end() ) {} XMLElement::XMLElement( const char *tagName, const char*const *attrValuePairList, unsigned int nAttr ) : mType( XET_TAG ) , mTagName( tagName ) , mAttributes() , mParent( 0 ) , mDocument( 0 ) , mIdAttribute( mAttributes.end() ) , mNameAttribute( mAttributes.end() ) { for (; (nAttr >= 2 && attrValuePairList[0] && attrValuePairList[1]); attrValuePairList += 2) setAttribute( attrValuePairList[0], attrValuePairList[1] ); } XMLElement::XMLElement( const char *tagName, const char*const *attrValuePairList ) : mType( XET_TAG ) , mTagName( tagName ) , mAttributes() , mParent( 0 ) , mDocument( 0 ) , mIdAttribute( mAttributes.end() ) , mNameAttribute( mAttributes.end() ) { for (; (attrValuePairList[0] && attrValuePairList[1]); attrValuePairList += 2) setAttribute( attrValuePairList[0], attrValuePairList[1] ); } XMLElement::XMLElement( const std::string &tagName, const std::vector< std::string > &attrValuePairList ) : mType( XET_TAG ) , mTagName( tagName ) , mAttributes() , mParent( 0 ) , mDocument( 0 ) , mIdAttribute( mAttributes.end() ) , mNameAttribute( mAttributes.end() ) { for (std::vector< std::string >::size_type i = 0; i+1 < attrValuePairList.size(); i += 2) setAttribute( attrValuePairList[i], attrValuePairList[i+1] ); } XMLElement::XMLElement( const std::string &tagName, const std::map< std::string, std::string > &attrValuePairList ) : mType( XET_TAG ) , mTagName( tagName ) , mAttributes( attrValuePairList ) , mParent( 0 ) , mDocument( 0 ) , mIdAttribute( mAttributes.find( "id" ) ) , mNameAttribute( mAttributes.find( "name" ) ) {} XMLElement::~XMLElement() { clear(); mParent = 0; mDocument = 0; } void XMLElement::clear( bool doAttributes ) { //Remove all - quickly for (child_iterator cit = childrenBegin(); cit != childrenEnd(); ++cit) delete *cit; mChildren.clear(); mById.clear(); mByName.clear(); if (doAttributes) mAttributes.clear(); mIdAttribute = mNameAttribute = mAttributes.end(); } const std::string& XMLElement::contents() const { static std::string empty; switch ( type() ) { case XET_CDATA : case XET_COMMENT: return mContents; case XET_TAG: case XET_ROOT: if (numChildren() > 0 && getChild( 0 )->type() == XET_CDATA) return getChild( 0 )->contents(); else return empty; default: return empty; } } std::string& XMLElement::contents() { assert( type() == XET_CDATA || type() == XET_COMMENT ); //Dirtify document if (mDocument) mDocument->dirty = true; return mContents; } const XMLElement* XMLElement::getChildById( const std::string &id ) const { ElementMap::const_iterator cit = mById.find( id ); if ( cit == mById.end() ) return 0; else return cit->second; } XMLElement* XMLElement::getChildById( const std::string &id ) { ElementMap::iterator cit = mById.find( id ); if ( cit == mById.end() ) return 0; else return cit->second; } const XMLElement* XMLElement::getChildByName( const std::string &name ) const { ElementMap::const_iterator cit = mByName.find( name ); if ( cit == mByName.end() ) return 0; else return cit->second; } XMLElement* XMLElement::getChildByName( const std::string &name ) { ElementMap::iterator cit = mByName.find( name ); if ( cit == mByName.end() ) return 0; else return cit->second; } unsigned int XMLElement::appendChild( XMLElement *newElem ) { //Dirtify document if (mDocument) mDocument->dirty = true; mChildren.push_back( newElem ); newElem->setParent( this ); newElem->setDocument( mDocument ); return mChildren.size()-1; } void XMLElement::removeChild( unsigned int idx ) { if (idx < mChildren.size() && mChildren[idx]) { //Dirtify document if (mDocument) mDocument->dirty = true; delete mChildren[idx]; mChildren.erase( mChildren.begin()+idx ); } } void XMLElement::removeChild( const XMLElement *which ) { removeChild( std::find( mChildren.begin(), mChildren.end(), which )-mChildren.begin() ); } void XMLElement::removeAttribute( const std::string &name ) { mAttributes.erase( name ); } void XMLElement::setAttribute( const std::string &name, const std::string &value ) { static std::string _id( "id" ); static std::string _name( "name" ); //Dirtify document if (mDocument) mDocument->dirty = true; std::pair< attribute_iterator, bool >rv = mAttributes.insert( std::pair< std::string, std::string > ( name, value ) ); if (rv.second) { if (name == _id) mIdAttribute = rv.first; else if (name == _name) mNameAttribute = rv.first; } } void XMLElement::appendContents( const std::string &cont ) { switch ( type() ) { case XET_CDATA: case XET_COMMENT: //Dirtify document if (mDocument) mDocument->dirty = true; mContents += cont; break; case XET_TAG: case XET_ROOT: if (numChildren() == 0 || getChild( numChildren()-1 )->type() != XET_CDATA) appendChild( new XMLElement( cont ) ); else getChild( numChildren()-1 )->appendContents( cont ); break; } } void XMLElement::setParent( XMLElement *parent ) { mParent = parent; } void XMLElement::setDocument( XMLDocument *document ) { mDocument = document; for (child_iterator cit = childrenBegin(); cit != childrenEnd(); ++cit) (*cit)->setDocument( document ); } void XMLElement::setType( Type newType ) { if ( newType != type() ) { if (mParent) { //Harder //Remove children by hand - to allow them to deregister themselves. while ( numChildren() ) removeChild( numChildren()-1 ); removeAttribute( "id" ); removeAttribute( "name" ); mAttributes.clear(); } else { //Faster clear(); } mType = newType; } } void XMLElement::JoinMaps( ElementMap &dst, const ElementMap &src ) { ElementMap::iterator dit = dst.begin(); ElementMap::const_iterator sit = src.begin(); while ( sit != src.end() ) { dit = dst.insert( dit, *sit ); ++sit; } } void XMLElement::rebuildNamedBindings( bool deepScan ) { mById.clear(); mByName.clear(); for (child_iterator it = childrenBegin(); it != childrenEnd(); ++it) { (*it)->rebuildNamedBindings( deepScan ); if (deepScan) { JoinMaps( mById, (*it)->mById ); JoinMaps( mByName, (*it)->mByName ); } const_attribute_iterator iit = (*it)->mIdAttribute; if ( iit != (*it)->attributesEnd() ) mById.insert( std::pair< std::string, XMLElement* > ( iit->second, *it ) ); const_attribute_iterator nit = (*it)->mNameAttribute; if ( nit != (*it)->attributesEnd() ) mByName.insert( std::pair< std::string, XMLElement* > ( nit->second, *it ) ); } } const XMLElement* XMLElement::getChildByHierarchicalId( const std::string &id ) const { std::string::size_type sep = id.find( '/' ); if (sep != std::string::npos) { const XMLElement *sub = getChildById( id.substr( 0, sep ) ); return sub ? sub->getChildByHierarchicalId( id.substr( sep+1 ) ) : 0; } else { return getChildById( id ); } } XMLElement* XMLElement::getChildByHierarchicalId( const std::string &id ) { std::string::size_type sep = id.find( '/' ); if (sep != std::string::npos) { XMLElement *sub = getChildById( id.substr( 0, sep ) ); return sub ? sub->getChildByHierarchicalId( id.substr( sep+1 ) ) : 0; } else { return getChildById( id ); } } const XMLElement* XMLElement::getChildByHierarchicalName( const std::string &name ) const { std::string::size_type sep = name.find( '/' ); if (sep != std::string::npos) { const XMLElement *sub = getChildByName( name.substr( 0, sep ) ); return sub ? sub->getChildByHierarchicalName( name.substr( sep+1 ) ) : 0; } else { return getChildByName( name ); } } XMLElement* XMLElement::getChildByHierarchicalName( const std::string &name ) { std::string::size_type sep = name.find( '/' ); if (sep != std::string::npos) { XMLElement *sub = getChildByName( name.substr( 0, sep ) ); return sub ? sub->getChildByHierarchicalName( name.substr( sep+1 ) ) : 0; } else { return getChildByName( name ); } } /****************************************************************** * * * * * XMLParser implementation * * * * * ******************************************************************/ struct XMLParserContext { typedef std::map< std::string, XMLProcessor* >ProcessorMap; ProcessorMap processors; XMLSerializer *xparser; XMLDocument *document; XMLElement *current; XML_Parser parser; }; namespace ExpatHandlers { /****************************************************************** * * * XMLSerializer implementation * * * * (ExpatHandlers) * * * ******************************************************************/ static void Doctype( void *userData, const XML_Char *doctypeName, const XML_Char *sysid, const XML_Char *pubid, int has_internal_subset ) { XMLParserContext *internals = (XMLParserContext*) userData; assert( internals ); assert( internals->document ); internals->document->docType = doctypeName; internals->document->sysId = sysid; internals->document->pubId = pubid; } /* atts is array of name/value pairs, terminated by 0; * names and values are 0 terminated. */ static void StartElement( void *userData, const XML_Char *name, const XML_Char **atts ) { XMLParserContext *internals = (XMLParserContext*) userData; assert( internals ); assert( internals->current ); internals->current = internals->current->getChild( internals->current->appendChild( new XMLElement( (const char*) name, (const char*const*) atts ) ) ); } static void EndElement( void *userData, const XML_Char *name ) { XMLParserContext *internals = (XMLParserContext*) userData; assert( internals ); assert( internals->current ); internals->current = internals->current->getParent(); } /* s is not 0 terminated. */ static void CData( void *userData, const XML_Char *s, int len ) { XMLParserContext *internals = (XMLParserContext*) userData; assert( internals ); assert( internals->current ); assert( internals->xparser ); if ( !(internals->xparser->options&XMLSerializer::OPT_WANT_CDATA) ) return; internals->current->appendContents( std::string( s, len ) ); } /* target and data are 0 terminated */ static void PI( void *userData, const XML_Char *target, const XML_Char *data ) { XMLParserContext *internals = (XMLParserContext*) userData; assert( internals ); XMLParserContext::ProcessorMap::const_iterator it = internals->processors.find( std::string( target ) ); if ( it != internals->processors.end() ) { it->second->execute( internals->xparser, internals->document, internals->current, std::string( data ) ); } } static void Comment( void *userData, const XML_Char *data ) { XMLParserContext *internals = (XMLParserContext*) userData; assert( internals ); assert( internals->current ); assert( internals->xparser ); if ( !(internals->xparser->options&XMLSerializer::OPT_WANT_COMMENTS) ) return; internals->current->appendChild( new XMLElement( XMLElement::XET_COMMENT, std::string( data ) ) ); } }; /****************************************************************** * * * XMLSerializer implementation * * * * (member functions) * * * ******************************************************************/ XMLSerializer::XMLSerializer( const char *encoding, XMLDocument *doc, XMLElement *elem ) : options( OPT_DEFAULT ) , internals( 0 ) { initialise( encoding, doc, elem ); } XMLSerializer::~XMLSerializer() { delete close(); } bool XMLSerializer::parse( const void *buf, unsigned int len ) { XMLParserContext *ctxt = (XMLParserContext*) internals; return XML_Parse( ctxt->parser, (const XML_Char*) buf, len, false ) != 0; } bool XMLSerializer::importXML( const std::string &path ) { std::ifstream fi( path.c_str() ); if ( fi.fail() ) { return false; } else { bool bok = true; while ( bok && !fi.fail() && !fi.eof() ) { char buffer[PARSING_BUFFER_SIZE]; fi.read( buffer, sizeof (buffer) ); bok = parse( buffer, fi.gcount() ); } fi.close(); return bok; } } bool _exportXML( std::ostream &stream, XMLElement *elem ) { if (!elem) return false; XMLElement::attribute_iterator ait; unsigned int i; //Prolog switch ( elem->type() ) { case XMLElement::XET_TAG: stream<<"<"<<elem->tagName().c_str(); for (ait = elem->attributesBegin(); ait != elem->attributesEnd(); ++ait) if (ait->second.find( "\"" ) != std::string::npos) stream<<" "<<ait->first.c_str()<<"=\'"<<ait->second.c_str()<<"\'"; else stream<<" "<<ait->first.c_str()<<"=\""<<ait->second.c_str()<<"\""; if (elem->numChildren() > 0) stream<<">"; else stream<<"/>"; break; case XMLElement::XET_CDATA: //To-do: Find out if it needs to be enveloped within '<![CDATA['/']]>' constructs. stream<<elem->contents().c_str(); return !stream.fail(); //No children case XMLElement::XET_COMMENT: stream<<"<!--"<<elem->contents().c_str()<<"-->"; return !stream.fail(); //No children case XMLElement::XET_ROOT: //WTF? return true; } if ( stream.fail() ) return false; //Children for (i = 0; i < elem->numChildren(); ++i) if ( !_exportXML( stream, elem->getChild( i ) ) ) return false; if ( stream.fail() ) return false; //Epilog switch ( elem->type() ) { case XMLElement::XET_TAG: if (elem->numChildren() > 0) stream<<"</"<<elem->tagName().c_str()<<">"; break; case XMLElement::XET_COMMENT: case XMLElement::XET_CDATA: case XMLElement::XET_ROOT: //WTF? return true; } if ( stream.fail() ) return false; return true; } bool _exportXML( std::ostream &stream, XMLDocument *doc ) { if (!doc) return false; //Output xml && <!DOCTYPE...> tags if ( doc->sysId.empty() ) stream<<"<?xml version=\"1.0\"?>\n"; else stream<<"<?xml version=\"1.1\"?>\n"; if ( !doc->sysId.empty() ) { stream<<"<!DOCTYPE "<<doc->docType.c_str(); if ( !doc->pubId.empty() ) stream<<" PUBLIC \""<<doc->pubId.c_str()<<"\""; else stream<<" SYSTEM"; if (doc->sysId.find( '\"' ) != std::string::npos) stream<<" \'"<<doc->sysId.c_str()<<"\'"; else stream<<" \""<<doc->sysId.c_str()<<"\""; stream<<">\n"; } //Did we fail? if ( stream.fail() ) return false; //Output the rest of the document //NOTE: Although XML 1.1 requires that 'root' may only have one child, //we cant't make that assumption because we count as elements comments //and other productions referred to as 'misc' by the standard. for (unsigned int i = 0; i < doc->root.numChildren(); ++i) if ( !_exportXML( stream, doc->root.getChild( i ) ) ) return false; return true; } bool XMLSerializer::exportXML( std::ostream &stream ) { return !stream.fail() && _exportXML( stream, ( (XMLParserContext*) internals )->document ); } bool XMLSerializer::exportXML( const std::string &filename ) { std::ofstream of( filename.c_str() ); return exportXML( of ); } void XMLSerializer::addProcessor( XMLProcessor *proc ) { assert( internals ); XMLParserContext *ctxt = (XMLParserContext*) internals; ctxt->processors.insert( std::pair< std::string, XMLProcessor* > ( proc->getTarget(), proc ) ); } bool XMLSerializer::initialise( const char *encoding, XMLDocument *doc, XMLElement *elem ) { //DO NOT assert encoding==0... in case an encoding natively supported by expat is passed. //DO assert, though, that doc==0 => elem==0 assert( !(!doc && elem) ); delete close(); XMLParserContext *ctxt = new XMLParserContext; ctxt->xparser = this; ctxt->document = doc ? doc : new XMLDocument(); ctxt->current = elem ? elem : &(ctxt->document->root); //Create Expat parser, and initialize ctxt->parser = XML_ParserCreate( (const XML_Char*) encoding ); XML_SetUserData( ctxt->parser, ctxt ); XML_SetElementHandler( ctxt->parser, &ExpatHandlers::StartElement, &ExpatHandlers::EndElement ); XML_SetCharacterDataHandler( ctxt->parser, &ExpatHandlers::CData ); XML_SetProcessingInstructionHandler( ctxt->parser, &ExpatHandlers::PI ); XML_SetCommentHandler( ctxt->parser, ExpatHandlers::Comment ); internals = ctxt; return true; } XMLDocument* XMLSerializer::close() { XMLDocument *doc = 0; XMLParserContext *ctxt = (XMLParserContext*) internals; if (ctxt) { XML_ParserFree( ctxt->parser ); doc = ctxt->document; if (options&OPT_WANT_NAMEBINDINGS) doc->root.rebuildNamedBindings( (options&OPT_WANT_NAMEBINDINGS_DEEPSCAN) != 0 ); delete ctxt; } internals = 0; return doc; } } //namespace XMLDOM
30.156573
117
0.549569
[ "vector" ]
c0f119cbab8f865d5c68106eebfb4f77a302582d
4,434
inl
C++
include/tpf/math/tpf_vector.inl
UniStuttgart-VISUS/tpf
cf9327363242daff9644bc0d0e40577cdaaf97aa
[ "MIT" ]
null
null
null
include/tpf/math/tpf_vector.inl
UniStuttgart-VISUS/tpf
cf9327363242daff9644bc0d0e40577cdaaf97aa
[ "MIT" ]
1
2021-06-10T15:24:28.000Z
2021-06-10T15:24:28.000Z
include/tpf/math/tpf_vector.inl
UniStuttgart-VISUS/tpf
cf9327363242daff9644bc0d0e40577cdaaf97aa
[ "MIT" ]
1
2021-03-19T16:08:34.000Z
2021-03-19T16:08:34.000Z
#include "tpf_vector.h" #include "Eigen/Dense" #include <algorithm> #include <array> #include <cmath> #include <stdexcept> #include <utility> namespace tpf { namespace math { template <typename floatp_t> inline std::pair<Eigen::Matrix<floatp_t, 3, 1>, Eigen::Matrix<floatp_t, 3, 1>> orthonormal(const Eigen::Matrix<floatp_t, 3, 1>& vector, const floatp_t epsilon) { #ifdef __tpf_sanity_checks if (vector.isZero(epsilon)) { throw std::runtime_error("Cannot find orthogonal vectors to a zero-vector"); } #endif std::pair<Eigen::Matrix<floatp_t, 3, 1>, Eigen::Matrix<floatp_t, 3, 1>> orthonormal_directions; // Create first orthogonal direction if (vector[0] == static_cast<floatp_t>(0.0L)) { orthonormal_directions.first[0] = static_cast<floatp_t>(0.0L); orthonormal_directions.first[1] = -vector[2]; orthonormal_directions.first[2] = vector[1]; } else if (vector[1] == static_cast<floatp_t>(0.0L)) { orthonormal_directions.first[0] = -vector[2]; orthonormal_directions.first[1] = static_cast<floatp_t>(0.0L); orthonormal_directions.first[2] = vector[0]; } else { orthonormal_directions.first[0] = -vector[1]; orthonormal_directions.first[1] = vector[0]; orthonormal_directions.first[2] = static_cast<floatp_t>(0.0L); } // Calculate second orthogonal vector using the cross product orthonormal_directions.second = vector.cross(orthonormal_directions.first); // Normalize and return found vectors orthonormal_directions.first.normalize(); orthonormal_directions.second.normalize(); return orthonormal_directions; } template <typename floatp_t> inline floatp_t calculate_angle(const Eigen::Matrix<floatp_t, 3, 1>& first, const Eigen::Matrix<floatp_t, 3, 1>& second, const floatp_t epsilon) { #ifdef __tpf_sanity_checks if (first.isZero(epsilon) || second.isZero(epsilon)) { throw std::runtime_error("Cannot calculate angle for zero-vectors"); } #endif return std::acos(first.normalized().dot(second.normalized())); } template <typename floatp_t, int components> inline std::array<Eigen::Matrix<floatp_t, components, 1>, components> get_fitting_directions(const Eigen::Matrix<floatp_t, components, 1>& vector) { static_assert(components > 0, "Number of vector components must be larger than zero"); // Sort vector components according to their value std::array<std::pair<int, floatp_t>, components> values; for (int i = 0; i < components; ++i) { values[i] = std::make_pair(i, vector[i]); } std::sort(values.begin(), values.end(), [](const std::pair<int, floatp_t>& first, const std::pair<int, floatp_t>& second) { return std::abs(first.second) > std::abs(second.second); }); // Create directions std::array<Eigen::Matrix<floatp_t, components, 1>, components> directions; for (int i = 0; i < components; ++i) { directions[i].setZero(); directions[i][values[i].first] = std::copysign(static_cast<floatp_t>(1.0), values[i].second); } return directions; } template <typename floatp_t, int components = 3> inline Eigen::Matrix<floatp_t, components, 1> get_fitting_direction(const Eigen::Matrix<floatp_t, 3, 1>& vector) { static_assert(components > 0, "Number of vector components must be larger than zero"); return get_fitting_directions(vector)[0]; } template <typename floatp_t, int components> inline bool equals(const Eigen::Matrix<floatp_t, components, 1>& lhs, const Eigen::Matrix<floatp_t, components, 1>& rhs, const floatp_t epsilon) { bool equal = true; for (int i = 0; i < components; ++i) { equal &= equals(lhs[i], rhs[i], epsilon); } return equal; } } }
36.95
167
0.584123
[ "vector" ]
c0f12adb1db371f0e115e593348af0668b107b81
6,139
cpp
C++
src/test/lang/parser/var_decls_grammar_test.cpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
src/test/lang/parser/var_decls_grammar_test.cpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
src/test/lang/parser/var_decls_grammar_test.cpp
ludkinm/stan
c318114f875266f22c98cf0bebfff928653727cb
[ "CC-BY-3.0", "BSD-3-Clause" ]
null
null
null
#include <gtest/gtest.h> #include <test/unit/lang/utility.hpp> TEST(langParserVarDeclsGrammarDef, addVar) { test_throws("validate_add_var_bad1", "Duplicate declaration of variable"); test_throws("validate_add_var_bad2", "Parameters or transformed parameters " "cannot be integer or integer array"); test_parsable("validate_add_var_good"); } TEST(langParserVarDeclsGrammarDef, validateIntExpr) { test_parsable("validate_validate_int_expr_good"); for (int i = 1; i <= 13; ++i) { std::string model_name("validate_validate_int_expr_bad"); model_name += boost::lexical_cast<std::string>(i); test_throws(model_name, "Dimension declaration requires"); } for (int i = 1; i <= 14; ++i) { std::string model_name("data_index/non_data_index"); model_name += boost::lexical_cast<std::string>(i); test_throws(model_name, "Non-data variables are not allowed in dimension declarations"); } } TEST(langParserVarDeclsGrammarDef, setIntRangeLower) { test_parsable("validate_set_int_range_lower_good"); test_throws("validate_set_int_range_lower_bad1", "Expression denoting integer required"); test_throws("validate_set_int_range_lower_bad2", "Expression denoting integer required"); test_throws("validate_set_int_range_lower_bad3", "Expression denoting integer required"); } TEST(langParserVarDeclsGrammarDef, setIntRangeUpper) { test_parsable("validate_set_int_range_upper_good"); test_throws("validate_set_int_range_upper_bad1", "Expression denoting integer required"); test_throws("validate_set_int_range_upper_bad2", "Expression denoting integer required"); } TEST(langParserVarDeclsGrammarDef, setDoubleRangeLower) { test_parsable("validate_set_double_range_lower_good"); test_throws("validate_set_double_range_lower_bad1", "Expression denoting real required"); test_throws("validate_set_double_range_lower_bad2", "Expression denoting real required"); } TEST(langParserVarDeclsGrammarDef, setDoubleRangeUpper) { test_parsable("validate_set_double_range_upper_good"); test_throws("validate_set_double_range_upper_bad1", "Expression denoting real required"); test_throws("validate_set_double_range_upper_bad2", "Expression denoting real required"); } TEST(langParserVarDeclsGrammarDef, setDoubleOffsetMultiplier) { test_parsable("validate_set_double_offset_multiplier_good"); test_throws("validate_set_double_offset_multiplier_bad1", "Expression denoting real required; found type=vector."); test_throws("validate_set_double_offset_multiplier_bad2", "Expression denoting real required; found type=vector."); test_throws("validate_set_double_offset_multiplier_bad3", "PARSER EXPECTED: \"upper\""); } TEST(langParserVarDeclsGrammarDef, parametersInLocals) { // test_parsable("var-decls-in-functions"); test_throws("var-decl-bad-1", "Non-data variables are not allowed in dimension declarations"); } TEST(langParserVarDeclsGrammarDef, constraintsInLocals) { test_throws("local_var_constraint", "PARSER EXPECTED: <vector length declaration"); test_throws("local_var_constraint2", "PARSER EXPECTED: <vector length declaration"); test_throws("local_var_constraint3", "PARSER EXPECTED: \"[\""); test_throws("local_var_constraint4", "PARSER EXPECTED: <identifier>"); } TEST(langParserVarDeclsGrammarDef, zeroVecs) { test_parsable("vector-zero"); } TEST(langParserVarDeclsGrammarDef, defDeclIntVar) { test_parsable("declare-define-var-int"); } TEST(langParserVarDeclsGrammarDef, badDefDeclIntVar1) { test_throws("declare-define-var-int-1", "Variable definition base type mismatch"); } TEST(langParserVarDeclsGrammarDef, badDefDeclIntVar2) { test_throws("declare-define-var-int-2", "Variable definition base type mismatch"); } TEST(langParserVarDeclsGrammarDef, badDefDeclIntVar3) { test_throws("declare-define-var-int-3", "Variable definition dimensions mismatch"); } TEST(langParserVarDeclsGrammarDef, badDefDeclIntVar4) { test_throws("declare-define-var-int-4", "Variable definition dimensions mismatch"); } TEST(langParserVarDeclsGrammarDef, defDeclDoubleVar) { test_parsable("declare-define-var-double"); } TEST(langParserVarDeclsGrammarDef, badDefDeclDoubleVar1) { test_throws("declare-define-var-double-1", "Variable definition dimensions mismatch"); } TEST(langParserVarDeclsGrammarDef, badDefDeclDoubleVar2) { test_throws("declare-define-var-double-2", "Variable definition base type mismatch"); } TEST(langParserVarDeclsGrammarDef, badDefDeclDoubleVar3) { test_throws("declare-define-var-double-3", "Variable definition not possible in this block"); } TEST(langParserVarDeclsGrammarDef, badDefDeclDoubleVar4) { test_throws("declare-define-var-double-4", "Variable definition not possible in this block"); } TEST(langParserVarDeclsGrammarDef, defDeclVecTypesVar) { test_parsable("declare-define-var-vec-types"); } TEST(langParserVarDeclsGrammarDef, badDefDeclVec1) { test_throws("declare-define-var-vec-1", "Variable definition base type mismatch"); } TEST(langParserVarDeclsGrammarDef, defDeclMatrixVar) { test_parsable("declare-define-var-matrix"); } TEST(langParserVarDeclsGrammarDef, badDefDeclMatrix1) { test_throws("declare-define-var-matrix-1", "Variable definition base type mismatch"); } TEST(langParserVarDeclsGrammarDef, defDeclConstrainedVectorVar) { test_parsable("declare-define-var-constrained-vector"); } TEST(langParserVarDeclsGrammarDef, defDeclConstrainedMatrixVar) { test_parsable("declare-define-var-constrained-matrix"); } TEST(langParserVarDeclsGrammarDef, badDefParamBlock) { test_throws("declare-define-param-block", "Variable definition not possible in this block"); } TEST(langParserVarDeclsGrammarDef, gqLocalRngFunCall) { test_parsable("declare-define-gq-local-rng"); }
36.111765
80
0.745561
[ "vector" ]
c0f1385ab1b3af1eae2d80ea5ad2bc376786e2b5
12,514
hpp
C++
Schweizer-Messer/sm_common/include/sm/serialization_macros.hpp
PushyamiKaveti/kalibr
d8bdfc59ee666ef854012becc93571f96fe5d80c
[ "BSD-4-Clause" ]
2,690
2015-01-07T03:50:23.000Z
2022-03-31T20:27:01.000Z
Schweizer-Messer/sm_common/include/sm/serialization_macros.hpp
PushyamiKaveti/kalibr
d8bdfc59ee666ef854012becc93571f96fe5d80c
[ "BSD-4-Clause" ]
481
2015-01-27T10:21:00.000Z
2022-03-31T14:02:41.000Z
Schweizer-Messer/sm_common/include/sm/serialization_macros.hpp
PushyamiKaveti/kalibr
d8bdfc59ee666ef854012becc93571f96fe5d80c
[ "BSD-4-Clause" ]
1,091
2015-01-26T21:21:13.000Z
2022-03-30T01:55:33.000Z
/** * @file serialization_macros.hpp * @author Simon Lynen <simon.lynen@mavt.ethz.ch> * @date Thu May 22 02:55:13 2013 * * @brief Comparison macros to facilitate checking in serialization methods. * * */ #ifndef SM_SERIALIZATION_MACROS_HPP #define SM_SERIALIZATION_MACROS_HPP #include <type_traits> #include <sstream> #include <ostream> #include <iostream> #include <boost/static_assert.hpp> #include <boost/shared_ptr.hpp> #include <sm/typetraits.hpp> namespace cv { class Mat; } // namespace cv namespace sm_serialization { namespace internal_types { typedef char yes; typedef int no; } // namespace internal_types } // namespace sm_serialization struct AnyT { template<class T> AnyT(const T &); }; sm_serialization::internal_types::no operator <<(const AnyT &, const AnyT &); namespace sm{ namespace serialization{ namespace internal{ template<class T> sm_serialization::internal_types::yes check(const T&); sm_serialization::internal_types::no check(sm_serialization::internal_types::no); struct makeCompilerSilent{ //rm warning about unused functions void foo(){ check(sm_serialization::internal_types::no()); AnyT t(5); operator <<(t, t); } }; //this template metaprogramming struct can tell us if there is the operator<< defined somewhere template<typename StreamType, typename T> class HasOStreamOperator { static StreamType & stream; static T & x; public: enum { value = sizeof(check(stream << x)) == sizeof(sm_serialization::internal_types::yes) }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, boost::shared_ptr<T> > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, T* > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; template<typename StreamType, typename T> class HasOStreamOperator<StreamType, T& > { public: enum { value = HasOStreamOperator<StreamType, T>::value }; }; //this template metaprogramming struct can tell us whether a class has a member //function isBinaryEqual template<typename T> class HasIsBinaryEqual { //for non const methods (which is actually wrong) template<typename U, bool (U::*)(const T&)> struct Check; template<typename U> static char func(Check<U, &U::isBinaryEqual> *); template<typename U> static int func(...); //for const methods template<typename U, bool (U::*)(const T&) const> struct CheckConst; template<typename U> static char funcconst(CheckConst<U, &U::isBinaryEqual> *); template<typename U> static int funcconst(...); public: enum { value = (int)((sizeof(func<T>(0)) == sizeof(char)) || (sizeof(funcconst<T>(0)) == sizeof(char))) }; }; template<typename T> class HasIsBinaryEqual<boost::shared_ptr<T> > { public: enum { value = HasIsBinaryEqual<T>::value }; }; template<typename T> class HasIsBinaryEqual<T*> { public: enum { value = HasIsBinaryEqual<T>::value }; }; template<typename T> class HasIsBinaryEqual<T&> { public: enum { value = HasIsBinaryEqual<T>::value }; }; //these structs are used to choose between isBinaryEqual function call and the //default operator== template<bool, typename A> struct isSame; template<typename A> struct isSame<true, A> { static bool eval(const A& lhs, const A& rhs) { return lhs.isBinaryEqual(rhs); } }; template<typename A> struct isSame<true, boost::shared_ptr<A> > { static bool eval(const boost::shared_ptr<A>& lhs, const boost::shared_ptr<A>& rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return lhs->isBinaryEqual(*rhs); } }; template<typename A> struct isSame<true, A* > { static bool eval(const A* const lhs, const A* const rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return lhs->isBinaryEqual(*rhs); } }; template<typename A> struct isSame<false, A> { static bool eval(const A& lhs, const A& rhs) { return lhs == rhs; } }; template<typename A> struct isSame<false, A*> { static bool eval(A const * lhs, A const * rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return *lhs == *rhs; } }; template<typename A> struct isSame<false, boost::shared_ptr<A> > { static bool eval(const boost::shared_ptr<A>& lhs, const boost::shared_ptr<A>& rhs) { if (!lhs && !rhs) { return true; } if (!lhs || !rhs) { return false; } return *lhs == *rhs; } }; //for opencv Mat we have to use the sm opencv isBinaryEqual method otherwise sm_common has to depend on sm_opencv template<typename T, bool B> struct checkTypeIsNotOpencvMat { enum{ value = true, }; }; template<bool B> struct checkTypeIsNotOpencvMat<cv::Mat, B> { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; template<bool B> struct checkTypeIsNotOpencvMat<boost::shared_ptr<cv::Mat>, B > { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; template<bool B> struct checkTypeIsNotOpencvMat<cv::Mat*, B> { enum{ value = true, //yes true is correct here }; BOOST_STATIC_ASSERT_MSG((B == !B) /*false*/, "You cannot use the macro SM_CHECKSAME or SM_CHECKSAMEMEMBER on opencv mat. Use sm::opencv::isBinaryEqual instead"); }; //if the object supports it stream to ostream, otherwise put NA template<bool, typename A> struct streamIf; template<typename A> struct streamIf<true, A> { static std::string eval(const A& rhs) { std::stringstream ss; ss << rhs; return ss.str(); } }; template<typename A> struct streamIf<true, A*> { static std::string eval(const A* rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<true, boost::shared_ptr<A> > { static std::string eval(const boost::shared_ptr<A>& rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<true, boost::shared_ptr<const A> > { static std::string eval(const boost::shared_ptr<const A>& rhs) { if (!rhs) { return "NULL"; } std::stringstream ss; ss << *rhs; return ss.str(); } }; template<typename A> struct streamIf<false, A> { static std::string eval(const A&) { return "NA"; } }; struct VerboseChecker { static bool SetVerbose(bool verbose) { Instance().verbose_ = verbose; return true; // Intended. } static bool Verbose() { return Instance().verbose_; } private: static VerboseChecker& Instance() { static VerboseChecker instance; return instance; } VerboseChecker() : verbose_(false) { } VerboseChecker(const VerboseChecker&); VerboseChecker& operator==(const VerboseChecker&); bool verbose_; }; } // namespace internal } // namespace serialization } // namespace sm #define IS_CHECKSAME_CURRENTLY_VERBOSE \ (sm::serialization::internal::VerboseChecker::Verbose()) #define SET_CHECKSAME_VERBOSITY(verbose) \ sm::serialization::internal::VerboseChecker::SetVerbose(verbose) #define SET_CHECKSAME_VERBOSE \ SET_CHECKSAME_VERBOSITY(true) #define SET_CHECKSAME_SILENT \ SET_CHECKSAME_VERBOSITY(false) #define SM_SERIALIZATION_CHECKSAME_VERBOSE(THIS, OTHER, VERBOSE) \ SET_CHECKSAME_VERBOSITY(VERBOSE) && \ SM_SERIALIZATION_CHECKSAME_IMPL(THIS, OTHER) #define SM_SERIALIZATION_CHECKSAME_IMPL(THIS, OTHER) \ (sm::serialization::internal::checkTypeIsNotOpencvMat<\ typename sm::common::StripConstReference<decltype(OTHER)>::result_t, \ false>::value && /*for opencvMats we have to use sm::opencv::isBinaryEqual otherwise this code has to depend on opencv*/ \ sm::serialization::internal::isSame<\ sm::serialization::internal::HasIsBinaryEqual<\ /*first run the test of equality: either isBinaryEqual or op==*/ \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t >::eval(THIS, OTHER)) ? \ true : /*return true if good*/ \ (IS_CHECKSAME_CURRENTLY_VERBOSE ? \ (std::cout << "*** Validation failed on " << #OTHER << ":\n"<< \ /* If not true, check whether VERBOSE and then try to output the * failed values using operator<<*/ \ sm::serialization::internal::streamIf<\ sm::serialization::internal::HasOStreamOperator<std::ostream, \ /*here we check whether operator<< is available*/ \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t >::eval(THIS) << \ "other:\n" << sm::serialization::internal::streamIf<\ sm::serialization::internal::HasOStreamOperator<std::ostream,\ typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(OTHER)>::result_t>::eval(OTHER) \ << "\nat " << __PRETTY_FUNCTION__ << /* Print the function where this happened.*/ \ " In: " << __FILE__ << ":" << __LINE__ << std::endl << std::endl) && false : false) #define SM_SERIALIZATION_CHECKMEMBERSSAME_VERBOSE(OTHER, MEMBER, VERBOSE) \ (SET_CHECKSAME_VERBOSITY(VERBOSE) && \ SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL(OTHER, MEMBER) #define SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL(OTHER, MEMBER) \ ((sm::serialization::internal::checkTypeIsNotOpencvMat<\ typename sm::common::StripConstReference<decltype(OTHER)>::result_t,\ false>::value) && /* For opencvMats we have to use sm::opencv::isBinaryEqual otherwise this code has to depend on opencv.*/\ (sm::serialization::internal::isSame<\ sm::serialization::internal::HasIsBinaryEqual<\ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<\ decltype(MEMBER)>::result_t >::eval(this->MEMBER, OTHER.MEMBER))) ? \ true : (IS_CHECKSAME_CURRENTLY_VERBOSE ? \ (std::cout << "*** Validation failed on " << #MEMBER << ":\n"<< \ sm::serialization::internal::streamIf<\ sm::serialization::internal::HasOStreamOperator<std::ostream,\ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t >::eval(this->MEMBER) << \ "\nother:\n" << sm::serialization::internal::streamIf<\ sm::serialization::internal::HasOStreamOperator<std::ostream,\ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t>::value, \ typename sm::common::StripConstReference<decltype(MEMBER)>::result_t >::eval(OTHER.MEMBER) \ << "\nat " << __PRETTY_FUNCTION__ << \ " In: " << __FILE__ << ":" << __LINE__ << std::endl << std::endl) && false : false) // This is some internal default macro parameter deduction. #define SM_SERIALIZATION_GET_3RD_ARG(arg1, arg2, arg3, ...) arg3 #define SM_SERIALIZATION_GET_4TH_ARG(arg1, arg2, arg3, arg4, ...) arg4 #define SM_SERIALIZATION_MACRO_CHOOSER_MEMBER_SAME(...) \ SM_SERIALIZATION_GET_4TH_ARG(__VA_ARGS__, SM_SERIALIZATION_CHECKMEMBERSSAME_VERBOSE,\ SM_SERIALIZATION_CHECKMEMBERSSAME_IMPL) #define SM_SERIALIZATION_MACRO_CHOOSER_SAME(...) \ SM_SERIALIZATION_GET_4TH_ARG(__VA_ARGS__, SM_SERIALIZATION_CHECKSAME_VERBOSE,\ SM_SERIALIZATION_CHECKSAME_IMPL) //\brief This macro checks this->MEMBER against OTHER.MEMBER with the // appropriate IsBinaryEqual or operator==. // Pointers and boost::shared_ptr are handled automatically. #define SM_CHECKMEMBERSSAME(...) \ SM_SERIALIZATION_MACRO_CHOOSER_MEMBER_SAME(__VA_ARGS__)(__VA_ARGS__) //\brief This macro checks THIS against OTHER with the appropriate // IsBinaryEqual or operator==. // Pointers and boost::shared_ptr are handled automatically. #define SM_CHECKSAME(...) \ SM_SERIALIZATION_MACRO_CHOOSER_SAME(__VA_ARGS__)(__VA_ARGS__) #endif //SM_SERIALIZATION_MACROS_HPP
30.975248
163
0.689148
[ "object" ]
c0f3cee2eaf7322ff2e16a850a8edcd7f80ea47f
6,289
cpp
C++
tests/obv/any/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
20
2019-11-13T12:31:20.000Z
2022-02-27T12:30:39.000Z
tests/obv/any/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
46
2019-11-15T20:40:18.000Z
2022-03-31T19:04:36.000Z
tests/obv/any/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
5
2019-11-12T15:00:50.000Z
2022-01-17T17:33:05.000Z
/** * @file client.cpp * @author Marcel Smit * * @brief CORBA C++11 client application * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "anyC.h" #include "ace/Get_Opt.h" #include "testlib/taox11_testlog.h" const ACE_TCHAR *ior = ACE_TEXT("file://test.ior"); bool parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("k:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'k': ior = get_opts.optarg; break; case '?': default: TAOX11_TEST_ERROR << "usage: " << std::endl << "-k <ior> " << std::endl; return false; } // Indicates successful parsing of the command line return true; } int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) { int errors = 0; try { IDL::traits<CORBA::ORB>::ref_type orb = CORBA::ORB_init (argc, argv); if (!orb) { TAOX11_TEST_ERROR << "ERROR: CORBA::ORB_init (argc, argv) returned null ORB." << std::endl; return 1; } if (!parse_args (argc, argv)) { return 1; } IDL::traits<CORBA::Object>::ref_type obj = orb->string_to_object (ior); if (!obj) { TAOX11_TEST_ERROR << "string_to_object failed." << std::endl; return 1; } // Create and register factories. IDL::traits<OBV_AnyTest::VA>::factory_ref_type va_factory = CORBA::make_reference< OBV_AnyTest::VA_init > (); orb->register_value_factory (va_factory->_obv_repository_id (), va_factory); IDL::traits< OBV_AnyTest::VB >::factory_ref_type vb_factory = CORBA::make_reference< OBV_AnyTest::VB_init > (); orb->register_value_factory (vb_factory->_obv_repository_id (), vb_factory); // Do local test IDL::traits< OBV_AnyTest::VA>::ref_type va1 = CORBA::make_reference< IDL::traits<OBV_AnyTest::VA>::obv_type > (); IDL::traits< OBV_AnyTest::VA>::ref_type va2 = CORBA::make_reference< IDL::traits<OBV_AnyTest::VA>::obv_type > (); uint32_t magic = 3145; va1->id (magic); va2->id (magic); CORBA::Any a1, a2; // Test both copying and non-copying version of operator<<= a1 <<= va1; IDL::traits<OBV_AnyTest::VA>::ref_type pva = va2; a2 <<= pva; IDL::traits<OBV_AnyTest::VA>::ref_type dst; if (!(a1 >>= dst) || dst->id () != magic) { TAOX11_TEST_ERROR << "ERROR - inserting any a1 into a valuetype" << std::endl; ++errors; } if (!(a2 >>= dst) || dst->id () != magic) { TAOX11_TEST_ERROR << "ERROR - inserting any a2 into a valuetype" << std::endl; ++errors; } // It should be possible to extract to a base type IDL::traits< OBV_AnyTest::VB>::ref_type vb1 = CORBA::make_reference< IDL::traits< OBV_AnyTest::VB >::obv_type > (); vb1->id (magic); a1 <<= vb1; IDL::traits<CORBA::ValueBase>::ref_type target; if (!(a1 >>= target)) { TAOX11_TEST_ERROR << "ERROR - unable to extract to its base type" << std::endl; ++errors; } dst = IDL::traits<OBV_AnyTest::VA>::narrow (target); if (dst == 0 || dst->id () != magic) { TAOX11_TEST_ERROR << "ERROR - unable to narrow CORBA::ValueBase to its original" << std::endl; ++errors; } // Now do remote test IDL::traits< OBV_AnyTest::Test>::ref_type test = IDL::traits< OBV_AnyTest::Test >::narrow (obj); if (!test) { TAOX11_TEST_ERROR << "IDL::traits<OBV_AnyTest::Test>::narrow failed." << std::endl; return 1; } // STEP 1. Retrieving VA in an any CORBA::Any result = test->get_something (false); if (!(result >>= dst) || dst->id () != magic) { TAOX11_TEST_ERROR << "ERROR - remote test 1 failed: " << dst->id() << std::endl; ++errors; } // STEP 2. IDL::traits< OBV_AnyTest::VB>::ref_type dst_vb; result = test->get_something (true); if (!(result >>= dst_vb) || dst_vb->id () != magic) { TAOX11_TEST_ERROR << "ERROR - remote test 2 failed" << std::endl; ++errors; } // STEP 3. A sanity check demonstrating base-type pointer to // derived type allowed. IDL::traits< OBV_AnyTest::VA>::ref_type dst_va = test->get_vb (); if (dst_va->id () != magic) { TAOX11_TEST_ERROR << "ERROR - remote test 3 failed" << std::endl; ++errors; } // STEP 4. A VA is added as ValueBase to an Any. Extract this here result = test->get_base (); IDL::traits<CORBA::ValueBase>::ref_type dst_base; if (!(result >>= dst_base)) { TAOX11_TEST_ERROR << "ERROR - remote test 4 failed: Unable to extract valuetype" << std::endl; ++errors; } else { dst = IDL::traits<OBV_AnyTest::VA>::narrow (dst_base); if (!dst || dst->id () != magic) { TAOX11_TEST_ERROR << "ERROR - remote test 4 failed: Unable to narrow to the original type" << std::endl; ++errors; } } #if !defined (TAO_HAS_OPTIMIZED_VALUETYPE_MARSHALING) // @@ There's still a problem here with the optimized valuetype // marshaling and passing values through anys. The problem is // that while the Any in fact contains all of the required type // information, there is no way to share that with the // ValueBase::_tao_unmarshal_pre() which needs the type info in // order to select the appropriate value factory. // STEP 5. get a VB, but extract to a VA*. result = test->get_something (true); if (!(result >>= target)) { TAOX11_TEST_ERROR << "ERROR - remote test 5 extraction failed" << std::endl; ++errors; } dst_va = IDL::traits<OBV_AnyTest::VA>::narrow (target); if (dst_va == nullptr || dst_va->id () != magic) { TAOX11_TEST_ERROR << "ERROR - remote test 5 failed" << std::endl; ++errors; } #endif /* TAO_HAS_OPTIMIZED_VALUETYPE_MARSHALING */ test->shutdown (); orb->destroy (); TAOX11_TEST_DEBUG << "client - test finished: <" << errors << "> issues were found." << std::endl; } catch (const CORBA::Exception& ex) { TAOX11_TEST_ERROR << "ERROR - unexpected Exception caught in client: " << ex << std::endl; return 1; } return errors; }
26.761702
98
0.58976
[ "object" ]
c0f44fa82e5ac4ed0ace26248719470dde7113c2
17,233
cc
C++
source/pch/compat_impl.cc
funrunskypalace/greatwall_memory_trading_libs
d01931e3a85a352f644a9cef5f7f5f569fd7aed7
[ "Apache-2.0" ]
null
null
null
source/pch/compat_impl.cc
funrunskypalace/greatwall_memory_trading_libs
d01931e3a85a352f644a9cef5f7f5f569fd7aed7
[ "Apache-2.0" ]
null
null
null
source/pch/compat_impl.cc
funrunskypalace/greatwall_memory_trading_libs
d01931e3a85a352f644a9cef5f7f5f569fd7aed7
[ "Apache-2.0" ]
null
null
null
#include "pch/compat.h" #include <iterator> #if (defined WINDOWS) || (defined WIN32) #include <WinSock2.h> #include <direct.h> #else #include <dirent.h> #include <dlfcn.h> #endif #include <codecvt> #include <cctype> #include <chrono> #include <random> #include <sstream> #include <string> #include "orchid/common/utility.h" std::string gb2312toutf8(const std::string& gb2312str) { #ifdef WIN32 const char* GBK_LOCALE_NAME = ".936"; // GBK在windows下的locale name #else const char* GBK_LOCALE_NAME = "zh_CN.GBK"; // GBK在windows下的locale name #endif struct codecvt : std::codecvt_byname<wchar_t, char, mbstate_t> { codecvt(const char* loc) : std::codecvt_byname<wchar_t, char, mbstate_t>(loc) { } ~codecvt() {} }; //构造GBK与wstring间的转码器(wstring_convert在析构时会负责销毁codecvt_byname,所以不用自己delete) // LWG issue 721 // http://www.open-std.org/jtc1/sc22/wg21/docs/lwg-closed.html#721 std::wstring_convert<codecvt> cv1(new codecvt(GBK_LOCALE_NAME)); std::wstring tmp_wstr = cv1.from_bytes(gb2312str); std::wstring_convert<std::codecvt_utf8<wchar_t>> cv2; std::string utf8_str = cv2.to_bytes(tmp_wstr); return utf8_str; } std::string utf8togb2312(const std::string& utf8str) { std::wstring_convert<std::codecvt_utf8<wchar_t>> cutf8; std::wstring wTemp; try { wTemp = cutf8.from_bytes(utf8str); } catch (const std::exception&) { return utf8str; } #ifdef _MSC_VER std::locale loc("zh-CN"); #else std::locale loc("zh_CN.GB18030"); #endif const wchar_t* pwszNext = nullptr; char* pszNext = nullptr; mbstate_t state = {}; std::vector<char> buff(wTemp.size() * 2); int res = std::use_facet<std::codecvt<wchar_t, char, mbstate_t>>(loc).out( state, wTemp.data(), wTemp.data() + wTemp.size(), pwszNext, buff.data(), buff.data() + buff.size(), pszNext); if (std::codecvt_base::ok == res) { return std::string(buff.data(), pszNext); } return ""; } std::string wstr2str(const std::wstring& wstr) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; return converter.to_bytes(wstr); } std::wstring str2wstr(const std::string& str) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter; return converter.from_bytes(str); } std::string convert_path_backslash(std::string pathStr) { if (!pathStr.empty()) { while (pathStr.find(R"(\)") != pathStr.npos) { pathStr[pathStr.find(R"(\)")] = '/'; } } return pathStr; } void convert_path(char* target, const char* source) { const char* s; char* t; for (s = source, t = target; ((s - source) < MAX_PATH_LEN) && (*s != '\0'); s++, t++) { if (strchr(ALL_SPLITS, *s) != NULL) { *t = PATH_SPLIT; } else { *t = *s; } } *t = '\0'; } FILE* mfopen(const char* filename, const char* mode) { char actualName[MAX_PATH_LEN + 1]; convert_path(actualName, filename); return fopen(actualName, mode); } std::string read_whole_file_(const char* filename) { #if false std::ifstream t(filename); return std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); #else /// here's a way to do it that allocates all the memory up front /// (rather than relying on the string class's automatic reallocation): std::string str; std::ifstream t(filename); t.seekg(0, std::ios::end); str.reserve(t.tellg()); t.seekg(0, std::ios::beg); str.assign((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); return str; #endif } std::string read_whole_file(const char* filename, std::string* errMsg) { try { return read_whole_file_(filename); } catch (const std::exception& e) { if (nullptr != errMsg) { *errMsg = std::string("read file exception: ") + filename + ", " + e.what(); } } return ""; } void assign(char* r, int32_t v, int n) { #if false auto str = std::to_string(v); size_t siz = std::min(size_t(n - 1), str.length()); strncpy(r, str.c_str(), siz); r[siz] = 0; #else char szTmp[20] = {0}; sprintf(szTmp, "%d", v); assign(r, szTmp, n); #endif } void assign(char* r, int64_t v, int n) { #if false auto str = std::to_string(v); size_t siz = std::min(size_t(n - 1), str.length()); strncpy(r, str.c_str(), siz); r[siz] = 0; #else char szTmp[21] = {0}; sprintf(szTmp, "%ld", v); assign(r, szTmp, n); #endif } void assign(char* r, const char* v, int n) { if (v == nullptr) { r[0] = 0; return; } size_t siz = std::min(size_t(n - 1), strlen(v)); strncpy(r, v, siz); r[siz] = 0; } void assign(char* r, unsigned int v, int n) { char szTmp[20] = {0}; sprintf(szTmp, "%d", v); assign(r, szTmp, n); } void assign(char* r, char v, int n) { char szTmp[20] = {0}; sprintf(szTmp, "%c", v); assign(r, szTmp, n); } void assign(char* r, std::string& v, int n) { assign(r, v.c_str(), n); } std::string& replace_whole(std::string& data, const std::string& s, const std::string& t) { std::string::size_type n = 0; while ((n = data.find(s, n)) != std::string::npos) { data.replace(n, s.size(), t); n += t.size() - 1; // “-1”是为了退回一个字符,这样\t\t就可以被循环替换为\t0\t } return data; } std::string& replace(std::string& data, const std::string& s, const std::string& t) { std::string::size_type n = 0; while ((n = data.find(s, n)) != std::string::npos) { data.replace(n, s.size(), t); n += t.size(); } return data; } // trim from start (in place) void ltrim(std::string& s, char token) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [token](int ch) { // return !std::isspace(ch); return token != ch; })); } // trim from end (in place) void rtrim(std::string& s, char token) { s.erase(std::find_if(s.rbegin(), s.rend(), [token](int ch) { return token != ch; }) .base(), s.end()); } // trim from both ends (in place) void trim(std::string& s, char token) { ltrim(s, token); rtrim(s, token); } // trim from start (copying) std::string ltrim_copy(std::string s, char token) { ltrim(s, token); return s; } // trim from end (copying) std::string rtrim_copy(std::string s, char token) { rtrim(s, token); return s; } // trim from both ends (copying) std::string trim_copy(std::string s, char token) { trim(s, token); return s; } bool is_string_nullorempty(char* str) { return (str == nullptr || strlen(str) == 0); } /** * \brief * \tparam Out * \param s * \param delim * \param result */ template <typename Out> void split(const std::string& s, char delim, Out result) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { trim(item, ' '); if (item.length() == 0) continue; *(result++) = item; } } std::vector<std::string> split(const std::string& s, char delim) { std::vector<std::string> elems; split(s, delim, std::back_inserter(elems)); return elems; } void abs_path(const char* path, std::string& out) { #ifdef _WIN32 char resolved_path[_MAX_PATH] = {0}; auto ret = _fullpath(nullptr, path, 0); if (ret != nullptr) { assign(resolved_path, ret, _MAX_PATH); out = resolved_path; } #else // linux release有个坑,需要大点的空间 #define max_path 40960 char resolved_path[max_path]; auto ret = realpath(path, resolved_path); if (ret == nullptr) { spdlog::error("Failed to get realpath of {}, errorno = {}", path, errno); } out = resolved_path; #endif } void str_path(const std::string& pathName, std::string& path, std::string& name) { std::string full = pathName; std::replace(full.begin(), full.end(), '\\', '/'); auto it = full.find_last_of('/'); if (it == -1) { path = "./"; name = full; } else { path = full.substr(0, it + 1); name = full.substr(std::min(it + 1, full.size())); } } void* x_load_lib(const char* pLibPath) { if (pLibPath == nullptr) return nullptr; #if (defined WINDOWS) || (defined WIN32) return LoadLibraryExA(pLibPath, nullptr, LOAD_WITH_ALTERED_SEARCH_PATH); #else return dlopen(pLibPath, RTLD_NOW | RTLD_GLOBAL); #endif } void* x_get_function(void* pLib, const char* ProcName) { if (pLib == nullptr) return nullptr; #if (defined WINDOWS) || (defined WIN32) return GetProcAddress((HMODULE)pLib, ProcName); #else return (dlsym(pLib, ProcName)); #endif } void x_free_lib(void* pLib) { if (pLib == nullptr) return; #if (defined WINDOWS) || (defined WIN32) FreeLibrary((HMODULE)pLib); #else dlclose(pLib); #endif } int32_t get_last_error() { return #ifdef __linux__ errno #else GetLastError() #endif ; } bool is_file_exists(const char* fileName) { #if true std::ifstream infile(fileName); return infile.good(); #else // may try following struct stat buf; return stat(fn, &buf) == 0 && (buf.st_mode & S_IFREG) != 0; #endif } bool is_directory_exists(std::string path) { #ifdef WIN32 // return PathIsDirectoryA(path.c_str()) ? true : false; DWORD dwAttrib = GetFileAttributesA(path.c_str()); return (dwAttrib != INVALID_FILE_ATTRIBUTES && (dwAttrib & FILE_ATTRIBUTE_DIRECTORY)); #else DIR* pdir = opendir(path.c_str()); if (pdir == NULL) { return false; } else { closedir(pdir); pdir = NULL; return true; } #endif } std::string& fix_path(std::string& path) { if (path.empty()) { return path; } for (std::string::iterator iter = path.begin(); iter != path.end(); ++iter) { if (*iter == '\\') { *iter = '/'; } } if (path.at(path.length() - 1) != '/') { path += "/"; } return path; } // dirPath is treated as directory only! and will be add '/' postfix bool create_recursion_dir(const std::string& dirPath) { auto path = dirPath; if (path.length() == 0) return true; std::string sub; fix_path(path); std::string::size_type pos = path.find('/'); while (pos != std::string::npos) { std::string cur = path.substr(0, pos - 0); if (cur.length() > 0 && !is_directory_exists(cur)) { bool ret = false; #ifdef WIN32 ret = CreateDirectoryA(cur.c_str(), nullptr) ? true : false; #else ret = (mkdir(cur.c_str(), S_IRWXU | S_IRWXG | S_IRWXO) == 0); #endif if (!ret) { return false; } } pos = path.find('/', pos + 1); } return true; } /** * \brief create directories before last '\\' or '/' * \param path if not ends with '\\' or '/', will not create directory according * to last section in path. \ return */ int make_directory_tree(const char* pPath) { auto path = std::string(pPath); std::string p, n; str_path(path, p, n); path = p; if (is_directory_exists(path)) return 0; return create_recursion_dir(path) ? 0 : 1; } int strcicmp(char const* a, char const* b) { if (a == nullptr) { return -1; } if (b == nullptr) { return 1; } for (;; a++, b++) { int d = tolower(*a) - tolower(*b); if (d != 0 || !*a) return d; } } std::string& to_lower(std::string& data) { std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c) { return std::tolower(c); }); return data; } std::string& to_upper(std::string& data) { std::transform(data.begin(), data.end(), data.begin(), [](unsigned char c) { return std::toupper(c); }); return data; } static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) { std::string ret; int i = 0; int j = 0; unsigned char char_array_3[3]; unsigned char char_array_4[4]; while (in_len--) { char_array_3[i++] = *(bytes_to_encode++); if (i == 3) { char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (i = 0; (i < 4); i++) ret += base64_chars[char_array_4[i]]; i = 0; } } if (i) { for (j = i; j < 3; j++) char_array_3[j] = '\0'; char_array_4[0] = (char_array_3[0] & 0xfc) >> 2; char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4); char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6); char_array_4[3] = char_array_3[2] & 0x3f; for (j = 0; (j < i + 1); j++) ret += base64_chars[char_array_4[j]]; while ((i++ < 3)) ret += '='; } return ret; } std::shared_ptr<std::unordered_map<std::string, std::string>> csv_mapping(const std::string& title, const std::string& value, const std::string& dummy) { auto maps = std::make_shared<std::unordered_map<std::string, std::string>>(); auto cleanvalue = value; cleanvalue = replace_whole(cleanvalue, " ", ""); cleanvalue = replace_whole(cleanvalue, ",,", "," + dummy + ","); auto titletokens = split(title, ','); auto valuetokens = split(cleanvalue, ','); for (int i = 0; i < std::min(titletokens.size(), valuetokens.size()); ++i) { maps->insert(std::make_pair(titletokens[i], valuetokens[i])); } return maps; } std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && (encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i == 4) { for (i = 0; i < 4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = i; j < 4; j++) char_array_4[j] = 0; for (j = 0; j < 4; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } #ifdef __linux__ char* itoa(int value, char* result, int base) { if (base < 2 || base > 36) { *result = '\0'; return result; } char *ptr = result, *ptr1 = result, tmp_char; int tmp_value; do { tmp_value = value; value /= base; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz" [35 + (tmp_value - value * base)]; } while (value); // Apply negative sign if (tmp_value < 0) *ptr++ = '-'; *ptr-- = '\0'; while (ptr1 < ptr) { tmp_char = *ptr; *ptr-- = *ptr1; *ptr1++ = tmp_char; } return result; } #endif int32_t atodate(const char* datestr) { std::string dateobj(datestr); replace_whole(dateobj, "/", ""); replace_whole(dateobj, "-", ""); trim(dateobj, ' '); if (dateobj.length() < 8) { return 19700101; } return atoi(dateobj.substr(0, 8).c_str()); } int32_t atotime(const char* timestr) { std::string timeobj(timestr); replace_whole(timeobj, ":", ""); replace_whole(timeobj, ".", ""); trim(timeobj, ' '); if (timeobj.length() < 6) { return 0; } else if (timeobj.length() < 9) { return atoi(timeobj.substr(0, 6).c_str()) * 1000; } else return atoi(timeobj.c_str()); }
23.736915
85
0.556548
[ "vector", "transform" ]
c0fa4370607e4a6059b4ccd3a36270f765f2ba7b
390
cpp
C++
minicloudsky/practices/cpp_solutions/main.cpp
minicloudsky/Leetcode_Practice
ae594db57e707350238259195247392a4a2b1276
[ "MIT" ]
null
null
null
minicloudsky/practices/cpp_solutions/main.cpp
minicloudsky/Leetcode_Practice
ae594db57e707350238259195247392a4a2b1276
[ "MIT" ]
null
null
null
minicloudsky/practices/cpp_solutions/main.cpp
minicloudsky/Leetcode_Practice
ae594db57e707350238259195247392a4a2b1276
[ "MIT" ]
null
null
null
#include <iostream> #include<vector> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ using namespace std; //int main(int argc, char** argv) { // int n=100,m=100; // vector<int> nums; // vector<int> nums2{1,3,5}; // vector<int> nums3(n,2); // vector<vector<int>> dp; // vector<vector<bool>> dp2(m,vector<bool>(n,true)); // return 0; //}
26
100
0.658974
[ "vector" ]
c0fb75871ea975ebbd49fd95770ab635b5a39513
913
hpp
C++
rendering/window/window_glfw.hpp
usadson/WebEngine
73f436535a70c6c9d7f3a5c565650b6152effd8d
[ "BSD-2-Clause" ]
3
2020-03-28T01:36:44.000Z
2020-06-19T23:55:08.000Z
rendering/window/window_glfw.hpp
usadson/WebEngine
73f436535a70c6c9d7f3a5c565650b6152effd8d
[ "BSD-2-Clause" ]
null
null
null
rendering/window/window_glfw.hpp
usadson/WebEngine
73f436535a70c6c9d7f3a5c565650b6152effd8d
[ "BSD-2-Clause" ]
null
null
null
#pragma once /** * Copyright (C) 2020 Tristan. All Rights Reserved. * This file is licensed under the BSD 2-Clause license. * See the COPYING file for licensing information. */ #include <GLFW/glfw3.h> #include "window.hpp" namespace Rendering { class WindowGLFW : public WindowBase { private: // Private Properties GLFWwindow *internalWindow; public: // Con/destructor WindowGLFW() /* throwable */; ~WindowGLFW() noexcept; public: // Public Methods [[nodiscard]] std::vector<RendererType> GetSupportedRenderers() const noexcept override; [[nodiscard]] std::pair<bool, std::optional<void *> > RegisterRenderer(Renderer &) override; bool PollClose() noexcept override; void SetTitle(Unicode::UString) noexcept override; void SwapBuffers() noexcept override; private: // Private Methods bool InternalPrepareGL() /* throwable */; }; } // namespace Rendering
20.75
56
0.707558
[ "vector" ]
8d116cbb694ff20f44368eb3bf04fd4548ca6f5d
10,978
cpp
C++
android-extend/src/main/jni/video/src/android/video_adapter.cpp
gqjjqg/android-widget-extend
418d7df266f695a8b638ffa1095835347c266381
[ "zlib-acknowledgement" ]
133
2015-12-10T01:42:17.000Z
2021-11-09T12:09:43.000Z
android-extend/src/main/jni/video/src/android/video_adapter.cpp
gqjjqg/android-widget-extend
418d7df266f695a8b638ffa1095835347c266381
[ "zlib-acknowledgement" ]
29
2017-10-09T03:27:27.000Z
2021-03-19T08:52:08.000Z
android-extend/src/main/jni/video/src/android/video_adapter.cpp
gqjjqg/android-widget-extend
418d7df266f695a8b638ffa1095835347c266381
[ "zlib-acknowledgement" ]
52
2017-11-28T09:56:26.000Z
2022-03-23T14:26:03.000Z
//jni #include <jni.h> #include <android/log.h> #include <android/bitmap.h> //lib c #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <string.h> //system #include <fcntl.h> #include <sys/select.h> #include <linux/videodev2.h> #include "device.h" #include "logger.h" #include "image.h" const static unsigned char dht_data[] = { 0xff, 0xc4, 0x01, 0xa2, 0x00, 0x00, 0x01, 0x05, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x01, 0x00, 0x03, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x10, 0x00, 0x02, 0x01, 0x03, 0x03, 0x02, 0x04, 0x03, 0x05, 0x05, 0x04, 0x04, 0x00, 0x00, 0x01, 0x7d, 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12, 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07, 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08, 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0, 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0x11, 0x00, 0x02, 0x01, 0x02, 0x04, 0x04, 0x03, 0x04, 0x07, 0x05, 0x04, 0x04, 0x00, 0x01, 0x02, 0x77, 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21, 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71, 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91, 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0, 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34, 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa }; static int mjpg_raw_insert_huffman(const void *in_buf, int buf_size, void *out_buf); //#define DEBUG //#define DEBUG_DUMP typedef struct engine_t { int mHandle; int mStatus; int mWidth; int mHeight; unsigned char *pTargetBuffer; int mTargetFormat; int mTargetSize; unsigned char *pSourceBuffer; int mSourceFormat; int mSourceSize; #ifdef DEBUG_DUMP FILE * pfile; int frame; #endif }VIDEO, *LPVIDEO; #define MSG_NONE 0 #define MSG_SwingLeft 1 #define MSG_SwingRight 2 #define MSG_SwingUp 3 //public method. static jlong NV_Init(JNIEnv *env, jobject object, jint port); static jint NV_UnInit(JNIEnv *env, jobject object, jlong handler); static jint NV_Set(JNIEnv *env, jobject object, jlong handler, jint width, jint height, jint format); static jint NV_ReadData(JNIEnv *env, jobject object, jlong handler, jbyteArray data, jint size); static JNINativeMethod gMethods[] = { {"initVideo", "(I)J",(void*)NV_Init}, {"uninitVideo", "(J)I",(void*)NV_UnInit}, {"setVideo", "(JIII)I", (void*)NV_Set}, {"readData", "(J[BI)I", (void*)NV_ReadData}, }; const char* JNI_NATIVE_INTERFACE_CLASS = "com/guo/android_extend/device/Video"; JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved){ JNIEnv *env = NULL; if (vm->GetEnv((void**)&env, JNI_VERSION_1_4)){ return JNI_ERR; } jclass cls = env->FindClass(JNI_NATIVE_INTERFACE_CLASS); if (cls == NULL){ LOGI("FindClass"); return JNI_ERR; } jint nRes = env->RegisterNatives(cls, gMethods, sizeof(gMethods)/sizeof(gMethods[0])); if (nRes < 0){ LOGI("RegisterNatives"); return JNI_ERR; } LOGI("video.so JNI_OnLoad"); return JNI_VERSION_1_4; } JNIEXPORT void JNI_OnUnload(JavaVM* vm, void* reserved){ JNIEnv *env = NULL; if (vm->GetEnv((void**)&env, JNI_VERSION_1_4)){ return; } jclass cls = env->FindClass(JNI_NATIVE_INTERFACE_CLASS); if (cls == NULL){ return; } jint nRes = env->UnregisterNatives(cls); } jlong NV_Init(JNIEnv *env, jobject object, jint port) { int error; LPVIDEO engine = (LPVIDEO)malloc(sizeof(VIDEO)); if (engine == NULL) { return -2; } memset(engine, 0, sizeof(VIDEO)); engine->pSourceBuffer = NULL; engine->pTargetBuffer = NULL; engine->mHandle = Open_Video(port); if (engine->mHandle < 0 && engine->mHandle >= -7) { LOGE("Open_Video = %d\n", engine->mHandle); free(engine); return -1; } #ifdef DEBUG_DUMP engine->pfile = fopen("/sdcard/frame1.mjpeg", "wb"); engine->frame = 1; #endif return (jlong)engine; } jint NV_UnInit(JNIEnv *env, jobject object, jlong handler) { LPVIDEO engine = (LPVIDEO)handler; if (engine->pTargetBuffer != NULL) { free(engine->pTargetBuffer); } if (engine->pSourceBuffer != NULL) { free(engine->pSourceBuffer); } Close_Video(engine->mHandle); #ifdef DEBUG_DUMP fclose(engine->pfile); #endif free(engine); return 0; } jint NV_Set(JNIEnv *env, jobject object, jlong handler, jint width, jint height, jint format) { LPVIDEO engine = (LPVIDEO)handler; int f = 0; engine->mWidth = width; engine->mHeight = height; engine->mTargetFormat = format; if (engine->pTargetBuffer != NULL) { free(engine->pTargetBuffer); } engine->mTargetSize = calcImageSize(width, height, engine->mTargetFormat); engine->pTargetBuffer = (unsigned char*)malloc(engine->mTargetSize); if (engine->pTargetBuffer == NULL) { LOGE("malloc fail"); return -1; } //set source format and set output format. engine->mSourceFormat = CP_MJPEG; if (engine->mTargetFormat == CP_PAF_NV12) { if (1 == Check_Format(engine->mHandle, V4L2_PIX_FMT_NV12)) { f = V4L2_PIX_FMT_NV12; engine->mSourceFormat = CP_PAF_NV12; } else if (1 == Check_Format(engine->mHandle, V4L2_PIX_FMT_YUYV)) { f = V4L2_PIX_FMT_YUYV; engine->mSourceFormat = CP_PAF_YUYV; } } else if (engine->mTargetFormat == CP_PAF_NV21) { if (1 == Check_Format(engine->mHandle, V4L2_PIX_FMT_NV21)) { f = V4L2_PIX_FMT_NV21; engine->mSourceFormat = CP_PAF_NV21; } else if (1 == Check_Format(engine->mHandle, V4L2_PIX_FMT_YUYV)) { f = V4L2_PIX_FMT_YUYV; engine->mSourceFormat = CP_PAF_YUYV; } } else if (engine->mTargetFormat == CP_PAF_YUYV) { if (1 == Check_Format(engine->mHandle, V4L2_PIX_FMT_YUYV)) { f = V4L2_PIX_FMT_YUYV; engine->mSourceFormat = CP_PAF_YUYV; } } else if (engine->mTargetFormat == CP_MJPEG) { if (1 == Check_Format(engine->mHandle, V4L2_PIX_FMT_MJPEG)) { f = V4L2_PIX_FMT_MJPEG; engine->mSourceFormat = CP_MJPEG; } } if (f == 0) { LOGE("NOT SUPPORT"); return -1; } #ifdef DEBUG LOGE("setting %d, %d", engine->mSourceFormat, engine->mTargetFormat); #endif if (engine->pSourceBuffer != NULL) { free(engine->pSourceBuffer); } engine->mSourceSize = calcImageSize(width, height, engine->mSourceFormat); engine->pSourceBuffer = (unsigned char*)malloc(engine->mSourceSize); if (engine->pSourceBuffer == NULL) { LOGE("malloc fail"); return -1; } if (Set_Video(engine->mHandle, width, height, f) == -1) { LOGE("Set_Video fail"); return -1; } return 0; } jint NV_ReadData(JNIEnv *env, jobject object, jlong handler, jbyteArray data, jint size) { #ifdef DEBUG unsigned long cost = GTimeGet(); #endif jint ret = 0; jboolean isCopy = false; LPVIDEO engine = (LPVIDEO)handler; signed char* buffer = env->GetByteArrayElements(data, &isCopy); if (buffer == NULL) { LOGI("buffer failed!\n"); return 0; } //LOGE("%d, %d", engine->mSourceFormat, engine->mTargetFormat); ret = Read_Video(engine->mHandle, engine->pSourceBuffer, engine->mSourceSize); #ifdef DEBUG LOGE("Read_Video = %d", ret); #endif if (ret > 0) { if (engine->mSourceFormat == CP_MJPEG) { //MJPG PROCESS ret = mjpg_raw_insert_huffman(engine->pSourceBuffer, ret, (unsigned char *)engine->pTargetBuffer); //mjpg data. decode to raw and convert. #ifdef DEBUG LOGE("mjpeg full size = %d", ret); #endif if (engine->mTargetFormat == CP_MJPEG) { memcpy(buffer, engine->pTargetBuffer, ret); #ifdef DEBUG_DUMP if (engine->frame > 0) { fwrite(engine->pTargetBuffer, sizeof(char), ret, engine->pfile); fclose(engine->pfile); engine->frame = 0; } #endif } else { LOGE("NOT SUPPORT DECODE!"); } } else if (engine->mSourceFormat != engine->mTargetFormat) { if (engine->mSourceFormat == CP_PAF_YUYV && engine->mTargetFormat == CP_PAF_NV21) { convert_YUYV_NV21(engine->pSourceBuffer, (unsigned char *)buffer, engine->mWidth, engine->mHeight); ret = calcImageSize(engine->mWidth, engine->mHeight, engine->mTargetFormat); } else if (engine->mSourceFormat == CP_PAF_YUYV && engine->mTargetFormat == CP_PAF_NV12) { convert_YUYV_NV12(engine->pSourceBuffer, (unsigned char *)buffer, engine->mWidth, engine->mHeight); ret = calcImageSize(engine->mWidth, engine->mHeight, engine->mTargetFormat); } else { LOGE("convert color format failed!"); ret = 0; } } else { // copy out memcpy(buffer, engine->pSourceBuffer, engine->mSourceSize); } } env->ReleaseByteArrayElements(data, buffer, isCopy); return ret; } int mjpg_raw_insert_huffman(const void *in_buf, int buf_size, void *out_buf) { int pos = 0; int size_start = 0; char *pcur = (char *)in_buf; char *pdeb = (char *)in_buf; char *plimit = (char *)in_buf + buf_size; char *jpeg_buf = (char *)out_buf; /* find the SOF0(Start Of Frame 0) of JPEG */ while ( (((pcur[0] << 8) | pcur[1]) != 0xffc0) && (pcur < plimit) ){ pcur++; } LOGE("pcur: %d, plimit: %d", pcur, plimit); /* SOF0 of JPEG exist */ if (pcur < plimit) { if (jpeg_buf != NULL) { //fprintf(stderr, ">"); /* insert huffman table after SOF0 */ size_start = pcur - pdeb; memcpy(jpeg_buf, in_buf, size_start); pos += size_start; memcpy(jpeg_buf + pos, dht_data, sizeof(dht_data)); pos += sizeof(dht_data); memcpy(jpeg_buf + pos, pcur, buf_size - size_start); pos += buf_size - size_start; return pos; } } return 0; }
30.494444
103
0.667426
[ "object" ]
8d1ccad8939a603e324703f9529f015dcccfd490
15,717
cc
C++
src/vw/tools/colormap.cc
maxsu/visionworkbench
34eb3009152d3696471056e65b313d964e658ee8
[ "Apache-2.0" ]
1
2019-06-12T19:42:48.000Z
2019-06-12T19:42:48.000Z
src/vw/tools/colormap.cc
maxsu/visionworkbench
34eb3009152d3696471056e65b313d964e658ee8
[ "Apache-2.0" ]
null
null
null
src/vw/tools/colormap.cc
maxsu/visionworkbench
34eb3009152d3696471056e65b313d964e658ee8
[ "Apache-2.0" ]
null
null
null
// __BEGIN_LICENSE__ // Copyright (c) 2006-2013, United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. All // rights reserved. // // The NASA Vision Workbench is 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. // __END_LICENSE__ #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #include <cstdlib> #include <boost/tokenizer.hpp> #include <boost/lexical_cast.hpp> #include <boost/numeric/conversion/cast.hpp> #include <boost/program_options.hpp> #include <boost/filesystem/path.hpp> #include <boost/foreach.hpp> namespace fs = boost::filesystem; namespace po = boost::program_options; #include <vw/Core/Functors.h> #include <vw/Image/Algorithms.h> #include <vw/Image/ImageMath.h> #include <vw/Image/ImageViewRef.h> #include <vw/Image/PerPixelViews.h> #include <vw/Image/PixelMask.h> #include <vw/Image/MaskViews.h> #include <vw/Image/PixelTypes.h> #include <vw/Image/Statistics.h> #include <vw/FileIO/DiskImageView.h> #include <vw/Cartography/GeoReference.h> #include <vw/tools/Common.h> using namespace vw; struct Options { // Input std::string input_file_name; std::string shaded_relief_file_name; // Settings std::string output_file_name, lut_file_name; float nodata_value, min_val, max_val; bool draw_legend; typedef Vector<uint8,3> Vector3u; typedef std::pair<std::string,Vector3u> lut_element; typedef std::vector<lut_element> lut_type; lut_type lut; std::map<float,Vector3u> lut_map; }; // Colormap function class ColormapFunc : public ReturnFixedType<PixelMask<PixelRGB<uint8> > > { typedef std::map<float,Options::Vector3u> map_type; map_type m_colormap; public: ColormapFunc( std::map<float,Options::Vector3u> const& map) : m_colormap(map) {} template <class PixelT> PixelMask<PixelRGB<uint8> > operator() (PixelT const& pix) const { if (is_transparent(pix)) return PixelMask<PixelRGB<uint8> >(); // Skip transparent pixels float val = compound_select_channel<const float&>(pix,0); if (val > 1.0) val = 1.0; if (val < 0.0) val = 0.0; // Get locations on sparse colormap that bound this pixel value map_type::const_iterator bot = m_colormap.upper_bound( val ); bot--; map_type::const_iterator top = m_colormap.upper_bound( val ); if ( top == m_colormap.end() ) // If this is above the top colormap value return PixelRGB<uint8>(bot->second[0], bot->second[1], bot->second[2]); // Use the max colormap value // Otherwise determine a proportional color between the bounding colormap values Options::Vector3u output = bot->second + // Lower colormap value ( ((val - bot->first)/(top->first - bot->first)) * // Fraction of distance to next colormap value (Vector3i(top->second) - Vector3i(bot->second)) ); // Difference between successive colormap values return PixelRGB<uint8>(output[0], output[1], output[2]); } }; template <class ViewT> UnaryPerPixelView<ViewT, ColormapFunc> colormap(ImageViewBase<ViewT> const& view, std::map<float,Options::Vector3u> const& map) { return UnaryPerPixelView<ViewT, ColormapFunc>(view.impl(), ColormapFunc(map)); } // ------------------------------------------------------------------------------------- template <class PixelT> void do_colorized_dem(Options& opt) { vw_out() << "Creating colorized DEM.\n"; cartography::GeoReference georef; cartography::read_georeference(georef, opt.input_file_name); // Attempt to extract nodata value SrcImageResource *disk_dem_rsrc = DiskImageResource::open(opt.input_file_name); if (opt.nodata_value != std::numeric_limits<float>::max()) { vw_out() << "\t--> Using user-supplied nodata value: " << opt.nodata_value << ".\n"; } else if ( disk_dem_rsrc->has_nodata_read() ) { opt.nodata_value = disk_dem_rsrc->nodata_read(); vw_out() << "\t--> Extracted nodata value from file: " << opt.nodata_value << ".\n"; } // Compute min/max of input image values DiskImageView<PixelT> disk_dem_file(opt.input_file_name); ImageViewRef<PixelGray<float> > input_image = pixel_cast<PixelGray<float> >(select_channel(disk_dem_file,0)); if (opt.min_val == 0 && opt.max_val == 0) { min_max_channel_values( create_mask( input_image, opt.nodata_value), opt.min_val, opt.max_val); vw_out() << "\t--> DEM color map range: [" << opt.min_val << " " << opt.max_val << "]\n"; } else { vw_out() << "\t--> Using user-specified color map range: [" << opt.min_val << " " << opt.max_val << "]\n"; } // Convert lut to lut_map ( converts altitudes to relative percent ) opt.lut_map.clear(); BOOST_FOREACH( Options::lut_element const& pair, opt.lut ) { try { if ( boost::contains(pair.first,"%") ) { float key = boost::lexical_cast<float>(boost::erase_all_copy(pair.first,"%"))/100.0; opt.lut_map[ key ] = pair.second; } else { float key = boost::lexical_cast<float>(pair.first); opt.lut_map[ ( key - opt.min_val ) / ( opt.max_val - opt.min_val ) ] = pair.second; } } catch ( const boost::bad_lexical_cast& e ) { continue; } } // Mask input ImageViewRef<PixelMask<PixelGray<float> > > dem; if ( PixelHasAlpha<PixelT>::value ) dem = alpha_to_mask(channel_cast<float>(disk_dem_file) ); else if (opt.nodata_value != std::numeric_limits<float>::max()) dem = channel_cast<float>(create_mask(input_image, opt.nodata_value)); else if ( disk_dem_rsrc->has_nodata_read() ) dem = create_mask(input_image, opt.nodata_value); else dem = pixel_cast<PixelMask<PixelGray<float> > >(input_image); delete disk_dem_rsrc; // Apply colormap ImageViewRef<PixelMask<PixelRGB<uint8> > > colorized_image = colormap(normalize(dem, opt.min_val, opt.max_val, 0, 1.0), opt.lut_map); if (!opt.shaded_relief_file_name.empty()) { // Using a hillshade file vw_out() << "\t--> Incorporating hillshading from: " << opt.shaded_relief_file_name << ".\n"; DiskImageView<PixelGray<float> > shaded_relief_image(opt.shaded_relief_file_name); // It's okay to throw away the // second channel if it exists. ImageViewRef<PixelMask<PixelRGB<uint8> > > shaded_image = copy_mask(channel_cast<uint8>(colorized_image*pixel_cast<float>(shaded_relief_image)), colorized_image); vw_out() << "Writing color-mapped image: " << opt.output_file_name << "\n"; boost::scoped_ptr<DiskImageResource> r(DiskImageResource::create(opt.output_file_name,shaded_image.format())); if ( r->has_block_write() ) r->set_block_write_size( Vector2i( vw_settings().default_tile_size(), vw_settings().default_tile_size() ) ); write_georeference( *r, georef ); block_write_image( *r, shaded_image, TerminalProgressCallback( "tools.colormap", "Writing:") ); } else { // Not using a hillshade file vw_out() << "Writing color-mapped image: " << opt.output_file_name << "\n"; boost::scoped_ptr<DiskImageResource> r(DiskImageResource::create(opt.output_file_name,colorized_image.format())); if ( r->has_block_write() ) r->set_block_write_size( Vector2i( vw_settings().default_tile_size(), vw_settings().default_tile_size() ) ); write_georeference( *r, georef ); block_write_image( *r, colorized_image, TerminalProgressCallback( "tools.colormap", "Writing:") ); } } void save_legend( Options const& opt) { ImageView<PixelGray<float> > img(100, 500); for (int j = 0; j < img.rows(); ++j) { float val = float(j) / img.rows(); for (int i = 0; i < img.cols(); ++i) { img(i,j) = val; } } ImageViewRef<PixelMask<PixelRGB<uint8> > > colorized_image = colormap(img, opt.lut_map); write_image("legend.png", channel_cast_rescale<uint8>(apply_mask(colorized_image))); } void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options(""); general_options.add_options() ("shaded-relief-file,s", po::value(&opt.shaded_relief_file_name), "Specify a shaded relief image (grayscale) to apply to the colorized image.") ("output-file,o", po::value(&opt.output_file_name), "Specify the output file") ("lut-file", po::value(&opt.lut_file_name), "Specify look up file for color output. It is similar to the file used by gdaldem. Without we revert to our standard LUT") ("nodata-value", po::value(&opt.nodata_value)->default_value(std::numeric_limits<float>::max()), "Remap the DEM default value to the min altitude value.") ("min", po::value(&opt.min_val)->default_value(0), "Minimum height of the color map.") ("max", po::value(&opt.max_val)->default_value(0), "Maximum height of the color map.") ("moon", "Set the min and max values to [-8499 10208] meters, which is suitable for covering elevations on the Moon.") ("mars", "Set the min and max values to [-8208 21249] meters, which is suitable for covering elevations on Mars.") ("legend", "Generate the colormap legend. This image is saved (without labels) as \'legend.png\'") ("help,h", "Display this help message"); po::options_description positional(""); positional.add_options() ("input-file", po::value(&opt.input_file_name), "Input disparity map"); po::positional_options_description positional_desc; positional_desc.add("input-file", 1); po::options_description all_options; all_options.add(general_options).add(positional); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm ); po::notify( vm ); } catch (const po::error& e) { vw_throw( ArgumentErr() << "Error parsing input:\n\t" << e.what() << general_options ); } std::ostringstream usage; usage << "Usage: " << argv[0] << " [options] <input dem> \n"; if ( vm.count("help") ) vw_throw( ArgumentErr() << usage.str() << general_options ); if ( opt.input_file_name.empty() ) vw_throw( ArgumentErr() << "Missing input file!\n" << usage.str() << general_options ); if ( vm.count("moon") ) { opt.min_val = -8499; opt.max_val = 10208; } if ( vm.count("mars") ) { opt.min_val = -8208; opt.max_val = 21249; } if ( opt.output_file_name.empty() ) opt.output_file_name = fs::path(opt.input_file_name).replace_extension().string()+"_CMAP.tif"; opt.draw_legend = vm.count("legend"); } int main( int argc, char *argv[] ) { Options opt; try { handle_arguments( argc, argv, opt ); // Decide legend if ( opt.lut_file_name.empty() ) { // Set up default colormap opt.lut.clear(); opt.lut.push_back( Options::lut_element("0%", Options::Vector3u( 0, 0, 0)) ); // Black opt.lut.push_back( Options::lut_element("20.8%",Options::Vector3u( 0, 0, 255)) ); // Blue opt.lut.push_back( Options::lut_element("25%", Options::Vector3u( 0, 0, 255)) ); // Blue opt.lut.push_back( Options::lut_element("37.5%",Options::Vector3u( 0, 191, 255)) ); // Light blue opt.lut.push_back( Options::lut_element("41.7%",Options::Vector3u( 0, 255, 255)) ); // Teal opt.lut.push_back( Options::lut_element("58.3%",Options::Vector3u(255, 255, 51)) ); // Yellow opt.lut.push_back( Options::lut_element("62.5%",Options::Vector3u(255, 191, 0)) ); // Orange opt.lut.push_back( Options::lut_element("75%", Options::Vector3u(255, 0, 0)) ); // Red opt.lut.push_back( Options::lut_element("79.1%",Options::Vector3u(255, 0, 0)) ); // Red opt.lut.push_back( Options::lut_element("100%", Options::Vector3u( 0, 0, 0)) ); // Black } else { // Read input LUT typedef boost::tokenizer<> tokenizer; boost::char_delimiters_separator<char> sep(false,",:"); std::ifstream lut_file( opt.lut_file_name.c_str() ); if ( !lut_file.is_open() ) vw_throw( IOErr() << "Unable to open LUT: " << opt.lut_file_name ); std::string line; std::getline( lut_file, line ); while ( lut_file.good() ) { // Skip lines containing spaces only bool only_spaces = true; for (unsigned s = 0; s < line.size(); s++) if (!isspace(line[s])) only_spaces = false; if (only_spaces){ std::getline( lut_file, line ); continue; } tokenizer tokens(line,sep); tokenizer::iterator iter = tokens.begin(); std::string key; Options::Vector3u value; try { if ( iter == tokens.end()) vw_throw( IOErr() << "Unable to read input LUT" ); key = *iter; iter++; if ( iter == tokens.end()) vw_throw( IOErr() << "Unable to read input LUT" ); value[0] = boost::numeric_cast<uint8>(boost::lexical_cast<int>(*iter)); iter++; if ( iter == tokens.end()) vw_throw( IOErr() << "Unable to read input LUT" ); value[1] = boost::numeric_cast<uint8>(boost::lexical_cast<int>(*iter)); iter++; if ( iter == tokens.end()) vw_throw( IOErr() << "Unable to read input LUT" ); value[2] = boost::numeric_cast<uint8>(boost::lexical_cast<int>(*iter)); } catch ( const boost::bad_lexical_cast& e ) { std::getline( lut_file, line ); continue; } opt.lut.push_back( Options::lut_element(key, value) ); std::getline( lut_file, line ); } lut_file.close(); } // Get the right pixel/channel type. ImageFormat fmt = tools::image_format(opt.input_file_name); switch(fmt.pixel_format) { case VW_PIXEL_GRAY: switch(fmt.channel_type) { case VW_CHANNEL_UINT8: do_colorized_dem<PixelGray<uint8> >(opt); break; case VW_CHANNEL_INT16: do_colorized_dem<PixelGray<int16> >(opt); break; case VW_CHANNEL_UINT16: do_colorized_dem<PixelGray<uint16> >(opt); break; default: do_colorized_dem<PixelGray<float32> >(opt); break; } break; case VW_PIXEL_GRAYA: switch(fmt.channel_type) { case VW_CHANNEL_UINT8: do_colorized_dem<PixelGrayA<uint8> >(opt); break; case VW_CHANNEL_INT16: do_colorized_dem<PixelGrayA<int16> >(opt); break; case VW_CHANNEL_UINT16: do_colorized_dem<PixelGrayA<uint16> >(opt); break; default: do_colorized_dem<PixelGrayA<float32> >(opt); break; } break; default: vw_throw( ArgumentErr() << "Unsupported pixel format. The DEM image must have only one channel." ); } // Draw legend if ( opt.draw_legend ) save_legend(opt); } catch ( const ArgumentErr& e ) { vw_out() << e.what() << std::endl; return 1; } catch ( const Exception& e ) { std::cerr << "Error: " << e.what() << std::endl; return 1; } return 0; }
41.800532
178
0.641916
[ "vector" ]
8d23a00e35814bde885bc11ffa75e4dbe6dbd3c9
66,560
cpp
C++
dev/Gems/CryLegacy/Code/Source/CryAction/PlayerProfiles/PlayerProfileManager.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
1
2019-02-06T19:12:41.000Z
2019-02-06T19:12:41.000Z
dev/Gems/CryLegacy/Code/Source/CryAction/PlayerProfiles/PlayerProfileManager.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
null
null
null
dev/Gems/CryLegacy/Code/Source/CryAction/PlayerProfiles/PlayerProfileManager.cpp
Kezryk/lumberyard
d21172c26536133a4213873469a171f4f0c4280c
[ "AML" ]
null
null
null
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ // Original file Copyright Crytek GMBH or its affiliates, used under license. #include "CryLegacy_precompiled.h" #include "PlayerProfileManager.h" #include "PlayerProfile.h" #include "CryAction.h" #include "IActionMapManager.h" #include "IPlatformOS.h" #include "CryCrc32.h" #include <PlayerProfileNotificationBus.h> //AzCore #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/Serialization/ObjectStream.h> #define SHARED_SAVEGAME_FOLDER "@user@/SaveGames" #define ONLINE_ATTRIBUTES_DEFINITION_FILE "Scripts/Network/OnlineAttributes.xml" #define ONLINE_VERSION_ATTRIBUTE_NAME "OnlineAttributes/version" const char* CPlayerProfileManager::FACTORY_DEFAULT_NAME = "default"; const char* CPlayerProfileManager::PLAYER_DEFAULT_PROFILE_NAME = "default"; namespace TESTING { void DumpProfiles(IPlayerProfileManager* pFS, const char* userId) { int nProfiles = pFS->GetProfileCount(userId); IPlayerProfileManager::SProfileDescription desc; CryLogAlways("User %s has %d profiles", userId, nProfiles); for (int i = 0; i < nProfiles; ++i) { pFS->GetProfileInfo(userId, i, desc); CryLogAlways("#%d: '%s'", i, desc.name); } } void DumpAttrs(IPlayerProfile* pProfile) { if (pProfile == 0) { return; } IAttributeEnumeratorPtr pEnum = pProfile->CreateAttributeEnumerator(); IAttributeEnumerator::SAttributeDescription desc; CryLogAlways("Attributes of profile %s", pProfile->GetName()); int i = 0; TFlowInputData val; while (pEnum->Next(desc)) { pProfile->GetAttribute(desc.name, val); string sVal; val.GetValueWithConversion(sVal); CryLogAlways("Attr %d: %s=%s", i, desc.name, sVal.c_str()); ++i; } } void DumpSaveGames(IPlayerProfile* pProfile) { ISaveGameEnumeratorPtr pSGE = pProfile->CreateSaveGameEnumerator(); ISaveGameEnumerator::SGameDescription desc; CryLogAlways("SaveGames for Profile '%s'", pProfile->GetName()); char timeBuf[256]; #ifdef AZ_COMPILER_MSVC tm time; for (int i = 0; i < pSGE->GetCount(); ++i) { pSGE->GetDescription(i, desc); localtime_s(&time, &desc.metaData.saveTime); if (strftime(timeBuf, sizeof(timeBuf), "%#c", &time) == 0) { asctime_s(timeBuf, AZ_ARRAY_SIZE(timeBuf), &time); } CryLogAlways("SaveGame %d/%d: name='%s' humanName='%s' desc='%s'", i, pSGE->GetCount() - 1, desc.name, desc.humanName, desc.description); CryLogAlways("MetaData: level=%s gr=%s version=%d build=%s savetime=%s", desc.metaData.levelName, desc.metaData.gameRules, desc.metaData.fileVersion, desc.metaData.buildVersion, timeBuf); } #else struct tm* timePtr; for (int i = 0; i < pSGE->GetCount(); ++i) { pSGE->GetDescription(i, desc); timePtr = localtime(&desc.metaData.saveTime); const char* timeString = timeBuf; if (strftime(timeBuf, sizeof(timeBuf), "%#c", timePtr) == 0) { timeString = asctime(timePtr); } CryLogAlways("SaveGame %d/%d: name='%s' humanName='%s' desc='%s'", i, pSGE->GetCount() - 1, desc.name, desc.humanName, desc.description); CryLogAlways("MetaData: level=%s gr=%s version=%d build=%s savetime=%s", desc.metaData.levelName, desc.metaData.gameRules, desc.metaData.fileVersion, desc.metaData.buildVersion, timeString); } #endif } void DumpActionMap(IPlayerProfile* pProfile, const char* name) { IActionMap* pMap = pProfile->GetActionMap(name); if (pMap) { int iAction = 0; IActionMapActionIteratorPtr pIter = pMap->CreateActionIterator(); while (const IActionMapAction* pAction = pIter->Next()) { CryLogAlways("Action %d: '%s'", iAction++, pAction->GetActionId().c_str()); int iNumInputData = pAction->GetNumActionInputs(); for (int i = 0; i < iNumInputData; ++i) { const SActionInput* pActionInput = pAction->GetActionInput(i); CRY_ASSERT(pActionInput != NULL); CryLogAlways("Key %d/%d: '%s'", i, iNumInputData - 1, pActionInput->input.c_str()); } } } } void DumpMap(IConsoleCmdArgs* args) { IActionMapManager* pAM = CCryAction::GetCryAction()->GetIActionMapManager(); IActionMapIteratorPtr iter = pAM->CreateActionMapIterator(); while (IActionMap* pMap = iter->Next()) { CryLogAlways("ActionMap: '%s' 0x%p", pMap->GetName(), pMap); int iAction = 0; IActionMapActionIteratorPtr pIter = pMap->CreateActionIterator(); while (const IActionMapAction* pAction = pIter->Next()) { CryLogAlways("Action %d: '%s'", iAction++, pAction->GetActionId().c_str()); int iNumInputData = pAction->GetNumActionInputs(); for (int i = 0; i < iNumInputData; ++i) { const SActionInput* pActionInput = pAction->GetActionInput(i); CRY_ASSERT(pActionInput != NULL); CryLogAlways("Key %d/%d: '%s'", i, iNumInputData - 1, pActionInput->input.c_str()); } } } } void TestProfile(IConsoleCmdArgs* args) { const char* userName = GetISystem()->GetUserName(); IPlayerProfileManager::EProfileOperationResult result; IPlayerProfileManager* pFS = CCryAction::GetCryAction()->GetIPlayerProfileManager(); // test renaming current profile #if 0 pFS->RenameProfile(userName, "newOne4", result); return; #endif bool bFirstTime = false; pFS->LoginUser(userName, bFirstTime); DumpProfiles(pFS, userName); pFS->DeleteProfile(userName, "PlayerCool", result); IPlayerProfile* pProfile = pFS->ActivateProfile(userName, "default"); if (pProfile) { DumpActionMap(pProfile, "default"); DumpAttrs(pProfile); pProfile->SetAttribute("hallo2", TFlowInputData(222)); pProfile->SetAttribute("newAddedAttribute", TFlowInputData(24.10f)); DumpAttrs(pProfile); pProfile->SetAttribute("newAddedAttribute", TFlowInputData(25.10f)); DumpAttrs(pProfile); pProfile->ResetAttribute("newAddedAttribute"); pProfile->ResetAttribute("hallo2"); DumpAttrs(pProfile); DumpSaveGames(pProfile); float fVal; pProfile->GetAttribute("newAddedAttribute", fVal); pProfile->SetAttribute("newAddedAttribute", 2.22f); } else { CryLogAlways("Can't activate profile 'default'"); } const IPlayerProfile* pPreviewProfile = pFS->PreviewProfile(userName, "previewTest"); if (pPreviewProfile) { float fVal; pPreviewProfile->GetAttribute("previewData", fVal); pPreviewProfile->GetAttribute("previewData2", fVal, true); } DumpProfiles(pFS, userName); // pFS->RenameProfile(userName, "new new profile"); pFS->LogoutUser(userName); } } int CPlayerProfileManager::sUseRichSaveGames = 0; int CPlayerProfileManager::sRSFDebugWrite = 0; int CPlayerProfileManager::sRSFDebugWriteOnLoad = 0; int CPlayerProfileManager::sLoadOnlineAttributes = 1; //------------------------------------------------------------------------ CPlayerProfileManager::CPlayerProfileManager(CPlayerProfileManager::IPlatformImpl* pImpl) : m_bInitialized(false) , m_pDefaultProfile(0) , m_pImpl(pImpl) , m_loadingProfile(false) , m_savingProfile(false) { assert (m_pImpl != 0); // FIXME: TODO: temp stuff static bool testInit = false; if (testInit == false) { testInit = true; REGISTER_CVAR2("pp_RichSaveGames", &CPlayerProfileManager::sUseRichSaveGames, 0, 0, "Enable RichSaveGame Format for SaveGames"); REGISTER_CVAR2("pp_RSFDebugWrite", &CPlayerProfileManager::sRSFDebugWrite, gEnv->pSystem->IsDevMode() ? 1 : 0, 0, "When RichSaveGames are enabled, save plain XML Data alongside for debugging"); REGISTER_CVAR2("pp_RSFDebugWriteOnLoad", &CPlayerProfileManager::sRSFDebugWriteOnLoad, 0, 0, "When RichSaveGames are enabled, save plain XML Data alongside for debugging when loading a savegame"); REGISTER_CVAR2("pp_LoadOnlineAttributes", &CPlayerProfileManager::sLoadOnlineAttributes, CPlayerProfileManager::sLoadOnlineAttributes, VF_REQUIRE_APP_RESTART, "Load online attributes"); REGISTER_COMMAND("test_profile", TESTING::TestProfile, VF_NULL, ""); REGISTER_COMMAND("dump_action_maps", TESTING::DumpMap, VF_NULL, "Prints all action map bindings to console"); #if PROFILE_DEBUG_COMMANDS REGISTER_COMMAND("loadOnlineAttributes", &CPlayerProfileManager::DbgLoadOnlineAttributes, VF_NULL, "Loads online attributes"); REGISTER_COMMAND("saveOnlineAttributes", &CPlayerProfileManager::DbgSaveOnlineAttributes, VF_NULL, "Saves online attributes"); REGISTER_COMMAND("testOnlineAttributes", &CPlayerProfileManager::DbgTestOnlineAttributes, VF_NULL, "Tests online attributes"); REGISTER_COMMAND("loadProfile", &CPlayerProfileManager::DbgLoadProfile, VF_NULL, "Load current user profile"); REGISTER_COMMAND("saveProfile", &CPlayerProfileManager::DbgSaveProfile, VF_NULL, "Save current user profile"); #endif } m_sharedSaveGameFolder = SHARED_SAVEGAME_FOLDER; // by default, use a shared savegame folder (Games For Windows Requirement) m_sharedSaveGameFolder.TrimRight("/\\"); m_curUserIndex = IPlatformOS::Unknown_User; memset(m_onlineOnlyData, 0, sizeof(m_onlineOnlyData)); m_onlineDataCount = 0; m_onlineDataByteCount = 0; m_onlineAttributeAutoGeneratedVersion = 0; m_registered = false; m_pReadingProfile = NULL; m_onlineAttributesListener = NULL; m_enableOnlineAttributes = false; m_allowedToProcessOnlineAttributes = true; m_exclusiveControllerDeviceIndex = INVALID_CONTROLLER_INDEX; // start uninitialized memset(m_onlineAttributesState, IOnlineAttributesListener::eOAS_None, sizeof(m_onlineAttributesState)); #if PROFILE_DEBUG_COMMANDS m_testingPhase = 0; #endif } //------------------------------------------------------------------------ CPlayerProfileManager::~CPlayerProfileManager() { // don't call virtual Shutdown or any other virtual function, // but delete things directly if (m_bInitialized) { GameWarning("[PlayerProfiles] CPlayerProfileManager::~CPlayerProfileManager Shutdown not called!"); } std::for_each(m_userVec.begin(), m_userVec.end(), stl::container_object_deleter()); SAFE_DELETE(m_pDefaultProfile); if (m_pImpl) { m_pImpl->Release(); m_pImpl = 0; } IConsole* pC = ::gEnv->pConsole; pC->UnregisterVariable("pp_RichSaveGames", true); pC->RemoveCommand("test_profile"); pC->RemoveCommand("dump_action_maps"); } //------------------------------------------------------------------------ bool CPlayerProfileManager::Initialize() { if (m_bInitialized) { return true; } m_pImpl->Initialize(this); CPlayerProfile* pDefaultProfile = new CPlayerProfile(this, FACTORY_DEFAULT_NAME, "", false); bool ok = LoadProfile(0, pDefaultProfile, pDefaultProfile->GetName()); if (!ok) { GameWarning("[PlayerProfiles] Cannot load factory default profile '%s'", FACTORY_DEFAULT_NAME); SAFE_DELETE(pDefaultProfile); } m_pDefaultProfile = pDefaultProfile; m_bInitialized = ok; AZ::PlayerProfileRequestBus::Handler::BusConnect(); return m_bInitialized; } //------------------------------------------------------------------------ bool CPlayerProfileManager::Shutdown() { while (m_userVec.empty () == false) { SUserEntry* pEntry = m_userVec.back(); LogoutUser(pEntry->userId); } SAFE_DELETE(m_pDefaultProfile); m_bInitialized = false; AZ::PlayerProfileRequestBus::Handler::BusDisconnect(); return true; } //------------------------------------------------------------------------ int CPlayerProfileManager::GetUserCount() { return m_userVec.size(); } //------------------------------------------------------------------------ bool CPlayerProfileManager::GetUserInfo(int index, IPlayerProfileManager::SUserInfo& outInfo) { if (index < 0 || index >= m_userVec.size()) { assert (index >= 0 && index < m_userVec.size()); return false; } SUserEntry* pEntry = m_userVec[index]; outInfo.userId = pEntry->userId; return true; } //------------------------------------------------------------------------ bool CPlayerProfileManager::LoginUser(const char* userId, bool& bOutFirstTime) { if (m_bInitialized == false) { return false; } bOutFirstTime = false; m_curUserID = userId; // user already logged in SUserEntry* pEntry = FindEntry(userId); if (pEntry) { m_curUserIndex = pEntry->userIndex; return true; } SUserEntry* newEntry = new SUserEntry(userId); newEntry->pCurrentProfile = 0; newEntry->userIndex = m_userVec.size(); // login the user and fill SUserEntry bool ok = m_pImpl->LoginUser(newEntry); if (!ok) { delete newEntry; GameWarning("[PlayerProfiles] Cannot login user '%s'", userId); return false; } // no entries yet -> create default profile by copying/saving factory default if (m_pDefaultProfile && newEntry->profileDesc.empty()) { // save the default profile ok = m_pImpl->SaveProfile(newEntry, m_pDefaultProfile, PLAYER_DEFAULT_PROFILE_NAME); if (!ok) { GameWarning("[PlayerProfiles] Login of user '%s' failed because default profile '%s' cannot be created", userId, PLAYER_DEFAULT_PROFILE_NAME); delete newEntry; // TODO: maybe assign use factory default in this case, but then // cannot save anything incl. save-games return false; } CryLog("[PlayerProfiles] Login of user '%s': First Time Login - Successfully created default profile '%s'", userId, PLAYER_DEFAULT_PROFILE_NAME); SLocalProfileInfo info(PLAYER_DEFAULT_PROFILE_NAME); time_t lastLoginTime; time(&lastLoginTime); info.SetLastLoginTime(lastLoginTime); newEntry->profileDesc.push_back(info); bOutFirstTime = true; } CryLog("[PlayerProfiles] Login of user '%s' successful.", userId); if (bOutFirstTime == false) { CryLog("[PlayerProfiles] Found %" PRISIZE_T " profiles.", newEntry->profileDesc.size()); for (int i = 0; i < newEntry->profileDesc.size(); ++i) { CryLog(" Profile %d : '%s'", i, newEntry->profileDesc[i].GetName().c_str()); } } m_curUserIndex = newEntry->userIndex; m_userVec.push_back(newEntry); return true; } //------------------------------------------------------------------------ bool CPlayerProfileManager::LogoutUser(const char* userId) { if (!m_bInitialized) { return false; } // check if user already logged in TUserVec::iterator iter; SUserEntry* pEntry = FindEntry(userId, iter); if (pEntry == 0) { GameWarning("[PlayerProfiles] Logout of user '%s' failed [was not logged in]", userId); return false; } #if defined(AZ_RESTRICTED_PLATFORM) #include AZ_RESTRICTED_FILE(PlayerProfileManager_cpp, AZ_RESTRICTED_PLATFORM) #endif #if defined(AZ_RESTRICTED_SECTION_IMPLEMENTED) #undef AZ_RESTRICTED_SECTION_IMPLEMENTED #else // auto-save profile if (pEntry->pCurrentProfile && (gEnv && gEnv->pSystem && (!gEnv->pSystem->IsQuitting()))) { EProfileOperationResult result; bool ok = SaveProfile(userId, result, ePR_Options); if (!ok) { GameWarning("[PlayerProfiles] Logout of user '%s': Couldn't save profile '%s'", userId, pEntry->pCurrentProfile->GetName()); } } #endif m_pImpl->LogoutUser(pEntry); if (m_curUserIndex == std::distance(m_userVec.begin(), iter)) { m_curUserIndex = IPlatformOS::Unknown_User; m_curUserID.clear(); } // delete entry from vector m_userVec.erase(iter); ClearOnlineAttributes(); SAFE_DELETE(pEntry->pCurrentProfile); SAFE_DELETE(pEntry->pCurrentPreviewProfile); // delete entry delete pEntry; return true; } //------------------------------------------------------------------------ int CPlayerProfileManager::GetProfileCount(const char* userId) { SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) { return 0; } return pEntry->profileDesc.size(); } //------------------------------------------------------------------------ bool CPlayerProfileManager::GetProfileInfo(const char* userId, int index, IPlayerProfileManager::SProfileDescription& outInfo) { if (!m_bInitialized) { return false; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) { GameWarning("[PlayerProfiles] GetProfileInfo: User '%s' not logged in", userId); return false; } int count = pEntry->profileDesc.size(); if (index >= count) { assert (index < count); return false; } SLocalProfileInfo& info = pEntry->profileDesc[index]; outInfo.name = info.GetName().c_str(); outInfo.lastLoginTime = info.GetLastLoginTime(); return true; } //------------------------------------------------------------------------ void CPlayerProfileManager::SetProfileLastLoginTime(const char* userId, int index, time_t lastLoginTime) { if (!m_bInitialized) { return; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) { GameWarning("[PlayerProfiles] GetProfileInfo: User '%s' not logged in", userId); return; } int count = pEntry->profileDesc.size(); if (index >= count) { assert (index < count); return; } SLocalProfileInfo& info = pEntry->profileDesc[index]; info.SetLastLoginTime(lastLoginTime); } //------------------------------------------------------------------------ bool CPlayerProfileManager::CreateProfile(const char* userId, const char* profileName, bool bOverride, IPlayerProfileManager::EProfileOperationResult& result) { if (!m_bInitialized) { result = ePOR_NotInitialized; return false; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) { GameWarning("[PlayerProfiles] CreateProfile: User '%s' not logged in", userId); result = ePOR_UserNotLoggedIn; return false; } SLocalProfileInfo* pInfo = GetLocalProfileInfo(pEntry, profileName); if (pInfo != 0 && !bOverride) // profile with this name already exists { GameWarning("[PlayerProfiles] CreateProfile: User '%s' already has a profile with name '%s'", userId, profileName); result = ePOR_NameInUse; return false; } result = ePOR_Unknown; bool ok = true; if (pEntry->pCurrentProfile == 0) { // save the default profile ok = m_pImpl->SaveProfile(pEntry, m_pDefaultProfile, profileName, bOverride); } if (ok) { result = ePOR_Success; if (pInfo == 0) // if we override, it's already present { SLocalProfileInfo info (profileName); time_t lastPlayTime; time(&lastPlayTime); info.SetLastLoginTime(lastPlayTime); pEntry->profileDesc.push_back(info); // create default profile by copying/saving factory default ok = m_pImpl->SaveProfile(pEntry, m_pDefaultProfile, profileName); if (!ok) { pEntry->profileDesc.pop_back(); result = ePOR_Unknown; } } } if (!ok) { GameWarning("[PlayerProfiles] CreateProfile: User '%s' cannot create profile '%s'", userId, profileName); } return ok; } //------------------------------------------------------------------------ bool CPlayerProfileManager::DeleteProfile(const char* userId, const char* profileName, IPlayerProfileManager::EProfileOperationResult& result) { if (!m_bInitialized) { result = ePOR_NotInitialized; return false; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) { GameWarning("[PlayerProfiles] DeleteProfile: User '%s' not logged in", userId); result = ePOR_UserNotLoggedIn; return false; } // cannot delete last profile if (pEntry->profileDesc.size() <= 1) { GameWarning("[PlayerProfiles] DeleteProfile: User '%s' cannot delete last profile", userId); result = ePOR_ProfileInUse; return false; } // make sure there is such a profile std::vector<SLocalProfileInfo>::iterator iter; SLocalProfileInfo* info = GetLocalProfileInfo(pEntry, profileName, iter); if (info) { bool ok = m_pImpl->DeleteProfile(pEntry, profileName); if (ok) { pEntry->profileDesc.erase(iter); // if the profile was the current profile, delete it if (pEntry->pCurrentProfile != 0 && azstricmp(profileName, pEntry->pCurrentProfile->GetName()) == 0) { delete pEntry->pCurrentProfile; pEntry->pCurrentProfile = 0; // TODO: Maybe auto-select a profile } result = ePOR_Success; return true; } result = ePOR_Unknown; } else { result = ePOR_NoSuchProfile; } return false; } //------------------------------------------------------------------------ bool CPlayerProfileManager::RenameProfile(const char* userId, const char* newName, IPlayerProfileManager::EProfileOperationResult& result) { if (!m_bInitialized) { result = ePOR_NotInitialized; return false; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) { GameWarning("[PlayerProfiles] RenameProfile: User '%s' not logged in", userId); result = ePOR_UserNotLoggedIn; return false; } // make sure there is no such profile if (GetLocalProfileInfo(pEntry, newName) != 0) { result = ePOR_NoSuchProfile; return false; } // can only rename current active profile if (pEntry->pCurrentProfile == 0) { result = ePOR_NoActiveProfile; return false; } if (azstricmp(pEntry->pCurrentProfile->GetName(), PLAYER_DEFAULT_PROFILE_NAME) == 0) { GameWarning("[PlayerProfiles] RenameProfile: User '%s' cannot rename default profile", userId); result = ePOR_DefaultProfile; return false; } result = ePOR_Unknown; bool ok = m_pImpl->RenameProfile(pEntry, newName); if (ok) { // assign a new name in the info DB SLocalProfileInfo* info = GetLocalProfileInfo(pEntry, pEntry->pCurrentProfile->GetName()); info->SetName(newName); // assign a new name in the profile itself pEntry->pCurrentProfile->SetName(newName); result = ePOR_Success; } else { GameWarning("[PlayerProfiles] RenameProfile: Failed to rename profile to '%s' for user '%s' ", newName, userId); } return ok; } //------------------------------------------------------------------------ bool CPlayerProfileManager::SaveProfile(const char* userId, IPlayerProfileManager::EProfileOperationResult& result, unsigned int reason) { EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaving); if (!m_bInitialized) { result = ePOR_NotInitialized; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaveFailure, AZ::ProfileSaveLoadError::SystemNotInitialized); return false; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) { GameWarning("[PlayerProfiles] SaveProfile: User '%s' not logged in", userId); result = ePOR_UserNotLoggedIn; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaveFailure, AZ::ProfileSaveLoadError::UserNotLoggedIn); return false; } if (pEntry->pCurrentProfile == 0) { GameWarning("[PlayerProfiles] SaveProfile: Profile for '%s' not active", userId); result = ePOR_NoActiveProfile; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaveFailure, AZ::ProfileSaveLoadError::ProfileNotActive); return false; } if (m_loadingProfile || m_savingProfile) { result = ePOR_LoadingProfile; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaveFailure, AZ::ProfileSaveLoadError::AnotherOperationInProgress); return false; } else { m_savingProfile = true; } result = ePOR_Success; // notify game systems that the profile is about to be saved const int listenerSize = m_listeners.size(); for (int i = 0; i < listenerSize; i++) { m_listeners[i]->SaveToProfile(pEntry->pCurrentProfile, false, reason); } bool ok = m_pImpl->SaveProfile(pEntry, pEntry->pCurrentProfile, pEntry->pCurrentProfile->GetName()); if (!ok) { GameWarning("[PlayerProfiles] SaveProfile: User '%s' cannot save profile '%s'", userId, pEntry->pCurrentProfile->GetName()); result = ePOR_Unknown; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaveFailure, AZ::ProfileSaveLoadError::Unknown); } m_savingProfile = false; if (ok) { EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaved); } return ok; } //------------------------------------------------------------------------ bool CPlayerProfileManager::SaveInactiveProfile(const char* userId, const char* profileName, EProfileOperationResult& result, unsigned int reason) { EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaving); if (!m_bInitialized) { result = ePOR_NotInitialized; return false; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) { GameWarning("[PlayerProfiles] SaveProfile: User '%s' not logged in", userId); result = ePOR_UserNotLoggedIn; return false; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaveFailure, AZ::ProfileSaveLoadError::UserNotLoggedIn); } CPlayerProfile* pProfile = profileName ? new CPlayerProfile(this, profileName, userId, false) : 0; if (!pProfile || !LoadProfile(pEntry, pProfile, profileName, true)) { result = ePOR_NoSuchProfile; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaveFailure, AZ::ProfileSaveLoadError::ProfileNotActive); return false; } result = ePOR_Success; // notify game systems that the profile is about to be saved const int listenerSize = m_listeners.size(); for (int i = 0; i < listenerSize; i++) { m_listeners[i]->SaveToProfile(pProfile, false, reason); } bool ok = m_pImpl->SaveProfile(pEntry, pProfile, pProfile->GetName()); if (!ok) { GameWarning("[PlayerProfiles] SaveProfile: User '%s' cannot save profile '%s'", userId, pProfile->GetName()); result = ePOR_Unknown; } delete pProfile; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileSaved); return ok; } //------------------------------------------------------------------------ bool CPlayerProfileManager::IsLoadingProfile() const { return m_loadingProfile; } //------------------------------------------------------------------------ bool CPlayerProfileManager::IsSavingProfile() const { return m_savingProfile; } //------------------------------------------------------------------------ bool CPlayerProfileManager::LoadProfile(SUserEntry* pEntry, CPlayerProfile* pProfile, const char* name, bool bPreview /*false*/) { EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileLoading); if (m_loadingProfile || m_savingProfile) { EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileLoadFailure, AZ::ProfileSaveLoadError::AnotherOperationInProgress); return false; } else { m_loadingProfile = true; } bool ok = m_pImpl->LoadProfile(pEntry, pProfile, name); if (ok && !bPreview) { // notify game systems about the new profile data const int listenerSize = m_listeners.size(); for (int i = 0; i < listenerSize; i++) { m_listeners[i]->LoadFromProfile(pProfile, false, ePR_All); } } else { EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileLoadFailure, AZ::ProfileSaveLoadError::Unknown); } m_loadingProfile = false; EBUS_EVENT(AZ::PlayerProfileNotificationBus, OnProfileLoaded); return ok; } //------------------------------------------------------------------------ const IPlayerProfile* CPlayerProfileManager::PreviewProfile(const char* userId, const char* profileName) { SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] ActivateProfile: User '%s' not logged in", userId); return 0; } // if this is the current profile, do nothing if (pEntry->pCurrentPreviewProfile != 0 && profileName && azstricmp(profileName, pEntry->pCurrentPreviewProfile->GetName()) == 0) { return pEntry->pCurrentPreviewProfile; } if (pEntry->pCurrentPreviewProfile != 0) { delete pEntry->pCurrentPreviewProfile; pEntry->pCurrentPreviewProfile = 0; } if (profileName == 0 || *profileName == '\0') { return 0; } SLocalProfileInfo* info = GetLocalProfileInfo(pEntry, profileName); if (info == 0) // no such profile { GameWarning("[PlayerProfiles] PreviewProfile: User '%s' has no profile '%s'", userId, profileName); return 0; } pEntry->pCurrentPreviewProfile = new CPlayerProfile(this, profileName, userId, true); const bool ok = LoadProfile(pEntry, pEntry->pCurrentPreviewProfile, profileName, true); if (!ok) { GameWarning("[PlayerProfiles] PreviewProfile: User '%s' cannot load profile '%s'", userId, profileName); delete pEntry->pCurrentPreviewProfile; pEntry->pCurrentPreviewProfile = 0; } return pEntry->pCurrentPreviewProfile; } //------------------------------------------------------------------------ IPlayerProfile* CPlayerProfileManager::ActivateProfile(const char* userId, const char* profileName) { SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] ActivateProfile: User '%s' not logged in", userId); return 0; } // if this is the current profile, do nothing if (pEntry->pCurrentProfile != 0 && azstricmp(profileName, pEntry->pCurrentProfile->GetName()) == 0) { return pEntry->pCurrentProfile; } SLocalProfileInfo* info = GetLocalProfileInfo(pEntry, profileName); time_t lastPlayTime; time(&lastPlayTime); if (info == 0) // no such profile { GameWarning("[PlayerProfiles] ActivateProfile: User '%s' has no profile '%s'", userId, profileName); return 0; } info->SetLastLoginTime(lastPlayTime); CPlayerProfile* pNewProfile = new CPlayerProfile(this, profileName, userId, false); gEnv->pGame->SetUserProfileChanged(true); const bool ok = LoadProfile(pEntry, pNewProfile, profileName); if (ok) { delete pEntry->pCurrentProfile; pEntry->pCurrentProfile = pNewProfile; } else { GameWarning("[PlayerProfiles] ActivateProfile: User '%s' cannot load profile '%s'", userId, profileName); delete pNewProfile; } return pEntry->pCurrentProfile; } //------------------------------------------------------------------------ IPlayerProfile* CPlayerProfileManager::GetCurrentProfile(const char* userId) { SUserEntry* pEntry = FindEntry(userId); return pEntry ? pEntry->pCurrentProfile : 0; } //------------------------------------------------------------------------ const char* CPlayerProfileManager::GetCurrentUser() { return m_curUserID.c_str(); } //------------------------------------------------------------------------ int CPlayerProfileManager::GetCurrentUserIndex() { return m_curUserIndex; } void CPlayerProfileManager::SetExclusiveControllerDeviceIndex(unsigned int exclusiveDeviceIndex) { m_exclusiveControllerDeviceIndex = exclusiveDeviceIndex; } unsigned int CPlayerProfileManager::GetExclusiveControllerDeviceIndex() const { return m_exclusiveControllerDeviceIndex; } //------------------------------------------------------------------------ bool CPlayerProfileManager::ResetProfile(const char* userId) { SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] ResetProfile: User '%s' not logged in", userId); return false; } if (pEntry->pCurrentProfile == 0) { return false; } pEntry->pCurrentProfile->Reset(); return true; } //------------------------------------------------------------------------ IPlayerProfile* CPlayerProfileManager::GetDefaultProfile() { return m_pDefaultProfile; } //------------------------------------------------------------------------ CPlayerProfileManager::SUserEntry* CPlayerProfileManager::FindEntry(const char* userId) const { TUserVec::const_iterator iter = m_userVec.begin(); while (iter != m_userVec.end()) { const SUserEntry* pEntry = *iter; if (pEntry->userId.compare(userId) == 0) { return (const_cast<SUserEntry*> (pEntry)); } ++iter; } return 0; } //------------------------------------------------------------------------ CPlayerProfileManager::SUserEntry* CPlayerProfileManager::FindEntry(const char* userId, CPlayerProfileManager::TUserVec::iterator& outIter) { TUserVec::iterator iter = m_userVec.begin(); while (iter != m_userVec.end()) { SUserEntry* pEntry = *iter; if (pEntry->userId.compare(userId) == 0) { outIter = iter; return pEntry; } ++iter; } outIter = iter; return 0; } //------------------------------------------------------------------------ CPlayerProfileManager::SLocalProfileInfo* CPlayerProfileManager::GetLocalProfileInfo(SUserEntry* pEntry, const char* profileName) const { std::vector<SLocalProfileInfo>::iterator iter = pEntry->profileDesc.begin(); while (iter != pEntry->profileDesc.end()) { SLocalProfileInfo& info = *iter; if (info.compare(profileName) == 0) { return &(const_cast<SLocalProfileInfo&> (info)); } ++iter; } return 0; } //------------------------------------------------------------------------ CPlayerProfileManager::SLocalProfileInfo* CPlayerProfileManager::GetLocalProfileInfo(SUserEntry* pEntry, const char* profileName, std::vector<SLocalProfileInfo>::iterator& outIter) const { std::vector<SLocalProfileInfo>::iterator iter = pEntry->profileDesc.begin(); while (iter != pEntry->profileDesc.end()) { SLocalProfileInfo& info = *iter; if (info.compare(profileName) == 0) { outIter = iter; return &(const_cast<SLocalProfileInfo&> (info)); } ++iter; } outIter = iter; return 0; } const char* CPlayerProfileManager::GetCurrentProfileForCurrentUser() { return GetCurrentProfileName(GetCurrentUser()); } const char* CPlayerProfileManager::GetCurrentProfileName(const char* userName) { if (auto* currenProfile = GetCurrentProfile(userName)) { return currenProfile->GetName(); } return CPlayerProfileManager::PLAYER_DEFAULT_PROFILE_NAME; } const char* CPlayerProfileManager::GetCurrentUserName() { return GetCurrentUser(); } bool CPlayerProfileManager::RequestProfileSave(AZ::ProfileSaveReason reason) { EProfileOperationResult saveResult; return SaveProfile(GetCurrentUser(), saveResult, static_cast<unsigned int>(reason)); } bool CPlayerProfileManager::StoreData(const char* dataKey, const void* classPtr, const AZ::Uuid& classId, AZ::SerializeContext* serializeContext) { if (IPlayerProfile* pProfile = GetCurrentProfile(GetCurrentUser())) { if (!serializeContext) { EBUS_EVENT_RESULT(serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); } if (serializeContext) { AZStd::vector<char> buffer; AZ::IO::ByteContainerStream<AZStd::vector<char>> memoryRepresentation = AZ::IO::ByteContainerStream<AZStd::vector<char>>(&buffer); AZ::ObjectStream* objectStream = AZ::ObjectStream::Create(&memoryRepresentation, *serializeContext, AZ::DataStream::StreamType::ST_XML); objectStream->WriteClass(classPtr, classId, nullptr); objectStream->Finalize(); buffer.push_back('\0'); CryStringT<char> stringRepresentationOfData = CryStringT<char>(memoryRepresentation.GetData()->begin()); pProfile->SetAttribute(dataKey, stringRepresentationOfData); return true; } } return false; } bool CPlayerProfileManager::RetrieveData(const char* dataKey, void** outClassPtr, AZ::SerializeContext* serializeContext) { if (IPlayerProfile* pProfile = GetCurrentProfile(GetCurrentUser())) { CryStringT<char> dataAsString; if (pProfile->GetAttribute(dataKey, dataAsString)) { if (!serializeContext) { EBUS_EVENT_RESULT(serializeContext, AZ::ComponentApplicationBus, GetSerializeContext); } AZ::IO::MemoryStream memoryRepresentation(dataAsString.c_str(), dataAsString.length()); AZ::ObjectStream::ClassReadyCB classReadyCallBack = [&outClassPtr](void* classPtr, const AZ::Uuid& classId, AZ::SerializeContext* context) { if (classPtr) { *outClassPtr = classPtr; } }; AZ::ObjectStream::LoadBlocking(&memoryRepresentation, *serializeContext, classReadyCallBack); return true; } } return false; } struct CSaveGameThumbnail : public ISaveGameThumbnail { CSaveGameThumbnail(const string& name) : m_nRefs(0) , m_name(name) { } void AddRef() { ++m_nRefs; } void Release() { if (0 == --m_nRefs) { delete this; } } void GetImageInfo(int& width, int& height, int& depth) { width = m_image.width; height = m_image.height; depth = m_image.depth; } int GetWidth() { return m_image.width; } int GetHeight() { return m_image.height; } int GetDepth() { return m_image.depth; } const uint8* GetImageData() { return m_image.data.begin(); } const char* GetSaveGameName() { return m_name; } CPlayerProfileManager::SThumbnail m_image; string m_name; int m_nRefs; }; // TODO: currently we don't cache thumbnails. // every entry in CPlayerProfileManager::TSaveGameInfoVec could store the thumbnail // or we store ISaveGameThumbailPtr there. // current access pattern (only one thumbnail at a time) doesn't call for optimization/caching // but: maybe store also image format, so we don't need to swap RB class CSaveGameEnumerator : public ISaveGameEnumerator { public: CSaveGameEnumerator(CPlayerProfileManager::IPlatformImpl* pImpl, CPlayerProfileManager::SUserEntry* pEntry) : m_nRefs(0) , m_pImpl(pImpl) , m_pEntry(pEntry) { assert (m_pImpl != 0); assert (m_pEntry != 0); pImpl->GetSaveGames(m_pEntry, m_saveGameInfoVec); } int GetCount() { return m_saveGameInfoVec.size(); } bool GetDescription(int index, SGameDescription& desc) { if (index < 0 || index >= m_saveGameInfoVec.size()) { return false; } CPlayerProfileManager::SSaveGameInfo& info = m_saveGameInfoVec[index]; info.CopyTo(desc); return true; } virtual ISaveGameThumbailPtr GetThumbnail(int index) { if (index >= 0 && index < m_saveGameInfoVec.size()) { ISaveGameThumbailPtr pThumbnail = new CSaveGameThumbnail(m_saveGameInfoVec[index].name); CSaveGameThumbnail* pCThumbnail = static_cast<CSaveGameThumbnail*> (pThumbnail.get()); if (m_pImpl->GetSaveGameThumbnail(m_pEntry, m_saveGameInfoVec[index].name, pCThumbnail->m_image)) { return pThumbnail; } } return 0; } virtual ISaveGameThumbailPtr GetThumbnail(const char* saveGameName) { CPlayerProfileManager::TSaveGameInfoVec::const_iterator iter = m_saveGameInfoVec.begin(); CPlayerProfileManager::TSaveGameInfoVec::const_iterator iterEnd = m_saveGameInfoVec.end(); while (iter != iterEnd) { if (iter->name.compareNoCase(saveGameName) == 0) { ISaveGameThumbailPtr pThumbnail = new CSaveGameThumbnail(iter->name); CSaveGameThumbnail* pCThumbnail = static_cast<CSaveGameThumbnail*> (pThumbnail.get()); if (m_pImpl->GetSaveGameThumbnail(m_pEntry, pCThumbnail->m_name, pCThumbnail->m_image)) { return pThumbnail; } return 0; } ++iter; } return 0; } void AddRef() { ++m_nRefs; } void Release() { if (0 == --m_nRefs) { delete this; } } private: int m_nRefs; CPlayerProfileManager::IPlatformImpl* m_pImpl; CPlayerProfileManager::SUserEntry* m_pEntry; CPlayerProfileManager::TSaveGameInfoVec m_saveGameInfoVec; }; //------------------------------------------------------------------------ ISaveGameEnumeratorPtr CPlayerProfileManager::CreateSaveGameEnumerator(const char* userId, CPlayerProfile* pProfile) { if (!m_bInitialized) { return 0; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] CreateSaveGameEnumerator: User '%s' not logged in", userId); return 0; } if (pEntry->pCurrentProfile == 0 || pEntry->pCurrentProfile != pProfile) { return 0; } return new CSaveGameEnumerator(m_pImpl, pEntry); } //------------------------------------------------------------------------ ISaveGame* CPlayerProfileManager::CreateSaveGame(const char* userId, CPlayerProfile* pProfile) { if (!m_bInitialized) { return 0; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] CreateSaveGame: User '%s' not logged in", userId); return 0; } if (pEntry->pCurrentProfile == 0 || pEntry->pCurrentProfile != pProfile) { return 0; } return m_pImpl->CreateSaveGame(pEntry); } //------------------------------------------------------------------------ ILoadGame* CPlayerProfileManager::CreateLoadGame(const char* userId, CPlayerProfile* pProfile) { if (!m_bInitialized) { return 0; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] CreateLoadGame: User '%s' not logged in", userId); return 0; } if (pEntry->pCurrentProfile == 0 || pEntry->pCurrentProfile != pProfile) { return 0; } return m_pImpl->CreateLoadGame(pEntry); } //------------------------------------------------------------------------ bool CPlayerProfileManager::DeleteSaveGame(const char* userId, CPlayerProfile* pProfile, const char* name) { if (!m_bInitialized) { return false; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] DeleteSaveGame: User '%s' not logged in", userId); return false; } if (pEntry->pCurrentProfile == 0 || pEntry->pCurrentProfile != pProfile) { return false; } return m_pImpl->DeleteSaveGame(pEntry, name); } //------------------------------------------------------------------------ ILevelRotationFile* CPlayerProfileManager::GetLevelRotationFile(const char* userId, CPlayerProfile* pProfile, const char* name) { if (!m_bInitialized) { return 0; } SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] GetLevelRotationFile: User '%s' not logged in", userId); return NULL; } if (pEntry->pCurrentProfile == 0 || pEntry->pCurrentProfile != pProfile) { return NULL; } return m_pImpl->GetLevelRotationFile(pEntry, name); } //------------------------------------------------------------------------ bool CPlayerProfileManager::ResolveAttributeBlock(const char* userId, const char* attrBlockName, IResolveAttributeBlockListener* pListener, int reason) { SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] ResolveAttributeBlock: User '%s' not logged in", userId); if (pListener) { pListener->OnFailure(); } return false; } if (pEntry->pCurrentProfile == NULL) { if (pListener) { pListener->OnFailure(); } return false; } return m_pImpl->ResolveAttributeBlock(pEntry, pEntry->pCurrentProfile, attrBlockName, pListener, reason); } //------------------------------------------------------------------------ bool CPlayerProfileManager::ResolveAttributeBlock(const char* userId, const SResolveAttributeRequest& attrBlockNameRequest, IResolveAttributeBlockListener* pListener, int reason) { SUserEntry* pEntry = FindEntry(userId); if (pEntry == 0) // no such user { GameWarning("[PlayerProfiles] ResolveAttributeBlock: User '%s' not logged in", userId); if (pListener) { pListener->OnFailure(); } return false; } if (pEntry->pCurrentProfile == NULL) { GameWarning("[PlayerProfiles] ResolveAttributeBlock: User '%s' doesn't have a profile", userId); if (pListener) { pListener->OnFailure(); } return false; } return m_pImpl->ResolveAttributeBlock(pEntry, pEntry->pCurrentProfile, attrBlockNameRequest, pListener, reason); } //------------------------------------------------------------------------ void CPlayerProfileManager::SetSharedSaveGameFolder(const char* sharedSaveGameFolder) { m_sharedSaveGameFolder = sharedSaveGameFolder; m_sharedSaveGameFolder.TrimRight("/\\"); } //------------------------------------------------------------------------ void CPlayerProfileManager::AddListener(IPlayerProfileListener* pListener, bool updateNow) { m_listeners.reserve(8); stl::push_back_unique(m_listeners, pListener); if (updateNow) { // allow new listener to init from the current profile if (IPlayerProfile* pCurrentProfile = GetCurrentProfile(GetCurrentUser())) { pListener->LoadFromProfile(pCurrentProfile, false, ePR_All); } } } //------------------------------------------------------------------------ void CPlayerProfileManager::RemoveListener(IPlayerProfileListener* pListener) { stl::find_and_erase(m_listeners, pListener); } //------------------------------------------------------------------------ void CPlayerProfileManager::AddOnlineAttributesListener(IOnlineAttributesListener* pListener) { CRY_ASSERT_MESSAGE(m_onlineAttributesListener == NULL, "PlayerProfileManager only handles a single OnlineAttributes Listener"); m_onlineAttributesListener = pListener; } //------------------------------------------------------------------------ void CPlayerProfileManager::RemoveOnlineAttributesListener(IOnlineAttributesListener* pListener) { CRY_ASSERT_MESSAGE(m_onlineAttributesListener == pListener, "Can't remove listener that hasn't been added!"); if (m_onlineAttributesListener == pListener) { m_onlineAttributesListener = NULL; } } //------------------------------------------------------------------------ void CPlayerProfileManager::SetOnlineAttributesState(const IOnlineAttributesListener::EEvent event, const IOnlineAttributesListener::EState newState) { if (m_onlineAttributesState[event] != newState) { m_onlineAttributesState[event] = newState; SendOnlineAttributeState(event, newState); } } //------------------------------------------------------------------------ void CPlayerProfileManager::SendOnlineAttributeState(const IOnlineAttributesListener::EEvent event, const IOnlineAttributesListener::EState newState) { if (m_onlineAttributesListener) { m_onlineAttributesListener->OnlineAttributeState(event, newState); } } //------------------------------------------------------------------------ void CPlayerProfileManager::GetOnlineAttributesState(const IOnlineAttributesListener::EEvent event, IOnlineAttributesListener::EState& state) const { CRY_ASSERT(event > IOnlineAttributesListener::eOAE_Invalid && event < IOnlineAttributesListener::eOAE_Max); state = m_onlineAttributesState[event]; } //------------------------------------------------------------------------ void CPlayerProfileManager::EnableOnlineAttributes(bool enable) { m_enableOnlineAttributes = enable; } //------------------------------------------------------------------------ // if saving and loading online is enabled bool CPlayerProfileManager::HasEnabledOnlineAttributes() const { return m_enableOnlineAttributes; } //------------------------------------------------------------------------ // if saving and loading online is possible bool CPlayerProfileManager::CanProcessOnlineAttributes() const { return m_allowedToProcessOnlineAttributes; } //------------------------------------------------------------------------ // whether the game is in a state that it can save/load online attributes - e.g. when in a mp game session is in progress saving online is disabled void CPlayerProfileManager::SetCanProcessOnlineAttributes(bool enable) { m_allowedToProcessOnlineAttributes = enable; } //------------------------------------------------------------------------ bool CPlayerProfileManager::IsOnlineOnlyAttribute(const char* name) { if (m_enableOnlineAttributes && m_registered) { TOnlineAttributeMap::const_iterator end = m_onlineAttributeMap.end(); TOnlineAttributeMap::const_iterator attr = m_onlineAttributeMap.find(name); if (attr != end) { uint32 index = attr->second; CRY_ASSERT(index >= 0 && index <= m_onlineDataCount); return m_onlineOnlyData[index]; } } return false; } //------------------------------------------------------------------------ bool CPlayerProfileManager::RegisterOnlineAttributes() { return true; } //------------------------------------------------------------------------ bool CPlayerProfileManager::RegisterOnlineAttribute(const char* name, const char* type, const bool onlineOnly, const SCryLobbyUserData& defaultValue, CCrc32& crc) { return true; } //------------------------------------------------------------------------ bool CPlayerProfileManager::SetUserDataType(SCryLobbyUserData* data, const char* type) { return true; } //------------------------------------------------------------------------ void CPlayerProfileManager::GetDefaultValue(const char* type, XmlNodeRef attributeNode, SCryLobbyUserData* pOutData) { } //------------------------------------------------------------------------ void CPlayerProfileManager::LoadOnlineAttributes(IPlayerProfile* pProfile) { } //------------------------------------------------------------------------ void CPlayerProfileManager::SaveOnlineAttributes(IPlayerProfile* pProfile) { } void CPlayerProfileManager::ClearOnlineAttributes() { } void CPlayerProfileManager::LoadGamerProfileDefaults(IPlayerProfile* pProfile) { CPlayerProfile* pDefaultProfile = m_pDefaultProfile; m_pDefaultProfile = NULL; pProfile->LoadGamerProfileDefaults(); m_pDefaultProfile = pDefaultProfile; } void CPlayerProfileManager::ReloadProfile(IPlayerProfile* pProfile, unsigned int reason) { TListeners::const_iterator it = m_listeners.begin(), itend = m_listeners.end(); for (; it != itend; ++it) { (*it)->LoadFromProfile(pProfile, false, reason); } } void CPlayerProfileManager::SetOnlineAttributes(IPlayerProfile* pProfile, const SCryLobbyUserData* pData, const int32 onlineDataCount) { CRY_ASSERT(pProfile); if (pProfile) { ReadOnlineAttributes(pProfile, pData, onlineDataCount); } } //------------------------------------------------------------------------ uint32 CPlayerProfileManager::GetOnlineAttributes(SCryLobbyUserData* pData, uint32 numData) { return 0; } //------------------------------------------------------------------------ uint32 CPlayerProfileManager::GetDefaultOnlineAttributes(SCryLobbyUserData* pData, uint32 numData) { return 0; } //------------------------------------------------------------------------ bool CPlayerProfileManager::SetUserData(SCryLobbyUserData* data, const TFlowInputData& value) { return true; } //------------------------------------------------------------------------ bool CPlayerProfileManager::ReadUserData(const SCryLobbyUserData* data, TFlowInputData& val) { return true; } //------------------------------------------------------------------------ uint32 CPlayerProfileManager::UserDataSize(const SCryLobbyUserData* data) { return 0; } //static------------------------------------------------------------------------ void CPlayerProfileManager::ReadUserDataCallback(CryLobbyTaskID taskID, ECryLobbyError error, SCryLobbyUserData* pData, uint32 numData, void* pArg) { } //----------------------------------------------------------------------------- void CPlayerProfileManager::ReadOnlineAttributes(IPlayerProfile* pProfile, const SCryLobbyUserData* pData, const uint32 numData) { } //------------------------------------------------------------------------ int CPlayerProfileManager::GetOnlineAttributesVersion() const { return m_onlineAttributeAutoGeneratedVersion + m_onlineAttributeDefinedVersion; } //------------------------------------------------------------------------ int CPlayerProfileManager::GetOnlineAttributeIndexByName(const char* name) { TOnlineAttributeMap::const_iterator end = m_onlineAttributeMap.end(); TOnlineAttributeMap::const_iterator versionIter = m_onlineAttributeMap.find(name); int index = -1; if (versionIter != end) { index = versionIter->second; } return index; } //------------------------------------------------------------------------ void CPlayerProfileManager::GetOnlineAttributesDataFormat(SCryLobbyUserData* pData, uint32 numData) { } //------------------------------------------------------------------------ uint32 CPlayerProfileManager::GetOnlineAttributeCount() { return m_onlineDataCount; } //------------------------------------------------------------------------ int CPlayerProfileManager::ChecksumConvertValueToInt(const SCryLobbyUserData* pData) { return 0; } //------------------------------------------------------------------------ void CPlayerProfileManager::ApplyChecksums(SCryLobbyUserData* pData, uint32 numData) { } //------------------------------------------------------------------------ bool CPlayerProfileManager::ValidChecksums(const SCryLobbyUserData* pData, uint32 numData) { return true; } //------------------------------------------------------------------------ int CPlayerProfileManager::Checksum(const int checksum, const SCryLobbyUserData* pData, uint32 numData) { return 0; } //------------------------------------------------------------------------ int CPlayerProfileManager::ChecksumHash(const int seed, const int value) const { int hash = seed + value; hash += (hash << 10); hash ^= (hash >> 6); hash += (hash << 3); return hash; } //------------------------------------------------------------------------ int CPlayerProfileManager::ChecksumHash(const int value0, const int value1, const int value2, const int value3, const int value4) const { uint32 a = (uint32) value0; uint32 b = (uint32) value1; uint32 c = (uint32) value2; uint32 d = (uint32) value3; uint32 e = (uint32) value4; for (int i = 0; i < 16; i++) { a += (e >> 11); b += (a ^ d); c += (b << 3); d ^= (c >> 5); e += (d + 233); } return a + b + c + d + e; } //static------------------------------------------------------------------------ void CPlayerProfileManager::RegisterUserDataCallback(CryLobbyTaskID taskID, ECryLobbyError error, void* pArg) { } //static------------------------------------------------------------------------ void CPlayerProfileManager::WriteUserDataCallback(CryLobbyTaskID taskID, ECryLobbyError error, void* pArg) { } #if PROFILE_DEBUG_COMMANDS //static------------------------------------------------------------------------ void CPlayerProfileManager::DbgLoadProfile(IConsoleCmdArgs* args) { CPlayerProfileManager* pPlayerProfMan = (CPlayerProfileManager*) CCryAction::GetCryAction()->GetIPlayerProfileManager(); CryLogAlways("Loading profile '%s'", pPlayerProfMan->GetCurrentUser()); SUserEntry* pEntry = pPlayerProfMan->FindEntry(pPlayerProfMan->GetCurrentUser()); CPlayerProfile* pProfile = (CPlayerProfile*) pPlayerProfMan->GetCurrentProfile(pPlayerProfMan->GetCurrentUser()); pPlayerProfMan->LoadProfile(pEntry, pProfile, pPlayerProfMan->GetCurrentUser()); } //static------------------------------------------------------------------------ void CPlayerProfileManager::DbgSaveProfile(IConsoleCmdArgs* args) { CPlayerProfileManager* pPlayerProfMan = (CPlayerProfileManager*) CCryAction::GetCryAction()->GetIPlayerProfileManager(); CryLogAlways("Saving profile '%s'", pPlayerProfMan->GetCurrentUser()); EProfileOperationResult result; pPlayerProfMan->SaveProfile(pPlayerProfMan->GetCurrentUser(), result, ePR_All); CryLogAlways("Result %d", result); } //static------------------------------------------------------------------------ void CPlayerProfileManager::DbgLoadOnlineAttributes(IConsoleCmdArgs* args) { CPlayerProfileManager* pPlayerProfMan = (CPlayerProfileManager*) CCryAction::GetCryAction()->GetIPlayerProfileManager(); CPlayerProfile* pProfile = (CPlayerProfile*) pPlayerProfMan->GetCurrentProfile(pPlayerProfMan->GetCurrentUser()); CryLogAlways("%s", pProfile->GetName()); pPlayerProfMan->LoadOnlineAttributes(pProfile); } //static------------------------------------------------------------------------ void CPlayerProfileManager::DbgSaveOnlineAttributes(IConsoleCmdArgs* args) { CPlayerProfileManager* pPlayerProfMan = (CPlayerProfileManager*) CCryAction::GetCryAction()->GetIPlayerProfileManager(); CPlayerProfile* pProfile = (CPlayerProfile*) pPlayerProfMan->GetCurrentProfile(pPlayerProfMan->GetCurrentUser()); CryLogAlways("%s", pProfile->GetName()); pPlayerProfMan->SaveOnlineAttributes(pProfile); } //static------------------------------------------------------------------------ void CPlayerProfileManager::DbgTestOnlineAttributes(IConsoleCmdArgs* args) { CPlayerProfileManager* pPlayerProfMan = (CPlayerProfileManager*) CCryAction::GetCryAction()->GetIPlayerProfileManager(); if (pPlayerProfMan->m_enableOnlineAttributes) { if (pPlayerProfMan->m_registered) { CryLogAlways("---Testing Phase %d---", pPlayerProfMan->m_testingPhase); switch (pPlayerProfMan->m_testingPhase) { case 0: { CryLogAlways("Version %d", pPlayerProfMan->GetOnlineAttributesVersion()); CryLogAlways("DefinedVersion %d", pPlayerProfMan->m_onlineAttributeDefinedVersion); CryLogAlways("AutoVersion %d", pPlayerProfMan->m_onlineAttributeAutoGeneratedVersion); CryLogAlways("OnlineDataCount %d/%d", pPlayerProfMan->m_onlineDataCount, pPlayerProfMan->k_maxOnlineDataCount); CryLogAlways("OnlineDataBytes %d/%d", pPlayerProfMan->m_onlineDataByteCount, pPlayerProfMan->k_maxOnlineDataBytes); pPlayerProfMan->m_testingPhase = 1; DbgSaveOnlineAttributes(args); } break; case 1: { CryLogAlways("Saved Online Data!"); CryLogAlways("Copying Profile FlowData"); int arrayIndex = 0; CPlayerProfile* pProfile = (CPlayerProfile*) pPlayerProfMan->GetCurrentProfile(pPlayerProfMan->GetCurrentUser()); TOnlineAttributeMap::const_iterator end = pPlayerProfMan->m_onlineAttributeMap.end(); TOnlineAttributeMap::const_iterator iter = pPlayerProfMan->m_onlineAttributeMap.begin(); while (iter != end) { TFlowInputData inputData; pProfile->GetAttribute(iter->first.c_str(), inputData); int inputIntData; inputData.GetValueWithConversion(inputIntData); pPlayerProfMan->m_testFlowData[arrayIndex] = inputIntData; arrayIndex++; ++iter; } pPlayerProfMan->m_testingPhase = 2; DbgLoadOnlineAttributes(args); } break; case 2: { CryLogAlways("Checking Profile FlowData"); int arrayIndex = 0; CPlayerProfile* pProfile = (CPlayerProfile*) pPlayerProfMan->GetCurrentProfile(pPlayerProfMan->GetCurrentUser()); TOnlineAttributeMap::const_iterator end = pPlayerProfMan->m_onlineAttributeMap.end(); TOnlineAttributeMap::const_iterator iter = pPlayerProfMan->m_onlineAttributeMap.begin(); while (iter != end) { if (iter->second >= k_onlineChecksums) { TFlowInputData data; pProfile->GetAttribute(iter->first.c_str(), data); int intValue = -1; data.GetValueWithConversion(intValue); if (pPlayerProfMan->m_testFlowData[arrayIndex] != intValue) { CryLogAlways("Non-matching Flow Data! FAILED!!!!!"); pPlayerProfMan->m_testingPhase = 0; return; } } arrayIndex++; ++iter; } CryLogAlways("Complete Success!!!!!"); pPlayerProfMan->m_testingPhase = 0; return; } break; } } else { CryLogAlways("Online Attributes aren't not registered"); } } else { CryLogAlways("Online Attributes aren't not enabled"); } } #endif //----------------------------------------------------------------------------- // FIXME: need something in crysystem or crypak to move files or directories #if defined(WIN32) || defined(WIN64) #include "CryWindows.h" bool CPlayerProfileManager::MoveFileHelper(const char* existingFileName, const char* newFileName) { char oldPath[ICryPak::g_nMaxPath]; char newPath[ICryPak::g_nMaxPath]; // need to adjust aliases and paths (use FLAGS_FOR_WRITING) gEnv->pCryPak->AdjustFileName(existingFileName, oldPath, AZ_ARRAY_SIZE(oldPath), ICryPak::FLAGS_FOR_WRITING); gEnv->pCryPak->AdjustFileName(newFileName, newPath, AZ_ARRAY_SIZE(newPath), ICryPak::FLAGS_FOR_WRITING); return ::MoveFile(oldPath, newPath) != 0; } #else // on all other platforms, just a warning bool CPlayerProfileManager::MoveFileHelper(const char* existingFileName, const char* newFileName) { char oldPath[ICryPak::g_nMaxPath]; gEnv->pCryPak->AdjustFileName(existingFileName, oldPath, AZ_ARRAY_SIZE(oldPath), ICryPak::FLAGS_FOR_WRITING); string msg; msg.Format("CPlayerProfileManager::MoveFileHelper for this Platform not implemented yet.\nOriginal '%s' will be lost!", oldPath); CRY_ASSERT_MESSAGE(0, msg.c_str()); GameWarning(msg.c_str()); return false; } #endif void CPlayerProfileManager::GetMemoryStatistics(ICrySizer* s) { SIZER_SUBCOMPONENT_NAME(s, "PlayerProfiles"); s->Add(*this); if (m_pDefaultProfile) { m_pDefaultProfile->GetMemoryStatistics(s); } s->AddContainer(m_userVec); m_pImpl->GetMemoryStatistics(s); s->AddObject(m_curUserID); }
33.346693
204
0.59985
[ "vector" ]
8d2c909bf8933ae144c6366d98ad67eba4c4dcf3
23,747
cc
C++
base/trace_event/trace_config.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2018-01-27T22:40:53.000Z
2018-01-27T22:40:53.000Z
base/trace_event/trace_config.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
1
2016-01-29T00:54:49.000Z
2016-01-29T00:54:49.000Z
base/trace_event/trace_config.cc
eval1749/elang
5208b386ba3a3e866a5c0f0271280f79f9aac8c4
[ "Apache-2.0" ]
null
null
null
// 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 "base/trace_event/trace_config.h" #include <utility> #include "base/json/json_reader.h" #include "base/json/json_writer.h" #include "base/strings/pattern.h" #include "base/strings/string_split.h" #include "base/strings/string_tokenizer.h" #include "base/strings/stringprintf.h" #include "base/trace_event/memory_dump_manager.h" #include "base/trace_event/memory_dump_request_args.h" #include "base/trace_event/trace_event.h" namespace base { namespace trace_event { namespace { // String options that can be used to initialize TraceOptions. const char kRecordUntilFull[] = "record-until-full"; const char kRecordContinuously[] = "record-continuously"; const char kRecordAsMuchAsPossible[] = "record-as-much-as-possible"; const char kTraceToConsole[] = "trace-to-console"; const char kEnableSampling[] = "enable-sampling"; const char kEnableSystrace[] = "enable-systrace"; const char kEnableArgumentFilter[] = "enable-argument-filter"; // String parameters that can be used to parse the trace config string. const char kRecordModeParam[] = "record_mode"; const char kEnableSamplingParam[] = "enable_sampling"; const char kEnableSystraceParam[] = "enable_systrace"; const char kEnableArgumentFilterParam[] = "enable_argument_filter"; const char kIncludedCategoriesParam[] = "included_categories"; const char kExcludedCategoriesParam[] = "excluded_categories"; const char kSyntheticDelaysParam[] = "synthetic_delays"; const char kSyntheticDelayCategoryFilterPrefix[] = "DELAY("; // String parameters that is used to parse memory dump config in trace config // string. const char kMemoryDumpConfigParam[] = "memory_dump_config"; const char kTriggersParam[] = "triggers"; const char kPeriodicIntervalParam[] = "periodic_interval_ms"; const char kModeParam[] = "mode"; // Default configuration of memory dumps. const TraceConfig::MemoryDumpTriggerConfig kDefaultHeavyMemoryDumpTrigger = { 2000, // periodic_interval_ms MemoryDumpLevelOfDetail::DETAILED}; const TraceConfig::MemoryDumpTriggerConfig kDefaultLightMemoryDumpTrigger = { 250, // periodic_interval_ms MemoryDumpLevelOfDetail::LIGHT}; class ConvertableTraceConfigToTraceFormat : public base::trace_event::ConvertableToTraceFormat { public: explicit ConvertableTraceConfigToTraceFormat(const TraceConfig& trace_config) : trace_config_(trace_config) {} void AppendAsTraceFormat(std::string* out) const override { out->append(trace_config_.ToString()); } protected: ~ConvertableTraceConfigToTraceFormat() override {} private: const TraceConfig trace_config_; }; } // namespace TraceConfig::TraceConfig() { InitializeDefault(); } TraceConfig::TraceConfig(const std::string& category_filter_string, const std::string& trace_options_string) { InitializeFromStrings(category_filter_string, trace_options_string); } TraceConfig::TraceConfig(const std::string& category_filter_string, TraceRecordMode record_mode) { std::string trace_options_string; switch (record_mode) { case RECORD_UNTIL_FULL: trace_options_string = kRecordUntilFull; break; case RECORD_CONTINUOUSLY: trace_options_string = kRecordContinuously; break; case RECORD_AS_MUCH_AS_POSSIBLE: trace_options_string = kRecordAsMuchAsPossible; break; case ECHO_TO_CONSOLE: trace_options_string = kTraceToConsole; break; default: NOTREACHED(); } InitializeFromStrings(category_filter_string, trace_options_string); } TraceConfig::TraceConfig(const std::string& config_string) { if (!config_string.empty()) InitializeFromConfigString(config_string); else InitializeDefault(); } TraceConfig::TraceConfig(const TraceConfig& tc) : record_mode_(tc.record_mode_), enable_sampling_(tc.enable_sampling_), enable_systrace_(tc.enable_systrace_), enable_argument_filter_(tc.enable_argument_filter_), memory_dump_config_(tc.memory_dump_config_), included_categories_(tc.included_categories_), disabled_categories_(tc.disabled_categories_), excluded_categories_(tc.excluded_categories_), synthetic_delays_(tc.synthetic_delays_) {} TraceConfig::~TraceConfig() { } TraceConfig& TraceConfig::operator=(const TraceConfig& rhs) { if (this == &rhs) return *this; record_mode_ = rhs.record_mode_; enable_sampling_ = rhs.enable_sampling_; enable_systrace_ = rhs.enable_systrace_; enable_argument_filter_ = rhs.enable_argument_filter_; memory_dump_config_ = rhs.memory_dump_config_; included_categories_ = rhs.included_categories_; disabled_categories_ = rhs.disabled_categories_; excluded_categories_ = rhs.excluded_categories_; synthetic_delays_ = rhs.synthetic_delays_; return *this; } const TraceConfig::StringList& TraceConfig::GetSyntheticDelayValues() const { return synthetic_delays_; } std::string TraceConfig::ToString() const { base::DictionaryValue dict; ToDict(dict); std::string json; base::JSONWriter::Write(dict, &json); return json; } scoped_refptr<ConvertableToTraceFormat> TraceConfig::AsConvertableToTraceFormat() const { return new ConvertableTraceConfigToTraceFormat(*this); } std::string TraceConfig::ToCategoryFilterString() const { std::string filter_string; WriteCategoryFilterString(included_categories_, &filter_string, true); WriteCategoryFilterString(disabled_categories_, &filter_string, true); WriteCategoryFilterString(excluded_categories_, &filter_string, false); WriteCategoryFilterString(synthetic_delays_, &filter_string); return filter_string; } bool TraceConfig::IsCategoryGroupEnabled( const char* category_group_name) const { // TraceLog should call this method only as part of enabling/disabling // categories. bool had_enabled_by_default = false; DCHECK(category_group_name); CStringTokenizer category_group_tokens( category_group_name, category_group_name + strlen(category_group_name), ","); while (category_group_tokens.GetNext()) { std::string category_group_token = category_group_tokens.token(); // Don't allow empty tokens, nor tokens with leading or trailing space. DCHECK(!TraceConfig::IsEmptyOrContainsLeadingOrTrailingWhitespace( category_group_token)) << "Disallowed category string"; if (IsCategoryEnabled(category_group_token.c_str())) { return true; } if (!base::MatchPattern(category_group_token.c_str(), TRACE_DISABLED_BY_DEFAULT("*"))) had_enabled_by_default = true; } // Do a second pass to check for explicitly disabled categories // (those explicitly enabled have priority due to first pass). category_group_tokens.Reset(); bool category_group_disabled = false; while (category_group_tokens.GetNext()) { std::string category_group_token = category_group_tokens.token(); for (StringList::const_iterator ci = excluded_categories_.begin(); ci != excluded_categories_.end(); ++ci) { if (base::MatchPattern(category_group_token.c_str(), ci->c_str())) { // Current token of category_group_name is present in excluded_list. // Flag the exclusion and proceed further to check if any of the // remaining categories of category_group_name is not present in the // excluded_ list. category_group_disabled = true; break; } // One of the category of category_group_name is not present in // excluded_ list. So, if it's not a disabled-by-default category, // it has to be included_ list. Enable the category_group_name // for recording. if (!base::MatchPattern(category_group_token.c_str(), TRACE_DISABLED_BY_DEFAULT("*"))) { category_group_disabled = false; } } // One of the categories present in category_group_name is not present in // excluded_ list. Implies this category_group_name group can be enabled // for recording, since one of its groups is enabled for recording. if (!category_group_disabled) break; } // If the category group is not excluded, and there are no included patterns // we consider this category group enabled, as long as it had categories // other than disabled-by-default. return !category_group_disabled && included_categories_.empty() && had_enabled_by_default; } void TraceConfig::Merge(const TraceConfig& config) { if (record_mode_ != config.record_mode_ || enable_sampling_ != config.enable_sampling_ || enable_systrace_ != config.enable_systrace_ || enable_argument_filter_ != config.enable_argument_filter_) { DLOG(ERROR) << "Attempting to merge trace config with a different " << "set of options."; } // Keep included patterns only if both filters have an included entry. // Otherwise, one of the filter was specifying "*" and we want to honor the // broadest filter. if (HasIncludedPatterns() && config.HasIncludedPatterns()) { included_categories_.insert(included_categories_.end(), config.included_categories_.begin(), config.included_categories_.end()); } else { included_categories_.clear(); } memory_dump_config_.insert(memory_dump_config_.end(), config.memory_dump_config_.begin(), config.memory_dump_config_.end()); disabled_categories_.insert(disabled_categories_.end(), config.disabled_categories_.begin(), config.disabled_categories_.end()); excluded_categories_.insert(excluded_categories_.end(), config.excluded_categories_.begin(), config.excluded_categories_.end()); synthetic_delays_.insert(synthetic_delays_.end(), config.synthetic_delays_.begin(), config.synthetic_delays_.end()); } void TraceConfig::Clear() { record_mode_ = RECORD_UNTIL_FULL; enable_sampling_ = false; enable_systrace_ = false; enable_argument_filter_ = false; included_categories_.clear(); disabled_categories_.clear(); excluded_categories_.clear(); synthetic_delays_.clear(); memory_dump_config_.clear(); } void TraceConfig::InitializeDefault() { record_mode_ = RECORD_UNTIL_FULL; enable_sampling_ = false; enable_systrace_ = false; enable_argument_filter_ = false; excluded_categories_.push_back("*Debug"); excluded_categories_.push_back("*Test"); } void TraceConfig::InitializeFromConfigString(const std::string& config_string) { scoped_ptr<base::Value> value(base::JSONReader::Read(config_string)); if (!value || !value->IsType(base::Value::TYPE_DICTIONARY)) { InitializeDefault(); return; } scoped_ptr<base::DictionaryValue> dict( static_cast<base::DictionaryValue*>(value.release())); record_mode_ = RECORD_UNTIL_FULL; std::string record_mode; if (dict->GetString(kRecordModeParam, &record_mode)) { if (record_mode == kRecordUntilFull) { record_mode_ = RECORD_UNTIL_FULL; } else if (record_mode == kRecordContinuously) { record_mode_ = RECORD_CONTINUOUSLY; } else if (record_mode == kTraceToConsole) { record_mode_ = ECHO_TO_CONSOLE; } else if (record_mode == kRecordAsMuchAsPossible) { record_mode_ = RECORD_AS_MUCH_AS_POSSIBLE; } } bool enable_sampling; if (!dict->GetBoolean(kEnableSamplingParam, &enable_sampling)) enable_sampling_ = false; else enable_sampling_ = enable_sampling; bool enable_systrace; if (!dict->GetBoolean(kEnableSystraceParam, &enable_systrace)) enable_systrace_ = false; else enable_systrace_ = enable_systrace; bool enable_argument_filter; if (!dict->GetBoolean(kEnableArgumentFilterParam, &enable_argument_filter)) enable_argument_filter_ = false; else enable_argument_filter_ = enable_argument_filter; base::ListValue* category_list = nullptr; if (dict->GetList(kIncludedCategoriesParam, &category_list)) SetCategoriesFromIncludedList(*category_list); if (dict->GetList(kExcludedCategoriesParam, &category_list)) SetCategoriesFromExcludedList(*category_list); if (dict->GetList(kSyntheticDelaysParam, &category_list)) SetSyntheticDelaysFromList(*category_list); if (IsCategoryEnabled(MemoryDumpManager::kTraceCategory)) { // If dump triggers not set, the client is using the legacy with just // category enabled. So, use the default periodic dump config. base::DictionaryValue* memory_dump_config = nullptr; if (dict->GetDictionary(kMemoryDumpConfigParam, &memory_dump_config)) SetMemoryDumpConfig(*memory_dump_config); else SetDefaultMemoryDumpConfig(); } } void TraceConfig::InitializeFromStrings( const std::string& category_filter_string, const std::string& trace_options_string) { if (!category_filter_string.empty()) { std::vector<std::string> split = base::SplitString( category_filter_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); std::vector<std::string>::iterator iter; for (iter = split.begin(); iter != split.end(); ++iter) { std::string category = *iter; // Ignore empty categories. if (category.empty()) continue; // Synthetic delays are of the form 'DELAY(delay;option;option;...)'. if (category.find(kSyntheticDelayCategoryFilterPrefix) == 0 && category.at(category.size() - 1) == ')') { category = category.substr( strlen(kSyntheticDelayCategoryFilterPrefix), category.size() - strlen(kSyntheticDelayCategoryFilterPrefix) - 1); size_t name_length = category.find(';'); if (name_length != std::string::npos && name_length > 0 && name_length != category.size() - 1) { synthetic_delays_.push_back(category); } } else if (category.at(0) == '-') { // Excluded categories start with '-'. // Remove '-' from category string. category = category.substr(1); excluded_categories_.push_back(category); } else if (category.compare(0, strlen(TRACE_DISABLED_BY_DEFAULT("")), TRACE_DISABLED_BY_DEFAULT("")) == 0) { disabled_categories_.push_back(category); } else { included_categories_.push_back(category); } } } record_mode_ = RECORD_UNTIL_FULL; enable_sampling_ = false; enable_systrace_ = false; enable_argument_filter_ = false; if(!trace_options_string.empty()) { std::vector<std::string> split = base::SplitString( trace_options_string, ",", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL); std::vector<std::string>::iterator iter; for (iter = split.begin(); iter != split.end(); ++iter) { if (*iter == kRecordUntilFull) { record_mode_ = RECORD_UNTIL_FULL; } else if (*iter == kRecordContinuously) { record_mode_ = RECORD_CONTINUOUSLY; } else if (*iter == kTraceToConsole) { record_mode_ = ECHO_TO_CONSOLE; } else if (*iter == kRecordAsMuchAsPossible) { record_mode_ = RECORD_AS_MUCH_AS_POSSIBLE; } else if (*iter == kEnableSampling) { enable_sampling_ = true; } else if (*iter == kEnableSystrace) { enable_systrace_ = true; } else if (*iter == kEnableArgumentFilter) { enable_argument_filter_ = true; } } } if (IsCategoryEnabled(MemoryDumpManager::kTraceCategory)) { SetDefaultMemoryDumpConfig(); } } void TraceConfig::SetCategoriesFromIncludedList( const base::ListValue& included_list) { included_categories_.clear(); for (size_t i = 0; i < included_list.GetSize(); ++i) { std::string category; if (!included_list.GetString(i, &category)) continue; if (category.compare(0, strlen(TRACE_DISABLED_BY_DEFAULT("")), TRACE_DISABLED_BY_DEFAULT("")) == 0) { disabled_categories_.push_back(category); } else { included_categories_.push_back(category); } } } void TraceConfig::SetCategoriesFromExcludedList( const base::ListValue& excluded_list) { excluded_categories_.clear(); for (size_t i = 0; i < excluded_list.GetSize(); ++i) { std::string category; if (excluded_list.GetString(i, &category)) excluded_categories_.push_back(category); } } void TraceConfig::SetSyntheticDelaysFromList(const base::ListValue& list) { synthetic_delays_.clear(); for (size_t i = 0; i < list.GetSize(); ++i) { std::string delay; if (!list.GetString(i, &delay)) continue; // Synthetic delays are of the form "delay;option;option;...". size_t name_length = delay.find(';'); if (name_length != std::string::npos && name_length > 0 && name_length != delay.size() - 1) { synthetic_delays_.push_back(delay); } } } void TraceConfig::AddCategoryToDict(base::DictionaryValue& dict, const char* param, const StringList& categories) const { if (categories.empty()) return; scoped_ptr<base::ListValue> list(new base::ListValue()); for (StringList::const_iterator ci = categories.begin(); ci != categories.end(); ++ci) { list->AppendString(*ci); } dict.Set(param, std::move(list)); } void TraceConfig::SetMemoryDumpConfig( const base::DictionaryValue& memory_dump_config) { memory_dump_config_.clear(); const base::ListValue* trigger_list = nullptr; if (!memory_dump_config.GetList(kTriggersParam, &trigger_list) || trigger_list->GetSize() == 0) { return; } for (size_t i = 0; i < trigger_list->GetSize(); ++i) { const base::DictionaryValue* trigger = nullptr; if (!trigger_list->GetDictionary(i, &trigger)) continue; MemoryDumpTriggerConfig dump_config; int interval = 0; if (!trigger->GetInteger(kPeriodicIntervalParam, &interval)) { continue; } DCHECK_GT(interval, 0); dump_config.periodic_interval_ms = static_cast<uint32>(interval); std::string level_of_detail_str; trigger->GetString(kModeParam, &level_of_detail_str); dump_config.level_of_detail = StringToMemoryDumpLevelOfDetail(level_of_detail_str); memory_dump_config_.push_back(dump_config); } } void TraceConfig::SetDefaultMemoryDumpConfig() { memory_dump_config_.clear(); memory_dump_config_.push_back(kDefaultHeavyMemoryDumpTrigger); memory_dump_config_.push_back(kDefaultLightMemoryDumpTrigger); } void TraceConfig::ToDict(base::DictionaryValue& dict) const { switch (record_mode_) { case RECORD_UNTIL_FULL: dict.SetString(kRecordModeParam, kRecordUntilFull); break; case RECORD_CONTINUOUSLY: dict.SetString(kRecordModeParam, kRecordContinuously); break; case RECORD_AS_MUCH_AS_POSSIBLE: dict.SetString(kRecordModeParam, kRecordAsMuchAsPossible); break; case ECHO_TO_CONSOLE: dict.SetString(kRecordModeParam, kTraceToConsole); break; default: NOTREACHED(); } if (enable_sampling_) dict.SetBoolean(kEnableSamplingParam, true); else dict.SetBoolean(kEnableSamplingParam, false); if (enable_systrace_) dict.SetBoolean(kEnableSystraceParam, true); else dict.SetBoolean(kEnableSystraceParam, false); if (enable_argument_filter_) dict.SetBoolean(kEnableArgumentFilterParam, true); else dict.SetBoolean(kEnableArgumentFilterParam, false); StringList categories(included_categories_); categories.insert(categories.end(), disabled_categories_.begin(), disabled_categories_.end()); AddCategoryToDict(dict, kIncludedCategoriesParam, categories); AddCategoryToDict(dict, kExcludedCategoriesParam, excluded_categories_); AddCategoryToDict(dict, kSyntheticDelaysParam, synthetic_delays_); if (IsCategoryEnabled(MemoryDumpManager::kTraceCategory)) { scoped_ptr<base::DictionaryValue> memory_dump_config( new base::DictionaryValue()); scoped_ptr<base::ListValue> triggers_list(new base::ListValue()); for (const MemoryDumpTriggerConfig& config : memory_dump_config_) { scoped_ptr<base::DictionaryValue> trigger_dict( new base::DictionaryValue()); trigger_dict->SetInteger(kPeriodicIntervalParam, static_cast<int>(config.periodic_interval_ms)); trigger_dict->SetString( kModeParam, MemoryDumpLevelOfDetailToString(config.level_of_detail)); triggers_list->Append(std::move(trigger_dict)); } // Empty triggers will still be specified explicitly since it means that // the periodic dumps are not enabled. memory_dump_config->Set(kTriggersParam, std::move(triggers_list)); dict.Set(kMemoryDumpConfigParam, std::move(memory_dump_config)); } } std::string TraceConfig::ToTraceOptionsString() const { std::string ret; switch (record_mode_) { case RECORD_UNTIL_FULL: ret = kRecordUntilFull; break; case RECORD_CONTINUOUSLY: ret = kRecordContinuously; break; case RECORD_AS_MUCH_AS_POSSIBLE: ret = kRecordAsMuchAsPossible; break; case ECHO_TO_CONSOLE: ret = kTraceToConsole; break; default: NOTREACHED(); } if (enable_sampling_) ret = ret + "," + kEnableSampling; if (enable_systrace_) ret = ret + "," + kEnableSystrace; if (enable_argument_filter_) ret = ret + "," + kEnableArgumentFilter; return ret; } void TraceConfig::WriteCategoryFilterString(const StringList& values, std::string* out, bool included) const { bool prepend_comma = !out->empty(); int token_cnt = 0; for (StringList::const_iterator ci = values.begin(); ci != values.end(); ++ci) { if (token_cnt > 0 || prepend_comma) StringAppendF(out, ","); StringAppendF(out, "%s%s", (included ? "" : "-"), ci->c_str()); ++token_cnt; } } void TraceConfig::WriteCategoryFilterString(const StringList& delays, std::string* out) const { bool prepend_comma = !out->empty(); int token_cnt = 0; for (StringList::const_iterator ci = delays.begin(); ci != delays.end(); ++ci) { if (token_cnt > 0 || prepend_comma) StringAppendF(out, ","); StringAppendF(out, "%s%s)", kSyntheticDelayCategoryFilterPrefix, ci->c_str()); ++token_cnt; } } bool TraceConfig::IsCategoryEnabled(const char* category_name) const { StringList::const_iterator ci; // Check the disabled- filters and the disabled-* wildcard first so that a // "*" filter does not include the disabled. for (ci = disabled_categories_.begin(); ci != disabled_categories_.end(); ++ci) { if (base::MatchPattern(category_name, ci->c_str())) return true; } if (base::MatchPattern(category_name, TRACE_DISABLED_BY_DEFAULT("*"))) return false; for (ci = included_categories_.begin(); ci != included_categories_.end(); ++ci) { if (base::MatchPattern(category_name, ci->c_str())) return true; } return false; } bool TraceConfig::IsEmptyOrContainsLeadingOrTrailingWhitespace( const std::string& str) { return str.empty() || str.at(0) == ' ' || str.at(str.length() - 1) == ' '; } bool TraceConfig::HasIncludedPatterns() const { return !included_categories_.empty(); } } // namespace trace_event } // namespace base
35.443284
80
0.699667
[ "vector" ]
8d390c2c09cdd2c188c48921077c80168329bd9a
17,065
cpp
C++
Code/Tools/SceneAPI/SceneCore/Containers/SceneManifest.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-09-13T00:01:12.000Z
2021-09-13T00:01:12.000Z
Code/Tools/SceneAPI/SceneCore/Containers/SceneManifest.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Code/Tools/SceneAPI/SceneCore/Containers/SceneManifest.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <SceneAPI/SceneCore/Containers/SceneManifest.h> #include <AzCore/Casting/numeric_cast.h> #include <AzCore/Component/ComponentApplicationBus.h> #include <AzCore/Debug/Trace.h> #include <AzCore/IO/GenericStreams.h> #include <AzCore/IO/Path/Path.h> #include <AzCore/IO/SystemFile.h> #include <AzCore/JSON/rapidjson.h> #include <AzCore/JSON/document.h> #include <AzCore/JSON/prettywriter.h> #include <AzCore/Memory/SystemAllocator.h> #include <AzCore/Serialization/Json/RegistrationContext.h> #include <AzCore/Serialization/Json/JsonSerialization.h> #include <AzCore/Serialization/Json/JsonSerializationResult.h> #include <AzCore/Serialization/Utils.h> #include <AzCore/std/algorithm.h> #include <AzCore/Utils/Utils.h> #include <AzFramework/FileFunc/FileFunc.h> #include <AzFramework/StringFunc/StringFunc.h> #include <AzToolsFramework/Debug/TraceContext.h> #include <SceneAPI/SceneCore/Utilities/Reporting.h> namespace AZ { namespace SceneAPI { namespace Containers { //! Protects from allocating too much memory. The choice of a 5MB threshold is arbitrary. const size_t MaxSceneManifestFileSizeInBytes = 5 * 1024 * 1024; const char ErrorWindowName[] = "SceneManifest"; AZ_CLASS_ALLOCATOR_IMPL(SceneManifest, AZ::SystemAllocator, 0) SceneManifest::~SceneManifest() { } void SceneManifest::Clear() { m_storageLookup.clear(); m_values.clear(); } bool SceneManifest::AddEntry(AZStd::shared_ptr<DataTypes::IManifestObject>&& value) { auto itValue = m_storageLookup.find(value.get()); if (itValue != m_storageLookup.end()) { AZ_TracePrintf(Utilities::WarningWindow, "Manifest Object has already been registered with the manifest."); return false; } Index index = aznumeric_caster(m_values.size()); m_storageLookup[value.get()] = index; m_values.push_back(AZStd::move(value)); AZ_Assert(m_values.size() == m_storageLookup.size(), "SceneManifest values and storage-lookup tables have gone out of lockstep (%i vs %i)", m_values.size(), m_storageLookup.size()); return true; } bool SceneManifest::RemoveEntry(const DataTypes::IManifestObject* const value) { auto storageLookupIt = m_storageLookup.find(value); if (storageLookupIt == m_storageLookup.end()) { AZ_Assert(false, "Value not registered in SceneManifest."); return false; } size_t index = storageLookupIt->second; m_values.erase(m_values.begin() + index); m_storageLookup.erase(storageLookupIt); for (auto& entry : m_storageLookup) { if (entry.second > index) { entry.second--; } } return true; } SceneManifest::Index SceneManifest::FindIndex(const DataTypes::IManifestObject* const value) const { auto it = m_storageLookup.find(value); return it != m_storageLookup.end() ? (*it).second : s_invalidIndex; } bool SceneManifest::LoadFromFile(const AZStd::string& absoluteFilePath, SerializeContext* context) { if (absoluteFilePath.empty()) { AZ_Error(ErrorWindowName, false, "Unable to load Scene Manifest: no file path was provided."); return false; } auto readFileOutcome = Utils::ReadFile(absoluteFilePath, MaxSceneManifestFileSizeInBytes); if (!readFileOutcome.IsSuccess()) { AZ_Error(ErrorWindowName, false, readFileOutcome.GetError().c_str()); return false; } AZStd::string fileContents(readFileOutcome.TakeValue()); // Attempt to read the file as JSON auto loadJsonOutcome = LoadFromString(fileContents, context); if (loadJsonOutcome.IsSuccess()) { return true; } // If JSON parsing failed, try to deserialize with XML auto loadXmlOutcome = LoadFromString(fileContents, context, nullptr, true); AZStd::string fileName; AzFramework::StringFunc::Path::GetFileName(absoluteFilePath.c_str(), fileName); if (loadXmlOutcome.IsSuccess()) { AZ_TracePrintf(ErrorWindowName, "Scene Manifest ( %s ) is using the deprecated XML file format. It will be upgraded to JSON the next time it is modified.\n", fileName.c_str()); return true; } // If both failed, throw an error AZ_Error(ErrorWindowName, false, "Unable to deserialize ( %s ) using JSON or XML. \nJSON reported error: %s\nXML reported error: %s", fileName.c_str(), loadJsonOutcome.GetError().c_str(), loadXmlOutcome.GetError().c_str()); return false; } bool SceneManifest::SaveToFile(const AZStd::string& absoluteFilePath, SerializeContext* context) { AZ_TraceContext(ErrorWindowName, absoluteFilePath); if (absoluteFilePath.empty()) { AZ_Error(ErrorWindowName, false, "Unable to save Scene Manifest: no file path was provided."); return false; } AZStd::string errorMsg = AZStd::string::format("Unable to save Scene Manifest to ( %s ):\n", absoluteFilePath.c_str()); AZ::Outcome<rapidjson::Document, AZStd::string> saveToJsonOutcome = SaveToJsonDocument(context); if (!saveToJsonOutcome.IsSuccess()) { AZ_Error(ErrorWindowName, false, "%s%s", errorMsg.c_str(), saveToJsonOutcome.GetError().c_str()); return false; } AZ::IO::Path fileIoPath(absoluteFilePath); auto saveToFileOutcome = AzFramework::FileFunc::WriteJsonFile(saveToJsonOutcome.GetValue(), fileIoPath); if (!saveToFileOutcome.IsSuccess()) { AZ_Error(ErrorWindowName, false, "%s%s", errorMsg.c_str(), saveToFileOutcome.GetError().c_str()); return false; } return true; } AZStd::shared_ptr<const DataTypes::IManifestObject> SceneManifest::SceneManifestConstDataConverter( const AZStd::shared_ptr<DataTypes::IManifestObject>& value) { return AZStd::shared_ptr<const DataTypes::IManifestObject>(value); } void SceneManifest::Reflect(ReflectContext* context) { SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context); if (serializeContext) { serializeContext->Class<SceneManifest>() ->Version(1, &SceneManifest::VersionConverter) ->Field("values", &SceneManifest::m_values); } BehaviorContext* behaviorContext = azrtti_cast<BehaviorContext*>(context); if (behaviorContext) { behaviorContext->Class<SceneManifest>() ->Attribute(AZ::Script::Attributes::Scope, AZ::Script::Attributes::ScopeFlags::Common) ->Attribute(AZ::Script::Attributes::Module, "scene") ->Method("ImportFromJson", [](SceneManifest& self, AZStd::string_view jsonBuffer) -> bool { auto outcome = self.LoadFromString(jsonBuffer); if (outcome.IsSuccess()) { return true; } AZ_Warning(ErrorWindowName, false, "LoadFromString outcome failure (%s)", outcome.GetError().c_str()); return true; }) ->Method("ExportToJson", [](SceneManifest& self) -> AZStd::string { auto outcome = self.SaveToJsonDocument(); if (outcome.IsSuccess()) { // write the manifest to a UTF-8 string buffer and move return the string rapidjson::StringBuffer sb; rapidjson::Writer<rapidjson::StringBuffer, rapidjson::UTF8<>> writer(sb); rapidjson::Document& document = outcome.GetValue(); document.Accept(writer); return AZStd::move(AZStd::string(sb.GetString())); } AZ_Warning(ErrorWindowName, false, "SaveToJsonDocument outcome failure (%s)", outcome.GetError().c_str()); return {}; }); } } bool SceneManifest::VersionConverter(SerializeContext& context, SerializeContext::DataElementNode& node) { if (node.GetVersion() != 0) { AZ_TracePrintf(ErrorWindowName, "Unable to upgrade SceneManifest from version %i.", node.GetVersion()); return false; } // Copy out the original values. AZStd::vector<SerializeContext::DataElementNode> values; values.reserve(node.GetNumSubElements()); for (int i = 0; i < node.GetNumSubElements(); ++i) { // The old format stored AZStd::pair<AZStd::string, AZStd::shared_ptr<IManifestObjets>>. All this // data is still used, but needs to be move to the new location. The shared ptr needs to be // moved into the new container, while the name needs to be moved to the group name. SerializeContext::DataElementNode& pairNode = node.GetSubElement(i); // This is the original content of the shared ptr. Using the shared pointer directly caused // registration issues so it's extracting the data the shared ptr was storing instead. SerializeContext::DataElementNode& elementNode = pairNode.GetSubElement(1).GetSubElement(0); SerializeContext::DataElementNode& nameNode = pairNode.GetSubElement(0); AZStd::string name; if (nameNode.GetData(name)) { elementNode.AddElementWithData<AZStd::string>(context, "name", name); } // It's better not to set a default name here as the default behaviors will take care of that // will have more information to work with. values.push_back(elementNode); } // Delete old values for (int i = 0; i < node.GetNumSubElements(); ++i) { node.RemoveElement(i); } // Put stored values back int vectorIndex = node.AddElement<ValueStorage>(context, "values"); SerializeContext::DataElementNode& vectorNode = node.GetSubElement(vectorIndex); for (SerializeContext::DataElementNode& value : values) { value.SetName("element"); // Put in a blank shared ptr to be filled with a value stored from "values". int valueIndex = vectorNode.AddElement<ValueStorageType>(context, "element"); SerializeContext::DataElementNode& pointerNode = vectorNode.GetSubElement(valueIndex); // Type doesn't matter as it will be overwritten by the stored value. pointerNode.AddElement<int>(context, "element"); pointerNode.GetSubElement(0) = value; } AZ_TracePrintf(Utilities::WarningWindow, "The SceneManifest has been updated from version %i. It's recommended to save the updated file.", node.GetVersion()); return true; } AZ::Outcome<void, AZStd::string> SceneManifest::LoadFromString(const AZStd::string& fileContents, SerializeContext* context, JsonRegistrationContext* registrationContext, bool loadXml) { Clear(); AZStd::string failureMessage; if (loadXml) { // Attempt to read the stream as XML (old format) // Gems can be removed, causing the setting for manifest objects in the the Gem to not be registered. Instead of failing // to load the entire manifest, just ignore those values. ObjectStream::FilterDescriptor loadFilter(&AZ::Data::AssetFilterNoAssetLoading, ObjectStream::FILTERFLAG_IGNORE_UNKNOWN_CLASSES); if (Utils::LoadObjectFromBufferInPlace<SceneManifest>(fileContents.data(), fileContents.size(), *this, context, loadFilter)) { Init(); return AZ::Success(); } failureMessage = "Unable to load Scene Manifest as XML"; } else { // Attempt to read the stream as JSON auto readJsonOutcome = AzFramework::FileFunc::ReadJsonFromString(fileContents); AZStd::string errorMsg; if (!readJsonOutcome.IsSuccess()) { return AZ::Failure(readJsonOutcome.TakeError()); } rapidjson::Document document = readJsonOutcome.TakeValue(); AZ::JsonDeserializerSettings settings; settings.m_serializeContext = context; settings.m_registrationContext = registrationContext; AZ::JsonSerializationResult::ResultCode jsonResult = AZ::JsonSerialization::Load(*this, document, settings); if (jsonResult.GetProcessing() != AZ::JsonSerializationResult::Processing::Halted) { Init(); return AZ::Success(); } failureMessage = jsonResult.ToString(""); } return AZ::Failure(failureMessage); } AZ::Outcome<rapidjson::Document, AZStd::string> SceneManifest::SaveToJsonDocument(SerializeContext* context, JsonRegistrationContext* registrationContext) { AZ::JsonSerializerSettings settings; settings.m_serializeContext = context; settings.m_registrationContext = registrationContext; rapidjson::Document jsonDocument; auto jsonResult = JsonSerialization::Store(jsonDocument, jsonDocument.GetAllocator(), *this, settings); if (jsonResult.GetProcessing() == AZ::JsonSerializationResult::Processing::Halted) { return AZ::Failure(AZStd::string::format("JSON serialization failed: %s", jsonResult.ToString("").c_str())); } return AZ::Success(AZStd::move(jsonDocument)); } void SceneManifest::Init() { auto end = AZStd::remove_if(m_values.begin(), m_values.end(), [](const ValueStorageType& entry) -> bool { return !entry; }); m_values.erase(end, m_values.end()); for (size_t i = 0; i < m_values.size(); ++i) { Index index = aznumeric_caster(i); m_storageLookup[m_values[i].get()] = index; } } } // Containers } // SceneAPI } // AZ
46.121622
196
0.539525
[ "object", "vector", "3d" ]
8d39f9b065f02997540b3ac3323d9d8e1f4987b8
6,336
hpp
C++
libmarch/include/march/gas/Solver_decl.hpp
j8xixo12/solvcon
a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a
[ "BSD-3-Clause" ]
16
2015-12-09T02:54:42.000Z
2021-04-20T11:26:39.000Z
libmarch/include/march/gas/Solver_decl.hpp
j8xixo12/solvcon
a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a
[ "BSD-3-Clause" ]
95
2015-12-09T00:49:40.000Z
2022-02-14T13:34:55.000Z
libmarch/include/march/gas/Solver_decl.hpp
j8xixo12/solvcon
a8bf3a54d4b1ed91d292e0cdbcb6f2710d33d99a
[ "BSD-3-Clause" ]
13
2015-05-08T04:16:42.000Z
2021-01-15T09:28:06.000Z
#pragma once /* * Copyright (c) 2016, Yung-Yu Chen <yyc@solvcon.net> * BSD 3-Clause License, see COPYING */ #include <cstdint> #include <limits> #include <memory> #include "march/core.hpp" #include "march/mesh.hpp" #include "march/gas/Solution.hpp" namespace march { namespace gas { /** * Parameters for the CESE method. Don't change once set. */ class Parameter { public: using int_type = int32_t; Parameter() = default; Parameter(Parameter const & ) = default; Parameter(Parameter &&) = delete; Parameter & operator=(Parameter const & ) = default; Parameter & operator=(Parameter &&) = delete; real_type sigma0() const { return m_sigma0; } real_type & sigma0() { return m_sigma0; } real_type taumin() const { return m_taumin; } real_type & taumin() { return m_taumin; } real_type tauscale() const { return m_tauscale; } real_type & tauscale() { return m_tauscale; } private: real_type m_sigma0=3; real_type m_taumin=0.0; real_type m_tauscale=1.0; #define DECL_MARCH_DEBUG(TYPE, NAME, DEFAULT) \ public: \ TYPE NAME() const { return m_##NAME; } \ TYPE & NAME() { return m_##NAME; } \ private: \ TYPE m_##NAME = DEFAULT; DECL_MARCH_DEBUG(real_type, stop_on_negative_density, 1.e-50) DECL_MARCH_DEBUG(real_type, stop_on_negative_energy, 1.e-50) DECL_MARCH_DEBUG(bool, stop_on_cfl_adjustment, true) DECL_MARCH_DEBUG(bool, stop_on_cfl_overflow, true) #undef DECL_MARCH_DEBUG_BOOL }; /* end class Parameter */ struct State { using int_type = int32_t; real_type time=0.0; real_type time_increment=0.0; int_type step_current=0; int_type step_global=0; int_type substep_run=2; int_type substep_current=0; int_type report_interval=0; real_type cfl_min=std::numeric_limits<real_type>::quiet_NaN(); real_type cfl_max=std::numeric_limits<real_type>::quiet_NaN(); int_type cfl_nadjusted=-1; int_type cfl_nadjusted_accumulated=-1; std::string step_info_string() const { return string::format("global=%d step=%d substep=%d", step_global, step_current, substep_current); } }; /* end struct State */ template< size_t NDIM > class Quantity; template< size_t NDIM > class TrimBase; template< size_t NDIM > class AnchorChain; template< size_t NDIM > class Solver : public InstanceCounter<Solver<NDIM>> , public std::enable_shared_from_this<Solver<NDIM>> { public: using int_type = State::int_type; using block_type = UnstructuredBlock<NDIM>; using anchor_chain_type = AnchorChain<NDIM>; using vector_type = Vector<NDIM>; using solution_type = Solution<NDIM>; static constexpr size_t ndim = solution_type::ndim; static constexpr size_t neq = solution_type::neq; static constexpr real_type TINY = 1.e-60; static constexpr real_type ALMOST_ZERO = 1.e-200; static constexpr index_type FCMND = block_type::FCMND; static constexpr index_type CLMND = block_type::CLMND; static constexpr index_type CLMFC = block_type::CLMFC; static constexpr index_type FCNCL = block_type::FCNCL; static constexpr index_type FCREL = block_type::FCREL; static constexpr index_type BFREL = block_type::BFREL; class ctor_passkey { ctor_passkey() = default; friend Solver<NDIM>; }; Solver(const ctor_passkey &, const std::shared_ptr<block_type> & block); Solver() = delete; Solver(Solver const & ) = delete; Solver(Solver &&) = delete; Solver & operator=(Solver const & ) = delete; Solver & operator=(Solver &&) = delete; static std::shared_ptr<Solver<NDIM>> construct(const std::shared_ptr<block_type> & block) { return std::make_shared<Solver<NDIM>>(ctor_passkey(), block); } std::shared_ptr<block_type> const & block() const { return m_block; } std::vector<std::unique_ptr<TrimBase<NDIM>>> const & trims() const { return m_trims; } std::vector<std::unique_ptr<TrimBase<NDIM>>> & trims() { return m_trims; } AnchorChain<NDIM> const & anchors() const { return m_anchors; } AnchorChain<NDIM> & anchors() { return m_anchors; } LookupTable<real_type, NDIM> const & cecnd() const { return m_cecnd; } Parameter const & param() const { return m_param; } Parameter & param() { return m_param; } State const & state() const { return m_state; } State & state() { return m_state; } solution_type const & sol() const { return m_sol; } solution_type & sol() { return m_sol; } std::shared_ptr<Quantity<NDIM>> const & qty() const { return m_qty; } /* no setter for m_qty */ std::shared_ptr<Quantity<NDIM>> const & make_qty(bool throw_on_exist=false); // TODO: move to UnstructuredBlock. // @[ void locate_point(const real_type (& crd)[NDIM]) const; // moved to mesh: void prepare_ce(); // moved to mesh: void prepare_sf(); // @] // marching core. // @[ void update(real_type time, real_type time_increment); void calc_so0t(); void calc_so0n(); void trim_do0(); void calc_cfl(); void trim_do1(); void calc_so1n(); // @] void march(real_type time_current, real_type time_increment, int_type steps_run); void init_solution( real_type gas_constant , real_type gamma , real_type density , real_type temperature ); private: void throw_on_negative_density(const char * filename, int lineno, const char * funcname, index_type icl) const; void throw_on_negative_energy(const char * filename, int lineno, const char * funcname, index_type icl) const; void throw_on_cfl_adjustment(const char * filename, int lineno, const char * funcname, index_type icl) const; void throw_on_cfl_overflow(const char * filename, int lineno, const char * funcname, index_type icl) const; private: std::shared_ptr<block_type> m_block; std::vector<std::unique_ptr<TrimBase<NDIM>>> m_trims; AnchorChain<NDIM> m_anchors; LookupTable<real_type, NDIM> m_cecnd; Parameter m_param; State m_state; solution_type m_sol; std::shared_ptr<Quantity<NDIM>> m_qty; }; /* end class Solver */ } /* end namespace gas */ } /* end namespace march */ // vim: set ff=unix fenc=utf8 nobomb et sw=4 ts=4:
30.757282
115
0.676452
[ "mesh", "vector" ]
8d3b9fd80bcc72c34418dd2125a269833a0bdc7e
2,308
cpp
C++
leetcode/417.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
22
2017-08-12T11:56:19.000Z
2022-03-27T10:04:31.000Z
leetcode/417.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
2
2017-12-17T02:52:59.000Z
2018-02-09T02:10:43.000Z
leetcode/417.cpp
yyong119/ACM-OnlineJudge
5871993b15231c6615bfa3e7c2b04f0f6a23e9dc
[ "MIT" ]
4
2017-12-22T15:24:38.000Z
2020-05-18T14:51:16.000Z
class Solution { public: const int actions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}}; vector<vector<int>> pacificAtlantic(vector<vector<int>>& matrix) { // init vector<vector<int>> ans; int n = matrix.size(); if (!n) return ans; int m = matrix[0].size(); if (!m) return ans; bool lu[n][m], rb[n][m]; memset(lu, false, sizeof(lu)); memset(rb, false, sizeof(rb)); // solve left up side vector<int> cur = {0, 0}, next = {0, 0}; queue<vector<int>> q; cur[0] = 0; for (int i = 0; i < m; ++i) { cur[1] = i; q.push(cur); } cur[1] = 0; for (int i = 0; i < n; ++i) { cur[0] = i; q.push(cur); } while(!q.empty()) { cur = q.front(); q.pop(); lu[cur[0]][cur[1]] = true; for (int i = 0; i < 4; ++i) { next[0] = cur[0] + actions[i][0]; next[1] = cur[1] + actions[i][1]; if (next[0] >= 0 && next[0] < n && next[1] >= 0 && next[1] < m && matrix[next[0]][next[1]] >= matrix[cur[0]][cur[1]] && !lu[next[0]][next[1]]) { q.push(next); } } } // solve right bottom side cur[0] = n - 1; for (int i = 0; i < m; ++i) { cur[1] = i; q.push(cur); } cur[1] = m - 1; for (int i = 0; i < n; ++i) { cur[0] = i; q.push(cur); } while(!q.empty()) { cur = q.front(); q.pop(); rb[cur[0]][cur[1]] = true; for (int i = 0; i < 4; ++i) { next[0] = cur[0] + actions[i][0]; next[1] = cur[1] + actions[i][1]; if (next[0] >= 0 && next[0] < n && next[1] >= 0 && next[1] < m && matrix[next[0]][next[1]] >= matrix[cur[0]][cur[1]] && !rb[next[0]][next[1]]) { q.push(next); } } } // compare for (int i = 0; i < n; ++i) for (int j = 0; j < m; ++j) if (lu[i][j] && rb[i][j]) { cur[0] = i; cur[1] = j; ans.push_back(cur); } return ans; } };
33.941176
81
0.35052
[ "vector" ]
8d3d679b4f40e3e5195cf53228e7b8583b0004c5
4,619
hpp
C++
include/crocoddyl/core/solvers/ddp.hpp
Capri2014/crocoddyl
341874fbad4507d6ed4e05e18e4a9cedf5470d01
[ "BSD-3-Clause" ]
1
2020-04-25T13:17:23.000Z
2020-04-25T13:17:23.000Z
include/crocoddyl/core/solvers/ddp.hpp
Capri2014/crocoddyl
341874fbad4507d6ed4e05e18e4a9cedf5470d01
[ "BSD-3-Clause" ]
null
null
null
include/crocoddyl/core/solvers/ddp.hpp
Capri2014/crocoddyl
341874fbad4507d6ed4e05e18e4a9cedf5470d01
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2018-2020, LAAS-CNRS, University of Edinburgh // Copyright note valid unless otherwise stated in individual files. // All rights reserved. /////////////////////////////////////////////////////////////////////////////// #ifndef CROCODDYL_CORE_SOLVERS_DDP_HPP_ #define CROCODDYL_CORE_SOLVERS_DDP_HPP_ #include <Eigen/Cholesky> #include <vector> #include "crocoddyl/core/solver-base.hpp" namespace crocoddyl { class SolverDDP : public SolverAbstract { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW explicit SolverDDP(boost::shared_ptr<ShootingProblem> problem); ~SolverDDP(); virtual bool solve(const std::vector<Eigen::VectorXd>& init_xs = DEFAULT_VECTOR, const std::vector<Eigen::VectorXd>& init_us = DEFAULT_VECTOR, const std::size_t& maxiter = 100, const bool& is_feasible = false, const double& regInit = 1e-9); virtual void computeDirection(const bool& recalc = true); virtual double tryStep(const double& steplength = 1); virtual double stoppingCriteria(); virtual const Eigen::Vector2d& expectedImprovement(); virtual double calc(); virtual void backwardPass(); virtual void forwardPass(const double& stepLength); virtual void computeGains(const std::size_t& t); void increaseRegularization(); void decreaseRegularization(); virtual void allocateData(); const double& get_regfactor() const; const double& get_regmin() const; const double& get_regmax() const; const std::vector<double>& get_alphas() const; const double& get_th_stepdec() const; const double& get_th_stepinc() const; const double& get_th_grad() const; const std::vector<Eigen::MatrixXd>& get_Vxx() const; const std::vector<Eigen::VectorXd>& get_Vx() const; const std::vector<Eigen::MatrixXd>& get_Qxx() const; const std::vector<Eigen::MatrixXd>& get_Qxu() const; const std::vector<Eigen::MatrixXd>& get_Quu() const; const std::vector<Eigen::VectorXd>& get_Qx() const; const std::vector<Eigen::VectorXd>& get_Qu() const; const std::vector<Eigen::MatrixXd>& get_K() const; const std::vector<Eigen::VectorXd>& get_k() const; const std::vector<Eigen::VectorXd>& get_fs() const; void set_regfactor(const double& reg_factor); void set_regmin(const double& regmin); void set_regmax(const double& regmax); void set_alphas(const std::vector<double>& alphas); void set_th_stepdec(const double& th_step); void set_th_stepinc(const double& th_step); void set_th_grad(const double& th_grad); protected: double regfactor_; //!< Regularization factor used to decrease / increase it double regmin_; //!< Minimum allowed regularization value double regmax_; //!< Maximum allowed regularization value double cost_try_; //!< Total cost computed by line-search procedure std::vector<Eigen::VectorXd> xs_try_; //!< State trajectory computed by line-search procedure std::vector<Eigen::VectorXd> us_try_; //!< Control trajectory computed by line-search procedure std::vector<Eigen::VectorXd> dx_; // allocate data std::vector<Eigen::MatrixXd> Vxx_; //!< Hessian of the Value function std::vector<Eigen::VectorXd> Vx_; //!< Gradient of the Value function std::vector<Eigen::MatrixXd> Qxx_; //!< Hessian of the Hamiltonian std::vector<Eigen::MatrixXd> Qxu_; //!< Hessian of the Hamiltonian std::vector<Eigen::MatrixXd> Quu_; //!< Hessian of the Hamiltonian std::vector<Eigen::VectorXd> Qx_; //!< Gradient of the Hamiltonian std::vector<Eigen::VectorXd> Qu_; //!< Gradient of the Hamiltonian std::vector<Eigen::MatrixXd> K_; //!< Feedback gains std::vector<Eigen::VectorXd> k_; //!< Feed-forward terms std::vector<Eigen::VectorXd> fs_; //!< Gaps/defects between shooting nodes Eigen::VectorXd xnext_; Eigen::MatrixXd FxTVxx_p_; std::vector<Eigen::MatrixXd> FuTVxx_p_; Eigen::VectorXd fTVxx_p_; std::vector<Eigen::LLT<Eigen::MatrixXd> > Quu_llt_; std::vector<Eigen::VectorXd> Quuk_; std::vector<double> alphas_; //!< Set of step lengths using by the line-search procedure double th_grad_; //!< Tolerance of the expected gradient used for testing the step double th_stepdec_; //!< Step-length threshold used to decrease regularization double th_stepinc_; //!< Step-length threshold used to increase regularization bool was_feasible_; //!< Label that indicates in the previous iterate was feasible }; } // namespace crocoddyl #endif // CROCODDYL_CORE_SOLVERS_DDP_HPP_
43.990476
116
0.696038
[ "vector" ]
8d3fd86c4dda431ca0d0449fdf5102b74c6904ad
937
cpp
C++
C++/Binary Search Tree Iterator/main.cpp
Leobuaa/LeetCode
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
[ "MIT" ]
2
2016-04-27T11:55:44.000Z
2017-02-06T04:15:46.000Z
C++/Binary Search Tree Iterator/main.cpp
Leobuaa/LeetCode
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
[ "MIT" ]
null
null
null
C++/Binary Search Tree Iterator/main.cpp
Leobuaa/LeetCode
dc2f0fc2d0ddd38e94e71b7a3ffdb75306178a04
[ "MIT" ]
null
null
null
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class BSTIterator { public: BSTIterator(TreeNode *root) { while (root) { sta.push_back(root); root = root->left; } } /** @return whether we have a next smallest number */ bool hasNext() { return !sta.empty(); } /** @return the next smallest number */ int next() { TreeNode *cur = sta.back(); sta.pop_back(); int res = cur->val; cur = cur->right; while (cur) { sta.push_back(cur); cur = cur->left; } return res; } private: vector<TreeNode *> sta; }; /** * Your BSTIterator will be called like this: * BSTIterator i = BSTIterator(root); * while (i.hasNext()) cout << i.next(); */
20.822222
59
0.514408
[ "vector" ]
8d406540724b25dfa6a0188c53318b3cc93c804f
7,344
cpp
C++
Grid.cpp
anthonychoi98/ReverseTetris
948e2791422baa9b17ca7346c44916ba49821207
[ "MIT" ]
null
null
null
Grid.cpp
anthonychoi98/ReverseTetris
948e2791422baa9b17ca7346c44916ba49821207
[ "MIT" ]
null
null
null
Grid.cpp
anthonychoi98/ReverseTetris
948e2791422baa9b17ca7346c44916ba49821207
[ "MIT" ]
null
null
null
#include "Grid.h" #include "Rect.h" Grid::Grid() { // Grid states currentState = chillin; // deleting behavior deletingState = notDeleting; deletingRowIndex = -3; yElements = 20; xElements = 13; rectWidth = 0.14; rectHeight = 0.14; std::vector<std::vector<Rect *>> matrix; gridData = matrix; std::vector<int> td; toDelete = td; resetGrid(); } void Grid::resetGrid() { for (int i = 0; i < yElements; i++) { std::vector<Rect *> aRow; for (int j = 0; j < xElements; j++) { float x = -1.5 + rectWidth * j + 0.006 * j; float y = 1.0 - rectHeight * i - 0.006 * i; // if (i < 1) // { // aRow.push_back(new Rect(x, y, rectWidth, rectHeight, 0.4, 0.9, 0.4)); // } // else // { aRow.push_back(NULL); // } } gridData.push_back(aRow); } } int Grid::check() { // check if any rows full // if so then delete all rows // check if game is over std::vector<int> toDeleteList; for (int i = 0; i < gridData.size(); i++) { int filledSpots = 0; for (int j = 0; j < gridData.at(i).size(); j++) { if (gridData.at(i).at(j) != NULL) { filledSpots++; } } if (filledSpots == 13) { toDeleteList.push_back(i); // filledSpots = 0; } else if (filledSpots == 0) { break; } } for (int j = 0; j < toDeleteList.size(); j++) { std::cout << "will delete " << toDeleteList.at(j) << std::endl; } if (toDeleteList.size() > 0) { // std::vector<int> toDeleteList; deleteRows(toDeleteList); } Print(); for (int j = 0; j < gridData.at(13).size(); j++) { if (gridData.at(13).at(j) != NULL) { std::cout << "game over" << std::endl; return -1; break; } } return toDeleteList.size(); } void Grid::Print() { std::cout << "Grid \n"; for (int i = 0; i < gridData.size(); i++) { for (int j = 0; j < gridData.at(i).size(); j++) { if (gridData.at(i).at(j) != NULL) { std::cout << 1 << " "; } else { std::cout << 0 << " "; } } std::cout << std::endl; } } std::vector<int> Grid::ContainsFullRows() { // TODO: check each row if they are complete std::vector<int> nums; for (int i = 0; i < gridData.size(); i++) { for (int j = 0; j < gridData.at(i).size(); j++) { gridData.at(i).at(j); } } return nums; } void Grid::draw() { // rows for (int i = 0; i < gridData.size(); i++) { // rect // if (currentState != deletingARow && deletingRowIndex != i) // { for (int j = 0; j < gridData.at(i).size(); j++) { Rect *curr = gridData.at(i).at(j); // std::cout << "rec to draw" << curr << std::endl; if (curr != NULL) { // std::cout << "" << i << " " << j << std::endl; curr->draw(); } } // } } } Rect *Grid::getAt(int y, int x) { return gridData.at(y).at(x); } // deleting behavior void Grid::deleteRows(std::vector<int> toDeleteVector) { std::cout << "deleteorws(): " << toDeleteVector.size() << std::endl; for (int j = 0; j < toDeleteVector.size(); j++) { std::cout << "will delete " << toDeleteVector.at(j) << std::endl; } // toDelete = toDeleteVector; // std::cout << "set to delete row: " << i << std::endl; currentState = deletingARow; deletingState = movingRects; std::vector<std::vector<Rect *>>::iterator nth = gridData.begin(); for (int i = toDeleteVector.size() - 1; i >= 0; i--) { int pos = toDeleteVector.at(i); nth += pos; gridData.erase(nth); nth -= pos; std::vector<Rect *> aRow; for (int j = 0; j < xElements; j++) { aRow.push_back(NULL); } gridData.push_back(aRow); } // deletingRowIndex = 0; glutPostRedisplay(); // std::1cout << "remoed rows" << std::endl; // Print(); // std::vector<std::vector<Rect *>>::iterator hth = gridData.begin(); for (int i = 0; i < gridData.size(); i++) { // rect // if (currentState != deletingARow && deletingRowIndex != i) // { // std::cout << "checking row" << i << std::endl; for (int j = 0; j < gridData.at(i).size(); j++) { float x = -1.5 + rectWidth * j + 0.006 * j; float y = 1.0 - rectHeight * i - 0.006 * i; if (gridData.at(i).at(j) != NULL) { gridData.at(i).at(j)->setX(x); gridData.at(i).at(j)->setY(y); } } } // toDelete.clear(); currentState = chillin; deletingState = notDeleting; glutPostRedisplay(); } void Grid::continueMovingRects() { if (currentState == deletingARow && deletingState == movingRects) { // bool willStop = false; // // go through all elements in row // for (int movingRowsIndex = deletingRowIndex + 1; movingRowsIndex < gridData.size(); movingRowsIndex++) // { // for (int i = 0; i < gridData.at(movingRowsIndex).size(); i++) // { // float yPos = gridData.at(movingRowsIndex).at(i)->getY(); // yPos += 0.00035; // gridData.at(movingRowsIndex).at(i)->setY(yPos); // if (deletingRowIndex + 1 == movingRowsIndex) // { // int borderIndexRow = deletingRowIndex - 1; // // dev tests // gridData.at(borderIndexRow).at(i)->setG(0); // gridData.at(borderIndexRow).at(i)->setB(0); // if (gridData.at(borderIndexRow).at(i)->touchesBottomEdge(gridData.at(movingRowsIndex).at(i))) // { // willStop = true; // } // } // } // } // if (willStop) // { // std::vector<std::vector<Rect *>>::iterator nth = gridData.begin(); // for (int i = 0; i < gridData.size(); i++) // { // int pos = gridData.at(i); // nth += pos; // gridData.erase(nth); // nth -= pos; // } // // deletingRowIndex = 0; // toDelete.clear(); // currentState = chillin; // deletingState = notDeleting; // } // glutPostRedisplay(); } } void Grid::setAt(int i, int j, float x, float y, float w, float h, float r, float g, float b) { // std::cout << "setting grid rec: (" << i << ", " << j << ")" << std::endl; Rect *copy = new Rect(x, y, w, h, r, g, b); gridData.at(i).at(j) = copy; // std::cout << "rec in grid: " << gridData.at(j).at(i) << std::endl; } Grid::~Grid() { }
25.95053
116
0.446487
[ "vector" ]
8d4259e67ad8834bda1bb0a3dc36b42f7afdead2
9,153
cpp
C++
examples/albumverify/albumverify.cpp
crf8472/libarcstk
b2c29006c7dda6476bf3e7098f51ee30675439fb
[ "MIT" ]
null
null
null
examples/albumverify/albumverify.cpp
crf8472/libarcstk
b2c29006c7dda6476bf3e7098f51ee30675439fb
[ "MIT" ]
null
null
null
examples/albumverify/albumverify.cpp
crf8472/libarcstk
b2c29006c7dda6476bf3e7098f51ee30675439fb
[ "MIT" ]
null
null
null
// // Example for matching local AccurateRip checksums against the checksums // provided by AccurateRip. // #include <algorithm> // for count #include <cstdint> // for uint32_t etc. #include <cstring> // for strtok #include <fstream> // for ifstream etc. #include <iomanip> // for setw, setfill, hex #include <iostream> // for cerr, cout #include <stdexcept> // for runtime_error #include <string> // for string #ifndef __LIBARCSTK_MATCH_HPP__ // libarcstk: match Checksums and ARResponse #include <arcstk/match.hpp> #endif #ifndef __LIBARCSTK_CALCULATE_HPP__ #include <arcstk/calculate.hpp> // for arcstk::Checksums #endif #ifndef __LIBARCSTK_PARSE_HPP__ #include <arcstk/parse.hpp> // for arcstk::ARResponse #endif #ifndef __LIBARCSTK_LOGGING_HPP__ // libarcstk: log what you do #include <arcstk/logging.hpp> #endif // ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! // NOTE! THIS IS EXAMPLE CODE! IT IS INTENDED TO DEMONSTRATE HOW LIBARCSTK COULD // BE USED. IT IS NOT INTENDED TO BE USED IN REAL LIFE PRODUCTION. IT IS IN NO // WAY TESTED FOR PRODUCTION. TAKE THIS AS A STARTING POINT TO YOUR OWN // SOLUTION, NOT AS A TOOL. // ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! // NOTE 2: This example is rather long, much longer than I would prefer it to // be. The reason for this longishness is that for using the match interface, // you have to add code that prepares and provides the following input: // // - your own sums, i.e. the sums you have from your rip // - the reference sums from AccurateRip and // - the AccurateRip id of the album. // // This requires some boilerplate code. Although that boilerplate does not carry // any didactic evidence concerning libarcstk, I wanted to provide an example // that at least demonstrates the added value on your own input data. // In fact, the functions // // parse_arid(), // parse_input_arcs() and // parse_match_arcs() // // are more or less quick and dirty dummies for just providing the required // input values. This is not related to getting acquainted to the libarcstk API. // The actual example demonstrating the use of the AlbumMatcher class is // contained in main(). It's very simple to use. Have fun! /** * \brief Parse the ARId from the command line. * * @param[in] input_id A string representation of the ARId * * @return Parsed ARId */ arcstk::ARId parse_arid(const char* input_id) { const std::string id_str { input_id }; const uint16_t track_count = std::stoul(id_str.substr(0, 3), nullptr, 10); const uint32_t id_1 = std::stoul(id_str.substr(4, 8), nullptr, 16); const uint32_t id_2 = std::stoul(id_str.substr(13, 8), nullptr, 16); const uint32_t cddb_id = std::stoul(id_str.substr(22, 8), nullptr, 16); return arcstk::ARId(track_count, id_1, id_2, cddb_id); } /** * \brief Parse a comma-separated list of hexadecimal numbers. * * @param[in] list A string representation of the list * @param[in] t The checksum type to declare (either ARCS1 or ARCS2) * * @return Parsed Checksums */ arcstk::Checksums parse_input_arcs(const char* list, const arcstk::checksum::type t) { const std::string checksum_list { list }; const auto total_tracks { static_cast<std::size_t>( 1 + std::count(checksum_list.begin(), checksum_list.end(), ',')) }; std::string::size_type token_start { 0 }; std::string::size_type token_end { checksum_list.find_first_of(',') }; auto prev_settings { std::cout.flags() }; std::cout << "My checksums to match:" << std::endl; std::string token; // current token auto arcs = uint32_t { 0 }; // ARCS of the current token arcstk::Checksums checksums { total_tracks }; for (std::size_t i = 0; i < total_tracks; ++i) { token = checksum_list.substr(token_start, token_end - token_start); arcs = std::stoul(token, nullptr, 16); std::cout << "Track " << std::dec << std::setw(2) << std::setfill(' ') << (i + 1) << ": " << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << arcs << std::dec << " (chars: " << std::setw(3) << std::setfill(' ') << token_start << " - " << std::setw(3) << std::setfill(' ') << token_end << ")" << '\n'; auto track_sum = arcstk::ChecksumSet { 0 }; track_sum.insert(t, arcstk::Checksum(arcs)); checksums.append(track_sum); token_start = token_end + 1; token_end = checksum_list.find_first_of(',', token_start); if (token_end == std::string::npos) { token_end = checksum_list.length(); } } std::cout.flags(prev_settings); return checksums; } /** * \brief Parse ARCSs from a non-empty response file or from stdin. * * @param[in] filename Name of the response file * * @return Parsed ARResponse * * @throws std::runtime_error If filename is empty */ arcstk::ARResponse parse_match_arcs(const std::string &filename) { if (filename.empty()) { throw std::runtime_error("Filename must not be empty!"); } auto content_hdlr { std::make_unique<arcstk::DefaultContentHandler>() }; arcstk::ARResponse response_data; content_hdlr->set_object(response_data); auto error_hdlr { std::make_unique<arcstk::DefaultErrorHandler>() }; std::unique_ptr<arcstk::ARStreamParser> parser; std::ifstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); file.open(filename, std::ifstream::in | std::ifstream::binary); parser = std::make_unique<arcstk::ARParser>(file); parser->set_content_handler(std::move(content_hdlr)); parser->set_error_handler(std::move(error_hdlr)); parser->parse(); // This may throw! return response_data; } int main(int argc, char* argv[]) { // Do only the absolutely inevitable checking if (argc < 3 or argc > 4) { std::cout << "Usage: albumverify --id=<ARId> --arcs2=0xA,0xB,0xC,... <file.bin>" << std::endl; return EXIT_SUCCESS; } // If you like, you can activate the internal logging of libarcstk to // see what's going on behind the scenes. We provide an appender for stdout // and set the loglevel to 'INFO', which means you should probably not see // anything unless you give libarcstk unexpected input. arcstk::Logging::instance().add_appender( std::make_unique<arcstk::Appender>("stdout", stdout)); // Set this to DEBUG or DEBUG1 if you want to see what libarcstk is // doing with your input arcstk::Logging::instance().set_level(arcstk::LOGLEVEL::INFO); // Parse the AccurateRip id of the album passed from the command line const arcstk::ARId arid { parse_arid(argv[1] + 5) }; std::cout << "Album ID: " << arid.to_string() << '\n'; // Parse declared ARCS type (ARCSv1 or ARCSv2) arcstk::checksum::type type { argv[2][6] == '1' ? arcstk::checksum::type::ARCS1 : arcstk::checksum::type::ARCS2 }; // Parse the checksums of the album passed from the command line const arcstk::Checksums checksums { parse_input_arcs(argv[2] + 8, type) }; // Parse the checksums to be matched from file or stdin std::string filename; if (argc == 4) { filename = std::string(argv[3]); } const arcstk::ARResponse arcss { parse_match_arcs(filename) }; // Now the interesting part: peform the match. // The AlbumMatcher class targets situations in which you have a list of // checksums and you _know_ in which order they form the album. Therefore // AlbumMatcher is the device of choice here. arcstk::AlbumMatcher matcher { checksums, arid, arcss }; // It may also be the case that you have just some tracks of an album or you // cannot be sure about the order. In this case, you would use the // arcstk::TracksetMatcher. // Inform about the result std::cout << "RESULT: "; if (matcher.matches()) { std::cout << "Response contains a total match in block " << matcher.best_match() << ", which is of type ARCSv" << (matcher.best_match_is_v2() + 1) << "." << std::endl; } else { std::cout << "No total match. Best block is " << matcher.best_match() << ", which is of type ARCSv" << (matcher.best_match_is_v2() + 1) << " with difference " << matcher.best_difference() << std::endl; } // And now print the gory details auto match { matcher.match() }; auto block { matcher.best_match() }; auto trackno { 0 }; auto is_match = bool { false }; auto prev_settings { std::cout.flags() }; std::cout << "TRACK MINE THEIRS\n"; for (const auto& track : arcss[block]) { // The match object stores flags for every check that the matcher // has performed. Thus, the result of the matching can be queried on the // match object by just giving the coordinate block/track/version. is_match = match->track(block, trackno, type == arcstk::checksum::type::ARCS2); std::cout << " " << std::dec << std::setw(2) << std::setfill('0') << (trackno + 1) << ": "; std::cout << std::hex << std::uppercase; std::cout << std::setw(8) << std::setfill('0') << checksums[trackno].get(type).value(); std::cout << (is_match ? " = " : " ") ; std::cout << std::setw(8) << std::setfill('0') << track.arcs(); std::cout << (is_match ? " [OK]" : " <- FAIL") ; std::cout << '\n'; ++trackno; } std::cout.flags(prev_settings); return EXIT_SUCCESS; }
31.34589
81
0.668961
[ "object" ]
1d25732a15dbb4645c1117362ad842bee77c72ed
514
cpp
C++
fakeheap.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
fakeheap.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
null
null
null
fakeheap.cpp
W-YXN/MyNOIPProjects
0269a8385a6c8d87511236146f374f39dcdd2b82
[ "Apache-2.0" ]
1
2019-01-19T01:05:07.000Z
2019-01-19T01:05:07.000Z
#include <iostream> #include <cstdlib> #include <cmath> #include <algorithm> #include <queue> using std::cerr; using std::cin; using std::cout; using std::endl; int main(){ priority_queue<int,vector<int>,greater<int> > q; int n; cin>>n; for (int i = 0; i < n; i++) { int code; cin>>code; if(code==1){ int tmp; cin>>tmp; q.push(tmp); }else{ cout<<q.top()<<endl; q.pop(); } } return 0; }
17.724138
52
0.480545
[ "vector" ]
1d283af6ff07160a2c63558c34214906695137c7
6,181
cpp
C++
filesys/storman_sdcard.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
13
2018-02-26T14:56:02.000Z
2022-03-31T06:01:56.000Z
filesys/storman_sdcard.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
null
null
null
filesys/storman_sdcard.cpp
nvitya/nvcm
80b5fb2736b400a10edeecdaf24eb998dfab9759
[ "Zlib" ]
3
2020-11-04T09:15:01.000Z
2021-07-06T09:42:00.000Z
/* ----------------------------------------------------------------------------- * This file is a part of the NVCM Tests project: https://github.com/nvitya/nvcmtests * Copyright (c) 2020 Viktor Nagy, nvitya * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. Permission is granted to anyone to use this * software for any purpose, including commercial applications, and to alter * it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * --------------------------------------------------------------------------- */ /* * file: storman_sdcard.cpp * brief: Storage Manager for SDCARDs * version: 1.00 * date: 2020-12-29 * authors: nvitya */ #include "string.h" #include <storman_sdcard.h> // state machine codes #define SMDS_IDLE 0 #define SMDS_WAIT_NORMAL 1 #define SMDS_RD_WAIT_PARTIAL 10 #define SMDS_RD_PROCESS_PARTIAL 11 #define SMDS_WR_WAIT_PARTIAL_RD 20 #define SMDS_WR_WAIT_PARTIAL_WR 21 #define SMDS_FINISH 100 #define SMD_BLOCK_ADDR_MASK 0xFFFFFFFFFFFFFE00 bool TStorManSdcard::Init(THwSdcard * asdcard) { sdcard = asdcard; super::Init(&sdbuf[0], sizeof(sdbuf)); erase_unit = 512; smallest_block = 512; return true; } void TStorManSdcard::StartPartialRead() { uint64_t bladdr = (curaddr & SMD_BLOCK_ADDR_MASK); if (bladdr != sdbufaddr) { if (!sdcard->StartReadBlocks((bladdr >> 9), &sdbuf[0], 1)) { curtra->errorcode = sdcard->errorcode; state = SMDS_FINISH; return; } state = SMDS_RD_WAIT_PARTIAL; } else { // already loaded ProcessPartialRead(); } } void TStorManSdcard::ProcessPartialRead() { uint32_t offset = (curaddr & 0x1FF); uint32_t rdsize = (512 - offset); if (rdsize > remaining) rdsize = remaining; memcpy(dataptr, &sdbuf[offset], rdsize); remaining -= rdsize; dataptr += rdsize; curaddr += rdsize; if (remaining > 0) { StartPartialRead(); } else { FinishCurTra(); } } void TStorManSdcard::PreparePartialWrite() { uint64_t bladdr = (curaddr & SMD_BLOCK_ADDR_MASK); if (bladdr != sdbufaddr) { if (!sdcard->StartReadBlocks((bladdr >> 9), &sdbuf[0], 1)) { curtra->errorcode = sdcard->errorcode; state = SMDS_FINISH; return; } state = SMDS_WR_WAIT_PARTIAL_RD; } else { // already loaded StartPartialWrite(); } } void TStorManSdcard::StartPartialWrite() { uint32_t offset = (curaddr & 0x1FF); chunksize = (512 - offset); if (chunksize > remaining) chunksize = remaining; memcpy(&sdbuf[offset], dataptr, chunksize); if (!sdcard->StartWriteBlocks((sdbufaddr >> 9), &sdbuf[0], 1)) { curtra->errorcode = sdcard->errorcode; state = SMDS_FINISH; return; } state = SMDS_WR_WAIT_PARTIAL_WR; } void TStorManSdcard::FinishPartialWrite() { remaining -= chunksize; dataptr += chunksize; curaddr += chunksize; if (remaining > 0) { PreparePartialWrite(); } else { FinishCurTra(); } } void TStorManSdcard::FinishCurTra() { // request completed // the callback function might add the same transaction object as new // therefore we have to remove the transaction from the chain before we call the callback curtra->completed = true; firsttra = firsttra->next; // advance to the next transaction if (!firsttra) lasttra = nullptr; state = SMDS_IDLE; ExecCallback(curtra); } void TStorManSdcard::FinishCurTraError(int aerror) { curtra->errorcode = aerror; FinishCurTra(); } void TStorManSdcard::Run() { if (!sdcard) { return; } sdcard->Run(); if (!sdcard->completed || !sdcard->card_initialized) { return; } if (!firsttra) { return; } uint8_t n; if (SMDS_IDLE == state) { // start (new request) curtra = firsttra; trastarttime = CLOCKCNT; state = 1; if (STRA_READ == curtra->trtype) { // check partial / full block remaining = curtra->datalen; dataptr = curtra->dataptr; curaddr = curtra->address; if ((curaddr & 0x1FF) || (remaining & 0x1FF)) { // partial mode StartPartialRead(); return; } else { // full block mode if (!sdcard->StartReadBlocks((curaddr >> 9), dataptr, (remaining >> 9))) { FinishCurTraError(sdcard->errorcode); return; } state = SMDS_WAIT_NORMAL; } } else if (STRA_WRITE == curtra->trtype) { // check partial / full block remaining = curtra->datalen; dataptr = curtra->dataptr; curaddr = curtra->address; if ((curaddr & 0x1FF) || (remaining & 0x1FF)) { // partial mode PreparePartialWrite(); return; } else { // full block mode if (!sdcard->StartWriteBlocks((curaddr >> 9), dataptr, (remaining >> 9))) { FinishCurTraError(sdcard->errorcode); return; } state = SMDS_WAIT_NORMAL; } } else { FinishCurTraError(ESTOR_NOTIMPL); } } else if (SMDS_WAIT_NORMAL == state) // finished, set the error code { curtra->errorcode = sdcard->errorcode; FinishCurTra(); } else if (SMDS_RD_WAIT_PARTIAL == state) { if (sdcard->errorcode) { FinishCurTraError(sdcard->errorcode); return; } sdbufaddr = (curaddr & SMD_BLOCK_ADDR_MASK); ProcessPartialRead(); } else if (SMDS_WR_WAIT_PARTIAL_RD == state) { if (sdcard->errorcode) { FinishCurTraError(sdcard->errorcode); return; } sdbufaddr = (curaddr & SMD_BLOCK_ADDR_MASK); StartPartialWrite(); } else if (SMDS_WR_WAIT_PARTIAL_WR == state) { if (sdcard->errorcode) { FinishCurTraError(sdcard->errorcode); return; } FinishPartialWrite(); } else if (SMDS_FINISH == state) { FinishCurTra(); } }
20.265574
90
0.653778
[ "object" ]
1d2fcee1ca99de43175e72653bd357a9fbfe263d
4,839
cpp
C++
tests/test-mempools.cpp
amit1144576/Advance-Database-Systems-Memory-Pooling
2e52f8f4d983903292fe7e01f00d0845a3bdfad7
[ "MIT" ]
2
2019-06-11T14:05:58.000Z
2019-06-11T14:25:45.000Z
tests/test-mempools.cpp
RAO-29/SG-1-Memory-Pooling
2e52f8f4d983903292fe7e01f00d0845a3bdfad7
[ "MIT" ]
null
null
null
tests/test-mempools.cpp
RAO-29/SG-1-Memory-Pooling
2e52f8f4d983903292fe7e01f00d0845a3bdfad7
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include <printf.h> #include <cinttypes> #include "shared/common.h" #include "shared/types.h" #include "core/mem/pool.h" //void test_mempool_none(struct pool *pool, struct pool_counters *counters) //{ // /* test alloc */ // { // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 0); // EXPECT_EQ(counters->num_realloc_calls, 0); // EXPECT_EQ(counters->num_free_calls, 0); // // for (u32 j = 1; j < 10000; j++) { // pool_alloc(pool, j); // } // // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 9999); // // pool_free_all(pool); // // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 9999); // EXPECT_EQ(counters->num_free_calls, 9999); // } // // /* test free */ // { // pool_reset_counters(pool); // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 0); // EXPECT_EQ(counters->num_realloc_calls, 0); // EXPECT_EQ(counters->num_free_calls, 0); // // struct vector ofType(void *) vec; // vec_create(&vec, NULL, sizeof(void *), 10000); // // for (u32 j = 1; j < 10000; j++) { // void *p = pool_alloc(pool, j); // vec_push(&vec, &p, 1); // // } // // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 9999); // // for (u32 j = 0; j < vec.num_elems; j++) { // void *p = *vec_get(&vec, j, void *); // pool_free(pool, p); // } // // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 9999); // EXPECT_EQ(counters->num_free_calls, 9999); // // vec_drop(&vec); // } // // /* test realloc */ // { // pool_reset_counters(pool); // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 0); // EXPECT_EQ(counters->num_realloc_calls, 0); // EXPECT_EQ(counters->num_free_calls, 0); // // struct vector ofType(void *) vec; // vec_create(&vec, NULL, sizeof(void *), 10000); // // for (u32 j = 1; j < 10000; j++) { // void *p = pool_alloc(pool, j); // vec_push(&vec, &p, 1); // // } // // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 9999); // // for (u32 j = 0; j < vec.num_elems; j++) { // void *p = *vec_get(&vec, j, void *); // void *p2 = pool_realloc(pool, p, (j + 1) * 2); // vec_set(&vec, j, &p2); // } // // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_realloc_calls, 9999); // EXPECT_EQ(counters->num_managed_realloc_calls, 0); // // for (u32 j = 0; j < vec.num_elems; j++) { // void *p = *vec_get(&vec, j, void *); // pool_free(pool, p); // } // // pool_get_counters(counters, pool); // EXPECT_EQ(counters->num_alloc_calls, 9999); // EXPECT_EQ(counters->num_free_calls, 9999); // // vec_drop(&vec); // } //} // // //TEST(MemPoolTest, SimpleTetst) { // // struct pool pool; // struct pool_strategy strategy; // struct pool_counters counters; // // for (u32 i = 0; i < pool_get_num_registered_strategies(); i++) { // struct pool_register_entry *entry = pool_register + i; // entry->_create(&strategy); // const char *name = strategy.impl_name; // // printf("*** Test '%s' ***\n", strategy.impl_name); // pool_create_by_name(&pool, name); // // if (strcmp(name, POOL_STRATEGY_NONE_NAME) == 0) { // test_mempool_none(&pool, &counters); // } else { // fprintf(stderr, "no test-case implementation found for strategy '%s'\n", name); // EXPECT_TRUE(false); // } // // ng5_optional_call(entry, _drop, &strategy); // // } //} // TODO: add pool tests again int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
35.065217
105
0.467865
[ "vector" ]
1d34b7354950495b2a6462947643668f9d77923f
9,427
cpp
C++
MapBuilder/main.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
MapBuilder/main.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
MapBuilder/main.cpp
coolzoom/namigator
722a9f9e71ac5091acfad6ad53d203e1f1ffcf49
[ "MIT" ]
null
null
null
#include "GameObjectBVHBuilder.hpp" #include "MeshBuilder.hpp" #include "Worker.hpp" #include "parser/Adt/Adt.hpp" #include "parser/MpqManager.hpp" #include "parser/Wmo/WmoInstance.hpp" #include <chrono> #include <cstdint> #include <filesystem> #include <iomanip> #include <iostream> #include <map> #include <sstream> #include <string> #include <thread> #define STATUS_INTERVAL_SECONDS 10 namespace { void DisplayUsage(std::ostream& o) { o << "Usage:\n"; o << " -h/--help -- Display help message\n"; o << " -d/--data <data directory> -- Path to data directory from " "which to draw input geometry\n"; o << " -m/--map <map name> -- Which map to produce data for\n"; o << " -b/--bvh -- Build line of sight (BVH) data " "for all models eligible for spawning by the server\n"; o << " -g/--gocsv <go csv file> -- Path to CSV file containing game " "object data to include in static mesh output\n"; o << " -o/--output <output directory> -- Path to root output directory\n"; o << " -t/--threads <thread count> -- How many worker threads to use\n"; o << " -l/--logLevel <log level> -- Log level (0 = none, 1 = " "progress, 2 = warning, 3 = error)\n"; #ifdef _DEBUG o << " -x/--adtX <x> -- X coordinate of individual ADT " "to process\n"; o << " -y/--adtY <y> -- Y coordinate of individual ADT " "to process\n"; #endif o.flush(); } } // namespace int main(int argc, char* argv[]) { std::string dataPath, map, outputPath, goCSVPath; int adtX = -1, adtY = -1, threads = 1, logLevel; bool bvh = false; try { for (auto i = 1; i < argc; ++i) { std::string arg(argv[i]); std::transform(arg.begin(), arg.end(), arg.begin(), ::tolower); const bool lastArgument = i == argc - 1; if (arg == "-b" || arg == "--bvh") { bvh = true; continue; } else if (arg == "-h" || arg == "--help") { // when this is requested, don't do anything else DisplayUsage(std::cout); return EXIT_SUCCESS; } if (lastArgument) throw std::invalid_argument("Missing argument to parameter " + arg); // below here we know that there is another argument if (arg == "-d" || arg == "--data") dataPath = argv[++i]; else if (arg == "-m" || arg == "--map") map = argv[++i]; else if (arg == "-g" || arg == "--gocsv") goCSVPath = argv[++i]; else if (arg == "-o" || arg == "--output") outputPath = argv[++i]; else if (arg == "-t" || arg == "--threads") threads = std::stoi(argv[++i]); else if (arg == "-l" || arg == "--loglevel") logLevel = std::stoi(argv[++i]); #ifdef _DEBUG else if (arg == "-x" || arg == "--adtX") adtX = std::stoi(argv[++i]); else if (arg == "-y" || arg == "--adtY") adtY = std::stoi(argv[++i]); #endif else throw std::invalid_argument("Unrecognized argument " + arg); } } catch (std::invalid_argument const& e) { std::cerr << "ERROR: " << e.what() << std::endl << std::endl; DisplayUsage(std::cerr); return EXIT_FAILURE; } if (outputPath.empty()) { std::cerr << "ERROR: Must specify output path" << std::endl; DisplayUsage(std::cerr); return EXIT_FAILURE; } if (!bvh && map.empty()) { std::cerr << "ERROR: Must specify either a map to generate (--map) or " "the global generation of BVH data (--bvh)" << std::endl; DisplayUsage(std::cerr); return EXIT_FAILURE; } if (adtX >= MeshSettings::Adts || adtY >= MeshSettings::Adts) { std::cerr << "ERROR: Invalid ADT (" << adtX << ", " << adtY << ")" << std::endl; DisplayUsage(std::cerr); return EXIT_FAILURE; } auto lastStatus = static_cast<time_t>(0); std::unique_ptr<MeshBuilder> builder; std::vector<std::unique_ptr<Worker>> workers; try { if (!std::filesystem::is_directory(outputPath)) std::filesystem::create_directory(outputPath); if (!std::filesystem::is_directory(outputPath + "/BVH")) std::filesystem::create_directory(outputPath + "/BVH"); if (bvh) { if (!goCSVPath.empty()) { std::cerr << "ERROR: Specifying gameobject data for BVH " "generation is meaningless" << std::endl; DisplayUsage(std::cerr); return EXIT_FAILURE; } parser::GameObjectBVHBuilder goBuilder(dataPath, outputPath, threads); auto const startSize = goBuilder.Remaining(); goBuilder.Begin(); do { std::this_thread::sleep_for(std::chrono::milliseconds(500)); auto const now = time(nullptr); auto const finished = goBuilder.Remaining() == 0; auto const update_status = finished || now - lastStatus >= STATUS_INTERVAL_SECONDS; // periodically output current status if (update_status) { std::stringstream str; auto const completed = startSize - goBuilder.Remaining(); auto const percentComplete = 100.f * static_cast<float>(completed) / startSize; str << "% Complete: " << std::setprecision(4) << percentComplete << " (" << std::dec << completed << " / " << startSize << ")\n"; std::cout << str.str(); std::cout.flush(); lastStatus = now; } if (finished) break; } while (true); goBuilder.Shutdown(); std::stringstream fin; fin << "Finished BVH generation"; std::cout << fin.str() << std::endl; return EXIT_SUCCESS; } if (!std::filesystem::is_directory(outputPath + "/Nav")) std::filesystem::create_directory(outputPath + "/Nav"); // nav mesh generation requires that the MPQ manager be initialized for // the main thread, whereas BVH generation above does not. parser::sMpqManager.Initialize(dataPath); if (adtX >= 0 && adtY >= 0) { builder = std::make_unique<MeshBuilder>(outputPath, map, logLevel, adtX, adtY); if (!goCSVPath.empty()) builder->LoadGameObjects(goCSVPath); if (builder->IsGlobalWMO()) { std::cerr << "ERROR: Specified map has no ADTs" << std::endl; DisplayUsage(std::cerr); return EXIT_FAILURE; } std::cout << "Building " << map << " (" << adtX << ", " << adtY << ")..." << std::endl; workers.push_back( std::make_unique<Worker>(dataPath, builder.get())); } // either both, or neither should be specified else if (adtX >= 0 || adtY >= 0) { std::cerr << "ERROR: Must specify ADT X and Y" << std::endl; DisplayUsage(std::cerr); return EXIT_FAILURE; } else { builder = std::make_unique<MeshBuilder>(outputPath, map, logLevel); if (!goCSVPath.empty()) builder->LoadGameObjects(goCSVPath); for (auto i = 0; i < threads; ++i) workers.push_back( std::make_unique<Worker>(dataPath, builder.get())); } } catch (std::exception const& e) { std::cerr << "Builder initialization failed: " << e.what() << std::endl; return EXIT_FAILURE; } auto const start = time(nullptr); for (;;) { bool done = true; for (auto const& worker : workers) if (!worker->IsFinished()) { done = false; break; } if (done) break; std::this_thread::sleep_for(std::chrono::milliseconds(500)); auto const now = time(nullptr); // periodically output current status if (now - lastStatus >= STATUS_INTERVAL_SECONDS) { std::stringstream str; str << "% Complete: " << builder->PercentComplete() << "\n"; std::cout << str.str(); lastStatus = now; } } builder->SaveMap(); auto const runTime = time(nullptr) - start; std::cout << "Finished " << map << " (" << builder->CompletedTiles() << " tiles) in " << runTime << " seconds." << std::endl; return EXIT_SUCCESS; }
31.740741
80
0.480959
[ "mesh", "geometry", "object", "vector", "transform" ]
1d4017d793315876f3cc79a8ac0942b391b7e29b
8,732
cc
C++
src/script_opt/CPP/DeclFunc.cc
sowmyaramapatruni/zeek
58fae227082dd09107f5389f2f054c4b6a6e1a20
[ "Apache-2.0" ]
1
2021-08-06T02:17:59.000Z
2021-08-06T02:17:59.000Z
src/script_opt/CPP/DeclFunc.cc
kevanGit/zeek
42d2a5fe05ab6c3f94bbdc36e712df2c17bda683
[ "Apache-2.0" ]
null
null
null
src/script_opt/CPP/DeclFunc.cc
kevanGit/zeek
42d2a5fe05ab6c3f94bbdc36e712df2c17bda683
[ "Apache-2.0" ]
1
2020-05-27T17:51:55.000Z
2020-05-27T17:51:55.000Z
// See the file "COPYING" in the main distribution directory for copyright. #include <errno.h> #include <unistd.h> #include <sys/stat.h> #include "zeek/script_opt/CPP/Compile.h" namespace zeek::detail { using namespace std; void CPPCompile::DeclareFunc(const FuncInfo& func) { if ( ! IsCompilable(func) ) return; auto fname = Canonicalize(BodyName(func).c_str()) + "_zf"; auto pf = func.Profile(); auto f = func.Func(); const auto& body = func.Body(); auto priority = func.Priority(); DeclareSubclass(f->GetType(), pf, fname, body, priority, nullptr, f->Flavor()); if ( f->GetBodies().size() == 1 ) compiled_simple_funcs[f->Name()] = fname; } void CPPCompile::DeclareLambda(const LambdaExpr* l, const ProfileFunc* pf) { ASSERT(is_CPP_compilable(pf)); auto lname = Canonicalize(l->Name().c_str()) + "_lb"; auto body = l->Ingredients().body; auto l_id = l->Ingredients().id; auto& ids = l->OuterIDs(); for ( auto id : ids ) lambda_names[id] = LocalName(id); DeclareSubclass(l_id->GetType<FuncType>(), pf, lname, body, 0, l, FUNC_FLAVOR_FUNCTION); } void CPPCompile::DeclareSubclass(const FuncTypePtr& ft, const ProfileFunc* pf, const string& fname, const StmtPtr& body, int priority, const LambdaExpr* l, FunctionFlavor flavor) { const auto& yt = ft->Yield(); in_hook = flavor == FUNC_FLAVOR_HOOK; const IDPList* lambda_ids = l ? &l->OuterIDs() : nullptr; auto yt_decl = in_hook ? "bool" : FullTypeName(yt); NL(); Emit("static %s %s(%s);", yt_decl, fname, ParamDecl(ft, lambda_ids, pf)); Emit("class %s_cl : public CPPStmt", fname); StartBlock(); Emit("public:"); string addl_args; // captures passed in on construction string inits; // initializers for corresponding member vars if ( lambda_ids ) { for ( auto& id : *lambda_ids ) { auto name = lambda_names[id]; auto tn = FullTypeName(id->GetType()); addl_args = addl_args + ", " + tn + " _" + name; inits = inits + ", " + name + "(_" + name + ")"; } } Emit("%s_cl(const char* name%s) : CPPStmt(name)%s { }", fname, addl_args.c_str(), inits.c_str()); // An additional constructor just used to generate place-holder // instances, due to the mis-design that lambdas are identified // by their Func objects rather than their FuncVal objects. if ( lambda_ids && lambda_ids->length() > 0 ) Emit("%s_cl(const char* name) : CPPStmt(name) { }", fname); Emit("ValPtr Exec(Frame* f, StmtFlowType& flow) override final"); StartBlock(); Emit("flow = FLOW_RETURN;"); if ( in_hook ) { Emit("if ( ! %s(%s) )", fname, BindArgs(ft, lambda_ids)); StartBlock(); Emit("flow = FLOW_BREAK;"); EndBlock(); Emit("return nullptr;"); } else if ( IsNativeType(yt) ) GenInvokeBody(fname, yt, BindArgs(ft, lambda_ids)); else Emit("return %s(%s);", fname, BindArgs(ft, lambda_ids)); EndBlock(); if ( lambda_ids ) BuildLambda(ft, pf, fname, body, l, lambda_ids); else { // Track this function as known to have been compiled. // We don't track lambda bodies as compiled because they // can't be instantiated directly without also supplying // the captures. In principle we could make an exception // for lambdas that don't take any arguments, but that // seems potentially more confusing than beneficial. compiled_funcs.emplace(fname); auto loc_f = script_specific_filename(body); cf_locs[fname] = loc_f; // Some guidance for those looking through the generated code. Emit("// compiled body for: %s", loc_f); } EndBlock(true); auto h = pf->HashVal(); body_hashes[fname] = h; body_priorities[fname] = priority; body_names.emplace(body.get(), fname); names_to_bodies.emplace(fname, body.get()); total_hash = merge_p_hashes(total_hash, h); } void CPPCompile::BuildLambda(const FuncTypePtr& ft, const ProfileFunc* pf, const string& fname, const StmtPtr& body, const LambdaExpr* l, const IDPList* lambda_ids) { // Declare the member variables for holding the captures. for ( auto& id : *lambda_ids ) { auto name = lambda_names[id]; auto tn = FullTypeName(id->GetType()); Emit("%s %s;", tn, name.c_str()); } // Generate initialization to create and register the lambda. auto literal_name = string("\"") + l->Name() + "\""; auto instantiate = string("make_intrusive<") + fname + "_cl>(" + literal_name + ")"; int nl = lambda_ids->length(); auto h = Fmt(pf->HashVal()); auto has_captures = nl > 0 ? "true" : "false"; auto l_init = string("register_lambda__CPP(") + instantiate + ", " + h + ", \"" + l->Name() + "\", " + GenTypeName(ft) + ", " + has_captures + ");"; AddInit(l, l_init); NoteInitDependency(l, TypeRep(ft)); // Make the lambda's body's initialization depend on the lambda's // initialization. That way GenFuncVarInits() can generate // initializations with the assurance that the associated body // hashes will have been registered. AddInit(body.get()); NoteInitDependency(body.get(), l); // Generate method to extract the lambda captures from a deserialized // Frame object. Emit("void SetLambdaCaptures(Frame* f) override"); StartBlock(); for ( int i = 0; i < nl; ++i ) { auto l_i = (*lambda_ids)[i]; const auto& t_i = l_i->GetType(); auto cap_i = string("f->GetElement(") + Fmt(i) + ")"; Emit("%s = %s;", lambda_names[l_i], GenericValPtrToGT(cap_i, t_i, GEN_NATIVE)); } EndBlock(); // Generate the method for serializing the captures. Emit("std::vector<ValPtr> SerializeLambdaCaptures() const override"); StartBlock(); Emit("std::vector<ValPtr> vals;"); for ( int i = 0; i < nl; ++i ) { auto l_i = (*lambda_ids)[i]; const auto& t_i = l_i->GetType(); Emit("vals.emplace_back(%s);", NativeToGT(lambda_names[l_i], t_i, GEN_VAL_PTR)); } Emit("return vals;"); EndBlock(); // Generate the Clone() method. Emit("CPPStmtPtr Clone() override"); StartBlock(); auto arg_clones = GenLambdaClone(l, true); Emit("return make_intrusive<%s_cl>(name.c_str()%s);", fname, arg_clones); EndBlock(); } string CPPCompile::BindArgs(const FuncTypePtr& ft, const IDPList* lambda_ids) { const auto& params = ft->Params(); auto t = params->Types(); string res; int n = t ? t->size() : 0; for ( auto i = 0; i < n; ++i ) { auto arg_i = string("f->GetElement(") + Fmt(i) + ")"; const auto& pt = params->GetFieldType(i); if ( IsNativeType(pt) ) res += arg_i + NativeAccessor(pt); else res += GenericValPtrToGT(arg_i, pt, GEN_VAL_PTR); res += ", "; } if ( lambda_ids ) { for ( auto& id : *lambda_ids ) res += lambda_names[id] + ", "; } // Add the final frame argument. return res + "f"; } string CPPCompile::ParamDecl(const FuncTypePtr& ft, const IDPList* lambda_ids, const ProfileFunc* pf) { const auto& params = ft->Params(); int n = params->NumFields(); string decl; for ( auto i = 0; i < n; ++i ) { const auto& t = params->GetFieldType(i); auto tn = FullTypeName(t); auto param_id = FindParam(i, pf); string fn; if ( param_id ) { if ( t->Tag() == TYPE_ANY && param_id->GetType()->Tag() != TYPE_ANY ) // We'll need to translate the parameter // from its current representation to // type "any". fn = string("any_param__CPP_") + Fmt(i); else fn = LocalName(param_id); } else // Parameters that are unused don't wind up // in the ProfileFunc. Rather than dig their // name out of the function's declaration, we // explicitly name them to reflect that they're // unused. fn = string("unused_param__CPP_") + Fmt(i); if ( IsNativeType(t) ) // Native types are always pass-by-value. decl = decl + tn + " " + fn; else { if ( param_id && pf->Assignees().count(param_id) > 0 ) // We modify the parameter. decl = decl + tn + " " + fn; else // Not modified, so pass by const reference. decl = decl + "const " + tn + "& " + fn; } decl += ", "; } if ( lambda_ids ) { // Add the captures as additional parameters. for ( auto& id : *lambda_ids ) { auto name = lambda_names[id]; const auto& t = id->GetType(); auto tn = FullTypeName(t); // Allow the captures to be modified. decl = decl + tn + "& " + name + ", "; } } // Add in the declaration of the frame. return decl + "Frame* f__CPP"; } const ID* CPPCompile::FindParam(int i, const ProfileFunc* pf) { const auto& params = pf->Params(); for ( const auto& p : params ) if ( p->Offset() == i ) return p; return nullptr; } } // zeek::detail
26.867692
78
0.626432
[ "object", "vector" ]
1d5234875e5c334e6f611737b42c1972c746db0e
4,321
cpp
C++
leetcode_solutions/curated_top_100/tree/20201212_662_Maximum_Width_of_Binary_Tree_20201212.cpp
lovms/code_snippets
243d751cb2b3725e20dca1adb5b5563b64a3eed0
[ "MIT" ]
null
null
null
leetcode_solutions/curated_top_100/tree/20201212_662_Maximum_Width_of_Binary_Tree_20201212.cpp
lovms/code_snippets
243d751cb2b3725e20dca1adb5b5563b64a3eed0
[ "MIT" ]
null
null
null
leetcode_solutions/curated_top_100/tree/20201212_662_Maximum_Width_of_Binary_Tree_20201212.cpp
lovms/code_snippets
243d751cb2b3725e20dca1adb5b5563b64a3eed0
[ "MIT" ]
null
null
null
//Given a binary tree, write a function to get the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. // //The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation. // //It is guaranteed that the answer will in the range of 32-bit signed integer. // //Example 1: // //Input: // // 1 // / \ // 3 2 // / \ \ // 5 3 9 // //Output: 4 //Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9). //Example 2: // //Input: // // 1 // / // 3 // / \ // 5 3 // //Output: 2 //Explanation: The maximum width existing in the third level with the length 2 (5,3). //Example 3: // //Input: // // 1 // / \ // 3 2 // / // 5 // //Output: 2 //Explanation: The maximum width existing in the second level with the length 2 (3,2). //Example 4: // //Input: // // 1 // / \ // 3 2 // / \ // 5 9 // / \ // 6 7 //Output: 8 //Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7). //  // //Constraints: // //The given binary tree will have between 1 and 3000 nodes. // //来源:力扣(LeetCode) //链接:https://leetcode-cn.com/problems/maximum-width-of-binary-tree //著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 // 思路: // 1. 本题中首先要理解定义的层宽,实际上是给定数每层 // 的最左端,最右端的节点,以及其在对应的满二叉树上的序号的差值!! // // 2. 这和一般的将"每层的非空节点数目定义成层宽"是不一样的。 // // 3. 需要注意的是,题目中保证了层宽是32位的整数,但是对应的满二叉数的 // 序号肯定就超过了32位了,这个地方一开始我就没注意,导致提交没过。 // 换成unsigned long long就可以了。(第0层的层宽为1,第i层层宽为2^i, // i最大32,32层满二叉树节点总共有2^0+2^1+...+2^31 = (2^32-1),所以 // 64位整数肯定是够的) #include <utility> #include <queue> #include <vector> #include <iostream> using std::queue; using std::pair; using std::vector; /** * Definition for a binary tree node.*/ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} }; /* */ class Solution { public: int widthOfBinaryTree(TreeNode* root) { if (root == nullptr) { return 0; } if (root->left == nullptr && root->right == nullptr) { return 1; } queue<pair<TreeNode*, unsigned long long> > layers; layers.emplace(root, 1); int layerSize = 1; unsigned long long maxWidth = 1; unsigned long long first = 0; unsigned long long last = 0; while (!layers.empty()) { layerSize = layers.size(); for (int i = 0; i < layerSize; ++i) { TreeNode* cur = std::get<0>(layers.front()); unsigned long long seq = std::get<1>(layers.front()); layers.pop(); if (cur->left != nullptr) { layers.emplace(cur->left, 2*seq); } if (cur->right != nullptr) { layers.emplace(cur->right, 2*seq+1); } if (i == 0) { first = seq; } if (i == layerSize-1) { last = seq; } } if (last - first + 1 > maxWidth) { maxWidth = last - first + 1; } } return maxWidth; } }; class BinaryTree { public: BinaryTree() : root(nullptr) {} void buildTree(vector<int>& nums) { // node starts from index of 1 // nums[0] should always be -1 !!!! tree.resize(nums.size(), nullptr); for (int i = nums.size()-1; i > 0; --i) { if (nums[i] != -1) { tree[i] = new TreeNode(nums[i]); if (2*i < nums.size()) { tree[i]->left = tree[2*i]; } if (2*i+1 < nums.size()) { tree[i]->right = tree[2*i+1]; } } } root = tree[1]; } void destroyTree() { for (int i = 1; i < tree.size(); ++i) { if (tree[i] != nullptr) { delete tree[i]; } } } public: TreeNode* root; vector<TreeNode*> tree; }; int main() { //vector<int> nums = {-1,1,3,2,5,3,-1,9}; //vector<int> nums = {-1,1,3,-1,5,3}; //vector<int> nums = {-1,1,3,2,5,-1}; vector<int> nums = {-1,1,2,-1}; BinaryTree bt; bt.buildTree(nums); Solution s; std::cout << s.widthOfBinaryTree(bt.root) << std::endl; bt.destroyTree(); return 0; }
22.623037
218
0.57371
[ "vector" ]
1d57b1c1c40b638aa56cead0ec55de6242d8f76c
14,466
cpp
C++
compiler/optimizations/inlineFunctions.cpp
afiuorio/chapel
22e502d12ed5aaacb4964be02a3c1faf4d98c627
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/optimizations/inlineFunctions.cpp
afiuorio/chapel
22e502d12ed5aaacb4964be02a3c1faf4d98c627
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
compiler/optimizations/inlineFunctions.cpp
afiuorio/chapel
22e502d12ed5aaacb4964be02a3c1faf4d98c627
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2004-2018 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is licensed under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "passes.h" #include "astutil.h" #include "driver.h" #include "expr.h" #include "optimizations.h" #include "stlUtil.h" #include "stmt.h" #include "stringutil.h" #include <set> #include <vector> static void updateRefCalls(); static void inlineFunctionsImpl(); static void inlineFunction(FnSymbol* fn, std::set<FnSymbol*>& inlinedSet); static void inlineCall(CallExpr* call); static void updateDerefCalls(); static void inlineCleanup(); /************************************* | ************************************** * * * inline all functions with the inline flag * * remove unnecessary block statements and gotos * * * ************************************** | *************************************/ void inlineFunctions() { convertToQualifiedRefs(); compute_call_sites(); updateRefCalls(); inlineFunctionsImpl(); updateDerefCalls(); inlineCleanup(); } /************************************* | ************************************** * * * inline all functions with the inline flag * * * ************************************** | *************************************/ static void inlineFunctionsImpl() { if (fNoInline == false) { std::set<FnSymbol*> inlinedSet; forv_Vec(FnSymbol, fn, gFnSymbols) { if (fn->hasFlag(FLAG_INLINE) == true && inlinedSet.find(fn) == inlinedSet.end()) { inlineFunction(fn, inlinedSet); } } } } /************************************* | ************************************** * * * Inline a function at every call site * * * ************************************** | *************************************/ static void markFunction(FnSymbol* fn, std::set<FnSymbol*>& inlinedSet); static void inlineBody(FnSymbol* fn, std::set<FnSymbol*>& inlinedSet); static void simplifyBody(FnSymbol* fn); static void inlineAtCallSites(FnSymbol* fn); static void inlineFunction(FnSymbol* fn, std::set<FnSymbol*>& inlinedSet) { markFunction(fn, inlinedSet); inlineBody(fn, inlinedSet); simplifyBody(fn); inlineAtCallSites(fn); } static void markFunction(FnSymbol* fn, std::set<FnSymbol*>& inlinedSet) { inlinedSet.insert(fn); } // // The Chapel specification requires that inlining be performed for any // procedure with this linkage specifier. It is a preventable user error // if a recursive cycle is detected (directly or indirectly) // static void inlineBody(FnSymbol* fn, std::set<FnSymbol*>& inlinedSet) { std::vector<CallExpr*> calls; collectFnCalls(fn, calls); for_vector(CallExpr, call, calls) { if (call->parentSymbol) { FnSymbol* calledFn = call->resolvedFunction(); if (calledFn->hasFlag(FLAG_INLINE)) { if (inlinedSet.find(calledFn) != inlinedSet.end()) { if (calledFn == fn) { USR_FATAL(call, "Attempt to inline a function, '%s', that calls itself", fn->name); } else { USR_FATAL(call, "Detected a cycle back to inlined function '%s' while " "inlining '%s'", calledFn->name, fn->name); } } inlineFunction(calledFn, inlinedSet); } } } } static void simplifyBody(FnSymbol* fn) { fn->collapseBlocks(); removeUnnecessaryGotos(fn); #if DEBUG_CP < 2 // That is, disabled if DEBUG_CP >= 2 if (fNoCopyPropagation == false) { singleAssignmentRefPropagation(fn); localCopyPropagation(fn); } #endif if (fNoDeadCodeElimination == false) { deadVariableElimination(fn); deadExpressionElimination(fn); } } static void inlineAtCallSites(FnSymbol* fn) { forv_Vec(CallExpr, call, *fn->calledBy) { if (call->isResolved()) { inlineCall(call); if (report_inlining) { printf("chapel compiler: reporting inlining, " "%s function was inlined\n", fn->cname); } } } } /************************************* | ************************************** * * * inlines the function called by 'call' at that call site * * * ************************************** | *************************************/ static void inlineCall(CallExpr* call) { SET_LINENO(call); // // This is the statement that contains the call. Most of the statements // in the body will be inserted immediately before this stmt. // // 1) If the function does not return a value, this stmt will be removed. // // 2) Otherwise the call will be replaced with function's return value. // // Note that if the function does not return a value or if the // call does not consume the return value, then stmt == call // Expr* stmt = call->getStmtExpr(); FnSymbol* fn = call->resolvedFunction(); BlockStmt* bCopy = copyFnBodyForInlining(call, fn, stmt); // Transfer most of the statements from the body to immediately before // the statement that that contains the call. // The final statement, which be some form of return, is handled specially. for_alist(copy, bCopy->body) { // This is not the final statement if (copy->next != NULL) { // avoid inlining another epilogue label if (DefExpr* def = toDefExpr(copy)) { if (LabelSymbol* label = toLabelSymbol(def->sym)) { label->removeFlag(FLAG_EPILOGUE_LABEL); } } stmt->insertBefore(copy->remove()); // The function does not return a value. Remove the calling statement. } else if (fn->retType == dtVoid) { stmt->remove(); // Replace the call with the return value } else { CallExpr* returnStmt = toCallExpr(copy); Expr* returnValue = returnStmt->get(1); call->replace(returnValue->remove()); } } } // // Make a copy of the function's body. The symbol map is initialized // with a map from the function's formals to the actuals for the call. // The copy is not inserted into the tree. // Any adjustments for inlining are inserted before 'stmt'. // // It is possible that a) the function being inlined takes the address // of one or more of the formals and b) that an actual for this call // is an immediate value. This currently causes a failure during code-gen. // There are several solutions to this with differing tradeoffs; we currently // choose to always replace an actual immediate with a temp. // BlockStmt* copyFnBodyForInlining(CallExpr* call, FnSymbol* fn, Expr* stmt) { SET_LINENO(call); SymbolMap map; for_formals_actuals(formal, actual, call) { Symbol* sym = toSymExpr(actual)->symbol(); // Replace an immediate actual with a temp var "just in case" if (sym->isImmediate() == true) { VarSymbol* tmp = newTemp("inlineImm", sym->type); actual->replace(new SymExpr(tmp)); stmt->insertBefore(new DefExpr(tmp)); stmt->insertBefore(new CallExpr(PRIM_MOVE, tmp, actual)); sym = tmp; } if (formal->isRef() && !sym->isRef()) { // When passing a value to a reference argument, // create a reference temporary so that nothing in the // inlined code changes meaning. VarSymbol* tmp = newTemp(astr("i_", formal->name), formal->type); DefExpr* def = new DefExpr(tmp); CallExpr* move = NULL; tmp->qual = QUAL_REF; move = new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_SET_REFERENCE, sym)); stmt->insertBefore(def); stmt->insertBefore(move); sym = tmp; } map.put(formal, sym); } BlockStmt* retval = fn->body->copy(&map); if (preserveInlinedLineNumbers == false) { reset_ast_loc(retval, call); } return retval; } /************************************* | ************************************** * * * This is transition code to support the ref cleanup work * * * ************************************** | *************************************/ static void updateDerefCalls() { if (fNoInline == false) { forv_Vec(SymExpr, se, gSymExprs) { CallExpr* def = toCallExpr(se->parentExpr); if (def && def->isPrimitive(PRIM_DEREF)) { CallExpr* move = toCallExpr(def->parentExpr); INT_ASSERT(isMoveOrAssign(move)); if (se->isRef() == false) { SET_LINENO(se); def->replace(se->copy()); } } } } } /************************************* | ************************************** * * * Either remove the dead inlined calls or do some miscellaneous cleanup. * * * ************************************** | *************************************/ static void inlineCleanup() { forv_Vec(FnSymbol, fn, gFnSymbols) { if (fNoInline == false && fn->hasFlag(FLAG_INLINE) == true && fn->hasFlag(FLAG_VIRTUAL) == false) { fn->defPoint->remove(); } else { fn->collapseBlocks(); removeUnnecessaryGotos(fn); } } } /************************************* | ************************************** * * * NOAKES 2016/11/17 * * * * The following is transition logic while ref intents are being cleaned up. * * * * It was being applied in the inner loop of inlineFunctions but * * 1) That made inlineFunctions() a little more convoluted * * 2) This transformation could/should be applied more generally * * * * There are now many functions that have at least one formal with a ref * * intent and, correctly, a non-ref type e.g. a Record rather than a * * Class _ref(Record). However there are still call sites that continue to * * pass a temp that is Class _ref(t). * * * * The longer term path is to eliminate the creation of those ref types but in * * the short term this inserts another tmp var that has the correct type and * * then uses a relatively new PRIMOP to fix up the type information. * * * * NB: This function assumes that compute_call_sites() has been called. * * * ************************************** | *************************************/ static bool hasFormalWithRefIntent(FnSymbol* fn); static void updateRefCalls() { forv_Vec(FnSymbol, fn, gFnSymbols) { if (hasFormalWithRefIntent(fn) == true) { // Walk all of the call-sites and check types of actuals vs. formals forv_Vec(CallExpr, call, *fn->calledBy) { if (call->isResolved()) { Expr* stmt = call->getStmtExpr(); SET_LINENO(call); for_formals_actuals(formal, actual, call) { SymExpr* se = toSymExpr(actual); // Is this a case in which we are Passing an actual that is // a ref(t) to a formal with type t and intent ref? // // If so modify the call site and // // a) Introduce a tmp with qualified type ref t // b) Pass that tmp instead if ((formal->intent & INTENT_REF) != 0 && isReferenceType(formal->type) == false && formal->type->getRefType() == actual->typeInfo()) { // Introduce a ref temp VarSymbol* tmp = newTemp(astr("i_", formal->name), formal->type); DefExpr* def = new DefExpr(tmp); CallExpr* move = NULL; tmp->qual = QUAL_REF; move = new CallExpr(PRIM_MOVE, tmp, new CallExpr(PRIM_SET_REFERENCE, se->symbol())); stmt->insertBefore(def); stmt->insertBefore(move); // Replace the actual with the ref-temp actual->replace(new SymExpr(tmp)); } } } } } } } static bool hasFormalWithRefIntent(FnSymbol* fn) { for_formals(formal, fn) { if ((formal->intent & INTENT_REF) != 0 && isReferenceType(formal->type) == false) { return true; } } return false; }
34.442857
79
0.496474
[ "vector" ]
1d5a5479fa3386773815ba4ad6061e9d68a14237
2,131
cpp
C++
74.SearchA2DMatrix.cpp
mrdrivingduck/leet-code
fee008f3a62849a21ca703e05f755378996a1ff5
[ "MIT" ]
null
null
null
74.SearchA2DMatrix.cpp
mrdrivingduck/leet-code
fee008f3a62849a21ca703e05f755378996a1ff5
[ "MIT" ]
null
null
null
74.SearchA2DMatrix.cpp
mrdrivingduck/leet-code
fee008f3a62849a21ca703e05f755378996a1ff5
[ "MIT" ]
null
null
null
/** * @author Mr Dk. * @version 2021/03/30 */ /* Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties: Integers in each row are sorted from left to right. The first integer of each row is greater than the last integer of the previous row. Example 1: Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3 Output: true Example 2: Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13 Output: false Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 100 -104 <= matrix[i][j], target <= 104 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/search-a-2d-matrix 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 */ /* 首先根据矩阵第一列的数组进行二分查找,确定元素所在的行;然后再对 该行进行二分查找。 */ #include <cassert> #include <iostream> #include <vector> #include <algorithm> using std::cout; using std::endl; using std::vector; class Solution { public: bool searchMatrix(vector<vector<int>>& matrix, int target) { int left = 0; int right = matrix.size() - 1; while (left < right) { int mid = (left + right) / 2; if (matrix[mid][0] > target) { right = mid - 1; } else if (matrix[mid][0] < target) { if (mid + 1 < (int) matrix.size() && matrix[mid + 1][0] > target) { left = mid; right = mid; } else { left = mid + 1; } } else { return true; } } return std::binary_search(matrix[left].begin(), matrix[left].end(), target); } }; int main() { Solution s; vector<vector<int>> matrix; matrix = { { 1 }, { 3 }, }; assert(true == s.searchMatrix(matrix, 3)); matrix = { { 1,3,5,7 }, { 10,11,16,20 }, { 23,30,34,60 } }; assert(true == s.searchMatrix(matrix, 3)); assert(false == s.searchMatrix(matrix, 13)); return 0; }
22.670213
84
0.51572
[ "vector" ]
1d5f8c3929f14ad0f90aec3fa39904eaa3e723b1
6,061
cxx
C++
Modules/Registration/Common/test/itkImageRegistrationMethodTest_11.cxx
rdsouza10/ITK
07cb23f9866768b5f4ee48ebec8766b6e19efc69
[ "Apache-2.0" ]
3
2019-11-19T09:47:25.000Z
2022-02-24T00:32:31.000Z
Modules/Registration/Common/test/itkImageRegistrationMethodTest_11.cxx
JamesLinus/ITK
01fb2f2a97ae7767b7835dd92b40b6cc2c82e750
[ "Apache-2.0" ]
1
2019-03-18T14:19:49.000Z
2020-01-11T13:54:33.000Z
Modules/Registration/Common/test/itkImageRegistrationMethodTest_11.cxx
JamesLinus/ITK
01fb2f2a97ae7767b7835dd92b40b6cc2c82e750
[ "Apache-2.0" ]
1
2022-02-24T00:32:36.000Z
2022-02-24T00:32:36.000Z
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkImageRegistrationMethod.h" #include "itkTranslationTransform.h" #include "itkMeanReciprocalSquareDifferenceImageToImageMetric.h" #include "itkLinearInterpolateImageFunction.h" #include "itkGradientDescentOptimizer.h" #include "itkTestingMacros.h" /** * This program test one instantiation of the itk::ImageRegistrationMethod class * * Only typedef are tested in this file. */ int itkImageRegistrationMethodTest_11(int, char* [] ) { const unsigned int dimension = 3; // Fixed Image Type typedef itk::Image<float,dimension> FixedImageType; // Moving Image Type typedef itk::Image<char,dimension> MovingImageType; // Transform Type typedef itk::TranslationTransform< double,dimension > TransformType; // Optimizer Type typedef itk::GradientDescentOptimizer OptimizerType; // Metric Type typedef itk::MeanReciprocalSquareDifferenceImageToImageMetric< FixedImageType, MovingImageType > MetricType; // Interpolation technique typedef itk:: LinearInterpolateImageFunction< MovingImageType, double > InterpolatorType; // Registration Method typedef itk::ImageRegistrationMethod< FixedImageType, MovingImageType > RegistrationType; MetricType::Pointer metric = MetricType::New(); TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); FixedImageType::Pointer fixedImage = FixedImageType::New(); MovingImageType::Pointer movingImage = MovingImageType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); RegistrationType::Pointer registration = RegistrationType::New(); registration->SetMetric( metric ); registration->SetOptimizer( optimizer ); registration->SetTransform( transform ); registration->SetFixedImage( fixedImage ); registration->SetMovingImage( movingImage ); registration->SetInterpolator( interpolator ); // // Now verify that all the sets are consistent with the Gets // TEST_SET_GET_VALUE( metric, registration->GetMetric() ); TEST_SET_GET_VALUE( optimizer, registration->GetOptimizer() ); TEST_SET_GET_VALUE( transform, registration->GetTransform() ); TEST_SET_GET_VALUE( fixedImage, registration->GetFixedImage() ); TEST_SET_GET_VALUE( movingImage, registration->GetMovingImage() ); TEST_SET_GET_VALUE( interpolator, registration->GetInterpolator() ); // // Now verify that they can be changed // MetricType::Pointer metric2 = MetricType::New(); TransformType::Pointer transform2 = TransformType::New(); OptimizerType::Pointer optimizer2 = OptimizerType::New(); FixedImageType::Pointer fixedImage2 = FixedImageType::New(); MovingImageType::Pointer movingImage2 = MovingImageType::New(); InterpolatorType::Pointer interpolator2 = InterpolatorType::New(); registration->SetMetric( metric2 ); registration->SetOptimizer( optimizer2 ); registration->SetTransform( transform2 ); registration->SetFixedImage( fixedImage2 ); registration->SetMovingImage( movingImage2 ); registration->SetInterpolator( interpolator2 ); // // Now verify that all the sets are consistent with the Gets // TEST_SET_GET_VALUE( metric2, registration->GetMetric() ); TEST_SET_GET_VALUE( optimizer2, registration->GetOptimizer() ); TEST_SET_GET_VALUE( transform2, registration->GetTransform() ); TEST_SET_GET_VALUE( fixedImage2, registration->GetFixedImage() ); TEST_SET_GET_VALUE( movingImage2, registration->GetMovingImage() ); TEST_SET_GET_VALUE( interpolator2, registration->GetInterpolator() ); // // Now verify that they can be set to ITK_NULLPTR // MetricType::Pointer metric3 = ITK_NULLPTR; TransformType::Pointer transform3 = ITK_NULLPTR; OptimizerType::Pointer optimizer3 = ITK_NULLPTR; FixedImageType::Pointer fixedImage3 = ITK_NULLPTR; MovingImageType::Pointer movingImage3 = ITK_NULLPTR; InterpolatorType::Pointer interpolator3 = ITK_NULLPTR; registration->SetMetric( metric3 ); registration->SetOptimizer( optimizer3 ); registration->SetTransform( transform3 ); registration->SetFixedImage( fixedImage3 ); registration->SetMovingImage( movingImage3 ); registration->SetInterpolator( interpolator3 ); // // Now verify that all the sets are consistent with the Gets // TEST_SET_GET_VALUE( metric3, registration->GetMetric() ); TEST_SET_GET_VALUE( optimizer3, registration->GetOptimizer() ); TEST_SET_GET_VALUE( transform3, registration->GetTransform() ); TEST_SET_GET_VALUE( fixedImage3, registration->GetFixedImage() ); TEST_SET_GET_VALUE( movingImage3, registration->GetMovingImage() ); TEST_SET_GET_VALUE( interpolator3, registration->GetInterpolator() ); std::cout << "Test passed." << std::endl; return EXIT_SUCCESS; }
38.852564
81
0.673651
[ "transform" ]
1d60c02862a28f2ebde2a0985eb9a652b55bba7b
2,783
cpp
C++
src/genetic/gen_alg.cpp
spitefulowl/qap-solver
490e14669e0fefe048c95ee2c709c271c06a4331
[ "MIT" ]
null
null
null
src/genetic/gen_alg.cpp
spitefulowl/qap-solver
490e14669e0fefe048c95ee2c709c271c06a4331
[ "MIT" ]
null
null
null
src/genetic/gen_alg.cpp
spitefulowl/qap-solver
490e14669e0fefe048c95ee2c709c271c06a4331
[ "MIT" ]
null
null
null
#include "genetic/gen_alg.h" namespace genetic { gen_alg::gen_alg(base_generation* generation, base_crossover* crossover, base_mutation* mutation, base_selection* selection, utils::matrix_t* data_volume, utils::matrix_t* transfer_cost, std::size_t iterations, std::size_t population_size, std::size_t probability, std::size_t beta) : data_volume(*data_volume), transfer_cost(*transfer_cost), calc(nullptr), generation(generation), crossover(crossover), mutation(mutation), selection(selection), iterations(iterations), population_size(population_size) , probability(probability), beta(beta) { calc = new utils::calculator(data_volume, transfer_cost); } gen_alg::gen_alg(const gen_alg& other_gen_alg) : data_volume(other_gen_alg.data_volume), transfer_cost(other_gen_alg.transfer_cost) { this->iterations = other_gen_alg.iterations; this->population_size = other_gen_alg.population_size; this->probability = other_gen_alg.probability; this->beta = other_gen_alg.beta; this->calc = new utils::calculator(&data_volume, &transfer_cost); this->generation = other_gen_alg.generation->clone(); this->crossover = other_gen_alg.crossover->clone(); this->mutation = other_gen_alg.mutation->clone(); this->selection = other_gen_alg.selection->clone(); } void gen_alg::execute(permutation& base_permutation_r) { std::vector<std::size_t> base_permutation = base_permutation_r.extract(); base_permutation.resize(base_permutation_r.determined_size()); generation->init(base_permutation, base_permutation_r.size(), population_size, random); std::vector<std::vector<std::size_t>>* my_population = nullptr; std::size_t start_idx = base_permutation.size(); std::vector<std::size_t> result; my_population = generation->exec(); for (std::size_t iter = 0; iter < iterations; ++iter) { crossover->init(my_population, start_idx, random); crossover->exec(); auto* descendants = crossover->get_descendants(); mutation->init(descendants, probability, start_idx, random); mutation->exec(); selection->init(&data_volume, &transfer_cost, my_population, descendants, beta, random); auto* my_population_tmp = selection->exec(); delete descendants; delete my_population; my_population = my_population_tmp; } if (result.size() > 0) { my_population->push_back(result); } result = *std::min_element(my_population->begin(), my_population->end(), [this](auto& first, auto& second) { std::size_t first_c = this->calc->criterion(first); std::size_t second_c = this->calc->criterion(second); return first_c < second_c; }); delete my_population; auto prepared_result = permutation(result); prepared_result.copy_to(base_permutation_r); } gen_alg::~gen_alg() { delete generation; delete crossover; delete mutation; delete selection; delete calc; } }
40.926471
133
0.763205
[ "vector" ]
1d6217c5fffd8efe743dd0f718963e4cc987cd9d
23,932
cpp
C++
source/loonyland/title.cpp
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
source/loonyland/title.cpp
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
source/loonyland/title.cpp
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
#include "title.h" #include "game.h" #include "jamulfmv.h" #include "pause.h" #include "options.h" #include "pause.h" #include "plasma.h" #include "palettes.h" #include "appdata.h" // special codes in the credits: // @ = use GirlsRWeird font // # = draw a major horizontal line // % = draw a minor horizontal line // $ = last line of the whole deal char credits[][32]={ "@LoonyLand:", "", "@Halloween Hill", "", "", "Copyright 2004, Hamumu Software", "#", "Original Concept", "Mike Hommel", "%", "Programming", "Mike Hommel", "%", "Character Design", "Mike Hommel", "%", "Level Design", "Mike Hommel", "%", "3D Graphics", "Mike Hommel", "%", "2D Graphics", "Mark Stevens", "Mike Hommel", "%", "Sound Effects", "Solange Hunt", "Mike Hommel", "%", "\"Music\"", "Mike Hommel", "%", "Testing", "Eric Arevalo", "Solange Hunt", "BJ McRae", "Barry Pennington", "Mark Stevens", "Carol \"Baba\" VanderMolen", "%", "Muse", "Solange Hunt", "%", "This game goes out as", "a special thanks to the", "Dr. Lunatic fans!!", "Keep me fed, and I'll keep", "making these things...", "", "#", "Stop by www.hamumu.com!", "","","","","","","","","","","","","","","","","","","", "P.S.... watch for", "Loonyland: Insanity", "and", "Sol Hunt", "coming soon!!", "$" }; char victoryTxt[][64]={ "", "", "After a little time to rest and wipe off a whole", "", "lot of mud, Loony got back to his feet and returned", "", "to Luniton, a hero at last.", "", "", "", "#", "", "", "All around the land of Halloween Hill, life was", "", "returning to normal. The frogs stopped licking", "", "so viciously, the mummies settled down and returned", "", "to their work in the toilet paper industry - Even", "", "the werewolves went back to their den to take a nap.", "", "Yes, everything was back to being as peaceful as it", "", "gets in Halloween Hill. Which, by the way, is not", "", "terribly peaceful.", "", "", "", "", "", "#", "", "", "There was just one thing wrong...", "", "The trees in the south of Wicked Woods were still", "", "hung with stick figures. Almost as if the evil", "", "presence there hadn't been the result of the", "", "Evilizer at all... and was still lurking somewhere.", "$" }; char cheatTxt[][64]={ "@Congratulations on getting", "", "", "@all 40 Merit Badges!", "", "", "#", "So since you've proven you don't need them,", "here are the cheat codes to the game!", "", "These ones are to be typed in while playing:", "", "%", "SUPERBOOM", "Causes tremendous explosions to wipe out enemies", "", "%", "GETALIFE", "Heals you to your full health", "", "%", "BANGZOOM", "Renders you invulnerable for a long time", "", "%", "GOGOGO", "Gives you double speed for a while", "", "", "#", "These cheats must be entered in the Badges screen,", "while holding down both fire buttons:", "", "%", "GIMME", "Gives you the merit badge you have highlighted", "If you already have it, it removes it instead", "", "%", "GIVEALL", "Gives you every merit badge", "", "%", "CLEAR", "Removes all merit badges, letting you make a fresh", "start if you want to earn them all again - also", "marks all bosses un-beaten, for Boss Bash mode", "", "%", "BOSSBASH", "Mark all bosses beaten for purposes of playing Boss", "Bash mode", "", "#", "", "Oh, and one other thing... start a new game as", "Loony or Werewolf Loony for a special surprise!", "", "#", "", "@Thank you for playing Loonyland!", "", "", "@Look for more good stuff coming soon at", "", "", "@WWW.HAMUMU.COM", "$", }; // once the credits have scrolled to END_OF_CREDITS pixels, they end #define END_OF_CREDITS 480*4-330 #define END_OF_VICTORY 480*2 #define END_OF_CHEATS 480*3-100 // the most custom worlds it will handle #define MAX_CUSTOM (64-5) #define VERSION_NO "Version 2.0" sprite_set_t *planetSpr; static int numRunsToMakeUp; static byte oldc=0; static byte keyAnim=0; char lvlName[32]; static byte cursor; byte *backScr; int numRuns; byte demoTextCounter; byte songRestart; static byte loadingGame; typedef struct menu_t { char txt[64]; byte known; char bright; } menu_t; menu_t menu[MENU_CHOICES]={ {"New Game",1,-32}, {"Load Game",1,-32}, {"Randomizer",1,-32}, //{"Bowling",0,-32}, //{"Survival",0,-32}, //{"Boss Bash",0,-32}, //{"Loony Ball",0,-32}, //{"Remix",0,-32}, {"Badges",0,-32}, {"Hi Scores",1,-32}, {"Options",1,-32}, {"Editor",1,-32}, {"Exit",1,-32}, {"!",0,-32} }; menu_t saves[5]; byte choosingDiffFor; byte HandleTitleKeys(MGLDraw *mgl) { char k; k=mgl->LastKeyPressed(); if(k=='e') return 1; // go to the editor if(k==27) return 2; // exit else return 0; // play the game } void SetSongRestart(byte b) { songRestart=b; } byte WhichGameToLoad(void) { return cursor; } void GetSavesForMenu(void) { FILE *f; int i; char txt[64]; float pct; player_t p; for(i=0;i<5;i++) { sprintf(txt,"save%d.sav",i+1); f=AppdataOpen(txt,"rb"); if(!f) { pct=0.0; sprintf(txt,"Unused"); saves[i].known=0; } else { fread(&p,sizeof(player_t),1,f); fclose(f); pct=CalcPercent(&p); if(p.worldNum==WORLD_NORMAL) strcpy(txt,p.areaName); else sprintf(txt,"*%s",p.areaName); saves[i].known=1; } sprintf(saves[i].txt,"%s - %0.1f%%",txt,pct); saves[i].bright=-32; } } TASK(byte) LunaticTitle(MGLDraw *mgl) { mgl->LoadBMP("graphics/title.bmp"); AWAIT mgl->Flip(); while(!mgl->LastKeyPeek()) { if(!mgl->Process()) CO_RETURN 2; AWAIT mgl->Flip(); } CO_RETURN HandleTitleKeys(mgl); } void ShowMenuOption(int x,int y,menu_t m,byte on) { int i; if(m.known) { PrintGlow(x,y,m.txt,m.bright,2); if(on && m.bright>-20) { PrintGlow(x-4+Random(9),y-4+Random(9),m.txt,-20,2); } } else // if this option is unknown { // bouncy question marks! if(on) { for(i=0;i<8;i++) { PrintGlow(x+i*16-2+Random(5),y-2+Random(5),"?",m.bright,2); } } else { PrintGlow(x,y,"????????",m.bright,2); } } } void ShowSavedGame(int x,int y,menu_t m,byte on) { PrintGlow(x,y,m.txt,m.bright,0); if(on && m.bright>-20) { PrintGlow(x-2+Random(5),y-2+Random(5),m.txt,-20,0); } } void MainMenuDisplay(MGLDraw *mgl) { int i; int x,y; for(i=0;i<480;i++) memcpy(mgl->GetScreen()+mgl->GetWidth()*i,&backScr[i*640],640); // version #: Print(555,3,VERSION_NO,1,1); Print(554,2,VERSION_NO,0,1); // Copyright: PrintGlow(395,467,"Copyright 2004, Hamumu Software",-10,1); // menu options x=5; y=320; for(i=0;i<MENU_CHOICES;i++) { if(menu[i].txt[0]!='!') ShowMenuOption(x,y-menu[i].bright/4,menu[i],(cursor==i)); x+=160; if(x>640-150) { x=5; y+=45; } } } void DiffChooseDisplay(MGLDraw *mgl) { int i; char diffName[6][16]={"Beginner","Normal","Challenge","Mad","Loony", "Rando Special"}; char diffDesc[][128]={ // beginner "Enemies never do more than 1 Heart of damage, and move slower than normal. You", "begin with 15 Hearts, and do extra damage. Enemies drop more items than normal.", "", // normal "The standard difficulty. Good for someone who has an idea of what they're doing!", "You begin with 10 Hearts.", "", // challenge "If you're looking for a bigger challenge, this is it! Enemies do more damage, and", "you do less. You begin with 5 Hearts, and enemies drop fewer items.", "", // mad "A special difficulty to inject more skillful play into the late-game, although it makes", "the early going very tough. Only for Loonyland aficionados. You begin with 3 Hearts", "and enemies are much tougher to beat.", // Loony "For masochists. Enemies do double damage, you do 1/4 damage, you begin with ONE", "Heart, poison is twice as deadly, enemies move faster, and enemies only drop items", "when Combo'd!", // Loony "Intended difficulty for the randomizer. It's mostly challenge mode, but enemies", "take damage like normal mode so they aren't super bulky, and item drops are", "slightly better than challenge and slightly worse than normal" }; for(i=0;i<480;i++) memcpy(mgl->GetScreen()+mgl->GetWidth()*i,&backScr[i*640],640); // version #: Print(560,3,VERSION_NO,1,1); Print(559,2,VERSION_NO,0,1); PrintGlow(5,330,"Difficulty Level:",0,2); if(opt.difficulty>0) PrintGlow(280,330,"<<<",0,2); CenterPrintGlow(440,330,diffName[opt.difficulty],0,2); CenterPrintGlow(440-4+Random(9),330-4+Random(9),diffName[opt.difficulty],-20,2); if(opt.difficulty<5) PrintGlow(560,330,">>>",0,2); PrintGlow(5,450,"The chosen difficulty applies to all game modes. You can change it at any time",0,1); PrintGlow(5,465,"in the Options menu on the title screen, but that doesn't affect saved games.",0,1); PrintGlow(310,318,"Select with arrow keys and press Enter",0,1); for(i=0;i<3;i++) { PrintGlow(5,390+i*15,diffDesc[opt.difficulty*3+i],0,1); } } void LoadGameDisplay(MGLDraw *mgl) { int i; int x,y; for(i=0;i<480;i++) memcpy(mgl->GetScreen()+mgl->GetWidth()*i,&backScr[i*640],640); // version #: Print(560,3,VERSION_NO,1,1); Print(559,2,VERSION_NO,0,1); // Copyright: PrintGlow(395,467,"Copyright 2004, Hamumu Software",-10,1); PrintGlow(5,360,"Select a game to load",0,0); PrintGlow(5,390,"Or press ESC to cancel",0,0); // menu options x=320; y=320; for(i=0;i<5;i++) { ShowSavedGame(x,y-menu[i].bright/4,saves[i],(cursor==i)); y+=26; } } byte MainMenuUpdate(int *lastTime,MGLDraw *mgl) { byte c; static byte reptCounter=0; int i; if(*lastTime>TIME_PER_FRAME*30) *lastTime=TIME_PER_FRAME*30; while(*lastTime>=TIME_PER_FRAME) { for(i=0;i<MENU_CHOICES;i++) { if(cursor==i) { if(menu[i].bright<0) menu[i].bright++; } else { if(menu[i].bright>-23) menu[i].bright--; else if(menu[i].bright<-23) menu[i].bright++; } } // now real updating c=GetControls()|GetArrows(); if((c&CONTROL_UP) && !(oldc&CONTROL_UP)) { cursor-=4; if(cursor>=MENU_CHOICES) cursor+=MENU_CHOICES; if(menu[cursor].txt[0]=='!') { cursor-=4; if(cursor>=MENU_CHOICES) cursor+=MENU_CHOICES; } MakeNormalSound(SND_MENUCLICK); } if((c&CONTROL_DN) && !(oldc&CONTROL_DN)) { cursor+=4; if(cursor>=MENU_CHOICES) cursor-=MENU_CHOICES; if(menu[cursor].txt[0]=='!') { cursor-=8; if(cursor>=MENU_CHOICES) cursor-=MENU_CHOICES; } MakeNormalSound(SND_MENUCLICK); } if((c&CONTROL_LF) && !(oldc&CONTROL_LF)) { cursor--; if(cursor>=MENU_CHOICES) cursor+=MENU_CHOICES; if(cursor%4==3) { cursor+=4; if(cursor>=MENU_CHOICES) cursor-=MENU_CHOICES; } if(menu[cursor].txt[0]=='!') { cursor--; } MakeNormalSound(SND_MENUCLICK); } if((c&CONTROL_RT) && !(oldc&CONTROL_RT)) { cursor++; if(cursor>=MENU_CHOICES) cursor-=MENU_CHOICES; if(cursor%4==0) { cursor-=4; if(cursor>=MENU_CHOICES) cursor+=MENU_CHOICES; } if(menu[cursor].txt[0]=='!') { cursor-=3; } MakeNormalSound(SND_MENUCLICK); } if((c&(CONTROL_B1|CONTROL_B2)) && !(oldc&(CONTROL_B1|CONTROL_B2))) { if(menu[cursor].known) { MakeNormalSound(SND_MENUSELECT); return cursor+1; } else MakeNormalSound(SND_MENUCANCEL); } if(c) // hitting any key prevents credits numRuns=0; oldc=c; c=mgl->LastKeyPressed(); if(c==27) return MENU_EXIT+1; #ifdef _DEBUG if(c=='e') return MENU_EDITOR+1; #endif *lastTime-=TIME_PER_FRAME; numRuns++; } return 0; } byte LoadGameUpdate(int *lastTime,MGLDraw *mgl) { byte c; int i; if(*lastTime>TIME_PER_FRAME*30) *lastTime=TIME_PER_FRAME*30; while(*lastTime>=TIME_PER_FRAME) { for(i=0;i<5;i++) { if(cursor==i) { if(saves[i].bright<0) saves[i].bright++; } else { if(saves[i].bright>-23) saves[i].bright--; else if(saves[i].bright<-23) saves[i].bright++; } } // now real updating c=GetControls()|GetArrows(); if((c&CONTROL_UP) && !(oldc&CONTROL_UP)) { cursor--; if(cursor>4) cursor=4; MakeNormalSound(SND_MENUCLICK); } if((c&CONTROL_DN) && !(oldc&CONTROL_DN)) { cursor++; if(cursor>4) cursor=0; MakeNormalSound(SND_MENUCLICK); } if((c&(CONTROL_B1|CONTROL_B2)) && !(oldc&(CONTROL_B1|CONTROL_B2))) { if(saves[cursor].known) { MakeNormalSound(SND_MENUSELECT); return 2; } else MakeNormalSound(SND_MENUCANCEL); } // no credits while sitting here numRuns=0; oldc=c; c=mgl->LastKeyPressed(); if(c==27) { MakeNormalSound(SND_MENUCANCEL); return 0; } *lastTime-=TIME_PER_FRAME; numRuns++; } return 1; } byte ChooseDiffUpdate(int *lastTime,MGLDraw *mgl) { byte c; if(*lastTime>TIME_PER_FRAME*30) *lastTime=TIME_PER_FRAME*30; while(*lastTime>=TIME_PER_FRAME) { // now real updating c=GetControls()|GetArrows(); if((c&CONTROL_LF) && !(oldc&CONTROL_LF)) { if(opt.difficulty>0) opt.difficulty--; MakeNormalSound(SND_MENUCLICK); } if((c&CONTROL_RT) && !(oldc&CONTROL_RT)) { if(opt.difficulty<5) opt.difficulty++; MakeNormalSound(SND_MENUCLICK); } if((c&(CONTROL_B1|CONTROL_B2)) && !(oldc&(CONTROL_B1|CONTROL_B2))) { MakeNormalSound(SND_MENUSELECT); SaveOptions(); return 2; } // no credits while sitting here numRuns=0; oldc=c; c=mgl->LastKeyPressed(); if(c==27) { MakeNormalSound(SND_MENUCANCEL); return 0; } *lastTime-=TIME_PER_FRAME; numRuns++; } return 1; } TASK(byte) MainMenu(MGLDraw *mgl) { byte b=0; int i; int lastTime=1; if(songRestart) { JamulSoundPurge(); LoopingSound(SND_HAMUMU); } for(i=0;i<MENU_CHOICES;i++) menu[i].bright=-32; mgl->LoadBMP("graphics/title.bmp"); if(opt.cheats[CH_VINTAGE]) GreyPalette(mgl); mgl->LastKeyPressed(); oldc=255;//CONTROL_B1|CONTROL_B2; backScr=(byte *)malloc(640*480); if(!backScr) FatalError("Out of memory!"); for(i=0;i<480;i++) memcpy(&backScr[i*640],mgl->GetScreen()+mgl->GetWidth()*i,640); menu[MENU_BADGES].known=1; menu[MENU_RANDOMIZER].known=1; cursor=0; loadingGame=0; GetTaps(); while(b==0) { lastTime+=TimeLength(); StartClock(); if(loadingGame==0) { b=MainMenuUpdate(&lastTime,mgl); MainMenuDisplay(mgl); } else if(loadingGame==1) { b=LoadGameUpdate(&lastTime,mgl); LoadGameDisplay(mgl); if(b==0) { for(i=0;i<MENU_CHOICES;i++) menu[i].bright=-32; cursor=1; loadingGame=0; } else if(b==2) { free(backScr); CO_RETURN MENU_LOADGAME+1; } b=0; } else { b=ChooseDiffUpdate(&lastTime,mgl); DiffChooseDisplay(mgl); if(b==0) { cursor=0; loadingGame=0; } else if(b==2) { free(backScr); if(choosingDiffFor==0) CO_RETURN MENU_ADVENTURE+1; else CO_RETURN MENU_REMIX+1; } b=0; } AWAIT mgl->Flip(); if(!mgl->Process()) { free(backScr); CO_RETURN 255; } EndClock(); if(!loadingGame && numRuns>=30*15) { GetTaps(); oldc=255; AWAIT Credits(mgl,1); mgl->LoadBMP("graphics/title.bmp"); numRuns=0; } if(!loadingGame && b==MENU_LOADGAME+1) { loadingGame=1; GetSavesForMenu(); cursor=0; b=0; oldc=255; } if(!loadingGame && b==MENU_ADVENTURE+1) { loadingGame=2; choosingDiffFor=0; cursor=0; b=0; oldc=255; } if(!loadingGame && b==MENU_REMIX+1) { loadingGame=2; choosingDiffFor=1; cursor=0; b=0; oldc=255; } } free(backScr); CO_RETURN b; } void CreditsRender(int y) { int i,ypos; char *s; char b; i=0; ypos=0; while(credits[i][0]!='$') { s=credits[i]; if(ypos-y>-60) { if(ypos-y>240) b=-((ypos-y)-300)/10; else b=0; if(b>0) b=0; if(s[0]=='@') { CenterPrintColor(320,ypos-y,&s[1],4,b,2); } else if(s[0]=='#') { DrawFillBox(320-200,ypos-y+8,320+200,ypos-y+11,4*32+31+b); } else if(s[0]=='%') { DrawFillBox(320-70,ypos-y+8,320+70,ypos-y+9,4*32+31+b); } else CenterPrintColor(320,ypos-y,s,4,b,1); } ypos+=20; i++; if(ypos-y>=480) return; } } TASK(void) Credits(MGLDraw *mgl,byte init) { int y=-470; int lastTime; int wid; byte* pos; int i; dword hangon; EndClock(); hangon=TimeLength(); mgl->LastKeyPressed(); mgl->LoadBMP("graphics/title.bmp"); lastTime=1; if(init) InitPlasma(4); hangon=0; for(i=0;i<40;i++) if(opt.meritBadge[i]) hangon++; if(hangon==40) AWAIT CheatText(mgl,0); while(1) { lastTime+=TimeLength(); StartClock(); wid=mgl->GetWidth(); pos=mgl->GetScreen()+0*wid; for(i=0;i<480;i++) { memset((byte *)pos,4*32+2,640); pos+=wid; } RenderPlasma2(mgl); CreditsRender(y); if(lastTime>TIME_PER_FRAME*30) lastTime=TIME_PER_FRAME*30; while(lastTime>=TIME_PER_FRAME) { y+=1; UpdatePlasma(); lastTime-=TIME_PER_FRAME; } AWAIT mgl->Flip(); EndClock(); if(!mgl->Process()) { ExitPlasma(); ResetClock(hangon); CO_RETURN; } if(mgl->LastKeyPressed()) { ExitPlasma(); ResetClock(hangon); CO_RETURN; } if(y==END_OF_CREDITS) { ExitPlasma(); ResetClock(hangon); CO_RETURN; } } ResetClock(hangon); } void CheatsRender(int y) { int i,ypos; char *s; char b; i=0; ypos=0; while(cheatTxt[i][0]!='$') { s=cheatTxt[i]; if(ypos-y>-60) { if(ypos-y>240) b=-((ypos-y)-300)/10; else b=0; if(b>0) b=0; if(s[0]=='@') { CenterPrintColor(320,ypos-y,&s[1],4,b,2); } else if(s[0]=='#') { DrawFillBox(320-200,ypos-y+8,320+200,ypos-y+11,4*32+31+b); } else if(s[0]=='%') { DrawFillBox(320-70,ypos-y+8,320+70,ypos-y+9,4*32+31+b); } else CenterPrintColor(320,ypos-y,s,4,b,1); } ypos+=20; i++; if(ypos-y>=480) return; } } TASK(void) CheatText(MGLDraw *mgl,byte init) { int y=-470; int lastTime; int wid; byte* pos; int i; dword hangon; EndClock(); hangon=TimeLength(); mgl->LastKeyPressed(); mgl->LoadBMP("graphics/title.bmp"); lastTime=1; if(init) InitPlasma(4); while(1) { lastTime+=TimeLength(); StartClock(); wid=mgl->GetWidth(); pos=mgl->GetScreen()+0*wid; for(i=0;i<480;i++) { memset(pos,4*32+2,640); pos+=wid; } RenderPlasma2(mgl); CheatsRender(y); if(lastTime>TIME_PER_FRAME*30) lastTime=TIME_PER_FRAME*30; while(lastTime>=TIME_PER_FRAME) { y+=1; UpdatePlasma(); lastTime-=TIME_PER_FRAME; } AWAIT mgl->Flip(); EndClock(); if(!mgl->Process()) { ExitPlasma(); ResetClock(hangon); CO_RETURN; } if(mgl->LastKeyPressed()) { ExitPlasma(); ResetClock(hangon); CO_RETURN; } if(y==END_OF_CHEATS) { ExitPlasma(); ResetClock(hangon); CO_RETURN; } } ResetClock(hangon); } void VictoryTextRender(int y) { int i,ypos; char *s; char b; i=0; ypos=0; while(victoryTxt[i][0]!='$') { s=victoryTxt[i]; if(ypos-y>-60) { if(ypos-y>240) b=-((ypos-y)-300)/10; else b=0; if(b>0) b=0; if(s[0]=='@') { CenterPrintColor(320,ypos-y,&s[1],4,b,2); } else if(s[0]=='#') { DrawFillBox(320-200,ypos-y+8,320+200,ypos-y+11,4*32+31+b); } else if(s[0]=='%') { DrawFillBox(320-70,ypos-y+8,320+70,ypos-y+9,4*32+31+b); } else CenterPrintColor(320,ypos-y,s,4,b,0); } ypos+=20; i++; if(ypos-y>=480) return; } } TASK(void) VictoryText(MGLDraw *mgl) { int y=-470; int lastTime; int wid; byte* pos; int i; dword hangon; EndClock(); hangon=TimeLength(); lastTime=1; mgl->LastKeyPressed(); mgl->LoadBMP("graphics/title.bmp"); InitPlasma(4); while(1) { lastTime+=TimeLength(); StartClock(); wid=mgl->GetWidth(); pos=mgl->GetScreen()+0*wid; for(i=0;i<480;i++) { memset(pos,4*32+2,640); pos+=wid; } RenderPlasma2(mgl); VictoryTextRender(y); if(lastTime>TIME_PER_FRAME*30) lastTime=TIME_PER_FRAME*30; while(lastTime>=TIME_PER_FRAME) { y++; UpdatePlasma(); lastTime-=TIME_PER_FRAME; } AWAIT mgl->Flip(); EndClock(); if(!mgl->Process()) { ResetClock(hangon); CO_RETURN; } if(mgl->LastKeyPressed()==27) { ResetClock(hangon); CO_RETURN; } if(y==END_OF_VICTORY) { ResetClock(hangon); CO_RETURN; } } ResetClock(hangon); } TASK(byte) SpeedSplash(MGLDraw *mgl,const char *fname) { int i,j,clock; RGB desiredpal[256],curpal[256]; byte mode,done; byte c,oldc; for(i=0;i<256;i++) { curpal[i].r=0; curpal[i].g=0; curpal[i].b=0; } mgl->SetPalette(curpal); mgl->RealizePalette(); mgl->LastKeyPressed(); oldc=GetControls()|GetArrows(); if (!mgl->LoadBMP(fname, desiredpal)) CO_RETURN 0; mode=0; clock=0; done=0; while(!done) { AWAIT mgl->Flip(); if(!mgl->Process()) CO_RETURN 0; c=mgl->LastKeyPressed(); if(c==27) CO_RETURN 0; else if(c) mode=2; c=GetControls()|GetArrows(); if((c&(CONTROL_B1|CONTROL_B2)) && (!(oldc&(CONTROL_B1|CONTROL_B2)))) mode=2; oldc=c; clock++; switch(mode) { case 0: // fading in for(j=0;j<16;j++) for(i=0;i<256;i++) { if(curpal[i].r<desiredpal[i].r) curpal[i].r++; if(curpal[i].g<desiredpal[i].g) curpal[i].g++; if(curpal[i].b<desiredpal[i].b) curpal[i].b++; } mgl->SetPalette(curpal); mgl->RealizePalette(); if(clock>16) { mode=1; clock=0; } break; case 1: // sit around break; case 2: // fading out clock=0; for(j=0;j<16;j++) for(i=0;i<256;i++) { if(curpal[i].r>0) curpal[i].r--; else clock++; if(curpal[i].g>0) curpal[i].g--; else clock++; if(curpal[i].b>0) curpal[i].b--; else clock++; } mgl->SetPalette(curpal); mgl->RealizePalette(); if(clock==256*3*16) done=1; break; } } mgl->ClearScreen(); AWAIT mgl->Flip(); CO_RETURN 1; } TASK(void) HelpScreens(MGLDraw *mgl) { int i; char name[32]; for(i=0;i<5;i++) { sprintf(name,"docs/help%d.bmp",i+1); if(!AWAIT SpeedSplash(mgl,name)) CO_RETURN; } } TASK(void) DemoSplashScreens(MGLDraw *mgl) { if(!AWAIT SpeedSplash(mgl,"graphics/advert.bmp")) CO_RETURN; } TASK(void) SplashScreen(MGLDraw *mgl,const char *fname,int delay,byte sound) { int i,j,clock; RGB desiredpal[256],curpal[256]; byte mode,done; dword tick; for(i=0;i<256;i++) { curpal[i].r=0; curpal[i].g=0; curpal[i].b=0; } mgl->SetPalette(curpal); mgl->RealizePalette(); mgl->LastKeyPressed(); if (!mgl->LoadBMP(fname, desiredpal)) CO_RETURN; StartClock(); mode=0; clock=0; done=0; tick=0; while(!done) { AWAIT mgl->Flip(); if(!mgl->Process()) CO_RETURN; if(mgl->LastKeyPressed()) mode=2; EndClock(); tick+=TimeLength(); StartClock(); if(tick>1000/30) { clock++; tick-=1000/30; switch(mode) { case 0: // fading in for(j=0;j<8;j++) for(i=0;i<256;i++) { if(curpal[i].r<desiredpal[i].r) curpal[i].r++; if(curpal[i].g<desiredpal[i].g) curpal[i].g++; if(curpal[i].b<desiredpal[i].b) curpal[i].b++; } mgl->SetPalette(curpal); mgl->RealizePalette(); if(clock==32) { //if(sound==2) //MakeNormalSound(SND_HAMUMU); } if(clock>64) { mode=1; clock=0; } break; case 1: if(clock>delay) { mode=2; clock=0; } break; case 2: // fading out clock=0; for(j=0;j<8;j++) for(i=0;i<256;i++) { if(curpal[i].r>0) curpal[i].r--; else clock++; if(curpal[i].g>0) curpal[i].g--; else clock++; if(curpal[i].b>0) curpal[i].b--; else clock++; } mgl->SetPalette(curpal); mgl->RealizePalette(); if(clock==256*3*8) done=1; break; } } } mgl->ClearScreen(); AWAIT mgl->Flip(); }
16.997159
104
0.596858
[ "3d" ]
1d6a7d191ea1d023826c5cb573fb8d071c3110c9
17,414
cpp
C++
admin/netui/llsmgr/ausrdlg.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/netui/llsmgr/ausrdlg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/netui/llsmgr/ausrdlg.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/*++ Copyright (c) 1994-95 Microsoft Corporation Module Name: ausrdlg.cpp Abstract: Add user dialog implementation. Author: Don Ryan (donryan) 14-Feb-1995 Environment: User Mode - Win32 Revision History: Jeff Parham (jeffparh) 30-Jan-1996 o Added new element to LV_COLUMN_ENTRY to differentiate the string used for the column header from the string used in the menus (so that the menu option can contain hot keys). --*/ #include "stdafx.h" #include "llsmgr.h" #include "ausrdlg.h" static LV_COLUMN_INFO g_userColumnInfo = {0, 0, 1, {0, 0, 0, -1}}; static LV_COLUMN_INFO g_addedColumnInfo = {0, 0, 1, {0, 0, 0, -1}}; #ifdef _DEBUG #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif BEGIN_MESSAGE_MAP(CAddUsersDialog, CDialog) //{{AFX_MSG_MAP(CAddUsersDialog) ON_BN_CLICKED(IDC_ADD_USERS_ADD, OnAdd) ON_BN_CLICKED(IDC_ADD_USERS_DELETE, OnDelete) ON_NOTIFY(NM_DBLCLK, IDC_ADD_USERS_ADD_USERS, OnDblclkAddUsers) ON_NOTIFY(NM_DBLCLK, IDC_ADD_USERS_USERS, OnDblclkUsers) ON_CBN_SELCHANGE(IDC_ADD_USERS_DOMAINS, OnSelchangeDomains) ON_NOTIFY(LVN_GETDISPINFO, IDC_ADD_USERS_USERS, OnGetdispinfoUsers) ON_NOTIFY(NM_KILLFOCUS, IDC_ADD_USERS_USERS, OnKillfocusUsers) ON_NOTIFY(NM_SETFOCUS, IDC_ADD_USERS_USERS, OnSetfocusUsers) ON_NOTIFY(NM_KILLFOCUS, IDC_ADD_USERS_ADD_USERS, OnKillfocusAddUsers) ON_NOTIFY(NM_SETFOCUS, IDC_ADD_USERS_ADD_USERS, OnSetfocusAddUsers) //}}AFX_MSG_MAP END_MESSAGE_MAP() CAddUsersDialog::CAddUsersDialog(CWnd* pParent /*=NULL*/) : CDialog(CAddUsersDialog::IDD, pParent) /*++ Routine Description: Constructor for add user dialog. Arguments: pParent - parent window handle. Return Values: None. --*/ { //{{AFX_DATA_INIT(CAddUsersDialog) m_iDomain = -1; m_iIndex = 0; //}}AFX_DATA_INIT m_pObList = NULL; m_bIsFocusUserList = FALSE; m_bIsFocusAddedList = FALSE; } void CAddUsersDialog::DoDataExchange(CDataExchange* pDX) /*++ Routine Description: Called by framework to exchange dialog data. Arguments: pDX - data exchange object. Return Values: None. --*/ { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CAddUsersDialog) DDX_Control(pDX, IDC_ADD_USERS_ADD, m_addBtn); DDX_Control(pDX, IDC_ADD_USERS_DELETE, m_delBtn); DDX_Control(pDX, IDC_ADD_USERS_DOMAINS, m_domainList); DDX_Control(pDX, IDC_ADD_USERS_ADD_USERS, m_addedList); DDX_Control(pDX, IDC_ADD_USERS_USERS, m_userList); DDX_CBIndex(pDX, IDC_ADD_USERS_DOMAINS, m_iDomain); //}}AFX_DATA_MAP } void CAddUsersDialog::InitDialog(CObList* pObList) /*++ Routine Description: Initializes return list. Arguments: pObList - pointer to return list. Return Values: None. --*/ { ASSERT_VALID(pObList); m_pObList = pObList; } void CAddUsersDialog::InitDomainList() /*++ Routine Description: Initializes list of domains. Arguments: None. Return Values: VT_BOOL. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; CDomains* pDomains = NULL; CDomain* pDomain = NULL; int iDomain = 0; //First add the default domain CString strLabel = ""; strLabel.LoadString(IDS_DEFAULT_DOMAIN); if ((iDomain = m_domainList.AddString(strLabel)) != CB_ERR) { m_domainList.SetCurSel(iDomain); m_domainList.SetItemDataPtr(iDomain, (LPVOID)-1L); } else { theApp.DisplayStatus( STATUS_NO_MEMORY ); return; } //If FocusDomain, add the trusted domains if (LlsGetApp()->IsFocusDomain()) { pDomain = (CDomain*)MKOBJ(LlsGetApp()->GetActiveDomain()); ASSERT(pDomain && pDomain->IsKindOf(RUNTIME_CLASS(CDomain))); if (pDomain) { VARIANT va; VariantInit(&va); pDomains = (CDomains*)MKOBJ(pDomain->GetTrustedDomains(va)); if (pDomains && InsertDomains(pDomains)) { // Now add active domain itself... if ((iDomain = m_domainList.AddString(pDomain->m_strName)) != CB_ERR) m_domainList.SetItemDataPtr(iDomain, pDomain); else NtStatus = STATUS_NO_MEMORY; } else NtStatus = LlsGetLastStatus(); if (pDomains) pDomains->InternalRelease(); pDomain->InternalRelease(); } else NtStatus = LlsGetLastStatus(); } //If not FocusDomain, add all domains else { pDomain = (CDomain*)MKOBJ(LlsGetApp()->GetLocalDomain()); ASSERT(pDomain && pDomain->IsKindOf(RUNTIME_CLASS(CDomain))); if (pDomain) { VARIANT va; VariantInit(&va); pDomains = (CDomains*)MKOBJ(LlsGetApp()->GetDomains(va)); if (pDomains && InsertDomains(pDomains)) { // // CODEWORK... scroll to local domain??? // } else NtStatus = LlsGetLastStatus(); if (pDomains) pDomains->InternalRelease(); pDomain->InternalRelease(); } else NtStatus = LlsGetLastStatus(); } if (!NT_SUCCESS(NtStatus)) { theApp.DisplayStatus(NtStatus); m_domainList.ResetContent(); } } void CAddUsersDialog::InitUserList() /*++ Routine Description: Initializes list of users. Arguments: None. Return Values: None. --*/ { ::LvInitColumns(&m_userList, &g_userColumnInfo); ::LvInitColumns(&m_addedList, &g_addedColumnInfo); } BOOL CAddUsersDialog::InsertDomains(CDomains* pDomains) /*++ Routine Description: Inserts domains into domain list. Arguments: pDomains - domain collection. Return Values: None. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; ASSERT_VALID(pDomains); if (pDomains) { VARIANT va; VariantInit(&va); CDomain* pDomain; int iDomain; int nDomains = pDomains->GetCount(); for (va.vt = VT_I4, va.lVal = 0; (va.lVal < nDomains) && NT_SUCCESS(NtStatus); va.lVal++) { pDomain = (CDomain*)MKOBJ(pDomains->GetItem(va)); ASSERT(pDomain && pDomain->IsKindOf(RUNTIME_CLASS(CDomain))); if (pDomain) { if ((iDomain = m_domainList.AddString(pDomain->m_strName)) != CB_ERR) { m_domainList.SetItemDataPtr(iDomain, pDomain); } else { NtStatus = STATUS_NO_MEMORY; } pDomain->InternalRelease(); } else { NtStatus = STATUS_NO_MEMORY; } } } else { NtStatus = STATUS_INVALID_PARAMETER; } if (!NT_SUCCESS(NtStatus)) { m_domainList.ResetContent(); LlsSetLastStatus(NtStatus); return FALSE; } return TRUE; } void CAddUsersDialog::OnAdd() /*++ Routine Description: Message handler for IDC_ADD_USER_ADD. Arguments: None. Return Values: None. --*/ { CUser* pUser; int iItem = -1; while (NULL != (pUser = (CUser*)::LvGetNextObj(&m_userList, &iItem))) { ASSERT(pUser->IsKindOf(RUNTIME_CLASS(CUser))); LV_FINDINFO lvFindInfo; lvFindInfo.flags = LVFI_STRING; lvFindInfo.psz = MKSTR(pUser->m_strName); if (m_addedList.FindItem(&lvFindInfo, -1) == -1) { // // Make a copy of the user (w/no parent) // CUser* pNewUser = new CUser(NULL, pUser->m_strName); if (pNewUser) { LV_ITEM lvItem; lvItem.mask = LVIF_TEXT| LVIF_PARAM| LVIF_IMAGE; lvItem.iSubItem = 0; lvItem.lParam = (LPARAM)(LPVOID)pNewUser; lvItem.iImage = BMPI_USER; lvItem.pszText = MKSTR(pNewUser->m_strName); lvItem.iItem = m_iIndex; m_addedList.InsertItem(&lvItem); m_iIndex++; } else { theApp.DisplayStatus( STATUS_NO_MEMORY ); break; } } } m_userList.SetFocus(); } void CAddUsersDialog::OnDblclkAddUsers(NMHDR* pNMHDR, LRESULT* pResult) /*++ Routine Description: Notification handler for NM_DLBCLK. Arguments: pNMHDR - notification header. pResult - return code. Return Values: None. --*/ { UNREFERENCED_PARAMETER(pNMHDR); OnDelete(); ASSERT(NULL != pResult); *pResult = 0; } void CAddUsersDialog::OnDblclkUsers(NMHDR* pNMHDR, LRESULT* pResult) /*++ Routine Description: Notification handler for NM_DLBCLK. Arguments: pNMHDR - notification header. pResult - return code. Return Values: None. --*/ { UNREFERENCED_PARAMETER(pNMHDR); OnAdd(); ASSERT(NULL != pResult); *pResult = 0; } void CAddUsersDialog::OnDelete() /*++ Routine Description: Message handler for IDC_ADD_USER_DELETE. Arguments: None. Return Values: None. --*/ { CUser* pUser; int iItem = -1; int iLastItem = 0; while (NULL != (pUser = (CUser*)::LvGetNextObj(&m_addedList, &iItem))) { ASSERT(pUser->IsKindOf(RUNTIME_CLASS(CUser))); pUser->InternalRelease(); // allocated above.... m_addedList.DeleteItem(iItem); iLastItem = iItem; iItem = -1; m_iIndex--; } m_addedList.SetItemState(iLastItem, LVIS_SELECTED|LVIS_FOCUSED, LVIS_SELECTED|LVIS_FOCUSED); m_addedList.SetFocus(); } BOOL CAddUsersDialog::OnInitDialog() /*++ Routine Description: Message handler for WM_INITDIALOG. Arguments: None. Return Values: None. --*/ { BeginWaitCursor(); CDialog::OnInitDialog(); InitUserList(); // always construct headers... InitDomainList(); m_addBtn.EnableWindow(FALSE); m_delBtn.EnableWindow(FALSE); if (!RefreshUserList()) theApp.DisplayLastStatus(); m_domainList.SetFocus(); EndWaitCursor(); return FALSE; // set focus to domain list } void CAddUsersDialog::OnSelchangeDomains() /*++ Routine Description: Message handler for CBN_SELCHANGED. Arguments: None. Return Values: None. --*/ { RefreshUserList(); } BOOL CAddUsersDialog::RefreshUserList() /*++ Routine Description: Refreshs list of users (with currently selected item). Arguments: None. Return Values: VT_BOOL. --*/ { NTSTATUS NtStatus = STATUS_SUCCESS; m_userList.DeleteAllItems(); int iDomain; if ((iDomain = m_domainList.GetCurSel()) != CB_ERR) { CDomain* pDomain = (CDomain*)m_domainList.GetItemDataPtr(iDomain); CUsers* pUsers = (CUsers*)NULL; VARIANT va; VariantInit(&va); if (pDomain == (CDomain*)-1L) { // // Enumerate users in license cache... // CController* pController = (CController*)MKOBJ(LlsGetApp()->GetActiveController()); if ( pController ) { pController->InternalRelease(); // held open by CApplication pUsers = pController->m_pUsers; pUsers->InternalAddRef(); // released below... } } else { // // Enumerate users in particular domain... // ASSERT(pDomain->IsKindOf(RUNTIME_CLASS(CDomain))); pUsers = (CUsers*)MKOBJ(pDomain->GetUsers(va)); ASSERT(pUsers && pUsers->IsKindOf(RUNTIME_CLASS(CUsers))); } if (pUsers) { CUser* pUser; int nUsers = pUsers->GetCount(); LV_ITEM lvItem; lvItem.mask = LVIF_TEXT| LVIF_PARAM| LVIF_IMAGE; lvItem.iSubItem = 0; lvItem.pszText = LPSTR_TEXTCALLBACK; lvItem.cchTextMax = LPSTR_TEXTCALLBACK_MAX; lvItem.iImage = BMPI_USER; for (va.vt = VT_I4, va.lVal = 0; (va.lVal < nUsers) && NT_SUCCESS(NtStatus); va.lVal++) { pUser = (CUser*)MKOBJ(pUsers->GetItem(va)); ASSERT(pUser && pUser->IsKindOf(RUNTIME_CLASS(CUser))); if (pUser) { lvItem.iItem = va.lVal; lvItem.lParam = (LPARAM)(LPVOID)pUser; if (m_userList.InsertItem(&lvItem) == -1) { NtStatus = STATUS_NO_MEMORY; } pUser->InternalRelease(); } else { NtStatus = STATUS_NO_MEMORY; } } pUsers->InternalRelease(); } else { NtStatus = LlsGetLastStatus(); } VariantClear(&va); } else { NtStatus = STATUS_NO_MEMORY; } if (!NT_SUCCESS(NtStatus)) { m_userList.DeleteAllItems(); LlsSetLastStatus(NtStatus); } ::LvResizeColumns(&m_userList, &g_userColumnInfo); return NT_SUCCESS(NtStatus); } void CAddUsersDialog::OnOK() /*++ Routine Description: Message handler for IDOK. Arguments: None. Return Values: None. --*/ { if (m_pObList) { CUser* pUser; int iItem = -1; m_pObList->RemoveAll(); while (NULL != (pUser = (CUser*)::LvGetNextObj(&m_addedList, &iItem, LVNI_ALL))) { ASSERT(pUser->IsKindOf(RUNTIME_CLASS(CUser))); m_pObList->AddTail(pUser); } } CDialog::OnOK(); } void CAddUsersDialog::OnCancel() /*++ Routine Description: Message handler for IDCANCEL. Arguments: None. Return Values: None. --*/ { CUser* pUser; int iItem = -1; while (NULL != (pUser = (CUser*)::LvGetNextObj(&m_addedList, &iItem, LVNI_ALL))) { ASSERT(pUser->IsKindOf(RUNTIME_CLASS(CUser))); pUser->InternalRelease(); } CDialog::OnCancel(); } void CAddUsersDialog::InitDialogCtrls() { int iItem = -1; if (m_bIsFocusUserList && m_userList.GetItemCount()) { m_addBtn.EnableWindow(TRUE); m_delBtn.EnableWindow(FALSE); } else if (m_bIsFocusAddedList && m_addedList.GetItemCount()) { m_addBtn.EnableWindow(FALSE); m_delBtn.EnableWindow(TRUE); } else { m_addBtn.EnableWindow(FALSE); m_delBtn.EnableWindow(FALSE); } ::LvResizeColumns(&m_userList, &g_userColumnInfo); ::LvResizeColumns(&m_addedList, &g_addedColumnInfo); } void CAddUsersDialog::OnGetdispinfoUsers(NMHDR* pNMHDR, LRESULT* pResult) { ASSERT(NULL != pNMHDR); LV_ITEM lvItem = ((LV_DISPINFO*)pNMHDR)->item; if (lvItem.iSubItem == 0) { CUser* pUser = (CUser*)lvItem.lParam; ASSERT(pUser && pUser->IsKindOf(RUNTIME_CLASS(CUser))); lstrcpyn(lvItem.pszText, pUser->m_strName, lvItem.cchTextMax); } ASSERT(NULL != pResult); *pResult = 0; } void CAddUsersDialog::OnKillfocusUsers(NMHDR* pNMHDR, LRESULT* pResult) { UNREFERENCED_PARAMETER(pNMHDR); ASSERT(NULL != pResult); *pResult = 0; } void CAddUsersDialog::OnSetfocusUsers(NMHDR* pNMHDR, LRESULT* pResult) { UNREFERENCED_PARAMETER(pNMHDR); m_bIsFocusUserList = TRUE; m_bIsFocusAddedList = FALSE; PostMessage(WM_COMMAND, ID_INIT_CTRLS); ASSERT(NULL != pResult); *pResult = 0; } void CAddUsersDialog::OnKillfocusAddUsers(NMHDR* pNMHDR, LRESULT* pResult) { UNREFERENCED_PARAMETER(pNMHDR); ASSERT(NULL != pResult); *pResult = 0; } void CAddUsersDialog::OnSetfocusAddUsers(NMHDR* pNMHDR, LRESULT* pResult) { UNREFERENCED_PARAMETER(pNMHDR); m_bIsFocusUserList = FALSE; m_bIsFocusAddedList = TRUE; PostMessage(WM_COMMAND, ID_INIT_CTRLS); ASSERT(NULL != pResult); *pResult = 0; } BOOL CAddUsersDialog::OnCommand(WPARAM wParam, LPARAM lParam) { if (wParam == ID_INIT_CTRLS) { InitDialogCtrls(); return TRUE; // processed... } return CDialog::OnCommand(wParam, lParam); }
20.062212
100
0.556851
[ "object" ]
1d6bab1461ac47f9bd63abbe2fd02aa55c4657ca
9,383
cpp
C++
src/planner/match/Expand.cpp
yew1eb/nebula-graph
2c6eb04578946abfe2fb230d86c284db9ab738e3
[ "Apache-2.0" ]
null
null
null
src/planner/match/Expand.cpp
yew1eb/nebula-graph
2c6eb04578946abfe2fb230d86c284db9ab738e3
[ "Apache-2.0" ]
null
null
null
src/planner/match/Expand.cpp
yew1eb/nebula-graph
2c6eb04578946abfe2fb230d86c284db9ab738e3
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "planner/match/Expand.h" #include "planner/Logic.h" #include "planner/Query.h" #include "planner/match/MatchSolver.h" #include "planner/match/SegmentsConnector.h" #include "util/AnonColGenerator.h" #include "util/ExpressionUtils.h" #include "visitor/RewriteMatchLabelVisitor.h" using nebula::storage::cpp2::EdgeProp; using nebula::storage::cpp2::VertexProp; using PNKind = nebula::graph::PlanNode::Kind; namespace nebula { namespace graph { static std::unique_ptr<std::vector<VertexProp>> genVertexProps() { return std::make_unique<std::vector<VertexProp>>(); } std::unique_ptr<std::vector<storage::cpp2::EdgeProp>> Expand::genEdgeProps(const EdgeInfo &edge) { auto edgeProps = std::make_unique<std::vector<EdgeProp>>(); for (auto edgeType : edge.edgeTypes) { auto edgeSchema = matchCtx_->qctx->schemaMng()->getEdgeSchema( matchCtx_->space.id, edgeType); switch (edge.direction) { case Direction::OUT_EDGE: { if (reversely_) { edgeType = -edgeType; } break; } case Direction::IN_EDGE: { if (!reversely_) { edgeType = -edgeType; } break; } case Direction::BOTH: { EdgeProp edgeProp; edgeProp.set_type(-edgeType); std::vector<std::string> props{kSrc, kType, kRank, kDst}; for (std::size_t i = 0; i < edgeSchema->getNumFields(); ++i) { props.emplace_back(edgeSchema->getFieldName(i)); } edgeProp.set_props(std::move(props)); edgeProps->emplace_back(std::move(edgeProp)); break; } } EdgeProp edgeProp; edgeProp.set_type(edgeType); std::vector<std::string> props{kSrc, kType, kRank, kDst}; for (std::size_t i = 0; i < edgeSchema->getNumFields(); ++i) { props.emplace_back(edgeSchema->getFieldName(i)); } edgeProp.set_props(std::move(props)); edgeProps->emplace_back(std::move(edgeProp)); } return edgeProps; } static Expression* mergePathColumnsExpr(const std::string& lcol, const std::string& rcol) { auto expr = std::make_unique<PathBuildExpression>(); expr->add(ExpressionUtils::inputPropExpr(lcol)); expr->add(ExpressionUtils::inputPropExpr(rcol)); return expr.release(); } static Expression* buildPathExpr() { auto expr = std::make_unique<PathBuildExpression>(); expr->add(std::make_unique<VertexExpression>()); expr->add(std::make_unique<EdgeExpression>()); return expr.release(); } Status Expand::doExpand(const NodeInfo& node, const EdgeInfo& edge, SubPlan* plan) { NG_RETURN_IF_ERROR(expandSteps(node, edge, plan)); NG_RETURN_IF_ERROR(filterDatasetByPathLength(edge, plan->root, plan)); return Status::OK(); } Status Expand::expandSteps(const NodeInfo& node, const EdgeInfo& edge, SubPlan* plan) { SubPlan subplan; NG_RETURN_IF_ERROR(expandStep(edge, dependency_, inputVar_, node.filter, true, &subplan)); // plan->tail = subplan.tail; PlanNode* passThrough = subplan.root; auto maxHop = edge.range ? edge.range->max() : 1; for (int64_t i = 1; i < maxHop; ++i) { SubPlan curr; NG_RETURN_IF_ERROR( expandStep(edge, passThrough, passThrough->outputVar(), nullptr, false, &curr)); auto rNode = subplan.root; DCHECK(rNode->kind() == PNKind::kUnion || rNode->kind() == PNKind::kPassThrough); NG_RETURN_IF_ERROR(collectData(passThrough, curr.root, rNode, &passThrough, &subplan)); } plan->root = subplan.root; return Status::OK(); } // build subplan: Project->Dedup->GetNeighbors->[Filter]->Project Status Expand::expandStep(const EdgeInfo& edge, PlanNode* dep, const std::string& inputVar, const Expression* nodeFilter, bool needPassThrough, SubPlan* plan) { auto qctx = matchCtx_->qctx; // Extract dst vid from input project node which output dataset format is: [v1,e1,...,vn,en] SubPlan curr; curr.root = dep; MatchSolver::extractAndDedupVidColumn(qctx, initialExpr_.release(), dep, inputVar, curr); auto gn = GetNeighbors::make(qctx, curr.root, matchCtx_->space.id); auto srcExpr = ExpressionUtils::inputPropExpr(kVid); gn->setSrc(qctx->objPool()->add(srcExpr.release())); gn->setVertexProps(genVertexProps()); gn->setEdgeProps(genEdgeProps(edge)); gn->setEdgeDirection(edge.direction); PlanNode* root = gn; if (nodeFilter != nullptr) { auto filter = qctx->objPool()->add(nodeFilter->clone().release()); RewriteMatchLabelVisitor visitor( [](const Expression* expr) -> Expression *{ DCHECK(expr->kind() == Expression::Kind::kLabelAttribute || expr->kind() == Expression::Kind::kLabel); // filter prop if (expr->kind() == Expression::Kind::kLabelAttribute) { auto la = static_cast<const LabelAttributeExpression*>(expr); return new AttributeExpression( new VertexExpression(), la->right()->clone().release()); } // filter tag return new VertexExpression(); }); filter->accept(&visitor); auto filterNode = Filter::make(matchCtx_->qctx, root, filter); filterNode->setColNames(root->colNames()); root = filterNode; } if (edge.filter != nullptr) { RewriteMatchLabelVisitor visitor([](const Expression*expr) { DCHECK_EQ(expr->kind(), Expression::Kind::kLabelAttribute); auto la = static_cast<const LabelAttributeExpression*>(expr); return new AttributeExpression(new EdgeExpression(), la->right()->clone().release()); }); auto filter = saveObject(edge.filter->clone().release()); filter->accept(&visitor); auto filterNode = Filter::make(qctx, root, filter); filterNode->setColNames(root->colNames()); root = filterNode; } auto listColumns = saveObject(new YieldColumns); listColumns->addColumn(new YieldColumn(buildPathExpr(), new std::string(kPathStr))); root = Project::make(qctx, root, listColumns); root->setColNames({kPathStr}); if (needPassThrough) { auto pt = PassThroughNode::make(qctx, root); pt->setColNames(root->colNames()); pt->setOutputVar(root->outputVar()); root = pt; } plan->root = root; plan->tail = curr.tail; return Status::OK(); } Status Expand::collectData(const PlanNode* joinLeft, const PlanNode* joinRight, const PlanNode* inUnionNode, PlanNode** passThrough, SubPlan* plan) { auto qctx = matchCtx_->qctx; auto join = SegmentsConnector::innerJoinSegments(qctx, joinLeft, joinRight); auto lpath = folly::stringPrintf("%s_%d", kPathStr, 0); auto rpath = folly::stringPrintf("%s_%d", kPathStr, 1); join->setColNames({lpath, rpath}); plan->tail = join; auto columns = saveObject(new YieldColumns); auto listExpr = mergePathColumnsExpr(lpath, rpath); columns->addColumn(new YieldColumn(listExpr)); auto project = Project::make(qctx, join, columns); project->setColNames({kPathStr}); auto filter = MatchSolver::filtPathHasSameEdge(project, kPathStr, qctx); auto pt = PassThroughNode::make(qctx, filter); pt->setOutputVar(filter->outputVar()); pt->setColNames({kPathStr}); auto uNode = Union::make(qctx, pt, const_cast<PlanNode*>(inUnionNode)); uNode->setColNames({kPathStr}); *passThrough = pt; plan->root = uNode; return Status::OK(); } Status Expand::filterDatasetByPathLength(const EdgeInfo& edge, PlanNode* input, SubPlan* plan) { auto qctx = matchCtx_->qctx; // filter rows whose edges number less than min hop auto args = std::make_unique<ArgumentList>(); // expr: length(relationships(p)) >= minHop auto pathExpr = ExpressionUtils::inputPropExpr(kPathStr); args->addArgument(std::move(pathExpr)); auto fn = std::make_unique<std::string>("length"); auto edgeExpr = std::make_unique<FunctionCallExpression>(fn.release(), args.release()); auto minHop = edge.range == nullptr ? 1 : edge.range->min(); auto minHopExpr = std::make_unique<ConstantExpression>(minHop); auto expr = std::make_unique<RelationalExpression>( Expression::Kind::kRelGE, edgeExpr.release(), minHopExpr.release()); auto filter = Filter::make(qctx, input, saveObject(expr.release())); filter->setColNames(input->colNames()); plan->root = filter; // plan->tail = curr.tail; return Status::OK(); } } // namespace graph } // namespace nebula
38.613169
98
0.613983
[ "vector" ]
1d73409a7f01c2de6aae0a2c09d6e2e65476ab06
10,474
cpp
C++
admin/admt/dommigsi/prgrnode.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/admt/dommigsi/prgrnode.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/admt/dommigsi/prgrnode.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
// This node class ... #include "stdafx.h" #include "MyNodes.h" #include "DomSel.h" #include "..\Common\UString.hpp" #include "..\Common\Common.hpp" #import "\bin\NetEnum.tlb" no_namespace, named_guids // {162A41A3-405C-11d3-8AED-00A0C9AFE114} static const GUID CPruneGraftGUID_NODETYPE = { 0x162a41a3, 0x405c, 0x11d3, { 0x8a, 0xed, 0x0, 0xa0, 0xc9, 0xaf, 0xe1, 0x14 } }; const GUID* CPruneGraftNode::m_NODETYPE = &CPruneGraftGUID_NODETYPE; const OLECHAR* CPruneGraftNode::m_SZNODETYPE = OLESTR("C8C24622-3FA1-11d3-8AED-00A0C9AFE114"); const OLECHAR* CPruneGraftNode::m_SZDISPLAY_NAME = OLESTR("Domain Migrator"); const CLSID* CPruneGraftNode::m_SNAPIN_CLASSID = &CLSID_DomMigrator; // 0 1 2 3 4 WCHAR * gLDAPColumns[] = { L"", L"", L"", L"", L"" }; WCHAR * gColumnHeaders[] = { L"", L"",L"",L"" }; // these define the index in gLDAPColumns to use for each column int gDomainMapping[] = { 0,1,2,4 }; int gOuMapping[] = { 3,1,2,4 }; int gContainerMapping[] = { 0,1,2,4 }; int gGroupMapping[] = { 0, 1,2,4 }; int gUserMapping[] = { 0, 1,2,4 }; CPruneGraftNode::CPruneGraftNode() { // Initialize the array of children // TODO: load the domain hierarchy for the current forest m_bLoaded = FALSE; m_bstrDisplayName = SysAllocString(L"Prune & Graft"); m_scopeDataItem.nImage = IMAGE_INDEX_AD; // May need modification m_scopeDataItem.nOpenImage = IMAGE_INDEX_AD_OPEN; // May need modification m_resultDataItem.nImage = IMAGE_INDEX_AD; // May need modification m_Data.SetSize(MAX_COLUMNS); } void CPruneGraftNode::Init( WCHAR const * domain, WCHAR const * path, WCHAR const * objClass, WCHAR const * displayName ) { m_Domain = domain; m_LDAPPath = path; m_objectClass = objClass; m_bstrDisplayName = displayName; // set the icons if ( ! UStrICmp(objClass,L"user") ) { m_scopeDataItem.nImage = IMAGE_INDEX_USER; m_scopeDataItem.nOpenImage = IMAGE_INDEX_USER_OPEN; m_resultDataItem.nImage = IMAGE_INDEX_USER; } else if ( ! UStrICmp(objClass,L"group") ) { m_scopeDataItem.nImage = IMAGE_INDEX_GROUP; m_scopeDataItem.nOpenImage = IMAGE_INDEX_GROUP_OPEN; m_resultDataItem.nImage = IMAGE_INDEX_GROUP; } else if ( ! UStrICmp(objClass,L"organizationalUnit") ) { m_scopeDataItem.nImage = IMAGE_INDEX_OU; m_scopeDataItem.nOpenImage = IMAGE_INDEX_OU_OPEN; m_resultDataItem.nImage = IMAGE_INDEX_OU; } else if ( ! UStrICmp(objClass,L"domain") ) { m_scopeDataItem.nImage = IMAGE_INDEX_DOMAIN; m_scopeDataItem.nOpenImage = IMAGE_INDEX_DOMAIN_OPEN; m_resultDataItem.nImage = IMAGE_INDEX_DOMAIN; } else if ( ! UStrICmp(objClass,L"container") ) { m_scopeDataItem.nImage = IMAGE_INDEX_VIEW; m_scopeDataItem.nOpenImage = IMAGE_INDEX_VIEW_OPEN; m_resultDataItem.nImage = IMAGE_INDEX_VIEW; } } BOOL CPruneGraftNode::ShowInScopePane() { return ( UStrICmp(m_objectClass,L"user") ); } HRESULT CPruneGraftNode::OnAddDomain(bool &bHandled, CSnapInObjectRootBase * pObj) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = S_OK; CDomainSelDlg dlg; CComPtr<IConsole> pConsole; hr = GetConsoleFromCSnapInObjectRootBase(pObj, &pConsole ); if (FAILED(hr)) return hr; if ( IDOK == dlg.DoModal() ) { // insert the domain in the scope pane CPruneGraftNode * pNode = new CPruneGraftNode(); pNode->Init(dlg.m_Domain.AllocSysString(),L"",L"domain",dlg.m_Domain.AllocSysString()); hr = InsertNodeToScopepane2((IConsole*)pConsole, pNode, m_scopeDataItem.ID ); m_ChildArray.Add(pNode); } return hr; } HRESULT CPruneGraftNode::OnExpand( IConsole *spConsole ) { // TODO: if we haven't already, enumerate our contents if ( ! m_bLoaded ) { EnumerateChildren(spConsole); m_bLoaded = TRUE; } return CNetNode<CPruneGraftNode>::OnExpand(spConsole); } SAFEARRAY * CPruneGraftNode::GetAvailableColumns(WCHAR const * objectClass) { long nItems = 0; WCHAR ** columns = NULL; columns = gLDAPColumns; nItems = DIM(gLDAPColumns); // Build a safearray containing the data SAFEARRAYBOUND bound[1] = { { 0, 0 } }; long ndx[1]; bound[0].cElements = nItems; SAFEARRAY * pArray = SafeArrayCreate(VT_BSTR,1,bound); for ( long i = 0 ; i < nItems ; i++ ) { ndx[0] = i; SafeArrayPutElement(pArray,ndx,SysAllocString(columns[i])); } return pArray; } HRESULT CPruneGraftNode::EnumerateChildren(IConsole * spConsole) { HRESULT hr = S_OK; WCHAR path[MAX_PATH]; INetObjEnumeratorPtr pEnum; IEnumVARIANT * pValues = NULL; hr = pEnum.CreateInstance(CLSID_NetObjEnumerator); if ( SUCCEEDED(hr) ) { if ( m_LDAPPath.length() ) { swprintf(path,L"LDAP://%ls/%ls",(WCHAR*)m_Domain,(WCHAR*)m_LDAPPath); } else { safecopy(path,(WCHAR*)m_LDAPPath); } hr = pEnum->raw_SetQuery(path,m_Domain,L"(objectClass=*)",1,FALSE); } if ( SUCCEEDED(hr) ) { hr = pEnum->raw_SetColumns(GetAvailableColumns(m_objectClass)); } if ( SUCCEEDED(hr) ) { hr = pEnum->raw_Execute(&pValues); } if ( SUCCEEDED(hr) ) { hr = LoadChildren(pValues); pValues->Release(); } return hr; } HRESULT CPruneGraftNode::LoadChildren(IEnumVARIANT * pEnumerator) { HRESULT hr = 0; VARIANT var; long count = 0; ULONG nReturned = 0; CPruneGraftNode * pNode = NULL; VariantInit(&var); while ( hr != S_FALSE ) { hr = pEnumerator->Next(1,&var,&nReturned); // break if there was an error, or Next returned S_FALSE if ( hr != S_OK ) break; // see if this is an array ( it should be!) if ( var.vt == ( VT_ARRAY | VT_VARIANT ) ) { VARIANT * pData; SAFEARRAY * pArray; pArray = var.parray; pNode = new CPruneGraftNode; SafeArrayGetUBound(pArray,1,&count); SafeArrayAccessData(pArray,(void**)&pData); // make sure we at least have an LDAP path and an objectClass if ( count ) { // get the object class and distinguishedName pNode->Init(m_Domain,pData[1].bstrVal,pData[2].bstrVal,pData[0].bstrVal); m_ChildArray.Add(pNode); for ( long i = 0 ; i <= count ; i++ ) { // convert each value to a string, and store it in the node if ( SUCCEEDED(VariantChangeType(&pData[i],&pData[i],0,VT_BSTR)) ) { pNode->AddColumnValue(i,pData[i].bstrVal); } } } else { delete pNode; } } } return hr; } HRESULT CPruneGraftNode::OnShow( bool bShow, IHeaderCtrl *spHeader, IResultData *spResultData) { HRESULT hr=S_OK; if (bShow) { // show for ( int i = 0 ; i < DIM(gColumnHeaders) ; i++ ) { spHeader->InsertColumn(i, gColumnHeaders[i], LVCFMT_LEFT, m_iColumnWidth[i]); } { CString cstr; CComBSTR text; cstr.Format(_T("%d subitem(s)"), m_ChildArray.GetSize() ); text = (LPCTSTR)cstr; spResultData->SetDescBarText( BSTR(text) ); } } else { // hide // save the column widths for ( int i = 0 ; i < DIM(gColumnHeaders) ; i++ ) { spHeader->GetColumnWidth(i, m_iColumnWidth + i); } } hr = S_OK; return hr; } LPOLESTR CPruneGraftNode::GetResultPaneColInfo(int nCol) { CString value; int ndx = nCol; int * mapping = NULL; if ( m_objectClass.length() && UStrICmp(m_objectClass,L"domain") ) { if ( ! UStrICmp(m_objectClass,L"user") ) { mapping = gUserMapping; } else if ( ! UStrICmp(m_objectClass,L"group") ) { mapping = gGroupMapping; } else if ( ! UStrICmp(m_objectClass,L"organizationalUnit") ) { mapping = gOuMapping; } else if ( ! UStrICmp(m_objectClass,L"domain") ) { mapping = gDomainMapping; } else if ( ! UStrICmp(m_objectClass,L"container") ) { mapping = gContainerMapping; } else { mapping = gContainerMapping; } if ( mapping ) ndx = mapping[nCol]; if ( ndx <= m_Data.GetUpperBound() ) { value = m_Data.GetAt(ndx); return value.AllocSysString(); } else return OLESTR("Override GetResultPaneColInfo"); } else { return CNetNode<CPruneGraftNode>::GetResultPaneColInfo(nCol); } return NULL; } void CPruneGraftNode::AddColumnValue(int col,WCHAR const * value) { m_Data.SetAtGrow(col,value); // see if we need to update the display name // get the pointer for the columns int * mapping = NULL; if ( ! UStrICmp(m_objectClass,L"user") ) { mapping = gUserMapping; } else if ( ! UStrICmp(m_objectClass,L"group") ) { mapping = gGroupMapping; } else if ( ! UStrICmp(m_objectClass,L"organizationalUnit") ) { mapping = gOuMapping; } else if ( ! UStrICmp(m_objectClass,L"domain") ) { mapping = gDomainMapping; } else if ( ! UStrICmp(m_objectClass,L"container") ) { mapping = gContainerMapping; } else { mapping = gContainerMapping; } if ( mapping && col == mapping[0] ) // display name { m_bstrDisplayName = value; } }
28.080429
95
0.562727
[ "object" ]
1d736e84c927fcc734e22b5602c75f48430597d5
2,287
cpp
C++
aws-cpp-sdk-apigateway/source/model/CreateAuthorizerRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-apigateway/source/model/CreateAuthorizerRequest.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-apigateway/source/model/CreateAuthorizerRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/apigateway/model/CreateAuthorizerRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::APIGateway::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; CreateAuthorizerRequest::CreateAuthorizerRequest() : m_restApiIdHasBeenSet(false), m_nameHasBeenSet(false), m_type(AuthorizerType::NOT_SET), m_typeHasBeenSet(false), m_providerARNsHasBeenSet(false), m_authTypeHasBeenSet(false), m_authorizerUriHasBeenSet(false), m_authorizerCredentialsHasBeenSet(false), m_identitySourceHasBeenSet(false), m_identityValidationExpressionHasBeenSet(false), m_authorizerResultTtlInSeconds(0), m_authorizerResultTtlInSecondsHasBeenSet(false) { } Aws::String CreateAuthorizerRequest::SerializePayload() const { JsonValue payload; if(m_nameHasBeenSet) { payload.WithString("name", m_name); } if(m_typeHasBeenSet) { payload.WithString("type", AuthorizerTypeMapper::GetNameForAuthorizerType(m_type)); } if(m_providerARNsHasBeenSet) { Array<JsonValue> providerARNsJsonList(m_providerARNs.size()); for(unsigned providerARNsIndex = 0; providerARNsIndex < providerARNsJsonList.GetLength(); ++providerARNsIndex) { providerARNsJsonList[providerARNsIndex].AsString(m_providerARNs[providerARNsIndex]); } payload.WithArray("providerARNs", std::move(providerARNsJsonList)); } if(m_authTypeHasBeenSet) { payload.WithString("authType", m_authType); } if(m_authorizerUriHasBeenSet) { payload.WithString("authorizerUri", m_authorizerUri); } if(m_authorizerCredentialsHasBeenSet) { payload.WithString("authorizerCredentials", m_authorizerCredentials); } if(m_identitySourceHasBeenSet) { payload.WithString("identitySource", m_identitySource); } if(m_identityValidationExpressionHasBeenSet) { payload.WithString("identityValidationExpression", m_identityValidationExpression); } if(m_authorizerResultTtlInSecondsHasBeenSet) { payload.WithInteger("authorizerResultTtlInSeconds", m_authorizerResultTtlInSeconds); } return payload.View().WriteReadable(); }
23.10101
113
0.763883
[ "model" ]
1d807f36d82efc04a53b668e75da0544890eb3a0
7,667
cpp
C++
src/axom/primal/tests/primal_clip.cpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
src/axom/primal/tests/primal_clip.cpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
src/axom/primal/tests/primal_clip.cpp
Parqua/axom
c3a64b372d25e53976b3ba8676a25acc49a9a6cd
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2017-2020, Lawrence Livermore National Security, LLC and // other Axom Project Developers. See the top-level COPYRIGHT file for details. // // SPDX-License-Identifier: (BSD-3-Clause) #include "gtest/gtest.h" #include "axom/primal/geometry/Point.hpp" #include "axom/primal/geometry/BoundingBox.hpp" #include "axom/primal/geometry/Triangle.hpp" #include "axom/primal/operators/clip.hpp" #include <limits> namespace Primal3D { typedef axom::primal::Point< double, 3 > PointType; typedef axom::primal::Vector< double, 3 > VectorType; typedef axom::primal::BoundingBox< double, 3 > BoundingBoxType; typedef axom::primal::Triangle< double, 3 > TriangleType; typedef axom::primal::Polygon< double, 3 > PolygonType; } TEST( primal_clip, simple_clip) { using namespace Primal3D; BoundingBoxType bbox; bbox.addPoint( PointType::zero()); bbox.addPoint( PointType::ones()); PointType points[] = { PointType::make_point(2,2,2), PointType::make_point(2,2,4), PointType::make_point(2,4,2), PointType::make_point(-100,-100,0.5), PointType::make_point(-100,100,0.5), PointType::make_point(100,0,0.5), PointType::make_point(0.25,0.25,0.5), PointType::make_point(0.75,0.25,0.5), PointType::make_point(0.66,0.5,0.5), PointType::make_point(1.5,0.5,0.5), }; { TriangleType tri( points[0], points[1], points[2]); PolygonType poly = axom::primal::clip(tri, bbox); EXPECT_EQ(0, poly.numVertices()); } { TriangleType tri( points[3], points[4], points[5]); PolygonType poly = axom::primal::clip(tri, bbox); EXPECT_EQ(4, poly.numVertices()); SLIC_INFO("Intersection of triangle " << tri << " and bounding box " << bbox << " is polygon" << poly); } { TriangleType tri( points[3], points[4], points[5]); PolygonType poly = axom::primal::clip(tri, bbox); EXPECT_EQ(4, poly.numVertices()); EXPECT_EQ(PointType(.5), poly.centroid()); SLIC_INFO("Intersection of triangle " << tri << " and bounding box " << bbox << " is polygon" << poly); } { TriangleType tri( points[6], points[7], points[9]); PolygonType poly = axom::primal::clip(tri, bbox); EXPECT_EQ(4, poly.numVertices()); SLIC_INFO("Intersection of triangle " << tri << " and bounding box " << bbox << " is polygon" << poly); } } TEST( primal_clip, unit_simplex) { using namespace Primal3D; double delta = 1e-5; // Test the "unit simplex", and a jittered version PointType points[] = { PointType::make_point(1,0,0), PointType::make_point(0,1,0), PointType::make_point(0,0,1), PointType::make_point(1+delta,delta,delta), PointType::make_point(delta,1+delta,delta), PointType::make_point(delta,delta,1+delta) }; BoundingBoxType bbox; bbox.addPoint( PointType::zero()); bbox.addPoint( PointType(.75)); // intersection of this triangle and cube is a hexagon { TriangleType tri( points[0], points[1], points[2]); PolygonType poly = axom::primal::clip(tri, bbox); EXPECT_EQ(6, poly.numVertices()); SLIC_INFO("Intersection of triangle " << tri << " and bounding box " << bbox << " is polygon" << poly); } { TriangleType tri( points[3], points[4], points[5]); PolygonType poly = axom::primal::clip(tri, bbox); EXPECT_EQ(6, poly.numVertices()); SLIC_INFO("Intersection of triangle " << tri << " and bounding box " << bbox << " is polygon" << poly); } } TEST( primal_clip, boundingBoxOptimization ) { using namespace Primal3D; SLIC_INFO("Checking correctness of optimization for skipping clipping " << " of planes that the triangle's bounding box doesn't cover"); const double VAL1 = 3.; const double VAL2 = 2.; BoundingBoxType bbox; bbox.addPoint( PointType(-1.) ); bbox.addPoint( PointType(1.) ); PointType midpoint = PointType::zero(); PointType points[] = { PointType::make_point( VAL1, VAL2, 0), PointType::make_point(-VAL1, VAL2, 0), PointType::make_point( VAL1, -VAL2, 0), PointType::make_point(-VAL1, -VAL2, 0), PointType::make_point( VAL1, 0, VAL2), PointType::make_point(-VAL1, 0, VAL2), PointType::make_point( VAL1, 0, -VAL2), PointType::make_point(-VAL1, 0, -VAL2), PointType::make_point( 0, VAL2, VAL1), PointType::make_point( 0, VAL2, -VAL1), PointType::make_point( 0, -VAL2, VAL1), PointType::make_point( 0, -VAL2, -VAL1), PointType::make_point( 0, VAL1, VAL2), PointType::make_point( 0, -VAL1, VAL2), PointType::make_point( 0, VAL1, -VAL2), PointType::make_point( 0, -VAL1, -VAL2), }; for (int i=0 ; i<16 ; i+=2) { TriangleType tri(midpoint, points[i], points[i+1]); PolygonType poly = axom::primal::clip(tri, bbox); SLIC_INFO(poly); EXPECT_EQ(5, poly.numVertices()); } } TEST( primal_clip, experimentalData) { using namespace Primal3D; const double EPS = 1e-8; // Triangle 248 from sphere mesh TriangleType tri( PointType::make_point(0.405431,3.91921,3.07821), PointType::make_point(1.06511,3.96325,2.85626), PointType::make_point(0.656002,4.32465,2.42221)); // Block index {grid pt: (19,29,24); level: 5} from InOutOctree BoundingBoxType box12( PointType::make_point(0.937594,4.06291,2.50025), PointType::make_point(1.25012,4.37544,2.81278)); PolygonType poly = axom::primal::clip(tri, box12); EXPECT_EQ(3, poly.numVertices()); SLIC_INFO("Intersection of triangle " << tri << " \n\t and bounding box " << box12 << " \n\t is polygon" << poly << " with centroid " << poly.centroid() ); // Check that the polygon vertices are on the triangle for (int i=0 ; i< poly.numVertices() ; ++i) { PointType bary = tri.physToBarycentric(poly[i]); PointType reconstructed = tri.baryToPhysical(bary); SLIC_INFO("Testing clipped polygon point " << poly[i] << "-- w/ barycentric coords " << bary << "\n\t-- reconstructed point is: " << reconstructed << "...\n"); double barySum = bary[0]+bary[1]+bary[2]; EXPECT_NEAR(1., barySum, EPS); for (int dim=0 ; dim < 3 ; ++dim) { EXPECT_GE(bary[dim], -EPS); EXPECT_NEAR(poly[i][dim], reconstructed[dim], EPS); } EXPECT_TRUE(box12.contains(poly[i])); } // Check that the polygon centroid is on the triangle { PointType centroid = poly.centroid(); PointType bary = tri.physToBarycentric( centroid ); PointType reconstructed = tri.baryToPhysical(bary); SLIC_INFO("Testing clipped polygon centroid " << centroid << "-- w/ barycentric coords " << bary << "\n\t-- reconstructed point is: " << reconstructed << "...\n"); double barySum = bary[0]+bary[1]+bary[2]; EXPECT_NEAR(1., barySum, EPS); for (int dim=0 ; dim < 3 ; ++dim) { EXPECT_GE(bary[dim], -EPS); EXPECT_NEAR(centroid[dim], reconstructed[dim], EPS); } EXPECT_TRUE(box12.contains(centroid)); } } //------------------------------------------------------------------------------ #include "axom/slic/core/UnitTestLogger.hpp" using axom::slic::UnitTestLogger; int main(int argc, char* argv[]) { ::testing::InitGoogleTest(&argc, argv); UnitTestLogger logger; // create & initialize test logger, int result = RUN_ALL_TESTS(); return result; }
27.778986
80
0.610278
[ "mesh", "geometry", "vector" ]
1d83f29561dfa2f28eaed6b89f8cf568d127c1d6
11,712
cpp
C++
src/gausskernel/storage/mot/core/src/memory/mm_huge_object_allocator.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
1
2021-11-05T10:14:39.000Z
2021-11-05T10:14:39.000Z
src/gausskernel/storage/mot/core/src/memory/mm_huge_object_allocator.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
src/gausskernel/storage/mot/core/src/memory/mm_huge_object_allocator.cpp
wotchin/openGauss-server
ebd92e92b0cfd76b121d98e4c57a22d334573159
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (c) 2020 Huawei Technologies Co.,Ltd. * * openGauss is licensed under Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. * ------------------------------------------------------------------------- * * mm_huge_object_allocator.cpp * Memory huge object allocation infrastructure. * * IDENTIFICATION * src/gausskernel/storage/mot/core/src/memory/mm_huge_object_allocator.cpp * * ------------------------------------------------------------------------- */ #include <string.h> #include "global.h" #include "mm_huge_object_allocator.h" #include "mm_numa.h" #include "mm_raw_chunk_dir.h" #include "mm_cfg.h" #include "mot_atomic_ops.h" namespace MOT { DECLARE_LOGGER(HugeAlloc, Memory) // Memory Usage Counters static uint64_t memUsedBytes[MEM_MAX_NUMA_NODES]; static uint64_t memRequestedBytes[MEM_MAX_NUMA_NODES]; static uint64_t objectCount[MEM_MAX_NUMA_NODES]; static void MemSessionRecordHugeChunk( MemVirtualHugeChunkHeader* chunkHeader, MemVirtualHugeChunkHeader** chunkHeaderList); static void MemSessioUnrecordHugeChunk( MemVirtualHugeChunkHeader* chunkHeader, MemVirtualHugeChunkHeader** chunkHeaderList); extern void MemHugeInit() { errno_t erc = memset_s(memUsedBytes, sizeof(memUsedBytes), 0, sizeof(memUsedBytes)); securec_check(erc, "\0", "\0"); erc = memset_s(memRequestedBytes, sizeof(memRequestedBytes), 0, sizeof(memRequestedBytes)); securec_check(erc, "\0", "\0"); erc = memset_s(objectCount, sizeof(objectCount), 0, sizeof(objectCount)); securec_check(erc, "\0", "\0"); } extern void MemHugeDestroy() { MemHugePrint("Shutdown Report", LogLevel::LL_INFO); } extern void* MemHugeAlloc(uint64_t size, int node, MemAllocType allocType, MemVirtualHugeChunkHeader** chunkHeaderList, MemLock* lock /* = nullptr */) { // compute aligned size uint64_t alignedSize = MEM_ALIGN(size, MEM_CHUNK_SIZE_MB * MEGA_BYTE); uint64_t alignment = MEM_CHUNK_SIZE_MB * MEGA_BYTE; // make the huge allocation void* chunk = NULL; if (allocType == MEM_ALLOC_GLOBAL) { chunk = MemNumaAllocAlignedGlobal(alignedSize, alignment); } else { chunk = MemNumaAllocAlignedLocal(alignedSize, alignment, node); } if (chunk != NULL) { // now prepare a virtual header (we have a special maintenance chunk for that) MemVirtualHugeChunkHeader* chunkHeader = MemVirtualHugeChunkHeaderAlloc(size, alignedSize, (int16_t)node, allocType); if (chunkHeader != NULL) { chunkHeader->m_chunk = chunk; MemRawChunkDirInsertEx(chunk, alignedSize / (MEM_CHUNK_SIZE_MB * MEGA_BYTE), chunkHeader); MOT_ATOMIC_ADD(memUsedBytes[node], alignedSize); MOT_ATOMIC_ADD(memRequestedBytes[node], size); MOT_ATOMIC_INC(objectCount[node]); if (lock != nullptr) { MemLockAcquire(lock); } MemSessionRecordHugeChunk(chunkHeader, chunkHeaderList); if (lock != nullptr) { MemLockRelease(lock); } } else { // cleanup to avoid memory leak MOT_LOG_TRACE("Failed to allocate virtual huge chunk header."); if (allocType == MEM_ALLOC_GLOBAL) { MemNumaFreeGlobal(chunk, alignedSize); } else { MemNumaFreeLocal(chunk, alignedSize, node); } chunk = NULL; } } return chunk; } extern void MemHugeFree(MemVirtualHugeChunkHeader* chunkHeader, void* object, MemVirtualHugeChunkHeader** chunkHeaderList, MemLock* lock /* = nullptr */) { if (lock != nullptr) { MemLockAcquire(lock); } MemSessioUnrecordHugeChunk(chunkHeader, chunkHeaderList); if (lock != nullptr) { MemLockRelease(lock); } MOT_ATOMIC_SUB(memUsedBytes[chunkHeader->m_node], chunkHeader->m_chunkSizeBytes); MOT_ATOMIC_SUB(memRequestedBytes[chunkHeader->m_node], chunkHeader->m_objectSizeBytes); MOT_ATOMIC_DEC(objectCount[chunkHeader->m_node]); // clear the chunk directory MemRawChunkDirRemoveEx(object, chunkHeader->m_chunkSizeBytes / (MEM_CHUNK_SIZE_MB * MEGA_BYTE)); // free the object if (chunkHeader->m_allocType == MEM_ALLOC_GLOBAL) { MemNumaFreeGlobal(object, chunkHeader->m_chunkSizeBytes); } else { MemNumaFreeLocal(object, chunkHeader->m_chunkSizeBytes, chunkHeader->m_node); } // recycle the header MemVirtualHugeChunkHeaderFree(chunkHeader); } extern void* MemHugeRealloc(MemVirtualHugeChunkHeader* chunkHeader, void* object, uint64_t newSizeBytes, MemReallocFlags flags, MemVirtualHugeChunkHeader** chunkHeaderList, MemLock* lock /* = nullptr */) { errno_t erc; // locate the proper list to see if the size still fits void* newObject = NULL; if (chunkHeader->m_chunkSizeBytes >= newSizeBytes) { // new object fits newObject = object; // size fits, we are done MOT_ATOMIC_SUB(memRequestedBytes[chunkHeader->m_node], chunkHeader->m_objectSizeBytes); MOT_ATOMIC_ADD(memRequestedBytes[chunkHeader->m_node], newSizeBytes); chunkHeader->m_objectSizeBytes = newSizeBytes; } else { // allocate new object, copy/zero data if required and free old object newObject = MemHugeAlloc(newSizeBytes, chunkHeader->m_node, chunkHeader->m_allocType, chunkHeaderList, lock); if (newObject != NULL) { uint64_t objectSizeBytes = chunkHeader->m_objectSizeBytes; if (flags == MEM_REALLOC_COPY) { // attention: new object size may be smaller erc = memcpy_s(newObject, newSizeBytes, object, std::min(newSizeBytes, objectSizeBytes)); securec_check(erc, "\0", "\0"); } else if (flags == MEM_REALLOC_ZERO) { erc = memset_s(newObject, newSizeBytes, 0, newSizeBytes); securec_check(erc, "\0", "\0"); } else if (flags == MEM_REALLOC_COPY_ZERO) { // attention: new object size may be smaller erc = memcpy_s(newObject, newSizeBytes, object, std::min(newSizeBytes, objectSizeBytes)); securec_check(erc, "\0", "\0"); if (newSizeBytes > chunkHeader->m_objectSizeBytes) { erc = memset_s(((char*)newObject) + objectSizeBytes, newSizeBytes - objectSizeBytes, 0, newSizeBytes - objectSizeBytes); securec_check(erc, "\0", "\0"); } } MemHugeFree(chunkHeader, object, chunkHeaderList, lock); } } return newObject; } static void MemSessionRecordHugeChunk( MemVirtualHugeChunkHeader* chunkHeader, MemVirtualHugeChunkHeader** chunkHeaderList) { chunkHeader->m_next = *chunkHeaderList; chunkHeader->m_prev = NULL; if ((*chunkHeaderList) != NULL) { (*chunkHeaderList)->m_prev = chunkHeader; } *chunkHeaderList = chunkHeader; } static void MemSessioUnrecordHugeChunk( MemVirtualHugeChunkHeader* chunkHeader, MemVirtualHugeChunkHeader** chunkHeaderList) { if (chunkHeader->m_prev == NULL) { *chunkHeaderList = chunkHeader->m_next; if (chunkHeader->m_next != NULL) { chunkHeader->m_next->m_prev = NULL; } } else if (chunkHeader->m_next == NULL) { if (chunkHeader->m_prev != NULL) { chunkHeader->m_prev->m_next = NULL; } } else { chunkHeader->m_prev->m_next = chunkHeader->m_next; chunkHeader->m_next->m_prev = chunkHeader->m_prev; } } extern void MemHugeGetStats(MemHugeAllocStats* stats) { errno_t erc = memset_s(stats, sizeof(MemHugeAllocStats), 0, sizeof(MemHugeAllocStats)); securec_check(erc, "\0", "\0"); for (uint32_t i = 0; i < g_memGlobalCfg.m_nodeCount; ++i) { stats->m_memUsedBytes[i] = MOT_ATOMIC_LOAD(memUsedBytes[i]); stats->m_memRequestedBytes[i] = MOT_ATOMIC_LOAD(memRequestedBytes[i]); stats->m_objectCount[i] = MOT_ATOMIC_LOAD(objectCount[i]); } } extern void MemHugePrintStats(const char* name, LogLevel logLevel, MemHugeAllocStats* stats) { MOT_LOG(logLevel, "%s Huge Memory Report:", name); for (uint32_t i = 0; i < g_memGlobalCfg.m_nodeCount; ++i) { if (stats->m_memUsedBytes[i] > 0) { MOT_LOG( logLevel, "Huge memory usage on node %d: %" PRIu64 " MB Used", i, stats->m_memUsedBytes[i] / MEGA_BYTE); MOT_LOG(logLevel, "Huge memory usage on node %d: %" PRIu64 " MB Requested", i, stats->m_memRequestedBytes[i] / MEGA_BYTE); MOT_LOG(logLevel, "Huge object count on node %d: %" PRIu64 "", i, stats->m_objectCount[i]); } } } extern void MemHugePrintCurrentStats(const char* name, LogLevel logLevel) { if (MOT_CHECK_LOG_LEVEL(logLevel)) { MemHugeAllocStats stats; MemHugeGetStats(&stats); MemHugePrintStats(name, logLevel, &stats); } } extern void MemHugePrint(const char* name, LogLevel logLevel, MemReportMode reportMode /* = MEM_REPORT_SUMMARY */) { if (MOT_CHECK_LOG_LEVEL(logLevel)) { StringBufferApply([name, logLevel, reportMode](StringBuffer* stringBuffer) { MemHugeToString(0, name, stringBuffer, reportMode); MOT_LOG(logLevel, "%s", stringBuffer->m_buffer); }); } } extern void MemHugeToString( int indent, const char* name, StringBuffer* stringBuffer, MemReportMode reportMode /* = MEM_REPORT_SUMMARY */) { MemHugeAllocStats stats; MemHugeGetStats(&stats); if (reportMode == MEM_REPORT_DETAILED) { for (uint32_t i = 0; i < g_memGlobalCfg.m_nodeCount; ++i) { if (stats.m_memUsedBytes[i] > 0) { StringBufferAppend(stringBuffer, "\n%*sHuge memory usage on node %d: %" PRIu64 " MB Used", indent, "", i, stats.m_memUsedBytes[i] / MEGA_BYTE); StringBufferAppend(stringBuffer, "\n%*sHuge memory usage on node %d: %" PRIu64 " MB Requested", indent, "", i, stats.m_memRequestedBytes[i] / MEGA_BYTE); StringBufferAppend(stringBuffer, "\n%*sHuge object count on node %d: %" PRIu64 " MB", indent, "", i, stats.m_objectCount[i]); } } } else { uint64_t memUsedBytes = 0; uint64_t memRequestedBytes = 0; uint64_t objectCount = 0; for (uint32_t i = 0; i < g_memGlobalCfg.m_nodeCount; ++i) { memUsedBytes += stats.m_memUsedBytes[i]; memRequestedBytes += stats.m_memRequestedBytes[i]; objectCount += stats.m_objectCount[i]; } StringBufferAppend(stringBuffer, "%*sHuge memory: %" PRIu64 " MB Used, %" PRIu64 " MB Requested, %" PRIu64 " objects\n", indent, "", memUsedBytes / MEGA_BYTE, memRequestedBytes / MEGA_BYTE, objectCount); } } } // namespace MOT
38.4
120
0.626622
[ "object" ]
1d85d9c07c8682c372fceca5b435c4677431529b
2,148
cc
C++
hackt_docker/hackt/src/Object/traits/class_traits.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/traits/class_traits.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
hackt_docker/hackt/src/Object/traits/class_traits.cc
broken-wheel/hacktist
36e832ae7dd38b27bca9be7d0889d06054dc2806
[ "MIT" ]
null
null
null
/** \file "Object/traits/class_traits.cc" Traits and policy classes for instances. This file used to be "Object/art_object_classification_details.cc". $Id: class_traits.cc,v 1.13 2011/04/02 01:46:07 fang Exp $ */ #include "Object/traits/instance_traits.hh" #include "Object/traits/data_traits.hh" #include "Object/traits/param_traits.hh" #include "Object/traits/value_traits.hh" #include "Object/traits/node_traits.hh" #include "Object/unroll/unroll_context.hh" #include "Object/unroll/empty_instantiation_statement_type_ref_base.hh" namespace HAC { namespace entity { //============================================================================= const char class_traits<int_tag>::tag_name[] = "int"; const char class_traits<bool_tag>::tag_name[] = "bool"; const meta_type_tag_enum class_traits<bool_tag>::type_tag_enum_value; const char class_traits<enum_tag>::tag_name[] = "enum"; const char class_traits<real_tag>::tag_name[] = "real"; const char class_traits<string_tag>::tag_name[] = "string"; const char class_traits<datastruct_tag>::tag_name[] = "struct"; const char class_traits<process_tag>::tag_name[] = "process"; const char class_traits<channel_tag>::tag_name[] = "channel"; const char class_traits<pint_tag>::tag_name[] = "pint"; const char class_traits<pint_tag>::value_type_name[] = "integer"; const char class_traits<pbool_tag>::tag_name[] = "pbool"; const char class_traits<pbool_tag>::value_type_name[] = "boolean"; const char class_traits<preal_tag>::tag_name[] = "preal"; const char class_traits<preal_tag>::value_type_name[] = "real-value"; const char class_traits<pstring_tag>::tag_name[] = "pstring"; const char class_traits<pstring_tag>::value_type_name[] = "string-value"; const char class_traits<node_tag>::tag_name[] = "node"; //============================================================================= #if 0 /** What's this doing here? */ unroll_context null_parameter_type::make_unroll_context(void) const { return unroll_context(NULL, NULL); } #endif //============================================================================= } // end namespace entity } // end namespace HAC
24.409091
79
0.672253
[ "object" ]
1d8ee5ae3b81d167cec6d9838602976fb8013a20
4,322
hpp
C++
drape/batcher_helpers.hpp
marceldallagnol/omim
774de15a3b8c369acbf412f15a1db61717358262
[ "Apache-2.0" ]
2
2019-01-24T15:36:20.000Z
2019-12-26T10:03:48.000Z
drape/batcher_helpers.hpp
marceldallagnol/omim
774de15a3b8c369acbf412f15a1db61717358262
[ "Apache-2.0" ]
1
2018-03-07T15:05:23.000Z
2018-03-07T15:05:23.000Z
drape/batcher_helpers.hpp
marceldallagnol/omim
774de15a3b8c369acbf412f15a1db61717358262
[ "Apache-2.0" ]
1
2019-08-09T21:31:29.000Z
2019-08-09T21:31:29.000Z
#pragma once #include "drape/pointers.hpp" #include "std/function.hpp" #include "std/vector.hpp" namespace dp { class AttributeProvider; class BindingInfo; class BatchCallbacks { public: virtual void FlushData(BindingInfo const & binding, void const * data, uint32_t count) = 0; virtual void * GetIndexStorage(uint32_t indexCount, uint32_t & startIndex) = 0; virtual void SubmitIndices() = 0; virtual uint32_t GetAvailableVertexCount() const = 0; virtual uint32_t GetAvailableIndexCount() const = 0; virtual void ChangeBuffer() = 0; }; class UniversalBatch { public: UniversalBatch(BatchCallbacks & callbacks, uint8_t minVerticesCount, uint8_t minIndicesCount); virtual ~UniversalBatch(){} virtual void BatchData(ref_ptr<AttributeProvider> streams) = 0; void SetCanDevideStreams(bool canDevide); bool CanDevideStreams() const; void SetVertexStride(uint8_t vertexStride); protected: void FlushData(ref_ptr<AttributeProvider> streams, uint32_t vertexCount) const; void FlushData(BindingInfo const & info, void const * data, uint32_t elementCount) const; void * GetIndexStorage(uint32_t indexCount, uint32_t & startIndex); void SubmitIndex(); uint32_t GetAvailableVertexCount() const; uint32_t GetAvailableIndexCount() const; void ChangeBuffer() const; uint8_t GetVertexStride() const; virtual bool IsBufferFilled(uint32_t availableVerticesCount, uint32_t availableIndicesCount) const; private: BatchCallbacks & m_callbacks; bool m_canDevideStreams; uint8_t m_vertexStride; uint8_t const m_minVerticesCount; uint8_t const m_minIndicesCount; }; class TriangleListBatch : public UniversalBatch { using TBase = UniversalBatch; public: TriangleListBatch(BatchCallbacks & callbacks); void BatchData(ref_ptr<AttributeProvider> streams) override; }; class LineStripBatch : public UniversalBatch { using TBase = UniversalBatch; public: LineStripBatch(BatchCallbacks & callbacks); void BatchData(ref_ptr<AttributeProvider> streams) override; }; class LineRawBatch : public UniversalBatch { using TBase = UniversalBatch; public: LineRawBatch(BatchCallbacks & callbacks, vector<int> const & indices); void BatchData(ref_ptr<AttributeProvider> streams) override; private: vector<int> const & m_indices; }; class FanStripHelper : public UniversalBatch { using TBase = UniversalBatch; public: FanStripHelper(BatchCallbacks & callbacks); protected: uint32_t BatchIndexes(uint32_t vertexCount); void CalcBatchPortion(uint32_t vertexCount, uint32_t avVertex, uint32_t avIndex, uint32_t & batchVertexCount, uint32_t & batchIndexCount); bool IsFullUploaded() const; virtual uint32_t VtoICount(uint32_t vCount) const; virtual uint32_t ItoVCount(uint32_t iCount) const; virtual uint32_t AlignVCount(uint32_t vCount) const; virtual uint32_t AlignICount(uint32_t vCount) const; virtual void GenerateIndexes(void * indexStorage, uint32_t count, uint32_t startIndex) const = 0; private: bool m_isFullUploaded; }; class TriangleStripBatch : public FanStripHelper { using TBase = FanStripHelper; public: TriangleStripBatch(BatchCallbacks & callbacks); virtual void BatchData(ref_ptr<AttributeProvider> streams); protected: virtual void GenerateIndexes(void * indexStorage, uint32_t count, uint32_t startIndex) const; }; class TriangleFanBatch : public FanStripHelper { using TBase = FanStripHelper; public: TriangleFanBatch(BatchCallbacks & callbacks); virtual void BatchData(ref_ptr<AttributeProvider> streams); protected: virtual void GenerateIndexes(void * indexStorage, uint32_t count, uint32_t startIndex) const; }; class TriangleListOfStripBatch : public FanStripHelper { using TBase = FanStripHelper; public: TriangleListOfStripBatch(BatchCallbacks & callbacks); virtual void BatchData(ref_ptr<AttributeProvider> streams); protected: virtual bool IsBufferFilled(uint32_t availableVerticesCount, uint32_t availableIndicesCount) const; virtual uint32_t VtoICount(uint32_t vCount) const; virtual uint32_t ItoVCount(uint32_t iCount) const; virtual uint32_t AlignVCount(uint32_t vCount) const; virtual uint32_t AlignICount(uint32_t iCount) const; virtual void GenerateIndexes(void * indexStorage, uint32_t count, uint32_t startIndex) const; }; } // namespace dp
27.883871
101
0.78621
[ "vector" ]
1d9406c69d6e98e5b3132bbfb6730d1fef51732d
4,144
cpp
C++
tests/test/endpoint/test_handler.cpp
faasm/faabric
0e7a32c43bf009e22b715e27ae4c58a7866c065f
[ "Apache-2.0" ]
35
2020-10-20T15:15:40.000Z
2022-03-19T15:48:38.000Z
tests/test/endpoint/test_handler.cpp
faasm/faabric
0e7a32c43bf009e22b715e27ae4c58a7866c065f
[ "Apache-2.0" ]
66
2020-10-19T13:48:13.000Z
2022-03-26T15:06:48.000Z
tests/test/endpoint/test_handler.cpp
faasm/faabric
0e7a32c43bf009e22b715e27ae4c58a7866c065f
[ "Apache-2.0" ]
6
2020-10-20T15:15:43.000Z
2021-08-20T23:59:04.000Z
#include <catch2/catch.hpp> #include "faabric_utils.h" #include <DummyExecutor.h> #include <DummyExecutorFactory.h> #include <faabric/endpoint/FaabricEndpointHandler.h> #include <faabric/scheduler/Scheduler.h> #include <faabric/util/json.h> using namespace Pistache; namespace tests { class EndpointHandlerTestFixture : public SchedulerTestFixture { public: EndpointHandlerTestFixture() { executorFactory = std::make_shared<faabric::scheduler::DummyExecutorFactory>(); setExecutorFactory(executorFactory); } ~EndpointHandlerTestFixture() { executorFactory->reset(); } protected: std::shared_ptr<faabric::scheduler::DummyExecutorFactory> executorFactory; }; TEST_CASE_METHOD(EndpointHandlerTestFixture, "Test valid calls to endpoint", "[endpoint]") { // Note - must be async to avoid needing a result faabric::Message call = faabric::util::messageFactory("foo", "bar"); call.set_isasync(true); std::string user = "foo"; std::string function = "bar"; std::string actualInput; SECTION("With input") { actualInput = "foobar"; call.set_inputdata(actualInput); } SECTION("No input") {} call.set_user(user); call.set_function(function); const std::string& requestStr = faabric::util::messageToJson(call); // Handle the function endpoint::FaabricEndpointHandler handler; std::pair<int, std::string> response = handler.handleFunction(requestStr); REQUIRE(response.first == 0); std::string responseStr = response.second; // Check actual call has right details including the ID returned to the // caller std::vector<faabric::Message> msgs = sch.getRecordedMessagesAll(); REQUIRE(msgs.size() == 1); faabric::Message actualCall = msgs.at(0); REQUIRE(actualCall.user() == call.user()); REQUIRE(actualCall.function() == call.function()); REQUIRE(actualCall.id() == std::stoi(responseStr)); REQUIRE(actualCall.inputdata() == actualInput); } TEST_CASE("Test empty invocation", "[endpoint]") { endpoint::FaabricEndpointHandler handler; std::pair<int, std::string> actual = handler.handleFunction(""); REQUIRE(actual.first == 1); REQUIRE(actual.second == "Empty request"); } TEST_CASE("Test empty JSON invocation", "[endpoint]") { faabric::Message call; call.set_isasync(true); std::string expected; SECTION("Empty user") { expected = "Empty user"; call.set_function("echo"); } SECTION("Empty function") { expected = "Empty function"; call.set_user("demo"); } endpoint::FaabricEndpointHandler handler; const std::string& requestStr = faabric::util::messageToJson(call); std::pair<int, std::string> actual = handler.handleFunction(requestStr); REQUIRE(actual.first == 1); REQUIRE(actual.second == expected); } TEST_CASE_METHOD(EndpointHandlerTestFixture, "Check getting function status from endpoint", "[endpoint]") { // Create a message faabric::Message msg = faabric::util::messageFactory("demo", "echo"); int expectedReturnCode = 0; std::string expectedOutput; SECTION("Running") { expectedOutput = "RUNNING"; } SECTION("Failure") { std::string errorMsg = "I have failed"; msg.set_outputdata(errorMsg); msg.set_returnvalue(1); sch.setFunctionResult(msg); expectedReturnCode = 1; expectedOutput = "FAILED: " + errorMsg; } SECTION("Success") { std::string errorMsg = "I have succeeded"; msg.set_outputdata(errorMsg); msg.set_returnvalue(0); sch.setFunctionResult(msg); expectedOutput = faabric::util::messageToJson(msg); } msg.set_isstatusrequest(true); endpoint::FaabricEndpointHandler handler; const std::string& requestStr = faabric::util::messageToJson(msg); std::pair<int, std::string> actual = handler.handleFunction(requestStr); REQUIRE(actual.first == expectedReturnCode); REQUIRE(actual.second == expectedOutput); } }
27.084967
78
0.663127
[ "vector" ]
1d944e919d7974364023bbcd585720bc0539f83c
70,021
cpp
C++
ComputerVisionThesisSolution/ScenceSimulateProj/Core/cSanResourceManager.cpp
zxyinz/ComputerVisionThesis
081cadc6b9d2b05bd42f0ff0ba9d084c1da4faa2
[ "MIT" ]
null
null
null
ComputerVisionThesisSolution/ScenceSimulateProj/Core/cSanResourceManager.cpp
zxyinz/ComputerVisionThesis
081cadc6b9d2b05bd42f0ff0ba9d084c1da4faa2
[ "MIT" ]
null
null
null
ComputerVisionThesisSolution/ScenceSimulateProj/Core/cSanResourceManager.cpp
zxyinz/ComputerVisionThesis
081cadc6b9d2b05bd42f0ff0ba9d084c1da4faa2
[ "MIT" ]
null
null
null
#include"cSanResourceManager.h" using namespace std; using namespace San; using namespace San::FileIOStream; bool cSanResourceManager::iCreateResourceManager() { if(::gloFoundVector(this->m_strName)) { return false; } this->m_bManagerLock=false; this->m_FileMatchTable.clear(); //this->m_TextureList.clear(); //this->m_MeshList.clear(); //this->m_SoundList.clear(); this->m_FilePathSearchTableForward.clear(); this->m_FilepathSearchTableBackward.clear(); this->m_pResourcesTableArray = new SANRESOURCETABLE[RESOURCETYPECOUNT]; this->m_pAvailableIDListArray = new list<SVALUE>[RESOURCETYPECOUNT]; this->m_pMaxAvailableIDArray = new SVALUE[RESOURCETYPECOUNT]; for (uint32 seek = 0; seek < RESOURCETYPECOUNT; seek = seek + 1) { this->m_pResourcesTableArray[seek].clear(); this->m_pMaxAvailableIDArray[seek] = (uint32) (this->_GetResourceTypeByArrayIndex(seek)) + 1; this->m_pAvailableIDListArray[seek].clear(); } this->m_GraphicsDeviceResourceManagerHandle=nullptr; this->iRegistResourceCreaterFunc(_SSTR(".bmp"),this->_LoadBMPFile,RT_TEXTURE); this->iRegistResourceCreaterFunc(_SSTR(".bmp"), this->_LoadBMPFile, RT_TEXTURE_2D); this->iRegistResourceCreaterFunc(_SSTR(".BMP"),this->_LoadBMPFile,RT_TEXTURE); this->iRegistResourceCreaterFunc(_SSTR(".BMP"), this->_LoadBMPFile, RT_TEXTURE_2D); this->iRegistResourceCreaterFunc(_SSTR(".tga"),this->_LoadTGAFile,RT_TEXTURE); this->iRegistResourceCreaterFunc(_SSTR(".tga"), this->_LoadTGAFile, RT_TEXTURE_2D); this->iRegistResourceCreaterFunc(_SSTR(".TGA"),this->_LoadTGAFile,RT_TEXTURE); this->iRegistResourceCreaterFunc(_SSTR(".TGA"), this->_LoadTGAFile, RT_TEXTURE_2D); this->iRegistResourceCreaterFunc(_SSTR(".obj"),this->_LoadOBJFile,RT_MESH); this->iRegistResourceCreaterFunc(_SSTR(".obj"), this->_LoadOBJFile, RT_MESH_STATIC); this->iRegistResourceCreaterFunc(_SSTR(".OBJ"),this->_LoadOBJFile,RT_MESH); this->iRegistResourceCreaterFunc(_SSTR(".OBJ"), this->_LoadOBJFile, RT_MESH_STATIC); this->iRegistResourceCreaterFunc(_SSTR(".x"),this->_LoadXMDFile,RT_MESH); this->iRegistResourceCreaterFunc(_SSTR(".x"), this->_LoadXMDFile, RT_MESH_STATIC); this->iRegistResourceCreaterFunc(_SSTR(".X"),this->_LoadXMDFile,RT_MESH); this->iRegistResourceCreaterFunc(_SSTR(".X"), this->_LoadXMDFile, RT_MESH_STATIC); this->iRegistResourceCreaterFunc(_SSTR(".fbx"),this->_LoadFBXFile,RT_MESH); this->iRegistResourceCreaterFunc(_SSTR(".fbx"), this->_LoadFBXFile, RT_MESH_STATIC); this->iRegistResourceCreaterFunc(_SSTR(".fbx"), this->_LoadFBXFile, RT_MESH_DYNAMIC); this->iRegistResourceCreaterFunc(_SSTR(".FBX"),this->_LoadFBXFile,RT_MESH); this->iRegistResourceCreaterFunc(_SSTR(".FBX"), this->_LoadFBXFile, RT_MESH_STATIC); this->iRegistResourceCreaterFunc(_SSTR(".FBX"), this->_LoadFBXFile, RT_MESH_DYNAMIC); this->iRegistResourceCopyFunc(this->_CopyTexture,RT_TEXTURE); this->iRegistResourceCopyFunc(this->_CopyTexture, RT_TEXTURE_2D); this->iRegistResourceCopyFunc(this->_CopyTexture, RT_TEXTURE_3D); this->iRegistResourceCopyFunc(this->_CopyMesh, RT_MESH); this->iRegistResourceCopyFunc(this->_CopyMesh, RT_MESH_STATIC); this->iRegistResourceCopyFunc(this->_CopyMesh, RT_MESH_DYNAMIC); this->iRegistResourceCopyFunc(this->_CopyMesh, RT_SOUND); this->iRegistResourceReleaseFunc(this->_ReleaseTexture, RT_TEXTURE); this->iRegistResourceReleaseFunc(this->_ReleaseTexture, RT_TEXTURE_2D); this->iRegistResourceReleaseFunc(this->_ReleaseTexture, RT_TEXTURE_3D); this->iRegistResourceReleaseFunc(this->_ReleaseMesh, RT_MESH); this->iRegistResourceReleaseFunc(this->_ReleaseMesh, RT_MESH_STATIC); this->iRegistResourceReleaseFunc(this->_ReleaseMesh, RT_MESH_DYNAMIC); ::gloRegisterVector(this->m_strName,VT_SYS|VT_VAR,(SHANDLE)this); return true; } void cSanResourceManager::iReleaseResourceManager() { if(!this->m_FileMatchTable.empty()) { this->m_FileMatchTable.clear(); } for (uint32 seek = 0; seek < RESOURCETYPECOUNT; seek = seek + 1) { this->_ReleaseList(this->_GetResourceTypeByArrayIndex(seek)); this->m_pMaxAvailableIDArray[seek] = (uint32) (this->_GetResourceTypeByArrayIndex(seek)) + 1; this->m_pAvailableIDListArray[seek].clear(); } list<lpSANRESPTR>::iterator pRes = this->m_AssignedVoidPtrList.begin(); while (pRes != this->m_AssignedVoidPtrList.end()) { delete (*pRes); (*pRes) = nullptr; pRes++; } list<lpSANRESPTRC>::iterator pResC = this->m_AssignedVoidConstPtrList.begin(); while (pResC != this->m_AssignedVoidConstPtrList.end()) { delete (*pResC); (*pResC) = nullptr; pResC++; } delete this->m_pResourcesTableArray; this->m_pResourcesTableArray = nullptr; delete this->m_pAvailableIDListArray; this->m_pAvailableIDListArray = nullptr; delete this->m_pMaxAvailableIDArray; this->m_pMaxAvailableIDArray = nullptr; ::gloDestoryVector(this->m_strName,VT_SYS|VT_VAR); } uint32 cSanResourceManager::iCreateResourceFromFile(const SString &strFilePath, const eSANRESOURCETYPE Type, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_CREATEFUNC pCreateFunc, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { if (strFilePath.empty()) { return 0; } while (this->m_bManagerLock) { } this->m_bManagerLock = true; SVALUE ResID = this->iGetAvailableID(Type); if (ResID == 0) { this->m_bManagerLock = false; return 0; } if(this->m_FilePathSearchTableForward.find(strFilePath)!=this->m_FilePathSearchTableForward.end()) { this->m_bManagerLock=false; return this->iGetResourceIDByPath(strFilePath); } if(pCreateFunc==nullptr) { pCreateFunc = this->iGetCreateFunc(strFilePath.substr(strFilePath.find(_SSTR(".")), strFilePath.length()), Type); } if(pCreateFunc==nullptr) { this->m_bManagerLock=false; return 0; } SANRESOURCE Res; Res.description.ResID=ResID; Res.description.CreaterID = CreaterID; Res.description.GroupID = GroupID; Res.description.AccessFlag = SRIO_ORIGIONAL_RESOURCE | Flag; Res.description.AccessFlag = (CreaterID == 0) ? (Res.description.AccessFlag | SRIO_MANAGER_AUTO_DELETE) : Res.description.AccessFlag; Res.description.pCopyFunc = pCopyFunc == nullptr ? this->iGetCopyFunc(Type) : pCopyFunc; Res.description.pReleaseFunc = pReleaseFunc == nullptr ? this->iGetReleaseFunc(Type) : pReleaseFunc; Res.description.OrigionResPtr = nullptr; Res.description.PreviousResPtr = nullptr; Res.description.AssignedPtr.clear(); Res.description.AssignedConstPtr.clear(); Res.description.ReferenceCount = -1; Res.value = nullptr; Res.description.Size = pCreateFunc(strFilePath, 0, &(Res.value)); if ((Res.description.Size == 0) || (Res.value == nullptr)) { this->m_bManagerLock = false; return 0; } this->_RegisteID(&Res, Type); this->m_FilePathSearchTableForward.insert(::make_pair(strFilePath, ResID)); this->m_FilepathSearchTableBackward.insert(::make_pair(ResID, strFilePath)); this->m_bManagerLock=false; return ResID; } SVALUE cSanResourceManager::iCreateTextureFromFile(const SString &strFilePath, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_CREATEFUNC pCreateFunc, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { SVALUE TexID = this->iCreateResourceFromFile(strFilePath, RT_TEXTURE, CreaterID, GroupID, Flag, pCreateFunc, pCopyFunc, pReleaseFunc); if (TexID == 0) { return TexID; } lpSANRESOURCE pTexRes = this->_GetResourceHandle(TexID, RT_TEXTURE); if (pTexRes == nullptr) { return 0; } lpSANTEXTURE pTex = (lpSANTEXTURE)pTexRes->value; pTex->CurrentParam = (SVALUE)this->iAddToDeviceTextureList(pTex); return TexID; } SVALUE cSanResourceManager::iCreateMeshFromFile(const SString &strFilePath, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_CREATEFUNC pCreateFunc, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { SVALUE MeshID = this->iCreateResourceFromFile(strFilePath, RT_MESH, CreaterID, GroupID, Flag, pCreateFunc, pCopyFunc, pReleaseFunc); if (MeshID == 0) { return MeshID; } lpSANRESOURCE pMeshRes = this->_GetResourceHandle(MeshID,RT_MESH); if (pMeshRes == nullptr) { return 0; } lpSANMESH pMesh = (lpSANMESH)pMeshRes->value; SANOBJECTLIST::iterator pObj = pMesh->value.begin(); SVALUE TexID; while (pObj != pMesh->value.end()) { pObj->ObjParam = this->iAddToDeviceMeshList(&(*pObj)); list<stSANUNKNOWNEX<SANTEXRENDERDESC, SHANDLE>>::iterator pTex = pObj->Material.TexList.begin(); while (pTex != pObj->Material.TexList.end()) { TexID = this->iCreateTextureFromFile(pTex->description.strFilePath, CreaterID, GroupID, Flag, nullptr, nullptr, nullptr); lpSANRESPTRC pTextureRes = this->iGetTextureConstPtr(TexID, CreaterID, GroupID); if (pTextureRes->res_ptr != nullptr) { pTex->value = (SHANDLE) pTextureRes; } else { pTex->value = nullptr; } pTex++; } pObj++; } return MeshID; } SVALUE cSanResourceManager::iCreateResourceFromMemory(SHANDLE BufferPtr, SVALUE BufferSize, const eSANRESOURCETYPE Type, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { if (BufferPtr == nullptr) { return 0; } while (this->m_bManagerLock) { } this->m_bManagerLock=true; SVALUE ResID = this->iGetAvailableID(Type); if (ResID == 0) { return 0; } SANRESOURCE Res; Res.description.ResID=ResID; Res.description.Size = BufferSize; Res.description.CreaterID = CreaterID; Res.description.GroupID = GroupID; Res.description.AccessFlag = SRIO_ORIGIONAL_RESOURCE | Flag; Res.description.pCopyFunc = pCopyFunc == nullptr ? this->iGetCopyFunc(Type) : pCopyFunc; Res.description.pReleaseFunc = pReleaseFunc == nullptr ? this->iGetReleaseFunc(Type) : pReleaseFunc; Res.description.OrigionResPtr = nullptr; Res.description.PreviousResPtr = nullptr; Res.description.AssignedPtr.clear(); Res.description.AssignedConstPtr.clear(); Res.description.ReferenceCount = -1; Res.value=BufferPtr; this->_RegisteID(&Res,Type); this->m_bManagerLock=false; return ResID; } SVALUE cSanResourceManager::iCreateTextureFromMemory(lpSANTEXTURE pTexture, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { SVALUE TexID = this->iCreateResourceFromMemory(pTexture, sizeof(SANTEXTURE), RT_TEXTURE, CreaterID, GroupID, Flag, pCopyFunc, pReleaseFunc); if (TexID == 0) { return TexID; } lpSANRESOURCE pTexRes = this->_GetResourceHandle(TexID, RT_TEXTURE); if (pTexRes == nullptr) { return 0; } lpSANTEXTURE pTex = (lpSANTEXTURE) pTexRes->value; pTex->CurrentParam = (SVALUE)this->iAddToDeviceTextureList(pTex); return TexID; } SVALUE cSanResourceManager::iCreateMeshFromMemory(lpSANMESH pMesh, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { SVALUE MeshID = this->iCreateResourceFromMemory(pMesh, sizeof(SANMESH), RT_MESH, CreaterID, GroupID, Flag, pCopyFunc, pReleaseFunc); if (MeshID == 0) { return MeshID; } lpSANRESOURCE pMeshRes = this->_GetResourceHandle(MeshID,RT_MESH); if (pMeshRes == nullptr) { return 0; } lpSANMESH MeshPtr = (lpSANMESH) pMeshRes->value; SANOBJECTLIST::iterator pObj = MeshPtr->value.begin(); SVALUE TexID; while (pObj != MeshPtr->value.end()) { pObj->ObjParam = this->iAddToDeviceMeshList(&(*pObj)); list<stSANUNKNOWNEX<SANTEXRENDERDESC, SHANDLE>>::iterator pTex = pObj->Material.TexList.begin(); while (pTex != pObj->Material.TexList.end()) { TexID = this->iCreateTextureFromFile(pTex->description.strFilePath, CreaterID, GroupID, Flag, nullptr, nullptr, nullptr); lpSANRESPTRC pTextureRes = this->iGetTextureConstPtr(TexID, CreaterID, GroupID); if (pTextureRes->res_ptr != nullptr) { pTex->value = (SHANDLE) pTextureRes; } else { pTex->value = nullptr; } pTex++; } pObj++; } return MeshID; } SVALUE cSanResourceManager::iCopyResource(uint32 ResID, const uint32 RequireID, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { while (this->m_bManagerLock) { } this->m_bManagerLock = true; eSANRESOURCETYPE Type = this->iGetResourceType(ResID); SVALUE DestResID = this->iGetAvailableID(Type); if (DestResID == 0) { this->m_bManagerLock = false; return 0; } lpSANRESOURCE pRes = this->_GetResourceHandle(ResID, Type); if (pRes == nullptr) { this->m_bManagerLock = false; return 0; } if ((pRes->description.AccessFlag&SRIO_MANAGER_REFERENCE) == SRIO_MANAGER_REFERENCE) { this->m_bManagerLock = false; return 0; } if (pRes->description.CreaterID == 0) { if ((pRes->description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_bManagerLock = false; return 0; } } else { if (pRes->description.CreaterID != RequireID) { if (pRes->description.GroupID == 0) { if ((pRes->description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_bManagerLock = false; return 0; } } else { if (pRes->description.GroupID != RequireID) { if ((pRes->description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_bManagerLock = false; return 0; } } else { if ((pRes->description.AccessFlag&SRIO_GROUP_COPY) != SRIO_GROUP_COPY) { this->m_bManagerLock = false; return 0; } } } } else { if ((pRes->description.AccessFlag&SRIO_CREATER_COPY) != SRIO_CREATER_COPY) { this->m_bManagerLock = false; return 0; } } } SANRESOURCE DestRes; DestRes.description.ResID = DestResID; DestRes.description.Size = pRes->description.Size; DestRes.description.CreaterID = CreaterID; DestRes.description.GroupID = GroupID; DestRes.description.AccessFlag = ((Flag&SRIO_MANAGER_COPY_FLAG) == SRIO_MANAGER_COPY_FLAG) ? pRes->description.AccessFlag : Flag; DestRes.description.AccessFlag = (CreaterID == 0) ? (DestRes.description.AccessFlag | SRIO_MANAGER_AUTO_DELETE) : DestRes.description.AccessFlag; DestRes.description.pCopyFunc = pCopyFunc == nullptr ? pRes->description.pCopyFunc : pCopyFunc; DestRes.description.pReleaseFunc = pReleaseFunc == nullptr ? pRes->description.pReleaseFunc : pReleaseFunc; DestRes.description.OrigionResPtr = ((pRes->description.AccessFlag&SRIO_ORIGIONAL_RESOURCE) == SRIO_ORIGIONAL_RESOURCE) ? pRes : pRes->description.OrigionResPtr; DestRes.description.PreviousResPtr = pRes; DestRes.description.AssignedPtr.clear(); DestRes.description.AssignedConstPtr.clear(); DestRes.description.ReferenceCount = -1; DestRes.description.Size = DestRes.description.pCopyFunc(pRes->value, &(DestRes.value)); if (DestRes.value == 0) { this->m_bManagerLock = false; return 0; } this->_RegisteID(&DestRes, Type); this->m_bManagerLock = false; return ResID; } SVALUE cSanResourceManager::iCopyTexture(uint32 TexID, const uint32 RequireID, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { SVALUE DestTexID = this->iCopyResource(TexID, RequireID, CreaterID, GroupID, Flag, pCopyFunc, pReleaseFunc); if (DestTexID == 0) { return DestTexID; } lpSANRESOURCE pTexRes = this->_GetResourceHandle(DestTexID, RT_TEXTURE); if (pTexRes == nullptr) { return 0; } lpSANTEXTURE pTex = (lpSANTEXTURE) pTexRes->value; pTex->CurrentParam = (SVALUE)this->iAddToDeviceTextureList(pTex); return DestTexID; } SVALUE cSanResourceManager::iCopyMesh(uint32 MeshID, const uint32 RequireID, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { SVALUE DestMeshID = this->iCopyResource(MeshID, RequireID, CreaterID, GroupID, Flag, pCopyFunc, pReleaseFunc); if (DestMeshID == 0) { return DestMeshID; } lpSANRESOURCE pMeshRes = this->_GetResourceHandle(DestMeshID, RT_MESH); if (pMeshRes == nullptr) { return 0; } lpSANMESH pMesh = (lpSANMESH) pMeshRes->value; SANOBJECTLIST::iterator pObj = pMesh->value.begin(); SVALUE TexID; while (pObj != pMesh->value.end()) { pObj->ObjParam = this->iAddToDeviceMeshList(&(*pObj)); list<stSANUNKNOWNEX<SANTEXRENDERDESC, SHANDLE>>::iterator pTex = pObj->Material.TexList.begin(); while (pTex != pObj->Material.TexList.end()) { TexID = this->iCreateTextureFromFile(pTex->description.strFilePath, CreaterID, GroupID, Flag, nullptr, nullptr, nullptr); lpSANRESPTRC pTextureRes = this->iGetTextureConstPtr(TexID, CreaterID, GroupID); if (pTextureRes->res_ptr != nullptr) { pTex->value = (SHANDLE) pTextureRes; } else { pTex->value = nullptr; } pTex++; } pObj++; } return DestMeshID; } bool cSanResourceManager::iReleaseResource(SVALUE ResID, const uint32 ReleaseID, SANRES_RELEASEFUNC pReleaseFunc) { if(ResID==0) { return false; } eSANRESOURCETYPE ResType = this->iGetResourceType(ResID); while (this->m_bManagerLock) { } this->m_bManagerLock = true; if (this->_ReleaseID(ResID, ResType, ReleaseID, ReleaseID, pReleaseFunc)) { map<SVALUE, SString>::iterator pItem = this->m_FilepathSearchTableBackward.find(ResID); if (pItem != this->m_FilepathSearchTableBackward.end()) { this->m_FilepathSearchTableBackward.erase(ResID); this->m_FilePathSearchTableForward.erase(pItem->second); } this->m_bManagerLock = false; return true; } this->m_bManagerLock = false; return false; } bool cSanResourceManager::iReleaseTextureResource(SVALUE TexID, const uint32 ReleaseID, SANRES_RELEASEFUNC pReleaseFunc) { return this->iReleaseResource(TexID, ReleaseID, pReleaseFunc); } bool cSanResourceManager::iReleaseMeshResource(SVALUE MeshID, const uint32 ReleaseID, SANRES_RELEASEFUNC pReleaseFunc) { return this->iReleaseResource(MeshID, ReleaseID, pReleaseFunc); } bool cSanResourceManager::iUpdateResourceAccessFlag(uint32 ResID, const eSANRESOURCETYPE Type, const uint32 Flag, const uint32 RequireID) { if (ResID == 0) { return false; } eSANRESOURCETYPE ResType = this->iGetResourceType(ResID); lpSANRESOURCE pRes = this->_GetResourceHandle(ResID, ResType); if (pRes == nullptr) { return false; } if (pRes->description.CreaterID != RequireID) { return false; } pRes->description.AccessFlag = Flag; this->m_bManagerLock = false; return false; } bool cSanResourceManager::iUpdateResourceCopyFunc(uint32 ResID, const eSANRESOURCETYPE Type, SANRES_COPYFUNC pCopyFunc, const uint32 RequireID) { if (ResID == 0) { return false; } eSANRESOURCETYPE ResType = this->iGetResourceType(ResID); lpSANRESOURCE pRes = this->_GetResourceHandle(ResID, ResType); if (pRes == nullptr) { return false; } if (pRes->description.CreaterID != RequireID) { return false; } pRes->description.pCopyFunc = pCopyFunc; this->m_bManagerLock = false; return false; } bool cSanResourceManager::iUpdateResourceReleaseFunc(uint32 ResID, const eSANRESOURCETYPE Type, SANRES_RELEASEFUNC pReleaseFunc, const uint32 RequireID) { if (ResID == 0) { return false; } eSANRESOURCETYPE ResType = this->iGetResourceType(ResID); lpSANRESOURCE pRes = this->_GetResourceHandle(ResID, ResType); if (pRes == nullptr) { return false; } if (pRes->description.CreaterID != RequireID) { return false; } pRes->description.pReleaseFunc = pReleaseFunc; this->m_bManagerLock = false; return false; } SVALUE cSanResourceManager::iRegisteResource(const SHANDLE ResHandle, const uint32 ResSize, const eSANRESOURCETYPE ResType, const uint32 CreaterID, const uint32 GroupID, const uint32 Flag, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { while (this->m_bManagerLock) { } this->m_bManagerLock = true; SANRESOURCE Res; Res.description.ResID = 0; Res.description.Size = ResSize; Res.description.AccessFlag = SRIO_MANAGER_REFERENCE | Flag; Res.description.CreaterID = CreaterID; Res.description.GroupID = GroupID; Res.description.pReleaseFunc = pReleaseFunc; Res.description.OrigionResPtr = nullptr; Res.description.PreviousResPtr = nullptr; Res.description.AssignedPtr.clear(); Res.description.AssignedConstPtr.clear(); Res.description.ReferenceCount = -1; Res.value = ResHandle; this->m_bManagerLock = false; return this->_RegisteID(&Res, ResType); } SRESULT cSanResourceManager::_LoadBMPFile(SString strFilePath, SVALUE Param, SHANDLE* pHandle) { if ((pHandle == nullptr) || ((*pHandle) != nullptr)) { return 0; } SStringW strPath = ::gloTToW(strFilePath.c_str()).c_str(); cBMPLoader *pBMPLoader=new cBMPLoader(strPath.c_str()); if(!pBMPLoader->iBMPLoad()) { delete pBMPLoader; pBMPLoader=nullptr; *pHandle = nullptr; return 0; } *pHandle = new SANTEXTURE; lpSANTEXTURE pTex = (lpSANTEXTURE) (*pHandle); ::gloMemSet(pTex,0,sizeof(SANTEXTURE)); pTex->Version=STV_STATIC; pTex->Type=STT_TEX2D; pTex->PixMapPtr = new SANPIXMAP2D; ::gloMemSet((pTex->PixMapPtr), 0, sizeof(SANPIXMAP2D)); lpSANPIXMAP2D(pTex->PixMapPtr)->width = pBMPLoader->iBMPGetWeight(); lpSANPIXMAP2D(pTex->PixMapPtr)->height = pBMPLoader->iBMPGetHigh(); unsigned int size = lpSANPIXMAP2D(pTex->PixMapPtr)->width*lpSANPIXMAP2D(pTex->PixMapPtr)->height; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap = new SANPIX[size]; ::gloMemSet(lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap, 0, sizeof(SANPIX)*size); uint8 *pPtr=(uint8*)pBMPLoader->iBMPGetImage(); if(pBMPLoader->iGetBitmapType()==BMP_RGB) { pTex->PixFormat=PT_RGB; for(int seek=0;seek<size;seek=seek+1) { unsigned int seekb=seek*3; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap[seek].r = pPtr[seekb]; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap[seek].g = pPtr[seekb + 1]; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap[seek].b = pPtr[seekb + 2]; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap[seek].a = 0xff; } } else { pTex->PixFormat=PT_RGBA; ::gloMemCopy(lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap, pPtr, size*pTex->PixFormat); } pTex->DataSize=pBMPLoader->iBMPGetSize(); delete[] pPtr; pPtr=nullptr; delete pBMPLoader; pBMPLoader=nullptr; return pTex->DataSize; } SRESULT cSanResourceManager::_LoadTGAFile(SString strFilePath, SVALUE Param, SHANDLE* pHandle) { if ((pHandle == nullptr) || ((*pHandle) != nullptr)) { return 0; } SStringW strPath = ::gloTToW(strFilePath.c_str()).c_str(); cTGALoader *pTGALoader=new cTGALoader(strPath.c_str()); if(!pTGALoader->iTGALoad()) { delete pTGALoader; pTGALoader=nullptr; *pHandle = nullptr; return 0; } *pHandle = new SANTEXTURE; lpSANTEXTURE pTex = (lpSANTEXTURE) (*pHandle); ::gloMemSet(pTex, 0, sizeof(SANTEXTURE)); pTex->Version=STV_STATIC; pTex->Type=STT_TEX2D; pTex->PixMapPtr=new SANPIXMAP2D; ::gloMemSet((pTex->PixMapPtr), 0, sizeof(SANPIXMAP2D)); lpSANPIXMAP2D(pTex->PixMapPtr)->width = pTGALoader->iTGAGetWeight(); lpSANPIXMAP2D(pTex->PixMapPtr)->height = pTGALoader->iTGAGetHigh(); unsigned int size = lpSANPIXMAP2D(pTex->PixMapPtr)->width*lpSANPIXMAP2D(pTex->PixMapPtr)->height; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap = new SANPIX[size]; ::gloMemSet(lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap, 0, sizeof(SANPIX)*size); uint8 *pPtr=(uint8*)pTGALoader->iGetImage(); if(pTGALoader->iGetTGAType()==BMP_RGB) { pTex->PixFormat=PT_RGB; for(unsigned int seek=0;seek<size;seek=seek+1) { unsigned int seekb=seek*3; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap[seek].r = pPtr[seekb]; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap[seek].g = pPtr[seekb + 1]; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap[seek].b = pPtr[seekb + 2]; lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap[seek].a = 0xff; } } else { pTex->PixFormat=PT_RGBA; ::gloMemCopy(lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap, pPtr, size*pTex->PixFormat); } pTex->DataSize=pTGALoader->iTGAGetSize(); delete[] pPtr; pPtr=nullptr; delete pTGALoader; pTGALoader=nullptr; return pTex->DataSize; } SRESULT cSanResourceManager::_LoadOBJFile(SString strFilePath, SVALUE Param, SHANDLE* pHandle) { if ((pHandle == nullptr) || ((*pHandle) != nullptr)) { return 0; } cOBJFileLoader *pOBJLoader=new cOBJFileLoader(); if (!pOBJLoader->iLoadFile(::gloTToW(strFilePath))) { delete pOBJLoader; pOBJLoader=nullptr; *pHandle = nullptr; return 0; } *pHandle = new SANMESH; lpSANMESH pMesh = (lpSANMESH) (*pHandle); pMesh->description = strFilePath; pMesh->value=pOBJLoader->iGetObjectList(); delete pOBJLoader; pOBJLoader=nullptr; return pMesh->value.size(); } SRESULT cSanResourceManager::_LoadXMDFile(SString strFilePath, SVALUE Param, SHANDLE* pHandle) { #ifdef _DIRECTX cXFileLoader *pXFileLoader=new cXFileLoader(); if(!pXFileLoader->iLoadXFile(strFile)) { delete pXFileLoader; return nullptr; } SANFRAMEELEMENT* pFrameElement=new SANFRAMEELEMENT; pFrameElement->pFrame=pXFileLoader->iGetXFrame(); pFrameElement->Time=0; pFrameElement->Speed=0.0; pFrameElement->strName=strFile; delete pXFileLoader; return (SHANDLE)pFrameElement; #else return 0; #endif } SRESULT cSanResourceManager::_LoadFBXFile(SString strFilePath, SVALUE Param, SHANDLE* pHandle) { if ((pHandle == nullptr) || ((*pHandle) != nullptr)) { return 0; } /*cFBXFileLoader *pFBXLoader=new cFBXFileLoader(); if (!pFBXLoader->iLoadFile(strFilePath)) { pFBXLoader->iRelease(); delete pFBXLoader; *pHandle = nullptr; return 0; } *pHandle = new SANMESH; lpSANMESH pMesh = (lpSANMESH) (*pHandle); pMesh->description = strFilePath; pMesh->value=pFBXLoader->iGetMesh(); delete pFBXLoader; pFBXLoader=nullptr; if(pMesh->value.empty()) { pMesh->description.clear(); delete pMesh; pMesh=nullptr; } return pMesh->value.size();*/ } SRESULT cSanResourceManager::_CopyTexture(SHANDLE TextureHandle, SHANDLE* pDestHandle) { if ((TextureHandle == nullptr) || (pDestHandle = nullptr)) { return 0; } lpSANTEXTURE pTex = new SANTEXTURE; *pTex = *((lpSANTEXTURE) TextureHandle); pTex->PixMapPtr = nullptr; pTex->ParamList = nullptr; pTex->ParamList = new SVALUE[pTex->ParamListSize]; for (uint32 seek = 0; seek < pTex->ParamListSize; seek = seek + 1) { pTex->ParamList[seek] = 0; } pTex->CurrentParam = 0; lpSANPIXMAP2D pMap2D = nullptr; lpSANPIXMAPF2D pMap2DF = nullptr; switch (pTex->PixFormat) { case eSANPIXTYPE::PT_RGB: case eSANPIXTYPE::PT_RGBA: pTex->PixMapPtr = new SANPIXMAP2D; pMap2D = (lpSANPIXMAP2D)pTex->PixMapPtr; *pMap2D = *((lpSANPIXMAP2D) ((lpSANTEXTURE) TextureHandle)->PixMapPtr); pMap2D->pPixMap = new SANPIX[pMap2D->width*pMap2D->height]; pTex->DataSize = pMap2D->width*pMap2D->height; ::gloMemCopy(pTex->PixMapPtr, ((lpSANTEXTURE) TextureHandle)->PixMapPtr, sizeof(SANPIX)*pTex->DataSize); break; case eSANPIXTYPE::PT_RGB_F: case eSANPIXTYPE::PT_RGBA_F: pTex->PixMapPtr = new SANPIXMAPF2D; pMap2DF = (lpSANPIXMAPF2D) pTex->PixMapPtr; *pMap2DF = *((lpSANPIXMAPF2D) ((lpSANTEXTURE) TextureHandle)->PixMapPtr); pMap2DF->pPixMap = new SANPIXF[pMap2DF->width*pMap2DF->height]; pTex->DataSize = pMap2DF->width*pMap2DF->height; ::gloMemCopy(pTex->PixMapPtr, ((lpSANTEXTURE) TextureHandle)->PixMapPtr, sizeof(SANPIXF)*pTex->DataSize); break; default: delete (pTex->ParamList); pTex->ParamList = nullptr; delete pTex; pTex = nullptr; return 0; break; } *pDestHandle = pTex; return pTex->DataSize; } SRESULT cSanResourceManager::_CopyMesh(SHANDLE MeshHandle, SHANDLE* pDestHandle) { if ((MeshHandle == nullptr) || (pDestHandle = nullptr)) { return 0; } lpSANMESH pMesh = new SANMESH; lpSANMESH pSrcMesh = (lpSANMESH) MeshHandle; pMesh->description = pSrcMesh->description; SANOBJECTLIST::iterator pObject = pSrcMesh->value.begin(); SANOBJECT Obj; while (pObject != pSrcMesh->value.end()) { Obj = *pObject; list<stSANUNKNOWNEX<SANTEXRENDERDESC, SHANDLE>>::iterator pTex = Obj.Material.TexList.begin(); while (pTex != Obj.Material.TexList.end()) { pTex->value = nullptr; pTex++; } Obj.ObjParam = 0; Obj.pVertexList = nullptr; Obj.pVertexList = new SANVERTEX[Obj.VertexListSize]; for (uint32 seek = 0; seek < Obj.VertexListSize; seek = seek + 1) { Obj.pVertexList[seek] = pObject->pVertexList[seek]; } pMesh->value.insert(pMesh->value.end(), Obj); pObject++; } *pDestHandle = pMesh; return pMesh->value.size(); } SRESULT cSanResourceManager::_ReleaseTexture(SHANDLE TextureHandle, SHANDLE ResourceManagerPtr, SVALUE Param) { if ((TextureHandle == nullptr) || (ResourceManagerPtr == nullptr)) { return true; } cSanResourceManager* pManager = (cSanResourceManager*) ResourceManagerPtr; lpSANTEXTURE pTex=(lpSANTEXTURE)TextureHandle; if(pTex->Type==STT_TEX2D) { delete [](lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap); lpSANPIXMAP2D(pTex->PixMapPtr)->pPixMap = nullptr; delete (lpSANPIXMAP2D(pTex->PixMapPtr)); pTex->PixMapPtr = nullptr; } else { delete [](lpSANPIXMAP3D(pTex->PixMapPtr)->pPixMap); lpSANPIXMAP3D(pTex->PixMapPtr)->pPixMap = nullptr; delete (lpSANPIXMAP3D(pTex->PixMapPtr)); pTex->PixMapPtr = nullptr; } //pManager->iDeleteFormDeviceTextureList(pTex); pTex->DataSize=0; return true; } SRESULT cSanResourceManager::_ReleaseMesh(SHANDLE MeshHandle, SHANDLE ResourceManagerPtr, SVALUE Param) { if ((MeshHandle == nullptr) || (ResourceManagerPtr == nullptr)) { return true; } cSanResourceManager* pManager = (cSanResourceManager*) ResourceManagerPtr; lpSANMESH pMesh=(lpSANMESH)MeshHandle; SANOBJECTLIST::iterator pObject=pMesh->value.begin(); while(pObject!=pMesh->value.end()) { //if(pObject->ObjParam!=nullptr) //{ //if (pManager->iDeleteFromDeviceMeshList(&(*pObject))) //{ //return false; //} //} list<stSANUNKNOWNEX<SANTEXRENDERDESC, SHANDLE>>::iterator pTex = pObject->Material.TexList.begin(); while (pTex != pObject->Material.TexList.end()) { if (pTex->description.RenderType == STRT_NORMAL) { #ifdef _DIRECTX//////////////////////////////////////////////////////////////////////////////////////////////////Create Member From Memory LPDIRECT3DTEXTURE9 pDXTex=(LPDIRECT3DTEXTURE9)(pTexElement->Param); if(pDXTex!=nullptr) { pDXTex->Release(); delete pDXTex; } #endif } if (((lpSANRESPTRC) (pTex->value))->iIsReleased()) { delete ((lpSANRESPTRC) (pTex->value)); } else { ((lpSANRESPTRC) (pTex->value))->iRelease(); } pTex++; } pObject->Material.TexList.clear(); if(pObject->pVertexList!=nullptr) { delete[] (pObject->pVertexList); pObject->pVertexList=nullptr; pObject->VertexListSize=0; } pObject++; } pMesh->value.clear(); return true; } bool cSanResourceManager::_ReleaseList(uint32 ListType) { SANRESOURCETABLE::iterator pRes; eSANRESOURCETYPE ResType = this->_GetResourceTypeByArrayIndex(ListType); if (this->m_pResourcesTableArray[ListType].empty()) { return true; } pRes = this->m_pResourcesTableArray[ListType].begin(); lpSANMESH pMesh = nullptr; SANOBJECTLIST::iterator pObj; while (pRes != this->m_pResourcesTableArray[ListType].end()) { this->m_FilePathSearchTableForward.erase(this->m_FilepathSearchTableBackward.find(pRes->first)->second); this->m_FilepathSearchTableBackward.erase(pRes->first); switch (ResType) { case RT_TEXTURE: case RT_TEXTURE_2D: case RT_TEXTURE_3D: this->iDeleteFormDeviceTextureList((lpSANTEXTURE) pRes->second.value); break; case RT_MESH: case RT_MESH_STATIC: case RT_MESH_DYNAMIC: pMesh = (lpSANMESH) pRes->second.value; pObj = pMesh->value.begin(); while (pObj != pMesh->value.end()) { this->iDeleteFromDeviceMeshList(&(*pObj)); } break; case RT_SOUND: break; default: break; } if (!pRes->second.description.AssignedPtr.empty()) { list<lpSANRESPTR>* pAsdList = &(pRes->second.description.AssignedPtr); list<lpSANRESPTR>::iterator pAsdPtr = pAsdList->begin(); while (pAsdPtr != pAsdList->end()) { (*pAsdPtr)->res_ptr = nullptr; if ((*pAsdPtr)->b_released) { delete (*pAsdPtr); (*pAsdPtr) = nullptr; } else { (*pAsdPtr)->b_released = true; } pAsdPtr++; } pRes->second.description.AssignedPtr.clear(); } if (pRes->second.description.pReleaseFunc != nullptr) { pRes->second.description.pReleaseFunc(pRes->second.value, this, NULL); } pRes->second.description.pReleaseFunc = nullptr; pRes->second.description.Size = 0; pRes++; } this->m_pMaxAvailableIDArray[ListType] = this->_GetResourceTypeByArrayIndex(ListType) + 1; this->m_pAvailableIDListArray[ListType].clear(); this->m_pResourcesTableArray[ListType].clear(); } SVALUE cSanResourceManager::_RegisteID(lpSANRESOURCE pRes, const eSANRESOURCETYPE Type) { uint32 Index = this->_GetResourceArrayIndexByType(Type); if (pRes->description.ResID == 0) { if (!this->m_pAvailableIDListArray[Index].empty()) { pRes->description.ResID = *(this->m_pAvailableIDListArray[Index].begin()); this->m_pAvailableIDListArray[Index].erase((this->m_pAvailableIDListArray[Index].begin())); } else { if (this->m_pMaxAvailableIDArray[Index] == 0) { return 0; } pRes->description.ResID = this->m_pMaxAvailableIDArray[Index]; if (this->m_pMaxAvailableIDArray[Index] >= (Type + San::MAXAVAILABLERESID)) { this->m_pMaxAvailableIDArray[Index] = 0; } else { this->m_pMaxAvailableIDArray[Index] = this->m_pMaxAvailableIDArray[Index] + 1; } } } this->m_pResourcesTableArray[Index].insert(::make_pair(pRes->description.ResID, *pRes)); return pRes->description.ResID; } bool cSanResourceManager::_ReleaseID(SVALUE ResID, const eSANRESOURCETYPE Type, const uint32 CreaterID, const uint32 GroupID, SANRES_RELEASEFUNC pReleaseFunc) { uint32 Index = this->_GetResourceArrayIndexByType(Type); SANRESOURCETABLE::iterator pRes = this->m_pResourcesTableArray[Index].find(ResID); if (pRes == this->m_pResourcesTableArray[Index].end()) { return false; } if (pRes->second.description.CreaterID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_DELETE) != SRIO_GLOBAL_DELETE) { return false; } } else { if (pRes->second.description.CreaterID != CreaterID) { if (pRes->second.description.GroupID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_DELETE) != SRIO_GLOBAL_DELETE) { return false; } } else { if (pRes->second.description.GroupID != GroupID) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_DELETE) != SRIO_GLOBAL_DELETE) { return false; } } else { if ((pRes->second.description.AccessFlag&SRIO_GROUP_DELETE) != SRIO_GROUP_DELETE) { return false; } } } } } map < uint32, stSANUNKNOWNEX<SANRESOURCEDESC, SHANDLE>>::iterator pSubRes = this->m_pResourcesTableArray[Index].begin(); while (pSubRes != this->m_pResourcesTableArray[Index].end()) { if (pSubRes->second.description.OrigionResPtr == (&(pRes->second))) { pSubRes->second.description.OrigionResPtr = nullptr; } if (pSubRes->second.description.PreviousResPtr == (&(pRes->second))) { pSubRes->second.description.PreviousResPtr = nullptr; } pSubRes++; } /*Count == 0*/ if (!pRes->second.description.AssignedPtr.empty()) { list<lpSANRESPTR>::iterator pPtr = pRes->second.description.AssignedPtr.begin(); while (pPtr != pRes->second.description.AssignedPtr.end()) { (*pPtr)->res_ptr = nullptr; if ((*pPtr)->b_released) { delete (*pPtr); (*pPtr) = nullptr; } else { (*pPtr)->res_id = 0; (*pPtr)->res_ptr = nullptr; this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), *pPtr); } pPtr++; } pRes->second.description.AssignedPtr.clear(); pRes->second.description.AssignedConstPtr.clear(); } if (!pRes->second.description.AssignedConstPtr.empty()) { list<lpSANRESPTRC>::iterator pPtrC = pRes->second.description.AssignedConstPtr.begin(); while (pPtrC != pRes->second.description.AssignedConstPtr.end()) { (*pPtrC)->res_ptr = nullptr; if ((*pPtrC)->b_released) { delete (*pPtrC); (*pPtrC) = nullptr; } else { (*pPtrC)->res_id = 0; (*pPtrC)->res_ptr = nullptr; this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), *pPtrC); } pPtrC++; } } lpSANMESH pMesh = nullptr; SANOBJECTLIST::iterator pObj; switch (Type) { case RT_TEXTURE: case RT_TEXTURE_2D: case RT_TEXTURE_3D: this->iDeleteFormDeviceTextureList((lpSANTEXTURE) pRes->second.value); break; case RT_MESH: case RT_MESH_STATIC: case RT_MESH_DYNAMIC: pMesh = (lpSANMESH) pRes->second.value; pObj = pMesh->value.begin(); while (pObj != pMesh->value.end()) { this->iDeleteFromDeviceMeshList(&(*pObj)); } break; case RT_SOUND: break; default: break; } if (pReleaseFunc == nullptr) { pReleaseFunc = pRes->second.description.pReleaseFunc; } if (pReleaseFunc != nullptr) { pReleaseFunc(pRes->second.value, this, NULL); } this->m_pResourcesTableArray[Index].erase(pRes); this->m_pAvailableIDListArray[Index].insert(this->m_pAvailableIDListArray[Index].end(),ResID); } eSANRESOURCETYPE cSanResourceManager::_GetResourceTypeByArrayIndex(uint32 Index) { switch (Index) { case 0:return RT_UNKNOWN; break; case 1:return RT_TEXTURE; break; case 2:return RT_TEXTURE_2D; break; case 3:return RT_TEXTURE_3D; break; case 4:return RT_MESH; break; case 5:return RT_MESH_STATIC; break; case 6:return RT_MESH_DYNAMIC; break; case 7:return RT_SOUND; break; case 8:return RT_BUFFER; break; #ifndef _OPENGL case 9: return RT_BINARY; break; case 10:return RT_BINARY_EXEC; break; case 11:return RT_BINARY_DLL; break; case 12:return RT_BINARY_SHADER; break; case 13:return RT_DEVICE; break; case 14:return RT_DEVICE_WINDOW; break; case 15:return RT_TEXT; break; case 16:return RT_TEXT_ASCII; break; case 17:return RT_TEXT_UNICODE; break; case 18:return RT_TEXT_SRCCODE; break; #else case 9:return RT_BUFFER_TBO; break; case 10:return RT_BUFFER_FBO; break; case 11:return RT_BUFFER_VBO; break; case 12:return RT_BUFFER_VAO; break; case 13: return RT_BINARY; break; case 14:return RT_BINARY_EXEC; break; case 15:return RT_BINARY_DLL; break; case 16:return RT_BINARY_SHADER; break; case 17:return RT_DEVICE; break; case 18:return RT_DEVICE_WINDOW; break; case 19:return RT_TEXT; break; case 20:return RT_TEXT_ASCII; break; case 21:return RT_TEXT_UNICODE; break; case 22:return RT_TEXT_SRCCODE; break; #endif default:return RT_UNKNOWN; break; } } uint32 cSanResourceManager::_GetResourceArrayIndexByType(eSANRESOURCETYPE Type) { switch (Type) { case RT_UNKNOWN: return 0; break; case RT_TEXTURE: return 1; break; case RT_TEXTURE_2D: return 2; break; case RT_TEXTURE_3D: return 3; break; case RT_MESH: return 4; break; case RT_MESH_STATIC: return 5; break; case RT_MESH_DYNAMIC: return 6; break; case RT_SOUND: return 7; break; case RT_BUFFER: return 8; break; #ifndef _OPENGL case RT_BINARY: return 9; break; case RT_BINARY_EXEC: return 10; break; case RT_BINARY_DLL: return 11; break; case RT_BINARY_SHADER: return 12; break; case RT_DEVICE: return 13; break; case RT_DEVICE_WINDOW: return 14; break; case RT_TEXT: return 15; break; case RT_TEXT_ASCII: return 16; break; case RT_TEXT_UNICODE: return 17; break; case RT_TEXT_SRCCODE: return 18; break; #else case RT_BUFFER_TBO: return 9; break; case RT_BUFFER_FBO: return 10; break; case RT_BUFFER_VBO: return 11; break; case RT_BUFFER_VAO: return 12; break; case RT_BINARY: return 13; break; case RT_BINARY_EXEC: return 14; break; case RT_BINARY_DLL: return 15; break; case RT_BINARY_SHADER: return 16; break; case RT_DEVICE: return 17; break; case RT_DEVICE_WINDOW: return 18; break; case RT_TEXT: return 19; break; case RT_TEXT_ASCII: return 20; break; case RT_TEXT_UNICODE: return 21; break; case RT_TEXT_SRCCODE: return 22; break; #endif default:RT_UNKNOWN : return 0; break; } } lpSANRESOURCE cSanResourceManager::_GetResourceHandle(SVALUE ResID, const eSANRESOURCETYPE Type) { if (ResID == 0) { return nullptr; } uint32 Index = this->_GetResourceArrayIndexByType(Type); SANRESOURCETABLE::iterator pRes = this->m_pResourcesTableArray[Index].find(ResID); if (pRes == this->m_pResourcesTableArray[Index].end()) { return nullptr; } return &(pRes->second); } bool cSanResourceManager::iRegistResourceCreaterFunc(const SString &strFileName, SANRES_CREATEFUNC pCreateFunc, eSANRESOURCETYPE Type) { SString strFileType = strFileName.substr(strFileName.find(_SSTR(".")), strFileName.length()); if (strFileType.empty()) { return false; } Type = static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK); SANFILEMATCHTABLE::iterator pItem=this->m_FileMatchTable.find(Type); if(pItem==this->m_FileMatchTable.end()) { SANFILEMATCHITEM FileMatchItem; FileMatchItem.ResourceType = Type; FileMatchItem.DefaultCreateFuncPtrMap.clear(); FileMatchItem.pDefaultCopyFunc = nullptr; FileMatchItem.pDefaultReleaseFunc = nullptr; this->m_FileMatchTable.insert(::make_pair(Type,FileMatchItem)); pItem=this->m_FileMatchTable.find(Type); } map<SString, list<SANRES_CREATEFUNC>>::iterator pFunc = pItem->second.DefaultCreateFuncPtrMap.find(strFileType); if (pFunc == pItem->second.DefaultCreateFuncPtrMap.end()) { list <SANRES_CREATEFUNC> FuncList; FuncList.insert(FuncList.end(), pCreateFunc); pItem->second.DefaultCreateFuncPtrMap.insert(make_pair(strFileType, FuncList)); return true; } list<SANRES_CREATEFUNC>::iterator pFuncPtr = pFunc->second.begin(); while (pFuncPtr != pFunc->second.end()) { if ((*pFuncPtr) == pCreateFunc) { return false; } pFuncPtr++; } pFunc->second.insert(pFunc->second.begin(), pCreateFunc); return true; } bool cSanResourceManager::iReleaseResourceCreaterFunc(const SString &strFileName, SANRES_CREATEFUNC pCreateFunc, eSANRESOURCETYPE Type) { SString strFileType = strFileName.substr(strFileName.find(_SSTR(".")), strFileName.length()); if (strFileType.empty()) { return false; } Type = static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK); SANFILEMATCHTABLE::iterator pItem = this->m_FileMatchTable.find(Type); if (pItem == this->m_FileMatchTable.end()) { return false; } map<SString, list<SANRES_CREATEFUNC>>::iterator pFunc = pItem->second.DefaultCreateFuncPtrMap.find(strFileType); if (pFunc == pItem->second.DefaultCreateFuncPtrMap.end()) { return false; } list<SANRES_CREATEFUNC>::iterator pFuncPtr = pFunc->second.begin(); while (pFuncPtr != pFunc->second.end()) { if ((*pFuncPtr) == pCreateFunc) { pFunc->second.erase(pFuncPtr); return true; } pFuncPtr++; } return false; } bool cSanResourceManager::iRegistResourceCopyFunc(SANRES_COPYFUNC pCopyFunc, eSANRESOURCETYPE Type) { Type = static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK); SANFILEMATCHTABLE::iterator pItem = this->m_FileMatchTable.find(Type); if (pItem == this->m_FileMatchTable.end()) { SANFILEMATCHITEM FileMatchItem; FileMatchItem.ResourceType = Type; FileMatchItem.DefaultCreateFuncPtrMap.clear(); FileMatchItem.pDefaultCopyFunc = pCopyFunc; FileMatchItem.pDefaultReleaseFunc = nullptr; this->m_FileMatchTable.insert(::make_pair(Type, FileMatchItem)); return true; } pItem->second.pDefaultCopyFunc = pCopyFunc; return true; } bool cSanResourceManager::iReleaseResourceCopyFunc(SANRES_COPYFUNC pCopyFunc, eSANRESOURCETYPE Type) { Type = static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK); SANFILEMATCHTABLE::iterator pItem = this->m_FileMatchTable.find(Type); if (pItem == this->m_FileMatchTable.end()) { return false; } pItem->second.pDefaultCopyFunc = nullptr; } bool cSanResourceManager::iRegistResourceReleaseFunc(SANRES_RELEASEFUNC pReleaseFunc, eSANRESOURCETYPE Type) { Type = static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK); SANFILEMATCHTABLE::iterator pItem = this->m_FileMatchTable.find(Type); if (pItem == this->m_FileMatchTable.end()) { SANFILEMATCHITEM FileMatchItem; FileMatchItem.ResourceType = Type; FileMatchItem.DefaultCreateFuncPtrMap.clear(); FileMatchItem.pDefaultCopyFunc = nullptr; FileMatchItem.pDefaultReleaseFunc = pReleaseFunc; this->m_FileMatchTable.insert(::make_pair(Type, FileMatchItem)); return true; } pItem->second.pDefaultReleaseFunc = pReleaseFunc; return true; } bool cSanResourceManager::iReleaseResourceReleaseFunc(SANRES_RELEASEFUNC pReleaseFunc, eSANRESOURCETYPE Type) { Type = static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK); SANFILEMATCHTABLE::iterator pItem = this->m_FileMatchTable.find(Type); if (pItem == this->m_FileMatchTable.end()) { return false; } pItem->second.pDefaultReleaseFunc = nullptr; } bool cSanResourceManager::iRegistResourceDefaultPath(const SString &strDefaultPath) { if(strDefaultPath.empty()) { return false; } list<SString>::iterator pSeek=this->m_DefaultPathList.begin(); while(pSeek!=this->m_DefaultPathList.end()) { if((*pSeek)==strDefaultPath) { return false; } pSeek++; } this->m_DefaultPathList.insert(this->m_DefaultPathList.end(),strDefaultPath); return true; } void cSanResourceManager::iReleaseResourceDefaultPath(const SString &strDefaultPath) { if(strDefaultPath.empty()) { return; } list<SString>::iterator pSeek=this->m_DefaultPathList.begin(); while(pSeek!=this->m_DefaultPathList.end()) { if((*pSeek)==strDefaultPath) { this->m_DefaultPathList.erase(pSeek); return; } pSeek++; } } bool cSanResourceManager::iIsIDInUse(const SVALUE ResID) { uint32 Index = this->_GetResourceArrayIndexByType(this->iGetResourceType(ResID)); if(this->m_pMaxAvailableIDArray[Index]!=0) { if (ResID >= this->m_pMaxAvailableIDArray[Index]) { return false; } } else { if(this->m_pAvailableIDListArray[Index].empty()) { return true; } } list<uint32>::iterator pID=this->m_pAvailableIDListArray[Index].begin(); while(pID!=this->m_pAvailableIDListArray[Index].end()) { if ((*pID) == ResID) { return true; } pID++; } return false; } SVALUE cSanResourceManager::iGetAvailableID(eSANRESOURCETYPE ResType) { SVALUE ID = 0; uint32 Index = this->_GetResourceArrayIndexByType(ResType); if(this->m_pAvailableIDListArray[Index].empty()) { ID = this->m_pMaxAvailableIDArray[Index]; if (this->m_pMaxAvailableIDArray[Index] == 0) { return 0; } this->m_pMaxAvailableIDArray[Index] = this->m_pMaxAvailableIDArray[Index] + 1; return ID; } ID=*(this->m_pAvailableIDListArray[Index].begin()); this->m_pAvailableIDListArray[Index].erase(this->m_pAvailableIDListArray[Index].begin()); return ID; } SANRES_CREATEFUNC cSanResourceManager::iGetCreateFunc(const SString &strFileName, eSANRESOURCETYPE Type) { SString strFileType = strFileName.substr(strFileName.find(_SSTR(".")), strFileType.length()); if (strFileType.empty()) { return false; } Type = static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK); SANFILEMATCHTABLE::iterator pItem = this->m_FileMatchTable.find(Type); if (pItem == this->m_FileMatchTable.end()) { return nullptr; } map<SString, list<SANRES_CREATEFUNC>>::iterator pFunc = pItem->second.DefaultCreateFuncPtrMap.find(strFileType); if (pFunc == pItem->second.DefaultCreateFuncPtrMap.end()) { return nullptr; } return *pFunc->second.begin(); } SANRES_COPYFUNC cSanResourceManager::iGetCopyFunc(eSANRESOURCETYPE Type) { SANFILEMATCHTABLE::iterator pItem = this->m_FileMatchTable.find(static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK)); if (pItem == this->m_FileMatchTable.end()) { return false; } return pItem->second.pDefaultCopyFunc; } SANRES_RELEASEFUNC cSanResourceManager::iGetReleaseFunc(eSANRESOURCETYPE Type) { SANFILEMATCHTABLE::iterator pItem = this->m_FileMatchTable.find(static_cast<eSANRESOURCETYPE>(Type&RT_TYPE_MASK)); if (pItem == this->m_FileMatchTable.end()) { return false; } return pItem->second.pDefaultReleaseFunc; } uint32 cSanResourceManager::iGetResourceIDByPath(const SString &strFilePath) { map<SString,uint32>::iterator pItem=this->m_FilePathSearchTableForward.find(strFilePath); if(pItem==this->m_FilePathSearchTableForward.end()) { return 0; } return pItem->second; } SString cSanResourceManager::iGetResourcePathByID(const SVALUE ResID) { map<uint32, SString>::iterator pItem = this->m_FilepathSearchTableBackward.find(ResID); if(pItem==this->m_FilepathSearchTableBackward.end()) { return 0; } return pItem->second; } eSANRESOURCETYPE cSanResourceManager::iGetResourceType(const SVALUE ResID) { if (ResID == 0) { return ::RT_UNKNOWN; } return (eSANRESOURCETYPE) (ResID&::RT_TYPE_MASK); } bool cSanResourceManager::iFindResource(const SVALUE ResID) { if(ResID==0) { return false; } uint32 Index = this->_GetResourceArrayIndexByType(this->iGetResourceType(ResID)); SANRESOURCETABLE::iterator pRes=this->m_pResourcesTableArray[Index].find(ResID); if(pRes!=this->m_pResourcesTableArray[Index].end()) { return true; } return false; } bool cSanResourceManager::iFindTexture(const SVALUE TexID) { return this->iFindResource(TexID); } bool cSanResourceManager::iFindMesh(const SVALUE MeshID) { return this->iFindResource(MeshID); } lpSANRESPTRC cSanResourceManager::iGetResourceConstPtr(const SVALUE ResID, const uint32 RequireID, const uint32 RequireGroupID) { eSANRESOURCETYPE ResType = this->iGetResourceType(ResID); lpSANRESPTRC pPtr = new SANRESPTRC; if (ResID == 0) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pPtr); return pPtr; } uint32 Index = this->_GetResourceArrayIndexByType(ResType); SANRESOURCETABLE::iterator pRes = this->m_pResourcesTableArray[Index].find(ResID); if (pRes != this->m_pResourcesTableArray[Index].end()) { if ((pRes->second.description.AccessFlag&SRIO_MANAGER_REFERENCE) == SRIO_MANAGER_REFERENCE) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pPtr); return pPtr; } if (pRes->second.description.CreaterID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_READ) != SRIO_GLOBAL_READ) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pPtr); return pPtr; } } else { if (pRes->second.description.CreaterID != RequireID) { if (pRes->second.description.GroupID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_READ) != SRIO_GLOBAL_READ) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pPtr); return pPtr; } } else { if (pRes->second.description.GroupID != RequireID) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_READ) != SRIO_GLOBAL_READ) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pPtr); return pPtr; } } else { if ((pRes->second.description.AccessFlag&SRIO_GROUP_READ) != SRIO_GROUP_READ) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pPtr); return pPtr; } } } } else { if ((pRes->second.description.AccessFlag&SRIO_CREATER_READ) != SRIO_CREATER_READ) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pPtr); return pPtr; } } } pPtr->res_id = ResID; pPtr->type = ResType; pPtr->res_ptr = pRes->second.value; pRes->second.description.AssignedConstPtr.insert(pRes->second.description.AssignedConstPtr.end(), pPtr); return pPtr; } this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pPtr); return pPtr; } lpSANRESPTRC cSanResourceManager::iGetTextureConstPtr(const SVALUE TexID, const uint32 RequireID, const uint32 RequireGroupID) { return this->iGetResourceConstPtr(TexID, RequireID, RequireGroupID); } lpSANRESPTRC cSanResourceManager::iGetMeshConstPtr(const SVALUE MeshID, const uint32 RequireID, const uint32 RequireGroupID) { return this->iGetResourceConstPtr(MeshID, RequireID, RequireGroupID); } lpSANRESPTRC cSanResourceManager::iCopyResourceConstPtr(const lpSANRESPTRC Ptr, const uint32 RequireID, const uint32 RequireGroupID) { eSANRESOURCETYPE ResType = this->iGetResourceType(Ptr->res_id); lpSANRESPTRC pDestPtr = new SANRESPTRC; if (Ptr == nullptr) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pDestPtr); return pDestPtr; } if (Ptr->b_released) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pDestPtr); return pDestPtr; } uint32 Index = this->_GetResourceArrayIndexByType(ResType); SANRESOURCETABLE::iterator pRes = this->m_pResourcesTableArray[Index].find(Ptr->res_id); if (pRes != this->m_pResourcesTableArray[Index].end()) { if (pRes->second.description.CreaterID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pDestPtr); return pDestPtr; } } else { if (pRes->second.description.CreaterID != RequireID) { if (pRes->second.description.GroupID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pDestPtr); return pDestPtr; } } else { if (pRes->second.description.GroupID != RequireID) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pDestPtr); return pDestPtr; } } else { if ((pRes->second.description.AccessFlag&SRIO_GROUP_COPY) != SRIO_GROUP_COPY) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pDestPtr); return pDestPtr; } } } } else { if ((pRes->second.description.AccessFlag&SRIO_CREATER_COPY) != SRIO_CREATER_COPY) { this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pDestPtr); return pDestPtr; } } } pDestPtr->res_id = Ptr->res_id; pDestPtr->type = Ptr->type; pDestPtr->res_ptr = pRes->second.value; pRes->second.description.ReferenceCount = pRes->second.description.ReferenceCount < 0 ? 1 : (pRes->second.description.ReferenceCount + 1); pRes->second.description.AssignedConstPtr.insert(pRes->second.description.AssignedConstPtr.end(), pDestPtr); return pDestPtr; } this->m_AssignedVoidConstPtrList.insert(this->m_AssignedVoidConstPtrList.end(), pDestPtr); return pDestPtr; } lpSANRESPTRC cSanResourceManager::iCopyTextureConstPtr(const lpSANRESPTRC Ptr, const uint32 RequireID, const uint32 RequireGroupID) { return this->iCopyResourceConstPtr(Ptr, RequireID, RequireGroupID); } lpSANRESPTRC cSanResourceManager::iCopyMeshConstPtr(const lpSANRESPTRC Ptr, const uint32 RequireID, const uint32 RequireGroupID) { return this->iCopyResourceConstPtr(Ptr, RequireID, RequireGroupID); } lpSANRESPTR cSanResourceManager::iGetResourcePtr(const uint32 ResID, const uint32 RequireID, const uint32 RequireGroupID) { eSANRESOURCETYPE ResType = this->iGetResourceType(ResID); lpSANRESPTR pPtr = new SANRESPTR; if (ResID == 0) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } uint32 Index = this->_GetResourceArrayIndexByType(ResType); SANRESOURCETABLE::iterator pRes=this->m_pResourcesTableArray[Index].find(ResID); if(pRes!=this->m_pResourcesTableArray[Index].end()) { if ((pRes->second.description.AccessFlag&SRIO_MANAGER_REFERENCE) == SRIO_MANAGER_REFERENCE) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } if ((pRes->second.description.AccessFlag&SRIO_MANAGER_CONST) == SRIO_MANAGER_CONST) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } if (pRes->second.description.CreaterID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_READ) != SRIO_GLOBAL_READ) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } } else { if (pRes->second.description.CreaterID != RequireID) { if (pRes->second.description.GroupID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_READ) != SRIO_GLOBAL_READ) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } } else { if (pRes->second.description.GroupID != RequireID) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_READ) != SRIO_GLOBAL_READ) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } } else { if ((pRes->second.description.AccessFlag&SRIO_GROUP_READ) != SRIO_GROUP_READ) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } } } } else { if ((pRes->second.description.AccessFlag&SRIO_CREATER_READ) != SRIO_CREATER_READ) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } } } pPtr->res_id = ResID; pPtr->type = ResType; pPtr->res_ptr = pRes->second.value; pRes->second.description.ReferenceCount = pRes->second.description.ReferenceCount < 0 ? 1 : (pRes->second.description.ReferenceCount + 1); pRes->second.description.AssignedPtr.insert(pRes->second.description.AssignedPtr.end(), pPtr); return pPtr; } this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pPtr); return pPtr; } lpSANRESPTR cSanResourceManager::iGetTexturePtr(const uint32 TexID, const uint32 RequireID, const uint32 RequireGroupID) { return this->iGetResourcePtr(TexID, RequireID, RequireGroupID); } lpSANRESPTR cSanResourceManager::iGetMeshPtr(const uint32 MeshID, const uint32 RequireID, const uint32 RequireGroupID) { return this->iGetResourcePtr(MeshID, RequireID, RequireGroupID); } lpSANRESPTR cSanResourceManager::iCopyResourcePtr(const lpSANRESPTR Ptr, const uint32 RequireID, const uint32 RequireGroupID) { eSANRESOURCETYPE ResType = this->iGetResourceType(Ptr->res_id); lpSANRESPTR pDestPtr = new SANRESPTR; if (Ptr == nullptr) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } if (Ptr->b_released) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } uint32 Index = this->_GetResourceArrayIndexByType(ResType); SANRESOURCETABLE::iterator pRes = this->m_pResourcesTableArray[Index].find(Ptr->res_id); if (pRes != this->m_pResourcesTableArray[Index].end()) { if ((pRes->second.description.AccessFlag&SRIO_MANAGER_CONST) == SRIO_MANAGER_CONST) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } if (pRes->second.description.CreaterID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } } else { if (pRes->second.description.CreaterID != RequireID) { if (pRes->second.description.GroupID == 0) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } } else { if (pRes->second.description.GroupID != RequireID) { if ((pRes->second.description.AccessFlag&SRIO_GLOBAL_COPY) != SRIO_GLOBAL_COPY) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } } else { if ((pRes->second.description.AccessFlag&SRIO_GROUP_COPY) != SRIO_GROUP_COPY) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } } } } else { if ((pRes->second.description.AccessFlag&SRIO_CREATER_COPY) != SRIO_CREATER_COPY) { this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } } } pDestPtr->res_id = Ptr->res_id; pDestPtr->type = Ptr->type; pDestPtr->res_ptr = pRes->second.value; pRes->second.description.ReferenceCount = pRes->second.description.ReferenceCount < 0 ? 1 : (pRes->second.description.ReferenceCount + 1); pRes->second.description.AssignedPtr.insert(pRes->second.description.AssignedPtr.end(), pDestPtr); return pDestPtr; } this->m_AssignedVoidPtrList.insert(this->m_AssignedVoidPtrList.end(), pDestPtr); return pDestPtr; } lpSANRESPTR cSanResourceManager::iCopyTexturePtr(const lpSANRESPTR Ptr, const uint32 RequireID, const uint32 RequireGroupID) { return this->iCopyResourcePtr(Ptr, RequireID, RequireGroupID); } lpSANRESPTR cSanResourceManager::iCopyMeshPtr(const lpSANRESPTR Ptr, const uint32 RequireID, const uint32 RequireGroupID) { return this->iCopyResourcePtr(Ptr, RequireID, RequireGroupID); } bool cSanResourceManager::iRegistGraphicsDeviceResourceManagerHandle(SHANDLE Handle) { this->m_GraphicsDeviceResourceManagerHandle=Handle; return true; } SHANDLE cSanResourceManager::iGetDeviceResourceManagerHandle() { return this->m_GraphicsDeviceResourceManagerHandle; } SHANDLE cSanResourceManager::iAddToDeviceTextureList(lpSANTEXTURE pTexture) { #ifdef _DIRECTX cVectorManager *pManager=new cVectorManager(); LPDIRECT3DDEVICE9 pDXDevice=(LPDIRECT3DDEVICE9)(pManager->iFound(_SSTR("Sys_DXDevice"))); if(pDXDevice==nullptr) { delete pManager; return nullptr; } delete pManager; LPDIRECT3DTEXTURE9 pDXTexture; D3DFORMAT TextureFormat; if(pTexture->PixFormat==PT_RGB) { TextureFormat=D3DFMT_R8G8B8; } else { TextureFormat=D3DFMT_A8R8G8B8; } if(::D3DXCreateTextureFromFileW(pDXDevice,pTexture->strFile.c_str(),&pDXTexture)==D3D_OK) { if(pDXTexture!=nullptr) { return (uint32)pDXTexture; } } return nullptr; #endif #ifdef _OPENGL cSanGLBufferManager* pBufferManager=(cSanGLBufferManager*)this->m_GraphicsDeviceResourceManagerHandle; if(pBufferManager==nullptr) { return nullptr; } SANTBODESC TboDesc; if(pTexture->ParamList!=nullptr) { if(pTexture->DataSize==1) { pBufferManager->iReleaseTBOObject(pTexture->ParamList[0]); delete pTexture->ParamList; } else { for(uint32 seek=0;seek<pTexture->ParamListSize;seek=seek+1) { pBufferManager->iReleaseTBOObject(pTexture->ParamList[seek]); } delete[] pTexture->ParamList; } pTexture->CurrentParam=0; pTexture->ParamList=nullptr; pTexture->ParamListSize=0; } uint32 FrameSize=0; switch(pTexture->Type) { case STT_TEX1D: break; case STT_TEX2D: pTexture->ParamList=new SVALUE; pTexture->ParamListSize=1; switch(pTexture->PixFormat) { case PT_RGB: TboDesc.Type=SGTT_RGBA_8;////////////////////////////////////// break; case PT_RGBA: TboDesc.Type=SGTT_RGBA_8; break; case PT_RGB_F: TboDesc.Type=SGTT_RGB_F; break; case PT_RGBA_F: TboDesc.Type=SGTT_RGBA_F; break; default: TboDesc.Type=SGTT_RGB_8; break; } TboDesc.Width=lpSANPIXMAP2D(pTexture->PixMapPtr)->width; TboDesc.Height = lpSANPIXMAP2D(pTexture->PixMapPtr)->height; TboDesc.BufferSize = pTexture->DataSize; TboDesc.pBuffer = (SHANDLE) lpSANPIXMAP2D(pTexture->PixMapPtr)->pPixMap; pTexture->ParamList[0] = pBufferManager->iCreateTBOObject(TboDesc); if(pTexture->ParamList[0]!=0) { pTexture->CurrentParam = pTexture->ParamList[0]; return (SHANDLE) (pTexture->ParamList[0]); } return false; break; case STT_TEX3D: pTexture->ParamListSize = lpSANPIXMAP3D(pTexture->PixMapPtr)->depth; pTexture->ParamList = new SVALUE[pTexture->DataSize]; FrameSize = pTexture->DataSize / pTexture->ParamListSize; switch(pTexture->PixFormat) { case PT_RGB: TboDesc.Type=SGTT_RGBA_8;////////////////////////////////////// break; case PT_RGBA: TboDesc.Type=SGTT_RGBA_8; break; case PT_RGB_F: TboDesc.Type=SGTT_RGB_F; break; case PT_RGBA_F: TboDesc.Type=SGTT_RGBA_F; break; default: TboDesc.Type=SGTT_RGB_8; break; } TboDesc.Width = lpSANPIXMAP2D(pTexture->PixMapPtr)->width; TboDesc.Height = lpSANPIXMAP2D(pTexture->PixMapPtr)->height; TboDesc.BufferSize = pTexture->DataSize; for(uint32 seek=0;seek<pTexture->DataSize;seek=seek+1) { TboDesc.pBuffer = (SHANDLE) ((uint32) lpSANPIXMAP2D(pTexture->PixMapPtr)->pPixMap + FrameSize*seek); pTexture->ParamList[seek] = pBufferManager->iCreateTBOObject(&(*pTexture)); if(pTexture->ParamList[seek]==0) { return nullptr; } } pTexture->CurrentParam=pTexture->ParamList[0]; return (SHANDLE)(pTexture->ParamList[0]); break; default: return nullptr; break; } return nullptr; #endif } SHANDLE cSanResourceManager::iAddToDeviceMeshList(lpSANOBJECT pObject) { #ifdef _DIRECTX cVectorManager *pManager=new cVectorManager(); LPDIRECT3DDEVICE9 pDXDevice=(LPDIRECT3DDEVICE9)(pManager->iFound(_SSTR("Sys_DXDevice"))); if(pDXDevice==nullptr) { delete pManager; return 0; } delete pManager; //uint32 VertexListSize=Object.VertexList.size()*8; //sfloat *pVertexList=new sfloat[VertexListSize]; uint32 ElementSize=6; uint32 TextureType=D3DFVF_TEX0; TextureType=TextureType+Object.Material.TextureList.size()*D3DFVF_TEX1; ElementSize=ElementSize+Object.Material.TextureList.size()*2; uint32 VertexListSize=Object.VertexListSize*ElementSize; sfloat *pVertexList=new sfloat[VertexListSize]; ::gloMemSet(pVertexList,0,sizeof(pVertexList)); uint32 Seek=0; //stVERTEXLIST::iterator pVertex=Object.VertexList.begin(); stVERTEXELEMENT *pVertex=Object.pVertexList; while(Seek<VertexListSize/*pVertex!=Object.VertexList.end()*/) { pVertexList[Seek]=pVertex->v.x; pVertexList[Seek+1]=pVertex->v.y; pVertexList[Seek+2]=pVertex->v.z; Seek=Seek+3; pVertexList[Seek]=-pVertex->vn.x; pVertexList[Seek+1]=pVertex->vn.y; pVertexList[Seek+2]=-pVertex->vn.z; Seek=Seek+3; for(int seek=0;seek<Object.Material.TextureList.size();seek=seek+1) { pVertexList[Seek]=pVertex->vt.x; pVertexList[Seek+1]=-pVertex->vt.y; Seek=Seek+2; } pVertex++; } LPDIRECT3DVERTEXBUFFER9 pDXVertexList; if(pDXDevice->CreateVertexBuffer(sizeof(sfloat)*VertexListSize,0,D3DFVF_XYZ|D3DFVF_NORMAL|TextureType/*D3DFVF_TEX1*/,D3DPOOL_DEFAULT,&pDXVertexList,nullptr)==D3D_OK) { if(pDXVertexList!=nullptr) { unsigned char *pDXVertexPtr; if(FAILED(pDXVertexList->Lock(0,sizeof(sfloat)*VertexListSize,(void**)(&pDXVertexPtr),0))) { delete[] pVertexList; pVertexList=nullptr; pDXVertexList->Release(); return 0; } ::gloMemCopy(pDXVertexPtr,pVertexList,sizeof(sfloat)*VertexListSize); pDXVertexList->Unlock(); delete[] pVertexList; pVertexList=nullptr; return (uint32)pDXVertexList; } else { pDXVertexList->Release(); delete[] pVertexList; pVertexList=nullptr; return 0; } } delete[] pVertexList; return 0; #else cSanGLBufferManager* pBufferManager=(cSanGLBufferManager*)this->m_GraphicsDeviceResourceManagerHandle; if(pBufferManager==nullptr) { return 0; } switch(pObject->ObjStructVersion) { case ::SOSV_TRADITIONAL: return (SHANDLE)pBufferManager->iCreateVAOObject(pObject,SVBS_STATIC); break; case ::SOSV_INDEXVERTEX: return nullptr; break; case ::SOSV_FRAMEANIMATION: return (SHANDLE)pBufferManager->iCreateVAOObject(pObject,SVBS_STATIC); break; case ::SOSV_SKELETONANIMATION: return (SHANDLE)pBufferManager->iCreateVAOObject(pObject,SVBS_DYNAMIC); return nullptr; break; default: return nullptr; break; } #endif } bool cSanResourceManager::iDeleteFormDeviceTextureList(lpSANTEXTURE pTexture) { #ifdef _DIRECTX if(Param==0) { return false; } LPDIRECT3DTEXTURE9 pDXTexture=(LPDIRECT3DTEXTURE9)Param; pDXTexture->Release(); pDXTexture=nullptr; return true; #endif #ifdef _OPENGL cSanGLBufferManager* pBufferManager=(cSanGLBufferManager*)this->m_GraphicsDeviceResourceManagerHandle; if(pBufferManager==nullptr) { return false; } if(pTexture->ParamList!=nullptr) { if(pTexture->DataSize==1) { pBufferManager->iReleaseTBOObject(pTexture->ParamList[0]); delete pTexture->ParamList; } else { for(uint32 seek=0;seek<pTexture->ParamListSize;seek=seek+1) { pBufferManager->iReleaseTBOObject(pTexture->ParamList[seek]); } delete[] pTexture->ParamList; } pTexture->CurrentParam=0; pTexture->ParamList=nullptr; pTexture->ParamListSize=0; } return true; #endif } bool cSanResourceManager::iDeleteFromDeviceMeshList(lpSANOBJECT pObject) { #ifdef _DIRECTX if(Param==0) { return false; } LPDIRECT3DVERTEXBUFFER9 pDXVertexList=(LPDIRECT3DVERTEXBUFFER9)Param; pDXVertexList->Release(); pDXVertexList=nullptr; return true; #else if(pObject->ObjParam!=nullptr) { cSanGLBufferManager* pBufferManager=(cSanGLBufferManager*)this->m_GraphicsDeviceResourceManagerHandle; if(pBufferManager==nullptr) { return false; } pBufferManager->iReleaseVAOObject((uint32)(pObject->ObjParam)); pObject->ObjParam=nullptr; } return true; #endif } SVALUE San::gloRegisteResource(SHANDLE ResHandle, const uint32 ResSize, const eSANRESOURCETYPE ResType, SVALUE CreaterID, SVALUE GroupID, uint32 Flag, SANRES_COPYFUNC pCopyFunc, SANRES_RELEASEFUNC pReleaseFunc) { cSanResourceManager *pResManager = (cSanResourceManager*) San::gloFoundVector(_SSTR("Sys_SanResourceManager")); if (pResManager == nullptr) { return 0; } pResManager->iRegisteResource(ResHandle, ResSize, ResType, CreaterID, GroupID, Flag, pCopyFunc, pReleaseFunc); } SRESULT San::gloReleaseResource(SVALUE ResID, const SVALUE ID, SANRES_RELEASEFUNC pReleaseFunc) { cSanResourceManager *pResManager = (cSanResourceManager*) San::gloFoundVector(_SSTR("Sys_SanResourceManager")); if (pResManager == nullptr) { return 0; } pResManager->iReleaseResource(ResID, ID, pReleaseFunc); } eSANRESOURCETYPE San::gloGetResourceType(const SVALUE ResID) { cSanResourceManager *pResManager = (cSanResourceManager*) San::gloFoundVector(_SSTR("Sys_SanResourceManager")); if (pResManager == nullptr) { return RT_UNKNOWN; } return pResManager->iGetResourceType(ResID); }
31.712409
264
0.738436
[ "object" ]
1d97bf70c501c74e4b74a182ee132beea1422bd9
29,587
cpp
C++
Tests/Tests/VectorTests.cpp
barneydellar/SpaceTypes
da0741563de3416792e1927b9c4c84be10959aed
[ "RSA-MD" ]
7
2019-06-23T02:38:02.000Z
2021-09-08T09:19:32.000Z
Tests/Tests/VectorTests.cpp
barneydellar/SpaceTypes
da0741563de3416792e1927b9c4c84be10959aed
[ "RSA-MD" ]
12
2020-02-29T07:50:34.000Z
2021-04-01T09:29:45.000Z
Tests/Tests/VectorTests.cpp
barneydellar/SpaceTypes
da0741563de3416792e1927b9c4c84be10959aed
[ "RSA-MD" ]
null
null
null
#include "pch.h" #include "SpaceHelpers.h" using namespace Space; TEST_CASE("Vectors can be constructed") { View::Vector v; } TEST_CASE("Vectors have zero value by default") { View::Vector v; CHECK(v[0] == 0); CHECK(v[1] == 0); CHECK(v[2] == 0); } TEST_CASE("Vectors can be constructed from implementation") { TestVector impl; impl.m_values[0] = 3; impl.m_values[1] = 2; impl.m_values[2] = 1; const Data::Vector v(impl); CHECK(v.X() == 3); CHECK(v.Y() == 2); CHECK(v.Z() == 1); } TEST_CASE("Vectors Can Be Constructed From Three Doubles") { const Data::Vector v(4, 5, 6); CHECK(v.X() == 4); CHECK(v.Y() == 5); CHECK(v.Z() == 6); } TEST_CASE("Vectors can be created using initalizer lists of three numbers") { View::Vector v{ 1, 2, 4 }; CHECK(v[0] == 1); CHECK(v[1] == 2); CHECK(v[2] == 4); } TEST_CASE("Vectors can be assigned from a vector") { const View::Vector v2(1, 2, 3); const View::Vector v = v2; CHECK(v.X() == 1); CHECK(v.Y() == 2); CHECK(v.Z() == 3); } TEST_CASE("Vectors can be explicitly cast to the implementation") { const Data::Vector v(1, 2, 3); auto impl = static_cast<TestVector>(v); CHECK(impl.m_values[0] == 1); CHECK(impl.m_values[1] == 2); CHECK(impl.m_values[2] == 3); } TEST_CASE("Vectors support element access by name") { const Image::Vector v(2, 3, 4); CHECK(v.X() == 2); CHECK(v.Y() == 3); CHECK(v.Z() == 4); } TEST_CASE("Vector elements can be modified by name") { Image::Vector v(2, 3, 4); v.SetX(10); v.SetY(20); v.SetZ(30); CHECK(v.X() == 10); CHECK(v.Y() == 20); CHECK(v.Z() == 30); } TEST_CASE("Vectors support const begin and end") { const Image::Vector v(2, 3, 4); std::vector<double> values; std::copy(v.cbegin(), v.cend(), std::back_inserter(values)); CHECK(values.size() == 3); CHECK(values[0] == 2); CHECK(values[1] == 3); CHECK(values[2] == 4); } TEST_CASE("Vectors support non-const begin and end") { Image::Vector v(2, 3, 4); std::fill(v.begin(), v.end(), 3); CHECK(v.X() == 3); CHECK(v.Y() == 3); CHECK(v.Z() == 3); } TEST_CASE("Vectors support element access by random access") { const Image::Vector v(2, 3, 4); CHECK(v[0] == 2); CHECK(v[1] == 3); CHECK(v[2] == 4); } TEST_CASE("Vectors throw if random access is too high") { const Image::Vector v; CHECK_THROWS_AS(v[3], std::invalid_argument); } TEST_CASE("Vectors throw with the right message if random access is too high") { const Image::Vector v; CHECK_THROWS_WITH(v[3], "Index is out of range"); } TEST_CASE("Vectors support element access by at") { const Image::Vector v(2, 3, 4); CHECK(v.at<0>() == 2); CHECK(v.at<1>() == 3); CHECK(v.at<2>() == 4); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors at does not compile if too low") { const Image::Vector v; using converted_type = decltype(v.at<-1>()); using required_type = StaticAssert::invalid_at_access; CHECK(static_cast<bool>(std::is_same_v<converted_type, required_type>)); } TEST_CASE("Vectors at does not compile if too high") { const Image::Vector v; using converted_type = decltype(v.at<3>()); using required_type = StaticAssert::invalid_at_access; CHECK(static_cast<bool>(std::is_same_v<converted_type, required_type>)); } #endif TEST_CASE("Vector and Vector can be compared using equal: same") { const View::Vector v(1, 0, 0); const View::Vector v2(1, 0, 0); CHECK(v == v2); } TEST_CASE("Vector and NormalizedVector can be compared using equal: same") { const View::Vector v(1, 0, 0); const View::NormalizedVector v2(1, 0, 0); CHECK(v == v2); } TEST_CASE("Vector and NormalizedXYVector can be compared using equal: same") { const View::Vector v(1, 0, 0); const View::NormalizedXYVector v2(1, 0); CHECK(v == v2); } TEST_CASE("Vector and XYVector can be compared using equal: same") { const View::Vector v(1, 0, 0); const View::XYVector v2(1, 0); CHECK(v == v2); } TEST_CASE("Vector and Vector can be compared using equal: different") { const View::Vector v(1, 0, 1); const View::Vector v2(1, 0, 0); CHECK(!(v == v2)); } TEST_CASE("Vector and NormalizedVector can be compared using equal: different") { const View::Vector v(1, 0, 1); const View::NormalizedVector v2(1, 0, 0); CHECK(!(v == v2)); } TEST_CASE("Vector and NormalizedXYVector can be compared using equal: different") { const View::Vector v(1, 0, 1); const View::NormalizedXYVector v2(1, 0); CHECK(!(v == v2)); } TEST_CASE("Vector and XYVector can be compared using equal: different") { const View::Vector v(1, 0, 1); const View::XYVector v2(1, 0); CHECK(!(v == v2)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors from different spaces cannot be compared using equal") { const View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v == v_v); using converted_type_2 = decltype(v == v_n); using converted_type_3 = decltype(v == v_n_xy); using converted_type_4 = decltype(v == v_xy); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors and Points cannot be compared using equal") { const View::Vector v; const View::Point p; const View::Point p_xy; using converted_type_1 = decltype(v == p); using converted_type_2 = decltype(v == p_xy); using required_type = StaticAssert::invalid_point_vector_equality; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); } #endif TEST_CASE("Vector and Vector can be compared using inequality: same") { const View::Vector v(1, 0, 0); const View::Vector v2(1, 0, 0); CHECK(!(v != v2)); } TEST_CASE("Vector and NormalizedVector can be compared using inequality: same") { const View::Vector v(1, 0, 0); const View::NormalizedVector v2(1, 0, 0); CHECK(!(v != v2)); } TEST_CASE("Vector and NormalizedXYVector can be compared using inequality: same") { const View::Vector v(1, 0, 0); const View::NormalizedXYVector v2(1, 0); CHECK(!(v != v2)); } TEST_CASE("Vector and XYVector can be compared using inequality: same") { const View::Vector v(1, 0, 0); const View::XYVector v2(1, 0); CHECK(!(v != v2)); } TEST_CASE("Vector and Vector can be compared using inequality: different") { const View::Vector v(1, 0, 1); const View::Vector v2(1, 0, 0); CHECK(v != v2); } TEST_CASE("Vector and NormalizedVector can be compared using inequality: different") { const View::Vector v(1, 0, 1); const View::NormalizedVector v2(1, 0, 0); CHECK(v != v2); } TEST_CASE("Vector and NormalizedXYVector can be compared using inequality: different") { const View::Vector v(1, 0, 1); const View::NormalizedXYVector v2(1, 0); CHECK(v != v2); } TEST_CASE("Vector and XYVector can be compared using inequality: different") { const View::Vector v(1, 0, 1); const View::XYVector v2(1, 0); CHECK(v != v2); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors from different spaces cannot be compared using inequality") { const View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v != v_v); using converted_type_2 = decltype(v != v_n); using converted_type_3 = decltype(v != v_n_xy); using converted_type_4 = decltype(v != v_xy); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors and Points cannot be compared using inequality") { const View::Vector v; const View::Point p; const View::Point p_xy; using converted_type_1 = decltype(v != p); using converted_type_2 = decltype(v != p_xy); using required_type = StaticAssert::invalid_point_vector_equality; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); } #endif TEST_CASE("Vectors can have Vectors subtracted in place") { Image::Vector v(1, 2, 3); const Image::Vector v2(1, 0, 0); v -= v2; CHECK(v == Image::Vector(0, 2, 3)); } TEST_CASE("Vectors can have NormalizedVectors subtracted in place") { Image::Vector v(1, 2, 3); const Image::NormalizedVector v2(1, 0, 0); v -= v2; CHECK(v == Image::Vector(0, 2, 3)); } TEST_CASE("Vectors can have NormalizedXYVectors subtracted in place") { Image::Vector v(1, 2, 3); const Image::NormalizedXYVector v2(1, 0); v -= v2; CHECK(v == Image::Vector(0, 2, 3)); } TEST_CASE("Vectors can have XYVectors subtracted in place") { Image::Vector v(1, 2, 3); const Image::NormalizedXYVector v2(1, 0); v -= v2; CHECK(v == Image::Vector(0, 2, 3)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors in different spaces cannot be subtracted in place") { View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v -= v_v); using converted_type_2 = decltype(v -= v_n); using converted_type_3 = decltype(v -= v_n_xy); using converted_type_4 = decltype(v -= v_xy); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif TEST_CASE("Vectors can have Vectors subtracted") { const Image::Vector v(1, 2, 3); const Image::Vector v2(1, 0, 0); auto v3 = v - v2; CHECK(v3 == Image::Vector(0, 2, 3)); } TEST_CASE("Vectors can have NormalizedVector subtracted") { const Image::Vector v(1, 2, 3); const Image::NormalizedVector v2(1, 0, 0); auto v3 = v - v2; CHECK(v3 == Image::Vector(0, 2, 3)); } TEST_CASE("Vectors can have NormalizedXYVector subtracted") { const Image::Vector v(1, 2, 3); const Image::NormalizedXYVector v2(1, 0); auto v3 = v - v2; CHECK(v3 == Image::Vector(0, 2, 3)); } TEST_CASE("Vectors can have XYVector subtracted") { const Image::Vector v(1, 2, 3); const Image::XYVector v2(1, 0); auto v3 = v - v2; CHECK(v3 == Image::Vector(0, 2, 3)); } TEST_CASE("Vectors can have other vectors subtracted to produce another Vector") { View::Vector v; const View::Vector v_v; const View::NormalizedVector v_n; const View::NormalizedXYVector v_n_xy; const View::XYVector v_xy; using converted_type_1 = decltype(v - v_v); using converted_type_2 = decltype(v - v_n); using converted_type_3 = decltype(v - v_n_xy); using converted_type_4 = decltype(v - v_xy); using required_type = View::Vector; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors in different spaces cannot be subtracted") { View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v - v_v); using converted_type_2 = decltype(v - v_n); using converted_type_3 = decltype(v - v_n_xy); using converted_type_4 = decltype(v - v_xy); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors cannot have points subtracted") { const View::Vector v; const View::Point p; const View::Point p_xy; using converted_type_1 = decltype(v - p); using converted_type_2 = decltype(v - p_xy); using required_type = StaticAssert::invalid_point_from_vector_subtraction; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); } #endif TEST_CASE("Vectors can have Vectors added in place") { Image::Vector v(1, 2, 3); const Image::Vector v2(1, 0, 0); v += v2; CHECK(v == Image::Vector(2, 2, 3)); } TEST_CASE("Vectors can have NormalizedVectors added in place") { Image::Vector v(1, 2, 3); const Image::NormalizedVector v2(1, 0, 0); v += v2; CHECK(v == Image::Vector(2, 2, 3)); } TEST_CASE("Vectors can have NormalizedXYVectors added in place") { Image::Vector v(1, 2, 3); const Image::NormalizedXYVector v2(1, 0); v += v2; CHECK(v == Image::Vector(2, 2, 3)); } TEST_CASE("Vectors can have XYVectors added in place") { Image::Vector v(1, 2, 3); const Image::NormalizedXYVector v2(1, 0); v += v2; CHECK(v == Image::Vector(2, 2, 3)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors in different spaces cannot be added in place") { View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v += v_v); using converted_type_2 = decltype(v += v_n); using converted_type_3 = decltype(v += v_n_xy); using converted_type_4 = decltype(v += v_xy); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif TEST_CASE("Vectors can have Vectors added") { const Image::Vector v(1, 2, 3); const Image::Vector v2(1, 0, 0); auto v3 = v + v2; CHECK(v3 == Image::Vector(2, 2, 3)); } TEST_CASE("Vectors can have NormalizedVector added") { const Image::Vector v(1, 2, 3); const Image::NormalizedVector v2(1, 0, 0); auto v3 = v + v2; CHECK(v3 == Image::Vector(2, 2, 3)); } TEST_CASE("Vectors can have NormalizedXYVector added") { const Image::Vector v(1, 2, 3); const Image::NormalizedXYVector v2(1, 0); auto v3 = v + v2; CHECK(v3 == Image::Vector(2, 2, 3)); } TEST_CASE("Vectors can have XYVector added") { const Image::Vector v(1, 2, 3); const Image::XYVector v2(1, 0); auto v3 = v + v2; CHECK(v3 == Image::Vector(2, 2, 3)); } TEST_CASE("Vectors can have other vectors added to produce another Vector") { View::Vector v; const View::Vector v_v; const View::NormalizedVector v_n; const View::NormalizedXYVector v_n_xy; const View::XYVector v_xy; using converted_type_1 = decltype(v + v_v); using converted_type_2 = decltype(v + v_n); using converted_type_3 = decltype(v + v_n_xy); using converted_type_4 = decltype(v + v_xy); using required_type = View::Vector; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors in different spaces cannot be added") { View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v + v_v); using converted_type_2 = decltype(v + v_n); using converted_type_3 = decltype(v + v_n_xy); using converted_type_4 = decltype(v + v_xy); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors cannot have points added") { const View::Vector v; const View::Point p; const View::Point p_xy; using converted_type_1 = decltype(v + p); using converted_type_2 = decltype(v + p_xy); using required_type = StaticAssert::invalid_point_to_vector_addition; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); } #endif TEST_CASE("Vectors can be scaled") { View::Vector v(1, 2, 3); v *= 2; CHECK(v == View::Vector(2, 4, 6)); } TEST_CASE("Vectors can have Vectors crossed in place") { Image::Vector v(0, 1, 0); const Image::Vector v2(1, 0, 0); v *= v2; CHECK(v == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have NormalizedVectors crossed in place") { Image::Vector v(0, 1, 0); const Image::NormalizedVector v2(1, 0, 0); v *= v2; CHECK(v == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have NormalizedXYVectors crossed in place") { Image::Vector v(0, 1, 0); const Image::NormalizedXYVector v2(1, 0); v *= v2; CHECK(v == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have XYVectors crossed in place") { Image::Vector v(0, 1, 0); const Image::NormalizedXYVector v2(1, 0); v *= v2; CHECK(v == Image::Vector(0, 0, -1)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors in different spaces cannot be crossed in place") { View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v *= v_v); using converted_type_2 = decltype(v *= v_n); using converted_type_3 = decltype(v *= v_n_xy); using converted_type_4 = decltype(v *= v_xy); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif TEST_CASE("Vectors can have Vectors crossed using star") { const Image::Vector v(0, 1, 0); const Image::Vector v2(1, 0, 0); auto v3 = v * v2; CHECK(v3 == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have NormalizedVector crossed using star") { const Image::Vector v(0, 1, 0); const Image::NormalizedVector v2(1, 0, 0); auto v3 = v * v2; CHECK(v3 == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have NormalizedXYVector crossed using star") { const Image::Vector v(0, 1, 0); const Image::NormalizedXYVector v2(1, 0); auto v3 = v * v2; CHECK(v3 == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have XYVector crossed using star") { const Image::Vector v(0, 1, 0); const Image::XYVector v2(1, 0); auto v3 = v * v2; CHECK(v3 == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have other vectors crossed using star to produce another Vector") { View::Vector v; const View::Vector v_v; const View::NormalizedVector v_n; const View::NormalizedXYVector v_n_xy; const View::XYVector v_xy; using converted_type_1 = decltype(v * v_v); using converted_type_2 = decltype(v * v_n); using converted_type_3 = decltype(v * v_n_xy); using converted_type_4 = decltype(v * v_xy); using required_type = View::Vector; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors in different spaces cannot be crossed using star") { View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v * v_v); using converted_type_2 = decltype(v * v_n); using converted_type_3 = decltype(v * v_n_xy); using converted_type_4 = decltype(v * v_xy); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif TEST_CASE("Vectors can have Vectors crossed") { const Image::Vector v(0, 1, 0); const Image::Vector v2(1, 0, 0); auto v3 = v.Cross(v2); CHECK(v3 == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have NormalizedVector crossed") { const Image::Vector v(0, 1, 0); const Image::NormalizedVector v2(1, 0, 0); auto v3 = v.Cross(v2); CHECK(v3 == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have NormalizedXYVector crossed") { const Image::Vector v(0, 1, 0); const Image::NormalizedXYVector v2(1, 0); auto v3 = v.Cross(v2); CHECK(v3 == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have XYVector crossed") { const Image::Vector v(0, 1, 0); const Image::XYVector v2(1, 0); auto v3 = v.Cross(v2); CHECK(v3 == Image::Vector(0, 0, -1)); } TEST_CASE("Vectors can have other vectors crossed to produce another Vector") { View::Vector v; const View::Vector v_v; const View::NormalizedVector v_n; const View::NormalizedXYVector v_n_xy; const View::XYVector v_xy; using converted_type_1 = decltype(v.Cross(v_v)); using converted_type_2 = decltype(v.Cross(v_n)); using converted_type_3 = decltype(v.Cross(v_n_xy)); using converted_type_4 = decltype(v.Cross(v_xy)); using required_type = View::Vector; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors in different spaces cannot be crossed") { View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v.Cross(v_v)); using converted_type_2 = decltype(v.Cross(v_n)); using converted_type_3 = decltype(v.Cross(v_n_xy)); using converted_type_4 = decltype(v.Cross(v_xy)); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif TEST_CASE("Vectors and Vectors can be dotted") { const View::Vector v(3, 4, 5); const View::Vector v2(1, 0, 0); const auto dot = v.Dot(v2); CHECK(dot == 3); } TEST_CASE("Vectors and NormalizedVector can be dotted") { const View::Vector v(3, 4, 5); const View::NormalizedVector v2(1, 0, 0); const auto dot = v.Dot(v2); CHECK(dot == 3); } TEST_CASE("Vectors and NormalizedXYVector can be dotted") { const View::Vector v(3, 4, 5); const View::NormalizedXYVector v2(1, 0); const auto dot = v.Dot(v2); CHECK(dot == 3); } TEST_CASE("Vectors and XYVector can be dotted") { const View::Vector v(3, 4, 5); const View::XYVector v2(1, 0); const auto dot = v.Dot(v2); CHECK(dot == 3); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors from different spaces cannot be dotted") { View::Vector v; const Image::Vector v_v; const Image::NormalizedVector v_n; const Image::NormalizedXYVector v_n_xy; const Image::XYVector v_xy; using converted_type_1 = decltype(v.Dot(v_v)); using converted_type_2 = decltype(v.Dot(v_n)); using converted_type_3 = decltype(v.Dot(v_n_xy)); using converted_type_4 = decltype(v.Dot(v_xy)); using required_type = StaticAssert::invalid_space; CHECK(static_cast<bool>(std::is_same_v<converted_type_1, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_2, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_3, required_type>)); CHECK(static_cast<bool>(std::is_same_v<converted_type_4, required_type>)); } #endif TEST_CASE("Vectors can have their z-value removed") { const View::Vector v(2, 3, 4); const auto v2 = v.ToXY(); CHECK(v2 == View::XYVector(2, 3)); } TEST_CASE("Vectors can have their z-value removed to produce a XYVector") { const View::Vector v; using converted_type = decltype(v.ToXY()); using required_type = View::XYVector; CHECK(static_cast<bool>(std::is_same_v<converted_type, required_type>)); } TEST_CASE("Vectors from Spaces that do not support XY cannot have their z-value removed") { const Volume::Vector v; using converted_type = decltype(v.ToXY()); using required_type = StaticAssert::XYVector_not_supported; CHECK(static_cast<bool>(std::is_same_v<converted_type, required_type>)); } TEST_CASE("Vectors can be normalized") { const Image::Vector v(0, 3, 4); const auto v_norm = v.Norm(); // Mag of v = sqrt(3*3 + 4*4) = 5 CHECK(v_norm == Image::NormalizedVector(0, 3.0 / 5, 4.0 / 5)); } TEST_CASE("Vectors can be normalized to produce a NormalizedVector") { const View::Vector v; using converted_type = decltype(v.Norm()); using required_type = View::NormalizedVector; CHECK(static_cast<bool>(std::is_same_v<converted_type, required_type>)); } TEST_CASE("Zero size vectors cannot be normalized") { const Image::Vector v(0, 0, 0); CHECK_THROWS_AS(v.Norm(), std::invalid_argument); } TEST_CASE("Zero size vectors throw the correct message when you try and normalise them.") { const Image::Vector v(0, 0, 0); CHECK_THROWS_WITH(v.Norm(), "Zero-sized normal vectors are not allowed"); } TEST_CASE("Vectors can be converted from one space to another ignoring translation") { const TransformManager tm; const View::Vector v_view(1, 0, 0); auto v_patient = v_view.ConvertTo<Data>(tm); CHECK(v_patient == Data::Vector(15, 16, 17)); } TEST_CASE("Vectors can be converted from one space to another to produce a Vector") { const TransformManager tm; const View::Vector v_view; using converted_type = decltype(v_view.ConvertTo<Data>(tm)); using required_type = Data::Vector; CHECK(static_cast<bool>(std::is_same_v<converted_type, required_type>)); } #ifndef IGNORE_SPACE_STATIC_ASSERT TEST_CASE("Vectors cannot be converted to the same space") { const TransformManager tm; const View::Vector v; using converted_type = decltype(v.ConvertTo<View>(tm)); using required_type = StaticAssert::invalid_conversion; CHECK(static_cast<bool>(std::is_same_v<converted_type, required_type>)); } #endif TEST_CASE("Vectors support mag") { const Image::Vector v(0, 3, 4); // 5 = sqrt(3*3 + 4*4) CHECK(v.Mag().get() == 5); } TEST_CASE("Vector Mag is strongly typed") { const Image::Vector v(0, 3, 4); const Millimetres m{ 0 }; CHECK(typeid(v.Mag()).name() == typeid(m).name()); } TEST_CASE("Vectors support Mag_double") { const Image::Vector v(0, 3, 4); // 5 = sqrt(3*3 + 4*4) CHECK(v.Mag_double() == 5); } TEST_CASE("Vectors can be streamed") { const View::Vector v(1.2, 2.3, 3.4); std::stringstream stream; stream << v; CHECK(stream.str() == std::string("View::Vector (1.2, 2.3, 3.4)")); }
35.906553
91
0.681617
[ "vector" ]
1d9b4e291f583a6411b333dbbc3b75dc59976207
1,935
cpp
C++
295_a.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
295_a.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
295_a.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const int INF = 0x3f3f3f3f; int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}}; int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("inputf.in","r",stdin); freopen("outputf.in","w",stdout); #endif int n,m,k; cin>>n>>m>>k; vector<int>v(n+1); unordered_map<int,vector<int>>op; for(int i=1;i<=n;i++) cin>>v[i]; for(int i=1;i<=m;i++) { vector<int>temp(3); cin>>temp[0]>>temp[1]>>temp[2]; op[i]=temp; } for(int i=0;i<k;i++) { int start,end; cin>>start>>end; for(int j=start;j<=end;j++) { vector<int>temp=op[j]; int l=temp[0]; int r=temp[1]; int val=temp[2]; cout<<l<<" "<<r<<" "<<val<<endl; v[l]+=val; if(r<n-1) v[r+1]-=val; } } vector<int>res(n); res[0]=v[1]; for(int i=1;i<=n;i++) cout<<v[i]<<" "; cout<<endl; for(int i=1;i<n;i++) { res[i]=res[i-1]+v[i+1]; } for(int i=0;i<n;i++) cout<<res[i]<<" "; }
23.597561
106
0.562274
[ "vector" ]
1d9d3c2c673ddf050d44342e24b9792167d7ff02
6,445
cc
C++
modules/compiled/select_knn_kernel.cu.cc
shahrukhqasim/HGCalML
2808564b31c89d9b7eb882734f6aebc6f35e94f3
[ "BSD-3-Clause" ]
null
null
null
modules/compiled/select_knn_kernel.cu.cc
shahrukhqasim/HGCalML
2808564b31c89d9b7eb882734f6aebc6f35e94f3
[ "BSD-3-Clause" ]
null
null
null
modules/compiled/select_knn_kernel.cu.cc
shahrukhqasim/HGCalML
2808564b31c89d9b7eb882734f6aebc6f35e94f3
[ "BSD-3-Clause" ]
null
null
null
//#define GOOGLE_CUDA 1 #if GOOGLE_CUDA #define EIGEN_USE_GPU #include "select_knn_kernel.h" #include "helpers.h" #include "tensorflow/core/util/gpu_kernel_helper.h" #include <cuda.h> #include <cuda_runtime.h> #include <cuda_runtime_api.h> #include "cuda_helpers.h" namespace tensorflow { namespace functor { namespace gpu{ __device__ float calculateDistance(size_t i_v, size_t j_v, const float * d_coord, size_t n_coords){ float distsq=0; if(i_v == j_v) return 0; for(size_t i=0;i<n_coords;i++){ float dist = d_coord[I2D(i_v,i,n_coords)] - d_coord[I2D(j_v,i,n_coords)]; distsq += dist*dist; } return distsq; } __device__ int searchLargestDistance(int i_v, float* d_dist, int n_neigh, float& maxdist){ maxdist=0; int maxidx=0; if(n_neigh < 2) return maxidx; for(size_t n=1;n<n_neigh;n++){ //0 is self float distsq = d_dist[I2D(i_v,n,n_neigh)]; if(distsq > maxdist){ maxdist = distsq; maxidx = n; } } return maxidx; } __global__ void set_defaults( int *d_indices, float *d_dist, const bool tf_compat, const int n_vert, const int n_neigh ){ const size_t i_v = blockIdx.x * blockDim.x + threadIdx.x; if(i_v >= n_vert) return; const size_t n = blockIdx.y * blockDim.y + threadIdx.y; if(n >= n_neigh) return; if(n){ if(tf_compat) d_indices[I2D(i_v,n,n_neigh)] = i_v; else d_indices[I2D(i_v,n,n_neigh)] = -1; } else{ d_indices[I2D(i_v,n,n_neigh)] = i_v; } d_dist[I2D(i_v,n,n_neigh)] = 0; } __global__ void select_knn_kernel( const float *d_coord, const int* d_row_splits, const int* d_mask, int *d_indices, float *d_dist, const int n_vert, const int n_neigh, const int n_coords, const int j_rs, const bool tf_compat, const float max_radius, selknn::mask_mode_en mask_mode, selknn::mask_logic_en mask_logic) { //really no buffering at all here const size_t start_vert = d_row_splits[j_rs]; const size_t end_vert = d_row_splits[j_rs+1]; const size_t i_v = blockIdx.x * blockDim.x + threadIdx.x + start_vert; if(i_v >= end_vert || i_v>=n_vert) return;//this will be a problem with actual RS if(mask_mode != selknn::mm_none){ if(mask_logic == selknn::ml_and){ if(!d_mask[i_v]) return; } else{ if(mask_mode == selknn::mm_scat && d_mask[i_v]) return; else if(mask_mode == selknn::mm_acc && !d_mask[i_v]) return; } } //protection against n_vert<n_neigh size_t nvert_in_row = end_vert - start_vert; size_t max_neighbours = n_neigh; //set default to self if(nvert_in_row<n_neigh){ max_neighbours=nvert_in_row; } size_t nfilled=1; size_t maxidx_local=0; float maxdistsq=0; for(size_t j_v=start_vert;j_v<end_vert;j_v++){ if(i_v == j_v) continue; if(mask_mode != selknn::mm_none){ if(mask_logic == selknn::ml_and){ if(!d_mask[j_v]) continue; } else{ if(mask_mode == selknn::mm_scat && !d_mask[j_v]) continue; else if(mask_mode == selknn::mm_acc && d_mask[j_v]) continue; } } //fill up float distsq = calculateDistance(i_v,j_v,d_coord,n_coords); if(nfilled<max_neighbours && (max_radius<=0 || max_radius>=distsq)){ d_indices[I2D(i_v,nfilled,n_neigh)] = j_v; d_dist[I2D(i_v,nfilled,n_neigh)] = distsq; if(distsq > maxdistsq){ maxdistsq = distsq; maxidx_local = nfilled; } nfilled++; continue; } if(distsq < maxdistsq){// automatically applies to max radius //replace former max d_indices[I2D(i_v,maxidx_local,n_neigh)] = j_v; d_dist[I2D(i_v,maxidx_local,n_neigh)] = distsq; //search new max maxidx_local = searchLargestDistance(i_v,d_dist,n_neigh,maxdistsq); } } __syncthreads(); } } typedef Eigen::GpuDevice GPUDevice; template <typename dummy> struct SelectKnnOpFunctor<GPUDevice, dummy> { void operator()(const GPUDevice& d, const float *d_coord, const int* d_row_splits, const int* d_mask, int *d_indices, float *d_dist, const int n_vert, const int n_neigh, const int n_coords, const int n_rs, const bool tf_compat, const float max_radius, selknn::mask_mode_en mask_mode, selknn::mask_logic_en mask_logic ) { //for too low n, d_indices might need to be initialised with some number the // rest of the code understands.. maybe -1? //just loop over n_rs, in a realistic setting these shouldn't be more than a handful entries grid_and_block gb(n_vert,256,n_neigh,4); gpu::set_defaults<<<gb.grid(),gb.block()>>>( d_indices, d_dist, tf_compat, n_vert, n_neigh); cudaDeviceSynchronize(); std::vector<int> cpu_rowsplits(n_rs); cudaMemcpy(&cpu_rowsplits.at(0),d_row_splits,n_rs*sizeof(int),cudaMemcpyDeviceToHost); for(size_t j_rs=0;j_rs<n_rs-1;j_rs++){ //n_rs-1 important! int nvert_rs = cpu_rowsplits.at(j_rs+1) - cpu_rowsplits.at(j_rs); grid_and_block gb(nvert_rs,1024); gpu::select_knn_kernel<<<gb.grid(),gb.block() >>>( d_coord, d_row_splits, d_mask, d_indices, d_dist, n_vert, n_neigh, n_coords, j_rs, tf_compat, max_radius, mask_mode, mask_logic); cudaDeviceSynchronize(); } } }; template struct SelectKnnOpFunctor<GPUDevice, int>; }//functor }//tensorflow #endif // GOOGLE_CUDA
25.077821
100
0.554383
[ "vector" ]
1da578c1f12e56a1fc6560decde02f5777fa1f94
292,747
cpp
C++
src/SpeciesSpecificParameters.cpp
RemiMattheyDoret/SimBit
ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43
[ "MIT" ]
11
2017-06-06T23:02:48.000Z
2021-08-17T20:13:05.000Z
src/SpeciesSpecificParameters.cpp
RemiMattheyDoret/SimBit
ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43
[ "MIT" ]
1
2017-06-06T23:08:05.000Z
2017-06-07T09:28:08.000Z
src/SpeciesSpecificParameters.cpp
RemiMattheyDoret/SimBit
ed0e64c0abb97c6c889bc0adeec1277cbc6cbe43
[ "MIT" ]
null
null
null
/* Author: Remi Matthey-Doret MIT License Copyright (c) 2017 Remi Matthey-Doret 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. */ int SpeciesSpecificParameters::selectNonEmptyPatch(int firstPatchToLookAt, std::vector<int>& PSs, bool increasingOrder) { int r = -1; if (firstPatchToLookAt != -1 && PSs[firstPatchToLookAt] > 0) { r = firstPatchToLookAt; } else { if (increasingOrder) { for (int patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index) { if (PSs[patch_index] > 0) { r = patch_index; break; } } } else { for (int patch_index = GP->PatchNumber - 1 ; patch_index >= 0 ; --patch_index) { if (PSs[patch_index] > 0) { r = patch_index; break; } } } } return r; } void SpeciesSpecificParameters::setRandomDistributions() { SSP = this; geneticSampler.set_nbRecombinations(TotalRecombinationRate); geneticSampler.set_T1_nbMuts(T1_Total_Mutation_rate); geneticSampler.set_T2_nbMuts(T2_Total_Mutation_rate); geneticSampler.set_T3_nbMuts(T3_Total_Mutation_rate); geneticSampler.set_T4_nbMuts(T4_Total_Mutation_rate); geneticSampler.set_T56_nbMuts(T56_Total_Mutation_rate); geneticSampler.set_T8_mutationStuff(T8_Total_Mutation_rate, T8_MutationRate, T8_map); geneticSampler.set_recombinationPosition(RecombinationRate); geneticSampler.set_T1_mutationPosition(T1_MutationRate); geneticSampler.set_T2_mutationPosition(T2_MutationRate); geneticSampler.set_T3_mutationPosition(T3_MutationRate); geneticSampler.set_T4_mutationPosition(T4_MutationRate); geneticSampler.set_T56_mutationPosition(T56_MutationRate); SSP = nullptr; #ifdef DEBUG std::cout << "Exiting 'setRandomDistributions' " << std::endl; #endif } void SpeciesSpecificParameters::readSegDiversityFile_includeMainColor(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); SegDiversityFile_includeMainColor = false; } else { SegDiversityFile_includeMainColor = input.GetNextElementBool(); } } void SpeciesSpecificParameters::readSwapInLifeCycle(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); if (selectionOn == 0 && Gmap.TotalNbLoci > 1000 && TotalRecombinationRate < 10.0) { SwapInLifeCycle = true; } else { SwapInLifeCycle = false; } } else { SwapInLifeCycle = input.GetNextElementBool(); if (SwapInLifeCycle && selectionOn != 0) { std::cout << "You asked for selection to be not only on fecundity and for SwapInLifeCycle. Swapping is only possible if selection is only on fecundity.\n"; abort(); } } } void SpeciesSpecificParameters::readDispMat(InputReader& input) { dispersalData.readDispMat(input); } void SpeciesSpecificParameters::readGameteDispersal(InputReader& input) { std::string s = input.GetNextElementString(); if (s == "no" || s == "n" || s == "N" || s == "No" || s == "NO" || s == "0") { gameteDispersal = false; } else if (s == "yes" || s == "y" || s == "Y" || s == "Yes" || s == "YES" || s == "1") { gameteDispersal = true; } else { std::cout << "In option --gameteDispersal, expected either 'yes' (or 'y','Y', '1' and a few others) or 'no' (or 'n', 'N', '0' and a few others) but instead received " << s << "\n"; abort(); } } void SpeciesSpecificParameters::readOutputSFSbinSize(InputReader& input) { while (input.IsThereMoreToRead()) { if (input.PeakNextElementString() == "default") { input.skipElement(); outputSFSbinSizes.push_back(0.01); } else { double x = input.GetNextElementDouble(); if (x <= 0 || x > 1) { std::cout << "While reading option --outputSFSbinSize, a bin size of " << x << " has been received. A bin size must be great than zero and must be lower (or equal) to one.\n"; abort(); } outputSFSbinSizes.push_back(x); } } } SpeciesSpecificParameters::SpeciesSpecificParameters(std::string sN, int sI) : speciesName(sN), speciesIndex(sI) { //std::cout << "Constructor of SpeciesSpecificParameters\n"; } SpeciesSpecificParameters::SpeciesSpecificParameters() { std::cout << "Default cnstructor of SpeciesSpecificParameters called\n"; } SpeciesSpecificParameters::~SpeciesSpecificParameters() { //std::cout << "Destructor of SpeciesSpecificParameters\n"; } /* template <typename T> T log(T x, double base) { return std::log(x) / std::log(base); } */ bool SpeciesSpecificParameters::setFromLocusToFitnessMapIndex_DecidingFunction(double sumOfProb, int nbLoci) { assert(this->FitnessMapCoefficient == -9.0 || this->FitnessMapProbOfEvent == -9.0); assert(nbLoci > 0); if (this->FitnessMapCoefficient > 0.0) { return (nbLoci > 80 && (sumOfProb * nbLoci / 500) > this->FitnessMapCoefficient); } else if (this->FitnessMapProbOfEvent > 0.0 && nbLoci > this->FitnessMapMinimNbLoci) { return sumOfProb > this->FitnessMapProbOfEvent; } return false; } void SpeciesSpecificParameters::setFromLocusToFitnessMapIndex() { assert(this->FromLocusToFitnessMapIndex.size() == 0); if (this->FitnessMapProbOfEvent < 0.0) { std::cout << "In 'setFromLocusToFitnessMapIndex', it appears that the inputted parameter for 'FitnessMapProbOfEvent' is negative. Value received is " << this->FitnessMapProbOfEvent << "\n"; abort(); } /* std::cout << "T56_isMultiplicitySelection = " << T56_isMultiplicitySelection << "\n"; std::cout << "T1_isSelection = " << T1_isSelection << "\n"; std::cout << "T1_isMultiplicitySelection = " << T1_isMultiplicitySelection << "\n"; */ bool ShouldThereBeSeveralFitnessBlocks = (this->T1_isSelection && this->T1_isMultiplicitySelection) || (this->T56_isSelection && this->T56_isMultiplicitySelection) || this->T2_isSelection; double sumOfProb = 0.0; // only used if not whole description int FitnessMapIndex = 0; int nbLociInPiece = 0; if (ShouldThereBeSeveralFitnessBlocks) { for (int interlocus = 0 ; interlocus < (this->Gmap.TotalNbLoci - 1) ; interlocus++) { nbLociInPiece++; // only used if not whole description // Get Locus info int T1_locus = this->Gmap.FromLocusToNextT1Locus(interlocus); int T2_locus = this->Gmap.FromLocusToNextT2Locus(interlocus); int T3_locus = this->Gmap.FromLocusToNextT3Locus(interlocus); int T4_locus = this->Gmap.FromLocusToNextT4Locus(interlocus); int T56ntrl_locus = this->Gmap.FromLocusToNextT56ntrlLocus(interlocus); int T56sel_locus = this->Gmap.FromLocusToNextT56selLocus(interlocus); int locusType; { //std::cout << "interlocus " << interlocus << " / " << this->Gmap.TotalNbLoci - 1 << "\n"; // Get locusType and long security if (interlocus == 0) { assert(T1_locus + T2_locus + T3_locus + T4_locus + T56ntrl_locus + T56sel_locus == 1); if (T1_locus == 1) { locusType = 1; } else if (T2_locus == 1) { locusType = 2; } else if (T3_locus == 1) { locusType = 3; } else if (T4_locus == 1) { locusType = 4; } else if (T56ntrl_locus == 1) { locusType = 50; } else if (T56sel_locus == 1) { locusType = 51; } else { std::cout << "Internal error in void SpeciesSpecificParameters::setFromLocusToFitnessMapIndex(): unknown locusType received.\n"; abort(); } } else { assert(T1_locus + T2_locus + T3_locus + T4_locus + T56ntrl_locus + T56sel_locus - this->Gmap.FromLocusToNextT1Locus(interlocus - 1) - this->Gmap.FromLocusToNextT2Locus(interlocus - 1) - this->Gmap.FromLocusToNextT3Locus(interlocus - 1) - this->Gmap.FromLocusToNextT4Locus(interlocus - 1) - this->Gmap.FromLocusToNextT56ntrlLocus(interlocus - 1) - this->Gmap.FromLocusToNextT56selLocus(interlocus - 1) == 1); if (T1_locus - this->Gmap.FromLocusToNextT1Locus(interlocus - 1) == 1) { locusType = 1; } else if (T2_locus - this->Gmap.FromLocusToNextT2Locus(interlocus - 1) == 1) { locusType = 2; } else if (T3_locus - this->Gmap.FromLocusToNextT3Locus(interlocus - 1) == 1) { locusType = 3; } else if (T4_locus - this->Gmap.FromLocusToNextT4Locus(interlocus - 1) == 1) { locusType = 4; } else if (T56ntrl_locus - this->Gmap.FromLocusToNextT56ntrlLocus(interlocus - 1) == 1) { locusType = 50; } else if (T56sel_locus - this->Gmap.FromLocusToNextT56selLocus(interlocus - 1) == 1) { locusType = 51; } else { std::cout << "Internal error in 'void SpeciesSpecificParameters::setFromLocusToFitnessMapIndex()'.\n"; abort(); } } //assert(locusType == this->FromLocusToTXLocus[interlocus].TType); // Has there been a whole description of the map if (this->FitnessMapInfo_wholeDescription.size()) { //std::cout << "this->FitnessMapInfo_wholeDescription.size() = " << this->FitnessMapInfo_wholeDescription.size() << "\n"; //std::cout << "FitnessMapIndex = " << FitnessMapIndex << "\n"; assert(this->FitnessMapInfo_wholeDescription.size() > FitnessMapIndex); //std::cout << "nbLociInPiece = " << nbLociInPiece << "\n"; //std::cout << "this->FitnessMapInfo_wholeDescription["<<FitnessMapIndex<<"] = " << this->FitnessMapInfo_wholeDescription[FitnessMapIndex] << "\n"; if (nbLociInPiece == this->FitnessMapInfo_wholeDescription[FitnessMapIndex] && FitnessMapIndex != this->FitnessMapInfo_wholeDescription.size() - 1) // Don't add the last element in FromFitnessMapIndexToTXLocus as it will be done afterward. { FitnessMapIndex++; nbLociInPiece = 0; //std::cout << T1_locus << "\n"; FromLocusToTXLocusElement E(T1_locus, T2_locus, T3_locus, T4_locus, T56ntrl_locus, T56sel_locus, locusType); FromFitnessMapIndexToTXLocus.push_back(E); // last locus included of each type } } else { // Get Recombination Rate info double r; if (locusType == 1 || locusType == 2 || locusType == 50 || locusType == 51) { if (this->RecombinationRate.size() == 1) // which is the case if the rate is constant between any two loci. { r = this->RecombinationRate[0]; } else { if (interlocus == 0) { r = this->RecombinationRate[0]; } else { assert(this->RecombinationRate.size() > interlocus); r = this->RecombinationRate[interlocus] - this->RecombinationRate[interlocus - 1]; } } } else { r = 0.0; } if (locusType == 50 || locusType == 51) { r *= this->FitnessMapT5WeightProbOfEvent; } // Sum probabilities of an event sumOfProb += r; // test if needs to make a new boundary bool avoidTooMuchByteSplitting_mustRunDecidingFun = true; if (locusType == 1 && (T1_locus%8) != 7) { avoidTooMuchByteSplitting_mustRunDecidingFun = false; } if (avoidTooMuchByteSplitting_mustRunDecidingFun && setFromLocusToFitnessMapIndex_DecidingFunction(sumOfProb, nbLociInPiece)) { FitnessMapIndex++; sumOfProb = 0.0; FromLocusToTXLocusElement E(T1_locus, T2_locus, T3_locus, T4_locus, T56ntrl_locus, T56sel_locus, locusType); FromFitnessMapIndexToTXLocus.push_back(E); // last locus included of each type nbLociInPiece = 0; } } } } } ++FitnessMapIndex; NbElementsInFitnessMap = FitnessMapIndex; if (this->FitnessMapInfo_wholeDescription.size()) { //std::cout << "this->FitnessMapInfo_wholeDescription.size() = " << this->FitnessMapInfo_wholeDescription.size() << "\n"; //std::cout << "NbElementsInFitnessMap = " << NbElementsInFitnessMap << "\n"; if (ShouldThereBeSeveralFitnessBlocks) assert(this->FitnessMapInfo_wholeDescription.size() == NbElementsInFitnessMap); std::vector<int>().swap(this->FitnessMapInfo_wholeDescription); } // Add last element to boundaries FromLocusToTXLocusElement E(this->Gmap.T1_nbLoci, this->Gmap.T2_nbLoci, this->Gmap.T3_nbLoci, this->Gmap.T4_nbLoci, this->Gmap.T56ntrl_nbLoci, this->Gmap.T56sel_nbLoci, this->Gmap.getLocusType(this->Gmap.TotalNbLoci-1)); FromFitnessMapIndexToTXLocus.push_back(E); assert(FromFitnessMapIndexToTXLocus.size() == NbElementsInFitnessMap); // Create FromLocusToFitnessMapIndex from FromFitnessMapIndexToTXLocus if ( ShouldThereBeSeveralFitnessBlocks ) { int previous_b_interlocus = 0; for (int i = 0 ; i < FromFitnessMapIndexToTXLocus.size() ; i++) { auto& b = FromFitnessMapIndexToTXLocus[i]; assert(b.T1 + b.T2 + b.T3 + b.T4 + b.T56ntrl + b.T56sel <= this->Gmap.TotalNbLoci); int b_interlocus = b.T1 + b.T2 + b.T3 + b.T4 + b.T56ntrl + b.T56sel; for (int j = previous_b_interlocus ; j < b_interlocus ; j++) { FromLocusToFitnessMapIndex.push_back(i); } previous_b_interlocus = b_interlocus; } //std::cout << "FromLocusToFitnessMapIndex.size() = " << FromLocusToFitnessMapIndex.size() << " this->Gmap.TotalNbLoci = " << this->Gmap.TotalNbLoci << "\n"; assert(FromLocusToFitnessMapIndex.size() == this->Gmap.TotalNbLoci); //std::cout << "NbElementsInFitnessMap = " << NbElementsInFitnessMap << "\n"; //std::cout << "FromLocusToFitnessMapIndex.back() = " << FromLocusToFitnessMapIndex.back() << "\n"; assert(NbElementsInFitnessMap == FromLocusToFitnessMapIndex.back()+1); } // print to console if ( ShouldThereBeSeveralFitnessBlocks ) { assert(NbElementsInFitnessMap >= 1); std::cout << "\t\tThe fitnessMap of species '"<<this->speciesName<<"' contains " << NbElementsInFitnessMap << " element\n\n"; } /* std::cout << "FromFitnessMapIndexToTXLocus"; std::cout << "("<<FromFitnessMapIndexToTXLocus.size()<<"):\n"; for (auto& e : FromFitnessMapIndexToTXLocus) std::cout << e.T1 + e.T2 + e.T3 << " "; std::cout << "\n"; std::cout << "FromLocusToFitnessMapIndex" << std::flush; std::cout << "("<<FromLocusToFitnessMapIndex.size()<<"):\n" << std::flush; for (int i = 0 ; i < FromLocusToFitnessMapIndex.size() ; i++) std::cout << "FromLocusToFitnessMapIndex["<<i<<"] = " << FromLocusToFitnessMapIndex[i] << "\n" << std::flush; */ } /* void SpeciesSpecificParameters::readT4_printTree(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T4_printTree', the std::string that is read is: " << input.print() << std::endl; #endif OutputFile file(input.GetNextElementString(), T4_printTree); T4Tree.indicateOutputFile(&file); } */ void SpeciesSpecificParameters::readSNPfreqCalculationAssumption(InputReader& input) { if (input.PeakNextElementString() == "default") { // Awefully approximative expectation input.skipElement(); size_t maxEverTotalpatchCapacity = 0; for (auto& elem : maxEverpatchCapacity) maxEverTotalpatchCapacity += elem; if (this->Gmap.T4_nbLoci) { T4SNPfreq_assumeMuchDiversity = Gmap.T4_nbLoci < 1e4 ? true : 4 * maxEverTotalpatchCapacity * T4_Total_Mutation_rate / Gmap.T4_nbLoci > 0.001; } else { T4SNPfreq_assumeMuchDiversity = false; // whatever } TxSNPfreq_assumeMuchDiversity = this->Gmap.TotalNbLoci - this->Gmap.T4_nbLoci < 1e4 ? true : maxEverTotalpatchCapacity > 5e3 && ((this->Gmap.TotalNbLoci - this->Gmap.T4_nbLoci) / this->Gmap.TotalNbLoci) < 0.5; } else { T4SNPfreq_assumeMuchDiversity = input.GetNextElementBool(); TxSNPfreq_assumeMuchDiversity = input.GetNextElementBool(); } } void SpeciesSpecificParameters::readT4_nbRunsToPlaceMutations(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); T4_nbRunsToPlaceMutations = 200; } else { auto x = input.GetNextElementInt(); if (x <= 0) { std::cout << "For option '--T4_nbRunsToPlaceMutations', only positive values are accepted. Received " << x << "\n"; abort(); } T4_nbRunsToPlaceMutations = x; } } void SpeciesSpecificParameters::readGeneticSampling_withWalker(InputReader& input) { geneticSampling_withWalker = input.GetNextElementBool(); } void SpeciesSpecificParameters::readIndividualSampling_withWalker(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); double meanPatchCapacity = 0.0; for (uint32_t patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index) { meanPatchCapacity += SSP->patchCapacity[patch_index]; } meanPatchCapacity /= GP->PatchNumber; /* The walker seem to be buggy. So until, I fix it, I won't use it by default if (meanPatchCapacity > 1e4) { individualSampling_withWalker = true; } else { individualSampling_withWalker = false; }*/ individualSampling_withWalker = false; } else { individualSampling_withWalker = input.GetNextElementBool(); } } void SpeciesSpecificParameters::readSampleSeq_info(InputReader& input) { #ifdef DEBUG std::cout << "For option '--sampleSeq_file', the std::string that is read for for a given species is: " << input.print() << std::endl; #endif sampleSequenceDataContainer.readInput(input); } void SpeciesSpecificParameters::readForcedMigration(InputReader& input) { this->forcedMigration.readInput(input); } void SpeciesSpecificParameters::readStochasticMigration(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); this->isStochasticMigration = true; } else { this->isStochasticMigration = input.GetNextElementBool(); } } void SpeciesSpecificParameters::readLoci(InputReader& input) { #ifdef DEBUG std::cout << "For option '--Loci', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA" || input.PeakNextElementString() == "0") { std::cout << "In option --L (--Loci), received 'NA' or '0' at the beginning of input. I suppose you meant that you don't want any genetics. Do you really want that? SimBit is a population genetics software but I can understand that you might be interested in demographic processes only. It is probably easy to allow SimBit to run simulations without genetic architecture but I did not made sure it would not cause bugs. So, if you don't want any genetics, I suggest you just use a single locus without selection on it (do '--L T5 1 --T5_mu A 0 --T5_fit multfitA 1' for example) and you just don't ask for outputs concerning the genetics.\n"; abort(); } Gmap.readLoci(input); if (Gmap.T4_nbLoci > 0) { if (this->nbSubGenerationsPerGeneration != 1) { std::cout << "You have asked for loci of type T4 via option --Loci (--L). You have also asked for having a number of subGeneration per generation different than 1 via option --nbSubGenerations (--nbSubGens). Sorry, the coalescent tree used to track T4 loci assumes on subgeneration per generation. It would be easy for Remi to get rid of this assumption. Please let me know!\n"; abort(); } /*int nbDemes = patchCapacity.size(); for (auto& pc : __patchCapacity) { if (pc.size() != nbDemes) { std::cout << "You have asked for loci of type T4 via option --Loci (--L). You have also asked for having change in the number of demes over time (via --PN). Sorry, the coalescent tree used to track T4 loci assumes no change in the carrying capacity or in the number of demes over time. This assumption is simply caused by Remi being too lazy to make it more flexible!\n"; abort(); } for (uint32_t patch_index = 0 ; patch_index < nbDemes ; ++patch_index) { if (pc[patch_index] != patchCapacity[patch_index]) { std::cout << "You have asked for loci of type T4 via option --Loci (--L). You have also asked for having change in the carrying patchCapacity over time.(via --N). Sorry, the coalescent tree used to track T4 loci assumes no change in the carrying capacity or in the number of demes over time. This assumption is simply caused by Remi being too lazy to make it more flexible!\n"; abort(); } } }*/ } /////////////////////////// ///// T5 and T6 stuff ///// /////////////////////////// // T6 will use T56_FitnessEffects. It is a bit misleading but it is useless to rename it assert(T56_FitnessEffects.size() == MaxEverHabitat+1); // Remove from T5_fit everything that is not under selection for (uint32_t habitat = 0 ; habitat <= this->MaxEverHabitat ; habitat++) { auto& fits = T56_FitnessEffects[habitat]; if (T56_isMultiplicitySelection) { //std::cout << "fits.size() = " << fits.size() << "\n"; //std::cout << "T5_nbLoci = " << T5_nbLoci << "\n"; //std::cout << "T6_nbLoci = " << T6_nbLoci << "\n"; assert(fits.size() == Gmap.T56_nbLoci); //would be faster with erase-remove idiom fits.erase( std::remove_if( fits.begin(), fits.end(), [&fits, this](fitnesstype& elem) { uint32_t locus = &elem - fits.data(); return Gmap.isT56neutral(locus); } ), fits.end() ); //std::cout << "fits.size() = " << fits.size() << "\n"; //std::cout << "T5sel_nbLoci = " << T5sel_nbLoci << "\n"; assert(fits.size() == Gmap.T56sel_nbLoci); } else { //std::cout << "fits.size() = " << fits.size() << "\n"; //std::cout << "T5_nbLoci = " << T5_nbLoci << "\n"; assert(fits.size() == Gmap.T56_nbLoci*2); //would be faster with erase-remove idiom fits.erase( std::remove_if( fits.begin(), fits.end(), [&fits, this](fitnesstype& elem) { uint32_t locus = (&elem - fits.data())/2; return Gmap.isT56neutral(locus); } ), fits.end() ); //std::cout << "fits.size() = " << fits.size() << "\n"; //std::cout << "T5sel_nbLoci = " << T5sel_nbLoci << "\n"; assert(fits.size() == Gmap.T56sel_nbLoci * 2); } } } void SpeciesSpecificParameters::readT56_compress(InputReader& input) { Gmap.readT56Compression(input); } void SpeciesSpecificParameters::readT56_approximationForNtrl(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); T56_approximationForNtrl = 0.0; } else { T56_approximationForNtrl = input.GetNextElementDouble(); } if (T56_approximationForNtrl < 0.0 || T56_approximationForNtrl > 1.0) { std::cout << "In --T56_approximationForNtrl, the value received is " << T56_approximationForNtrl << ". Sorry only values greater or equal to 0.0 and smaller or equal to 1.0 make sense. Default is 0.0, which means 'no approximation'. The approximation is computed as following. For a fitness value 'fit' greater than 1.0, SimBit will consider the locus to be neutral if 'fit' is greater than '1+T56_approximationForNtrl'. For a fitness value 'fit' lower than 1.0, SimBit will consider the locus to be neutral if 'fit' is lower than '1 / (1+T56_approximationForNtrl)'.\n"; abort(); } } void SpeciesSpecificParameters::resetT56_freqThresholToDefault() { T56ntrl_frequencyThresholdForFlippingMeaning = 1.0; T56sel_frequencyThresholdForFlippingMeaning = 1.0; /* if (TotalpatchCapacity > 50) { T56ntrl_frequencyThresholdForFlippingMeaning = 0.95; T56sel_frequencyThresholdForFlippingMeaning = 0.95; } if (TotalpatchCapacity > 500) { T56ntrl_frequencyThresholdForFlippingMeaning = 0.9; T56sel_frequencyThresholdForFlippingMeaning = 0.9; } if (TotalpatchCapacity > 1000) { T56ntrl_frequencyThresholdForFlippingMeaning = 0.8; T56sel_frequencyThresholdForFlippingMeaning = 0.8; } if (TotalpatchCapacity > 3000) { T56ntrl_frequencyThresholdForFlippingMeaning = 0.7; T56sel_frequencyThresholdForFlippingMeaning = 0.7; } if (TotalpatchCapacity > 10000) { T56ntrl_frequencyThresholdForFlippingMeaning = 0.6; T56sel_frequencyThresholdForFlippingMeaning = 0.6; }*/ //std::cout << "T56ntrl_frequencyThresholdForFlippingMeaning = " << T56ntrl_frequencyThresholdForFlippingMeaning << "\n"; //std::cout << "T56sel_frequencyThresholdForFlippingMeaning = " << T56sel_frequencyThresholdForFlippingMeaning << "\n"; } void SpeciesSpecificParameters::readT56_freqThreshold(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); T5_freqThresholdWasSetToDefault = true; this->resetT56_freqThresholToDefault(); } else { T5_freqThresholdWasSetToDefault = false; T56ntrl_frequencyThresholdForFlippingMeaning = input.GetNextElementDouble(); T56sel_frequencyThresholdForFlippingMeaning = input.GetNextElementDouble(); } // Securities if (T56ntrl_frequencyThresholdForFlippingMeaning <= 0.5 ) { std::cout << "In --T5_freqThreshold, received the value " << T56ntrl_frequencyThresholdForFlippingMeaning << " for T5ntrl. Sorry a value lower or equal to 0.5 makes no sense.\n"; abort(); } if (T56sel_frequencyThresholdForFlippingMeaning <= 0.5 ) { std::cout << "In --T5_freqThreshold, received the value " << T56sel_frequencyThresholdForFlippingMeaning << " for T5sel. Sorry a value lower or equal to 0.5 makes no sense.\n"; abort(); } } /*void SpeciesSpecificParameters::readreverseFixedT5selMuts(InputReader& input) { std::string x = input.GetNextElementString(); if (x == "false" || x == "0" || x == "f") { reverseFixedT5selMuts = false; } else if (x == "true" || x == "1" || x == "t") { reverseFixedT5selMuts = true; } else { std::cout << "In option --reverseFixedT5selMuts, was expecting either 'true' (or '1' or 't') or 'false' (or '0' or 'f') but instead received " << x << "\n"; abort(); } }*/ /*void SpeciesSpecificParameters::readT1mutsDirectional(InputReader& input) { std::string x = input.GetNextElementString(); if (x == "false" || x == "0" || x == "f") { T1mutsDirectional = false; } else if (x == "true" || x == "1" || x == "t") { T1mutsDirectional = true; } else { std::cout << "In option --T1mutsDirectional, was expecting either 'true' (or '1' or 't') or 'false' (or '0' or 'f') but instead received " << x << "\n"; abort(); } }*/ /*void SpeciesSpecificParameters::readT5mutsDirectional(InputReader& input) { std::string x = input.GetNextElementString(); if (x == "false" || x == "0" || x == "f") { T5mutsDirectional = false; } else if (x == "true" || x == "1" || x == "t") { T5mutsDirectional = true; T5sel_knownMutFixed.resize(T5sel_nbLoci, false); } else { std::cout << "In option --T5mutsDirectional, was expecting either 'true' (or '1' or 't') or 'false' (or '0' or 'f') but instead received " << x << "\n"; abort(); } assert(MaxEverHabitat >= 0); T5sel_fitnessEffectOfknownMutFixed.resize(MaxEverHabitat+1,1.0); }*/ void SpeciesSpecificParameters::readCloningRate(InputReader& input) { this->cloningRate = input.GetNextElementDouble(); if (this->cloningRate > 1.0 || this->cloningRate < 0.0) { std::cout << "In --cloningRate, received a cloning rate for species '"<<this->speciesName<<"' that is either lower than zero or greater than one. cloningRate receveid is " << this->cloningRate << "\n"; abort(); } } void SpeciesSpecificParameters::readSelfingRate(InputReader& input) { this->selfingRate = input.GetNextElementDouble(); if ((this->selfingRate > 1.0 || this->selfingRate < 0.0) && this->selfingRate != -1.0) { std::cout << "In --selfingRate, received a selfing rate that is either lower than zero or greater than one. selfing rate receveid is " << this->selfingRate << ". Note that a selfingRate of -1 (default) refers to a simple Wright-Fisher model where the selfing rate is at 1/2N (a little bit lower with migration)\n"; abort(); } } void SpeciesSpecificParameters::readShrinkT56EveryNGeneration(InputReader& input) { if (input.PeakNextElementString() == "default") { T56_memManager.set_attempt_shrinking_every_N_generation(1000); input.skipElement(); } else { T56_memManager.set_attempt_shrinking_every_N_generation(input.GetNextElementInt()); } } void SpeciesSpecificParameters::readMatingSystem(InputReader& input) { #ifdef DEBUG std::cout << "For option '--matingSystem', the std::string that is read is: " << input.print() << std::endl; #endif std::string s = input.GetNextElementString(); if (s == "H" || s == "h") { this->malesAndFemales = false; this->sexRatio = 0.0; } else if (s == "MF" || s == "FM" || s == "fm" || s == "mf") { this->malesAndFemales = true; this->sexRatio = input.GetNextElementDouble(); if (this->sexRatio >= 1.0 || this->sexRatio <= 0.0) { std::cout << "For option '--matingSystem', the mating system chosen is 'fm' (males and females). The sex ratio received is " << this->sexRatio << ". A sex ratio must be between 0 and 1 (non-bounded). If set at zero, all individuals are female and no reproduction is possible. If set at one, all individuals are males and no reproduction is possible. If you want hermaphrodites, please indicate 'h' (or 'H') and no sex-ratio\n"; abort(); } assert(SSP->__patchCapacity.size() == GP->__GenerationChange.size()); assert(GP->__PatchNumber.size() == GP->__GenerationChange.size()); if (SSP->fecundityForFitnessOfOne == -1.0) { for (int generation_index = 0 ; generation_index < GP->__GenerationChange.size() ; generation_index++) { assert(SSP->__patchCapacity[generation_index].size() == GP->__PatchNumber[generation_index]); for (double N : SSP->__patchCapacity[generation_index]) { int nbMales = (int) (sexRatio * N + 0.5); int nbFemales = N - nbMales; //std::cout << "nbMales = "<<nbMales<<" nbFemales = "<<nbFemales<<"\n"; if (nbMales <= 0 || nbFemales <= 0) { std::cout << "For option '--matingSystem', the mating system chosen is 'fm' (males and females). The sex ratio received for species "<< this->speciesName<< " is " << this->sexRatio << ". At the " << generation_index << "th generation index (after generation " << GP->__GenerationChange[generation_index] << "), the patchCapacity multiplied by the sex ratio lead to either the number of males or the number of females to be zero (nbMales = "<<nbMales<<" nbFemales = "<<nbFemales<<"). This error message would not appear if the fecundity (from option --fec) was set to -1.0 (fecundityForFitnessOfOne = "<<SSP->fecundityForFitnessOfOne<<"). If fecundity was not set to -1.0, then the patch size would just reach 0. SimBit enforces that there is at least one female and one male per patch when fecundity is different from -1.0. (this error message was written at a time when sex ratio is deterministic. If at some point SimBit evovles to have stochasticity in the sex ratio, then I should remove this error message and deal with cases where the sex ratio is 0 or 1).\n"; abort(); } } } } } else { std::cout << "For option '--matingSystem', the mating system received is " << s << ". Only types 'fm' (or 'mf', 'FM','MF') and 'h' (or 'H') are recognized. Sorry.\n"; abort(); } } void SpeciesSpecificParameters::readDispWeightByFitness(InputReader& input) { #ifdef DEBUG std::cout << "For option '--DispWeightByFitness', the std::string that is read is: " << input.print() << std::endl; #endif // Note that --fec has already been received but not --m if (input.PeakNextElementString() == "default") { input.skipElement(); if (this->fecundityForFitnessOfOne == -1) { this->DispWeightByFitness = false; } else { this->DispWeightByFitness = true; } } else { this->DispWeightByFitness = input.GetNextElementBool(); } if (fecundityForFitnessOfOne != -1 && !DispWeightByFitness) { std::cout << "For option '--DispWeightByFitness', received 'false' and fecundityForFitnessOfOne is not -1 (is " << fecundityForFitnessOfOne << "). When the fecundity is not -1 (which means infinite), then dispersal must necessarily be weigthed by fitness (or I don't really know what it would mean otherwise).\n"; abort(); } } void SpeciesSpecificParameters::readPloidy(InputReader& input) { #ifdef DEBUG std::cout << "For option '--ploidy', the std::string that is read is: " << input.print() << std::endl; #endif this->ploidy = input.GetNextElementInt(); if (this->ploidy!=2) { std::cout << "Sorry, for the moment ploidy can only be equal to 2" << std::endl; abort(); } } void SpeciesSpecificParameters::readT4_paintedHaplo_ignorePatchSizeSecurityChecks(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); T4_paintedHaplo_shouldIgnorePatchSizeSecurityChecks = false; } else { T4_paintedHaplo_shouldIgnorePatchSizeSecurityChecks = input.GetNextElementBool(); } } ResetGeneticsEvent_A SpeciesSpecificParameters::readResetGenetics_readEventA(InputReader& input, int& eventIndex) { // generation int generation = input.GetNextElementInt(); if (generation < 0) { std::cout << "For option '--resetGenetics', the generation must be 0 or larger. Received generation = " << generation << ".\n"; abort(); } int generation_index = std::upper_bound(GP->__GenerationChange.begin(), GP->__GenerationChange.end(), generation) - GP->__GenerationChange.begin() - 1; // loci type std::string locusType = input.GetNextElementString(); if (locusType != "T1" && locusType != "T2" && locusType != "T3" && locusType != "T5") { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), the locus type is '" << locusType <<"'. Sorry only mutation types 'T1', 'T2', 'T3' and 'T5' (but not T4) are accepted.\n"; abort(); } // mutation type char mutationType; if (locusType == "T1" || locusType == "T5") { std::string string_mutationType = input.GetNextElementString(); if (string_mutationType == "setTo0") { mutationType = 0; /*if (SSP->T5mutsDirectional) { std::cout << "For option --resetGenetics, you indicated a mutation type 'setTo0'. It is impossible to ask to set a T5 allele to 0 when the model chosen is direction. The option --T5mutsDirectional was indeed set to 'true' (either by the user or by default). Note that it would be relatively easy to allow that. Just ask Remi to make a few modifications. Otherwise, you could set --T1mutsDirectional (and/or --T5mutsDirectional) to false (which might makes things slower).\n"; abort(); }*/ } else if (string_mutationType == "setTo1") { mutationType = 1; } else if (string_mutationType == "toggle") { mutationType = 2; /*if (SSP->T5mutsDirectional) { std::cout << "For option --resetGenetics, you indicated a mutation type 'toggle'. This means that it could happen that resetGenetics would attempt to convert a 1 into a 0. It is impossible to ask to set a T5 or T1 allele to 0 when the model chosen is direction. The option --T5mutsDirectional was indeed set to 'true' (either by the user or by default). Note that it would be relatively easy to allow that. Just ask Remi to make a few modifications. Otherwise, you could set --T1mutsDirectional (and/or --T5mutsDirectional) to false (which might makes things slower).\n"; abort(); }*/ } else { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<") for loci of type "<<locusType<<", the mutation type received is '" << string_mutationType <<"'. Sorry only mutation types 'setTo0', 'setTo1' and 'toggle' are accepted.\n"; abort(); } } else { mutationType = -1; } // Loci indices std::string lociKeyword = input.GetNextElementString(); if (lociKeyword != "lociList" && lociKeyword != "allLoci") { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<") expected the keyword 'lociList' or 'allLoci' but instead received "<<lociKeyword<<".\n"; abort(); } std::vector<int> T1loci; std::vector<int> T2loci; std::vector<int> T3loci; std::vector<int> T5loci; if (lociKeyword == "lociList") { while (input.PeakNextElementString() != "haplo") { if (locusType == "T1") { int T1locus = input.GetNextElementInt(); if (T1locus < 0) { std::cout << "For option --resetGenetics received T1locus index of "<<T1locus<<" for an event happening at generation "<<generation<<".\n"; abort(); } if (T1locus >= SSP->Gmap.T1_nbLoci) { std::cout << "For option --resetGenetics for an event happening at generation "<<generation<<", received T1locus index of "<<T1locus<<" while there are only "<<SSP->Gmap.T1_nbLoci<<" T1 loci (in bits) in total. As a reminder, the first locus has index 0.\n"; abort(); } T1loci.push_back(T1locus); } else if (locusType == "T2") { int T2locus = input.GetNextElementInt(); if (T2locus < 0) { std::cout << "For option --resetGenetics received T2 locus index of "<<T2locus<<" for an event happening at generation "<<generation<<".\n"; abort(); } if (T2locus >= SSP->Gmap.T2_nbLoci) { std::cout << "For option --resetGenetics for an event happening at generation "<<generation<<", received T2 locus index of "<<T2locus<<" while there are only "<<SSP->Gmap.T2_nbLoci<<" T2 loci in total. As a reminder, the first locus has index 0.\n"; abort(); } T2loci.push_back(T2locus); } else if (locusType == "T3") { int T3locus = input.GetNextElementInt(); if (T3locus < 0) { std::cout << "For option --resetGenetics received T3locus index of "<<T3locus<<" for an event happening at generation "<<generation<<".\n"; abort(); } if (T3locus >= SSP->Gmap.T3_nbLoci) { std::cout << "For option --resetGenetics for an event happening at generation "<<generation<<", received T3 locus index of "<<T3locus<<" while there are only "<<SSP->Gmap.T3_nbLoci<<" T3 loci in total. As a reminder, the first locus has index 0.\n"; abort(); } T3loci.push_back(T3locus); } else if (locusType == "T5") { int T5locus = input.GetNextElementInt(); if (T5locus < 0) { std::cout << "For option --resetGenetics received T5locus index of "<<T5locus<<" for an event happening at generation "<<generation<<".\n"; abort(); } if (T5locus >= SSP->Gmap.T56_nbLoci) { std::cout << "For option --resetGenetics for an event happening at generation "<<generation<<", received T5locus index of "<<T5locus<<" while there are only "<<SSP->Gmap.T56_nbLoci<<" T5 loci in total. As a reminder, the first locus has index 0.\n"; abort(); } T5loci.push_back(T5locus); } } } else // lociKeyword == "allLoci" { if (locusType == "T1") { for (int T1locus = 0 ; T1locus < SSP->Gmap.T1_nbLoci; T1locus++) { T1loci.push_back(T1locus); } } else if (locusType == "T2") { for (int T2locus = 0 ; T2locus < SSP->Gmap.T2_nbLoci; T2locus++) { T2loci.push_back(T2locus); } } else if (locusType == "T3") { for (int T3locus = 0 ; T3locus < SSP->Gmap.T3_nbLoci; T3locus++) { T3loci.push_back(T3locus); } } else if (locusType == "T5") { for (int T5locus = 0 ; T5locus < SSP->Gmap.T56_nbLoci; T5locus++) { T5loci.push_back(T5locus); } } } // haplotypes concerned std::string haploString = input.GetNextElementString(); if (haploString != "haplo") { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), expected the keyword 'haplo' but instead received '" << haploString <<"'.\n"; abort(); } std::string haploDescription = input.GetNextElementString(); std::vector<int> haplotypes; if (haploDescription == "0" || haploDescription == "f" || haploDescription == "F") { haplotypes.push_back(0); } else if (haploDescription == "1" || haploDescription == "m" || haploDescription == "M") { haplotypes.push_back(1); } else if (haploDescription == "both") { haplotypes.push_back(0); haplotypes.push_back(1); } // patches and individuals std::vector<std::vector<int>> individuals; std::vector<int> patches; while (input.IsThereMoreToRead() && input.PeakNextElementString().substr(0,5) != "event") { // patch std::string patchString = input.GetNextElementString(); if (patchString != "patch") { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), expected the keyword 'patch' but instead received '" << patchString <<"'.\n"; abort(); } int patch_index = input.GetNextElementInt(); if (patch_index < 0 || patch_index > GP->__PatchNumber[generation_index]) { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), after the keyword 'patch' received the patch index '" << patch_index <<"'. At the generation "<<generation<<" there are "<<GP->__PatchNumber[generation_index]<< "patches. The patch index must be lower than the number of patches (because it is a zero based counting) and positive.\n"; abort(); } patches.push_back(patch_index); // individuals std::string modeOfEntryOfIndividuals = input.GetNextElementString(); if (modeOfEntryOfIndividuals == "allInds") { assert(SSP->__patchCapacity[generation_index].size() == GP->__PatchNumber[generation_index]); std::vector<int> onePatchIndviduals; onePatchIndviduals.reserve(SSP->__patchCapacity[generation_index][patch_index]); for (int ind_index = 0 ; ind_index < SSP->__patchCapacity[generation_index][patch_index]; ind_index++) { onePatchIndviduals.push_back(ind_index); } individuals.push_back(onePatchIndviduals); } else if (modeOfEntryOfIndividuals == "indsList") { std::vector<int> onePatchIndviduals; while (input.IsThereMoreToRead() && input.PeakNextElementString().substr(0,5) != "event" && input.PeakNextElementString() != "patch") { onePatchIndviduals.push_back(input.GetNextElementInt()); } if (onePatchIndviduals.size() == 0) { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), for patch index "<< patch_index <<" there seems to have no individuals indicated.\n"; abort(); } individuals.push_back(onePatchIndviduals); } else { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), for patch index "<< patch_index <<" expected mode of entry of individuals (either 'indsList' or 'allInds') but instead received '" << modeOfEntryOfIndividuals <<"'.\n"; abort(); } } if (patches.size() == 0) { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), there seems to have no patch indicated.\n"; abort(); } return ResetGeneticsEvent_A( generation, mutationType, T1loci, T2loci, T3loci, T5loci, patches, haplotypes, individuals ); } ResetGeneticsEvent_B SpeciesSpecificParameters::readResetGenetics_readEventB(InputReader& input, int& eventIndex) { // generation int generation = input.GetNextElementInt(); if (generation < 0) { std::cout << "For option '--resetGenetics', the generation must be 0 or larger. Received generation = " << generation << ".\n"; abort(); } int generation_index = std::upper_bound(GP->__GenerationChange.begin(), GP->__GenerationChange.end(), generation) - GP->__GenerationChange.begin() - 1; // patch index int patch_index = input.GetNextElementInt(); if (patch_index < 0 || patch_index >= GP->__PatchNumber[generation_index]) { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), after the keyword 'patch' received the patch index '" << patch_index <<"'. At the generation "<<generation<<" there are "<<GP->__PatchNumber[generation_index]<< "patches. The patch index must be lower than the number of patches (because it is a zero based counting) and positive.\n"; abort(); } // Type std::vector<std::string> typeNames; std::vector<unsigned> howManys; while (input.IsThereMoreToRead() && input.PeakNextElementString().substr(0,5) != "event") { std::string typeName = input.GetNextElementString(); if (this->individualTypes.find(typeName) == this->individualTypes.end()) { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"), indicated individualType "<< typeName << " but no individual type with this name has been defined in option --indTypes\n"; abort(); } typeNames.push_back(typeName); howManys.push_back((unsigned)input.GetNextElementInt()); } // Security auto sumNbInds = std::accumulate(howManys.begin(), howManys.end(),0); if (sumNbInds > this->__patchCapacity[generation_index][patch_index]) { std::cout << "For option '--resetGenetics', " << eventIndex << "th event, for the "<<eventIndex<<"th event (generation "<<generation<<"; species "<<SSP->speciesName<<"). Indicated a total of "<<sumNbInds<<" individuals but the carrying capacity will only be " << this->__patchCapacity[generation_index][patch_index] << " at generation "<< generation << " (generation index: "<< generation_index <<")\n"; abort(); } // return return ResetGeneticsEvent_B( generation, typeNames, howManys, patch_index ); } void SpeciesSpecificParameters::readResetGenetics(InputReader& input) { #ifdef DEBUG std::cout << "For option '--resetGenetics', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "default") { input.skipElement(); return; } // input example with eventA's --resetGenetics @S0 event 100 T1 setTo0 lociList 2 4 6 8 haplo both patch 0 allInds patch 2 indsList 1 2 3 4 5 // ^generation int eventIndex = 0; while (input.IsThereMoreToRead()) { std::string eventString = input.GetNextElementString(); if (eventString == "eventA") { resetGenetics.addEvent(readResetGenetics_readEventA(input, eventIndex)); } else if (eventString == "eventB") { resetGenetics.addEvent(readResetGenetics_readEventB(input, eventIndex)); } else { std::cout << "For option '--resetGenetics', for the "<<eventIndex<<"th event (species "<<SSP->speciesName<<"), expected the keyword 'eventA' or 'eventB' but got "<<eventString<<"\n"; abort(); } eventIndex++; } } void SpeciesSpecificParameters::readfecundityDependentOfFitness(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); fecundityDependentOfFitness = true; } else { fecundityDependentOfFitness = input.GetNextElementBool(); } } void SpeciesSpecificParameters::readfecundityForFitnessOfOne(InputReader& input) { #ifdef DEBUG std::cout << "For option '--fec', the std::string that is read is: " << input.print() << std::endl; #endif this->fecundityForFitnessOfOne = input.GetNextElementDouble(); //std::cout << "fecundity set to " << this->fecundityForFitnessOfOne << "\n"; if (this->fecundityForFitnessOfOne > 10000.0) { std::cout << "this->fecundityForFitnessOfOne received is greater than " << 10000.0 << " (is " << this->fecundityForFitnessOfOne << "). If you want the patch to always be at carrying capacity, just use fecundityForFitnessOfOne = -1. It will make everything faster. Change the code if you really want to use such high fecundity\n"; abort(); } else if (this->fecundityForFitnessOfOne < 0.0) { if (this->fecundityForFitnessOfOne != -1.0) { std::cout << "this->fecundityForFitnessOfOne received is negative but different from -1.0 (which would mean patch size is always at carrying capacity).\n"; abort(); } } } /*void SpeciesSpecificParameters::readResetTrackedT1Muts(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); if (T1_isSelection) { if (T1_isMultiplicitySelection) { recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations = -1; } else { double averageMu = T1_MutationRate.back() / T1_nbLoci; double a = 0.0; for (int i = 1 ; i < TotalpatchCapacity ; i++) { a += 1/i; } //std::cout << "TotalpatchCapacity = " << TotalpatchCapacity << " averageMu = " << averageMu << " a = " << a << "\n"; //std::cout << "TotalpatchCapacity * averageMu * 4 * a = " << TotalpatchCapacity * averageMu * 4 * a << "\n"; if (TotalpatchCapacity * averageMu * 4 * a < 1.0) { recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations = 20; } else { recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations = -1; } } } else { recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations = -1; } } else { recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations = input.GetNextElementInt(); if (recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations == 0 || recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations < -1) { std::cout << "In --T1_resetTrackedT1Muts, the number of generations received is " << recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations << ". Please use a number that is strictly positive or -1 (-1 means, to loop through all the sites systematically).\n"; abort(); } } std::string s = input.GetNextElementString(); if (s == "n" || s == "N" || s == "no" || s == "0") { allowToCorrectRecomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations = false; } else if (s == "y" || s == "Y" || s == "yes" || s == "1") { std::cout << "In --T1_resetTrackedT1Muts, the string received for the second argument is " << s << ". This string is valid. However, the current version of SimBit is not able to modify the generations at which the listing of tracked mutations is done. Sorry! The only possible entry for the second argument is therefore 'no' (or 'n' or '0' or a few other equivalents).\n"; abort(); allowToCorrectRecomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations = true; } else { std::cout << "In --T1_resetTrackedT1Muts, expected yes or no (or a few equivalents) as second argument but instead received " << s << ".\n"; abort(); } //std::cout << "recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations = "<< recomputeLociOverWhichFitnessMustBeComputedEveryHowManyGenerations << "\n"; }*/ template<typename INT> double SpeciesSpecificParameters::getRecombinationRatePositionOfLocus(INT locus) { assert(locus < Gmap.TotalNbLoci-1); if (locus == 0) return 0.0; assert(RecombinationRate.size()); if (RecombinationRate.size() == 1) { return RecombinationRate.front() * locus; } else { assert(RecombinationRate.size() == Gmap.TotalNbLoci-1); return RecombinationRate[locus]; } } void SpeciesSpecificParameters::readT8_mapInfo(InputReader& input) { std::string mode = input.GetNextElementString(); if (mode == "default" || mode == "prob") { double prob; if (mode == "default") prob = 0.05; else prob = input.GetNextElementDouble(); if (prob <= 0.0) { std::cout << "For option --T8_mapInfo, mode 'prob' (or 'default', but 'default' should not cause any trouble), received value '" << prob << "'. The value received must be greater than 0.\n"; abort(); } if (Gmap.T8_nbLoci) { auto totalProb = (double)getRecombinationRatePositionOfLocus(Gmap.FromT8LocusToLocus(Gmap.T8_nbLoci-2)); double lastPosition = 0.0; for (long T8locus = 0 ; T8locus < Gmap.T8_nbLoci - 1 ; ++T8locus) { //std::cout << "Gmap.FromT8LocusToLocus(T8locus) = " << Gmap.FromT8LocusToLocus(T8locus) << "\n"; auto position = getRecombinationRatePositionOfLocus(Gmap.FromT8LocusToLocus(T8locus)); //std::cout << "position = " << position << "\n"; if (position > totalProb - prob / 2) break; auto sizeOfBlock = position - lastPosition; if (sizeOfBlock > prob) { T8_map.push_back(T8locus); lastPosition = position; } } if (T8_map.size() == 0 ) T8_map.push_back(Gmap.T8_nbLoci-1); else if (T8_map.back() != Gmap.T8_nbLoci-1) T8_map.push_back(Gmap.T8_nbLoci-1); //T8_map = {20000000, 40000000, 60000000, 80000000, 99999999}; std::cout << "nbBlocks = " << T8_map.size() << "\n"; std::cout << "prob = " << prob << "\n"; } } else if (mode == "descr") { uint32_t sum = 0; while (input.IsThereMoreToRead()) { auto x = input.GetNextElementInt(); if (x <= 0) { std::cout << "For option --T8_mapInfo, mode 'descr', received valule '" << x << "'. Values must be greater than 0 (no blocks of T8 loci can contain less than a singe T8 locus).\n"; abort(); } sum += x; if (sum > Gmap.T8_nbLoci) { std::cout << "For option --T8_mapInfo, mode 'descr', the sum of values is greater than the total number of T8 loci. There are " << Gmap.T8_nbLoci << " T8 loci. The last value read is '" << x << "' and it caused the sum of values read so far to be equal " << sum << ".\n"; abort(); } T8_map.push_back(sum-1); } } else { std::cout << "For option --T8_mapInfo, received mode '" << mode << "'. Only modes 'default', 'prob' and 'descr' are accepted.\n"; abort(); } // Test if (Gmap.T8_nbLoci) { if (T8_map.back() != Gmap.T8_nbLoci-1) { std::cout << "Problem when creating the T8 map (--T8_mapInfo). The last value is " << T8_map.back() << " and it does not equal the total number of T8 loci minus 1 (which is "<< Gmap.T8_nbLoci-1<< ").\n"; abort(); } for (size_t i = 1 ; i < T8_map.size() ; ++i) { if (T8_map[i] <= T8_map[i-1]) { std::cout << "Problem when creating the T8 map (--T8_mapInfo). One of the value (the "<< i << "th value which equals "<<T8_map[i]<<") is not strictly greater than the previous (the "<< i-1 << "th value which equals "<<T8_map[i-1]<<"). Note by the way that there are "<< Gmap.T8_nbLoci<< " T8 loci in total.\n"; abort(); } } } std::cout << "T8_map: "; for (size_t i = 0 ; i < T8_map.size() ; ++i) std::cout << T8_map[i] << " "; std::cout << "\n"; } void SpeciesSpecificParameters::readFitnessMapInfo(InputReader& input) { this->FitnessMapMinimNbLoci = 0; // This is set to a different value (in allParameters.cpp) only if used default this->FitnessMapProbOfEvent = 0.0; std::string mode; if (!this->T1_isMultiplicitySelection && !this->T56_isMultiplicitySelection && this->Gmap.T2_nbLoci == 0) { mode = "prob"; this->FitnessMapProbOfEvent = DBL_MAX; while (input.IsThereMoreToRead()) { input.skipElement(); } this->FitnessMapT5WeightProbOfEvent = 1.0; // whatever } else { mode = input.GetNextElementString(); if (mode == "prob") { this->FitnessMapProbOfEvent = input.GetNextElementDouble(); if (this->FitnessMapProbOfEvent <= 0.0) { std::cout << "For species " << this->speciesName << " when reading --FitnessMapInfo ( mode = " << mode << ") received not strictly positive value for 'FitnessMapProbOfEvent' (received "<<this->FitnessMapProbOfEvent<<").\n"; abort(); } this->FitnessMapT5WeightProbOfEvent = input.GetNextElementDouble(); if (this->FitnessMapT5WeightProbOfEvent <= 0.0) { std::cout << "For species " << this->speciesName << " when reading --FitnessMapInfo ( mode = " << mode << ") received not strictly positive value for 'FitnessMapT5WeightProbOfEvent'(received "<<this->FitnessMapT5WeightProbOfEvent<<").\n"; abort(); } this->FitnessMapCoefficient = -9.0; } else if (mode == "coef") { std::cout << "Sorry for --FitnessMapInfo, mode coef is not available on this version.\n"; abort(); this->FitnessMapProbOfEvent = -9.0; this->FitnessMapCoefficient = input.GetNextElementDouble(); if (this->FitnessMapCoefficient <= 0.0) { std::cout << "For species " << this->speciesName << " when reading --FitnessMapInfo ( mode = " << mode << ") received a not strictly positive value (received "<<this->FitnessMapCoefficient<<").\n"; abort(); } this->FitnessMapT5WeightProbOfEvent = input.GetNextElementDouble(); if (this->FitnessMapT5WeightProbOfEvent <= 0.0) { std::cout << "For species " << this->speciesName << " when reading --FitnessMapInfo ( mode = " << mode << ") received not strictly positive value for 'FitnessMapT5WeightProbOfEvent'(received "<<this->FitnessMapT5WeightProbOfEvent<<").\n"; abort(); } } else if (mode == "descr") { assert(this->FitnessMapInfo_wholeDescription.size() == 0); int sum = 0; while (input.IsThereMoreToRead()) { auto x = input.GetNextElementInt(); if (x < 1) { std::cout << "For species " << this->speciesName << " when reading --FitnessMapInfo ( mode = " << mode << ") received a number of loci that is lower than 1 (received "<<x<<").\n"; abort(); } sum += x; this->FitnessMapInfo_wholeDescription.push_back(x); } if (sum != this->Gmap.TotalNbLoci) { std::cout << "For species " << this->speciesName << " when reading --FitnessMapInfo ( mode = " << mode << ") received a total of "<<sum<<" loci but there is a total of "<< this->Gmap.TotalNbLoci << " loci asked for option --L. Please note that all loci must be allocated to a fitness map index whether or not the fitness of that locus will be saved for use in next generation. In other words, even for a T3 locus who cannot do the assumption of multiplciity, you have to tell which index map this locus will fall on. It is a little confusing maybe but that's how SimBit works and I've got my reasons :)\n"; abort(); } } else { std::cout << "For species " << this->speciesName << " when reading --FitnessMapInfo, received mode = " << mode << ". Sorry only modes 'prob', 'descr' and 'coef' are allowed\n"; std::cout << "Hum.... actually even mode 'coef' is not allowed on this version due to potential misfunctioning and slow down. Sorry! Please use 'prob' or 'descr'.\n"; abort(); } } //std::cout << "\n\n\n\n\n\nin SSP : FitnessMapT5WeightProbOfEvent = " << FitnessMapT5WeightProbOfEvent << "\n\n\n\n\n\n\n"; } void SpeciesSpecificParameters::readInitialpatchSize(InputReader& input) { int TotalNbIndsAtStart = 0; assert(this->patchSize.size() == 0); std::string Mode = input.GetNextElementString(); if (Mode == "A") { for (int patch_index = 0 ; patch_index < GP->__PatchNumber[0] ; patch_index++) { int x = input.GetNextElementInt(); int ps; if (x < 0) { ps = this->__patchCapacity[0][patch_index]; } else { ps = x; } if (ps > this->__patchCapacity[0][patch_index]) { std::cout << "For patch " << patch_index << " (zero-based counting), the capacity is " << this->__patchCapacity[0][patch_index] << " but the initial patch size is " << ps << "\n"; abort(); } if (this->fecundityForFitnessOfOne == -1 && ps != this->__patchCapacity[0][patch_index]) { std::cout << "For patch " << patch_index << " (zero-based counting), the capacity is " << this->__patchCapacity[0][patch_index] << " and the initial patch size is " << ps << ". When the fecundityForFitnessOfOne does not differ from -1 (-1 is the default and means infinite fecundity so that patch sizes are always at carrying capacity), the initial patch size must be at carrying capacity. This error message should only appear if you set both --InitialpatchSize and --fec yourself and made a mismatch between the initial patch size and the carrying capacity at the zeroth generation (indicated by option --N)\n"; abort(); } this->patchSize.push_back(ps); TotalNbIndsAtStart+=ps; } } else if (Mode == "unif") { int x = input.GetNextElementInt(); for (int patch_index = 0 ; patch_index < GP->__PatchNumber[0] ; patch_index++) { int ps; // stands for patchSize if (x < 0) { ps = this->__patchCapacity[0][patch_index]; } else { ps = x; } if (ps > this->__patchCapacity[0][patch_index]) { std::cout << "For patch " << patch_index << " (zero-based counting), the capacity is " << this->__patchCapacity[0][patch_index] << " but the initial patch size is " << ps << "\n"; } if (this->fecundityForFitnessOfOne == -1 && ps != this->__patchCapacity[0][patch_index]) { std::cout << "For patch " << patch_index << " (zero-based counting), the capacity is " << this->__patchCapacity[0][patch_index] << " and the initial patch size is " << ps << ". When the fecundityForFitnessOfOne does not differs from -1 (-1 is the default and means infinite fecundity so that the patch size is always at carrying capacity), the initial patch size must be at carrying capacity. This error message should only appear if you set both --InitialpatchSize and --fec yourself and made a mismatch between the initial patch size and the carrying capacity at the zeroth generation (indicated by option --N)\n"; abort(); } this->patchSize.push_back(ps); TotalNbIndsAtStart+=ps; } } else { std::cout << "For option --InitialpatchSize, mode received is " << Mode << ". Sorry only modes 'A' and 'unif' are recognized.\n"; abort(); } assert(this->patchSize.size() == GP->__PatchNumber[0]); if (TotalNbIndsAtStart == 0) { std::cout << "You asked for a total of exactly 0 individual (over all patches) at initialization (via option '--InitialpatchSize')! Nothing can be simulated for this species!\n" << std::endl; abort(); } assert(TotalNbIndsAtStart > 0); // Just an extra security TotalpatchSize = 0; for (uint32_t patch_index = 0 ; patch_index < GP->PatchNumber ; patch_index++) { TotalpatchSize += patchSize[patch_index]; } assert(TotalpatchSize <= TotalpatchCapacity); } Haplotype SpeciesSpecificParameters::getHaplotypeForIndividualType(InputReader& input, bool haploIndex, std::string& IndividualTypeName) { // IsThereSelection() is called in resetGenetics that comes first. std::string beginKeyword; std::string endKeyword; if (!haploIndex) // if haplo0 { beginKeyword = "haplo0"; endKeyword = "haplo1"; } else { beginKeyword = "haplo1"; endKeyword = "ind"; } if (!input.IsThereMoreToRead()) { std::cout << "In --indIni (--IndividualInitialization), for individualType '" << IndividualTypeName << "'. expected keyword "<<beginKeyword<< " but the input has been completely read already.\n"; abort(); } if (input.PeakNextElementString() != beginKeyword && input.PeakNextElementString() != "bothHaplo") { std::cout << "In --indIni (--IndividualInitialization), for individualType '" << IndividualTypeName << "'. expected keyword '"<<beginKeyword<< "'' (or 'bothHaplo') but got " << input.PeakNextElementString() << " instead.\n"; abort(); } input.skipElement(); if (input.PeakNextElementString() == "empty") { input.skipElement(); std::vector<unsigned char> T1_info(Gmap.T1_nbChars,0); std::vector<unsigned char> T2_info(Gmap.T2_nbLoci, 0); std::vector<T3type> T3_info(Gmap.T3_nbLoci, 0); uint32_t T4ID = std::numeric_limits<uint32_t>::max(); std::vector<uint32_t> T56_info; return Haplotype(T1_info, T2_info, T3_info, T4ID, T56_info); } // Gather info bool receivedT1_info = false; bool receivedT2_info = false; bool receivedT3_info = false; bool receivedT4_info = false; bool receivedT56_info = false; std::vector<unsigned char> T1_info; std::vector<unsigned char> T2_info; std::vector<T3type> T3_info; uint32_t T4ID = std::numeric_limits<uint32_t>::max(); std::vector<uint32_t> T56_info; while (input.IsThereMoreToRead() && input.PeakNextElementString().substr(0,5) != "haplo" && input.PeakNextElementString() != "ind") { auto TT = input.GetNextElementString(); if (TT == "T1" || TT == "t1") { // Security if (receivedT1_info) { std::cout << "In --indTypes, for individualType '" << IndividualTypeName << "'. Received info about "<<TT<<" twice!\n"; abort(); } receivedT1_info = true; // read info T1_info.resize(this->Gmap.T1_nbChars,0); // put all zeros for every bit for (unsigned locus = 0 ; locus < this->Gmap.T1_nbLoci ; ++locus) { auto char_index = locus / 8; auto bit_index = locus % 8; assert(char_index * 8 + bit_index == locus); assert(char_index < T1_info.size()); bool value = input.GetNextElementBool(); // Set value (code just copy pasted from haplotype.cpp; not a great design to copy paste!) //std::cout << "set locus " << locus << " to " << value << "\n"; //std::cout << "char_index " << char_index << " bit_index " << bit_index << "\n"; if (value) { T1_info[char_index] |= 1 << bit_index; } else { T1_info[char_index] &= ~(1 << bit_index); } } } else if (TT == "T2" || TT == "t2") { // Security if (receivedT2_info) { std::cout << "In --indTypes, for individualType '" << IndividualTypeName << "'. Received info about "<<TT<<" twice!\n"; abort(); } receivedT2_info = true; // read info T2_info.reserve(this->Gmap.T2_nbLoci); for (unsigned T2locus = 0 ; T2locus < this->Gmap.T2_nbLoci ; ++T2locus) { T2_info.push_back(input.GetNextElementInt()); // implicit cast } } else if (TT == "T3" || TT == "t3") { // Security if (receivedT3_info) { std::cout << "In --indTypes, for individualType '" << IndividualTypeName << "'. Received info about "<<TT<<" twice!\n"; abort(); } receivedT3_info = true; // read info T3_info.reserve(this->Gmap.T3_nbLoci); for (unsigned T3locus = 0 ; T3locus < this->Gmap.T3_nbLoci ; ++T3locus) { T3_info.push_back(input.GetNextElementInt()); } } else if (TT == "T4" || TT == "t4") { // Security if (receivedT4_info) { std::cout << "In --indTypes, for individualType '" << IndividualTypeName << "'. Received info about "<<TT<<" twice!\n"; abort(); } receivedT4_info = true; // read info T4ID = input.GetNextElementInt(); } else if (TT == "T5" || TT == "t5" || TT == "T6" || TT == "t6" || TT == "T56" || TT == "t56") { // Security if (receivedT56_info) { std::cout << "In --indTypes, for individualType '" << IndividualTypeName << "'. Received info about "<<TT<<" twice!\n"; abort(); } receivedT56_info = true; // read info // Watch out T56 get index of mutations while (input.IsThereMoreToRead() && input.PeakNextElementString().substr(0,5) != "patch" && input.PeakNextElementString() != endKeyword && input.PeakNextElementString().at(0) != 'T' && input.PeakNextElementString().at(0) != 't') { auto newMutPosition = input.GetNextElementInt(); if (T56_info.size() != 0 && T56_info.back() >= newMutPosition) { std::cout << "In --indTypes, for individualType '" << IndividualTypeName << "'. When reading info about T5 loci, got the mutation position " << newMutPosition << " after mutPosition " << T56_info.back() << ". Please make sure that the info value are strictly increased. Note that for T5 loci, you are expected to indicate mutation positions (unlike for T1 loci that expects T1_nbLoci boolean values).\n"; abort(); } T56_info.push_back(newMutPosition); } } else if (TT == "T7" || TT == "t7") { std::cout << "In --indTypes, received info about type of locus T7. Sorry, --indIni is currently not able to initialize the T7 loci.\n"; abort(); } else { std::cout << "In --indTypes, received unknown type of locus (" << TT << "). Please if you want to indicate locus of type 1, write either T1 or t1. Same logic apply to other type of loci.\nMaybe you tried to write 'haplo1' but wrote 'Haplo1' or something like that!\nMaybe, did inputted the correct number of values for a given type of loci (give the number of loci for this type at option --Loci (--L))\n"; abort(); } } // Security if (Gmap.T1_nbLoci && !receivedT1_info) { std::cout << "In --indTypes, for individualType "<< IndividualTypeName<< " expected info for T1 loci but did not receive it!\n"; abort(); } if (Gmap.T2_nbLoci && !receivedT2_info) { std::cout << "In --indTypes, for individualType "<< IndividualTypeName<< " expected info for T2 loci but did not receive it!\n"; abort(); } if (Gmap.T3_nbLoci && !receivedT3_info) { std::cout << "In --indTypes, for individualType "<< IndividualTypeName<< " expected info for T3 loci but did not receive it!\n"; abort(); } if (Gmap.T4_nbLoci && !receivedT4_info) { std::cout << "In --indTypes, for individualType "<< IndividualTypeName<< " expected info for T4 loci but did not receive it!\n"; std::cout << "Note btw that you cannot specify what mutations the haplotype is carrying for the T4 loci as the mutations are placed on the tree. You can only tell what ID the haplotype has (that is its position in the tree).\n"; abort(); } if (Gmap.T56_nbLoci && !receivedT56_info) { std::cout << "In --indTypes, for individualType "<< IndividualTypeName<< " expected info for T56 (aka T5; aka T6) loci but did not receive it!\n"; abort(); } assert(T1_info.size() == Gmap.T1_nbChars); assert(T2_info.size() == Gmap.T2_nbLoci); return Haplotype(T1_info, T2_info, T3_info, T4ID, T56_info); } void SpeciesSpecificParameters::readRedefIndTypes(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); return; } while( input.IsThereMoreToRead() ) { // Expecting 'redef' { auto x = input.GetNextElementString(); if (x != "redef") { std::cout << "For option --redefIndTypes, expected keyword 'redef' but received "<<x<<" instead.\n"; abort(); } } // Name of individual type to modify { auto x = input.GetNextElementString(); bool foundIt = false; for (auto it = individualTypes.begin() ; it != individualTypes.end() ;++it) { if (it->first == x) { foundIt = true; break; } } if (!foundIt) { std::cout << "For option --redefIndTypes, received a individual type named "<<x<<" but SimBit could not find any previously defined individual types with the same name given in option --indTypes.\n"; abort(); } redefIndTypes_types.push_back(x); } // Get haplo to modify std::string haploToModify = input.GetNextElementString(); if (haploToModify != "haplo0" && haploToModify != "haplo1" && haploToModify != "bothHaplo") { std::cout << "For option --redefIndTypes, expected keyword 'haplo0', 'haplo1' or 'bothHaplo' (indicating what haplotype to redefine) but received "<<haploToModify<<" instead.\n"; abort(); } // Expecting 'at' { auto x = input.GetNextElementString(); if (x != "at") { std::cout << "For option --redefIndTypes, expected keyword 'at' but received "<<x<<" instead.\n"; abort(); } } // Generation { auto x = input.GetNextElementInt(); if (x <= 0 || x > GP->nbGenerations) { std::cout << "For option --redefIndTypes, received a time value that is either not strictly positive or greater than the total number of generations. Received " << x << ".\n"; abort(); } redefIndTypes_times.push_back(x); } // Expecting 'basedOn' { auto x = input.GetNextElementString(); if (x != "basedOn") { std::cout << "For option --redefIndTypes, expected keyword 'basedOn' but received "<<x<<" instead.\n"; abort(); } } // definition of what haplotpes to copy int patch; int ind; std::string haplo; { int generation_index = std::upper_bound(GP->__GenerationChange.begin(), GP->__GenerationChange.end(), redefIndTypes_times.back()) - GP->__GenerationChange.begin() - 1; patch = input.GetNextElementInt(); auto currentPatchNumber = GP->__PatchNumber[generation_index]; if (patch < 0 || patch >= currentPatchNumber) { std::cout << "For option --redefIndTypes, got patch index " << patch << " at generation " << redefIndTypes_times.back() << ". It appears that at this generation, there are only " << currentPatchNumber << " patches in the world. As a reminder, the patch index is zero-based counting and can therefore not equal the number of patches.\n"; abort(); } ind = input.GetNextElementInt(); auto capacity = SSP->__patchCapacity[generation_index][patch]; if (patch < 0 || patch >= capacity) { std::cout << "For option --redefIndTypes, got individual index " << ind << " in patch index " << patch << " at generation " << redefIndTypes_times.back() << ". It appears that at this generation, this patch has a carrying capacity of " << capacity << " only.\n"; abort(); } haplo = input.GetNextElementString(); if (haplo != "haplo0" && haplo != "haplo1" && haplo != "bothHaplo") { std::cout << "For option --redefIndTypes, expected keywords 'haplo0', 'haplo1' or 'bothHaplo' for the haplotypes the redefinition is based on (after keyword 'basedOn').\n"; abort(); } if (haplo == "bothHaplo" && haploToModify != "bothHaplo") { std::cout << "For option --redefIndTypes, redefining indType " << redefIndTypes_types.back() << " at generation " << redefIndTypes_times.back() << ". You indicated that the redefinition must based based on both haplotypes of individual " << ind << " in patch " << patch << " but to set only one haplotype (you used keyword '" << haploToModify << "') in the individual type. If you base your redefinition on two haplotypes, you need to modify two haplotypes (use 'bothHaplo' for both the indType to redefine and the haplotype you base redefinition on.\n"; abort(); } } // Set how to redefine things if (haplo == "bothHaplo") { assert(haploToModify == "bothHaplo"); redefIndTypes_whereFromInfo.push_back({{patch, ind, 0},{patch, ind, 1}}); } else { std::array<int, 3> haploArray; if (haplo == "haplo0") { haploArray = {patch, ind, 0}; } else { assert(haplo == "haplo1"); haploArray = {patch, ind, 1}; } if (haploToModify == "haplo0") { redefIndTypes_whereFromInfo.push_back({haploArray,{-1,-1,-1}}); } else if (haploToModify == "haplo1") { redefIndTypes_whereFromInfo.push_back({{-1,-1,-1},haploArray}); } else { assert(haploToModify == "bothHaplo"); redefIndTypes_whereFromInfo.push_back({haploArray,haploArray}); } } } // Finished reading input // Reorder stuff to go in decreasing generation order assert(redefIndTypes_times.size() == redefIndTypes_types.size()); assert(redefIndTypes_times.size() == redefIndTypes_whereFromInfo.size()); if (redefIndTypes_times.size() >= 2) { auto order = reverse_sort_indexes(redefIndTypes_times); reorderNoAssertions(redefIndTypes_times, order); reorderNoAssertions(redefIndTypes_types, order); reorderNoAssertions(redefIndTypes_whereFromInfo, order); assert(redefIndTypes_times[0] >= redefIndTypes_times[1]); } } void SpeciesSpecificParameters::redefineIndividualTypesIfNeeded(Pop& pop) { while (redefIndTypes_times.size() && redefIndTypes_times.back() == GP->CurrentGeneration) { auto indTypeName = redefIndTypes_types.back(); auto info = redefIndTypes_whereFromInfo.back(); redefIndTypes_times.pop_back(); redefIndTypes_types.pop_back(); redefIndTypes_whereFromInfo.pop_back(); auto indTypeIt = SSP->individualTypes.find(indTypeName); assert(indTypeIt != SSP->individualTypes.end()); Individual& indType = indTypeIt->second; // Zeroth (first) haplotype if (info.first[0] == -1) { assert(info.first[1] == -1); assert(info.first[2] == -1); } else { auto patchi = info.first[0]; auto indi = info.first[1]; auto haploi = info.first[2]; assert(patchi >= 0 && patchi < GP->PatchNumber); assert(indi >= 0 && indi < patchCapacity[patchi]); assert(haploi == 0 || haploi == 1); if (indi < patchSize[patchi]) { indType.getHaplo(0) = pop.getPatch(patchi).getInd(indi).getHaplo(haploi); } } // first (second) haplotype if (info.second[0] == -1) { assert(info.second[1] == -1); assert(info.second[2] == -1); } else { auto patchi = info.second[0]; auto indi = info.second[1]; auto haploi = info.second[2]; assert(patchi >= 0 && patchi < GP->PatchNumber); assert(indi >= 0 && indi < patchCapacity[patchi]); assert(haploi == 0 || haploi == 1); if (indi < patchSize[patchi]) { indType.getHaplo(1) = pop.getPatch(patchi).getInd(indi).getHaplo(haploi); } } } assert(GP->CurrentGeneration >= 0); if (redefIndTypes_times.size()) assert(redefIndTypes_times.back() > GP->CurrentGeneration); } void SpeciesSpecificParameters::readIndividualTypes(InputReader& input) { IsThereSelection(); // Need that to initialize individual types setFromLocusToFitnessMapIndex(); // Need that to initialize individual types // Default if (input.PeakNextElementString() == "default") { input.skipElement(); return; } // Read and build individual types while (input.IsThereMoreToRead()) { if (input.PeakNextElementString() != "ind") { std::cout << "In --indIni, expected keyword 'ind' but instead received '" << input.PeakNextElementString() << "'\n"; abort(); } input.skipElement(); // skipping "ind" // Get name and make sure it is a new name auto IndividualTypeName = input.GetNextElementString(); if (individualTypes.find(IndividualTypeName) != individualTypes.end()) { std::cout << "In --indIni, you start a new individualType (with keyword 'ind') and you name it " << IndividualTypeName << ". This name has already been used by a previous IndiivdualType. Please use unique names! Just call them with number if you are lazy to give them names!\n"; abort(); } // Get Haplotypes Haplotype haplo0; Haplotype haplo1; if (input.PeakNextElementString() == "bothHaplo") { haplo0 = getHaplotypeForIndividualType(input, 1, IndividualTypeName); // second argument is 1 so that it stops at keyword 'ind' haplo1 = haplo0; } else { haplo0 = getHaplotypeForIndividualType(input, 0, IndividualTypeName); haplo1 = getHaplotypeForIndividualType(input, 1, IndividualTypeName); } // Add IndividualType individualTypes[IndividualTypeName] = Individual(haplo0, haplo1); } } void SpeciesSpecificParameters::readIndividualInitialization(InputReader& input) { // Set isIndividualInitialization to inform other initialization option that this one has been used if (input.PeakNextElementString() == "default") { input.skipElement(); this->isIndividualInitialization = false; return; } else { this->isIndividualInitialization = true; } // security if (individualTypes.size() == 0) { std::cout << "You explicitely used the option '--indIni (--IndividualInitialization)', but no individual types have been defined (with option --indTypes).\n"; abort(); } //////////////////////////// // Assign individual type // //////////////////////////// individualTypesForInitialization.resize(GP->PatchNumber); for (unsigned patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index) { std::string patchKeyword = "patch" + std::to_string(patch_index); if (input.PeakNextElementString() != patchKeyword) { std::cout << "In --indIni (--IndividualInitialization), expected keyword "<<patchKeyword<< " but got " << input.PeakNextElementString() << " instead\n"; abort(); } input.skipElement(); // skipping patch<number> unsigned ind_index = 0; while (ind_index < this->patchSize[patch_index]) { auto IndividualTypeName = input.GetNextElementString(); if (individualTypes.find(IndividualTypeName) == individualTypes.end()) { std::cout << "In --indIni (--IndividualInitialization), asking for individual type " << IndividualTypeName << " in patch " << patch_index << " but individual type " << IndividualTypeName << " has not been defined previously. It is probably caused by a typo when naming individual types.\n"; abort(); } unsigned howMany = input.GetNextElementInt(); // security ind_index += howMany; if (ind_index > this->patchSize[patch_index]) { std::cout << "In --indIni (--IndividualInitialization), for patch " << patch_index << " received more individuals than was set as initial patch size (initial patch size for this patch is " << this->patchSize[patch_index] << "). Note that if you have not specified the initial patch size yourself, then it is set to carrying capacity of this patch at generation 0.\n"; abort(); } for (unsigned howMany_index = 0 ; howMany_index < howMany ; ++howMany_index ) { individualTypesForInitialization[patch_index].push_back(IndividualTypeName); } } assert(ind_index == this->patchSize[patch_index]); assert(individualTypesForInitialization[patch_index].size() == this->patchSize[patch_index]); } } void SpeciesSpecificParameters::readT1_Initial_AlleleFreqs(InputReader& input) { #ifdef DEBUG std::cout << "For option --T1_Initial_AlleleFreqs, the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { if (this->Gmap.T1_nbLoci != 0) { std::cout << "For option --T1_Initial_AlleleFreqs, received 'NA' however there are T1 loci as indiciated by --L (--Loci) (this->Gmap.T1_nbLoci = "<<this->Gmap.T1_nbLoci<<")" << "\n"; abort(); } input.skipElement(); } else { std::string Mode = input.GetNextElementString(); if (Mode != "default" && isIndividualInitialization) { std::cout << "You cannot use both --individualInitialization (--indIni) and --T1_Initial_AlleleFreqs\n"; abort(); } this->T1_Initial_AlleleFreqs_AllZeros = false; // Set to true laster if received "AllZeros" this->T1_Initial_AlleleFreqs_AllOnes = false; // Set to true laster if received "AllOnes" if (Mode.compare("freqs") == 0) { for (int patch_index = 0 ; patch_index < GP->__PatchNumber[0] ; ++patch_index) { int nbRepeatsLeft = 0; double freq; std::vector<double> OneLine; for (int T1Locus = 0 ; T1Locus < this->Gmap.T1_nbLoci ; T1Locus++) { if (nbRepeatsLeft == 0 && input.PeakNextElementString() == "R") { input.skipElement(); freq = input.GetNextElementDouble(); nbRepeatsLeft = input.GetNextElementInt(); if (nbRepeatsLeft < 0) { std::cout << "In '--T1_Initial_AlleleFreqs', received a number of repeats lower than zero. Number of repeats received is " << nbRepeatsLeft << "\n"; abort(); } } if (nbRepeatsLeft == 0) { freq = input.GetNextElementDouble(); } else { nbRepeatsLeft--; } if (freq < 0.0 || freq > 1.0) { std::cout << "In '--T1_Initial_AlleleFreqs', received an impossible allele frequency. Received '" << freq << "'\n"; abort(); } //std::cout << "T1Locus = " << T1Locus << " x = " << x << " nbRepeatsLeft = "<<nbRepeatsLeft<<"\n"; OneLine.push_back(freq); } assert(nbRepeatsLeft >= 0); if (nbRepeatsLeft != 0) { std::cout << "In '--T1_Initial_AlleleFreqs', too many values received!'\n"; abort(); } assert(OneLine.size() == this->Gmap.T1_nbLoci); this->T1_Initial_AlleleFreqs.push_back(OneLine); } } else if (Mode.compare("Shift")==0) { int shiftPosition = input.GetNextElementInt(); if (shiftPosition < 0 || shiftPosition > GP->__PatchNumber[0]) { std::cout << "In '--T1_Initial_AlleleFreqs', received an impossible shiftPosition. Received '" << shiftPosition << ". For information, the simulation is starting with " << GP->__PatchNumber[0] << " as indicated in option '--PN (--PatchNumber)'\n"; abort(); } for (int patch_index = 0 ; patch_index < GP->__PatchNumber[0] ; ++patch_index) { std::vector<double> line; for (int T1Locus = 0 ; T1Locus < this->Gmap.T1_nbLoci ; T1Locus++) { if (patch_index < shiftPosition) { line.push_back(0.0); } else { line.push_back(1.0); } } assert(line.size() == this->Gmap.T1_nbLoci); this->T1_Initial_AlleleFreqs.push_back(line); } } else if (Mode.compare("AllZeros") == 0 || Mode.compare("default") == 0) { this->T1_Initial_AlleleFreqs_AllZeros = true; } else if (Mode.compare("AllOnes") == 0) { this->T1_Initial_AlleleFreqs_AllOnes = true; } else { std::cout << "Sorry, for '--T1_Initial_AlleleFreqs', the Mode " << Mode << " has not been implemented yet. Only Modes 'freqs' (note that 'freqs' was previously called 'A'), 'AllZeros', 'AllOnes' and 'Shift' are accepted for the moment."; abort(); } } // Security check if (!this->T1_Initial_AlleleFreqs_AllZeros && !this->T1_Initial_AlleleFreqs_AllOnes) { assert(this->T1_Initial_AlleleFreqs.size() == GP->__PatchNumber[0]); for (int patch_index = 0 ; patch_index < GP->__PatchNumber[0] ; ++patch_index) { assert(this->T1_Initial_AlleleFreqs[patch_index].size() == this->Gmap.T1_nbLoci); } } if (!T1_Initial_AlleleFreqs_AllZeros && !T1_Initial_AlleleFreqs_AllOnes) { funkyMathForQuasiRandomT1AllFreqInitialization.resize(GP->PatchNumber); for (int patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index) { funkyMathForQuasiRandomT1AllFreqInitialization[patch_index].reserve(Gmap.T1_nbLoci); for (int locus = 0 ; locus < Gmap.T1_nbLoci ; ++locus) { funkyMathForQuasiRandomT1AllFreqInitialization[patch_index].push_back( (int)(((long)locus*103) % (long)(2 * SSP->TotalpatchCapacity)) ); } } } } void SpeciesSpecificParameters::readT56_toggleMutsEveryNGeneration(InputReader& input) { T56_toggleMutsEveryNGeneration = input.GetNextElementInt(); if (T56_toggleMutsEveryNGeneration <= 0) { T56_toggleMutsEveryNGeneration_nextGeneration = -1; } else { T56_toggleMutsEveryNGeneration_nextGeneration = T56_toggleMutsEveryNGeneration; } } void SpeciesSpecificParameters::readT56_Initial_AlleleFreqs(InputReader& input) { #ifdef DEBUG std::cout << "For option --T5_Initial_AlleleFreqs, the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "default") { input.skipElement(); this->T56_Initial_AlleleFreqs_AllZeros = true; this->T56_Initial_AlleleFreqs_AllOnes = false; } else if (input.PeakNextElementString() == "NA") { if (this->Gmap.T56_nbLoci != 0) { std::cout << "For option --T5_Initial_AlleleFreqs, received 'NA' however there are T5 loci as indiciated by --L (--Loci) (this->Gmap.T5_nbLoci = "<<this->Gmap.T56_nbLoci<<")" << "\n"; abort(); } input.skipElement(); } else { std::string Mode; Mode = input.GetNextElementString(); if (Mode != "default" && isIndividualInitialization) { std::cout << "You cannot use both --individualInitialization (--indIni) and --T56_Initial_AlleleFreqs\n"; abort(); } this->T56_Initial_AlleleFreqs_AllZeros = false; // Set to true later if received "AllZeros" this->T56_Initial_AlleleFreqs_AllOnes = false; // Set to true later if received "AllOnes" if (Mode.compare("A") == 0) { for (int patch_index = 0 ; patch_index < GP->__PatchNumber[0] ; ++patch_index) { int nbRepeatsLeft = 0; double freq; std::vector<double> OneLine; for (int T5Locus = 0 ; T5Locus < this->Gmap.T56_nbLoci ; T5Locus++) { if (nbRepeatsLeft == 0 && input.PeakNextElementString() == "R") { input.skipElement(); freq = input.GetNextElementDouble(); nbRepeatsLeft = input.GetNextElementInt(); if (nbRepeatsLeft < 0) { std::cout << "In '--T56_Initial_AlleleFreqs', received a number of repeats lower than zero. Number of repeats received is " << nbRepeatsLeft << "\n"; abort(); } } if (nbRepeatsLeft == 0) { freq = input.GetNextElementDouble(); } else { nbRepeatsLeft--; } if (freq < 0.0 || freq > 1.0) { std::cout << "In '--T56_Initial_AlleleFreqs', received an impossible allele frequency. Received '" << freq << "'\n"; abort(); } //std::cout << "T1Locus = " << T1Locus << " x = " << x << " nbRepeatsLeft = "<<nbRepeatsLeft<<"\n"; OneLine.push_back(freq); } assert(nbRepeatsLeft >= 0); if (nbRepeatsLeft != 0) { std::cout << "In '--T1_Initial_AlleleFreqs', too many values received!'\n"; abort(); } assert(OneLine.size() == this->Gmap.T56_nbLoci); this->T56_Initial_AlleleFreqs.push_back(OneLine); } } else if (Mode.compare("Shift")==0) { int shiftPosition = input.GetNextElementInt(); if (shiftPosition < 0 || shiftPosition > GP->__PatchNumber[0]) { std::cout << "In '--T56_Initial_AlleleFreqs', received an impossible shiftPosition. Received '" << shiftPosition << ". For information, the simulation is starting with " << GP->__PatchNumber[0] << " as indicated in option '--PN (--PatchNumber)'\n"; abort(); } for (int patch_index = 0 ; patch_index < GP->__PatchNumber[0] ; ++patch_index) { std::vector<double> line; for (int T5Locus = 0 ; T5Locus < this->Gmap.T56_nbLoci ; T5Locus++) { if (patch_index < shiftPosition) { line.push_back(0.0); } else { line.push_back(1.0); } } assert(line.size() == this->Gmap.T56_nbLoci); this->T56_Initial_AlleleFreqs.push_back(line); } } else if (Mode.compare("AllZeros") == 0 || Mode.compare("default") == 0) { this->T56_Initial_AlleleFreqs_AllZeros = true; } else if (Mode.compare("AllOnes") == 0) { std::cout << "Sorry the option AllOnes is currently not available for T56_Initial_AlleleFreqs.\n"; abort(); this->T56_Initial_AlleleFreqs_AllOnes = true; } else { std::cout << "Sorry, for '--T56_Initial_AlleleFreqs', the Mode " << Mode << " has not been implemented yet. Only Modes 'A', 'AllZeros', 'AllOnes' and 'Shift' are accepted for the moment."; abort(); } } // Security check if (!this->T56_Initial_AlleleFreqs_AllZeros && !this->T56_Initial_AlleleFreqs_AllOnes) { assert(this->T56_Initial_AlleleFreqs.size() == GP->__PatchNumber[0]); for (int patch_index = 0 ; patch_index < GP->__PatchNumber[0] ; ++patch_index) { assert(this->T56_Initial_AlleleFreqs[patch_index].size() == this->Gmap.T56_nbLoci); } } // Initialize flipped if T6 if (SSP->Gmap.T6ntrl_nbLoci) { T6ntrl_flipped = CompressedSortedDeque(SSP->Gmap.T6ntrl_nbLoci); } /*if (T56sel_compress && SSP->Gmap.T6sel_nbLoci) { T6sel_flipped = CompressedSortedDeque(SSP->Gmap.T6sel_nbLoci); }*/ // If all fixed if (T56_Initial_AlleleFreqs_AllOnes) { if (Gmap.isT56ntrlCompress) { for (auto locus = 0 ; locus < this->Gmap.T6ntrl_nbLoci ; ++locus) T6ntrl_flipped.push_back(locus); } else { for (auto locus = 0 ; locus < this->Gmap.T5ntrl_nbLoci ; ++locus) T5ntrl_flipped.push_back(locus); } /*if (T56sel_compress) { for (auto locus = 0 ; locus < this->Gmap.T6sel_nbLoci ; ++locus) T6sel_flipped.push_back(locus); } else { for (auto locus = 0 ; locus < this->Gmap.T5sel_nbLoci ; ++locus) T5sel_flipped.push_back(locus); }*/ } // The following sounds awefully sily but it is just to ensure that begin and end are not nullptr (so as to not give nullptr to ZipIterator<std::vector<uint32_t>, std::vector<uint32_t>::iterator>). It probably serves no purpose though! if (T5ntrl_flipped.size() == 0) { T5ntrl_flipped.push_back(0); T5ntrl_flipped.resize(0); } /*if (T5sel_flipped.size() == 0) { T5sel_flipped.push_back(0); T5sel_flipped.resize(0); }*/ if (!T56_Initial_AlleleFreqs_AllZeros && !T56_Initial_AlleleFreqs_AllOnes) { funkyMathForQuasiRandomT56AllFreqInitialization.resize(GP->PatchNumber); for (int patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index) { funkyMathForQuasiRandomT56AllFreqInitialization[patch_index].reserve(Gmap.T56_nbLoci); for (int locus = 0 ; locus < Gmap.T56_nbLoci ; ++locus) { funkyMathForQuasiRandomT56AllFreqInitialization[patch_index].push_back( (int)(((long)locus*107) % (long)(2 * SSP->TotalpatchCapacity)) ); } } } } void SpeciesSpecificParameters::readSelectionOn(InputReader& input) { #ifdef DEBUG std::cout << "For option '--selectionOn', the std::string that is read is: " << input.print() << std::endl; #endif std::string s = input.GetNextElementString(); if (s == "fertility") { selectionOn = 0; } else if (s == "viability") { selectionOn = 1; if (fecundityForFitnessOfOne != -1) { std::cout << "You asked for fecundityForFitnessOfOne different from -1 (" << fecundityForFitnessOfOne << ") and for selection on viability only. Sorry, variation of patch size must be computed from selection on fertility and therefore both can not be simulated simultaneously.\n"; abort(); } } else if (s == "both" || s == "fertilityAndViability") { selectionOn = 2; } else { std::cout << "For option '--selectionOn', expected either 'fertility' (which should be the default), 'viability' or 'fertilityAndViability' (aka. 'both'). Instead it received '" << s << "'.\n"; abort(); } } void SpeciesSpecificParameters::readPopGrowthModel(InputReader& input) { #ifdef DEBUG std::cout << "For option '--popGrowthModel', the std::string that is read is: " << input.print() << std::endl; #endif bool isAnyLogisticModel = false;// To test user input this->__growthK.resize(GP->__GenerationChange.size()); for ( int generation_index = 0; generation_index < GP->__GenerationChange.size() ; generation_index++) { (void) input.GetNextGenerationMarker(generation_index); int currentPatchNumber = GP->__PatchNumber[generation_index]; this->__growthK[generation_index].resize(currentPatchNumber); std::string Mode = input.GetNextElementString(); if (Mode == "A") { for (int patch_index = 0 ; patch_index < currentPatchNumber ; patch_index++) { int x; std::string s = input.PeakNextElementString(); if (s == "logistic") { input.skipElement(); x = -2; } else if (s == "exponential") { input.skipElement(); x = -1; } else { x = input.GetNextElementInt(); if (x < -2) { std::cout << "In --popGrowthModel, received a negative K value different from -1 and -2 (-1 is aka 'exponential'; -2 (aka. 'logistic') means logistic with the carrying capacity as the growthK; k value received = "<<x << ")\n"; abort(); } } if (x != -1) isAnyLogisticModel = true; this->__growthK[generation_index][patch_index] = x; } } else if (Mode == "unif") { std::string s = input.PeakNextElementString(); int x; if (s == "logistic") { input.skipElement(); x = -2; } else if (s == "exponential") { input.skipElement(); x = -1; } else { x = input.GetNextElementInt(); if (x < -2) { std::cout << "In --popGrowthModel, received a negative K value different from -1 and -2 (-1 is aka 'exponential'; -2 (aka. 'logistic') means logistic with the carrying capacity as the growthK; k value received = "<<x << ")\n"; abort(); } } if (x != -1) isAnyLogisticModel = true; for (int patch_index = 0 ; patch_index < currentPatchNumber ; patch_index++) { assert(this->__patchCapacity[generation_index][patch_index] >= 0); this->__growthK[generation_index][patch_index] = x; } } else { std::cout << "In --popGrowthModel, received " << Mode << " for mode. Only modes 'A' and 'unif' are recognized. Sorry\n"; abort(); } } this->growthK = this->__growthK[0]; // Test user input if (!isAnyLogisticModel) { // Then make sure user did not specify competitiono matrix for (int speciesIndexA = 0 ; speciesIndexA < GP->nbSpecies ; ++speciesIndexA) { for (int speciesIndexB = 0 ; speciesIndexB < GP->nbSpecies ; ++speciesIndexB) { if (speciesIndexA == speciesIndexB) { assert(GP->speciesCompetition[speciesIndexA][speciesIndexB] == 1.0); } else { if (GP->speciesCompetition[speciesIndexA][speciesIndexB] != 0.0) { std::cout << "When received --popGrowthModel, some values differ from -1 (-1 is aka 'exponential' in the input). So far, so good! The problem is that at the option --eco you specified a competition matrix that does have some non-zero values on the off-diagonal. Competition (unlike 'interaction') is computed through the logistic model and therefore such non-zeros off the diagonal cannot be simulated if all of the growthK are set to -1 (aka. exponential). I hope that makes sense to you! So either, remove the non-zeros values from the off-diagonal of the competition matrix or explicitely specify a logistic growth model.\n"; abort(); } } } } } } void SpeciesSpecificParameters::readHabitats(InputReader& input) { #ifdef DEBUG std::cout << "For option '--H (--Habitats)', the std::string that is read is: " << input.print() << std::endl; #endif assert(GP->__GenerationChange.size() > 0); for ( int generation_index = 0; generation_index < GP->__GenerationChange.size() ; generation_index++) { int Generation = input.GetNextGenerationMarker(generation_index); //std::cout << "Generation = " << Generation << "\n"; std::string Mode = input.GetNextElementString(); //std::cout << "Mode = " << Mode << "\n"; std::vector<int> ForASingleGeneration; if (Mode.compare("unif")==0) { int UniqueHabitat = input.GetNextElementInt(); assert(GP->__PatchNumber.size() > generation_index); for (int patch_index = 0 ; patch_index < GP->__PatchNumber[generation_index] ; ++patch_index) { ForASingleGeneration.push_back(UniqueHabitat); } this->__MaxHabitat.push_back(UniqueHabitat); } else if (Mode.compare("A")==0) { assert(GP->__PatchNumber[generation_index] > 0); int max = 0; assert(GP->__PatchNumber.size() > generation_index); for (int patch_index = 0 ; patch_index < GP->__PatchNumber[generation_index] ; ++patch_index) { int h = input.GetNextElementInt(); if (max < h) {max = h;} ForASingleGeneration.push_back(h); } this->__MaxHabitat.push_back(max); } else { std::cout << "In '--H (--Habitats)', at generation " << Generation << ", Mode received is " << Mode << ". Sorry, only Modes 'unif' and 'A' are implemented for the moment.\n"; abort(); } assert(ForASingleGeneration.size() == GP->__PatchNumber[generation_index]); // Assign to __Habitats this->__Habitats.push_back(ForASingleGeneration); } assert(this->__Habitats.size() == GP->__GenerationChange.size()); assert(this->__Habitats.size() == this->__MaxHabitat.size()); // flatten, sort and remove duplicates from the matrix to 1) get the maximum number and 2) make sure no habitat index is missing. std::vector<int> flat; for (int generation_index = 0 ; generation_index < GP->__GenerationChange.size() ; generation_index++) { auto& ForASingleGeneration = this->__Habitats[generation_index]; assert(ForASingleGeneration.size() == GP->__PatchNumber[generation_index]); for (int patch_index = 0 ; patch_index < GP->__PatchNumber[generation_index] ; patch_index++) { flat.push_back(ForASingleGeneration[patch_index]); } } std::sort(flat.begin(), flat.end()); flat.erase(std::unique(flat.begin(), flat.end()), flat.end()); assert(this->__MaxHabitat.size() > 0); assert(this->__Habitats.size() > 0); this->MaxHabitat = this->__MaxHabitat[0]; this->Habitats = this->__Habitats[0]; if (flat[0] != 0) { std::cout << "In option '--H (--Habitats)', the lowest element received is " << flat[0] << ". The lowest element has to be 0 (zero based counting). Please also note that one cannot input an habitat index of n if all [0,n-1] have have not been included.\n"; abort(); } // 2) make sure no habitat index is missing. int previous = flat[0] - 1; for (int current : flat) { if (previous + 1 != current) { std::cout << "In option '--H (--Habitats)', you included the index " << current << " while the previous index has not been included. The last index included was " << previous << ". Please also note that you used. Please note --Habitats use zero based counting.\n"; abort(); } previous = current; } // set MaxEverHabitat MaxEverHabitat = 0; assert(MaxHabitat >= 0); assert(__MaxHabitat.size() > 0); assert(__MaxHabitat[0] == MaxHabitat); for (auto& MaxHabitatInSpecificGenerationRange : __MaxHabitat) { assert(MaxHabitatInSpecificGenerationRange >= 0); if (MaxHabitatInSpecificGenerationRange > MaxEverHabitat) MaxEverHabitat = MaxHabitatInSpecificGenerationRange; } assert(MaxEverHabitat >= 0); } void SpeciesSpecificParameters::readpatchCapacity(InputReader& input) { #ifdef DEBUG std::cout << "For option '--N (--patchCapacity)', the std::string that is read is: " << input.print() << std::endl; #endif this->TotalpatchCapacity = 0; maxEverpatchCapacity.resize(GP->maxEverPatchNumber,-1); for (int generation_index = 0 ; generation_index < GP->__GenerationChange.size() ; generation_index++) { (void) input.GetNextGenerationMarker(generation_index); int CurrentPatchNumber = GP->__PatchNumber[generation_index]; assert(CurrentPatchNumber <= GP->maxEverPatchNumber); std::string Mode = input.GetNextElementString(); std::vector<int> patchCapacity_line; // Will contain a single entry (for one interval of time) that will be pushed to '__patchCapacity' if (Mode.compare("A")==0) { for (int patch_index = 0 ; patch_index < CurrentPatchNumber; patch_index++) { int PC = input.GetNextElementInt(); if (PC < 0) { std::cout << "For option 'patchCapacity', received a patch capacity that is negative for the patch index "<<patch_index<<". Value received is "<<PC<<"."<< std::endl; abort(); } if (generation_index == 0) this->TotalpatchCapacity += PC; patchCapacity_line.push_back(PC); } } else if (Mode.compare("unif")==0) { int uniquepatchCapacity = input.GetNextElementInt(); if (uniquepatchCapacity < 0) { std::cout << "For option 'patchCapacity', received a unique patch capacity that is negative. Value received is "<<uniquepatchCapacity<<"."<< std::endl; abort(); } for (int patch_index=0 ; patch_index < CurrentPatchNumber ; ++patch_index) { if (generation_index == 0) this->TotalpatchCapacity += uniquepatchCapacity; patchCapacity_line.push_back(uniquepatchCapacity); } } else { std::cout << "Sorry, for option 'patchCapacity', only Modes 'A' and 'unif' are implemented for the moment. Mode received is " << Mode << std::endl; abort(); } for (int patch_index=0 ; patch_index < CurrentPatchNumber ; ++patch_index) { maxEverpatchCapacity[patch_index] = std::max(maxEverpatchCapacity[patch_index], patchCapacity_line[patch_index]); } this->__patchCapacity.push_back(patchCapacity_line); if (generation_index == 0) { if (this->TotalpatchCapacity <= 0) { std::cout << "The total patch capacity over all patches for species " << this->speciesName << " is " << this->TotalpatchCapacity << ". Nothing can be simulated.\n"; abort(); } } } assert(this->__patchCapacity.size() == GP->__GenerationChange.size()); this->patchCapacity = this->__patchCapacity[0]; for (int patch_index=0 ; patch_index < GP->maxEverPatchNumber ; ++patch_index) { if (maxEverpatchCapacity[patch_index] == 0) { std::cout << "patch_index " << patch_index << " never gets a carrying capacity greater than " << 0 << ". This is a weird unseless patch!\n"; abort(); } } } void SpeciesSpecificParameters::readnbSubGenerations(InputReader& input) { #ifdef DEBUG std::cout << "For option '--nbSubGens (--nbSubGenerations)', the std::string that is read is: " << input.print() << std::endl; #endif this->nbSubGenerationsPerGeneration = input.GetNextElementInt(); if (this->nbSubGenerationsPerGeneration < 1) { std::cout << "In option '--nbSubGens (--nbSubGenerations)', for species " << this->speciesName << " received " << this->nbSubGenerationsPerGeneration << ". The number of subGeneration must be equal or greater than 1.\n"; abort(); } } void SpeciesSpecificParameters::readT1_EpistaticFitnessEffects(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T1_epistasis (--T1_EpistaticFitnessEffects)', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { if (this->Gmap.T1_nbLoci != 0) { std::cout << "In option '--T1_epistasis (--T1_EpistaticFitnessEffects)', for species "<<this->speciesName<<", received 'NA' but there are T1 loci as indiciated in --L (--Loci) (this->Gmap.T1_nbLoci = "<<this->Gmap.T1_nbLoci<<").\n"; abort(); } input.skipElement(); } else { for (int habitat = 0; habitat <= this->MaxEverHabitat ; habitat++) { input.GetNextHabitatMarker(habitat); // Get info for this habitat std::vector<std::vector<T1_locusDescription>> LociIndices_ForASingleHabitat; std::vector<std::vector<fitnesstype>> FitnessEffects_ForASingleHabitat; while (input.IsThereMoreToRead() && input.PeakNextElementString().at(0) != '@') { // Initialize vector to fill std::vector<T1_locusDescription> LociIndices_ForASingleGroupOfLoci; std::vector<fitnesstype> FitnessEffects_ForASingleGroupOfLoci; // 'loci' keyword if (input.PeakNextElementString() != "loci") { std::cout << "In option '--T1_epistasis (--T1_EpistaticFitnessEffects)', for species "<<this->speciesName<<", expected string 'loci' but received "<<input.PeakNextElementString()<<" instead.\n"; } input.skipElement(); // skip expectedString (set<number>) // Read interacting loci while (input.PeakNextElementString() != "fit") { int LocusPosition = input.GetNextElementInt(); if ( LocusPosition < 0 || LocusPosition >= this->Gmap.T1_nbLoci ) { std::cout << "In option '--T1_epistasis (--T1_EpistaticFitnessEffects)', received locus position "<<LocusPosition<<" (indicated for habitat " << habitat << " that is either lower than zero or greater or equal to the number of T1 sites (" << this->Gmap.T1_nbLoci <<"). As a reminder the first locus is the zeroth locus (zero based counting).\n"; abort(); } //std::cout << "LocusPosition = " << LocusPosition << "\n"; T1_locusDescription T1_locus(LocusPosition / EIGHT, LocusPosition % EIGHT, LocusPosition); LociIndices_ForASingleGroupOfLoci.push_back(T1_locus); } auto nbLociUnderEpistasis = LociIndices_ForASingleGroupOfLoci.size(); input.skipElement(); // skip "fit" if (nbLociUnderEpistasis <= 1) { std::cout << "In option '--T1_epistasis (--T1_EpistaticFitnessEffects)', received "<<nbLociUnderEpistasis<<" loci but it takes at least 2 loci to have an epistatic interaction.\n"; abort(); } // Read fitness effects /* SSP->T1_Epistasis_LociIndices[Habitat][0]. locus 1: 00 00 00 00 00 00 00 00 00 01 01 01 01 01 01 01 01 01 11 11 11 11 11 11 11 11 11 locus 2: 00 00 00 01 01 01 11 11 11 00 00 00 01 01 01 11 11 11 00 00 00 01 01 01 11 11 11 locus 3: 00 01 11 00 01 11 00 01 11 00 01 11 00 01 11 00 01 11 00 01 11 00 01 11 00 01 11 Index: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 */ int TotalNbFitnessesToIndicate = pow(3,nbLociUnderEpistasis); for (int i = 0 ; i < TotalNbFitnessesToIndicate; i++) { double fit = input.GetNextElementDouble(); if ( fit < 0.0) { std::cout << "In option '--T1_epistasis (--T1_EpistaticFitnessEffects)', the " << i << "th fitness value indicated after habitat " << habitat << "is either lower than zero. The fitness value indicated is " << fit << ".\n"; abort(); } FitnessEffects_ForASingleGroupOfLoci.push_back(fit); } // Push to "for a single habitat" LociIndices_ForASingleHabitat.push_back(LociIndices_ForASingleGroupOfLoci); FitnessEffects_ForASingleHabitat.push_back(FitnessEffects_ForASingleGroupOfLoci); } this->T1_Epistasis_LociIndices.push_back(LociIndices_ForASingleHabitat); this->T1_Epistasis_FitnessEffects.push_back(FitnessEffects_ForASingleHabitat); } // end of for habitat assert(this->T1_Epistasis_LociIndices.size() == this->MaxEverHabitat + 1); assert(this->T1_Epistasis_FitnessEffects.size() == this->MaxEverHabitat + 1); //get fitness value with this->FitnessEffects_ForASingleHabitat[habitat][groupOfLoci][fitnessValueIndex] } // end of if "NA" } void SpeciesSpecificParameters::readT56_FitnessEffects(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T5_FitnessEffects', the std::string that is read is: " << input.print() << std::endl; #endif // WATCH OUT: This option is read before --L. Only a quick screen of L has been done to set quickScreenAtL_T56_nbLoci assert(SSP != nullptr); this->T56_isMultiplicitySelection = false; char isMultfit = -1; // -1 is undefeined. 0 is false, 1 is true if (input.PeakNextElementString() == "NA") { if (this->quickScreenAtL_T56_nbLoci != 0) { std::cout << "In option '--T5_FitnessEffects', for species " << this->speciesName << ", received 'NA' but there are T5 loci as indiciated in --L (--Loci) (this->Gmap.T5_nbLoci = " << quickScreenAtL_T56_nbLoci << ").\n"; abort(); } isMultfit = 0; // whatever but not -1 input.skipElement(); } else { //std::cout << "this->MaxEverHabitat = "<<this->MaxEverHabitat << std::endl ; assert(this->MaxEverHabitat >= 0); std::string firstMode; for (int habitat = 0; habitat <= this->MaxEverHabitat ; habitat++) { (void) input.GetNextHabitatMarker(habitat); std::string Mode = input.GetNextElementString(); if ((Mode == "MultiplicityA" || Mode == "MultiplicityGamma" || Mode == "MultiplicityUnif" || Mode == "multfitA" || Mode == "multfitGamma" || Mode == "multfitUnif")) { isMultfit = 1; } else { isMultfit = 0; } if (habitat == 0) { firstMode = Mode; } else { bool wasFirstMultFit = !(Mode == "MultiplicityA" || Mode == "MultiplicityGamma" || Mode == "MultiplicityUnif" || Mode == "multfitA" || Mode == "multfitGamma" || Mode == "multfitUnif"); bool isCurrentMultFit = !(firstMode == "MultiplicityA" || firstMode == "MultiplicityGamma" || firstMode == "MultiplicityUnif" || firstMode == "multfitA" || firstMode == "multfitGamma" || firstMode == "multfitUnif"); if (wasFirstMultFit != isCurrentMultFit) { std::cout << "For --T5_fit, the Mode received for the zeroth habitat is '" << firstMode << "'. The Mode received for the " << habitat << "th habitat is '" << Mode << "'. In the current version, if one patch make the assumption of 'multfit', then all patches must make this assumption.\n"; abort(); } } std::vector<fitnesstype> ForASingleHabitat; if (Mode.compare("A")==0) { this->T56_isMultiplicitySelection = false; ForASingleHabitat.reserve(2 * this->quickScreenAtL_T56_nbLoci); for (int entry_index = 0 ; entry_index < (2 * this->quickScreenAtL_T56_nbLoci) ; entry_index++) { double fit = input.GetNextElementDouble(); if (fit < 0.0) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'A', one 'fit' value is lower than 0 ( is " << fit << " ).\n"; abort(); } if (isLocusConsideredNeutral(fit, T56_approximationForNtrl)) fit = 1.0; ForASingleHabitat.push_back(fit); } if (ForASingleHabitat.size() != 2 * this->quickScreenAtL_T56_nbLoci) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'A' " << ForASingleHabitat.size() << " have been received while " << 2 * (this->quickScreenAtL_T56_nbLoci) << " were expected\n"; abort(); } } else if (Mode.compare("cstHgamma") == 0) { this->T56_isMultiplicitySelection = false; double h = input.GetNextElementDouble(); bool isHomoFollows; { std::string s = input.GetNextElementString(); if (s == "homo" || s == "Homo" || s == "HOMO") { isHomoFollows = true; } else if (s == "hetero" || s == "Hetero" || s == "HETERO") { if (h == 0.0) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'cstHgamma', receive an h value of 0.0, which means that heterozygotes have a fitness of 1.0. But the values are being specified for the heterozygotes (as indicated by keyword "<<s<<").\n"; abort(); } isHomoFollows = false; } else { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'cstHgamma', after the 'h' value, expected either keywor 'homo' or keyword 'hetero' but got '" << s << "' instead.\n"; abort(); } } double alpha = input.GetNextElementDouble(); double beta = input.GetNextElementDouble(); if (alpha <= 0 || beta <= 0) { std::cout << "Either alpha ("<<alpha<<") or beta ("<<beta<<") have non-positive values.\n"; abort(); } std::gamma_distribution<double> dist(alpha, beta); for (int entry_index = 0 ; entry_index < this->quickScreenAtL_T56_nbLoci ; entry_index++) { double fitHomo; double fitHetero; if (isHomoFollows) { fitHomo = dist(GP->rngw.getRNG()); fitHetero = 1 - h * (1 - fitHomo); } else { fitHetero = dist(GP->rngw.getRNG()); fitHomo = 1 - (1-fitHetero)/h; } //if (fitHomo > 1.0) fitHomo = 1.0; if (fitHomo < 0.0) fitHomo = 0.0; //if (fitHetero > 1.0) fitHetero = 1.0; if (fitHetero < 0.0) fitHetero = 0.0; if (isLocusConsideredNeutral(fitHetero, T56_approximationForNtrl)) fitHetero = 1.0; if (isLocusConsideredNeutral(fitHomo, T56_approximationForNtrl)) fitHomo = 1.0; ForASingleHabitat.push_back(fitHetero); ForASingleHabitat.push_back(fitHomo); } assert(ForASingleHabitat.size() == 2 * this->quickScreenAtL_T56_nbLoci); } else if (Mode.compare("cstH")==0) { this->T56_isMultiplicitySelection = false; double h = input.GetNextElementDouble(); bool isHomoFollows; { std::string s = input.GetNextElementString(); if (s == "homo" || s == "Homo" || s == "HOMO") { isHomoFollows = true; } else if (s == "hetero" || s == "Hetero" || s == "HETERO") { if (h == 0.0) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'cstH', receive an h value of 0.0, which means that heterozygotes have a fitness of 1.0. But the values are being specified for the heterozygotes (as indicated by keyword "<<s<<").\n"; abort(); } isHomoFollows = false; } else { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'cstH', after the 'h' value, expected either keywor 'homo' or keyword 'hetero' but got '" << s << "' instead.\n"; abort(); } } for (int entry_index = 0 ; entry_index < this->quickScreenAtL_T56_nbLoci ; entry_index++) { double fitHomo; double fitHetero; if (isHomoFollows) { fitHomo = input.GetNextElementDouble(); fitHetero = 1 - h * (1 - fitHomo); } else { fitHetero = input.GetNextElementDouble(); fitHomo = 1 - (1-fitHetero)/h; } if (fitHomo < 0 ) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'cstH', one 'fitHomo' value is lower than 0 ( is " << fitHomo << " ).\n"; abort(); } if (fitHetero < 0 ) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'cstH', one 'fitHetero' value is lower than 0 ( is " << fitHetero << ", fitHomo = "<<fitHomo<<", h = "<<h<<" ).\n"; abort(); } if (isLocusConsideredNeutral(fitHetero, T56_approximationForNtrl)) fitHetero = 1.0; if (isLocusConsideredNeutral(fitHomo, T56_approximationForNtrl)) fitHomo = 1.0; ForASingleHabitat.push_back(fitHetero); ForASingleHabitat.push_back(fitHomo); } if (ForASingleHabitat.size() != 2 * this->quickScreenAtL_T56_nbLoci) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'cstH' " << ForASingleHabitat.size() << " have been received while " << 2 * (this->quickScreenAtL_T56_nbLoci) << " were expected\n"; abort(); } } else if (Mode.compare("MultiplicityA")==0 || Mode.compare("multfitA")==0) { this->T56_isMultiplicitySelection = true; ForASingleHabitat.reserve(this->quickScreenAtL_T56_nbLoci); for (int entry_index = 0 ; entry_index < this->quickScreenAtL_T56_nbLoci ; ) { double fit01 = input.GetNextElementDouble(); if (fit01 < 0) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'multfitA', one 'fit01' value is lower than 0 ( is " << fit01 << " ).\n"; abort(); } if (isLocusConsideredNeutral(fit01, T56_approximationForNtrl)) fit01 = 1.0; ForASingleHabitat.push_back(fit01); entry_index++; } if (ForASingleHabitat.size() != this->quickScreenAtL_T56_nbLoci) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'multfitA' " << ForASingleHabitat.size() << " have been received while " << this->quickScreenAtL_T56_nbLoci << " were expected\n"; abort(); } } else if (Mode.compare("unif")==0) { ForASingleHabitat.reserve(2 * this->quickScreenAtL_T56_nbLoci); this->T56_isMultiplicitySelection = false; double fitHet = input.GetNextElementDouble(); double fitHom = input.GetNextElementDouble(); if (fitHet<0 || fitHom<0) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'unif', value for fitness are negative (they are " << fitHet << " " << fitHom << " )\n"; abort(); } if (isLocusConsideredNeutral(fitHet, T56_approximationForNtrl)) fitHet = 1.0; if (isLocusConsideredNeutral(fitHom, T56_approximationForNtrl)) fitHom = 1.0; for (int locus = 0 ; locus < this->quickScreenAtL_T56_nbLoci ; ++locus) { ForASingleHabitat.push_back(fitHet); ForASingleHabitat.push_back(fitHom); } if (ForASingleHabitat.size() != 2 * this->quickScreenAtL_T56_nbLoci) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'unif' " << ForASingleHabitat.size() << " have been received while " << 2 * (this->quickScreenAtL_T56_nbLoci) << " were expected\n"; abort(); } } else if (Mode.compare("MultiplicityUnif")==0 || Mode.compare("multfitUnif")==0) { this->T56_isMultiplicitySelection = true; ForASingleHabitat.reserve(this->quickScreenAtL_T56_nbLoci); double fit01 = input.GetNextElementDouble(); if (fit01<0) { std::cout << "In option '--T5_FitnessEffects' Mode 'multfitUnif', habitat " << habitat << ", value for 'fit01' is negative (is " << fit01 << ")\n"; abort(); } if (isLocusConsideredNeutral(fit01, T56_approximationForNtrl)) fit01 = 1.0; for (int locus = 0 ; locus < this->quickScreenAtL_T56_nbLoci ; locus++) { ForASingleHabitat.push_back(fit01); } if (ForASingleHabitat.size() != this->quickScreenAtL_T56_nbLoci) { std::cout << "In option '--T5_FitnessEffects', habitat " << habitat << ", Mode 'multfitUnif' " << ForASingleHabitat.size() << " have been received while " << this->quickScreenAtL_T56_nbLoci << " were expected (likely an internal error)\n"; abort(); } } else if (Mode.compare("multfitGamma")==0 || Mode.compare("MultiplicityGamma")==0) { this->T56_isMultiplicitySelection = true; double alpha = input.GetNextElementDouble(); double beta = input.GetNextElementDouble(); if (alpha <= 0 || beta <= 0) { std::cout << "Either alpha ("<<alpha<<") or beta ("<<beta<<") have non-positive values.\n"; abort(); } std::gamma_distribution<double> dist(alpha, beta); ForASingleHabitat.reserve(this->quickScreenAtL_T56_nbLoci); for (int locus = 0 ; locus < this->quickScreenAtL_T56_nbLoci ; locus++) { double fit = 1 - dist(GP->rngw.getRNG()); if (fit < 0.0) fit = 0.0; //if (fit > 1.0) fit = 1.0; if (isLocusConsideredNeutral(fit, T56_approximationForNtrl)) fit = 1.0; ForASingleHabitat.push_back(fit); } assert(ForASingleHabitat.size() == this->quickScreenAtL_T56_nbLoci); } else { std::cout << "Sorry, for option '--T5_fit (--T56_FitnessEffects)', only Modes 'A', 'unif', 'cstHgamma', 'multfitA' (aka. 'MultiplicityA'), 'multfitUnif' (aka. 'MultiplicityUnif') and 'multfitGamma' (aka. 'MultiplicityGamma') are implemented for the moment (received Mode " << Mode << ")" << std::endl; abort(); } // end of ifelse Mode this->T56_FitnessEffects.push_back(ForASingleHabitat); } // end of for habitat assert(this->T56_FitnessEffects.size() == this->MaxEverHabitat + 1); } assert(isMultfit == 1 || isMultfit == 0); Gmap.setT56GenderLoci(T56_FitnessEffects, isMultfit == 1); // Set default values for T56_compress that will be changed later if the user wants uint32_t localCount_T56ntrl_nbLoci = 0; uint32_t localCount_T56sel_nbLoci = 0; for (uint32_t locus = 0 ; locus < this->quickScreenAtL_T56_nbLoci ; locus++) { //std::cout << "line 3188 locus " << locus << "\n"; if (!Gmap.isT56neutral(locus)) { ++localCount_T56sel_nbLoci; } else { ++localCount_T56ntrl_nbLoci; } } if (localCount_T56ntrl_nbLoci <= 65534 && localCount_T56ntrl_nbLoci > 5e3) // 65535 is the largest unsigned short (65535 = 2^16-1) and we are actually wasting a bit at every operation in order to gain . { Gmap.isT56ntrlCompress = true; } else { Gmap.isT56ntrlCompress = false; } Gmap.isT56selCompress = false; /*if (localCount_T56sel_nbLoci <= 65534) // 65535 is the largest unsigned short (65535 = 2^16-1) and we are actually wasting a bit at every operation in order to gain . { T56sel_compress = true; } else { T56sel_compress = false; }*/ } /*bool SpeciesSpecificParameters::isT56LocusUnderSelection(uint32_t locus) { assert(this->MaxEverHabitat >= 0); assert(this->T56_FitnessEffects.size() == this->MaxEverHabitat + 1); for (uint32_t habitat = 0 ; habitat <= this->MaxEverHabitat ; habitat++) { if (this->T56_isMultiplicitySelection) { assert(this->T56_FitnessEffects[habitat].size() > locus); if (this->T56_FitnessEffects[habitat][locus] < T56_approximationForNtrl) { return true; } } else { assert(this->T56_FitnessEffects[habitat].size() > 2*(locus) + 1); if (this->T56_FitnessEffects[habitat][2*(locus) + 1] < T56_approximationForNtrl || this->T56_FitnessEffects[habitat][2*(locus)] < T56_approximationForNtrl) { return true; } } } return false; }*/ void SpeciesSpecificParameters::readT8_FitnessEffects(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T8_FitnessEffects', the std::string that is read is: " << input.print() << std::endl; #endif assert(SSP != nullptr); if (input.PeakNextElementString() == "NA") { if (this->Gmap.T8_nbLoci != 0) { std::cout << "In option '--T8_FitnessEffects', for species "<<this->speciesName<<", received 'NA' but there are T8 loci as indiciated in --L (--Loci) (this->Gmap.T8_nbLoci = "<<this->Gmap.T8_nbLoci<<").\n"; abort(); } input.skipElement(); } else { std::string Mode = input.GetNextElementString(); if (Mode.compare("MultiplicityA")==0 || Mode.compare("multfitA")==0 || Mode.compare("A")==0) { for (int entry_index = 0 ; entry_index < this->Gmap.T8_nbLoci ; ) { if (input.isNextRKeyword()) { double fit01 = input.GetNextElementDouble(); int nbRepeats = input.GetNextElementInt(); if (fit01 < 0 ) { std::cout << "In option '--T8_FitnessEffects', Mode 'multfitA', one 'fit01' value (coming after keyword 'R') is lower than 0 ( is " << fit01 << " ).\n"; abort(); } for (int i = 0 ; i < nbRepeats; i++) { this->T8_FitnessEffects.push_back(fit01); entry_index++; if (entry_index > this->Gmap.T8_nbLoci) { std::cout << "In 'T8_FitnessEffects', mode 'multfitA', when reading after keyword 'R', you asked to repeat the value " << fit01 << " for " << nbRepeats << " times. This (on top with previous entries) results of a number of entry greater than " << this->Gmap.T8_nbLoci << " as requested given the mode here (multfitA) and the arguments given to the option '--Loci'\n"; abort(); } } } else { double fit01 = input.GetNextElementDouble(); if (fit01 < 0 ) { std::cout << "In option '--T8_FitnessEffects', Mode 'MultiplicityA', one 'fit01' value is lower than 0 ( is " << fit01 << " ).\n"; abort(); } this->T8_FitnessEffects.push_back(fit01); entry_index++; } } if (this->T8_FitnessEffects.size() != this->Gmap.T8_nbLoci) { std::cout << "In option '--T8_FitnessEffects', Mode 'multfitA' " << this->T8_FitnessEffects.size() << " have been received while " << this->Gmap.T8_nbLoci << " were expected\n"; abort(); } } else if (Mode.compare("MultiplicityUnif")==0 || Mode.compare("multfitUnif")==0 || Mode.compare("unif")==0) { double fit01 = input.GetNextElementDouble(); if (fit01<0) { std::cout << "In option '--T8_FitnessEffects' Mode 'multfitUnif', value for 'fit01' is negative (is " << fit01 << ")\n"; abort(); } for (int locus = 0 ; locus < this->Gmap.T8_nbLoci ; locus++) { this->T8_FitnessEffects.push_back(fit01); } if (this->T8_FitnessEffects.size() != this->Gmap.T8_nbLoci) { std::cout << "In option '--T8_FitnessEffects', Mode 'multfitUnif' " << this->T8_FitnessEffects.size() << " have been received while " << this->Gmap.T8_nbLoci << " were expected\n"; abort(); } } else if (Mode.compare("MultiplicityGamma")==0 || Mode.compare("multfitGamma")==0 || Mode.compare("gamma")==0) { double alpha = input.GetNextElementDouble(); double beta = input.GetNextElementDouble(); if (alpha <= 0 || beta <= 0) { std::cout << "Either alpha ("<<alpha<<") or beta ("<<beta<<") have non-positive values.\n"; abort(); } std::gamma_distribution<double> dist(alpha, beta); for (int locus = 0 ; locus < this->Gmap.T8_nbLoci ; locus++) { double fit = 1 - dist(GP->rngw.getRNG()); if (fit < 0.0) fit = 0.0; //if (fit > 1.0) fit = 1.0; this->T8_FitnessEffects.push_back(fit); } } else { std::cout << "Sorry, for option '--T8_fit (--T8_fitnessEffects)', only Modes 'A' (or 'multfitA' or 'MultiplicityA'), 'unif' (or 'multfitUnif' or 'MultiplicityUnif'). Mode received is '" << Mode << "'\n"; abort(); } // end of ifelse Mode } } void SpeciesSpecificParameters::readT1_FitnessEffects(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T1_FitnessEffects', the std::string that is read is: " << input.print() << std::endl; #endif assert(SSP != nullptr); if (input.PeakNextElementString() == "NA") { if (this->Gmap.T1_nbLoci != 0) { std::cout << "In option '--T1_FitnessEffects', for species "<<this->speciesName<<", received 'NA' but there are T1 loci as indiciated in --L (--Loci) (this->Gmap.T1_nbLoci = "<<this->Gmap.T1_nbLoci<<").\n"; abort(); } input.skipElement(); } else { std::string firstMode; for (int habitat = 0; habitat <= this->MaxEverHabitat ; habitat++) { (void) input.GetNextHabitatMarker(habitat); std::string Mode = input.GetNextElementString(); if (habitat == 0) { firstMode = Mode; } else { bool wasFirstMultFit = !(Mode == "MultiplicityA" || Mode == "MultiplicityGamma" || Mode == "MultiplicityUnif" || Mode == "multfitA" || Mode == "multfitGamma" || Mode == "multfitUnif"); bool isCurrentMultFit = !(firstMode == "MultiplicityA" || firstMode == "MultiplicityGamma" || firstMode == "MultiplicityUnif" || firstMode == "multfitA" || firstMode == "multfitGamma" || firstMode == "multfitUnif"); if (wasFirstMultFit != isCurrentMultFit) { std::cout << "For --T1_fit, the Mode received for the zeroth habitat is '" << firstMode << "'. The Mode received for the " << habitat << "th habitat is '" << Mode << "'. In the current version, if one patch make the assumption of 'multfit', then all patches must make this assumption.\n"; abort(); } } std::vector<fitnesstype> ForASingleHabitat; if (Mode.compare("DomA")==0 || Mode.compare("domA")==0) { this->T1_isMultiplicitySelection = false; std::string cst_or_fun = input.GetNextElementString(); if (cst_or_fun.compare("cst") != 0 && cst_or_fun.compare("fun") != 0) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'domA', you had to indicate 'cst' or 'fun' for how dominance coefficient is defined but instead, SimBit received " << cst_or_fun << ".\n"; abort(); } double dominance = input.GetNextElementDouble(); // either cst or mean dominance if (dominance < 0.0 || dominance > 1.0) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'domA', the dominance value is either smaller than 0.0 or larger than 1.0. dominance recevied = " << dominance << std::endl; abort(); } double mean_s = 0; // used only if cst_or_fun is 'fun' for (int entry_index = 0 ; entry_index < this->Gmap.T1_nbLoci ; ) { if (input.isNextRKeyword()) { double fit11 = input.GetNextElementDouble(); if (fit11 < 0) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'domA', one 'fit' value (directly after keyword 'R') is lower than 0 ( is " << fit11 << " ).\n"; abort(); } double fit01; if (cst_or_fun.compare("cst") == 0) { fit01 = 1 - ((1-fit11) * dominance); } else if (cst_or_fun.compare("fun") == 0) { fit01 = -1.0; // this is temporary because we need to read all s, before being able to compute the locus specific dominance mean_s += 1 - fit11; } else { std::cout << "Internal error in Parameters::readT1_FitnessEffects.\n"; abort(); } int nbRepeats = input.GetNextElementInt(); for (int i = 0 ; i < nbRepeats ; i++) { ForASingleHabitat.push_back(1.0); ForASingleHabitat.push_back(fit01); ForASingleHabitat.push_back(fit11); entry_index++; if (entry_index > this->Gmap.T1_nbLoci) { std::cout << "In 'T1_FitnessEffects', mode 'DomA', when reading after keyword 'R', you asked to repeat the value " << fit11 << " for " << nbRepeats << " times. This (on top with previous entries) results of a number of entry greater than " << this->Gmap.T1_nbLoci << " as requested given the mode here ('CstDomA') and the arguments given to the option '--Loci'\n"; abort(); } } } else { double fit11 = input.GetNextElementDouble(); if (fit11 < 0 || fit11 > 1 ) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'A', one 'fit' value is either greater than 1 or lower than 0 ( is " << fit11 << " ).\n"; abort(); } double fit01; if (cst_or_fun.compare("cst") == 0) { fit01 = 1 - ((1-fit11) * dominance); } else if (cst_or_fun.compare("fun") == 0) { fit01 = -1.0; // this is temporary because we need to read all s, before being able to compute the locus specific dominance mean_s += 1 - fit11; } else { std::cout << "Internal error in Parameters::readT1_FitnessEffects.\n"; abort(); } ForASingleHabitat.push_back(1.0); ForASingleHabitat.push_back(fit01); ForASingleHabitat.push_back(fit11); entry_index++; } } if (ForASingleHabitat.size() != THREE * this->Gmap.T1_nbLoci) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'DomA' " << ForASingleHabitat.size() / 3 << " have been received while " << this->Gmap.T1_nbLoci << " (= 8 * ( " << this->Gmap.T1_nbChars << ")) were expected\n"; abort(); } // Now if used the function, compute locus-specific dominance and insert them in place of the current -1.0 if (cst_or_fun.compare("fun") == 0) { mean_s /= this->Gmap.T1_nbLoci; assert(mean_s >= 0.0 && mean_s <= 1.0); if (mean_s == 0.0) {std::cout << "All T1 are neutral!\n";} double k = -1.0; if (mean_s > 0.0) { k = log(2 * dominance) / mean_s; // See Nemo manual for definition } int securityCount = 0; for (int i = 2 ; i < ForASingleHabitat.size() ; i += 3) { double fit11 = ForASingleHabitat[i]; assert(fit11 >= 0.0 && fit11 <= 1.0); double s11 = 1 - fit11; assert(s11 >= 0.0 && s11 <= 1.0); double dom = -1.0; double fit01 = 1.0; if (mean_s > 0.0) { dom = exp(k * s11) / 2; assert(dom >= 0.0 && dom <= 1.0); fit01 = 1 - (s11 * dom); } assert(fit01 >= 0.0 && fit01 <= 1.0); assert(ForASingleHabitat[i-2] == 1.0); // homozygote wildtype assert(ForASingleHabitat[i-1] == -1.0); // heterozygote should currently be set to -1.0 ForASingleHabitat[i-1] = fit01; securityCount++; } assert(securityCount == this->Gmap.T1_nbLoci); } } else if (Mode.compare("A")==0) { this->T1_isMultiplicitySelection = false; for (int entry_index = 0 ; entry_index < THREE * this->Gmap.T1_nbLoci ; ) { if (input.isNextRKeyword()) { double fit00 = input.GetNextElementDouble(); double fit01 = input.GetNextElementDouble(); double fit11 = input.GetNextElementDouble(); int nbRepeats = input.GetNextElementInt(); for (int i = 0 ; i < nbRepeats ; i++) { ForASingleHabitat.push_back(fit00); ForASingleHabitat.push_back(fit01); ForASingleHabitat.push_back(fit11); entry_index += 3; if (entry_index > (THREE * this->Gmap.T1_nbLoci)) { std::cout << "In 'T1_FitnessEffects', mode 'A', when reading after keyword 'R', you asked to repeat the values " << fit00 << " " << fit01 << " " << fit11 << " for " << nbRepeats << " times. This (on top with previous entries) results of a number of entry greater than " << THREE * this->Gmap.T1_nbLoci << " as requested given the mode here ('A') and the arguments given to the optinn '--Loci'\n"; abort(); } } } else { double fit = input.GetNextElementDouble(); if (fit < 0) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'A', one 'fit' value is lower than 0 ( is " << fit << " ).\n"; abort(); } ForASingleHabitat.push_back(fit); entry_index++; } } if (ForASingleHabitat.size() != THREE * this->Gmap.T1_nbLoci) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'A' " << ForASingleHabitat.size() << " have been received while " << THREE * (this->Gmap.T1_nbLoci) << " (= 3 * 8 * ( " << this->Gmap.T1_nbChars << ")) were expected\n"; abort(); } } else if (Mode.compare("MultiplicityA")==0 || Mode.compare("multfitA")==0) { this->T1_isMultiplicitySelection = true; for (int entry_index = 0 ; entry_index < this->Gmap.T1_nbLoci ; ) { if (input.isNextRKeyword()) { double fit01 = input.GetNextElementDouble(); int nbRepeats = input.GetNextElementInt(); if (fit01 < 0 ) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'multfitA', one 'fit01' value (coming after keyword 'R') is lower than 0 ( is " << fit01 << " ).\n"; abort(); } for (int i = 0 ; i < nbRepeats; i++) { ForASingleHabitat.push_back(fit01); entry_index++; if (entry_index > this->Gmap.T1_nbLoci) { std::cout << "In 'T1_FitnessEffects', mode 'multfitA', when reading after keyword 'R', you asked to repeat the value " << fit01 << " for " << nbRepeats << " times. This (on top with previous entries) results of a number of entry greater than " << this->Gmap.T1_nbLoci << " as requested given the mode here (multfitA) and the arguments given to the option '--Loci'\n"; abort(); } } } else { double fit01 = input.GetNextElementDouble(); if (fit01 < 0 ) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'MultiplicityA', one 'fit01' value is lower than 0 ( is " << fit01 << " ).\n"; abort(); } ForASingleHabitat.push_back(fit01); entry_index++; } } if (ForASingleHabitat.size() != this->Gmap.T1_nbLoci) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'multfitA' " << ForASingleHabitat.size() << " have been received while " << this->Gmap.T1_nbLoci << " (= 8 * ( " << this->Gmap.T1_nbChars << ")) were expected\n"; abort(); } } else if (Mode.compare("unif")==0) { this->T1_isMultiplicitySelection = false; double fit00 = input.GetNextElementDouble(); double fit01 = input.GetNextElementDouble(); double fit11 = input.GetNextElementDouble(); if (fit00<0 || fit01<0 || fit11<0) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'unif', value for fitness are negative (they are " << fit00 << " " << fit01 << " " << fit11 << " )\n"; abort(); } for (int locus = 0 ; locus < this->Gmap.T1_nbLoci ; ++locus) { ForASingleHabitat.push_back(fit00); ForASingleHabitat.push_back(fit01); ForASingleHabitat.push_back(fit11); } if (ForASingleHabitat.size() != THREE * this->Gmap.T1_nbLoci) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'unif' " << ForASingleHabitat.size() << " have been received while " << THREE * (this->Gmap.T1_nbLoci) << " (= 3 * 8 * ( " << this->Gmap.T1_nbChars << ")) were expected\n"; abort(); } } else if (Mode.compare("MultiplicityUnif")==0 || Mode.compare("multfitUnif")==0) { this->T1_isMultiplicitySelection = true; double fit01 = input.GetNextElementDouble(); if (fit01<0) { std::cout << "In option '--T1_FitnessEffects' Mode 'multfitUnif', habitat " << habitat << ", value for 'fit01' is negative (is " << fit01 << ")\n"; abort(); } for (int locus = 0 ; locus < this->Gmap.T1_nbLoci ; locus++) { ForASingleHabitat.push_back(fit01); } if (ForASingleHabitat.size() != this->Gmap.T1_nbLoci) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'multfitUnif' " << ForASingleHabitat.size() << " have been received while " << this->Gmap.T1_nbLoci << " (= 8 * ( " << this->Gmap.T1_nbChars << ")) were expected\n"; abort(); } } else if (Mode.compare("MultiplicityGamma")==0 || Mode.compare("multfitGamma")==0) { double alpha = input.GetNextElementDouble(); double beta = input.GetNextElementDouble(); if (alpha <= 0 || beta <= 0) { std::cout << "Either alpha ("<<alpha<<") or beta ("<<beta<<") have non-positive values.\n"; abort(); } std::gamma_distribution<double> dist(alpha, beta); for (int locus = 0 ; locus < this->Gmap.T1_nbLoci ; locus++) { double fit = 1 - dist(GP->rngw.getRNG()); if (fit < 0.0) fit = 0.0; //if (fit > 1.0) fit = 1.0; ForASingleHabitat.push_back(fit); } } else if (Mode.compare("cstHgamma") == 0) { this->T1_isMultiplicitySelection = false; double h = input.GetNextElementDouble(); bool isHomoFollows; { std::string s = input.GetNextElementString(); if (s == "homo" || s == "Homo" || s == "HOMO") { isHomoFollows = true; } else if (s == "hetero" || s == "Hetero" || s == "HETERO") { if (h == 0.0) { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'cstHgamma', receive an h value of 0.0, which means that heterozygotes have a fitness of 1.0. But the values are being specified for the heterozygotes (as indicated by keyword "<<s<<").\n"; abort(); } isHomoFollows = false; } else { std::cout << "In option '--T1_FitnessEffects', habitat " << habitat << ", Mode 'cstHgamma', after the 'h' value, expected either keywor 'homo' or keyword 'hetero' but got '" << s << "' instead.\n"; abort(); } } double alpha = input.GetNextElementDouble(); double beta = input.GetNextElementDouble(); if (alpha <= 0 || beta <= 0) { std::cout << "Either alpha ("<<alpha<<") or beta ("<<beta<<") have non-positive values.\n"; abort(); } std::gamma_distribution<double> dist(alpha, beta); for (int entry_index = 0 ; entry_index < this->Gmap.T1_nbLoci ; entry_index++) { double fitHomo; double fitHetero; if (isHomoFollows) { fitHomo = dist(GP->rngw.getRNG()); fitHetero = 1 - h * (1 - fitHomo); } else { fitHetero = dist(GP->rngw.getRNG()); fitHomo = 1 - (1-fitHetero)/h; } //if (fitHomo > 1.0) fitHomo = 1.0; if (fitHomo < 0.0) fitHomo = 0.0; //if (fitHetero > 1.0) fitHetero = 1.0; if (fitHetero < 0.0) fitHetero = 0.0; ForASingleHabitat.push_back(1.0); ForASingleHabitat.push_back(fitHetero); ForASingleHabitat.push_back(fitHomo); } assert(ForASingleHabitat.size() == 3 * this->Gmap.T1_nbLoci); } else { std::cout << "Sorry, for option '--T1_fit (--T1_fitnessEffects)', only Modes 'A', 'unif', 'domA' (or 'DomA'), 'multfitA' (aka. 'MultiplicityA'), 'multfitUnif' (aka. 'MultiplicityUnif'), cstHgamma and 'multfitGamma' (aka. 'MultiplicityGamma') are implemented for the moment (received Mode " << Mode << ")" << std::endl; abort(); } // end of ifelse Mode this->T1_FitnessEffects.push_back(ForASingleHabitat); } // end of for habitat assert(this->T1_FitnessEffects.size() == this->MaxEverHabitat + 1); } } void SpeciesSpecificParameters::readT2_FitnessEffects(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T2_FitnessEffects', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { if (this->Gmap.T2_nbLoci != 0) { std::cout << "In option '--T2_FitnessEffects', for species "<<this->speciesName<<", received 'NA' but there are T2 loci as indiciated in --L (--Loci) (this->Gmap.T2_nbLoci = "<<this->Gmap.T2_nbLoci<<").\n"; abort(); } input.skipElement(); } else { for (int habitat = 0 ; habitat <= this->MaxEverHabitat ; habitat++) { (void) input.GetNextHabitatMarker(habitat); std::vector<fitnesstype> ForASingleHabitat; std::string Mode = input.GetNextElementString(); if (Mode.compare("unif") == 0) { double fit = input.GetNextElementDouble(); if (fit < 0.0) { std::cout << "In option '--T2_FitnessEffects', habitat " << habitat << ", Mode 'unif', 'fit' value received is " << fit << " which is lower than zero.\n"; abort(); } for (int char_index = 0 ; char_index < this->Gmap.T2_nbLoci ; char_index++) { ForASingleHabitat.push_back(fit); } } else if (Mode.compare("A") == 0) { for (int entry_index = 0 ; entry_index < this->Gmap.T2_nbLoci ; ++entry_index) { double fit = input.GetNextElementDouble(); if (fit < 0.0) { std::cout << "In option '--T2_FitnessEffects' Mode 'A', 'fit' value received is " << fit << " which is lower than zero.\n"; abort(); } ForASingleHabitat.push_back(fit); } if (ForASingleHabitat.size() != this->Gmap.T2_nbLoci) { std::cout << "In option '--T2_FitnessEffects', habitat " << habitat << ", Mode 'A', " << ForASingleHabitat.size() << " values received while " << this->Gmap.T2_nbLoci << " were expected." << std::endl; abort(); } } else if (Mode.compare("Gamma") == 0) { double alpha = input.GetNextElementDouble(); double beta = input.GetNextElementDouble(); if (alpha <= 0 || beta <= 0) { std::cout << "Either alpha ("<<alpha<<") or beta ("<<beta<<") have non-positive values.\n"; abort(); } std::gamma_distribution<double> dist(alpha, beta); for (int locus = 0 ; locus < this->Gmap.T2_nbLoci ; locus++) { double fit = 1 - dist(GP->rngw.getRNG()); if (fit < 0.0) fit = 0.0; //if (fit > 1.0) fit = 1.0; ForASingleHabitat.push_back(fit); } } else { std::cout << "In option '--T2_FitnessEffects', habitat " << habitat << ", Mode received is " << Mode << ". Sorry only Modes 'A' and 'unif' are recognized for the moment!\n"; abort(); } // end of ifelse Mode assert(this->T2_FitnessEffects.size() == habitat); this->T2_FitnessEffects.push_back(ForASingleHabitat); } // end of Habitat loop assert(this->T2_FitnessEffects.size() == this->MaxEverHabitat + 1); } } void SpeciesSpecificParameters::readT56_MutationRate(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T5_MutationRate', the std::string that is read is: " << input.print() << std::endl; #endif //std::cout << "T5_nbLoci = " << T5_nbLoci << "\n"; this->T56_Total_Mutation_rate = 0.0; // just for safety but it is not necessary if (input.PeakNextElementString() == "NA" || input.PeakNextElementString() == "default") { this->T56_Total_Mutation_rate = 0.0; if (this->Gmap.T56_nbLoci != 0) { std::cout << "In option '--T5_MutationRate', for species "<<this->speciesName<<", received 'default' (default input). The default input is only valid when there are no T5 loci indicated in option --L (--Loci). In short, if you want T5 loci, please indicate a mutation rate for these loci (with option --T5_mu). Note SimBit received "<<this->Gmap.T56_nbLoci<<" T5 loci from option --L (--Loci)\n"; abort(); } input.skipElement(); } else { std::string Mode = input.GetNextElementString(); if (Mode.compare("A")==0) { double currentSum = 0.0; while (input.IsThereMoreToRead()) { if (input.isNextRKeyword()) { double inputValue = input.GetNextElementDouble(); int nbRepeats = input.GetNextElementInt(); if (inputValue < 0.0) { std::cout << "For option 'T5_MutationRate', received a negative rate (received " << inputValue << ").\n"; abort(); } if (inputValue > 0.5) { std::cout << "For option 'T5_MutationRate', received a value greater than 0.5 (received " << inputValue << ").\n"; abort(); } for (uint32_t repeat = 0 ; repeat < nbRepeats ; ++repeat) { currentSum += inputValue; T56_MutationRate.push_back(currentSum); } } else { double inputValue = input.GetNextElementDouble(); if (inputValue < 0.0) { std::cout << "For option 'T5_MutationRate', received a negative rate (received " << inputValue << ").\n"; abort(); } currentSum += inputValue; T56_MutationRate.push_back(currentSum); } } if (T56_MutationRate.size() != Gmap.T56_nbLoci) { std::cout << "For option 'T5_MutationRate', received " << T56_MutationRate.size() << " values but it was expected "<< Gmap.T56_nbLoci <<" values.\n"; abort(); } T56_Total_Mutation_rate = T56_MutationRate.back(); } else if (Mode.compare("unif")==0) { double perLocusRate = input.GetNextElementDouble(); if (perLocusRate < 0) { std::cout << "T56_MutationRate of Mode 'unif' is lower than zero" << std::endl; abort(); } if (perLocusRate > 0.5) { std::cout << "For option 'T5_MutationRate', received a value greater than 0.5 (received " << perLocusRate << ").\n"; abort(); } if (Gmap.T56_nbLoci > 0) { this->T56_MutationRate.push_back(perLocusRate * this->Gmap.T56_nbLoci); } T56_Total_Mutation_rate = T56_MutationRate.back(); } else { std::cout << "Sorry, for 'T56_MutationRate' only Mode 'unif' and 'A' are recognized so far. Mode received (" << Mode << ") is unknown!" << std::endl; abort(); } assert(this->T56_MutationRate.size() == this->Gmap.T56_nbLoci || this->T56_MutationRate.size() == 1); } //std::cout << "T5ntrl_Total_Mutation_rate = "<< T5ntrl_Total_Mutation_rate << "\n"; //std::cout << "T5sel_Total_Mutation_rate = "<< T5sel_Total_Mutation_rate << "\n"; } void SpeciesSpecificParameters::readT1_mutDirection(InputReader& input) { if (input.PeakNextElementString() == "default") { T1_mutDirection = 2; input.skipElement(); } else { std::string s = input.GetNextElementString(); if (s == "0to1") { T1_mutDirection = 1; } else if (s == "1to0") { T1_mutDirection = 0; } else if (s == "both") { T1_mutDirection = 2; } else { std::cout << "For option --T1_mutDirection, only values '1to0', '0to1' and 'both' (or 'default') are accepted. Received '" << s << "'\n"; abort(); } } assert(T1_mutDirection >= 0 && T1_mutDirection <= 2); } void SpeciesSpecificParameters::readT4_nbMutationPlacingsPerOutput(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); T4_nbMutationPlacingsPerOutput = 1; } else { auto x = input.GetNextElementInt(); if (x < 1) { std::cout << "For option --T4_nbMutationPlacingsPerOutput, you asked for " << x << " mutations placings. Sorry, the number of mutation placings must be great or equal to 1.\n"; abort(); } T4_nbMutationPlacingsPerOutput = x; } } void SpeciesSpecificParameters::readT4_respectPreviousMutationsOutputs(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); if (T4_nbMutationPlacingsPerOutput == 1 && !outputWriter.isFile(T4_paintedHaplo_file) && !outputWriter.isFile(T4_paintedHaploSegmentsDiversity_file) && !outputWriter.isFile(T4_paintedHaploSegmentsOrigin_file)) { T4_respectPreviousMutationsOutputs = true; } else { T4_respectPreviousMutationsOutputs = false; } } else { T4_respectPreviousMutationsOutputs = input.GetNextElementBool(); if (T4_respectPreviousMutationsOutputs) { if (T4_nbMutationPlacingsPerOutput > 1) { std::cout << "For options --T4_respectPreviousMutationsOutputs, received 'true' (or equivalent). T4_respectPreviousMutationsOutputs can only be set to true if you only ask for a single mutation placing per T4 output (as set with option --T4_nbMutationPlacingsPerOutput; because it would not make any sense otherwise). However, you appear to have asked for " << T4_nbMutationPlacingsPerOutput << " mutation placings per T4 outputs.\n"; abort(); } if (outputWriter.isFile(T4_paintedHaplo_file) || outputWriter.isFile(T4_paintedHaploSegmentsDiversity_file) || outputWriter.isFile(T4_paintedHaploSegmentsOrigin_file)) { std::cout << "For options --T4_respectPreviousMutationsOutputs, received 'true' (or equivalent). T4_respectPreviousMutationsOutputs can only be set to true if you do not use haplotype painted (but you seem to use haploytpe painting). Sorry, that's a little bit of a silly limitation of SimBit.\n"; abort(); } } } } void SpeciesSpecificParameters::readT4_mutDirection(InputReader& input) { if (input.PeakNextElementString() == "default") { T4_mutDirection = 2; input.skipElement(); } else { std::string s = input.GetNextElementString(); if (s == "0to1") { T4_mutDirection = 1; } else if (s == "1to0") { T4_mutDirection = 0; } else if (s == "both") { T4_mutDirection = 2; } else { std::cout << "For option --T4_mutDirection, only values '1to0', '0to1' and 'both' (or 'default') are accepted. Redeived " << s << "\n"; abort(); } } assert(T4_mutDirection >= 0 && T4_mutDirection <= 2); } void SpeciesSpecificParameters::readT8_mutDirection(InputReader& input) { if (input.PeakNextElementString() == "default") { T8_mutDirection = 2; input.skipElement(); } else { std::string s = input.GetNextElementString(); if (s == "0to1") { T8_mutDirection = 1; } else if (s == "1to0") { T8_mutDirection = 0; } else if (s == "both") { T8_mutDirection = 2; } else { std::cout << "For option --T8_mutDirection, only values '1to0', '0to1' and 'both' (or 'default') are accepted. Redeived " << s << "\n"; abort(); } } assert(T8_mutDirection >= 0 && T8_mutDirection <= 2); } void SpeciesSpecificParameters::readT56_mutDirection(InputReader& input) { if (input.PeakNextElementString() == "default") { T56_mutDirection = 2; input.skipElement(); } else { std::string s = input.GetNextElementString(); if (s == "0to1") { T56_mutDirection = 1; } else if (s == "1to0") { T56_mutDirection = 0; } else if (s == "both") { T56_mutDirection = 2; } else { std::cout << "For option --T56_mutDirection, only values '1to0', '0to1' and 'both' (or 'default') are accepted. Redeived " << s << "\n"; abort(); } } assert(T56_mutDirection >= 0 && T56_mutDirection <= 2); } void SpeciesSpecificParameters::readT1_MutationRate(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T1_MutationRate', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { if (this->Gmap.T1_nbLoci != 0) { std::cout << "In option '--T1_MutationRate', for species "<<this->speciesName<<", received 'NA' but there are T1 loci as indiciated in --L (--Loci) (this->Gmap.T1_nbLoci = "<<this->Gmap.T1_nbLoci<<").\n"; abort(); } input.skipElement(); } else { std::string Mode = input.GetNextElementString(); if (Mode.compare("A")==0) { double currentSum = 0; int T1_char_index = 0; int bit_index = 0; while (input.IsThereMoreToRead()) { if (input.isNextRKeyword()) { double inputValue = input.GetNextElementDouble(); int NbRepeats = input.GetNextElementInt(); for (int repeat = 0 ; repeat < NbRepeats ; ++repeat) { currentSum += inputValue; this->T1_MutationRate.push_back(currentSum); // Adjust the bit_index and T1_char_index if (bit_index == 7) { bit_index = 0; ++T1_char_index; } else { ++bit_index; } } // security if (inputValue < 0) { std::cout << "In 'T1_MutationRate' of Mode 'A' the value for the " << T1_char_index << "th T1_char_index is negative (is " << inputValue << ")" << std::endl; abort(); } if (inputValue >= 0.1) { std::cout << "In 'T1_MutationRate' of Mode 'A' the value for the " << T1_char_index << "th T1_char_index is greater or equal to 0.1 (is " << inputValue << "). Is it really what you want to do?" << std::endl; abort(); } } else { double inputValue = input.GetNextElementDouble(); currentSum += inputValue; this->T1_MutationRate.push_back(currentSum); // security if (inputValue < 0) { std::cout << "In 'T1_MutationRate' of Mode 'A' the value for the " << T1_char_index << "th T1_char_index is negative (is " << inputValue << ")" << std::endl; abort(); } if (inputValue >= 0.1) { std::cout << "In 'T1_MutationRate' of Mode 'A' the value for the " << T1_char_index << "th T1_char_index is greater than 0.1 (is " << inputValue << "). Is it really what you want to do?" << std::endl; abort(); } // Adjust the bit_index and T1_char_index if (bit_index == 7) { bit_index = 0; ++T1_char_index; } else { ++bit_index; } } } // Did I get the info I expected? if ((T1_char_index * EIGHT + bit_index) != this->Gmap.T1_nbLoci) { std::cout << "In '--T1_MutationRate', expected " << this->Gmap.T1_nbLoci << " elements. But " << T1_char_index * EIGHT + bit_index << " elements were received.\n"; abort(); } } else if (Mode.compare("unif")==0) { this->T1_MutationRate.push_back(input.GetNextElementDouble() * this->Gmap.T1_nbLoci); if (this->T1_MutationRate.back() < 0) { std::cout << "T1_MutationRate of Mode 'unif' is lower than zero" << std::endl; abort(); } } else { std::cout << "Sorry, for 'T1_MutationRate' only Mode 'unif' and 'A' are recognized so far. Mode received (" << Mode << ") is unknown!" << std::endl; abort(); } assert(this->T1_MutationRate.size() == this->Gmap.T1_nbLoci || this->T1_MutationRate.size() == 1); this->T1_Total_Mutation_rate = this->T1_MutationRate.back(); } } void SpeciesSpecificParameters::readT2_MutationRate(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T2_MutationRate', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { if (this->Gmap.T2_nbLoci != 0) { std::cout << "In option '--T2_MutationRate', for species "<<this->speciesName<<", received 'NA' but there are T2 loci as indiciated in --L (--Loci) (this->Gmap.T2_nbLoci = "<<this->Gmap.T2_nbLoci<<").\n"; abort(); } input.skipElement(); } else { std::string Mode = input.GetNextElementString(); if (Mode.compare("A")==0) { double currentSum = 0; int T2_char_index = 0; while (input.IsThereMoreToRead()) { if (input.isNextRKeyword()) { double inputValue = input.GetNextElementDouble(); int nbRepeats = input.GetNextElementInt(); T2_char_index += nbRepeats; for (int repeat = 0 ; repeat < nbRepeats ; ++repeat) { currentSum += inputValue; this->T2_MutationRate.push_back(currentSum); } // security if (inputValue < 0) { std::cout << "In 'T2_MutationRate' of Mode 'A' the value for the " << T2_char_index << "th T2_char_index is negative (is " << inputValue << ")" << std::endl; abort(); } if (inputValue > 0.5) { std::cout << "In 'T2_MutationRate' of Mode 'A' the value for the " << T2_char_index << "th T2_char_index is greater than 0.5 (is " << inputValue << "). Is it really what you want to do?" << std::endl; abort(); } } else { double inputValue = input.GetNextElementDouble(); currentSum += inputValue; this->T2_MutationRate.push_back(currentSum); ++T2_char_index; // security if (inputValue < 0) { std::cout << "In 'T2_MutationRate' of Mode 'A' the value for the " << T2_char_index << "th T2_char_index is negative (is " << this->T2_MutationRate.back() << ")" << std::endl; abort(); } if (inputValue > 0.5) { std::cout << "In 'T2_MutationRate' of Mode 'A' the value for the " << T2_char_index << "th T2_char_index is greater than 0.5 (is " << this->T2_MutationRate.back() << "). Is it really what you want to do?" << std::endl; abort(); } } } } else if (Mode.compare("unif")==0) { this->T2_MutationRate.push_back(input.GetNextElementDouble() * this->Gmap.T2_nbLoci); if (this->T2_MutationRate.back() < 0) { std::cout << "T2_MutationRate of Mode 'unif' is lower than zero" << std::endl; abort(); } } else { std::cout << "Sorry, for 'T2_MutationRate' only Mode 'unif' and 'A' are recognized so far. Mode received (" << Mode << ") is unknown!" << std::endl; abort(); } this->T2_Total_Mutation_rate = this->T2_MutationRate.back(); assert(this->T2_MutationRate.size() == this->Gmap.T2_nbLoci || this->T2_MutationRate.size() == 1); } } void SpeciesSpecificParameters::readT3_mutationalEffect(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T3_mutationalEffect', the std::string that is read is: " << input.print() << std::endl; #endif auto type = input.GetNextElementString(); if (type == "default") { T3_mutationType = '1'; T3_mutationType_effectSizeInfo = 1.0; } else if (type == "cst") { T3_mutationType = '1'; T3_mutationType_effectSizeInfo = input.GetNextElementDouble(); } else if (type == "gauss1") { T3_mutationType = 'g'; T3_mutationType_effectSizeInfo = input.GetNextElementDouble(); } else if (type == "gauss2") { T3_mutationType = 'G'; T3_mutationType_effectSizeInfo = input.GetNextElementDouble(); } else { std::cout << "For option 'T3_mutationType', received type '"<< type << "'. Sorry, only types 'default', 'cst', 'gauss1' and 'gauss2' are accepted. Note that 'default' and 'cst' are the same and mean that at each mutation a constant value is either added or removed (with equal probability). For the types 'gauss1' and 'gauss2', at each mutation, SimBit draws an mutation effect from a normal (Gaussian) distribution with specified variance and mean of zero. With 'gauss1' this mutational effect is added to the current allelic value while with 'gauss2', the mutational effect replaces the current allelic value." << std::endl; abort(); } if (T3_mutationType_effectSizeInfo < 0.0) { std::cout << "For option 'T3_mutationType', received type '"<< type << "' followed by the value "<<T3_mutationType_effectSizeInfo<<". This value cannot be negative." << std::endl; abort(); } } void SpeciesSpecificParameters::readT3_MutationRate(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T3_MutationRate', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { if (this->Gmap.T3_nbLoci != 0) { std::cout << "In option '--T3_MutationRate', for species "<<this->speciesName<<", received 'NA' but there are T3 loci as indiciated in --L (--Loci) (this->Gmap.T3_nbLoci = "<<this->Gmap.T3_nbLoci<<").\n"; abort(); } input.skipElement(); } else { std::string Mode = input.GetNextElementString(); if (Mode.compare("A")==0) { double currentSum = 0; int T3_char_index = 0; while (input.IsThereMoreToRead()) { if (input.isNextRKeyword()) { double inputValue = input.GetNextElementDouble(); int nbRepeats = input.GetNextElementInt(); T3_char_index += nbRepeats; for (int repeat = 0 ; repeat < nbRepeats ; ++repeat) { currentSum += inputValue; this->T3_MutationRate.push_back(currentSum); } // security if (inputValue < 0) { std::cout << "In 'T3_MutationRate' of Mode 'A' the value for the " << T3_char_index << "th T3_char_index is negative (is " << inputValue << ")" << std::endl; abort(); } if (inputValue > 0.5) { std::cout << "In 'T3_MutationRate' of Mode 'A' the value for the " << T3_char_index << "th T3_char_index is greater than 0.5 (is " << inputValue << "). Is it really what you want to do?" << std::endl; abort(); } } else { double inputValue = input.GetNextElementDouble(); currentSum += inputValue; this->T3_MutationRate.push_back(currentSum); ++T3_char_index; // security if (inputValue < 0) { std::cout << "In 'T3_MutationRate' of Mode 'A' the value for the " << T3_char_index << "th T3_char_index is negative (is " << this->T3_MutationRate.back() << ")" << std::endl; abort(); } if (inputValue > 0.5) { std::cout << "In 'T3_MutationRate' of Mode 'A' the value for the " << T3_char_index << "th T3_char_index is greater than 0.5 (is " << this->T3_MutationRate.back() << "). Is it really what you want to do?" << std::endl; abort(); } } } } else if (Mode.compare("unif")==0) { this->T3_MutationRate.push_back(input.GetNextElementDouble() * this->Gmap.T3_nbLoci); if (this->T3_MutationRate.back() < 0) { std::cout << "T3_MutationRate of Mode 'unif' is lower than zero" << std::endl; abort(); } } else { std::cout << "Sorry, for 'T3_MutationRate' only Mode 'unif' and 'A' are recognized so far. Mode received (" << Mode << ") is unknown!" << std::endl; abort(); } this->T3_Total_Mutation_rate = this->T3_MutationRate.back(); assert(this->T3_MutationRate.size() == this->Gmap.T3_nbLoci || this->T3_MutationRate.size() == 1); } } void SpeciesSpecificParameters::readT3_PhenotypicEffects(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T3_PhenotypicEffects', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { if (this->Gmap.T3_nbLoci != 0) { std::cout << "In option 'T3_PhenotypicEffects', for species "<<this->speciesName<<", received 'NA' but there are T3 loci as indiciated in --L (--Loci) (this->Gmap.T3_nbLoci = "<<this->Gmap.T3_nbLoci<<").\n"; abort(); } input.skipElement(); } else { this->T3_PhenoNbDimensions = input.GetNextElementInt(); if (this->T3_PhenoNbDimensions < 1) { std::cout << "In option 'T3_PhenotypicEffects', the first entry should be the number of dimensions of the fitness space. The minimal possible value is 1. Received " << this->T3_PhenoNbDimensions << "\n"; abort(); } if (this->T3_PhenoNbDimensions > this->Gmap.T3_nbLoci) { std::cout << "In option 'T3_PhenotypicEffects', the first entry should be the number of dimensions of the fitness space. The number of dimensions received ("<<this->T3_PhenoNbDimensions <<") is higher than the number of T3 loci ("<<this->Gmap.T3_nbLoci<<"). Is it really what you want? If yes, turn this security check off.\n"; abort(); } for (int i = 0 ; i < this->T3_PhenoNbDimensions; i++) { Individual::T3_IndPhenotype.push_back(0.0); // This is a static variable that is used by all inds to calculate fitness on T3 trait } input = InputReader(input, 1); // remove first element to avoid messing up when calling 'GetNextHabitatMarker' for (int habitat = 0; habitat <= this->MaxEverHabitat ; habitat++) { (void) input.GetNextHabitatMarker(habitat); std::vector<double> T3_PhenotypicEffects_OneHabitat; std::string Mode = input.GetNextElementString(); if (Mode.compare("A") == 0) { for (int T3_locus = 0 ; T3_locus < this->Gmap.T3_nbLoci ; ++T3_locus) { for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { T3_PhenotypicEffects_OneHabitat.push_back(input.GetNextElementDouble()); } } } else if (Mode.compare("unif") == 0) { std::vector<double> v; for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { v.push_back(input.GetNextElementDouble()); } assert(v.size() == this->T3_PhenoNbDimensions ); for (int T3_locus = 0 ; T3_locus < this->Gmap.T3_nbLoci ; ++T3_locus) { for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { T3_PhenotypicEffects_OneHabitat.push_back(v[dim]); } } } else { std::cout << "In option 'T3_PhenotypicEffects', received Mode "<< Mode << ". Sorry only modes 'A' and 'unif' are recognized for the moment. \n"; abort(); } this->T3_PhenotypicEffects.push_back(T3_PhenotypicEffects_OneHabitat); } // end of habitat for loop } } void SpeciesSpecificParameters::readCentralT1LocusForExtraGeneticInfo(InputReader& input) { #ifdef DEBUG std::cout << "For option '--centralT1LocusForExtraGeneticInfo', the std::string that is read is: " << input.print() << std::endl; #endif this->centralT1LocusForExtraGeneticInfo = input.GetNextElementInt(); } void SpeciesSpecificParameters::readT3_FitnessLandscape(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T3_fit (--T3_fitnessLandscape)', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { if (this->Gmap.T3_nbLoci != 0) { std::cout << "In option 'T3_FitnessLandscape', for species "<<this->speciesName<<", received 'NA' (default value if nothing is specified) but there are T3 loci as indiciated in --L (--Loci) (this->Gmap.T3_nbLoci = "<<this->Gmap.T3_nbLoci<<").\n"; abort(); } input.skipElement(); } else { std::string SelectionMode = input.GetNextElementString(); input = InputReader(input, 1); // remove first element to avoid messing up with GetNextHabitatMarker for (int habitat = 0; habitat <= this->MaxEverHabitat ; habitat++) { (void) input.GetNextHabitatMarker(habitat); std::string EntryMode = input.GetNextElementString(); std::vector<float> T3_fitnessLandscapeOptimum_OneHabitat; std::vector<float> T3_fitnessLandscapeLinearGradient_OneHabitat; std::vector<float> T3_fitnessLandscapeGaussStrength_OneHabitat; if (SelectionMode.compare("linear")==0 || SelectionMode.compare("simple")==0) { this->T3_fitnessLandscapeType='L'; if (EntryMode.compare("A")==0) { for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { double mean = input.GetNextElementDouble(); double gradient = input.GetNextElementDouble(); if (gradient < 0.0) { std::cout << "In '--T3_FitnessLandscape', SelectionMode 'linear', EntryMode 'A', for dimension "<<dim<<" (counting zero-based) received a gradient of "<<gradient<<". Gradient must be non-negative.\n"; abort(); } T3_fitnessLandscapeOptimum_OneHabitat.push_back(mean); T3_fitnessLandscapeLinearGradient_OneHabitat.push_back(gradient); } } else if (EntryMode.compare("unif")==0) { double mean = input.GetNextElementDouble(); double gradient = input.GetNextElementDouble(); if (gradient < 0.0) { std::cout << "In '--T3_FitnessLandscape', SelectionMode 'linear', EntryMode 'unif', received a gradient of "<<gradient<<". Gradient must be non-negative.\n"; abort(); } for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { T3_fitnessLandscapeOptimum_OneHabitat.push_back(mean); T3_fitnessLandscapeLinearGradient_OneHabitat.push_back(gradient); } } else { std::cout << "In option '--T3_fit (--T3_fitnessLandscape)', received EntryMode " << EntryMode << ". The only EntryMode accepted are 'A' and 'unif'. Sorry.\n"; abort(); } } else if (SelectionMode.compare("gaussian")==0 || SelectionMode.compare("gauss")==0) { this->T3_fitnessLandscapeType='G'; if (EntryMode.compare("A")==0) { for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { double mean = input.GetNextElementDouble(); double strength = input.GetNextElementDouble(); if (strength <= 0.0) { std::cout << "In '--T3_FitnessLandscape', SelectionMode 'gauss', EntryMode 'A', for dimension "<<dim<<" (counting zero-based) received a strength of "<<strength<<". strength must be non-negative.\n"; abort(); } T3_fitnessLandscapeOptimum_OneHabitat.push_back(mean); T3_fitnessLandscapeGaussStrength_OneHabitat.push_back(strength); } } else if (EntryMode.compare("unif")==0) { double mean = input.GetNextElementDouble(); double strength = input.GetNextElementDouble(); if (strength <= 0.0) { std::cout << "In '--T3_FitnessLandscape', SelectionMode 'gauss', EntryMode 'unif', received a strength of "<<strength<<". strength must be non-negative.\n"; abort(); } assert(this->T3_PhenoNbDimensions > 0); for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { T3_fitnessLandscapeOptimum_OneHabitat.push_back(mean); T3_fitnessLandscapeGaussStrength_OneHabitat.push_back(strength); } } else { std::cout << "In option '--T3_fit (--T3_fitnessLandscape)', received EntryMode " << EntryMode << ". The only EntryMode accepted are 'A' and 'unif'.\n"; abort(); } } else { std::cout << "In option '--T3_fit (--T3_fitnessLandscape)', the only SelectionMode accepted are 'linear' and 'gaussian' (or 'gauss'). Mode received = '"<<SelectionMode<< "'.\n"; abort(); } this->T3_fitnessLandscapeOptimum.push_back(T3_fitnessLandscapeOptimum_OneHabitat); if (SelectionMode.compare("gaussian")==0 || SelectionMode.compare("gauss")==0) { this->T3_fitnessLandscapeGaussStrength.push_back(T3_fitnessLandscapeGaussStrength_OneHabitat); } else if (SelectionMode.compare("linear")==0) { this->T3_fitnessLandscapeLinearGradient.push_back(T3_fitnessLandscapeLinearGradient_OneHabitat); } else if (SelectionMode != "NA") { std::cout << "Unknown SelectionMode in T3_FitnessLandscape. The error should have been detected earlier in the process. There is therefore an internal error but you might want to check your input parameters anyway.\n"; abort(); } } // end of for habitat assert(this->T3_fitnessLandscapeOptimum.size() == this->MaxEverHabitat+1); if (SelectionMode.compare("gaussian")==0 || SelectionMode.compare("gauss")==0) { assert(this->T3_fitnessLandscapeGaussStrength.size() == this->MaxEverHabitat+1); } else if (SelectionMode.compare("linear")==0) { assert(this->T3_fitnessLandscapeLinearGradient.size() == this->MaxEverHabitat+1); } } } void SpeciesSpecificParameters::readT3_DevelopmentalNoise(InputReader& input) { #ifdef DEBUG std::cout << "For option '--T3_DN (--T3_DevelopmentalNoise)', the std::string that is read is: " << input.print() << std::endl; #endif if (this->Gmap.T3_nbLoci) { for (int habitat = 0; habitat <= this->MaxEverHabitat ; habitat++) { (void) input.GetNextHabitatMarker(habitat); std::string EntryMode = input.GetNextElementString(); std::vector<double> DN_OneHabitat; // each value is for one dimension of the phenotypic space if (EntryMode.compare("A")==0) { for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { double sd = input.GetNextElementDouble(); if (sd < 0) { std::cout << "In '--T3_DevelopmentalNoise', mode = A. Received a negative standard deviation. sd = "<< sd << "\n"; abort(); } DN_OneHabitat.push_back(sd); } } else if (EntryMode.compare("unif")==0) { double sd = input.GetNextElementDouble(); if (sd < 0) { std::cout << "In '--T3_DevelopmentalNoise', mode = unif. Received a negative standard deviation. sd = "<< sd << "\n"; abort(); } for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { DN_OneHabitat.push_back(sd); } } else { std::cout << "In option '--T3_fit (--T3_fitnessLandscape)', received EntryMode " << EntryMode << ". The only EntryMode accepted are 'A' and 'unif'. Sorry.\n"; abort(); } this->T3_DevelopmentalNoiseStandardDeviation.push_back(DN_OneHabitat); } // end of for habitat assert(this->T3_DevelopmentalNoiseStandardDeviation.size() == this->MaxEverHabitat+1); } else { this->T3_PhenoNbDimensions = 0; input.consideredFullyRead(); } } void SpeciesSpecificParameters::readT4_MutationRate(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T4_MutationRate', the std::string that is read is: " << input.print() << std::endl; #endif std::string mode = input.GetNextElementString(); if (mode == "unif") { double constantRate = input.GetNextElementDouble(); T4_MutationRate.push_back(constantRate); // yes, just one value. It will be taken care of. Not very clean though as a design T4_Total_Mutation_rate = constantRate * Gmap.T4_nbLoci; } else if (mode == "A") { double currentSum = 0.0; while (input.IsThereMoreToRead()) { if (input.isNextRKeyword()) { double inputValue = input.GetNextElementDouble(); int nbRepeats = input.GetNextElementInt(); if (inputValue < 0.0) { std::cout << "For option 'T4_MutationRate', received a negative rate (received " << inputValue << ").\n"; abort(); } if (inputValue > 0.5) { std::cout << "For option 'T4_MutationRate', received a value greater than 0.5 (received " << inputValue << ").\n"; abort(); } for (uint32_t repeat = 0 ; repeat < nbRepeats ; ++repeat) { currentSum += inputValue; T4_MutationRate.push_back(currentSum); } } else { double inputValue = input.GetNextElementDouble(); if (inputValue < 0.0) { std::cout << "For option 'T4_MutationRate', received a negative rate (received " << inputValue << ").\n"; abort(); } currentSum += inputValue; T4_MutationRate.push_back(currentSum); } } if (T4_MutationRate.size() != Gmap.T4_nbLoci) { std::cout << "For option 'T4_MutationRate', received " << T4_MutationRate.size() << " values but it was expected "<< Gmap.T4_nbLoci <<" values.\n"; abort(); } T4_Total_Mutation_rate = T4_MutationRate.back(); } else { std::cout << "For option 'T4_MutationRate', received the mode of entry '"<<mode<<"'. Sorry, only modes 'unif' and 'A' are accepted.\n"; abort(); } //std::cout << "T4_Total_Mutation_rate = " << T4_Total_Mutation_rate << "\n"; } void SpeciesSpecificParameters::readT8_MutationRate(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T8_MutationRate', the std::string that is read is: " << input.print() << std::endl; #endif std::string mode = input.GetNextElementString(); if (mode == "unif") { double constantRate = input.GetNextElementDouble(); T8_MutationRate.push_back(constantRate); // yes, just one value. It will be taken care of. Not very clean though as a design T8_Total_Mutation_rate = constantRate * Gmap.T8_nbLoci; } else if (mode == "A") { double currentSum = 0.0; while (input.IsThereMoreToRead()) { if (input.isNextRKeyword()) { double inputValue = input.GetNextElementDouble(); int nbRepeats = input.GetNextElementInt(); if (inputValue < 0.0) { std::cout << "For option --T8_mu, received a negative mutation rate (" << inputValue << ").\n"; abort(); } if (nbRepeats > Gmap.T8_nbLoci) { std::cout << "For option --T8_mu, received more valules than expected. Expected " << Gmap.T8_nbLoci << " values but received at least " << nbRepeats << " values\n"; abort(); } for (uint32_t repeat = 0 ; repeat < nbRepeats ; ++repeat) { currentSum += inputValue; T8_MutationRate.push_back(currentSum); } } else { double inputValue = input.GetNextElementDouble(); if (inputValue < 0.0) { std::cout << "For option --T8_mu, received a negative mutation rate (" << inputValue << ").\n"; abort(); } currentSum += inputValue; T8_MutationRate.push_back(currentSum); } } if (T8_MutationRate.size() != Gmap.T8_nbLoci) { std::cout << "For option --T8_mu, received " << T8_MutationRate.size() << " values while it was expecting " << Gmap.T8_nbLoci << " values.\n"; abort(); } T8_Total_Mutation_rate = T8_MutationRate.back(); } else { std::cout << "For option 'T8_MutationRate', received the mode of entry '"<<mode<<"'. Sorry, only modes 'unif' and 'A' are accepted.\n"; abort(); } //std::cout << "T8_Total_Mutation_rate = " << T8_Total_Mutation_rate << "\n"; } void SpeciesSpecificParameters::readT7fitnessParameters(InputReader& input) { /* T7phenpars.nbDimensions = input.GetNextElementInt(); if (T7phenpars.nbDimensions < 1) { std::cout << "For option --T7_fit, received a negative number of dimensions. Received " << T7phenpars.nbDimensions << "\n"; abort(); } auto type = input.GetNextElementString(); if (type != "linear" && type != "gaussian") { std::cout << "For option --T7_fit, expected a type of fitness lansdcape. Types accepted are 'linear' and 'gaussian'. Type received is " << type << "\n"; abort(); } T7phenpars.fitnessLandscapeType = type == "linear" ? 'L' : 'G'; T7phenpars.fitnessLandscapeOptimum = input.GetNextElementDouble(); if (T7phenpars.fitnessLandscapeOptimum < 0.0) { std::cout << "For option --T7_fit, expected a negative fitnessLandscapeOptimum\n"; abort(); } T7phenpars.fitnessLandscapeLinearGradient = input.GetNextElementDouble(); if (T7phenpars.fitnessLandscapeLinearGradient < 0.0) { std::cout << "For option --T7_fit, expected a negative fitnessLandscapeLinearGradients\n"; abort(); } T7phenpars.fitnessLandscapeGaussStrength = input.GetNextElementDouble(); if (T7phenpars.fitnessLandscapeLinearGradient < 0.0) { std::cout << "For option --T7_fit, expected a negative fitnessLandscapeGaussStrength\n"; abort(); } while (input.IsThereMoreToRead()) { auto x = input.GetNextElementInt(); if (x <= 0 || x > T7devpars.maxAge) { std::cout << "Invalid age in T7_fit.\n"; abort(); } T7phenpars.agesAtwhichPhenotypeIsSampled.push_back(x); } */ } void SpeciesSpecificParameters::readT7developmentParameters(InputReader& input) { T7devpars.maxAge = input.GetNextElementInt(); if (T7devpars.maxAge <= 0) { std::cout << "For option '--T7developmentParameters', first argument (maxAge) is not great than zero. Value received ("<<T7devpars.maxAge<<")\n"; abort(); } T7devpars.maxDeltaT = input.GetNextElementInt(); if (T7devpars.maxDeltaT <= 0) { std::cout << "For option '--T7developmentParameters', second argument (maxDeltaT) is not great than zero. Value received ("<<T7devpars.maxDeltaT<<")\n"; abort(); } T7devpars.basal_transcription_rate = input.GetNextElementDouble(); if (T7devpars.basal_transcription_rate < 0) { std::cout << "For option '--T7developmentParameters', third argument (basal_transcription_rate) is not great than zero. Value received ("<<T7devpars.basal_transcription_rate<<")\n"; abort(); } T7devpars.EPSILON = input.GetNextElementDouble(); if (T7devpars.EPSILON < 0) { std::cout << "For option '--T7developmentParameters', fourth argument (EPSILON) is not great than zero. Value received ("<<T7devpars.EPSILON<<")\n"; abort(); } T7devpars.stochasticDevelopment = input.GetNextElementBool(); T7devpars.fitnessOverTime = input.GetNextElementBool(); T7devpars.nbCisSites = input.GetNextElementInt(); if (T7devpars.nbCisSites < 0) { std::cout << "For option '--T7developmentParameters', fifth argument (T7devpars.nbCisSites) is not great than zero. Value received ("<<T7devpars.nbCisSites<<")\n"; abort(); } T7devpars.basic_signal_trans_effect = input.GetNextElementDouble(); if (T7devpars.basic_signal_trans_effect < 0) { std::cout << "For option '--T7developmentParameters', sixth argument (T7devpars.basic_signal_trans_effect) is not great than zero. Value received ("<<T7devpars.basic_signal_trans_effect<<")\n"; abort(); } T7devpars.basic_signal_conc = input.GetNextElementInt(); if (T7devpars.basic_signal_conc < 0) { std::cout << "For option '--T7developmentParameters', seventh argument (T7devpars.basic_signal_conc) is not great than zero. Value received ("<<T7devpars.basic_signal_conc<<")\n"; abort(); } T7devpars.protein_decayRate = input.GetNextElementDouble(); if (T7devpars.basic_signal_conc < 0) { std::cout << "For option '--T7developmentParameters', eighth argument (T7devpars.protein_decayRate) is not great than zero. Value received ("<<T7devpars.protein_decayRate<<")\n"; abort(); } T7devpars.mRNA_decayRate = input.GetNextElementDouble(); if (T7devpars.mRNA_decayRate < 0) { std::cout << "For option '--T7developmentParameters', nineth argument (T7devpars.mRNA_decayRate) is not great than zero. Value received ("<<T7devpars.mRNA_decayRate<<")\n"; abort(); } T7devpars.translationRate = input.GetNextElementDouble(); if (T7devpars.translationRate < 0) { std::cout << "For option '--T7developmentParameters', nineth argument (T7devpars.translationRate) is not great than zero. Value received ("<<T7devpars.translationRate<<")\n"; abort(); } } void SpeciesSpecificParameters::readT7_MutationRate(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T7_MutationRate', the std::string that is read is: " << input.print() << std::endl; #endif T7mutpars.duplication = input.GetNextElementDouble(); if (T7mutpars.duplication < 0) { std::cout << "For option 'T7_MutationRate', received a negative duplication mutation rate (received " << T7mutpars.duplication << "\n"; abort(); } T7mutpars.deletion = input.GetNextElementDouble(); if (T7mutpars.deletion < 0) { std::cout << "For option 'T7_MutationRate', received a negative deletion mutation rate (received " << T7mutpars.deletion << "\n"; abort(); } T7mutpars.cisEffectMu = input.GetNextElementDouble(); if (T7mutpars.cisEffectMu < 0) { std::cout << "For option 'T7_MutationRate', received a negative value for the cis effect mutation rate (received " << T7mutpars.cisEffectMu << "\n"; abort(); } T7mutpars.cisEffectSD = input.GetNextElementDouble(); if (T7mutpars.cisEffectSD < 0) { std::cout << "For option 'T7_MutationRate', received a negative value for 'cisEffectSD' (received " << T7mutpars.cisEffectSD << "\n"; abort(); } T7mutpars.transEffectMu = input.GetNextElementDouble(); if (T7mutpars.transEffectSD < 0) { std::cout << "For option 'T7_MutationRate', received a negative value for the trans effect mutation rate (received " << T7mutpars.transEffectMu << "\n"; abort(); } T7mutpars.transEffectSD = input.GetNextElementDouble(); if (T7mutpars.transEffectSD < 0) { std::cout << "For option 'T7_MutationRate', received a negative transEffectSD mutation rate (received " << T7mutpars.transEffectSD << "\n"; abort(); } T7mutpars.changeTargetMu = input.GetNextElementDouble(); if (T7mutpars.changeTargetMu < 0) { std::cout << "For option 'T7_MutationRate', received a negative value for thee mutation to change the target (aka. cisSite). (received " << T7mutpars.changeTargetMu << "\n"; abort(); } T7mutpars.totalMutationRatePerGene = T7mutpars.duplication + T7mutpars.deletion + T7mutpars.cisEffectMu + T7mutpars.transEffectMu; assert(T7mutpars.totalMutationRatePerGene >= 0); } void SpeciesSpecificParameters::readT4_simplifyEveryNGenerations(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T4_simplifyEveryNGenerations', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "default") { input.skipElement(); //std::cout << "SSP->TotalpatchCapacity = " << SSP->TotalpatchCapacity << "\n"; //std::cout << "SSP->TotalRecombinationRate = " << SSP->TotalRecombinationRate << "\n"; size_t maxEverTotalpatchCapacity = 0; for (auto& elem : maxEverpatchCapacity) maxEverTotalpatchCapacity += elem; auto nbNewEdgesPerGenerations = maxEverTotalpatchCapacity * (1 + this->TotalRecombinationRate); auto nbBytesPerGeneration = nbNewEdgesPerGenerations * 4 * 5; T4_simplifyEveryNGenerations = 1e9 / nbBytesPerGeneration; // This is a very arbitrary choice and will strongly affect the RAM vs CPU time trade-off. has not been thoroughly tested and might be a poor default choice. I could use something like (SSP->TotalpatchCapacity + SSP->TotalpatchCapacity * SSP->TotalRecombinationRate * 100000) * 100000; maybe if (T4_simplifyEveryNGenerations < 30) T4_simplifyEveryNGenerations = 30; } else { T4_simplifyEveryNGenerations = input.GetNextElementInt(); } if (T4_simplifyEveryNGenerations <= 0) { std::cout << "T4_simplifyEveryNGenerations was set to " << T4_simplifyEveryNGenerations << ".\nIt makes no sense to have a value lower than 1."; abort(); } } void SpeciesSpecificParameters::readT8_simplifyEveryNGenerations(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T4_simplifyEveryNGenerations', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "default") { input.skipElement(); //std::cout << "SSP->TotalpatchCapacity = " << SSP->TotalpatchCapacity << "\n"; //std::cout << "SSP->TotalRecombinationRate = " << SSP->TotalRecombinationRate << "\n"; size_t maxEverTotalpatchCapacity = 0; for (auto& elem : maxEverpatchCapacity) maxEverTotalpatchCapacity += elem; T8_simplifyEveryNGenerations = 2*maxEverTotalpatchCapacity; if (T8_simplifyEveryNGenerations < 30) T8_simplifyEveryNGenerations = 30; } else { T8_simplifyEveryNGenerations = input.GetNextElementInt(); } if (T8_simplifyEveryNGenerations <= 0) { std::cout << "T8_simplifyEveryNGenerations was set to " << T8_simplifyEveryNGenerations << ".\nIt makes no sense to have a value lower than 1."; abort(); } } void SpeciesSpecificParameters::readRecRateOnMismatch(InputReader& input) { #ifdef DEBUG std::cout << "For option 'recRateOnMismatch', the std::string that is read is: " << input.print() << std::endl; #endif if (input.PeakNextElementString() == "NA") { recRateOnMismatch_bool = false; input.skipElement(); } else { std::cout << "Sorry, the option 'readRecRateOnMismatch' has been disabled.\n"; if (this->Gmap.T1_nbLoci != this->Gmap.TotalNbLoci) { std::cout << "Sorry, recRateOnMismatch can only be used if you only use T1 loci.\n"; abort(); } recRateOnMismatch_bool = true; recRateOnMismatch_halfWindow = input.GetNextElementInt() / 2; recRateOnMismatch_factor = input.GetNextElementDouble(); if (recRateOnMismatch_halfWindow*2 > this->Gmap.T1_nbLoci ) { std::cout << "recRateOnMismatch_Window must be smaller or equal to the total number ot T1 loci. Received recRateOnMismatch_Window = " << 2 * recRateOnMismatch_halfWindow << " while there are " << this->Gmap.T1_nbLoci << " T1 loci." << std::endl; abort(); } if (recRateOnMismatch_factor >= 0.0) { std::cout << "recRateOnMismatch_factor must be negative. Received recRateOnMismatch_factor = " << recRateOnMismatch_factor << std::endl; abort(); } } } void SpeciesSpecificParameters::readRecombinationRate(InputReader& input) { #ifdef DEBUG std::cout << "For option 'RecombinationRate', the std::string that is read is: " << input.print() << std::endl; #endif std::string unit = input.GetNextElementString(); if (unit != "M" && unit != "cM" && unit != "rate") { std::cout << "Error found while reading option --r (--RecombinationRate): First entry for a given species is the unit. There are only three units possible, 'M', 'cM' and 'rate'. Unit received is " << unit << "\n"; abort(); } std::string Mode = input.GetNextElementString(); if (Mode.compare("unif")==0) { double InputValue = input.GetNextElementDouble(); //std::cout << "InputValue = " << InputValue << "\n"; double AddToParam; double cumsum = 0.0; if (InputValue == -1.0) { AddToParam = -1.0; } else { if (unit.compare("M")==0) { AddToParam = InputValue; } else if (unit.compare("cM")==0) { AddToParam = InputValue / 100; } else if (unit.compare("rate")==0) { if (InputValue > 0.5) { std::cout << "Error found while reading option --r (--RecombinationRate): Received unit 'rate' and value '"<< InputValue <<"'. When you indicate a recombination rate in 'rate' (as opposed to 'cM' or 'M'), you cannot specify a value greater than 0.5 because it makes no sense. Independent chromosome have a recombination rate of 0.5. If you meant to express a recombination distance in centimorgans or morgans, please use 'cM' or 'M' as a unit instead.\n"; abort(); } else if (InputValue == 0.5) { AddToParam = -1; } else AddToParam = - log(1 - 2 * InputValue)/2; } else { std::cout << "First element of option 'RecombinationRate' should be the unit (either 'M' (Morgan), 'cM' (centiMorgan) or 'c'(crossOver rate)) should be inputed. Value received is " << unit << ".\n"; abort(); } } if (AddToParam > 10) { std::cout << "In option '--RecombinationRate' received a value which equivalent 'M' is higher than 10 (received " << AddToParam << ". Is it really what you wanted? It is not going to be very efficient. Note you can have independent chromosomes with '-1' if this is what you want.\n"; abort(); } if (AddToParam == -1.0) { for (int pos=0 ; pos < (this->Gmap.TotalNbLoci - 1); pos++) { this->ChromosomeBoundaries.push_back(pos); } cumsum += 0.5; this->RecombinationRate.push_back(cumsum); } else { assert(AddToParam >= 0.0); cumsum += AddToParam; this->RecombinationRate.push_back(cumsum); } } else if (Mode.compare("A")==0) { double cumsum = 0.0; int pos=0; while (input.IsThereMoreToRead()) { int NbRepeats; double InputValue; double AddToParam; if (input.isNextRKeyword()) { InputValue = input.GetNextElementDouble(); NbRepeats = input.GetNextElementDouble(); if (NbRepeats < 0) { std::cout << "In option '--RecombinationRate', NbRepeats (not directly after indication 'R') is negative\n"; abort(); } } else { InputValue = input.GetNextElementDouble(); NbRepeats = 1; } if (unit.compare("M")==0) { if (InputValue==-1) { AddToParam = -1; } else if (InputValue >= 0) { AddToParam = InputValue; } else { std::cout << "In option '--RecombinationRate', Unit 'M' received a value which is negative but different from -1. Value received is " << InputValue << ".\n"; abort(); } } else if (unit.compare("cM")==0) { if (InputValue==-1) { AddToParam = -1; } else if (InputValue >= 0) { AddToParam = InputValue / 100; } else { std::cout << "In option '--RecombinationRate', Unit 'cM' received a value which is negative but different from -1. Value received is " << InputValue << ".\n"; abort(); } } else if (unit.compare("rate")==0) { if (InputValue==-1 || InputValue==0.5) { AddToParam = -1; } else if (InputValue >= 0 && InputValue < 0.5) { AddToParam = - log(1 - 2 * InputValue)/2; } else { std::cout << "In option '--RecombinationRate', Unit 'rate' received a value which is either negative but different from -1 or greater than 0.5. Value received is " << InputValue << ".\n"; abort(); } } else { std::cout << "First element of option 'RecombinationRate' should be the unit (either 'M' (Morgan), 'cM' (centiMorgan) or 'c'(crossOver rate)) should be inputed. Value received is " << unit << ".\n"; abort(); } if (AddToParam > 10) { std::cout << "In option '--RecombinationRate' received a value which equivalent 'M' is higher than 10 (received " << AddToParam << ". Is it really what you wanted? It is not going to be very efficient! Note you can have independent chromosomes with '-1' if this is what you want.\n"; abort(); } for (int rep = 0 ; rep < NbRepeats ; rep++) { if (AddToParam == -1) { cumsum += 0.5; this->ChromosomeBoundaries.push_back(pos); this->RecombinationRate.push_back(cumsum); } else if (AddToParam >= 0) { cumsum += AddToParam; this->RecombinationRate.push_back(cumsum); } else { std::cout << "Internal Error: Should not get here in function 'readRecombinationRate'\n"; abort(); } pos++; } } } else { std::cout << "Sorry, for 'RecombinationRate' only Mode 'unif' and 'A' are recognized so far. Mode received (" << Mode << " and unit " << unit << ") is unknown!" << std::endl; abort(); } if (this->RecombinationRate.size() == 1) { this->TotalRecombinationRate = this->RecombinationRate[0] * (this->Gmap.TotalNbLoci - 1); } else if (this->RecombinationRate.size() > 1) { this->TotalRecombinationRate = this->RecombinationRate.back(); } else { abort(); } assert(this->TotalRecombinationRate >= 0); if ( ( this->RecombinationRate.size() != this->Gmap.TotalNbLoci - 1 && this->RecombinationRate.size() != 1 ) || (this->Gmap.TotalNbLoci != 1 && this->RecombinationRate.size() == 1 && Mode.compare("A")==0) ) { std::cout << "In '--RecombinationRate' did not receive the expected number of elements!\n"; std::cout << "Nb values expected was " << this->Gmap.TotalNbLoci-1 << " (that is the total number of loci minus 1)\n\n"; std::cout << "\nthis->RecombinationRate.size() = " << this->RecombinationRate.size() << " this->Gmap.T1_nbLoci = " << this->Gmap.T1_nbLoci << " this->Gmap.T2_nbLoci = " << this->Gmap.T2_nbLoci << " this->Gmap.T3_nbLoci = " << this->Gmap.T3_nbLoci << " this->Gmap.T4_nbLoci = " << this->Gmap.T4_nbLoci << " this->Gmap.T56_nbLoci = " << this->Gmap.T56_nbLoci << " this->Gmap.TotalNbLoci = " << this->Gmap.TotalNbLoci << "\n\n"; abort(); } assert(this->ChromosomeBoundaries.size() < this->Gmap.TotalNbLoci); if (this->Gmap.TotalNbLoci < 2) { this->TotalRecombinationRate = 0; } } /*void SpeciesSpecificParameters::readT1_vcfOutput_sequence(InputReader& input) { #ifdef DEBUG std::cout << "For option 'T1_vcfOutput_sequence', the std::string that is read is: " << input.print() << std::endl; #endif std::string Mode = input.GetNextElementString(); if (Mode.compare("range") == 0) { int from = input.GetNextElementInt(); int to = input.GetNextElementInt(); if (from > to) { std::cout << "In option 'T1_vcfOutput_sequence', 'from' is greater than 'to' from = " << from << ", to = " << to << ".\n"; abort(); } if (from < 0) { std::cout << "In option 'T1_vcfOutput_sequence', 'from' is lower than zero from = " << from << ", to = " << to << ".\n"; abort(); } if (to >= this->Gmap.T1_nbLoci) { std::cout << "In option 'T1_vcfOutput_sequence', 'to' is greater or equal to the number of T1 loci from = " << from << ", to = " << to << ", number of T1 loci = " << this->Gmap.T1_nbLoci << ".\n"; abort(); } for (int locus = from ; locus <= to ; locus++) { T1_locusDescription T1_locus(locus / EIGHT, locus % EIGHT, locus); T1_vcfOutput_sequenceList.push_back(T1_locus); } T1_vcfOutput_sequenceIsRange = true; } else if (Mode.compare("A") == 0) { std::string sub; T1_vcfOutput_sequenceIsRange = true; // will be set to false if loci dont follow in a range while (input.IsThereMoreToRead()) { int locus = input.GetNextElementInt(); if (locus < 0) { std::cout << "In option 'T1_vcfOutput_sequence', 'locus' is lower than zero. locus = " << locus << ".\n"; abort(); } if (locus >= this->Gmap.T1_nbLoci) { std::cout << "In option 'T1_vcfOutput_sequence', 'locus' is equal or greater than the number the T1 loci. locus = " << locus << ". Number of T1 loci = " << this->Gmap.T1_nbLoci << ". Please note that the loci indices here must be zero-based counting. The first locus has index '0'. The last locus has index 'Number of T1 loci - 1'\n"; abort(); } T1_locusDescription T1_locus(locus / EIGHT, locus % EIGHT, locus); // Test if it is in a range if (T1_vcfOutput_sequenceList.size() > 0) { if (T1_vcfOutput_sequenceList.back().locus != T1_locus.locus - 1) { T1_vcfOutput_sequenceIsRange = false; } } // Add to T1_vcfOutput_sequenceList T1_vcfOutput_sequenceList.push_back(T1_locus); } } else { std::cout << "In option '--T1_vcfOutput_sequence', the only two Modes accepted are 'range' and 'A'. Mode received is '" << Mode << "\n"; abort(); } std::sort( T1_vcfOutput_sequenceList.begin(), T1_vcfOutput_sequenceList.end(), [](const T1_locusDescription& left, const T1_locusDescription& right) { return left.locus < right.locus; } ); if (T1_vcfOutput_sequenceList.size() > 1) { assert(T1_vcfOutput_sequenceList[0].locus < T1_vcfOutput_sequenceList[1].locus); } }*/ void SpeciesSpecificParameters::readKillOnDemand(InputReader& input) { killOnDemand.readUserInput(input); } void SpeciesSpecificParameters::IsThereSelection() { #ifdef CALLENTRANCEFUNCTIONS std::cout << "In 'IsThereSelection' start of T1_isSelection\n"; #endif T1_FitnessEffects.shrink_to_fit(); T2_FitnessEffects.shrink_to_fit(); T56_FitnessEffects.shrink_to_fit(); T8_FitnessEffects.shrink_to_fit(); if (Gmap.T1_nbLoci) { T1_isSelection=false; assert(this->T1_FitnessEffects.size() == this->MaxEverHabitat + 1); for (int Habitat = 0 ; Habitat <= this->MaxEverHabitat ; Habitat++) { for (int locus = 0 ; locus < this->Gmap.T1_nbLoci ; ++locus) { if (this->T1_isMultiplicitySelection) { assert(this->T1_FitnessEffects[Habitat].size() > locus); assert(this->T1_FitnessEffects[Habitat][locus] >= 0.0); if (this->T1_FitnessEffects[Habitat][locus] != 1.0) { this->T1_isSelection = true; goto T1isSelectionDone; } } else { for (int geno = 0;geno < this->ploidy+1;geno++) { assert(this->T1_FitnessEffects[Habitat].size() > (THREE * locus + geno)); assert(this->T1_FitnessEffects[Habitat][THREE * locus + geno] >= 0.0); if (this->T1_FitnessEffects[Habitat][THREE * locus + geno] != 1.0) { this->T1_isSelection = true; goto T1isSelectionDone; } } } } } T1isSelectionDone: // Local selection if (this->T1_isSelection && this->MaxEverHabitat > 1) { for (int locus = 0 ; locus < this->Gmap.T1_nbLoci ; ++locus) { for (int Habitat = 0 ; Habitat <= this->MaxEverHabitat ; Habitat++) { if (this->T1_isMultiplicitySelection) { if (this->T1_FitnessEffects[Habitat][locus] != this->T1_FitnessEffects[0][locus]) { this->T1_isLocalSelection = true; goto T1isLocalSelectionDone; } } else { for (int geno = 0; geno < this->ploidy+1;geno++) { if (this->T1_FitnessEffects[Habitat][THREE * locus + geno] != this->T1_FitnessEffects[0][THREE * locus + geno]) { this->T1_isLocalSelection = true; goto T1isLocalSelectionDone; } } } } } } } else { this->T1_isMultiplicitySelection = false; this->T1_isSelection = false; this->T1_isEpistasis = false; this->T1_isLocalSelection = false; } T1isLocalSelectionDone: if (!this->T1_isSelection) this->T1_isMultiplicitySelection = false; #ifdef CALLENTRANCEFUNCTIONS std::cout << "In 'IsThereSelection' start of T1_isEpistasis\n"; #endif if (this->Gmap.T1_nbLoci) { this->T1_isEpistasis = false; //std::cout << "this->Gmap.T1_nbChars = " << this->Gmap.T1_nbChars << "\n"; int howManyWarningGiven = 0; //std::cout << "this->T1_Epistasis_LociIndices.size() = " << this->T1_Epistasis_LociIndices.size() << "\n"; if (this->T1_Epistasis_LociIndices.size() != 0) { //std::cout << "this->MaxEverHabitat = " << this->MaxEverHabitat << "\n"; //std::cout << "this->T1_Epistasis_FitnessEffects.size() = " << this->T1_Epistasis_FitnessEffects.size() << "\n"; assert(this->T1_Epistasis_FitnessEffects.size() == this->MaxEverHabitat + 1); for (int Habitat = 0 ; Habitat <= this->MaxEverHabitat ; Habitat++) { //std::cout << "this->T1_Epistasis_FitnessEffects[Habitat].size() = " << this->T1_Epistasis_FitnessEffects[Habitat].size() << "\n"; for (int groupOfLociIndex = 0 ; groupOfLociIndex < this->T1_Epistasis_FitnessEffects[Habitat].size() ; groupOfLociIndex++) { //std::cout << "groupOfLociIndex = " << groupOfLociIndex << "\n"; assert(this->T1_Epistasis_LociIndices[Habitat].size() > groupOfLociIndex); // Send warnings if a locus is under both types of selection for (auto& T1_locus : this->T1_Epistasis_LociIndices[Habitat][groupOfLociIndex]) { //std::cout << "T1_locus.locus = " << T1_locus.locus << "\n"; if (this->T1_FitnessEffects.size() != 0) { if (this->T1_isMultiplicitySelection) { assert(this->T1_FitnessEffects.size() > Habitat); assert(this->T1_FitnessEffects[Habitat].size() > T1_locus.locus); if (this->T1_FitnessEffects[Habitat][T1_locus.locus] != 1.0) { if (howManyWarningGiven < 50) { std::cout << "\tWARNING: The " << T1_locus.locus << "th locus is under both epistatic selection (--T1_epistasis (--T1_EpistaticFitnessEffects)) and regular selection (--T1_fit (--T1_FitnessEffects)) under habitat " << Habitat << ".\n"; howManyWarningGiven++; } else { if (howManyWarningGiven == 50) { std::cout << "You should have already received 50 warnings for having a locus under both types of selection. Further warnings will be silenced.\n"; howManyWarningGiven++; } } } } else { bool ShouldIGiveWarning = false; for (int geno=0 ; geno <= this->ploidy ; geno++) { //std::cout << "geno = " << geno << "\n"; assert(this->T1_FitnessEffects.size() > Habitat); assert(this->T1_FitnessEffects[Habitat].size() > THREE * T1_locus.locus + geno); //std::cout << "this->T1_FitnessEffects[Habitat][THREE * T1_locus.locus + geno] = " << this->T1_FitnessEffects[Habitat][THREE * T1_locus.locus + geno] << "\n"; //std::cout << "this->T1_FitnessEffects[Habitat][THREE * T1_locus.locus] = " << this->T1_FitnessEffects[Habitat][THREE * T1_locus.locus] << "\n"; if (this->T1_FitnessEffects[Habitat][THREE * T1_locus.locus + geno] != this->T1_FitnessEffects[Habitat][THREE * T1_locus.locus]) { ShouldIGiveWarning = true; break; } } if (ShouldIGiveWarning) { if (howManyWarningGiven < 50) { std::cout << "\tWARNING: The " << T1_locus.locus << "th locus is under both epistatic selection (--T1_epistasis (--T1_EpistaticFitnessEffects)) and regular selection (--T1_fit (--T1_FitnessEffects)) under habitat " << Habitat << ".\n"; howManyWarningGiven++; } else { if (howManyWarningGiven == 50) { std::cout << "You should have already received 50 warnings for having a locus under both types of selection. Further warnings will be silenced.\n"; howManyWarningGiven++; } } } } } } // Check if there is any selection assert(this->T1_Epistasis_FitnessEffects.size() > Habitat); assert(this->T1_Epistasis_FitnessEffects[Habitat].size() > groupOfLociIndex); for (auto& fit : this->T1_Epistasis_FitnessEffects[Habitat][groupOfLociIndex]) { if (fit != this->T1_Epistasis_FitnessEffects[Habitat][groupOfLociIndex][0]) { this->T1_isEpistasis = true; } } } // end of groupOfLoci } } else { assert(this->T1_Epistasis_FitnessEffects.size() == 0); } } else { this->T1_isMultiplicitySelection = false; this->T1_isSelection = false; this->T1_isEpistasis = false; this->T1_isLocalSelection = false; } #ifdef CALLENTRANCEFUNCTIONS std::cout << "In 'IsThereSelection' start of T8_isSelection\n"; #endif if (Gmap.T8_nbLoci) { T8_isSelection=false; for (int locus = 0 ; locus < this->Gmap.T8_nbLoci ; ++locus) { assert(this->T8_FitnessEffects.size() > locus); assert(this->T8_FitnessEffects[locus] > 0.0); if (this->T8_FitnessEffects[locus] != 1.0) { this->T8_isSelection = true; goto T8isSelectionDone; } } } else { this->T8_isSelection = false; } T8isSelectionDone: #ifdef CALLENTRANCEFUNCTIONS std::cout << "In 'IsThereSelection' start of T2_isSelection\n"; #endif if (this->Gmap.T2_nbLoci) { this->T2_isSelection = false; assert(T2_FitnessEffects.size() == this->MaxEverHabitat + 1); for (int Habitat = 0 ; Habitat <= this->MaxEverHabitat ; Habitat++) { for (int T2_char_index=0;T2_char_index < this->Gmap.T2_nbLoci;T2_char_index++) { assert(this->T2_FitnessEffects[Habitat].size() > T2_char_index); if (this->T2_FitnessEffects[Habitat][T2_char_index] != 1.0) { this->T2_isSelection = true; goto T2isSelectionDone; } } } T2isSelectionDone: // Local selection if (this->T2_isSelection && this->MaxEverHabitat > 1) { for (int locus = 0 ; locus < this->Gmap.T2_nbLoci ; ++locus) { for (int Habitat = 0 ; Habitat <= this->MaxEverHabitat ; Habitat++) { if (this->T2_FitnessEffects[Habitat][locus] != this->T2_FitnessEffects[0][locus]) { this->T2_isLocalSelection = true; goto T2isLocalSelectionDone; } } } } } else { this->T2_isSelection = false; } T2isLocalSelectionDone: #ifdef CALLENTRANCEFUNCTIONS std::cout << "In 'IsThereSelection' start of T3_isSelection\n"; #endif if (this->Gmap.T3_nbLoci) { this->T3_isSelection=false; if (this->T3_fitnessLandscapeType!='L' && this->T3_fitnessLandscapeType!='G') { std::cout << "Internal error: function 'IsThereSelection' only knows how to deal with T3_fitnessLandscapeType=='L' and T3_fitnessLandscapeType=='G' but it appears that T3_fitnessLandscapeType=="<<this->T3_fitnessLandscapeType<<"\n"; abort(); } if (this->T3_PhenoNbDimensions < 1) { std::cout << "Internal error: In 'IsThereSelection' the number of dimensions for T3 is lower than 1. It is "<<this->T3_PhenoNbDimensions<<".\n"; abort(); } if (this->T3_fitnessLandscapeType=='L') { assert(this->T3_fitnessLandscapeLinearGradient.size() == this->T3_fitnessLandscapeOptimum.size()); assert(this->T3_fitnessLandscapeLinearGradient.size() == this->MaxEverHabitat + 1); for (int Habitat = 0 ; Habitat <= this->MaxEverHabitat ; Habitat++) { assert(this->T3_fitnessLandscapeLinearGradient[Habitat].size() == this->T3_fitnessLandscapeOptimum[Habitat].size()); assert(this->T3_fitnessLandscapeLinearGradient[Habitat].size() == this->T3_PhenoNbDimensions); for (int dim = 0 ; dim < this->T3_PhenoNbDimensions ; dim++) { if (this->T3_fitnessLandscapeLinearGradient[Habitat][dim] != 0.0) { this->T3_isSelection = true; goto T3isSelectionDone; } } } } else if (this->T3_fitnessLandscapeType=='G') { for (auto& elem1 : this->T3_fitnessLandscapeGaussStrength) { for (auto& elem2 : elem1) { assert(elem2 > 0.0); } } // There is necessarily some selection unless this->T3_fitnessLandscapeGaussian is infinity which is impossible. this->T3_isSelection = true; } else { std::cout << "Internal error in funciton IsThereSelection\n"; abort(); } T3isSelectionDone: if (T3_isSelection) T3_isLocalSelection = true; // This could really be improved. A priori I don't think it will have any consequence for the moment though } else { this->T3_isSelection = false; } #ifdef CALLENTRANCEFUNCTIONS std::cout << "In 'IsThereSelection' end of T3_isSelection\n"; #endif #ifdef CALLENTRANCEFUNCTIONS std::cout << "In 'IsThereSelection' start of T56_isSelection\n"; #endif //std::cout << "T5sel_nbLoci = " << T5sel_nbLoci << "\n"; if (Gmap.T56sel_nbLoci) { this->T56_isSelection = true; } else { this->T56_isSelection = false; this->T56_isMultiplicitySelection = false; this->T56_isLocalSelection = false; } //std::cout << "this->T56_isSelection = " << this->T56_isSelection << "\n"; if (this->T56_isSelection) { assert(this->T56_FitnessEffects.size() == this->MaxEverHabitat + 1); for (int locus = 0 ; locus < this->Gmap.T5sel_nbLoci ; ++locus) { for (int Habitat = 0 ; Habitat <= this->MaxEverHabitat ; Habitat++) { if (this->T56_isMultiplicitySelection) { assert(this->T56_FitnessEffects[Habitat].size() > locus); assert(this->T56_FitnessEffects[Habitat][locus] >= 0.0); if (this->T56_FitnessEffects[Habitat][locus] != this->T56_FitnessEffects[0][locus]) { this->T56_isLocalSelection = true; // no need for goto as I actually want the assert statements to run by security } } else { for (int geno = 0; geno < 2; geno++) // only values for het and double mutant { assert(this->T56_FitnessEffects[Habitat].size() > (2 * locus + geno)); assert(this->T56_FitnessEffects[Habitat][2 * locus + geno] >= 0.0); if (this->T56_FitnessEffects[Habitat][2 * locus + geno] != this->T56_FitnessEffects[0][2 * locus + geno]) { this->T56_isLocalSelection = true; // no need for goto as I actually want the assert statements to run by security } } } } } } if (!this->T56_isSelection) { this->T56_isMultiplicitySelection = false; this->T56_isLocalSelection = false; } #ifdef CALLENTRANCEFUNCTIONS std::cout << "In 'IsThereSelection' end of T56_isSelection\n"; #endif // if fecundity is different from -1, then dispersal rate necessarily depends on fitness if (this->fecundityForFitnessOfOne != -1.0) { assert(this->DispWeightByFitness); } // Dispersal probability cannot be a function of fitness if there is no selection if (!this->T1_isSelection && !this->T1_isEpistasis && !this->T2_isSelection && !this->T3_isSelection && !this->T56_isSelection && !this->T8_isSelection ) { isAnySelection = false; this->selectionOn = 0; // This is to avoid some bullshit in lifeCycle.pp if (this->fecundityForFitnessOfOne == -1.0) this->DispWeightByFitness = false; } else { isAnySelection = true; } if (this->MaxEverHabitat == 1) { this->T1_isLocalSelection = false; this->T2_isLocalSelection = false; this->T3_isLocalSelection = false; this->T56_isLocalSelection = false; } if (additiveEffectAmongLoci && (Gmap.T2_nbLoci || T1_isMultiplicitySelection || T56_isMultiplicitySelection)) { std::cout << "For option --additiveEffectAmongLoci, received 'true' (selective effects are additive among loci, including loci of different types). However, you used the multfit (multiplicative fitness) assumption, either for T1, T2 or T5 loci. This is not compatible.\n"; abort(); } } /*void SpeciesSpecificParameters::ClearT1_Initial_AlleleFreqs() { for ( int patch_index = 0 ; patch_index < this->T1_Initial_AlleleFreqs.size() ; ++patch_index ) { this->T1_Initial_AlleleFreqs[patch_index].clear(); } this->T1_Initial_AlleleFreqs.clear(); }*/ /*void SpeciesSpecificParameters::setInitialT1_AlleleFreqTo(const int uniqueFreq) { std::vector<double> line(this->Gmap.T1_nbChars); for (int T1_char_index=0;T1_char_index<this->Gmap.T1_nbChars;T1_char_index++) { line[T1_char_index] = uniqueFreq; } for (int patch_index=0;patch_index<GP->PatchNumber;++patch_index) { this->T1_Initial_AlleleFreqs.push_back(line); } }*/ std::vector<int> SpeciesSpecificParameters::UpdateParameters(int generation_index) { #ifdef DEBUG std::cout << "Enters in SpeciesSpecificParameters::UpdateParameters\n"; #endif /* std::cout << "patchSize when enterin SpeciesSpecificParameters::UpdateParameters: "; for (auto& e : patchSize) std::cout << e << " "; std::cout << "\n"; */ // Change patchCapacity Do not change patchSize yet as it will be used later assert(generation_index < this->__patchCapacity.size()); this->patchCapacity = this->__patchCapacity[generation_index]; this->patchCapacity.shrink_to_fit(); assert(this->patchCapacity.size() == GP->PatchNumber); // Change Patch size assert(this->patchSize.size()>0); this->patchSize.resize(GP->PatchNumber, 0); // complete with zeros this->patchSize.shrink_to_fit(); assert(this->patchSize.size() == GP->PatchNumber); std::vector<int> previousPatchSizes = this->patchSize; for (int patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index) { if (this->patchSize[patch_index] > this->patchCapacity[patch_index]) this->patchSize[patch_index] = this->patchCapacity[patch_index]; } // Set patch size to carrying capacity if it is not allowed to differ from it. Also change TotalpatchSize // Also change TotalpatchCapacity TotalpatchSize = 0; if (this->fecundityForFitnessOfOne == -1.0) { for (int patch_index = 0 ; patch_index < GP->PatchNumber ; ++patch_index) { this->patchSize[patch_index] = this->patchCapacity[patch_index]; TotalpatchSize += this->patchCapacity[patch_index]; } } else { this->TotalpatchCapacity = 0; for ( auto& OnepatchCapacity : this->patchCapacity ) { this->TotalpatchCapacity += OnepatchCapacity; } } if (T5_freqThresholdWasSetToDefault) this->resetT56_freqThresholToDefault(); // change Habitat this->Habitats = this->__Habitats[generation_index]; this->MaxHabitat = this->__MaxHabitat[generation_index]; assert(this->Habitats.size() == GP->PatchNumber); // Change growth model growthK = __growthK[generation_index]; assert(growthK.size() == GP->PatchNumber); // Change DispMat this->dispersalData.nextGenerationPatchSizes = SSP->patchCapacity; assert(this->dispersalData.__forwardMigration.size() > generation_index); assert(this->dispersalData.__forwardMigrationIndex.size() > generation_index); this->dispersalData.forwardMigration = this->dispersalData.__forwardMigration[generation_index]; this->dispersalData.forwardMigrationIndex = this->dispersalData.__forwardMigrationIndex[generation_index]; this->dispersalData.BackwardMigration.resize(GP->PatchNumber); this->dispersalData.BackwardMigrationIndex.resize(GP->PatchNumber); std::vector<unsigned> howManySendToMe(GP->PatchNumber, 0); //howManySendToMe[patch_to] returns number of patch sending migrants to "patch_to" assert(howManySendToMe.size() == GP->PatchNumber); assert(dispersalData.forwardMigrationIndex.size() == GP->PatchNumber); assert(dispersalData.forwardMigrationIndex.size() == dispersalData.forwardMigration.size()); for (int patch_from = 0 ; patch_from < GP->PatchNumber ; ++patch_from) { for (auto& patch_to : dispersalData.forwardMigrationIndex[patch_from]) { assert(patch_to < GP->PatchNumber); howManySendToMe[patch_to]++; } } for (int patch_to = 0 ; patch_to < GP->PatchNumber ; ++patch_to) { //std::cout << "howManySendToMe["<<patch_to<<"] = " << howManySendToMe[patch_to] << "\n"; this->dispersalData.BackwardMigration[patch_to].resize(howManySendToMe[patch_to]); this->dispersalData.BackwardMigrationIndex[patch_to].resize(howManySendToMe[patch_to]); } (void) this->dispersalData.setOriginalBackwardMigrationIfNeeded(); assert(this->dispersalData.forwardMigration.size() == GP->PatchNumber); /* std::cout << "patchSize when exiting SpeciesSpecificParameters::UpdateParameters: "; for (auto& e : patchSize) std::cout << e << " "; std::cout << "\n"; */ return previousPatchSizes; // This return value will be used to know what individuals to duplicate } void SpeciesSpecificParameters::readStochasticGrowth(InputReader& input) { #ifdef DEBUG std::cout << "Enters in SpeciesSpecificParameters::readStochasticGrowth\n"; #endif if (input.PeakNextElementString() == "default") { input.skipElement(); stochasticGrowth = true; } else { stochasticGrowth = input.GetNextElementBool(); } } void SpeciesSpecificParameters::readadditiveEffectAmongLoci(InputReader& input) { #ifdef DEBUG std::cout << "Enters in SpeciesSpecificParameters::readadditiveEffectAmongLoci\n"; #endif if (input.PeakNextElementString() == "default") { input.skipElement(); additiveEffectAmongLoci = false; } else { additiveEffectAmongLoci = input.GetNextElementBool(); } if (additiveEffectAmongLoci) { std::cout << "For option --additiveEffectAmongLoci, received 'true' (or equivalent). In the current version effects among loci can only be multiplicative. Sorry!\n"; abort(); } } void SpeciesSpecificParameters::readReadPopFromBinary(InputReader& input) { #ifdef DEBUG std::cout << "Enters in SpeciesSpecificParameters::readReadPopFromBinary\n"; #endif std::string yesNo = input.GetNextElementString(); if (yesNo == "yes" || yesNo == "y" || yesNo == "Y" || yesNo == "YES" || yesNo == "true" || yesNo == "1") { readPopFromBinary = true; // read file path readPopFromBinaryPath = input.GetNextElementString(); // test that the file exists std::ifstream f(readPopFromBinaryPath); if (!f.good()) { std::cout << "For species " << speciesName << ", in function 'SpeciesSpecificParameters::readReadPopFromBinary', the file " << readPopFromBinaryPath << " was not found. Note that paths to read binary populations from are NOT relative to the general path (the general path only applies to outputs).\n"; abort(); } } else if (yesNo == "no" || yesNo == "n" || yesNo == "N" || yesNo == "NO" || yesNo == "false" || yesNo == "0") { readPopFromBinary = false; readPopFromBinaryPath = ""; } else { std::cout << "For option '--readReadPopFromBinary', the first element received is " << yesNo << ". Expected 'yes' (or 'y', 'Y', 'true', '1', etc...), 'no' (or 'n', 'NO', '0', 'false', etc...) as to whether the population must be initialized based on a binary file.\n"; abort(); } } void SpeciesSpecificParameters::readT8_propagationMethod(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); T8_propagationMethod = 1; if (SSP->RecombinationRate.back() == 0) T8_WhenToSortData = '0'; else T8_WhenToSortData = 'P'; } else { T8_propagationMethod = input.GetNextElementInt(); if (T8_propagationMethod != 1 && T8_propagationMethod != 2) { std::cout << "For option --T8_propagationMethod, two elements are expected the method of propagation and how mutattions should be sorted. Received value '" << T8_propagationMethod << "'. Sorry, only '1' and '2' are valid methods of propagation.\n"; abort(); } auto s = input.GetNextElementString(); if (s == "endOfPropagation" || s == "p") { T8_WhenToSortData = 'p'; } else if (s == "duringPropagation" || s == "P" ) { T8_WhenToSortData = 'P'; } else if (s == "notSorted" || s == "0") { T8_WhenToSortData = '0'; } else { std::cout << "For option --T8_propagationMethod, two elements are expected the method of propagation and how mutations should be sorted. Received value '" << s << "'. Sorry, only 'endOfProbagation', 'duringProbagation' and 'notSorted' valid methods of sorting for T8 loci.\n"; abort(); } } /* if (T8_propagationMethod == 2 && T8_WhenToSortData == 'P') { std::cout << "For option --T8_propagationMethod, two elements are expected the method of propagation and whether ohw values must be sorted. Sorry, with method of propagation 2, sorting cannot happen during propagation.\n"; abort(); } */ std::cout << "T8_propagationMethod = " << static_cast<unsigned>(T8_propagationMethod) << "\n"; std::cout << "T8_WhenToSortData = " << T8_WhenToSortData << "\n"; } void SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input) { // Make sure it starts by LociSet! if (input.PeakNextElementString() != "LociSet") { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), the very first word expected (after the time information and species specific marker) was the keyword 'LociSet'. Instead, SimBit received received "<<input.PeakNextElementString()<<".\n"; abort(); } int nbLociSets = 0; std::string whichT; while (input.IsThereMoreToRead()) { if (input.PeakNextElementString() == "LociSet") { input.skipElement(); std::string whichTstring = input.PeakNextElementString(); if (whichTstring != "T1" && whichTstring != "T2" && whichTstring != "T3" && whichTstring != "T1epistasis") { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), expected a description of the type of locus (T1, T2, T3 or T1epistasis) after the keyword 'LociSet' but instead it received "<<whichTstring<<".\n"; abort(); } nbLociSets++; // prepare vectors subsetT1LociForfitnessSubsetLoci_file.push_back({}); subsetT2LociForfitnessSubsetLoci_file.push_back({}); subsetT3LociForfitnessSubsetLoci_file.push_back({}); subsetT5LociForfitnessSubsetLoci_file.push_back({}); subsetT1epistasisLociForfitnessSubsetLoci_file.push_back({}); assert(subsetT1LociForfitnessSubsetLoci_file.size() == nbLociSets); assert(subsetT2LociForfitnessSubsetLoci_file.size() == nbLociSets); assert(subsetT3LociForfitnessSubsetLoci_file.size() == nbLociSets); assert(subsetT5LociForfitnessSubsetLoci_file.size() == nbLociSets); assert(subsetT1epistasisLociForfitnessSubsetLoci_file.size() == nbLociSets); } else { std::string eventualTstring = input.PeakNextElementString(); if (eventualTstring.at(0) == 'T') { input.skipElement(); whichT = eventualTstring; if (whichT != "T1" && whichT != "T2" && whichT != "T3" && whichT != "T1epistasis") { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received a type of locus descriptor starting with the letter 'T', however it was not followed by '1', '2', '3' or '1epistasis'. The type of locus descriptor received is "<<whichT<<".\n"; abort(); } } int locus = input.GetNextElementInt(); if (whichT == "T1") { //std::cout << "locus = " << locus << "\n"; //std::cout << "T1_nbLoci = " << T1_nbLoci << "\n"; if (locus < 0 || locus >= Gmap.T1_nbLoci) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait of type "<<whichT<<". Only positive number lower than the total number of loci is accepted. As a reminder, the first locus has index 0 and the last locus has index nbLociForThisTrait-1 (T1_nbLoci = "<<Gmap.T1_nbLoci<<", T2_nbLoci = "<<Gmap.T2_nbLoci<<", T3_nbLoci = "<<Gmap.T3_nbLoci<<", T56_nbLoci = "<<Gmap.T56_nbLoci<<")\n"; abort(); } if ( std::find( subsetT1LociForfitnessSubsetLoci_file.back().begin(), subsetT1LociForfitnessSubsetLoci_file.back().end(), locus ) != subsetT1LociForfitnessSubsetLoci_file.back().end() ) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait type "<<whichT<<" several times within a single LociSet.\n"; abort(); } subsetT1LociForfitnessSubsetLoci_file.back().push_back(locus); } else if (whichT == "T2") { if (locus < 0 || locus >= Gmap.T2_nbLoci) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait of type "<<whichT<<". Only positive number lower than the total number of loci is accepted. As a reminder, the first locus has index 0 and the last locus has index nbLociForThisTrait-1 (T1_nbLoci = "<<Gmap.T1_nbLoci<<", T2_nbLoci = "<<Gmap.T2_nbLoci<<", T3_nbLoci = "<<Gmap.T3_nbLoci<<", T56_nbLoci = "<<Gmap.T56_nbLoci<<")\n"; abort(); } if ( std::find( subsetT2LociForfitnessSubsetLoci_file.back().begin(), subsetT2LociForfitnessSubsetLoci_file.back().end(), locus ) != subsetT2LociForfitnessSubsetLoci_file.back().end() ) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait type "<<whichT<<" several times within a single LociSet.\n"; abort(); } subsetT2LociForfitnessSubsetLoci_file.back().push_back(locus); } else if (whichT == "T3") { if (locus < 0 || locus >= Gmap.T3_nbLoci) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait of type "<<whichT<<". Only positive number lower than the total number of loci is accepted. As a reminder, the first locus has index 0 and the last locus has index nbLociForThisTrait-1 (T1_nbLoci = "<<Gmap.T1_nbLoci<<", T2_nbLoci = "<<Gmap.T2_nbLoci<<", T3_nbLoci = "<<Gmap.T3_nbLoci<<", T56_nbLoci = "<<Gmap.T56_nbLoci<<")\n"; abort(); } if ( std::find( subsetT3LociForfitnessSubsetLoci_file.back().begin(), subsetT3LociForfitnessSubsetLoci_file.back().end(), locus ) != subsetT3LociForfitnessSubsetLoci_file.back().end() ) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait type "<<whichT<<" several times within a single LociSet.\n"; abort(); } subsetT3LociForfitnessSubsetLoci_file.back().push_back(locus); } else if (whichT == "T1epistasis") { if (locus < 0 || locus >= Gmap.T1_nbLoci) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait of type "<<whichT<<". Only positive number lower than the total number of loci is accepted. As a reminder, the first locus has index 0 and the last locus has index nbLociForThisTrait-1 (T1_nbLoci = "<<Gmap.T1_nbLoci<<", T2_nbLoci = "<<Gmap.T2_nbLoci<<", T3_nbLoci = "<<Gmap.T3_nbLoci<<", T56_nbLoci = "<<Gmap.T56_nbLoci<<")\n"; abort(); } if ( std::find( subsetT1epistasisLociForfitnessSubsetLoci_file.back().begin(), subsetT1epistasisLociForfitnessSubsetLoci_file.back().end(), locus ) != subsetT1epistasisLociForfitnessSubsetLoci_file.back().end() ) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait type "<<whichT<<" several times within a single LociSet.\n"; abort(); } subsetT1epistasisLociForfitnessSubsetLoci_file.back().push_back(locus); } else if (whichT == "T5") { //std::cout << "locus = " << locus << "\n"; //std::cout << "T1_nbLoci = " << T1_nbLoci << "\n"; if (locus < 0 || locus >= Gmap.T56_nbLoci) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait of type "<<whichT<<". Only positive number lower than the total number of loci is accepted. As a reminder, the first locus has index 0 and the last locus has index nbLociForThisTrait-1 (T1_nbLoci = "<<Gmap.T1_nbLoci<<", T2_nbLoci = "<<Gmap.T2_nbLoci<<", T3_nbLoci = "<<Gmap.T3_nbLoci<<", T56_nbLoci = "<<Gmap.T56_nbLoci<<")\n"; abort(); } if ( std::find( subsetT5LociForfitnessSubsetLoci_file.back().begin(), subsetT5LociForfitnessSubsetLoci_file.back().end(), locus ) != subsetT5LociForfitnessSubsetLoci_file.back().end() ) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received the locus index " << locus << " for trait type "<<whichT<<" several times within a single LociSet.\n"; abort(); } subsetT5LociForfitnessSubsetLoci_file.back().push_back(locus); } else { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received a type of locus descriptor starting with the letter 'T', however it was not followed by '1', '2', '3', '5' or '1epistasis'. The type of locus descriptor received is "<<whichT<<". Note that this error message comes at a bit of an unexpected time and might therefore be due to an internal error. You might want to check your input nevertheless.\n"; abort(); } } } // Make sure at least one set has been received assert(subsetT1LociForfitnessSubsetLoci_file.size() == nbLociSets); assert(subsetT2LociForfitnessSubsetLoci_file.size() == nbLociSets); assert(subsetT3LociForfitnessSubsetLoci_file.size() == nbLociSets); assert(subsetT5LociForfitnessSubsetLoci_file.size() == nbLociSets); assert(subsetT1epistasisLociForfitnessSubsetLoci_file.size() == nbLociSets); if (nbLociSets == 0) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), received 0 LociSet.\n"; abort(); } // Make sure there is not empty set and also just sort them for fun! for (int lociSetIndex = 0 ; lociSetIndex < nbLociSets; lociSetIndex++) { if ( subsetT1LociForfitnessSubsetLoci_file[lociSetIndex].size() == 0 && subsetT2LociForfitnessSubsetLoci_file[lociSetIndex].size() == 0 && subsetT3LociForfitnessSubsetLoci_file[lociSetIndex].size() == 0 && subsetT5LociForfitnessSubsetLoci_file[lociSetIndex].size() == 0 && subsetT1epistasisLociForfitnessSubsetLoci_file[lociSetIndex].size() == 0 ) { std::cout << "For option --fitnessStats_file, in function SpeciesSpecificParameters::readSubsetLociForfitnessSubsetLoci_file(InputReader& input), the "<<lociSetIndex<<"th LociSet seem to contain no locus of any type! Maybe the keyword 'LociSet' has been repeated twice (or more times) without indicating loci indices in between. Maybe the option argument ends with the keyword 'LociSet'.\n"; abort(); } std::sort( subsetT1LociForfitnessSubsetLoci_file[lociSetIndex].begin(), subsetT1LociForfitnessSubsetLoci_file[lociSetIndex].end() ); std::sort( subsetT2LociForfitnessSubsetLoci_file[lociSetIndex].begin(), subsetT2LociForfitnessSubsetLoci_file[lociSetIndex].end() ); std::sort( subsetT3LociForfitnessSubsetLoci_file[lociSetIndex].begin(), subsetT3LociForfitnessSubsetLoci_file[lociSetIndex].end() ); std::sort( subsetT5LociForfitnessSubsetLoci_file[lociSetIndex].begin(), subsetT5LociForfitnessSubsetLoci_file[lociSetIndex].end() ); std::sort( subsetT1epistasisLociForfitnessSubsetLoci_file[lociSetIndex].begin(), subsetT1epistasisLociForfitnessSubsetLoci_file[lociSetIndex].end() ); } } void SpeciesSpecificParameters::readQuickScreenOfOptionL(InputReader& input) { quickScreenAtL_T56_nbLoci = 0; while( input.IsThereMoreToRead() ) { auto tmp = input.GetNextLocusInfo(); auto type = tmp.first; auto nbElements = tmp.second; if (type == 5) { quickScreenAtL_T56_nbLoci += nbElements; } else { if ( type != 1 && type != 2 && type != 3 && type != 4 && type != 7 && type != 8 ) { std::cout << "While making a quick screen through the option --L (--Loci), SimBit has found a unexpected type of trait (type "<< type << ").\n"; abort(); } } } //std::cout << "quickScreenAtL_T56_nbLoci = " << quickScreenAtL_T56_nbLoci << "\n"; } void SpeciesSpecificParameters::readkillIndividuals(InputReader& input) { if (input.PeakNextElementString() == "default") { input.skipElement(); return; } if (input.IsThereMoreToRead() && fecundityForFitnessOfOne == -1) { std::cout << "Option --killIndividuals can only be used if fecundity is different from -1 (SimBit cannot kill arbitrary individuals if the patch size cannot vary from the carrying capacity).\n"; abort(); } while (input.IsThereMoreToRead()) { // Expecting 'kill' { auto s = input.GetNextElementString(); if (s != "kill") { std::cout << "For option --killIndividuals, expected keyword 'kill' but got " << s << " instead.\n"; abort(); } } // Check if allBut bool isAllBut = false; { auto s = input.PeakNextElementString(); if (s == "allBut" || s == "allbut" || s == "AllBut" || s == "Allbut") { isAllBut = true; input.skipElement(); } } // Read number of individuals int nbInds; { nbInds = input.GetNextElementInt(); if (nbInds < 0) { if (isAllBut) { std::cout << "For option --killIndividuals, you asked to kill all but ('allBut') " << nbInds << " individuals. Cannot leave a negative number of indivduals.\n"; abort(); } else { std::cout << "For option --killIndividuals, you asked to kill " << nbInds << " individuals. Cannot kill a negative number of indivduals.\n"; abort(); } } } // Expecting 'patch' { auto s = input.GetNextElementString(); if (s != "patch") { std::cout << "For option --killIndividuals, expected keyword 'patch' but got " << s << " instead.\n"; abort(); } } // Read patch index int patch; { patch = input.GetNextElementInt(); if (patch < 0) { std::cout << "For option --killIndividuals, received a negative patch index. Patch index received is " << patch << ".\n"; abort(); } } // Expecting 'at' { auto s = input.GetNextElementString(); if (s != "at") { std::cout << "For option --killIndividuals, expected keyword 'at' but got " << s << " instead.\n"; abort(); } } // read generations std::vector<size_t> generations; while (input.IsThereMoreToRead() && input.PeakNextElementString() != "kill") { auto g = input.GetNextElementInt(); if (g <= 0 || g > GP->nbGenerations) { std::cout << "For option --killIndividuals, received generation " << g << ". This generation is either not greater than zero or is greater than the total number of generations (nbGenerations = "<< GP->nbGenerations <<").\n"; abort(); } generations.push_back(g); } for (const auto& generation : generations) { int generation_index = std::upper_bound(GP->__GenerationChange.begin(), GP->__GenerationChange.end(), generation) - GP->__GenerationChange.begin() - 1; { auto x = GP->__PatchNumber[generation_index]; if (patch >= x) { std::cout << "For option --killIndividuals, received patch " << patch << " at generation " << generation << " but there are only " << x << " patches in the world at that generation. As a ereminder all indices in SimBit are zero based counting\n"; abort(); } } { auto x = __patchCapacity[generation_index][patch]; if (nbInds > x) { if (isAllBut) { std::cout << "WARNING: For option --killIndividuals, received command to kill all but " << nbInds << " individuals in patch " << patch << " at generation " << generation << ". However, at this generation, in this patch, the carrying capacity is only " << x << ".\n"; } else { std::cout << "WARNING: For option --killIndividuals, received command to kill " << nbInds << " individuals in patch " << patch << " at generation " << generation << ". However, at this generation, in this patch, the carrying capacity is only " << x << ".\n"; } } } killIndividuals_times.push_back(generation); killIndividuals_patch.push_back(patch); killIndividuals_isAllBut.push_back(isAllBut); killIndividuals_numberInds.push_back(nbInds); } assert(killIndividuals_times.size() == killIndividuals_patch.size()); } assert(killIndividuals_times.size() == killIndividuals_patch.size()); assert(killIndividuals_times.size() == killIndividuals_isAllBut.size()); assert(killIndividuals_times.size() == killIndividuals_numberInds.size()); if (killIndividuals_times.size() >= 2) { auto order = reverse_sort_indexes(killIndividuals_times); reorderNoAssertions(killIndividuals_times, order); reorderNoAssertions(killIndividuals_patch, order); reorderNoAssertions(killIndividuals_isAllBut, order); reorderNoAssertions(killIndividuals_numberInds, order); } assert(killIndividuals_times.size() == killIndividuals_patch.size()); assert(killIndividuals_times.size() == killIndividuals_isAllBut.size()); assert(killIndividuals_times.size() == killIndividuals_numberInds.size()); /* for (auto& t : killIndividuals_times) std::cout << t << " "; std::cout << "\n"; */ } void SpeciesSpecificParameters::killIndividualsIfAskedFor() { //std::cout << "GP->CurrentGeneration = " << GP->CurrentGeneration << "\n"; //std::cout << "before killIndividuals_times.back() = " << killIndividuals_times.back() << "\n"; while (killIndividuals_times.size() && killIndividuals_times.back() == GP->CurrentGeneration) { assert(fecundityForFitnessOfOne != -1); auto patch = killIndividuals_patch.back(); assert(patch >= 0 && patch < GP->PatchNumber); assert(patchSize.size() > patch); int newSize = killIndividuals_isAllBut.back() ? killIndividuals_numberInds.back() : patchSize[patch] - killIndividuals_numberInds.back() < 0 ; assert(newSize <= patchCapacity[patch]); if (newSize >= 0 && newSize < patchSize[patch]) { patchSize[patch] = newSize; } killIndividuals_times.pop_back(); killIndividuals_patch.pop_back(); killIndividuals_isAllBut.pop_back(); killIndividuals_numberInds.pop_back(); } //std::cout << "after killIndividuals_times.back() = " << killIndividuals_times.back() << "\n"; if (killIndividuals_times.size()) assert(killIndividuals_times.back() > GP->CurrentGeneration); }
43.324996
1,090
0.547322
[ "vector", "model" ]
1db77c35d23bb2386902b24e71a150fcecbbf10c
4,934
cc
C++
cpp/icub/gazebo-yarp-plugins/plugins/modelposepublisher/src/ModelPosePublisher.cc
BrunoDaCosta/NL_limit_cycles
62c8c93d8ca9d6c7442154c467cd0f9e27329871
[ "RSA-MD" ]
2
2019-07-26T08:51:15.000Z
2020-10-16T09:52:58.000Z
cpp/icub/gazebo-yarp-plugins/plugins/modelposepublisher/src/ModelPosePublisher.cc
BrunoDaCosta/NL_limit_cycles
62c8c93d8ca9d6c7442154c467cd0f9e27329871
[ "RSA-MD" ]
null
null
null
cpp/icub/gazebo-yarp-plugins/plugins/modelposepublisher/src/ModelPosePublisher.cc
BrunoDaCosta/NL_limit_cycles
62c8c93d8ca9d6c7442154c467cd0f9e27329871
[ "RSA-MD" ]
1
2021-01-26T14:34:05.000Z
2021-01-26T14:34:05.000Z
/* * Copyright (C) 2018 Fondazione Istituto Italiano di Tecnologia iCub Facility * Authors: see AUTHORS file. * CopyPolicy: Released under the terms of the LGPLv2.1 or any later version, see LGPL.TXT or LGPL3.TXT */ // gazebo #include <gazebo/physics/Model.hh> #include <gazebo/physics/Link.hh> #include <gazebo/common/Events.hh> #include <gazebo/physics/World.hh> // ignition #include <ignition/math/Pose3.hh> #include <ignition/math/Vector3.hh> #include <ignition/math/Quaternion.hh> // GazeboYarpPlugins #include <GazeboYarpPlugins/common.h> // yarp #include <yarp/os/Log.h> #include <yarp/os/LogStream.h> #include <yarp/math/FrameTransform.h> // boost #include <boost/bind.hpp> #include "ModelPosePublisher.hh" GZ_REGISTER_MODEL_PLUGIN(gazebo::GazeboYarpModelPosePublisher) namespace gazebo { GazeboYarpModelPosePublisher::~GazeboYarpModelPosePublisher() { // Close the driver m_drvTransformClient.close(); } void GazeboYarpModelPosePublisher::Load(gazebo::physics::ModelPtr _parent, sdf::ElementPtr _sdf) { // Check yarp network availability if (!m_yarp.checkNetwork(GazeboYarpPlugins::yarpNetworkInitializationTimeout)) { yError() << "GazeboYarpModelPosePublisher::Load error:" << "yarp network does not seem to be available, is the yarpserver running?"; return; } // Store pointer to the model m_model = _parent; // Load update period if (_sdf->HasElement("period")) { // Get the parameter sdf::ParamPtr periodPtr = _sdf->GetElement("period")->GetValue(); // Check if it is a strictly positive double if (!periodPtr->Get<double>(m_period) || m_period <= 0) { yError() << "GazeboYarpModelPosePublisher::Load error:" << "parameter 'period' for model" << m_model->GetName() << "should be a strictly positive number"; return; } } else { // Default to 10 ms m_period = 0.01; } // Prepare properties for the PolyDriver yarp::os::Property propTfClient; propTfClient.put("device", "transformClient"); // The local port depends on the model name that is unique // also in the case of multiple insertions of the same model // in Gazebo propTfClient.put("local", "/" + m_model->GetName() + "/transformClient"); propTfClient.put("remote", "/transformServer"); // This is the update period of the transformClient in ms propTfClient.put("period", m_period * 1000); // Open the driver and obtain a a IFrameTransform view m_tfClient = nullptr; bool ok = m_drvTransformClient.open(propTfClient); ok = ok && m_drvTransformClient.view(m_tfClient) && m_tfClient != nullptr; // Return if the driver open failed // or the view retrieval failed // or the IFrameTransform pointer is not valid if (!ok) { yError() << "GazeboYarpModelPosePublisher::Load error:" << "failure in opening iFrameTransform interface for model" << m_model->GetName(); return; } // Clear last update time m_lastUpdateTime = gazebo::common::Time(0.0); // Listen to the update event auto worldUpdateBind = boost::bind(&GazeboYarpModelPosePublisher::OnWorldUpdate, this); m_worldUpdateConnection = gazebo::event::Events::ConnectWorldUpdateBegin(worldUpdateBind); } void GazeboYarpModelPosePublisher::PublishTransform() { // Get the current pose of the canonical link of the model #if GAZEBO_MAJOR_VERSION >= 8 ignition::math::Pose3d curPose = m_model->GetLink()->WorldPose(); #else gazebo::math::Pose curPoseGazebo = m_model->GetLink()->GetWorldPose(); // Convert to Ignition so that the same interface // can be used in the rest of the function ignition::math::Pose3d curPose = curPoseGazebo.Ign(); #endif // Get the positional and rotational parts ignition::math::Vector3d pos = curPose.Pos(); ignition::math::Quaterniond rot = curPose.Rot(); // Convert the pose to a homogeneous transformation matrix // (the first two arguments can be blank) yarp::math::FrameTransform inertialToModel("", "", pos.X(), pos.Y(), pos.Z(), rot.X(), rot.Y(), rot.Z(), rot.W()); // Set a new transform using // /inertial for source frame name and // /<model_name>/frame for the target frame name m_tfClient->setTransform("/" + m_model->GetName() + "/frame", "/inertial", inertialToModel.toMatrix()); } void GazeboYarpModelPosePublisher::OnWorldUpdate() { // Get current time #if GAZEBO_MAJOR_VERSION >= 8 gazebo::common::Time currentTime = m_model->GetWorld()->SimTime(); #else gazebo::common::Time currentTime = m_model->GetWorld()->GetSimTime(); #endif // Check if an update period is elapsed if(currentTime - m_lastUpdateTime >= m_period) { // Store current time for next update m_lastUpdateTime = currentTime; // Publish the transform with the current pose PublishTransform(); } } }
30.8375
103
0.689501
[ "model", "transform" ]
1dbb7469178f855939bfffb3d1dcb1e8c2fd84e2
1,397
cpp
C++
src/devices/base/BaseDevice.cpp
miso-develop/opniz-device
203c019a2088ede9aab79ec69ebe4fd5f857ff9f
[ "MIT" ]
3
2021-03-18T07:23:38.000Z
2021-09-06T11:37:54.000Z
src/devices/base/BaseDevice.cpp
miso-develop/opniz-device
203c019a2088ede9aab79ec69ebe4fd5f857ff9f
[ "MIT" ]
null
null
null
src/devices/base/BaseDevice.cpp
miso-develop/opniz-device
203c019a2088ede9aab79ec69ebe4fd5f857ff9f
[ "MIT" ]
null
null
null
#include "devices/base/BaseDevice.h" BaseDevice::BaseDevice(const char* address, uint16_t port) : TcpManager(address, port), _responseJsonDoc(1024) {} String BaseDevice::_messageHandler(String message) { const JsonArray messageArray = _jsonParser.parseArray(message); JsonArray responseJsonArray = _responseJsonDoc.to<JsonArray>(); for (JsonObject messageJson : messageArray) { BaseHandler* handler = _handlers[messageJson["name"]]; String response = (boolean)handler ? handler->handle(messageJson["parameters"]) : "notmatch"; responseJsonArray.add(response); } return _jsonParser.stringify(_responseJsonDoc); }; void BaseDevice::handleMessage() { receive(_messageHandlerFunction); } void BaseDevice::emitMessage() { for (BaseEmitter* emitter : _emitters) { if (emitter->canEmit()) { // MEMO: デバイスからのイベントを瞬間的に同時に受け取ることがあり、その場合`{...}{...}`のようなメッセージとなりJSON.parseでエラーとなる。 // MEMO: それを回避するため必ずオブジェクト末尾に`,`を付与し`{...},`の形でデバイスからメッセージを送り、Server側にて`[]`で括り配列にする。 send(emitter->emit() + ","); } } } void BaseDevice::addHandler(std::vector<BaseHandler*> handlers) { for (BaseHandler* handler : handlers) _handlers[handler->name().c_str()] = handler; } void BaseDevice::addEmitter(std::vector<BaseEmitter*> emitters) { copy(emitters.begin(), emitters.end(), back_inserter(_emitters)); }
37.756757
113
0.695061
[ "vector" ]
1dbcb3bd1dc751cba823707db19588eac54cfc3b
1,610
cpp
C++
leetcode/Two_Sum_2_best.cpp
Dts0/code
5dc2583f8346b83af80a7d1505d4e6b9ce4e54c0
[ "MIT" ]
null
null
null
leetcode/Two_Sum_2_best.cpp
Dts0/code
5dc2583f8346b83af80a7d1505d4e6b9ce4e54c0
[ "MIT" ]
null
null
null
leetcode/Two_Sum_2_best.cpp
Dts0/code
5dc2583f8346b83af80a7d1505d4e6b9ce4e54c0
[ "MIT" ]
null
null
null
/* Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number. The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Note: Your returned answers (both index1 and index2) are not zero-based. You may assume that each input would have exactly one solution and you may not use the same element twice. Example: Input: numbers = [2,7,11,15], target = 9 Output: [1,2] Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2. */ #include<iostream> #include<vector> #include<map> #include<unordered_map> #include<algorithm> using namespace std; class Solution { public: vector<int> twoSum(vector<int>& nums, int target) { unordered_map<int, int> map; for (int i = 0; i < nums.size(); i++) { int complement = target - nums[i]; if (map.find(complement) != map.end() && map[complement] != i) { return vector<int> {map[complement]+1, i+1}; } map.emplace(nums[i], i); } } }; #define REQUIRE(sol) {\ if(sol)\ cout<<"passed"<<endl;\ else cout<<"not passed"<<endl;\ } int main(){ Solution s; std::vector<int> v1{2, 7, 11, 15}; REQUIRE( (s.twoSum(v1, 9) == std::vector<int>{1, 2}) ); std::vector<int> v2{0, 4, 4, 5}; REQUIRE( (s.twoSum(v2, 8) == std::vector<int>{2, 3}) ); std::vector<int> v3{-3, 3, 4, 90}; REQUIRE( (s.twoSum(v3, 0) == std::vector<int>{1, 2}) ); return 0; }
25.15625
137
0.608696
[ "vector" ]
1dbfe38f587187ed85411254ae8da4cf0d15629b
749,456
cpp
C++
Bindings/Portable/Generated/binding.cpp
Haukinger/urho
3161c6ad4bf6fbdd7cf91b191017347c32209714
[ "MIT" ]
502
2015-12-07T20:32:12.000Z
2022-03-26T09:27:23.000Z
Bindings/Portable/Generated/binding.cpp
Haukinger/urho
3161c6ad4bf6fbdd7cf91b191017347c32209714
[ "MIT" ]
353
2015-12-07T20:34:16.000Z
2022-03-21T09:49:10.000Z
Bindings/Portable/Generated/binding.cpp
Haukinger/urho
3161c6ad4bf6fbdd7cf91b191017347c32209714
[ "MIT" ]
160
2015-12-08T02:32:38.000Z
2022-02-13T17:47:22.000Z
// Autogenerated, do not edit #include "../../Native/AllUrho.h" #include "../../Native/interop.h" using namespace Urho3D; extern "C" { DllExport void * RefCount_RefCount () { return new RefCount(); } DllExport void * RefCounted_RefCounted () { return new RefCounted(); } DllExport void RefCounted_AddRef (Urho3D::RefCounted *_target) { _target->AddRef (); } DllExport void RefCounted_ReleaseRef (Urho3D::RefCounted *_target) { _target->ReleaseRef (); } DllExport int RefCounted_Refs (Urho3D::RefCounted *_target) { return _target->Refs (); } DllExport int RefCounted_WeakRefs (Urho3D::RefCounted *_target) { return _target->WeakRefs (); } DllExport Urho3D::RefCount * RefCounted_RefCountPtr (Urho3D::RefCounted *_target) { return _target->RefCountPtr (); } DllExport void * UrhoString_String () { return new String(); } DllExport void * UrhoString_String0 (const char * str) { return new String(Urho3D::String(str)); } DllExport void * UrhoString_String1 (int value) { return new String(value); } DllExport void * UrhoString_String2 (short value) { return new String(value); } DllExport void * UrhoString_String3 (long value) { return new String(value); } DllExport void * UrhoString_String4 (long long value) { return new String(value); } DllExport void * UrhoString_String5 (unsigned int value) { return new String(value); } DllExport void * UrhoString_String6 (unsigned short value) { return new String(value); } DllExport void * UrhoString_String7 (unsigned long value) { return new String(value); } DllExport void * UrhoString_String8 (unsigned long long value) { return new String(value); } DllExport void * UrhoString_String9 (float value) { return new String(value); } DllExport void * UrhoString_String10 (double value) { return new String(value); } DllExport void * UrhoString_String11 (bool value) { return new String(value); } DllExport void UrhoString_Replace (Urho3D::String *_target, const char * replaceThis, const char * replaceWith, bool caseSensitive) { _target->Replace (Urho3D::String(replaceThis), Urho3D::String(replaceWith), caseSensitive); } DllExport void UrhoString_Replace12 (Urho3D::String *_target, unsigned int pos, unsigned int length, const char * replaceWith) { _target->Replace (pos, length, Urho3D::String(replaceWith)); } DllExport const char * UrhoString_Replaced (Urho3D::String *_target, const char * replaceThis, const char * replaceWith, bool caseSensitive) { return stringdup((_target->Replaced (Urho3D::String(replaceThis), Urho3D::String(replaceWith), caseSensitive)).CString ()); } DllExport void UrhoString_Insert (Urho3D::String *_target, unsigned int pos, const char * str) { _target->Insert (pos, Urho3D::String(str)); } DllExport void UrhoString_Erase (Urho3D::String *_target, unsigned int pos, unsigned int length) { _target->Erase (pos, length); } DllExport void UrhoString_Resize (Urho3D::String *_target, unsigned int newLength) { _target->Resize (newLength); } DllExport void UrhoString_Reserve (Urho3D::String *_target, unsigned int newCapacity) { _target->Reserve (newCapacity); } DllExport void UrhoString_Compact (Urho3D::String *_target) { _target->Compact (); } DllExport void UrhoString_Clear (Urho3D::String *_target) { _target->Clear (); } DllExport const char * UrhoString_Substring (Urho3D::String *_target, unsigned int pos) { return stringdup((_target->Substring (pos)).CString ()); } DllExport const char * UrhoString_Substring13 (Urho3D::String *_target, unsigned int pos, unsigned int length) { return stringdup((_target->Substring (pos, length)).CString ()); } DllExport const char * UrhoString_Trimmed (Urho3D::String *_target) { return stringdup((_target->Trimmed ()).CString ()); } DllExport const char * UrhoString_ToUpper (Urho3D::String *_target) { return stringdup((_target->ToUpper ()).CString ()); } DllExport const char * UrhoString_ToLower (Urho3D::String *_target) { return stringdup((_target->ToLower ()).CString ()); } DllExport unsigned int UrhoString_Find (Urho3D::String *_target, const char * str, unsigned int startPos, bool caseSensitive) { return _target->Find (Urho3D::String(str), startPos, caseSensitive); } DllExport unsigned int UrhoString_FindLast (Urho3D::String *_target, const char * str, unsigned int startPos, bool caseSensitive) { return _target->FindLast (Urho3D::String(str), startPos, caseSensitive); } DllExport int UrhoString_StartsWith (Urho3D::String *_target, const char * str, bool caseSensitive) { return _target->StartsWith (Urho3D::String(str), caseSensitive); } DllExport int UrhoString_EndsWith (Urho3D::String *_target, const char * str, bool caseSensitive) { return _target->EndsWith (Urho3D::String(str), caseSensitive); } DllExport unsigned int UrhoString_Length (Urho3D::String *_target) { return _target->Length (); } DllExport unsigned int UrhoString_Capacity (Urho3D::String *_target) { return _target->Capacity (); } DllExport int UrhoString_Empty (Urho3D::String *_target) { return _target->Empty (); } DllExport int UrhoString_Compare (Urho3D::String *_target, const char * str, bool caseSensitive) { return _target->Compare (Urho3D::String(str), caseSensitive); } DllExport int UrhoString_Contains (Urho3D::String *_target, const char * str, bool caseSensitive) { return _target->Contains (Urho3D::String(str), caseSensitive); } DllExport unsigned int UrhoString_LengthUTF8 (Urho3D::String *_target) { return _target->LengthUTF8 (); } DllExport unsigned int UrhoString_ByteOffsetUTF8 (Urho3D::String *_target, unsigned int index) { return _target->ByteOffsetUTF8 (index); } DllExport unsigned int UrhoString_AtUTF8 (Urho3D::String *_target, unsigned int index) { return _target->AtUTF8 (index); } DllExport void UrhoString_ReplaceUTF8 (Urho3D::String *_target, unsigned int index, unsigned int unicodeChar) { _target->ReplaceUTF8 (index, unicodeChar); } DllExport const char * UrhoString_SubstringUTF8 (Urho3D::String *_target, unsigned int pos) { return stringdup((_target->SubstringUTF8 (pos)).CString ()); } DllExport const char * UrhoString_SubstringUTF814 (Urho3D::String *_target, unsigned int pos, unsigned int length) { return stringdup((_target->SubstringUTF8 (pos, length)).CString ()); } DllExport unsigned int UrhoString_ToHash (Urho3D::String *_target) { return _target->ToHash (); } // Urho3D::Variant overloads begin: DllExport void AttributeAccessor_Set_0 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::Vector3 & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_1 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::IntRect & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_2 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::Color & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_3 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::Vector2 & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_4 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::Vector4 & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_5 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::IntVector2 & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_6 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::Quaternion & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_7 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::Matrix4 & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_8 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const class Urho3D::Matrix3x4 & src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_9 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, int src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_10 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, float src) { _target->Set (ptr, (src)); } DllExport void AttributeAccessor_Set_11 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, const char * src) { _target->Set (ptr, Urho3D::String(src)); } DllExport void AttributeAccessor_Set_12 (Urho3D::AttributeAccessor *_target, Urho3D::Serializable * ptr, bool src) { _target->Set (ptr, (src)); } // Urho3D::Variant overloads end. DllExport int UrhoObject_GetType (Urho3D::Object *_target) { return (_target->GetType ()).Value (); } DllExport const char * UrhoObject_GetTypeName (Urho3D::Object *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport const class Urho3D::TypeInfo * UrhoObject_GetTypeInfo (Urho3D::Object *_target) { return _target->GetTypeInfo (); } DllExport const class Urho3D::TypeInfo * UrhoObject_GetTypeInfoStatic () { return Object::GetTypeInfoStatic (); } DllExport int UrhoObject_IsInstanceOf (Urho3D::Object *_target, int type) { return _target->IsInstanceOf (Urho3D::StringHash(type)); } DllExport int UrhoObject_IsInstanceOf0 (Urho3D::Object *_target, const class Urho3D::TypeInfo * typeInfo) { return _target->IsInstanceOf (typeInfo); } DllExport void UrhoObject_SubscribeToEvent (Urho3D::Object *_target, int eventType, Urho3D::EventHandler * handler) { _target->SubscribeToEvent (Urho3D::StringHash(eventType), handler); } DllExport void UrhoObject_SubscribeToEvent1 (Urho3D::Object *_target, Urho3D::Object * sender, int eventType, Urho3D::EventHandler * handler) { _target->SubscribeToEvent (sender, Urho3D::StringHash(eventType), handler); } DllExport void UrhoObject_UnsubscribeFromEvent (Urho3D::Object *_target, int eventType) { _target->UnsubscribeFromEvent (Urho3D::StringHash(eventType)); } DllExport void UrhoObject_UnsubscribeFromEvent2 (Urho3D::Object *_target, Urho3D::Object * sender, int eventType) { _target->UnsubscribeFromEvent (sender, Urho3D::StringHash(eventType)); } DllExport void UrhoObject_UnsubscribeFromEvents (Urho3D::Object *_target, Urho3D::Object * sender) { _target->UnsubscribeFromEvents (sender); } DllExport void UrhoObject_UnsubscribeFromAllEvents (Urho3D::Object *_target) { _target->UnsubscribeFromAllEvents (); } DllExport void UrhoObject_SendEvent (Urho3D::Object *_target, int eventType) { _target->SendEvent (Urho3D::StringHash(eventType)); } DllExport Urho3D::Context * UrhoObject_GetContext (Urho3D::Object *_target) { return _target->GetContext (); } // Urho3D::Variant overloads begin: DllExport Interop::Vector3 UrhoObject_GetGlobalVar_0 (Urho3D::Object *_target, int key) { return *((Interop::Vector3 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetVector3())); } DllExport Interop::IntRect UrhoObject_GetGlobalVar_1 (Urho3D::Object *_target, int key) { return *((Interop::IntRect *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetIntRect())); } DllExport Interop::Color UrhoObject_GetGlobalVar_2 (Urho3D::Object *_target, int key) { return *((Interop::Color *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetColor())); } DllExport Interop::Vector2 UrhoObject_GetGlobalVar_3 (Urho3D::Object *_target, int key) { return *((Interop::Vector2 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetVector2())); } DllExport Interop::Vector4 UrhoObject_GetGlobalVar_4 (Urho3D::Object *_target, int key) { return *((Interop::Vector4 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetVector4())); } DllExport Interop::IntVector2 UrhoObject_GetGlobalVar_5 (Urho3D::Object *_target, int key) { return *((Interop::IntVector2 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetIntVector2())); } DllExport Interop::Quaternion UrhoObject_GetGlobalVar_6 (Urho3D::Object *_target, int key) { return *((Interop::Quaternion *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetQuaternion())); } DllExport Interop::Matrix4 UrhoObject_GetGlobalVar_7 (Urho3D::Object *_target, int key) { return *((Interop::Matrix4 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetMatrix4())); } DllExport Interop::Matrix3x4 UrhoObject_GetGlobalVar_8 (Urho3D::Object *_target, int key) { return *((Interop::Matrix3x4 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetMatrix3x4())); } DllExport int UrhoObject_GetGlobalVar_9 (Urho3D::Object *_target, int key) { return (_target->GetGlobalVar (Urho3D::StringHash(key)).GetInt()); } DllExport float UrhoObject_GetGlobalVar_10 (Urho3D::Object *_target, int key) { return (_target->GetGlobalVar (Urho3D::StringHash(key)).GetFloat()); } DllExport const char * UrhoObject_GetGlobalVar_11 (Urho3D::Object *_target, int key) { return stringdup(_target->GetGlobalVar (Urho3D::StringHash(key)).GetString().CString()); } DllExport bool UrhoObject_GetGlobalVar_12 (Urho3D::Object *_target, int key) { return (_target->GetGlobalVar (Urho3D::StringHash(key)).GetBool()); } // Urho3D::Variant overloads end. // Urho3D::Variant overloads begin: DllExport void UrhoObject_SetGlobalVar_0 (Urho3D::Object *_target, int key, const class Urho3D::Vector3 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_1 (Urho3D::Object *_target, int key, const class Urho3D::IntRect & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_2 (Urho3D::Object *_target, int key, const class Urho3D::Color & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_3 (Urho3D::Object *_target, int key, const class Urho3D::Vector2 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_4 (Urho3D::Object *_target, int key, const class Urho3D::Vector4 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_5 (Urho3D::Object *_target, int key, const class Urho3D::IntVector2 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_6 (Urho3D::Object *_target, int key, const class Urho3D::Quaternion & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_7 (Urho3D::Object *_target, int key, const class Urho3D::Matrix4 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_8 (Urho3D::Object *_target, int key, const class Urho3D::Matrix3x4 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_9 (Urho3D::Object *_target, int key, int value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_10 (Urho3D::Object *_target, int key, float value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void UrhoObject_SetGlobalVar_11 (Urho3D::Object *_target, int key, const char * value) { _target->SetGlobalVar (Urho3D::StringHash(key), Urho3D::String(value)); } DllExport void UrhoObject_SetGlobalVar_12 (Urho3D::Object *_target, int key, bool value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } // Urho3D::Variant overloads end. DllExport Urho3D::Object * UrhoObject_GetSubsystem (Urho3D::Object *_target, int type) { return _target->GetSubsystem (Urho3D::StringHash(type)); } DllExport Urho3D::Object * UrhoObject_GetEventSender (Urho3D::Object *_target) { return _target->GetEventSender (); } DllExport Urho3D::EventHandler * UrhoObject_GetEventHandler (Urho3D::Object *_target) { return _target->GetEventHandler (); } DllExport int UrhoObject_HasSubscribedToEvent (Urho3D::Object *_target, int eventType) { return _target->HasSubscribedToEvent (Urho3D::StringHash(eventType)); } DllExport int UrhoObject_HasSubscribedToEvent3 (Urho3D::Object *_target, Urho3D::Object * sender, int eventType) { return _target->HasSubscribedToEvent (sender, Urho3D::StringHash(eventType)); } DllExport int UrhoObject_HasEventHandlers (Urho3D::Object *_target) { return _target->HasEventHandlers (); } DllExport const char * UrhoObject_GetCategory (Urho3D::Object *_target) { return stringdup((_target->GetCategory ()).CString ()); } DllExport void UrhoObject_SetBlockEvents (Urho3D::Object *_target, bool block) { _target->SetBlockEvents (block); } DllExport int UrhoObject_GetBlockEvents (Urho3D::Object *_target) { return _target->GetBlockEvents (); } DllExport Urho3D::Object * ObjectFactory_CreateObject (Urho3D::ObjectFactory *_target) { auto copy = _target->CreateObject (); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::Context * ObjectFactory_GetContext (Urho3D::ObjectFactory *_target) { return _target->GetContext (); } DllExport const class Urho3D::TypeInfo * ObjectFactory_GetTypeInfo (Urho3D::ObjectFactory *_target) { return _target->GetTypeInfo (); } DllExport int ObjectFactory_GetType (Urho3D::ObjectFactory *_target) { return (_target->GetType ()).Value (); } DllExport const char * ObjectFactory_GetTypeName (Urho3D::ObjectFactory *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Serializable_GetType (Urho3D::Serializable *_target) { return (_target->GetType ()).Value (); } DllExport const char * Serializable_GetTypeName (Urho3D::Serializable *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Serializable_GetTypeStatic () { return (Serializable::GetTypeStatic ()).Value (); } DllExport const char * Serializable_GetTypeNameStatic () { return stringdup((Serializable::GetTypeNameStatic ()).CString ()); } DllExport void * Serializable_Serializable (Urho3D::Context * context) { return WeakPtr<Serializable>(new Serializable(context)); } DllExport int Serializable_Load_File (Urho3D::Serializable *_target, File * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int Serializable_Load_MemoryBuffer (Urho3D::Serializable *_target, MemoryBuffer * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int Serializable_Save_File (Urho3D::Serializable *_target, File * dest) { return _target->Save (*dest); } DllExport int Serializable_Save_MemoryBuffer (Urho3D::Serializable *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int Serializable_LoadXML (Urho3D::Serializable *_target, const class Urho3D::XMLElement & source, bool setInstanceDefault) { return _target->LoadXML (source, setInstanceDefault); } DllExport int Serializable_SaveXML (Urho3D::Serializable *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void Serializable_ApplyAttributes (Urho3D::Serializable *_target) { _target->ApplyAttributes (); } DllExport int Serializable_SaveDefaultAttributes (Urho3D::Serializable *_target) { return _target->SaveDefaultAttributes (); } DllExport void Serializable_MarkNetworkUpdate (Urho3D::Serializable *_target) { _target->MarkNetworkUpdate (); } // Urho3D::Variant overloads begin: DllExport int Serializable_SetAttribute_0 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::Vector3 & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_1 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::IntRect & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_2 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::Color & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_3 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::Vector2 & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_4 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::Vector4 & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_5 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::IntVector2 & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_6 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::Quaternion & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_7 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::Matrix4 & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_8 (Urho3D::Serializable *_target, unsigned int index, const class Urho3D::Matrix3x4 & value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_9 (Urho3D::Serializable *_target, unsigned int index, int value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_10 (Urho3D::Serializable *_target, unsigned int index, float value) { return _target->SetAttribute (index, (value)); } DllExport int Serializable_SetAttribute_11 (Urho3D::Serializable *_target, unsigned int index, const char * value) { return _target->SetAttribute (index, Urho3D::String(value)); } DllExport int Serializable_SetAttribute_12 (Urho3D::Serializable *_target, unsigned int index, bool value) { return _target->SetAttribute (index, (value)); } // Urho3D::Variant overloads end. // Urho3D::Variant overloads begin: DllExport int Serializable_SetAttribute0_0 (Urho3D::Serializable *_target, const char * name, const class Urho3D::Vector3 & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_1 (Urho3D::Serializable *_target, const char * name, const class Urho3D::IntRect & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_2 (Urho3D::Serializable *_target, const char * name, const class Urho3D::Color & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_3 (Urho3D::Serializable *_target, const char * name, const class Urho3D::Vector2 & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_4 (Urho3D::Serializable *_target, const char * name, const class Urho3D::Vector4 & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_5 (Urho3D::Serializable *_target, const char * name, const class Urho3D::IntVector2 & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_6 (Urho3D::Serializable *_target, const char * name, const class Urho3D::Quaternion & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_7 (Urho3D::Serializable *_target, const char * name, const class Urho3D::Matrix4 & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_8 (Urho3D::Serializable *_target, const char * name, const class Urho3D::Matrix3x4 & value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_9 (Urho3D::Serializable *_target, const char * name, int value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_10 (Urho3D::Serializable *_target, const char * name, float value) { return _target->SetAttribute (Urho3D::String(name), (value)); } DllExport int Serializable_SetAttribute0_11 (Urho3D::Serializable *_target, const char * name, const char * value) { return _target->SetAttribute (Urho3D::String(name), Urho3D::String(value)); } DllExport int Serializable_SetAttribute0_12 (Urho3D::Serializable *_target, const char * name, bool value) { return _target->SetAttribute (Urho3D::String(name), (value)); } // Urho3D::Variant overloads end. DllExport void Serializable_ResetToDefault (Urho3D::Serializable *_target) { _target->ResetToDefault (); } DllExport void Serializable_RemoveInstanceDefault (Urho3D::Serializable *_target) { _target->RemoveInstanceDefault (); } DllExport void Serializable_SetTemporary (Urho3D::Serializable *_target, bool enable) { _target->SetTemporary (enable); } DllExport void Serializable_SetInterceptNetworkUpdate (Urho3D::Serializable *_target, const char * attributeName, bool enable) { _target->SetInterceptNetworkUpdate (Urho3D::String(attributeName), enable); } DllExport void Serializable_AllocateNetworkState (Urho3D::Serializable *_target) { _target->AllocateNetworkState (); } DllExport void Serializable_WriteInitialDeltaUpdate_File (Urho3D::Serializable *_target, File * dest, unsigned char timeStamp) { _target->WriteInitialDeltaUpdate (*dest, timeStamp); } DllExport void Serializable_WriteInitialDeltaUpdate_MemoryBuffer (Urho3D::Serializable *_target, MemoryBuffer * dest, unsigned char timeStamp) { _target->WriteInitialDeltaUpdate (*dest, timeStamp); } DllExport void Serializable_WriteLatestDataUpdate_File (Urho3D::Serializable *_target, File * dest, unsigned char timeStamp) { _target->WriteLatestDataUpdate (*dest, timeStamp); } DllExport void Serializable_WriteLatestDataUpdate_MemoryBuffer (Urho3D::Serializable *_target, MemoryBuffer * dest, unsigned char timeStamp) { _target->WriteLatestDataUpdate (*dest, timeStamp); } DllExport int Serializable_ReadDeltaUpdate_File (Urho3D::Serializable *_target, File * source) { return _target->ReadDeltaUpdate (*source); } DllExport int Serializable_ReadDeltaUpdate_MemoryBuffer (Urho3D::Serializable *_target, MemoryBuffer * source) { return _target->ReadDeltaUpdate (*source); } DllExport int Serializable_ReadLatestDataUpdate_File (Urho3D::Serializable *_target, File * source) { return _target->ReadLatestDataUpdate (*source); } DllExport int Serializable_ReadLatestDataUpdate_MemoryBuffer (Urho3D::Serializable *_target, MemoryBuffer * source) { return _target->ReadLatestDataUpdate (*source); } DllExport Urho3D::Variant Serializable_GetAttribute (Urho3D::Serializable *_target, unsigned int index) { return _target->GetAttribute (index); } DllExport Urho3D::Variant Serializable_GetAttribute1 (Urho3D::Serializable *_target, const char * name) { return _target->GetAttribute (Urho3D::String(name)); } DllExport Urho3D::Variant Serializable_GetAttributeDefault (Urho3D::Serializable *_target, unsigned int index) { return _target->GetAttributeDefault (index); } DllExport Urho3D::Variant Serializable_GetAttributeDefault2 (Urho3D::Serializable *_target, const char * name) { return _target->GetAttributeDefault (Urho3D::String(name)); } DllExport unsigned int Serializable_GetNumAttributes (Urho3D::Serializable *_target) { return _target->GetNumAttributes (); } DllExport unsigned int Serializable_GetNumNetworkAttributes (Urho3D::Serializable *_target) { return _target->GetNumNetworkAttributes (); } DllExport int Serializable_IsTemporary (Urho3D::Serializable *_target) { return _target->IsTemporary (); } DllExport int Serializable_GetInterceptNetworkUpdate (Urho3D::Serializable *_target, const char * attributeName) { return _target->GetInterceptNetworkUpdate (Urho3D::String(attributeName)); } DllExport Urho3D::NetworkState * Serializable_GetNetworkState (Urho3D::Serializable *_target) { return _target->GetNetworkState (); } DllExport void * ValueAnimationInfo_ValueAnimationInfo (Urho3D::ValueAnimation * animation, enum Urho3D::WrapMode wrapMode, float speed) { return WeakPtr<ValueAnimationInfo>(new ValueAnimationInfo(animation, wrapMode, speed)); } DllExport void * ValueAnimationInfo_ValueAnimationInfo0 (Urho3D::Object * target, Urho3D::ValueAnimation * animation, enum Urho3D::WrapMode wrapMode, float speed) { return WeakPtr<ValueAnimationInfo>(new ValueAnimationInfo(target, animation, wrapMode, speed)); } DllExport int ValueAnimationInfo_Update (Urho3D::ValueAnimationInfo *_target, float timeStep) { return _target->Update (timeStep); } DllExport int ValueAnimationInfo_SetTime (Urho3D::ValueAnimationInfo *_target, float time) { return _target->SetTime (time); } DllExport void ValueAnimationInfo_SetWrapMode (Urho3D::ValueAnimationInfo *_target, enum Urho3D::WrapMode wrapMode) { _target->SetWrapMode (wrapMode); } DllExport void ValueAnimationInfo_SetSpeed (Urho3D::ValueAnimationInfo *_target, float speed) { _target->SetSpeed (speed); } DllExport Urho3D::Object * ValueAnimationInfo_GetTarget (Urho3D::ValueAnimationInfo *_target) { return _target->GetTarget (); } DllExport Urho3D::ValueAnimation * ValueAnimationInfo_GetAnimation (Urho3D::ValueAnimationInfo *_target) { return _target->GetAnimation (); } DllExport enum Urho3D::WrapMode ValueAnimationInfo_GetWrapMode (Urho3D::ValueAnimationInfo *_target) { return _target->GetWrapMode (); } DllExport float ValueAnimationInfo_GetTime (Urho3D::ValueAnimationInfo *_target) { return _target->GetTime (); } DllExport float ValueAnimationInfo_GetSpeed (Urho3D::ValueAnimationInfo *_target) { return _target->GetSpeed (); } DllExport int Animatable_GetType (Urho3D::Animatable *_target) { return (_target->GetType ()).Value (); } DllExport const char * Animatable_GetTypeName (Urho3D::Animatable *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Animatable_GetTypeStatic () { return (Animatable::GetTypeStatic ()).Value (); } DllExport const char * Animatable_GetTypeNameStatic () { return stringdup((Animatable::GetTypeNameStatic ()).CString ()); } DllExport void Animatable_RegisterObject (Urho3D::Context * context) { Animatable::RegisterObject (context); } DllExport int Animatable_LoadXML (Urho3D::Animatable *_target, const class Urho3D::XMLElement & source, bool setInstanceDefault) { return _target->LoadXML (source, setInstanceDefault); } DllExport int Animatable_SaveXML (Urho3D::Animatable *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void Animatable_SetAnimationEnabled (Urho3D::Animatable *_target, bool enable) { _target->SetAnimationEnabled (enable); } DllExport void Animatable_SetAnimationTime (Urho3D::Animatable *_target, float time) { _target->SetAnimationTime (time); } DllExport void Animatable_SetObjectAnimation (Urho3D::Animatable *_target, Urho3D::ObjectAnimation * objectAnimation) { _target->SetObjectAnimation (objectAnimation); } DllExport void Animatable_SetAttributeAnimation (Urho3D::Animatable *_target, const char * name, Urho3D::ValueAnimation * attributeAnimation, enum Urho3D::WrapMode wrapMode, float speed) { _target->SetAttributeAnimation (Urho3D::String(name), attributeAnimation, wrapMode, speed); } DllExport void Animatable_SetAttributeAnimationWrapMode (Urho3D::Animatable *_target, const char * name, enum Urho3D::WrapMode wrapMode) { _target->SetAttributeAnimationWrapMode (Urho3D::String(name), wrapMode); } DllExport void Animatable_SetAttributeAnimationSpeed (Urho3D::Animatable *_target, const char * name, float speed) { _target->SetAttributeAnimationSpeed (Urho3D::String(name), speed); } DllExport void Animatable_SetAttributeAnimationTime (Urho3D::Animatable *_target, const char * name, float time) { _target->SetAttributeAnimationTime (Urho3D::String(name), time); } DllExport void Animatable_RemoveObjectAnimation (Urho3D::Animatable *_target) { _target->RemoveObjectAnimation (); } DllExport void Animatable_RemoveAttributeAnimation (Urho3D::Animatable *_target, const char * name) { _target->RemoveAttributeAnimation (Urho3D::String(name)); } DllExport int Animatable_GetAnimationEnabled (Urho3D::Animatable *_target) { return _target->GetAnimationEnabled (); } DllExport Urho3D::ObjectAnimation * Animatable_GetObjectAnimation (Urho3D::Animatable *_target) { return _target->GetObjectAnimation (); } DllExport Urho3D::ValueAnimation * Animatable_GetAttributeAnimation (Urho3D::Animatable *_target, const char * name) { return _target->GetAttributeAnimation (Urho3D::String(name)); } DllExport enum Urho3D::WrapMode Animatable_GetAttributeAnimationWrapMode (Urho3D::Animatable *_target, const char * name) { return _target->GetAttributeAnimationWrapMode (Urho3D::String(name)); } DllExport float Animatable_GetAttributeAnimationSpeed (Urho3D::Animatable *_target, const char * name) { return _target->GetAttributeAnimationSpeed (Urho3D::String(name)); } DllExport float Animatable_GetAttributeAnimationTime (Urho3D::Animatable *_target, const char * name) { return _target->GetAttributeAnimationTime (Urho3D::String(name)); } DllExport Urho3D::ResourceRef Animatable_GetObjectAnimationAttr (Urho3D::Animatable *_target) { return _target->GetObjectAnimationAttr (); } DllExport int Component_GetType (Urho3D::Component *_target) { return (_target->GetType ()).Value (); } DllExport const char * Component_GetTypeName (Urho3D::Component *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Component_GetTypeStatic () { return (Component::GetTypeStatic ()).Value (); } DllExport const char * Component_GetTypeNameStatic () { return stringdup((Component::GetTypeNameStatic ()).CString ()); } DllExport void * Component_Component (Urho3D::Context * context) { return WeakPtr<Component>(new Component(context)); } DllExport void Component_OnSetEnabled (Urho3D::Component *_target) { _target->OnSetEnabled (); } DllExport int Component_Save_File (Urho3D::Component *_target, File * dest) { return _target->Save (*dest); } DllExport int Component_Save_MemoryBuffer (Urho3D::Component *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int Component_SaveXML (Urho3D::Component *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void Component_MarkNetworkUpdate (Urho3D::Component *_target) { _target->MarkNetworkUpdate (); } DllExport void Component_DrawDebugGeometry (Urho3D::Component *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void Component_SetEnabled (Urho3D::Component *_target, bool enable) { _target->SetEnabled (enable); } DllExport void Component_Remove (Urho3D::Component *_target) { _target->Remove (); } DllExport unsigned int Component_GetID (Urho3D::Component *_target) { return _target->GetID (); } DllExport Urho3D::Node * Component_GetNode (Urho3D::Component *_target) { return _target->GetNode (); } DllExport Urho3D::Scene * Component_GetScene (Urho3D::Component *_target) { return _target->GetScene (); } DllExport int Component_IsEnabled (Urho3D::Component *_target) { return _target->IsEnabled (); } DllExport int Component_IsEnabledEffective (Urho3D::Component *_target) { return _target->IsEnabledEffective (); } DllExport Urho3D::Component * Component_GetComponent (Urho3D::Component *_target, int type) { return _target->GetComponent (Urho3D::StringHash(type)); } DllExport void Component_AddReplicationState (Urho3D::Component *_target, Urho3D::ComponentReplicationState * state) { _target->AddReplicationState (state); } DllExport void Component_PrepareNetworkUpdate (Urho3D::Component *_target) { _target->PrepareNetworkUpdate (); } DllExport void Component_CleanupConnection (Urho3D::Component *_target, Urho3D::Connection * connection) { _target->CleanupConnection (connection); } DllExport int Time_GetType (Urho3D::Time *_target) { return (_target->GetType ()).Value (); } DllExport const char * Time_GetTypeName (Urho3D::Time *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Time_GetTypeStatic () { return (Time::GetTypeStatic ()).Value (); } DllExport const char * Time_GetTypeNameStatic () { return stringdup((Time::GetTypeNameStatic ()).CString ()); } DllExport void * Time_Time (Urho3D::Context * context) { return WeakPtr<Time>(new Time(context)); } DllExport void Time_BeginFrame (Urho3D::Time *_target, float timeStep) { _target->BeginFrame (timeStep); } DllExport void Time_EndFrame (Urho3D::Time *_target) { _target->EndFrame (); } DllExport void Time_SetTimerPeriod (Urho3D::Time *_target, unsigned int mSec) { _target->SetTimerPeriod (mSec); } DllExport unsigned int Time_GetFrameNumber (Urho3D::Time *_target) { return _target->GetFrameNumber (); } DllExport float Time_GetTimeStep (Urho3D::Time *_target) { return _target->GetTimeStep (); } DllExport unsigned int Time_GetTimerPeriod (Urho3D::Time *_target) { return _target->GetTimerPeriod (); } DllExport float Time_GetElapsedTime (Urho3D::Time *_target) { return _target->GetElapsedTime (); } DllExport float Time_GetFramesPerSecond (Urho3D::Time *_target) { return _target->GetFramesPerSecond (); } DllExport unsigned int Time_GetSystemTime () { return Time::GetSystemTime (); } DllExport unsigned int Time_GetTimeSinceEpoch () { return Time::GetTimeSinceEpoch (); } DllExport const char * Time_GetTimeStamp () { return stringdup((Time::GetTimeStamp ()).CString ()); } DllExport void Time_Sleep (unsigned int mSec) { Time::Sleep (mSec); } DllExport int Resource_GetType (Urho3D::Resource *_target) { return (_target->GetType ()).Value (); } DllExport const char * Resource_GetTypeName (Urho3D::Resource *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Resource_GetTypeStatic () { return (Resource::GetTypeStatic ()).Value (); } DllExport const char * Resource_GetTypeNameStatic () { return stringdup((Resource::GetTypeNameStatic ()).CString ()); } DllExport void * Resource_Resource (Urho3D::Context * context) { return WeakPtr<Resource>(new Resource(context)); } DllExport int Resource_Load_File (Urho3D::Resource *_target, File * source) { return _target->Load (*source); } DllExport int Resource_Load_MemoryBuffer (Urho3D::Resource *_target, MemoryBuffer * source) { return _target->Load (*source); } DllExport int Resource_BeginLoad_File (Urho3D::Resource *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Resource_BeginLoad_MemoryBuffer (Urho3D::Resource *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Resource_EndLoad (Urho3D::Resource *_target) { return _target->EndLoad (); } DllExport int Resource_Save_File (Urho3D::Resource *_target, File * dest) { return _target->Save (*dest); } DllExport int Resource_Save_MemoryBuffer (Urho3D::Resource *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int Resource_LoadFile (Urho3D::Resource *_target, const char * fileName) { return _target->LoadFile (Urho3D::String(fileName)); } DllExport int Resource_SaveFile (Urho3D::Resource *_target, const char * fileName) { return _target->SaveFile (Urho3D::String(fileName)); } DllExport void Resource_SetName (Urho3D::Resource *_target, const char * name) { _target->SetName (Urho3D::String(name)); } DllExport void Resource_SetMemoryUse (Urho3D::Resource *_target, unsigned int size) { _target->SetMemoryUse (size); } DllExport void Resource_ResetUseTimer (Urho3D::Resource *_target) { _target->ResetUseTimer (); } DllExport void Resource_SetAsyncLoadState (Urho3D::Resource *_target, enum Urho3D::AsyncLoadState newState) { _target->SetAsyncLoadState (newState); } DllExport const char * Resource_GetName (Urho3D::Resource *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport int Resource_GetNameHash (Urho3D::Resource *_target) { return (_target->GetNameHash ()).Value (); } DllExport unsigned int Resource_GetMemoryUse (Urho3D::Resource *_target) { return _target->GetMemoryUse (); } DllExport unsigned int Resource_GetUseTimer (Urho3D::Resource *_target) { return _target->GetUseTimer (); } DllExport enum Urho3D::AsyncLoadState Resource_GetAsyncLoadState (Urho3D::Resource *_target) { return _target->GetAsyncLoadState (); } DllExport int ResourceWithMetadata_GetType (Urho3D::ResourceWithMetadata *_target) { return (_target->GetType ()).Value (); } DllExport const char * ResourceWithMetadata_GetTypeName (Urho3D::ResourceWithMetadata *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ResourceWithMetadata_GetTypeStatic () { return (ResourceWithMetadata::GetTypeStatic ()).Value (); } DllExport const char * ResourceWithMetadata_GetTypeNameStatic () { return stringdup((ResourceWithMetadata::GetTypeNameStatic ()).CString ()); } DllExport void * ResourceWithMetadata_ResourceWithMetadata (Urho3D::Context * context) { return WeakPtr<ResourceWithMetadata>(new ResourceWithMetadata(context)); } // Urho3D::Variant overloads begin: DllExport void ResourceWithMetadata_AddMetadata_0 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::Vector3 & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_1 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::IntRect & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_2 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::Color & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_3 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::Vector2 & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_4 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::Vector4 & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_5 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::IntVector2 & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_6 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::Quaternion & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_7 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::Matrix4 & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_8 (Urho3D::ResourceWithMetadata *_target, const char * name, const class Urho3D::Matrix3x4 & value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_9 (Urho3D::ResourceWithMetadata *_target, const char * name, int value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_10 (Urho3D::ResourceWithMetadata *_target, const char * name, float value) { _target->AddMetadata (Urho3D::String(name), (value)); } DllExport void ResourceWithMetadata_AddMetadata_11 (Urho3D::ResourceWithMetadata *_target, const char * name, const char * value) { _target->AddMetadata (Urho3D::String(name), Urho3D::String(value)); } DllExport void ResourceWithMetadata_AddMetadata_12 (Urho3D::ResourceWithMetadata *_target, const char * name, bool value) { _target->AddMetadata (Urho3D::String(name), (value)); } // Urho3D::Variant overloads end. DllExport void ResourceWithMetadata_RemoveMetadata (Urho3D::ResourceWithMetadata *_target, const char * name) { _target->RemoveMetadata (Urho3D::String(name)); } DllExport void ResourceWithMetadata_RemoveAllMetadata (Urho3D::ResourceWithMetadata *_target) { _target->RemoveAllMetadata (); } // Urho3D::Variant overloads begin: DllExport Interop::Vector3 ResourceWithMetadata_GetMetadata_0 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::Vector3 *) &(_target->GetMetadata (Urho3D::String(name)).GetVector3())); } DllExport Interop::IntRect ResourceWithMetadata_GetMetadata_1 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::IntRect *) &(_target->GetMetadata (Urho3D::String(name)).GetIntRect())); } DllExport Interop::Color ResourceWithMetadata_GetMetadata_2 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::Color *) &(_target->GetMetadata (Urho3D::String(name)).GetColor())); } DllExport Interop::Vector2 ResourceWithMetadata_GetMetadata_3 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::Vector2 *) &(_target->GetMetadata (Urho3D::String(name)).GetVector2())); } DllExport Interop::Vector4 ResourceWithMetadata_GetMetadata_4 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::Vector4 *) &(_target->GetMetadata (Urho3D::String(name)).GetVector4())); } DllExport Interop::IntVector2 ResourceWithMetadata_GetMetadata_5 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::IntVector2 *) &(_target->GetMetadata (Urho3D::String(name)).GetIntVector2())); } DllExport Interop::Quaternion ResourceWithMetadata_GetMetadata_6 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::Quaternion *) &(_target->GetMetadata (Urho3D::String(name)).GetQuaternion())); } DllExport Interop::Matrix4 ResourceWithMetadata_GetMetadata_7 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::Matrix4 *) &(_target->GetMetadata (Urho3D::String(name)).GetMatrix4())); } DllExport Interop::Matrix3x4 ResourceWithMetadata_GetMetadata_8 (Urho3D::ResourceWithMetadata *_target, const char * name) { return *((Interop::Matrix3x4 *) &(_target->GetMetadata (Urho3D::String(name)).GetMatrix3x4())); } DllExport int ResourceWithMetadata_GetMetadata_9 (Urho3D::ResourceWithMetadata *_target, const char * name) { return (_target->GetMetadata (Urho3D::String(name)).GetInt()); } DllExport float ResourceWithMetadata_GetMetadata_10 (Urho3D::ResourceWithMetadata *_target, const char * name) { return (_target->GetMetadata (Urho3D::String(name)).GetFloat()); } DllExport const char * ResourceWithMetadata_GetMetadata_11 (Urho3D::ResourceWithMetadata *_target, const char * name) { return stringdup(_target->GetMetadata (Urho3D::String(name)).GetString().CString()); } DllExport bool ResourceWithMetadata_GetMetadata_12 (Urho3D::ResourceWithMetadata *_target, const char * name) { return (_target->GetMetadata (Urho3D::String(name)).GetBool()); } // Urho3D::Variant overloads end. DllExport int ResourceWithMetadata_HasMetadata (Urho3D::ResourceWithMetadata *_target) { return _target->HasMetadata (); } DllExport int Sprite2D_GetType (Urho3D::Sprite2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * Sprite2D_GetTypeName (Urho3D::Sprite2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Sprite2D_GetTypeStatic () { return (Sprite2D::GetTypeStatic ()).Value (); } DllExport const char * Sprite2D_GetTypeNameStatic () { return stringdup((Sprite2D::GetTypeNameStatic ()).CString ()); } DllExport void * Sprite2D_Sprite2D (Urho3D::Context * context) { return WeakPtr<Sprite2D>(new Sprite2D(context)); } DllExport void Sprite2D_RegisterObject (Urho3D::Context * context) { Sprite2D::RegisterObject (context); } DllExport int Sprite2D_BeginLoad_File (Urho3D::Sprite2D *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Sprite2D_BeginLoad_MemoryBuffer (Urho3D::Sprite2D *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Sprite2D_EndLoad (Urho3D::Sprite2D *_target) { return _target->EndLoad (); } DllExport void Sprite2D_SetTexture (Urho3D::Sprite2D *_target, Urho3D::Texture2D * texture) { _target->SetTexture (texture); } DllExport void Sprite2D_SetRectangle (Urho3D::Sprite2D *_target, const class Urho3D::IntRect & rectangle) { _target->SetRectangle (rectangle); } DllExport void Sprite2D_SetHotSpot (Urho3D::Sprite2D *_target, const class Urho3D::Vector2 & hotSpot) { _target->SetHotSpot (hotSpot); } DllExport void Sprite2D_SetOffset (Urho3D::Sprite2D *_target, const class Urho3D::IntVector2 & offset) { _target->SetOffset (offset); } DllExport void Sprite2D_SetTextureEdgeOffset (Urho3D::Sprite2D *_target, float offset) { _target->SetTextureEdgeOffset (offset); } DllExport void Sprite2D_SetSpriteSheet (Urho3D::Sprite2D *_target, Urho3D::SpriteSheet2D * spriteSheet) { _target->SetSpriteSheet (spriteSheet); } DllExport Urho3D::Texture2D * Sprite2D_GetTexture (Urho3D::Sprite2D *_target) { return _target->GetTexture (); } DllExport Interop::IntRect Sprite2D_GetRectangle (Urho3D::Sprite2D *_target) { return *((Interop::IntRect *) &(_target->GetRectangle ())); } DllExport Interop::Vector2 Sprite2D_GetHotSpot (Urho3D::Sprite2D *_target) { return *((Interop::Vector2 *) &(_target->GetHotSpot ())); } DllExport Interop::IntVector2 Sprite2D_GetOffset (Urho3D::Sprite2D *_target) { return *((Interop::IntVector2 *) &(_target->GetOffset ())); } DllExport float Sprite2D_GetTextureEdgeOffset (Urho3D::Sprite2D *_target) { return _target->GetTextureEdgeOffset (); } DllExport Urho3D::SpriteSheet2D * Sprite2D_GetSpriteSheet (Urho3D::Sprite2D *_target) { return _target->GetSpriteSheet (); } DllExport Urho3D::ResourceRef Sprite2D_SaveToResourceRef (Urho3D::Sprite2D * sprite) { return Sprite2D::SaveToResourceRef (sprite); } DllExport void * PropertySet2D_PropertySet2D () { return WeakPtr<PropertySet2D>(new PropertySet2D()); } DllExport void PropertySet2D_Load (Urho3D::PropertySet2D *_target, const class Urho3D::XMLElement & element) { _target->Load (element); } DllExport int PropertySet2D_HasProperty (Urho3D::PropertySet2D *_target, const char * name) { return _target->HasProperty (Urho3D::String(name)); } DllExport const char * PropertySet2D_GetProperty (Urho3D::PropertySet2D *_target, const char * name) { return stringdup((_target->GetProperty (Urho3D::String(name))).CString ()); } DllExport void * Tile2D_Tile2D () { return WeakPtr<Tile2D>(new Tile2D()); } DllExport int Tile2D_GetGid (Urho3D::Tile2D *_target) { return _target->GetGid (); } DllExport Urho3D::Sprite2D * Tile2D_GetSprite (Urho3D::Tile2D *_target) { return _target->GetSprite (); } DllExport int Tile2D_HasProperty (Urho3D::Tile2D *_target, const char * name) { return _target->HasProperty (Urho3D::String(name)); } DllExport const char * Tile2D_GetProperty (Urho3D::Tile2D *_target, const char * name) { return stringdup((_target->GetProperty (Urho3D::String(name))).CString ()); } DllExport void * TileMapObject2D_TileMapObject2D () { return WeakPtr<TileMapObject2D>(new TileMapObject2D()); } DllExport enum Urho3D::TileMapObjectType2D TileMapObject2D_GetObjectType (Urho3D::TileMapObject2D *_target) { return _target->GetObjectType (); } DllExport const char * TileMapObject2D_GetName (Urho3D::TileMapObject2D *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport const char * TileMapObject2D_GetType (Urho3D::TileMapObject2D *_target) { return stringdup((_target->GetType ()).CString ()); } DllExport Interop::Vector2 TileMapObject2D_GetPosition (Urho3D::TileMapObject2D *_target) { return *((Interop::Vector2 *) &(_target->GetPosition ())); } DllExport Interop::Vector2 TileMapObject2D_GetSize (Urho3D::TileMapObject2D *_target) { return *((Interop::Vector2 *) &(_target->GetSize ())); } DllExport unsigned int TileMapObject2D_GetNumPoints (Urho3D::TileMapObject2D *_target) { return _target->GetNumPoints (); } DllExport Interop::Vector2 TileMapObject2D_GetPoint (Urho3D::TileMapObject2D *_target, unsigned int index) { return *((Interop::Vector2 *) &(_target->GetPoint (index))); } DllExport int TileMapObject2D_GetTileGid (Urho3D::TileMapObject2D *_target) { return _target->GetTileGid (); } DllExport Urho3D::Sprite2D * TileMapObject2D_GetTileSprite (Urho3D::TileMapObject2D *_target) { return _target->GetTileSprite (); } DllExport int TileMapObject2D_HasProperty (Urho3D::TileMapObject2D *_target, const char * name) { return _target->HasProperty (Urho3D::String(name)); } DllExport const char * TileMapObject2D_GetProperty (Urho3D::TileMapObject2D *_target, const char * name) { return stringdup((_target->GetProperty (Urho3D::String(name))).CString ()); } DllExport int TileMapLayer2D_GetType (Urho3D::TileMapLayer2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * TileMapLayer2D_GetTypeName (Urho3D::TileMapLayer2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int TileMapLayer2D_GetTypeStatic () { return (TileMapLayer2D::GetTypeStatic ()).Value (); } DllExport const char * TileMapLayer2D_GetTypeNameStatic () { return stringdup((TileMapLayer2D::GetTypeNameStatic ()).CString ()); } DllExport void * TileMapLayer2D_TileMapLayer2D (Urho3D::Context * context) { return WeakPtr<TileMapLayer2D>(new TileMapLayer2D(context)); } DllExport void TileMapLayer2D_RegisterObject (Urho3D::Context * context) { TileMapLayer2D::RegisterObject (context); } DllExport void TileMapLayer2D_DrawDebugGeometry (Urho3D::TileMapLayer2D *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void TileMapLayer2D_Initialize (Urho3D::TileMapLayer2D *_target, Urho3D::TileMap2D * tileMap, const class Urho3D::TmxLayer2D * tmxLayer) { _target->Initialize (tileMap, tmxLayer); } DllExport void TileMapLayer2D_SetDrawOrder (Urho3D::TileMapLayer2D *_target, int drawOrder) { _target->SetDrawOrder (drawOrder); } DllExport void TileMapLayer2D_SetVisible (Urho3D::TileMapLayer2D *_target, bool visible) { _target->SetVisible (visible); } DllExport Urho3D::TileMap2D * TileMapLayer2D_GetTileMap (Urho3D::TileMapLayer2D *_target) { return _target->GetTileMap (); } DllExport const class Urho3D::TmxLayer2D * TileMapLayer2D_GetTmxLayer (Urho3D::TileMapLayer2D *_target) { return _target->GetTmxLayer (); } DllExport int TileMapLayer2D_GetDrawOrder (Urho3D::TileMapLayer2D *_target) { return _target->GetDrawOrder (); } DllExport int TileMapLayer2D_IsVisible (Urho3D::TileMapLayer2D *_target) { return _target->IsVisible (); } DllExport int TileMapLayer2D_HasProperty (Urho3D::TileMapLayer2D *_target, const char * name) { return _target->HasProperty (Urho3D::String(name)); } DllExport const char * TileMapLayer2D_GetProperty (Urho3D::TileMapLayer2D *_target, const char * name) { return stringdup((_target->GetProperty (Urho3D::String(name))).CString ()); } DllExport enum Urho3D::TileMapLayerType2D TileMapLayer2D_GetLayerType (Urho3D::TileMapLayer2D *_target) { return _target->GetLayerType (); } DllExport int TileMapLayer2D_GetWidth (Urho3D::TileMapLayer2D *_target) { return _target->GetWidth (); } DllExport int TileMapLayer2D_GetHeight (Urho3D::TileMapLayer2D *_target) { return _target->GetHeight (); } DllExport Urho3D::Node * TileMapLayer2D_GetTileNode (Urho3D::TileMapLayer2D *_target, int x, int y) { return _target->GetTileNode (x, y); } DllExport Urho3D::Tile2D * TileMapLayer2D_GetTile (Urho3D::TileMapLayer2D *_target, int x, int y) { return _target->GetTile (x, y); } DllExport unsigned int TileMapLayer2D_GetNumObjects (Urho3D::TileMapLayer2D *_target) { return _target->GetNumObjects (); } DllExport Urho3D::TileMapObject2D * TileMapLayer2D_GetObject (Urho3D::TileMapLayer2D *_target, unsigned int index) { return _target->GetObject (index); } DllExport Urho3D::Node * TileMapLayer2D_GetObjectNode (Urho3D::TileMapLayer2D *_target, unsigned int index) { return _target->GetObjectNode (index); } DllExport Urho3D::Node * TileMapLayer2D_GetImageNode (Urho3D::TileMapLayer2D *_target) { return _target->GetImageNode (); } DllExport void * TmxLayer2D_TmxLayer2D (Urho3D::TmxFile2D * tmxFile, enum Urho3D::TileMapLayerType2D type) { return WeakPtr<TmxLayer2D>(new TmxLayer2D(tmxFile, type)); } DllExport Urho3D::TmxFile2D * TmxLayer2D_GetTmxFile (Urho3D::TmxLayer2D *_target) { return _target->GetTmxFile (); } DllExport enum Urho3D::TileMapLayerType2D TmxLayer2D_GetType (Urho3D::TmxLayer2D *_target) { return _target->GetType (); } DllExport const char * TmxLayer2D_GetName (Urho3D::TmxLayer2D *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport int TmxLayer2D_GetWidth (Urho3D::TmxLayer2D *_target) { return _target->GetWidth (); } DllExport int TmxLayer2D_GetHeight (Urho3D::TmxLayer2D *_target) { return _target->GetHeight (); } DllExport int TmxLayer2D_IsVisible (Urho3D::TmxLayer2D *_target) { return _target->IsVisible (); } DllExport int TmxLayer2D_HasProperty (Urho3D::TmxLayer2D *_target, const char * name) { return _target->HasProperty (Urho3D::String(name)); } DllExport const char * TmxLayer2D_GetProperty (Urho3D::TmxLayer2D *_target, const char * name) { return stringdup((_target->GetProperty (Urho3D::String(name))).CString ()); } DllExport void * TmxTileLayer2D_TmxTileLayer2D (Urho3D::TmxFile2D * tmxFile) { return WeakPtr<TmxTileLayer2D>(new TmxTileLayer2D(tmxFile)); } DllExport int TmxTileLayer2D_Load (Urho3D::TmxTileLayer2D *_target, const class Urho3D::XMLElement & element, const struct Urho3D::TileMapInfo2D & info) { return _target->Load (element, info); } DllExport Urho3D::Tile2D * TmxTileLayer2D_GetTile (Urho3D::TmxTileLayer2D *_target, int x, int y) { return _target->GetTile (x, y); } DllExport void * TmxObjectGroup2D_TmxObjectGroup2D (Urho3D::TmxFile2D * tmxFile) { return WeakPtr<TmxObjectGroup2D>(new TmxObjectGroup2D(tmxFile)); } DllExport int TmxObjectGroup2D_Load (Urho3D::TmxObjectGroup2D *_target, const class Urho3D::XMLElement & element, const struct Urho3D::TileMapInfo2D & info) { return _target->Load (element, info); } DllExport unsigned int TmxObjectGroup2D_GetNumObjects (Urho3D::TmxObjectGroup2D *_target) { return _target->GetNumObjects (); } DllExport Urho3D::TileMapObject2D * TmxObjectGroup2D_GetObject (Urho3D::TmxObjectGroup2D *_target, unsigned int index) { return _target->GetObject (index); } DllExport void * TmxImageLayer2D_TmxImageLayer2D (Urho3D::TmxFile2D * tmxFile) { return WeakPtr<TmxImageLayer2D>(new TmxImageLayer2D(tmxFile)); } DllExport int TmxImageLayer2D_Load (Urho3D::TmxImageLayer2D *_target, const class Urho3D::XMLElement & element, const struct Urho3D::TileMapInfo2D & info) { return _target->Load (element, info); } DllExport Interop::Vector2 TmxImageLayer2D_GetPosition (Urho3D::TmxImageLayer2D *_target) { return *((Interop::Vector2 *) &(_target->GetPosition ())); } DllExport const char * TmxImageLayer2D_GetSource (Urho3D::TmxImageLayer2D *_target) { return stringdup((_target->GetSource ()).CString ()); } DllExport Urho3D::Sprite2D * TmxImageLayer2D_GetSprite (Urho3D::TmxImageLayer2D *_target) { return _target->GetSprite (); } DllExport int TmxFile2D_GetType (Urho3D::TmxFile2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * TmxFile2D_GetTypeName (Urho3D::TmxFile2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int TmxFile2D_GetTypeStatic () { return (TmxFile2D::GetTypeStatic ()).Value (); } DllExport const char * TmxFile2D_GetTypeNameStatic () { return stringdup((TmxFile2D::GetTypeNameStatic ()).CString ()); } DllExport void * TmxFile2D_TmxFile2D (Urho3D::Context * context) { return WeakPtr<TmxFile2D>(new TmxFile2D(context)); } DllExport void TmxFile2D_RegisterObject (Urho3D::Context * context) { TmxFile2D::RegisterObject (context); } DllExport int TmxFile2D_BeginLoad_File (Urho3D::TmxFile2D *_target, File * source) { return _target->BeginLoad (*source); } DllExport int TmxFile2D_BeginLoad_MemoryBuffer (Urho3D::TmxFile2D *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int TmxFile2D_EndLoad (Urho3D::TmxFile2D *_target) { return _target->EndLoad (); } DllExport int TmxFile2D_SetInfo (Urho3D::TmxFile2D *_target, enum Urho3D::Orientation2D orientation, int width, int height, float tileWidth, float tileHeight) { return _target->SetInfo (orientation, width, height, tileWidth, tileHeight); } DllExport void TmxFile2D_AddLayer (Urho3D::TmxFile2D *_target, unsigned int index, Urho3D::TmxLayer2D * layer) { _target->AddLayer (index, layer); } DllExport Urho3D::TileMapInfo2D TmxFile2D_GetInfo (Urho3D::TmxFile2D *_target) { return _target->GetInfo (); } DllExport Urho3D::Sprite2D * TmxFile2D_GetTileSprite (Urho3D::TmxFile2D *_target, int gid) { return _target->GetTileSprite (gid); } DllExport Urho3D::PropertySet2D * TmxFile2D_GetTilePropertySet (Urho3D::TmxFile2D *_target, int gid) { return _target->GetTilePropertySet (gid); } DllExport unsigned int TmxFile2D_GetNumLayers (Urho3D::TmxFile2D *_target) { return _target->GetNumLayers (); } DllExport const class Urho3D::TmxLayer2D * TmxFile2D_GetLayer (Urho3D::TmxFile2D *_target, unsigned int index) { return _target->GetLayer (index); } DllExport int MessageBox_GetType (Urho3D::MessageBox *_target) { return (_target->GetType ()).Value (); } DllExport const char * MessageBox_GetTypeName (Urho3D::MessageBox *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int MessageBox_GetTypeStatic () { return (MessageBox::GetTypeStatic ()).Value (); } DllExport const char * MessageBox_GetTypeNameStatic () { return stringdup((MessageBox::GetTypeNameStatic ()).CString ()); } DllExport void * MessageBox_MessageBox (Urho3D::Context * context, const char * messageString, const char * titleString, Urho3D::XMLFile * layoutFile, Urho3D::XMLFile * styleFile) { return WeakPtr<MessageBox>(new MessageBox(context, Urho3D::String(messageString), Urho3D::String(titleString), layoutFile, styleFile)); } DllExport void MessageBox_RegisterObject (Urho3D::Context * context) { MessageBox::RegisterObject (context); } DllExport void MessageBox_SetTitle (Urho3D::MessageBox *_target, const char * text) { _target->SetTitle (Urho3D::String(text)); } DllExport void MessageBox_SetMessage (Urho3D::MessageBox *_target, const char * text) { _target->SetMessage (Urho3D::String(text)); } DllExport const char * MessageBox_GetTitle (Urho3D::MessageBox *_target) { return stringdup((_target->GetTitle ()).CString ()); } DllExport const char * MessageBox_GetMessage (Urho3D::MessageBox *_target) { return stringdup((_target->GetMessage ()).CString ()); } DllExport Urho3D::UIElement * MessageBox_GetWindow (Urho3D::MessageBox *_target) { return _target->GetWindow (); } DllExport int Audio_GetType (Urho3D::Audio *_target) { return (_target->GetType ()).Value (); } DllExport const char * Audio_GetTypeName (Urho3D::Audio *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Audio_GetTypeStatic () { return (Audio::GetTypeStatic ()).Value (); } DllExport const char * Audio_GetTypeNameStatic () { return stringdup((Audio::GetTypeNameStatic ()).CString ()); } DllExport void * Audio_Audio (Urho3D::Context * context) { return WeakPtr<Audio>(new Audio(context)); } DllExport int Audio_SetMode (Urho3D::Audio *_target, int bufferLengthMSec, int mixRate, bool stereo, bool interpolation) { return _target->SetMode (bufferLengthMSec, mixRate, stereo, interpolation); } DllExport void Audio_Update (Urho3D::Audio *_target, float timeStep) { _target->Update (timeStep); } DllExport int Audio_Play (Urho3D::Audio *_target) { return _target->Play (); } DllExport void Audio_Stop (Urho3D::Audio *_target) { _target->Stop (); } DllExport void Audio_SetMasterGain (Urho3D::Audio *_target, const char * type, float gain) { _target->SetMasterGain (Urho3D::String(type), gain); } DllExport void Audio_PauseSoundType (Urho3D::Audio *_target, const char * type) { _target->PauseSoundType (Urho3D::String(type)); } DllExport void Audio_ResumeSoundType (Urho3D::Audio *_target, const char * type) { _target->ResumeSoundType (Urho3D::String(type)); } DllExport void Audio_ResumeAll (Urho3D::Audio *_target) { _target->ResumeAll (); } DllExport void Audio_SetListener (Urho3D::Audio *_target, Urho3D::SoundListener * listener) { _target->SetListener (listener); } DllExport void Audio_StopSound (Urho3D::Audio *_target, Urho3D::Sound * sound) { _target->StopSound (sound); } DllExport unsigned int Audio_GetSampleSize (Urho3D::Audio *_target) { return _target->GetSampleSize (); } DllExport int Audio_GetMixRate (Urho3D::Audio *_target) { return _target->GetMixRate (); } DllExport int Audio_GetInterpolation (Urho3D::Audio *_target) { return _target->GetInterpolation (); } DllExport int Audio_IsStereo (Urho3D::Audio *_target) { return _target->IsStereo (); } DllExport int Audio_IsPlaying (Urho3D::Audio *_target) { return _target->IsPlaying (); } DllExport int Audio_IsInitialized (Urho3D::Audio *_target) { return _target->IsInitialized (); } DllExport float Audio_GetMasterGain (Urho3D::Audio *_target, const char * type) { return _target->GetMasterGain (Urho3D::String(type)); } DllExport int Audio_IsSoundTypePaused (Urho3D::Audio *_target, const char * type) { return _target->IsSoundTypePaused (Urho3D::String(type)); } DllExport Urho3D::SoundListener * Audio_GetListener (Urho3D::Audio *_target) { return _target->GetListener (); } DllExport int Audio_HasMasterGain (Urho3D::Audio *_target, const char * type) { return _target->HasMasterGain (Urho3D::String(type)); } DllExport void Audio_AddSoundSource (Urho3D::Audio *_target, Urho3D::SoundSource * soundSource) { _target->AddSoundSource (soundSource); } DllExport void Audio_RemoveSoundSource (Urho3D::Audio *_target, Urho3D::SoundSource * soundSource) { _target->RemoveSoundSource (soundSource); } DllExport float Audio_GetSoundSourceMasterGain (Urho3D::Audio *_target, int typeHash) { return _target->GetSoundSourceMasterGain (Urho3D::StringHash(typeHash)); } DllExport void Audio_MixOutput (Urho3D::Audio *_target, void * dest, unsigned int samples) { _target->MixOutput (dest, samples); } DllExport int SoundStream_Seek (Urho3D::SoundStream *_target, unsigned int sample_number) { return _target->Seek (sample_number); } DllExport unsigned int SoundStream_GetData (Urho3D::SoundStream *_target, signed char * dest, unsigned int numBytes) { return _target->GetData (dest, numBytes); } DllExport void SoundStream_SetFormat (Urho3D::SoundStream *_target, unsigned int frequency, bool sixteenBit, bool stereo) { _target->SetFormat (frequency, sixteenBit, stereo); } DllExport void SoundStream_SetStopAtEnd (Urho3D::SoundStream *_target, bool enable) { _target->SetStopAtEnd (enable); } DllExport unsigned int SoundStream_GetSampleSize (Urho3D::SoundStream *_target) { return _target->GetSampleSize (); } DllExport float SoundStream_GetFrequency (Urho3D::SoundStream *_target) { return _target->GetFrequency (); } DllExport unsigned int SoundStream_GetIntFrequency (Urho3D::SoundStream *_target) { return _target->GetIntFrequency (); } DllExport int SoundStream_GetStopAtEnd (Urho3D::SoundStream *_target) { return _target->GetStopAtEnd (); } DllExport int SoundStream_IsSixteenBit (Urho3D::SoundStream *_target) { return _target->IsSixteenBit (); } DllExport int SoundStream_IsStereo (Urho3D::SoundStream *_target) { return _target->IsStereo (); } DllExport void * BufferedSoundStream_BufferedSoundStream () { return WeakPtr<BufferedSoundStream>(new BufferedSoundStream()); } DllExport unsigned int BufferedSoundStream_GetData (Urho3D::BufferedSoundStream *_target, signed char * dest, unsigned int numBytes) { return _target->GetData (dest, numBytes); } DllExport void BufferedSoundStream_AddData (Urho3D::BufferedSoundStream *_target, void * data, unsigned int numBytes) { _target->AddData (data, numBytes); } DllExport void BufferedSoundStream_Clear (Urho3D::BufferedSoundStream *_target) { _target->Clear (); } DllExport unsigned int BufferedSoundStream_GetBufferNumBytes (Urho3D::BufferedSoundStream *_target) { return _target->GetBufferNumBytes (); } DllExport float BufferedSoundStream_GetBufferLength (Urho3D::BufferedSoundStream *_target) { return _target->GetBufferLength (); } DllExport void * OggVorbisSoundStream_OggVorbisSoundStream (const class Urho3D::Sound * sound) { return WeakPtr<OggVorbisSoundStream>(new OggVorbisSoundStream(sound)); } DllExport int OggVorbisSoundStream_Seek (Urho3D::OggVorbisSoundStream *_target, unsigned int sample_number) { return _target->Seek (sample_number); } DllExport unsigned int OggVorbisSoundStream_GetData (Urho3D::OggVorbisSoundStream *_target, signed char * dest, unsigned int numBytes) { return _target->GetData (dest, numBytes); } DllExport int Sound_GetType (Urho3D::Sound *_target) { return (_target->GetType ()).Value (); } DllExport const char * Sound_GetTypeName (Urho3D::Sound *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Sound_GetTypeStatic () { return (Sound::GetTypeStatic ()).Value (); } DllExport const char * Sound_GetTypeNameStatic () { return stringdup((Sound::GetTypeNameStatic ()).CString ()); } DllExport void * Sound_Sound (Urho3D::Context * context) { return WeakPtr<Sound>(new Sound(context)); } DllExport void Sound_RegisterObject (Urho3D::Context * context) { Sound::RegisterObject (context); } DllExport int Sound_BeginLoad_File (Urho3D::Sound *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Sound_BeginLoad_MemoryBuffer (Urho3D::Sound *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Sound_LoadRaw_File (Urho3D::Sound *_target, File * source) { return _target->LoadRaw (*source); } DllExport int Sound_LoadRaw_MemoryBuffer (Urho3D::Sound *_target, MemoryBuffer * source) { return _target->LoadRaw (*source); } DllExport int Sound_LoadWav_File (Urho3D::Sound *_target, File * source) { return _target->LoadWav (*source); } DllExport int Sound_LoadWav_MemoryBuffer (Urho3D::Sound *_target, MemoryBuffer * source) { return _target->LoadWav (*source); } DllExport int Sound_LoadOggVorbis_File (Urho3D::Sound *_target, File * source) { return _target->LoadOggVorbis (*source); } DllExport int Sound_LoadOggVorbis_MemoryBuffer (Urho3D::Sound *_target, MemoryBuffer * source) { return _target->LoadOggVorbis (*source); } DllExport void Sound_SetSize (Urho3D::Sound *_target, unsigned int dataSize) { _target->SetSize (dataSize); } DllExport void Sound_SetData (Urho3D::Sound *_target, const void * data, unsigned int dataSize) { _target->SetData (data, dataSize); } DllExport void Sound_SetFormat (Urho3D::Sound *_target, unsigned int frequency, bool sixteenBit, bool stereo) { _target->SetFormat (frequency, sixteenBit, stereo); } DllExport void Sound_SetLooped (Urho3D::Sound *_target, bool enable) { _target->SetLooped (enable); } DllExport void Sound_SetLoop (Urho3D::Sound *_target, unsigned int repeatOffset, unsigned int endOffset) { _target->SetLoop (repeatOffset, endOffset); } DllExport Urho3D::SoundStream * Sound_GetDecoderStream (Urho3D::Sound *_target) { auto copy = _target->GetDecoderStream (); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport signed char * Sound_GetStart (Urho3D::Sound *_target) { return _target->GetStart (); } DllExport signed char * Sound_GetRepeat (Urho3D::Sound *_target) { return _target->GetRepeat (); } DllExport signed char * Sound_GetEnd (Urho3D::Sound *_target) { return _target->GetEnd (); } DllExport float Sound_GetLength (Urho3D::Sound *_target) { return _target->GetLength (); } DllExport unsigned int Sound_GetDataSize (Urho3D::Sound *_target) { return _target->GetDataSize (); } DllExport unsigned int Sound_GetSampleSize (Urho3D::Sound *_target) { return _target->GetSampleSize (); } DllExport float Sound_GetFrequency (Urho3D::Sound *_target) { return _target->GetFrequency (); } DllExport unsigned int Sound_GetIntFrequency (Urho3D::Sound *_target) { return _target->GetIntFrequency (); } DllExport int Sound_IsLooped (Urho3D::Sound *_target) { return _target->IsLooped (); } DllExport int Sound_IsSixteenBit (Urho3D::Sound *_target) { return _target->IsSixteenBit (); } DllExport int Sound_IsStereo (Urho3D::Sound *_target) { return _target->IsStereo (); } DllExport int Sound_IsCompressed (Urho3D::Sound *_target) { return _target->IsCompressed (); } DllExport void Sound_FixInterpolation (Urho3D::Sound *_target) { _target->FixInterpolation (); } DllExport int SoundListener_GetType (Urho3D::SoundListener *_target) { return (_target->GetType ()).Value (); } DllExport const char * SoundListener_GetTypeName (Urho3D::SoundListener *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int SoundListener_GetTypeStatic () { return (SoundListener::GetTypeStatic ()).Value (); } DllExport const char * SoundListener_GetTypeNameStatic () { return stringdup((SoundListener::GetTypeNameStatic ()).CString ()); } DllExport void * SoundListener_SoundListener (Urho3D::Context * context) { return WeakPtr<SoundListener>(new SoundListener(context)); } DllExport void SoundListener_RegisterObject (Urho3D::Context * context) { SoundListener::RegisterObject (context); } DllExport int SoundSource_GetType (Urho3D::SoundSource *_target) { return (_target->GetType ()).Value (); } DllExport const char * SoundSource_GetTypeName (Urho3D::SoundSource *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int SoundSource_GetTypeStatic () { return (SoundSource::GetTypeStatic ()).Value (); } DllExport const char * SoundSource_GetTypeNameStatic () { return stringdup((SoundSource::GetTypeNameStatic ()).CString ()); } DllExport void * SoundSource_SoundSource (Urho3D::Context * context) { return WeakPtr<SoundSource>(new SoundSource(context)); } DllExport void SoundSource_RegisterObject (Urho3D::Context * context) { SoundSource::RegisterObject (context); } DllExport void SoundSource_Seek (Urho3D::SoundSource *_target, float seekTime) { _target->Seek (seekTime); } DllExport void SoundSource_Play (Urho3D::SoundSource *_target, Urho3D::Sound * sound) { _target->Play (sound); } DllExport void SoundSource_Play0 (Urho3D::SoundSource *_target, Urho3D::Sound * sound, float frequency) { _target->Play (sound, frequency); } DllExport void SoundSource_Play1 (Urho3D::SoundSource *_target, Urho3D::Sound * sound, float frequency, float gain) { _target->Play (sound, frequency, gain); } DllExport void SoundSource_Play2 (Urho3D::SoundSource *_target, Urho3D::Sound * sound, float frequency, float gain, float panning) { _target->Play (sound, frequency, gain, panning); } DllExport void SoundSource_Play3 (Urho3D::SoundSource *_target, Urho3D::SoundStream * stream) { _target->Play (stream); } DllExport void SoundSource_Stop (Urho3D::SoundSource *_target) { _target->Stop (); } DllExport void SoundSource_SetSoundType (Urho3D::SoundSource *_target, const char * type) { _target->SetSoundType (Urho3D::String(type)); } DllExport void SoundSource_SetFrequency (Urho3D::SoundSource *_target, float frequency) { _target->SetFrequency (frequency); } DllExport void SoundSource_SetGain (Urho3D::SoundSource *_target, float gain) { _target->SetGain (gain); } DllExport void SoundSource_SetAttenuation (Urho3D::SoundSource *_target, float attenuation) { _target->SetAttenuation (attenuation); } DllExport void SoundSource_SetPanning (Urho3D::SoundSource *_target, float panning) { _target->SetPanning (panning); } DllExport void SoundSource_SetAutoRemoveMode (Urho3D::SoundSource *_target, enum Urho3D::AutoRemoveMode mode) { _target->SetAutoRemoveMode (mode); } DllExport void SoundSource_SetPlayPosition (Urho3D::SoundSource *_target, signed char * pos) { _target->SetPlayPosition (pos); } DllExport Urho3D::Sound * SoundSource_GetSound (Urho3D::SoundSource *_target) { return _target->GetSound (); } DllExport volatile signed char * SoundSource_GetPlayPosition (Urho3D::SoundSource *_target) { return _target->GetPlayPosition (); } DllExport const char * SoundSource_GetSoundType (Urho3D::SoundSource *_target) { return stringdup((_target->GetSoundType ()).CString ()); } DllExport float SoundSource_GetTimePosition (Urho3D::SoundSource *_target) { return _target->GetTimePosition (); } DllExport float SoundSource_GetFrequency (Urho3D::SoundSource *_target) { return _target->GetFrequency (); } DllExport float SoundSource_GetGain (Urho3D::SoundSource *_target) { return _target->GetGain (); } DllExport float SoundSource_GetAttenuation (Urho3D::SoundSource *_target) { return _target->GetAttenuation (); } DllExport float SoundSource_GetPanning (Urho3D::SoundSource *_target) { return _target->GetPanning (); } DllExport enum Urho3D::AutoRemoveMode SoundSource_GetAutoRemoveMode (Urho3D::SoundSource *_target) { return _target->GetAutoRemoveMode (); } DllExport int SoundSource_IsPlaying (Urho3D::SoundSource *_target) { return _target->IsPlaying (); } DllExport void SoundSource_Update (Urho3D::SoundSource *_target, float timeStep) { _target->Update (timeStep); } DllExport void SoundSource_Mix (Urho3D::SoundSource *_target, int * dest, unsigned int samples, int mixRate, bool stereo, bool interpolation) { _target->Mix (dest, samples, mixRate, stereo, interpolation); } DllExport void SoundSource_UpdateMasterGain (Urho3D::SoundSource *_target) { _target->UpdateMasterGain (); } DllExport void SoundSource_SetPositionAttr (Urho3D::SoundSource *_target, int value) { _target->SetPositionAttr (value); } DllExport Urho3D::ResourceRef SoundSource_GetSoundAttr (Urho3D::SoundSource *_target) { return _target->GetSoundAttr (); } DllExport void SoundSource_SetPlayingAttr (Urho3D::SoundSource *_target, bool value) { _target->SetPlayingAttr (value); } DllExport int SoundSource_GetPositionAttr (Urho3D::SoundSource *_target) { return _target->GetPositionAttr (); } DllExport int SoundSource3D_GetType (Urho3D::SoundSource3D *_target) { return (_target->GetType ()).Value (); } DllExport const char * SoundSource3D_GetTypeName (Urho3D::SoundSource3D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int SoundSource3D_GetTypeStatic () { return (SoundSource3D::GetTypeStatic ()).Value (); } DllExport const char * SoundSource3D_GetTypeNameStatic () { return stringdup((SoundSource3D::GetTypeNameStatic ()).CString ()); } DllExport void * SoundSource3D_SoundSource3D (Urho3D::Context * context) { return WeakPtr<SoundSource3D>(new SoundSource3D(context)); } DllExport void SoundSource3D_RegisterObject (Urho3D::Context * context) { SoundSource3D::RegisterObject (context); } DllExport void SoundSource3D_DrawDebugGeometry (Urho3D::SoundSource3D *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void SoundSource3D_Update (Urho3D::SoundSource3D *_target, float timeStep) { _target->Update (timeStep); } DllExport void SoundSource3D_SetDistanceAttenuation (Urho3D::SoundSource3D *_target, float nearDistance, float farDistance, float rolloffFactor) { _target->SetDistanceAttenuation (nearDistance, farDistance, rolloffFactor); } DllExport void SoundSource3D_SetAngleAttenuation (Urho3D::SoundSource3D *_target, float innerAngle, float outerAngle) { _target->SetAngleAttenuation (innerAngle, outerAngle); } DllExport void SoundSource3D_SetNearDistance (Urho3D::SoundSource3D *_target, float distance) { _target->SetNearDistance (distance); } DllExport void SoundSource3D_SetFarDistance (Urho3D::SoundSource3D *_target, float distance) { _target->SetFarDistance (distance); } DllExport void SoundSource3D_SetInnerAngle (Urho3D::SoundSource3D *_target, float angle) { _target->SetInnerAngle (angle); } DllExport void SoundSource3D_SetOuterAngle (Urho3D::SoundSource3D *_target, float angle) { _target->SetOuterAngle (angle); } DllExport void SoundSource3D_SetRolloffFactor (Urho3D::SoundSource3D *_target, float factor) { _target->SetRolloffFactor (factor); } DllExport void SoundSource3D_CalculateAttenuation (Urho3D::SoundSource3D *_target) { _target->CalculateAttenuation (); } DllExport float SoundSource3D_GetNearDistance (Urho3D::SoundSource3D *_target) { return _target->GetNearDistance (); } DllExport float SoundSource3D_GetFarDistance (Urho3D::SoundSource3D *_target) { return _target->GetFarDistance (); } DllExport float SoundSource3D_GetInnerAngle (Urho3D::SoundSource3D *_target) { return _target->GetInnerAngle (); } DllExport float SoundSource3D_GetOuterAngle (Urho3D::SoundSource3D *_target) { return _target->GetOuterAngle (); } DllExport float SoundSource3D_RollAngleoffFactor (Urho3D::SoundSource3D *_target) { return _target->RollAngleoffFactor (); } DllExport void * EventReceiverGroup_EventReceiverGroup () { return WeakPtr<EventReceiverGroup>(new EventReceiverGroup()); } DllExport void EventReceiverGroup_BeginSendEvent (Urho3D::EventReceiverGroup *_target) { _target->BeginSendEvent (); } DllExport void EventReceiverGroup_EndSendEvent (Urho3D::EventReceiverGroup *_target) { _target->EndSendEvent (); } DllExport void EventReceiverGroup_Add (Urho3D::EventReceiverGroup *_target, Urho3D::Object * object) { _target->Add (object); } DllExport void EventReceiverGroup_Remove (Urho3D::EventReceiverGroup *_target, Urho3D::Object * object) { _target->Remove (object); } DllExport void * Context_Context () { return WeakPtr<Context>(new Context()); } DllExport Urho3D::Object * Context_CreateObject (Urho3D::Context *_target, int objectType) { auto copy = _target->CreateObject (Urho3D::StringHash(objectType)); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport void Context_RegisterFactory (Urho3D::Context *_target, Urho3D::ObjectFactory * factory) { _target->RegisterFactory (factory); } DllExport void Context_RegisterSubsystem (Urho3D::Context *_target, Urho3D::Object * subsystem) { _target->RegisterSubsystem (subsystem); } DllExport void Context_RemoveSubsystem (Urho3D::Context *_target, int objectType) { _target->RemoveSubsystem (Urho3D::StringHash(objectType)); } DllExport void Context_RemoveAllAttributes (Urho3D::Context *_target, int objectType) { _target->RemoveAllAttributes (Urho3D::StringHash(objectType)); } DllExport int Context_RequireSDL (Urho3D::Context *_target, unsigned int sdlFlags) { return _target->RequireSDL (sdlFlags); } DllExport void Context_ReleaseSDL (Urho3D::Context *_target) { _target->ReleaseSDL (); } DllExport void Context_CopyBaseAttributes (Urho3D::Context *_target, int baseType, int derivedType) { _target->CopyBaseAttributes (Urho3D::StringHash(baseType), Urho3D::StringHash(derivedType)); } DllExport Urho3D::Object * Context_GetSubsystem (Urho3D::Context *_target, int type) { return _target->GetSubsystem (Urho3D::StringHash(type)); } // Urho3D::Variant overloads begin: DllExport Interop::Vector3 Context_GetGlobalVar_0 (Urho3D::Context *_target, int key) { return *((Interop::Vector3 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetVector3())); } DllExport Interop::IntRect Context_GetGlobalVar_1 (Urho3D::Context *_target, int key) { return *((Interop::IntRect *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetIntRect())); } DllExport Interop::Color Context_GetGlobalVar_2 (Urho3D::Context *_target, int key) { return *((Interop::Color *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetColor())); } DllExport Interop::Vector2 Context_GetGlobalVar_3 (Urho3D::Context *_target, int key) { return *((Interop::Vector2 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetVector2())); } DllExport Interop::Vector4 Context_GetGlobalVar_4 (Urho3D::Context *_target, int key) { return *((Interop::Vector4 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetVector4())); } DllExport Interop::IntVector2 Context_GetGlobalVar_5 (Urho3D::Context *_target, int key) { return *((Interop::IntVector2 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetIntVector2())); } DllExport Interop::Quaternion Context_GetGlobalVar_6 (Urho3D::Context *_target, int key) { return *((Interop::Quaternion *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetQuaternion())); } DllExport Interop::Matrix4 Context_GetGlobalVar_7 (Urho3D::Context *_target, int key) { return *((Interop::Matrix4 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetMatrix4())); } DllExport Interop::Matrix3x4 Context_GetGlobalVar_8 (Urho3D::Context *_target, int key) { return *((Interop::Matrix3x4 *) &(_target->GetGlobalVar (Urho3D::StringHash(key)).GetMatrix3x4())); } DllExport int Context_GetGlobalVar_9 (Urho3D::Context *_target, int key) { return (_target->GetGlobalVar (Urho3D::StringHash(key)).GetInt()); } DllExport float Context_GetGlobalVar_10 (Urho3D::Context *_target, int key) { return (_target->GetGlobalVar (Urho3D::StringHash(key)).GetFloat()); } DllExport const char * Context_GetGlobalVar_11 (Urho3D::Context *_target, int key) { return stringdup(_target->GetGlobalVar (Urho3D::StringHash(key)).GetString().CString()); } DllExport bool Context_GetGlobalVar_12 (Urho3D::Context *_target, int key) { return (_target->GetGlobalVar (Urho3D::StringHash(key)).GetBool()); } // Urho3D::Variant overloads end. // Urho3D::Variant overloads begin: DllExport void Context_SetGlobalVar_0 (Urho3D::Context *_target, int key, const class Urho3D::Vector3 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_1 (Urho3D::Context *_target, int key, const class Urho3D::IntRect & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_2 (Urho3D::Context *_target, int key, const class Urho3D::Color & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_3 (Urho3D::Context *_target, int key, const class Urho3D::Vector2 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_4 (Urho3D::Context *_target, int key, const class Urho3D::Vector4 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_5 (Urho3D::Context *_target, int key, const class Urho3D::IntVector2 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_6 (Urho3D::Context *_target, int key, const class Urho3D::Quaternion & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_7 (Urho3D::Context *_target, int key, const class Urho3D::Matrix4 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_8 (Urho3D::Context *_target, int key, const class Urho3D::Matrix3x4 & value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_9 (Urho3D::Context *_target, int key, int value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_10 (Urho3D::Context *_target, int key, float value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } DllExport void Context_SetGlobalVar_11 (Urho3D::Context *_target, int key, const char * value) { _target->SetGlobalVar (Urho3D::StringHash(key), Urho3D::String(value)); } DllExport void Context_SetGlobalVar_12 (Urho3D::Context *_target, int key, bool value) { _target->SetGlobalVar (Urho3D::StringHash(key), (value)); } // Urho3D::Variant overloads end. DllExport Urho3D::Object * Context_GetEventSender (Urho3D::Context *_target) { return _target->GetEventSender (); } DllExport Urho3D::EventHandler * Context_GetEventHandler (Urho3D::Context *_target) { return _target->GetEventHandler (); } DllExport const char * Context_GetTypeName (Urho3D::Context *_target, int objectType) { return stringdup((_target->GetTypeName (Urho3D::StringHash(objectType))).CString ()); } DllExport Urho3D::EventReceiverGroup * Context_GetEventReceivers (Urho3D::Context *_target, Urho3D::Object * sender, int eventType) { return _target->GetEventReceivers (sender, Urho3D::StringHash(eventType)); } DllExport Urho3D::EventReceiverGroup * Context_GetEventReceivers0 (Urho3D::Context *_target, int eventType) { return _target->GetEventReceivers (Urho3D::StringHash(eventType)); } DllExport int Profiler_GetType (Urho3D::Profiler *_target) { return (_target->GetType ()).Value (); } DllExport const char * Profiler_GetTypeName (Urho3D::Profiler *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Profiler_GetTypeStatic () { return (Profiler::GetTypeStatic ()).Value (); } DllExport const char * Profiler_GetTypeNameStatic () { return stringdup((Profiler::GetTypeNameStatic ()).CString ()); } DllExport void * Profiler_Profiler (Urho3D::Context * context) { return WeakPtr<Profiler>(new Profiler(context)); } DllExport void Profiler_EndBlock (Urho3D::Profiler *_target) { _target->EndBlock (); } DllExport void Profiler_BeginFrame (Urho3D::Profiler *_target) { _target->BeginFrame (); } DllExport void Profiler_EndFrame (Urho3D::Profiler *_target) { _target->EndFrame (); } DllExport void Profiler_BeginInterval (Urho3D::Profiler *_target) { _target->BeginInterval (); } DllExport const char * Profiler_PrintData (Urho3D::Profiler *_target, bool showUnused, bool showTotal, unsigned int maxDepth) { return stringdup((_target->PrintData (showUnused, showTotal, maxDepth)).CString ()); } DllExport const class Urho3D::ProfilerBlock * Profiler_GetCurrentBlock (Urho3D::Profiler *_target) { return _target->GetCurrentBlock (); } DllExport const class Urho3D::ProfilerBlock * Profiler_GetRootBlock (Urho3D::Profiler *_target) { return _target->GetRootBlock (); } DllExport void * Spline_Spline () { return new Spline(); } DllExport void * Spline_Spline0 (enum Urho3D::InterpolationMode mode) { return new Spline(mode); } DllExport enum Urho3D::InterpolationMode Spline_GetInterpolationMode (Urho3D::Spline *_target) { return _target->GetInterpolationMode (); } DllExport Urho3D::Variant Spline_GetKnot (Urho3D::Spline *_target, unsigned int index) { return _target->GetKnot (index); } DllExport Urho3D::Variant Spline_GetPoint (Urho3D::Spline *_target, float f) { return _target->GetPoint (f); } DllExport void Spline_SetInterpolationMode (Urho3D::Spline *_target, enum Urho3D::InterpolationMode interpolationMode) { _target->SetInterpolationMode (interpolationMode); } // Urho3D::Variant overloads begin: DllExport void Spline_SetKnot_0 (Urho3D::Spline *_target, const class Urho3D::Vector3 & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_1 (Urho3D::Spline *_target, const class Urho3D::IntRect & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_2 (Urho3D::Spline *_target, const class Urho3D::Color & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_3 (Urho3D::Spline *_target, const class Urho3D::Vector2 & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_4 (Urho3D::Spline *_target, const class Urho3D::Vector4 & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_5 (Urho3D::Spline *_target, const class Urho3D::IntVector2 & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_6 (Urho3D::Spline *_target, const class Urho3D::Quaternion & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_7 (Urho3D::Spline *_target, const class Urho3D::Matrix4 & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_8 (Urho3D::Spline *_target, const class Urho3D::Matrix3x4 & knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_9 (Urho3D::Spline *_target, int knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_10 (Urho3D::Spline *_target, float knot, unsigned int index) { _target->SetKnot ((knot), index); } DllExport void Spline_SetKnot_11 (Urho3D::Spline *_target, const char * knot, unsigned int index) { _target->SetKnot (Urho3D::String(knot), index); } DllExport void Spline_SetKnot_12 (Urho3D::Spline *_target, bool knot, unsigned int index) { _target->SetKnot ((knot), index); } // Urho3D::Variant overloads end. // Urho3D::Variant overloads begin: DllExport void Spline_AddKnot_0 (Urho3D::Spline *_target, const class Urho3D::Vector3 & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_1 (Urho3D::Spline *_target, const class Urho3D::IntRect & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_2 (Urho3D::Spline *_target, const class Urho3D::Color & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_3 (Urho3D::Spline *_target, const class Urho3D::Vector2 & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_4 (Urho3D::Spline *_target, const class Urho3D::Vector4 & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_5 (Urho3D::Spline *_target, const class Urho3D::IntVector2 & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_6 (Urho3D::Spline *_target, const class Urho3D::Quaternion & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_7 (Urho3D::Spline *_target, const class Urho3D::Matrix4 & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_8 (Urho3D::Spline *_target, const class Urho3D::Matrix3x4 & knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_9 (Urho3D::Spline *_target, int knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_10 (Urho3D::Spline *_target, float knot) { _target->AddKnot ((knot)); } DllExport void Spline_AddKnot_11 (Urho3D::Spline *_target, const char * knot) { _target->AddKnot (Urho3D::String(knot)); } DllExport void Spline_AddKnot_12 (Urho3D::Spline *_target, bool knot) { _target->AddKnot ((knot)); } // Urho3D::Variant overloads end. // Urho3D::Variant overloads begin: DllExport void Spline_AddKnot1_0 (Urho3D::Spline *_target, const class Urho3D::Vector3 & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_1 (Urho3D::Spline *_target, const class Urho3D::IntRect & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_2 (Urho3D::Spline *_target, const class Urho3D::Color & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_3 (Urho3D::Spline *_target, const class Urho3D::Vector2 & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_4 (Urho3D::Spline *_target, const class Urho3D::Vector4 & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_5 (Urho3D::Spline *_target, const class Urho3D::IntVector2 & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_6 (Urho3D::Spline *_target, const class Urho3D::Quaternion & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_7 (Urho3D::Spline *_target, const class Urho3D::Matrix4 & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_8 (Urho3D::Spline *_target, const class Urho3D::Matrix3x4 & knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_9 (Urho3D::Spline *_target, int knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_10 (Urho3D::Spline *_target, float knot, unsigned int index) { _target->AddKnot ((knot), index); } DllExport void Spline_AddKnot1_11 (Urho3D::Spline *_target, const char * knot, unsigned int index) { _target->AddKnot (Urho3D::String(knot), index); } DllExport void Spline_AddKnot1_12 (Urho3D::Spline *_target, bool knot, unsigned int index) { _target->AddKnot ((knot), index); } // Urho3D::Variant overloads end. DllExport void Spline_RemoveKnot (Urho3D::Spline *_target) { _target->RemoveKnot (); } DllExport void Spline_RemoveKnot2 (Urho3D::Spline *_target, unsigned int index) { _target->RemoveKnot (index); } DllExport void Spline_Clear (Urho3D::Spline *_target) { _target->Clear (); } DllExport void * WorkItem_WorkItem () { return WeakPtr<WorkItem>(new WorkItem()); } DllExport int WorkQueue_GetType (Urho3D::WorkQueue *_target) { return (_target->GetType ()).Value (); } DllExport const char * WorkQueue_GetTypeName (Urho3D::WorkQueue *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int WorkQueue_GetTypeStatic () { return (WorkQueue::GetTypeStatic ()).Value (); } DllExport const char * WorkQueue_GetTypeNameStatic () { return stringdup((WorkQueue::GetTypeNameStatic ()).CString ()); } DllExport void * WorkQueue_WorkQueue (Urho3D::Context * context) { return WeakPtr<WorkQueue>(new WorkQueue(context)); } DllExport void WorkQueue_CreateThreads (Urho3D::WorkQueue *_target, unsigned int numThreads) { _target->CreateThreads (numThreads); } DllExport Urho3D::WorkItem * WorkQueue_GetFreeItem (Urho3D::WorkQueue *_target) { auto copy = _target->GetFreeItem (); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport void WorkQueue_Pause (Urho3D::WorkQueue *_target) { _target->Pause (); } DllExport void WorkQueue_Resume (Urho3D::WorkQueue *_target) { _target->Resume (); } DllExport void WorkQueue_Complete (Urho3D::WorkQueue *_target, unsigned int priority) { _target->Complete (priority); } DllExport void WorkQueue_SetTolerance (Urho3D::WorkQueue *_target, int tolerance) { _target->SetTolerance (tolerance); } DllExport void WorkQueue_SetNonThreadedWorkMs (Urho3D::WorkQueue *_target, int ms) { _target->SetNonThreadedWorkMs (ms); } DllExport unsigned int WorkQueue_GetNumThreads (Urho3D::WorkQueue *_target) { return _target->GetNumThreads (); } DllExport int WorkQueue_IsCompleted (Urho3D::WorkQueue *_target, unsigned int priority) { return _target->IsCompleted (priority); } DllExport int WorkQueue_IsCompleting (Urho3D::WorkQueue *_target) { return _target->IsCompleting (); } DllExport int WorkQueue_GetTolerance (Urho3D::WorkQueue *_target) { return _target->GetTolerance (); } DllExport int WorkQueue_GetNonThreadedWorkMs (Urho3D::WorkQueue *_target) { return _target->GetNonThreadedWorkMs (); } DllExport int Engine_GetType (Urho3D::Engine *_target) { return (_target->GetType ()).Value (); } DllExport const char * Engine_GetTypeName (Urho3D::Engine *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Engine_GetTypeStatic () { return (Engine::GetTypeStatic ()).Value (); } DllExport const char * Engine_GetTypeNameStatic () { return stringdup((Engine::GetTypeNameStatic ()).CString ()); } DllExport void * Engine_Engine (Urho3D::Context * context) { return WeakPtr<Engine>(new Engine(context)); } DllExport int Engine_RunFrame (Urho3D::Engine *_target) { return _target->RunFrame (); } DllExport Urho3D::Console * Engine_CreateConsole (Urho3D::Engine *_target) { return _target->CreateConsole (); } DllExport Urho3D::DebugHud * Engine_CreateDebugHud (Urho3D::Engine *_target) { return _target->CreateDebugHud (); } DllExport void Engine_SetMinFps (Urho3D::Engine *_target, int fps) { _target->SetMinFps (fps); } DllExport void Engine_SetMaxFps (Urho3D::Engine *_target, int fps) { _target->SetMaxFps (fps); } DllExport void Engine_SetMaxInactiveFps (Urho3D::Engine *_target, int fps) { _target->SetMaxInactiveFps (fps); } DllExport void Engine_SetTimeStepSmoothing (Urho3D::Engine *_target, int frames) { _target->SetTimeStepSmoothing (frames); } DllExport void Engine_SetPauseMinimized (Urho3D::Engine *_target, bool enable) { _target->SetPauseMinimized (enable); } DllExport void Engine_SetAutoExit (Urho3D::Engine *_target, bool enable) { _target->SetAutoExit (enable); } DllExport void Engine_SetNextTimeStep (Urho3D::Engine *_target, float seconds) { _target->SetNextTimeStep (seconds); } DllExport void Engine_Exit (Urho3D::Engine *_target) { _target->Exit (); } DllExport void Engine_DumpProfiler (Urho3D::Engine *_target) { _target->DumpProfiler (); } DllExport void Engine_DumpResources (Urho3D::Engine *_target, bool dumpFileName) { _target->DumpResources (dumpFileName); } DllExport void Engine_DumpMemory (Urho3D::Engine *_target) { _target->DumpMemory (); } DllExport float Engine_GetNextTimeStep (Urho3D::Engine *_target) { return _target->GetNextTimeStep (); } DllExport int Engine_GetMinFps (Urho3D::Engine *_target) { return _target->GetMinFps (); } DllExport int Engine_GetMaxFps (Urho3D::Engine *_target) { return _target->GetMaxFps (); } DllExport int Engine_GetMaxInactiveFps (Urho3D::Engine *_target) { return _target->GetMaxInactiveFps (); } DllExport int Engine_GetTimeStepSmoothing (Urho3D::Engine *_target) { return _target->GetTimeStepSmoothing (); } DllExport int Engine_GetPauseMinimized (Urho3D::Engine *_target) { return _target->GetPauseMinimized (); } DllExport int Engine_GetAutoExit (Urho3D::Engine *_target) { return _target->GetAutoExit (); } DllExport int Engine_IsInitialized (Urho3D::Engine *_target) { return _target->IsInitialized (); } DllExport int Engine_IsExiting (Urho3D::Engine *_target) { return _target->IsExiting (); } DllExport int Engine_IsHeadless (Urho3D::Engine *_target) { return _target->IsHeadless (); } DllExport void Engine_Update (Urho3D::Engine *_target) { _target->Update (); } DllExport void Engine_Render (Urho3D::Engine *_target) { _target->Render (); } DllExport int Engine_ApplyFrameLimit (Urho3D::Engine *_target) { return _target->ApplyFrameLimit (); } DllExport int Application_GetType (Urho3D::Application *_target) { return (_target->GetType ()).Value (); } DllExport const char * Application_GetTypeName (Urho3D::Application *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Application_GetTypeStatic () { return (Application::GetTypeStatic ()).Value (); } DllExport const char * Application_GetTypeNameStatic () { return stringdup((Application::GetTypeNameStatic ()).CString ()); } DllExport int Application_Run (Urho3D::Application *_target) { return _target->Run (); } DllExport void Application_ErrorExit (Urho3D::Application *_target, const char * message) { _target->ErrorExit (Urho3D::String(message)); } DllExport int UrhoConsole_GetType (Urho3D::Console *_target) { return (_target->GetType ()).Value (); } DllExport const char * UrhoConsole_GetTypeName (Urho3D::Console *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int UrhoConsole_GetTypeStatic () { return (Console::GetTypeStatic ()).Value (); } DllExport const char * UrhoConsole_GetTypeNameStatic () { return stringdup((Console::GetTypeNameStatic ()).CString ()); } DllExport void * UrhoConsole_Console (Urho3D::Context * context) { return WeakPtr<Console>(new Console(context)); } DllExport void UrhoConsole_SetDefaultStyle (Urho3D::Console *_target, Urho3D::XMLFile * style) { _target->SetDefaultStyle (style); } DllExport void UrhoConsole_SetVisible (Urho3D::Console *_target, bool enable) { _target->SetVisible (enable); } DllExport void UrhoConsole_Toggle (Urho3D::Console *_target) { _target->Toggle (); } DllExport void UrhoConsole_SetAutoVisibleOnError (Urho3D::Console *_target, bool enable) { _target->SetAutoVisibleOnError (enable); } DllExport void UrhoConsole_SetCommandInterpreter (Urho3D::Console *_target, const char * interpreter) { _target->SetCommandInterpreter (Urho3D::String(interpreter)); } DllExport void UrhoConsole_SetNumBufferedRows (Urho3D::Console *_target, unsigned int rows) { _target->SetNumBufferedRows (rows); } DllExport void UrhoConsole_SetNumRows (Urho3D::Console *_target, unsigned int rows) { _target->SetNumRows (rows); } DllExport void UrhoConsole_SetNumHistoryRows (Urho3D::Console *_target, unsigned int rows) { _target->SetNumHistoryRows (rows); } DllExport void UrhoConsole_SetFocusOnShow (Urho3D::Console *_target, bool enable) { _target->SetFocusOnShow (enable); } DllExport void UrhoConsole_AddAutoComplete (Urho3D::Console *_target, const char * option) { _target->AddAutoComplete (Urho3D::String(option)); } DllExport void UrhoConsole_RemoveAutoComplete (Urho3D::Console *_target, const char * option) { _target->RemoveAutoComplete (Urho3D::String(option)); } DllExport void UrhoConsole_UpdateElements (Urho3D::Console *_target) { _target->UpdateElements (); } DllExport Urho3D::XMLFile * UrhoConsole_GetDefaultStyle (Urho3D::Console *_target) { return _target->GetDefaultStyle (); } DllExport Urho3D::BorderImage * UrhoConsole_GetBackground (Urho3D::Console *_target) { return _target->GetBackground (); } DllExport Urho3D::LineEdit * UrhoConsole_GetLineEdit (Urho3D::Console *_target) { return _target->GetLineEdit (); } DllExport Urho3D::Button * UrhoConsole_GetCloseButton (Urho3D::Console *_target) { return _target->GetCloseButton (); } DllExport int UrhoConsole_IsVisible (Urho3D::Console *_target) { return _target->IsVisible (); } DllExport int UrhoConsole_IsAutoVisibleOnError (Urho3D::Console *_target) { return _target->IsAutoVisibleOnError (); } DllExport const char * UrhoConsole_GetCommandInterpreter (Urho3D::Console *_target) { return stringdup((_target->GetCommandInterpreter ()).CString ()); } DllExport unsigned int UrhoConsole_GetNumBufferedRows (Urho3D::Console *_target) { return _target->GetNumBufferedRows (); } DllExport unsigned int UrhoConsole_GetNumRows (Urho3D::Console *_target) { return _target->GetNumRows (); } DllExport void UrhoConsole_CopySelectedRows (Urho3D::Console *_target) { _target->CopySelectedRows (); } DllExport unsigned int UrhoConsole_GetNumHistoryRows (Urho3D::Console *_target) { return _target->GetNumHistoryRows (); } DllExport unsigned int UrhoConsole_GetHistoryPosition (Urho3D::Console *_target) { return _target->GetHistoryPosition (); } DllExport const char * UrhoConsole_GetHistoryRow (Urho3D::Console *_target, unsigned int index) { return stringdup((_target->GetHistoryRow (index)).CString ()); } DllExport int UrhoConsole_GetFocusOnShow (Urho3D::Console *_target) { return _target->GetFocusOnShow (); } DllExport int DebugHud_GetType (Urho3D::DebugHud *_target) { return (_target->GetType ()).Value (); } DllExport const char * DebugHud_GetTypeName (Urho3D::DebugHud *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int DebugHud_GetTypeStatic () { return (DebugHud::GetTypeStatic ()).Value (); } DllExport const char * DebugHud_GetTypeNameStatic () { return stringdup((DebugHud::GetTypeNameStatic ()).CString ()); } DllExport void * DebugHud_DebugHud (Urho3D::Context * context) { return WeakPtr<DebugHud>(new DebugHud(context)); } DllExport void DebugHud_Update (Urho3D::DebugHud *_target) { _target->Update (); } DllExport void DebugHud_SetDefaultStyle (Urho3D::DebugHud *_target, Urho3D::XMLFile * style) { _target->SetDefaultStyle (style); } DllExport void DebugHud_SetMode (Urho3D::DebugHud *_target, unsigned int mode) { _target->SetMode (mode); } DllExport void DebugHud_SetProfilerMaxDepth (Urho3D::DebugHud *_target, unsigned int depth) { _target->SetProfilerMaxDepth (depth); } DllExport void DebugHud_SetProfilerInterval (Urho3D::DebugHud *_target, float interval) { _target->SetProfilerInterval (interval); } DllExport void DebugHud_SetUseRendererStats (Urho3D::DebugHud *_target, bool enable) { _target->SetUseRendererStats (enable); } DllExport void DebugHud_Toggle (Urho3D::DebugHud *_target, unsigned int mode) { _target->Toggle (mode); } DllExport void DebugHud_ToggleAll (Urho3D::DebugHud *_target) { _target->ToggleAll (); } DllExport Urho3D::XMLFile * DebugHud_GetDefaultStyle (Urho3D::DebugHud *_target) { return _target->GetDefaultStyle (); } DllExport Urho3D::Text * DebugHud_GetStatsText (Urho3D::DebugHud *_target) { return _target->GetStatsText (); } DllExport Urho3D::Text * DebugHud_GetModeText (Urho3D::DebugHud *_target) { return _target->GetModeText (); } DllExport Urho3D::Text * DebugHud_GetProfilerText (Urho3D::DebugHud *_target) { return _target->GetProfilerText (); } DllExport Urho3D::Text * DebugHud_GetMemoryText (Urho3D::DebugHud *_target) { return _target->GetMemoryText (); } DllExport unsigned int DebugHud_GetMode (Urho3D::DebugHud *_target) { return _target->GetMode (); } DllExport unsigned int DebugHud_GetProfilerMaxDepth (Urho3D::DebugHud *_target) { return _target->GetProfilerMaxDepth (); } DllExport float DebugHud_GetProfilerInterval (Urho3D::DebugHud *_target) { return _target->GetProfilerInterval (); } DllExport int DebugHud_GetUseRendererStats (Urho3D::DebugHud *_target) { return _target->GetUseRendererStats (); } DllExport void DebugHud_SetAppStats (Urho3D::DebugHud *_target, const char * label, const char * stats) { _target->SetAppStats (Urho3D::String(label), Urho3D::String(stats)); } DllExport int DebugHud_ResetAppStats (Urho3D::DebugHud *_target, const char * label) { return _target->ResetAppStats (Urho3D::String(label)); } DllExport void DebugHud_ClearAppStats (Urho3D::DebugHud *_target) { _target->ClearAppStats (); } DllExport int Node_GetType (Urho3D::Node *_target) { return (_target->GetType ()).Value (); } DllExport const char * Node_GetTypeName (Urho3D::Node *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Node_GetTypeStatic () { return (Node::GetTypeStatic ()).Value (); } DllExport const char * Node_GetTypeNameStatic () { return stringdup((Node::GetTypeNameStatic ()).CString ()); } DllExport void * Node_Node (Urho3D::Context * context) { return WeakPtr<Node>(new Node(context)); } DllExport void Node_RegisterObject (Urho3D::Context * context) { Node::RegisterObject (context); } DllExport int Node_Load_File (Urho3D::Node *_target, File * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int Node_Load_MemoryBuffer (Urho3D::Node *_target, MemoryBuffer * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int Node_LoadXML (Urho3D::Node *_target, const class Urho3D::XMLElement & source, bool setInstanceDefault) { return _target->LoadXML (source, setInstanceDefault); } DllExport int Node_Save_File (Urho3D::Node *_target, File * dest) { return _target->Save (*dest); } DllExport int Node_Save_MemoryBuffer (Urho3D::Node *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int Node_SaveXML (Urho3D::Node *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void Node_ApplyAttributes (Urho3D::Node *_target) { _target->ApplyAttributes (); } DllExport int Node_SaveDefaultAttributes (Urho3D::Node *_target) { return _target->SaveDefaultAttributes (); } DllExport void Node_MarkNetworkUpdate (Urho3D::Node *_target) { _target->MarkNetworkUpdate (); } DllExport void Node_AddReplicationState (Urho3D::Node *_target, Urho3D::NodeReplicationState * state) { _target->AddReplicationState (state); } DllExport int Node_SaveXML0_File (Urho3D::Node *_target, File * dest, const char * indentation) { return _target->SaveXML (*dest, Urho3D::String(indentation)); } DllExport int Node_SaveXML0_MemoryBuffer (Urho3D::Node *_target, MemoryBuffer * dest, const char * indentation) { return _target->SaveXML (*dest, Urho3D::String(indentation)); } DllExport int Node_SaveJSON_File (Urho3D::Node *_target, File * dest, const char * indentation) { return _target->SaveJSON (*dest, Urho3D::String(indentation)); } DllExport int Node_SaveJSON_MemoryBuffer (Urho3D::Node *_target, MemoryBuffer * dest, const char * indentation) { return _target->SaveJSON (*dest, Urho3D::String(indentation)); } DllExport void Node_SetName (Urho3D::Node *_target, const char * name) { _target->SetName (Urho3D::String(name)); } DllExport void Node_AddTag (Urho3D::Node *_target, const char * tag) { _target->AddTag (Urho3D::String(tag)); } DllExport int Node_RemoveTag (Urho3D::Node *_target, const char * tag) { return _target->RemoveTag (Urho3D::String(tag)); } DllExport void Node_RemoveAllTags (Urho3D::Node *_target) { _target->RemoveAllTags (); } DllExport void Node_SetPosition (Urho3D::Node *_target, const class Urho3D::Vector3 & position) { _target->SetPosition (position); } DllExport void Node_SetPosition2D (Urho3D::Node *_target, const class Urho3D::Vector2 & position) { _target->SetPosition2D (position); } DllExport void Node_SetPosition2D1 (Urho3D::Node *_target, float x, float y) { _target->SetPosition2D (x, y); } DllExport void Node_SetRotation (Urho3D::Node *_target, const class Urho3D::Quaternion & rotation) { _target->SetRotation (rotation); } DllExport void Node_SetRotation2D (Urho3D::Node *_target, float rotation) { _target->SetRotation2D (rotation); } DllExport void Node_SetDirection (Urho3D::Node *_target, const class Urho3D::Vector3 & direction) { _target->SetDirection (direction); } DllExport void Node_SetScale (Urho3D::Node *_target, float scale) { _target->SetScale (scale); } DllExport void Node_SetScale2 (Urho3D::Node *_target, const class Urho3D::Vector3 & scale) { _target->SetScale (scale); } DllExport void Node_SetScale2D (Urho3D::Node *_target, const class Urho3D::Vector2 & scale) { _target->SetScale2D (scale); } DllExport void Node_SetScale2D3 (Urho3D::Node *_target, float x, float y) { _target->SetScale2D (x, y); } DllExport void Node_SetTransform (Urho3D::Node *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetTransform (position, rotation); } DllExport void Node_SetTransform4 (Urho3D::Node *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, float scale) { _target->SetTransform (position, rotation, scale); } DllExport void Node_SetTransform5 (Urho3D::Node *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, const class Urho3D::Vector3 & scale) { _target->SetTransform (position, rotation, scale); } DllExport void Node_SetTransform6 (Urho3D::Node *_target, const class Urho3D::Matrix3x4 & matrix) { _target->SetTransform (matrix); } DllExport void Node_SetTransform2D (Urho3D::Node *_target, const class Urho3D::Vector2 & position, float rotation) { _target->SetTransform2D (position, rotation); } DllExport void Node_SetTransform2D7 (Urho3D::Node *_target, const class Urho3D::Vector2 & position, float rotation, float scale) { _target->SetTransform2D (position, rotation, scale); } DllExport void Node_SetTransform2D8 (Urho3D::Node *_target, const class Urho3D::Vector2 & position, float rotation, const class Urho3D::Vector2 & scale) { _target->SetTransform2D (position, rotation, scale); } DllExport void Node_SetWorldPosition (Urho3D::Node *_target, const class Urho3D::Vector3 & position) { _target->SetWorldPosition (position); } DllExport void Node_SetWorldPosition2D (Urho3D::Node *_target, const class Urho3D::Vector2 & position) { _target->SetWorldPosition2D (position); } DllExport void Node_SetWorldPosition2D9 (Urho3D::Node *_target, float x, float y) { _target->SetWorldPosition2D (x, y); } DllExport void Node_SetWorldRotation (Urho3D::Node *_target, const class Urho3D::Quaternion & rotation) { _target->SetWorldRotation (rotation); } DllExport void Node_SetWorldRotation2D (Urho3D::Node *_target, float rotation) { _target->SetWorldRotation2D (rotation); } DllExport void Node_SetWorldDirection (Urho3D::Node *_target, const class Urho3D::Vector3 & direction) { _target->SetWorldDirection (direction); } DllExport void Node_SetWorldScale (Urho3D::Node *_target, float scale) { _target->SetWorldScale (scale); } DllExport void Node_SetWorldScale10 (Urho3D::Node *_target, const class Urho3D::Vector3 & scale) { _target->SetWorldScale (scale); } DllExport void Node_SetWorldScale2D (Urho3D::Node *_target, const class Urho3D::Vector2 & scale) { _target->SetWorldScale2D (scale); } DllExport void Node_SetWorldScale2D11 (Urho3D::Node *_target, float x, float y) { _target->SetWorldScale2D (x, y); } DllExport void Node_SetWorldTransform (Urho3D::Node *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetWorldTransform (position, rotation); } DllExport void Node_SetWorldTransform12 (Urho3D::Node *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, float scale) { _target->SetWorldTransform (position, rotation, scale); } DllExport void Node_SetWorldTransform13 (Urho3D::Node *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, const class Urho3D::Vector3 & scale) { _target->SetWorldTransform (position, rotation, scale); } DllExport void Node_SetWorldTransform2D (Urho3D::Node *_target, const class Urho3D::Vector2 & position, float rotation) { _target->SetWorldTransform2D (position, rotation); } DllExport void Node_SetWorldTransform2D14 (Urho3D::Node *_target, const class Urho3D::Vector2 & position, float rotation, float scale) { _target->SetWorldTransform2D (position, rotation, scale); } DllExport void Node_SetWorldTransform2D15 (Urho3D::Node *_target, const class Urho3D::Vector2 & position, float rotation, const class Urho3D::Vector2 & scale) { _target->SetWorldTransform2D (position, rotation, scale); } DllExport void Node_Translate (Urho3D::Node *_target, const class Urho3D::Vector3 & delta, enum Urho3D::TransformSpace space) { _target->Translate (delta, space); } DllExport void Node_Translate2D (Urho3D::Node *_target, const class Urho3D::Vector2 & delta, enum Urho3D::TransformSpace space) { _target->Translate2D (delta, space); } DllExport void Node_Rotate (Urho3D::Node *_target, const class Urho3D::Quaternion & delta, enum Urho3D::TransformSpace space) { _target->Rotate (delta, space); } DllExport void Node_Rotate2D (Urho3D::Node *_target, float delta, enum Urho3D::TransformSpace space) { _target->Rotate2D (delta, space); } DllExport void Node_RotateAround (Urho3D::Node *_target, const class Urho3D::Vector3 & point, const class Urho3D::Quaternion & delta, enum Urho3D::TransformSpace space) { _target->RotateAround (point, delta, space); } DllExport void Node_RotateAround2D (Urho3D::Node *_target, const class Urho3D::Vector2 & point, float delta, enum Urho3D::TransformSpace space) { _target->RotateAround2D (point, delta, space); } DllExport void Node_Pitch (Urho3D::Node *_target, float angle, enum Urho3D::TransformSpace space) { _target->Pitch (angle, space); } DllExport void Node_Yaw (Urho3D::Node *_target, float angle, enum Urho3D::TransformSpace space) { _target->Yaw (angle, space); } DllExport void Node_Roll (Urho3D::Node *_target, float angle, enum Urho3D::TransformSpace space) { _target->Roll (angle, space); } DllExport int Node_LookAt (Urho3D::Node *_target, const class Urho3D::Vector3 & target, const class Urho3D::Vector3 & up, enum Urho3D::TransformSpace space) { return _target->LookAt (target, up, space); } DllExport void Node_Scale (Urho3D::Node *_target, float scale) { _target->Scale (scale); } DllExport void Node_Scale16 (Urho3D::Node *_target, const class Urho3D::Vector3 & scale) { _target->Scale (scale); } DllExport void Node_Scale2D (Urho3D::Node *_target, const class Urho3D::Vector2 & scale) { _target->Scale2D (scale); } DllExport void Node_SetEnabled (Urho3D::Node *_target, bool enable) { _target->SetEnabled (enable); } DllExport void Node_SetDeepEnabled (Urho3D::Node *_target, bool enable) { _target->SetDeepEnabled (enable); } DllExport void Node_ResetDeepEnabled (Urho3D::Node *_target) { _target->ResetDeepEnabled (); } DllExport void Node_SetEnabledRecursive (Urho3D::Node *_target, bool enable) { _target->SetEnabledRecursive (enable); } DllExport void Node_SetOwner (Urho3D::Node *_target, Urho3D::Connection * owner) { _target->SetOwner (owner); } DllExport void Node_MarkDirty (Urho3D::Node *_target) { _target->MarkDirty (); } DllExport Urho3D::Node * Node_CreateChild (Urho3D::Node *_target, const char * name, enum Urho3D::CreateMode mode, unsigned int id, bool temporary) { return _target->CreateChild (Urho3D::String(name), mode, id, temporary); } DllExport Urho3D::Node * Node_CreateTemporaryChild (Urho3D::Node *_target, const char * name, enum Urho3D::CreateMode mode, unsigned int id) { return _target->CreateTemporaryChild (Urho3D::String(name), mode, id); } DllExport void Node_AddChild (Urho3D::Node *_target, Urho3D::Node * node, unsigned int index) { _target->AddChild (node, index); } DllExport void Node_RemoveChild (Urho3D::Node *_target, Urho3D::Node * node) { _target->RemoveChild (node); } DllExport void Node_RemoveAllChildren (Urho3D::Node *_target) { _target->RemoveAllChildren (); } DllExport void Node_RemoveChildren (Urho3D::Node *_target, bool removeReplicated, bool removeLocal, bool recursive) { _target->RemoveChildren (removeReplicated, removeLocal, recursive); } DllExport Urho3D::Component * Node_CreateComponent (Urho3D::Node *_target, int type, enum Urho3D::CreateMode mode, unsigned int id) { return _target->CreateComponent (Urho3D::StringHash(type), mode, id); } DllExport Urho3D::Component * Node_GetOrCreateComponent (Urho3D::Node *_target, int type, enum Urho3D::CreateMode mode, unsigned int id) { return _target->GetOrCreateComponent (Urho3D::StringHash(type), mode, id); } DllExport Urho3D::Component * Node_CloneComponent (Urho3D::Node *_target, Urho3D::Component * component, unsigned int id) { return _target->CloneComponent (component, id); } DllExport Urho3D::Component * Node_CloneComponent17 (Urho3D::Node *_target, Urho3D::Component * component, enum Urho3D::CreateMode mode, unsigned int id) { return _target->CloneComponent (component, mode, id); } DllExport void Node_RemoveComponent (Urho3D::Node *_target, Urho3D::Component * component) { _target->RemoveComponent (component); } DllExport void Node_RemoveComponent18 (Urho3D::Node *_target, int type) { _target->RemoveComponent (Urho3D::StringHash(type)); } DllExport void Node_RemoveComponents (Urho3D::Node *_target, bool removeReplicated, bool removeLocal) { _target->RemoveComponents (removeReplicated, removeLocal); } DllExport void Node_RemoveComponents19 (Urho3D::Node *_target, int type) { _target->RemoveComponents (Urho3D::StringHash(type)); } DllExport void Node_RemoveAllComponents (Urho3D::Node *_target) { _target->RemoveAllComponents (); } DllExport void Node_ReorderComponent (Urho3D::Node *_target, Urho3D::Component * component, unsigned int index) { _target->ReorderComponent (component, index); } DllExport Urho3D::Node * Node_Clone (Urho3D::Node *_target, enum Urho3D::CreateMode mode) { return _target->Clone (mode); } DllExport void Node_Remove (Urho3D::Node *_target) { _target->Remove (); } DllExport void Node_SetParent (Urho3D::Node *_target, Urho3D::Node * parent) { _target->SetParent (parent); } // Urho3D::Variant overloads begin: DllExport void Node_SetVar_0 (Urho3D::Node *_target, int key, const class Urho3D::Vector3 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_1 (Urho3D::Node *_target, int key, const class Urho3D::IntRect & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_2 (Urho3D::Node *_target, int key, const class Urho3D::Color & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_3 (Urho3D::Node *_target, int key, const class Urho3D::Vector2 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_4 (Urho3D::Node *_target, int key, const class Urho3D::Vector4 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_5 (Urho3D::Node *_target, int key, const class Urho3D::IntVector2 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_6 (Urho3D::Node *_target, int key, const class Urho3D::Quaternion & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_7 (Urho3D::Node *_target, int key, const class Urho3D::Matrix4 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_8 (Urho3D::Node *_target, int key, const class Urho3D::Matrix3x4 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_9 (Urho3D::Node *_target, int key, int value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_10 (Urho3D::Node *_target, int key, float value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void Node_SetVar_11 (Urho3D::Node *_target, int key, const char * value) { _target->SetVar (Urho3D::StringHash(key), Urho3D::String(value)); } DllExport void Node_SetVar_12 (Urho3D::Node *_target, int key, bool value) { _target->SetVar (Urho3D::StringHash(key), (value)); } // Urho3D::Variant overloads end. DllExport void Node_AddListener (Urho3D::Node *_target, Urho3D::Component * component) { _target->AddListener (component); } DllExport void Node_RemoveListener (Urho3D::Node *_target, Urho3D::Component * component) { _target->RemoveListener (component); } DllExport unsigned int Node_GetID (Urho3D::Node *_target) { return _target->GetID (); } DllExport const char * Node_GetName (Urho3D::Node *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport int Node_GetNameHash (Urho3D::Node *_target) { return (_target->GetNameHash ()).Value (); } DllExport int Node_HasTag (Urho3D::Node *_target, const char * tag) { return _target->HasTag (Urho3D::String(tag)); } DllExport Urho3D::Node * Node_GetParent (Urho3D::Node *_target) { return _target->GetParent (); } DllExport Urho3D::Scene * Node_GetScene (Urho3D::Node *_target) { return _target->GetScene (); } DllExport int Node_IsChildOf (Urho3D::Node *_target, Urho3D::Node * node) { return _target->IsChildOf (node); } DllExport int Node_IsEnabled (Urho3D::Node *_target) { return _target->IsEnabled (); } DllExport int Node_IsEnabledSelf (Urho3D::Node *_target) { return _target->IsEnabledSelf (); } DllExport Urho3D::Connection * Node_GetOwner (Urho3D::Node *_target) { return _target->GetOwner (); } DllExport Interop::Vector3 Node_GetPosition (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetPosition ())); } DllExport Interop::Vector2 Node_GetPosition2D (Urho3D::Node *_target) { return *((Interop::Vector2 *) &(_target->GetPosition2D ())); } DllExport Interop::Quaternion Node_GetRotation (Urho3D::Node *_target) { return *((Interop::Quaternion *) &(_target->GetRotation ())); } DllExport float Node_GetRotation2D (Urho3D::Node *_target) { return _target->GetRotation2D (); } DllExport Interop::Vector3 Node_GetDirection (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetDirection ())); } DllExport Interop::Vector3 Node_GetUp (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetUp ())); } DllExport Interop::Vector3 Node_GetRight (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetRight ())); } DllExport Interop::Vector3 Node_GetScale (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetScale ())); } DllExport Interop::Vector2 Node_GetScale2D (Urho3D::Node *_target) { return *((Interop::Vector2 *) &(_target->GetScale2D ())); } DllExport Interop::Matrix3x4 Node_GetTransform (Urho3D::Node *_target) { return *((Interop::Matrix3x4 *) &(_target->GetTransform ())); } DllExport Interop::Vector3 Node_GetWorldPosition (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetWorldPosition ())); } DllExport Interop::Vector2 Node_GetWorldPosition2D (Urho3D::Node *_target) { return *((Interop::Vector2 *) &(_target->GetWorldPosition2D ())); } DllExport Interop::Quaternion Node_GetWorldRotation (Urho3D::Node *_target) { return *((Interop::Quaternion *) &(_target->GetWorldRotation ())); } DllExport float Node_GetWorldRotation2D (Urho3D::Node *_target) { return _target->GetWorldRotation2D (); } DllExport Interop::Vector3 Node_GetWorldDirection (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetWorldDirection ())); } DllExport Interop::Vector3 Node_GetWorldUp (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetWorldUp ())); } DllExport Interop::Vector3 Node_GetWorldRight (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetWorldRight ())); } DllExport Interop::Vector3 Node_GetWorldScale (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetWorldScale ())); } DllExport Interop::Vector3 Node_GetSignedWorldScale (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetSignedWorldScale ())); } DllExport Interop::Vector2 Node_GetWorldScale2D (Urho3D::Node *_target) { return *((Interop::Vector2 *) &(_target->GetWorldScale2D ())); } DllExport Interop::Matrix3x4 Node_GetWorldTransform (Urho3D::Node *_target) { return *((Interop::Matrix3x4 *) &(_target->GetWorldTransform ())); } DllExport Interop::Vector3 Node_LocalToWorld (Urho3D::Node *_target, const class Urho3D::Vector3 & position) { return *((Interop::Vector3 *) &(_target->LocalToWorld (position))); } DllExport Interop::Vector3 Node_LocalToWorld20 (Urho3D::Node *_target, const class Urho3D::Vector4 & vector) { return *((Interop::Vector3 *) &(_target->LocalToWorld (vector))); } DllExport Interop::Vector2 Node_LocalToWorld2D (Urho3D::Node *_target, const class Urho3D::Vector2 & vector) { return *((Interop::Vector2 *) &(_target->LocalToWorld2D (vector))); } DllExport Interop::Vector3 Node_WorldToLocal (Urho3D::Node *_target, const class Urho3D::Vector3 & position) { return *((Interop::Vector3 *) &(_target->WorldToLocal (position))); } DllExport Interop::Vector3 Node_WorldToLocal21 (Urho3D::Node *_target, const class Urho3D::Vector4 & vector) { return *((Interop::Vector3 *) &(_target->WorldToLocal (vector))); } DllExport Interop::Vector2 Node_WorldToLocal2D (Urho3D::Node *_target, const class Urho3D::Vector2 & vector) { return *((Interop::Vector2 *) &(_target->WorldToLocal2D (vector))); } DllExport int Node_IsDirty (Urho3D::Node *_target) { return _target->IsDirty (); } DllExport unsigned int Node_GetNumChildren (Urho3D::Node *_target, bool recursive) { return _target->GetNumChildren (recursive); } DllExport const Vector<SharedPtr<class Urho3D::Node> > & Node_GetChildren (Urho3D::Node *_target) { return _target->GetChildren (); } DllExport Urho3D::Node * Node_GetChild (Urho3D::Node *_target, unsigned int index) { return _target->GetChild (index); } DllExport Urho3D::Node * Node_GetChild22 (Urho3D::Node *_target, const char * name, bool recursive) { return _target->GetChild (Urho3D::String(name), recursive); } DllExport Urho3D::Node * Node_GetChild23 (Urho3D::Node *_target, int nameHash, bool recursive) { return _target->GetChild (Urho3D::StringHash(nameHash), recursive); } DllExport unsigned int Node_GetNumComponents (Urho3D::Node *_target) { return _target->GetNumComponents (); } DllExport unsigned int Node_GetNumNetworkComponents (Urho3D::Node *_target) { return _target->GetNumNetworkComponents (); } DllExport const Vector<SharedPtr<class Urho3D::Component> > & Node_GetComponents (Urho3D::Node *_target) { return _target->GetComponents (); } DllExport Urho3D::Component * Node_GetComponent (Urho3D::Node *_target, int type, bool recursive) { return _target->GetComponent (Urho3D::StringHash(type), recursive); } DllExport Urho3D::Component * Node_GetParentComponent (Urho3D::Node *_target, int type, bool fullTraversal) { return _target->GetParentComponent (Urho3D::StringHash(type), fullTraversal); } DllExport int Node_HasComponent (Urho3D::Node *_target, int type) { return _target->HasComponent (Urho3D::StringHash(type)); } // Urho3D::Variant overloads begin: DllExport Interop::Vector3 Node_GetVar_0 (Urho3D::Node *_target, int key) { return *((Interop::Vector3 *) &(_target->GetVar (Urho3D::StringHash(key)).GetVector3())); } DllExport Interop::IntRect Node_GetVar_1 (Urho3D::Node *_target, int key) { return *((Interop::IntRect *) &(_target->GetVar (Urho3D::StringHash(key)).GetIntRect())); } DllExport Interop::Color Node_GetVar_2 (Urho3D::Node *_target, int key) { return *((Interop::Color *) &(_target->GetVar (Urho3D::StringHash(key)).GetColor())); } DllExport Interop::Vector2 Node_GetVar_3 (Urho3D::Node *_target, int key) { return *((Interop::Vector2 *) &(_target->GetVar (Urho3D::StringHash(key)).GetVector2())); } DllExport Interop::Vector4 Node_GetVar_4 (Urho3D::Node *_target, int key) { return *((Interop::Vector4 *) &(_target->GetVar (Urho3D::StringHash(key)).GetVector4())); } DllExport Interop::IntVector2 Node_GetVar_5 (Urho3D::Node *_target, int key) { return *((Interop::IntVector2 *) &(_target->GetVar (Urho3D::StringHash(key)).GetIntVector2())); } DllExport Interop::Quaternion Node_GetVar_6 (Urho3D::Node *_target, int key) { return *((Interop::Quaternion *) &(_target->GetVar (Urho3D::StringHash(key)).GetQuaternion())); } DllExport Interop::Matrix4 Node_GetVar_7 (Urho3D::Node *_target, int key) { return *((Interop::Matrix4 *) &(_target->GetVar (Urho3D::StringHash(key)).GetMatrix4())); } DllExport Interop::Matrix3x4 Node_GetVar_8 (Urho3D::Node *_target, int key) { return *((Interop::Matrix3x4 *) &(_target->GetVar (Urho3D::StringHash(key)).GetMatrix3x4())); } DllExport int Node_GetVar_9 (Urho3D::Node *_target, int key) { return (_target->GetVar (Urho3D::StringHash(key)).GetInt()); } DllExport float Node_GetVar_10 (Urho3D::Node *_target, int key) { return (_target->GetVar (Urho3D::StringHash(key)).GetFloat()); } DllExport const char * Node_GetVar_11 (Urho3D::Node *_target, int key) { return stringdup(_target->GetVar (Urho3D::StringHash(key)).GetString().CString()); } DllExport bool Node_GetVar_12 (Urho3D::Node *_target, int key) { return (_target->GetVar (Urho3D::StringHash(key)).GetBool()); } // Urho3D::Variant overloads end. DllExport void Node_SetID (Urho3D::Node *_target, unsigned int id) { _target->SetID (id); } DllExport void Node_SetScene (Urho3D::Node *_target, Urho3D::Scene * scene) { _target->SetScene (scene); } DllExport void Node_ResetScene (Urho3D::Node *_target) { _target->ResetScene (); } DllExport void Node_SetNetPositionAttr (Urho3D::Node *_target, const class Urho3D::Vector3 & value) { _target->SetNetPositionAttr (value); } DllExport Interop::Vector3 Node_GetNetPositionAttr (Urho3D::Node *_target) { return *((Interop::Vector3 *) &(_target->GetNetPositionAttr ())); } DllExport void Node_PrepareNetworkUpdate (Urho3D::Node *_target) { _target->PrepareNetworkUpdate (); } DllExport void Node_CleanupConnection (Urho3D::Node *_target, Urho3D::Connection * connection) { _target->CleanupConnection (connection); } DllExport void Node_MarkReplicationDirty (Urho3D::Node *_target) { _target->MarkReplicationDirty (); } DllExport Urho3D::Node * Node_CreateChild24 (Urho3D::Node *_target, unsigned int id, enum Urho3D::CreateMode mode, bool temporary) { return _target->CreateChild (id, mode, temporary); } DllExport void Node_AddComponent (Urho3D::Node *_target, Urho3D::Component * component, unsigned int id, enum Urho3D::CreateMode mode) { _target->AddComponent (component, id, mode); } DllExport unsigned int Node_GetNumPersistentChildren (Urho3D::Node *_target) { return _target->GetNumPersistentChildren (); } DllExport unsigned int Node_GetNumPersistentComponents (Urho3D::Node *_target) { return _target->GetNumPersistentComponents (); } DllExport void Node_SetPositionSilent (Urho3D::Node *_target, const class Urho3D::Vector3 & position) { _target->SetPositionSilent (position); } DllExport void Node_SetRotationSilent (Urho3D::Node *_target, const class Urho3D::Quaternion & rotation) { _target->SetRotationSilent (rotation); } DllExport void Node_SetScaleSilent (Urho3D::Node *_target, const class Urho3D::Vector3 & scale) { _target->SetScaleSilent (scale); } DllExport void Node_SetTransformSilent (Urho3D::Node *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, const class Urho3D::Vector3 & scale) { _target->SetTransformSilent (position, rotation, scale); } DllExport int Skeleton_Load_File (Urho3D::Skeleton *_target, File * source) { return _target->Load (*source); } DllExport int Skeleton_Load_MemoryBuffer (Urho3D::Skeleton *_target, MemoryBuffer * source) { return _target->Load (*source); } DllExport int Skeleton_Save_File (Urho3D::Skeleton *_target, File * dest) { return _target->Save (*dest); } DllExport int Skeleton_Save_MemoryBuffer (Urho3D::Skeleton *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport void Skeleton_SetRootBoneIndex (Urho3D::Skeleton *_target, unsigned int index) { _target->SetRootBoneIndex (index); } DllExport void Skeleton_ClearBones (Urho3D::Skeleton *_target) { _target->ClearBones (); } DllExport void Skeleton_Reset (Urho3D::Skeleton *_target) { _target->Reset (); } DllExport unsigned int Skeleton_GetNumBones (Urho3D::Skeleton *_target) { return _target->GetNumBones (); } DllExport Urho3D::Bone * Skeleton_GetRootBone (Urho3D::Skeleton *_target) { return _target->GetRootBone (); } DllExport Urho3D::Bone * Skeleton_GetBone (Urho3D::Skeleton *_target, unsigned int index) { return _target->GetBone (index); } DllExport Urho3D::Bone * Skeleton_GetBone0 (Urho3D::Skeleton *_target, int boneNameHash) { return _target->GetBone (Urho3D::StringHash(boneNameHash)); } DllExport void Skeleton_ResetSilent (Urho3D::Skeleton *_target) { _target->ResetSilent (); } DllExport int Model_GetType (Urho3D::Model *_target) { return (_target->GetType ()).Value (); } DllExport const char * Model_GetTypeName (Urho3D::Model *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Model_GetTypeStatic () { return (Model::GetTypeStatic ()).Value (); } DllExport const char * Model_GetTypeNameStatic () { return stringdup((Model::GetTypeNameStatic ()).CString ()); } DllExport void * Model_Model (Urho3D::Context * context) { return WeakPtr<Model>(new Model(context)); } DllExport void Model_RegisterObject (Urho3D::Context * context) { Model::RegisterObject (context); } DllExport int Model_BeginLoad_File (Urho3D::Model *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Model_BeginLoad_MemoryBuffer (Urho3D::Model *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Model_EndLoad (Urho3D::Model *_target) { return _target->EndLoad (); } DllExport int Model_Save_File (Urho3D::Model *_target, File * dest) { return _target->Save (*dest); } DllExport int Model_Save_MemoryBuffer (Urho3D::Model *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport void Model_SetBoundingBox (Urho3D::Model *_target, const class Urho3D::BoundingBox & box) { _target->SetBoundingBox (box); } DllExport void Model_SetNumGeometries (Urho3D::Model *_target, unsigned int num) { _target->SetNumGeometries (num); } DllExport int Model_SetNumGeometryLodLevels (Urho3D::Model *_target, unsigned int index, unsigned int num) { return _target->SetNumGeometryLodLevels (index, num); } DllExport int Model_SetGeometry (Urho3D::Model *_target, unsigned int index, unsigned int lodLevel, Urho3D::Geometry * geometry) { return _target->SetGeometry (index, lodLevel, geometry); } DllExport int Model_SetGeometryCenter (Urho3D::Model *_target, unsigned int index, const class Urho3D::Vector3 & center) { return _target->SetGeometryCenter (index, center); } DllExport Urho3D::Model * Model_Clone (Urho3D::Model *_target, const char * cloneName) { auto copy = _target->Clone (Urho3D::String(cloneName)); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Interop::BoundingBox Model_GetBoundingBox (Urho3D::Model *_target) { return *((Interop::BoundingBox *) &(_target->GetBoundingBox ())); } DllExport const Vector<SharedPtr<class Urho3D::VertexBuffer> > & Model_GetVertexBuffers (Urho3D::Model *_target) { return _target->GetVertexBuffers (); } DllExport const Vector<SharedPtr<class Urho3D::IndexBuffer> > & Model_GetIndexBuffers (Urho3D::Model *_target) { return _target->GetIndexBuffers (); } DllExport unsigned int Model_GetNumGeometries (Urho3D::Model *_target) { return _target->GetNumGeometries (); } DllExport unsigned int Model_GetNumGeometryLodLevels (Urho3D::Model *_target, unsigned int index) { return _target->GetNumGeometryLodLevels (index); } DllExport Urho3D::Geometry * Model_GetGeometry (Urho3D::Model *_target, unsigned int index, unsigned int lodLevel) { return _target->GetGeometry (index, lodLevel); } DllExport Interop::Vector3 Model_GetGeometryCenter (Urho3D::Model *_target, unsigned int index) { return *((Interop::Vector3 *) &(_target->GetGeometryCenter (index))); } DllExport unsigned int Model_GetNumMorphs (Urho3D::Model *_target) { return _target->GetNumMorphs (); } DllExport const struct Urho3D::ModelMorph * Model_GetMorph (Urho3D::Model *_target, unsigned int index) { return _target->GetMorph (index); } DllExport const struct Urho3D::ModelMorph * Model_GetMorph0 (Urho3D::Model *_target, const char * name) { return _target->GetMorph (Urho3D::String(name)); } DllExport const struct Urho3D::ModelMorph * Model_GetMorph1 (Urho3D::Model *_target, int nameHash) { return _target->GetMorph (Urho3D::StringHash(nameHash)); } DllExport unsigned int Model_GetMorphRangeStart (Urho3D::Model *_target, unsigned int bufferIndex) { return _target->GetMorphRangeStart (bufferIndex); } DllExport unsigned int Model_GetMorphRangeCount (Urho3D::Model *_target, unsigned int bufferIndex) { return _target->GetMorphRangeCount (bufferIndex); } DllExport int Drawable_GetType (Urho3D::Drawable *_target) { return (_target->GetType ()).Value (); } DllExport const char * Drawable_GetTypeName (Urho3D::Drawable *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Drawable_GetTypeStatic () { return (Drawable::GetTypeStatic ()).Value (); } DllExport const char * Drawable_GetTypeNameStatic () { return stringdup((Drawable::GetTypeNameStatic ()).CString ()); } DllExport void Drawable_RegisterObject (Urho3D::Context * context) { Drawable::RegisterObject (context); } DllExport void Drawable_OnSetEnabled (Urho3D::Drawable *_target) { _target->OnSetEnabled (); } DllExport enum Urho3D::UpdateGeometryType Drawable_GetUpdateGeometryType (Urho3D::Drawable *_target) { return _target->GetUpdateGeometryType (); } DllExport Urho3D::Geometry * Drawable_GetLodGeometry (Urho3D::Drawable *_target, unsigned int batchIndex, unsigned int level) { return _target->GetLodGeometry (batchIndex, level); } DllExport unsigned int Drawable_GetNumOccluderTriangles (Urho3D::Drawable *_target) { return _target->GetNumOccluderTriangles (); } DllExport int Drawable_DrawOcclusion (Urho3D::Drawable *_target, Urho3D::OcclusionBuffer * buffer) { return _target->DrawOcclusion (buffer); } DllExport void Drawable_DrawDebugGeometry (Urho3D::Drawable *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void Drawable_SetDrawDistance (Urho3D::Drawable *_target, float distance) { _target->SetDrawDistance (distance); } DllExport void Drawable_SetShadowDistance (Urho3D::Drawable *_target, float distance) { _target->SetShadowDistance (distance); } DllExport void Drawable_SetLodBias (Urho3D::Drawable *_target, float bias) { _target->SetLodBias (bias); } DllExport void Drawable_SetViewMask (Urho3D::Drawable *_target, unsigned int mask) { _target->SetViewMask (mask); } DllExport void Drawable_SetLightMask (Urho3D::Drawable *_target, unsigned int mask) { _target->SetLightMask (mask); } DllExport void Drawable_SetShadowMask (Urho3D::Drawable *_target, unsigned int mask) { _target->SetShadowMask (mask); } DllExport void Drawable_SetZoneMask (Urho3D::Drawable *_target, unsigned int mask) { _target->SetZoneMask (mask); } DllExport void Drawable_SetMaxLights (Urho3D::Drawable *_target, unsigned int num) { _target->SetMaxLights (num); } DllExport void Drawable_SetCastShadows (Urho3D::Drawable *_target, bool enable) { _target->SetCastShadows (enable); } DllExport void Drawable_SetOccluder (Urho3D::Drawable *_target, bool enable) { _target->SetOccluder (enable); } DllExport void Drawable_SetOccludee (Urho3D::Drawable *_target, bool enable) { _target->SetOccludee (enable); } DllExport void Drawable_MarkForUpdate (Urho3D::Drawable *_target) { _target->MarkForUpdate (); } DllExport Interop::BoundingBox Drawable_GetBoundingBox (Urho3D::Drawable *_target) { return *((Interop::BoundingBox *) &(_target->GetBoundingBox ())); } DllExport Interop::BoundingBox Drawable_GetWorldBoundingBox (Urho3D::Drawable *_target) { return *((Interop::BoundingBox *) &(_target->GetWorldBoundingBox ())); } DllExport unsigned char Drawable_GetDrawableFlags (Urho3D::Drawable *_target) { return _target->GetDrawableFlags (); } DllExport float Drawable_GetDrawDistance (Urho3D::Drawable *_target) { return _target->GetDrawDistance (); } DllExport float Drawable_GetShadowDistance (Urho3D::Drawable *_target) { return _target->GetShadowDistance (); } DllExport float Drawable_GetLodBias (Urho3D::Drawable *_target) { return _target->GetLodBias (); } DllExport unsigned int Drawable_GetViewMask (Urho3D::Drawable *_target) { return _target->GetViewMask (); } DllExport unsigned int Drawable_GetLightMask (Urho3D::Drawable *_target) { return _target->GetLightMask (); } DllExport unsigned int Drawable_GetShadowMask (Urho3D::Drawable *_target) { return _target->GetShadowMask (); } DllExport unsigned int Drawable_GetZoneMask (Urho3D::Drawable *_target) { return _target->GetZoneMask (); } DllExport unsigned int Drawable_GetMaxLights (Urho3D::Drawable *_target) { return _target->GetMaxLights (); } DllExport int Drawable_GetCastShadows (Urho3D::Drawable *_target) { return _target->GetCastShadows (); } DllExport int Drawable_IsOccluder (Urho3D::Drawable *_target) { return _target->IsOccluder (); } DllExport int Drawable_IsOccludee (Urho3D::Drawable *_target) { return _target->IsOccludee (); } DllExport int Drawable_IsInView (Urho3D::Drawable *_target) { return _target->IsInView (); } DllExport int Drawable_IsInView0 (Urho3D::Drawable *_target, Urho3D::Camera * camera) { return _target->IsInView (camera); } DllExport void Drawable_SetZone (Urho3D::Drawable *_target, Urho3D::Zone * zone, bool temporary) { _target->SetZone (zone, temporary); } DllExport void Drawable_SetSortValue (Urho3D::Drawable *_target, float value) { _target->SetSortValue (value); } DllExport void Drawable_SetMinMaxZ (Urho3D::Drawable *_target, float minZ, float maxZ) { _target->SetMinMaxZ (minZ, maxZ); } DllExport void Drawable_MarkInView (Urho3D::Drawable *_target, unsigned int frameNumber) { _target->MarkInView (frameNumber); } DllExport void Drawable_LimitLights (Urho3D::Drawable *_target) { _target->LimitLights (); } DllExport void Drawable_LimitVertexLights (Urho3D::Drawable *_target, bool removeConvertedLights) { _target->LimitVertexLights (removeConvertedLights); } DllExport void Drawable_SetBasePass (Urho3D::Drawable *_target, unsigned int batchIndex) { _target->SetBasePass (batchIndex); } DllExport Urho3D::Octant * Drawable_GetOctant (Urho3D::Drawable *_target) { return _target->GetOctant (); } DllExport Urho3D::Zone * Drawable_GetZone (Urho3D::Drawable *_target) { return _target->GetZone (); } DllExport int Drawable_IsZoneDirty (Urho3D::Drawable *_target) { return _target->IsZoneDirty (); } DllExport float Drawable_GetDistance (Urho3D::Drawable *_target) { return _target->GetDistance (); } DllExport float Drawable_GetLodDistance (Urho3D::Drawable *_target) { return _target->GetLodDistance (); } DllExport float Drawable_GetSortValue (Urho3D::Drawable *_target) { return _target->GetSortValue (); } DllExport int Drawable_HasBasePass (Urho3D::Drawable *_target, unsigned int batchIndex) { return _target->HasBasePass (batchIndex); } DllExport Urho3D::Light * Drawable_GetFirstLight (Urho3D::Drawable *_target) { return _target->GetFirstLight (); } DllExport float Drawable_GetMinZ (Urho3D::Drawable *_target) { return _target->GetMinZ (); } DllExport float Drawable_GetMaxZ (Urho3D::Drawable *_target) { return _target->GetMaxZ (); } DllExport void Drawable_AddLight (Urho3D::Drawable *_target, Urho3D::Light * light) { _target->AddLight (light); } DllExport void Drawable_AddVertexLight (Urho3D::Drawable *_target, Urho3D::Light * light) { _target->AddVertexLight (light); } DllExport int StaticModel_GetType (Urho3D::StaticModel *_target) { return (_target->GetType ()).Value (); } DllExport const char * StaticModel_GetTypeName (Urho3D::StaticModel *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int StaticModel_GetTypeStatic () { return (StaticModel::GetTypeStatic ()).Value (); } DllExport const char * StaticModel_GetTypeNameStatic () { return stringdup((StaticModel::GetTypeNameStatic ()).CString ()); } DllExport void * StaticModel_StaticModel (Urho3D::Context * context) { return WeakPtr<StaticModel>(new StaticModel(context)); } DllExport void StaticModel_RegisterObject (Urho3D::Context * context) { StaticModel::RegisterObject (context); } DllExport Urho3D::Geometry * StaticModel_GetLodGeometry (Urho3D::StaticModel *_target, unsigned int batchIndex, unsigned int level) { return _target->GetLodGeometry (batchIndex, level); } DllExport unsigned int StaticModel_GetNumOccluderTriangles (Urho3D::StaticModel *_target) { return _target->GetNumOccluderTriangles (); } DllExport int StaticModel_DrawOcclusion (Urho3D::StaticModel *_target, Urho3D::OcclusionBuffer * buffer) { return _target->DrawOcclusion (buffer); } DllExport void StaticModel_SetModel (Urho3D::StaticModel *_target, Urho3D::Model * model) { _target->SetModel (model); } DllExport void StaticModel_SetMaterial (Urho3D::StaticModel *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport int StaticModel_SetMaterial0 (Urho3D::StaticModel *_target, unsigned int index, Urho3D::Material * material) { return _target->SetMaterial (index, material); } DllExport void StaticModel_SetOcclusionLodLevel (Urho3D::StaticModel *_target, unsigned int level) { _target->SetOcclusionLodLevel (level); } DllExport void StaticModel_ApplyMaterialList (Urho3D::StaticModel *_target, const char * fileName) { _target->ApplyMaterialList (Urho3D::String(fileName)); } DllExport Urho3D::Model * StaticModel_GetModel (Urho3D::StaticModel *_target) { return _target->GetModel (); } DllExport unsigned int StaticModel_GetNumGeometries (Urho3D::StaticModel *_target) { return _target->GetNumGeometries (); } DllExport Urho3D::Material * StaticModel_GetMaterial (Urho3D::StaticModel *_target, unsigned int index) { return _target->GetMaterial (index); } DllExport unsigned int StaticModel_GetOcclusionLodLevel (Urho3D::StaticModel *_target) { return _target->GetOcclusionLodLevel (); } DllExport int StaticModel_IsInside (Urho3D::StaticModel *_target, const class Urho3D::Vector3 & point) { return _target->IsInside (point); } DllExport int StaticModel_IsInsideLocal (Urho3D::StaticModel *_target, const class Urho3D::Vector3 & point) { return _target->IsInsideLocal (point); } DllExport Urho3D::ResourceRef StaticModel_GetModelAttr (Urho3D::StaticModel *_target) { return _target->GetModelAttr (); } DllExport int AnimatedModel_GetType (Urho3D::AnimatedModel *_target) { return (_target->GetType ()).Value (); } DllExport const char * AnimatedModel_GetTypeName (Urho3D::AnimatedModel *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int AnimatedModel_GetTypeStatic () { return (AnimatedModel::GetTypeStatic ()).Value (); } DllExport const char * AnimatedModel_GetTypeNameStatic () { return stringdup((AnimatedModel::GetTypeNameStatic ()).CString ()); } DllExport void * AnimatedModel_AnimatedModel (Urho3D::Context * context) { return WeakPtr<AnimatedModel>(new AnimatedModel(context)); } DllExport void AnimatedModel_RegisterObject (Urho3D::Context * context) { AnimatedModel::RegisterObject (context); } DllExport int AnimatedModel_Load_File (Urho3D::AnimatedModel *_target, File * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int AnimatedModel_Load_MemoryBuffer (Urho3D::AnimatedModel *_target, MemoryBuffer * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int AnimatedModel_LoadXML (Urho3D::AnimatedModel *_target, const class Urho3D::XMLElement & source, bool setInstanceDefault) { return _target->LoadXML (source, setInstanceDefault); } DllExport void AnimatedModel_ApplyAttributes (Urho3D::AnimatedModel *_target) { _target->ApplyAttributes (); } DllExport enum Urho3D::UpdateGeometryType AnimatedModel_GetUpdateGeometryType (Urho3D::AnimatedModel *_target) { return _target->GetUpdateGeometryType (); } DllExport void AnimatedModel_DrawDebugGeometry (Urho3D::AnimatedModel *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void AnimatedModel_SetModel (Urho3D::AnimatedModel *_target, Urho3D::Model * model, bool createBones) { _target->SetModel (model, createBones); } DllExport Urho3D::AnimationState * AnimatedModel_AddAnimationState (Urho3D::AnimatedModel *_target, Urho3D::Animation * animation) { return _target->AddAnimationState (animation); } DllExport void AnimatedModel_RemoveAnimationState (Urho3D::AnimatedModel *_target, Urho3D::Animation * animation) { _target->RemoveAnimationState (animation); } DllExport void AnimatedModel_RemoveAnimationState0 (Urho3D::AnimatedModel *_target, const char * animationName) { _target->RemoveAnimationState (Urho3D::String(animationName)); } DllExport void AnimatedModel_RemoveAnimationState1 (Urho3D::AnimatedModel *_target, int animationNameHash) { _target->RemoveAnimationState (Urho3D::StringHash(animationNameHash)); } DllExport void AnimatedModel_RemoveAnimationState2 (Urho3D::AnimatedModel *_target, Urho3D::AnimationState * state) { _target->RemoveAnimationState (state); } DllExport void AnimatedModel_RemoveAnimationState3 (Urho3D::AnimatedModel *_target, unsigned int index) { _target->RemoveAnimationState (index); } DllExport void AnimatedModel_RemoveAllAnimationStates (Urho3D::AnimatedModel *_target) { _target->RemoveAllAnimationStates (); } DllExport void AnimatedModel_SetAnimationLodBias (Urho3D::AnimatedModel *_target, float bias) { _target->SetAnimationLodBias (bias); } DllExport void AnimatedModel_SetUpdateInvisible (Urho3D::AnimatedModel *_target, bool enable) { _target->SetUpdateInvisible (enable); } DllExport void AnimatedModel_SetMorphWeight (Urho3D::AnimatedModel *_target, unsigned int index, float weight) { _target->SetMorphWeight (index, weight); } DllExport void AnimatedModel_SetMorphWeight4 (Urho3D::AnimatedModel *_target, const char * name, float weight) { _target->SetMorphWeight (Urho3D::String(name), weight); } DllExport void AnimatedModel_SetMorphWeight5 (Urho3D::AnimatedModel *_target, int nameHash, float weight) { _target->SetMorphWeight (Urho3D::StringHash(nameHash), weight); } DllExport void AnimatedModel_ResetMorphWeights (Urho3D::AnimatedModel *_target) { _target->ResetMorphWeights (); } DllExport void AnimatedModel_ApplyAnimation (Urho3D::AnimatedModel *_target) { _target->ApplyAnimation (); } DllExport const Vector<SharedPtr<class Urho3D::AnimationState> > & AnimatedModel_GetAnimationStates (Urho3D::AnimatedModel *_target) { return _target->GetAnimationStates (); } DllExport unsigned int AnimatedModel_GetNumAnimationStates (Urho3D::AnimatedModel *_target) { return _target->GetNumAnimationStates (); } DllExport Urho3D::AnimationState * AnimatedModel_GetAnimationState (Urho3D::AnimatedModel *_target, Urho3D::Animation * animation) { return _target->GetAnimationState (animation); } DllExport Urho3D::AnimationState * AnimatedModel_GetAnimationState6 (Urho3D::AnimatedModel *_target, const char * animationName) { return _target->GetAnimationState (Urho3D::String(animationName)); } DllExport Urho3D::AnimationState * AnimatedModel_GetAnimationState7 (Urho3D::AnimatedModel *_target, int animationNameHash) { return _target->GetAnimationState (Urho3D::StringHash(animationNameHash)); } DllExport Urho3D::AnimationState * AnimatedModel_GetAnimationState8 (Urho3D::AnimatedModel *_target, unsigned int index) { return _target->GetAnimationState (index); } DllExport float AnimatedModel_GetAnimationLodBias (Urho3D::AnimatedModel *_target) { return _target->GetAnimationLodBias (); } DllExport int AnimatedModel_GetUpdateInvisible (Urho3D::AnimatedModel *_target) { return _target->GetUpdateInvisible (); } DllExport const Vector<SharedPtr<class Urho3D::VertexBuffer> > & AnimatedModel_GetMorphVertexBuffers (Urho3D::AnimatedModel *_target) { return _target->GetMorphVertexBuffers (); } DllExport unsigned int AnimatedModel_GetNumMorphs (Urho3D::AnimatedModel *_target) { return _target->GetNumMorphs (); } DllExport float AnimatedModel_GetMorphWeight (Urho3D::AnimatedModel *_target, unsigned int index) { return _target->GetMorphWeight (index); } DllExport float AnimatedModel_GetMorphWeight9 (Urho3D::AnimatedModel *_target, const char * name) { return _target->GetMorphWeight (Urho3D::String(name)); } DllExport float AnimatedModel_GetMorphWeight10 (Urho3D::AnimatedModel *_target, int nameHash) { return _target->GetMorphWeight (Urho3D::StringHash(nameHash)); } DllExport int AnimatedModel_IsMaster (Urho3D::AnimatedModel *_target) { return _target->IsMaster (); } DllExport Urho3D::ResourceRef AnimatedModel_GetModelAttr (Urho3D::AnimatedModel *_target) { return _target->GetModelAttr (); } DllExport void AnimatedModel_UpdateBoneBoundingBox (Urho3D::AnimatedModel *_target) { _target->UpdateBoneBoundingBox (); } DllExport int Animation_GetType (Urho3D::Animation *_target) { return (_target->GetType ()).Value (); } DllExport const char * Animation_GetTypeName (Urho3D::Animation *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Animation_GetTypeStatic () { return (Animation::GetTypeStatic ()).Value (); } DllExport const char * Animation_GetTypeNameStatic () { return stringdup((Animation::GetTypeNameStatic ()).CString ()); } DllExport void * Animation_Animation (Urho3D::Context * context) { return WeakPtr<Animation>(new Animation(context)); } DllExport void Animation_RegisterObject (Urho3D::Context * context) { Animation::RegisterObject (context); } DllExport int Animation_BeginLoad_File (Urho3D::Animation *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Animation_BeginLoad_MemoryBuffer (Urho3D::Animation *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Animation_Save_File (Urho3D::Animation *_target, File * dest) { return _target->Save (*dest); } DllExport int Animation_Save_MemoryBuffer (Urho3D::Animation *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport void Animation_SetAnimationName (Urho3D::Animation *_target, const char * name) { _target->SetAnimationName (Urho3D::String(name)); } DllExport void Animation_SetLength (Urho3D::Animation *_target, float length) { _target->SetLength (length); } DllExport Urho3D::AnimationTrack * Animation_CreateTrack (Urho3D::Animation *_target, const char * name) { return _target->CreateTrack (Urho3D::String(name)); } DllExport int Animation_RemoveTrack (Urho3D::Animation *_target, const char * name) { return _target->RemoveTrack (Urho3D::String(name)); } DllExport void Animation_RemoveAllTracks (Urho3D::Animation *_target) { _target->RemoveAllTracks (); } // Urho3D::Variant overloads begin: DllExport void Animation_AddTrigger_0 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::Vector3 & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_1 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::IntRect & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_2 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::Color & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_3 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::Vector2 & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_4 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::Vector4 & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_5 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::IntVector2 & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_6 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::Quaternion & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_7 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::Matrix4 & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_8 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const class Urho3D::Matrix3x4 & data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_9 (Urho3D::Animation *_target, float time, bool timeIsNormalized, int data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_10 (Urho3D::Animation *_target, float time, bool timeIsNormalized, float data) { _target->AddTrigger (time, timeIsNormalized, (data)); } DllExport void Animation_AddTrigger_11 (Urho3D::Animation *_target, float time, bool timeIsNormalized, const char * data) { _target->AddTrigger (time, timeIsNormalized, Urho3D::String(data)); } DllExport void Animation_AddTrigger_12 (Urho3D::Animation *_target, float time, bool timeIsNormalized, bool data) { _target->AddTrigger (time, timeIsNormalized, (data)); } // Urho3D::Variant overloads end. DllExport void Animation_RemoveTrigger (Urho3D::Animation *_target, unsigned int index) { _target->RemoveTrigger (index); } DllExport void Animation_RemoveAllTriggers (Urho3D::Animation *_target) { _target->RemoveAllTriggers (); } DllExport void Animation_SetNumTriggers (Urho3D::Animation *_target, unsigned int num) { _target->SetNumTriggers (num); } DllExport Urho3D::Animation * Animation_Clone (Urho3D::Animation *_target, const char * cloneName) { auto copy = _target->Clone (Urho3D::String(cloneName)); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport const char * Animation_GetAnimationName (Urho3D::Animation *_target) { return stringdup((_target->GetAnimationName ()).CString ()); } DllExport int Animation_GetAnimationNameHash (Urho3D::Animation *_target) { return (_target->GetAnimationNameHash ()).Value (); } DllExport float Animation_GetLength (Urho3D::Animation *_target) { return _target->GetLength (); } DllExport unsigned int Animation_GetNumTracks (Urho3D::Animation *_target) { return _target->GetNumTracks (); } DllExport Urho3D::AnimationTrack * Animation_GetTrack (Urho3D::Animation *_target, unsigned int index) { return _target->GetTrack (index); } DllExport Urho3D::AnimationTrack * Animation_GetTrack0 (Urho3D::Animation *_target, const char * name) { return _target->GetTrack (Urho3D::String(name)); } DllExport Urho3D::AnimationTrack * Animation_GetTrack1 (Urho3D::Animation *_target, int nameHash) { return _target->GetTrack (Urho3D::StringHash(nameHash)); } DllExport unsigned int Animation_GetNumTriggers (Urho3D::Animation *_target) { return _target->GetNumTriggers (); } DllExport Urho3D::AnimationTriggerPoint * Animation_GetTrigger (Urho3D::Animation *_target, unsigned int index) { return _target->GetTrigger (index); } DllExport void * AnimationState_AnimationState (Urho3D::AnimatedModel * model, Urho3D::Animation * animation) { return WeakPtr<AnimationState>(new AnimationState(model, animation)); } DllExport void * AnimationState_AnimationState0 (Urho3D::Node * node, Urho3D::Animation * animation) { return WeakPtr<AnimationState>(new AnimationState(node, animation)); } DllExport void AnimationState_SetStartBone (Urho3D::AnimationState *_target, Urho3D::Bone * bone) { _target->SetStartBone (bone); } DllExport void AnimationState_SetLooped (Urho3D::AnimationState *_target, bool looped) { _target->SetLooped (looped); } DllExport void AnimationState_SetWeight (Urho3D::AnimationState *_target, float weight) { _target->SetWeight (weight); } DllExport void AnimationState_SetBlendMode (Urho3D::AnimationState *_target, enum Urho3D::AnimationBlendMode mode) { _target->SetBlendMode (mode); } DllExport void AnimationState_SetTime (Urho3D::AnimationState *_target, float time) { _target->SetTime (time); } DllExport void AnimationState_SetBoneWeight (Urho3D::AnimationState *_target, unsigned int index, float weight, bool recursive) { _target->SetBoneWeight (index, weight, recursive); } DllExport void AnimationState_SetBoneWeight1 (Urho3D::AnimationState *_target, const char * name, float weight, bool recursive) { _target->SetBoneWeight (Urho3D::String(name), weight, recursive); } DllExport void AnimationState_SetBoneWeight2 (Urho3D::AnimationState *_target, int nameHash, float weight, bool recursive) { _target->SetBoneWeight (Urho3D::StringHash(nameHash), weight, recursive); } DllExport void AnimationState_AddWeight (Urho3D::AnimationState *_target, float delta) { _target->AddWeight (delta); } DllExport void AnimationState_AddTime (Urho3D::AnimationState *_target, float delta) { _target->AddTime (delta); } DllExport void AnimationState_SetLayer (Urho3D::AnimationState *_target, unsigned char layer) { _target->SetLayer (layer); } DllExport Urho3D::Animation * AnimationState_GetAnimation (Urho3D::AnimationState *_target) { return _target->GetAnimation (); } DllExport Urho3D::AnimatedModel * AnimationState_GetModel (Urho3D::AnimationState *_target) { return _target->GetModel (); } DllExport Urho3D::Node * AnimationState_GetNode (Urho3D::AnimationState *_target) { return _target->GetNode (); } DllExport Urho3D::Bone * AnimationState_GetStartBone (Urho3D::AnimationState *_target) { return _target->GetStartBone (); } DllExport float AnimationState_GetBoneWeight (Urho3D::AnimationState *_target, unsigned int index) { return _target->GetBoneWeight (index); } DllExport float AnimationState_GetBoneWeight3 (Urho3D::AnimationState *_target, const char * name) { return _target->GetBoneWeight (Urho3D::String(name)); } DllExport float AnimationState_GetBoneWeight4 (Urho3D::AnimationState *_target, int nameHash) { return _target->GetBoneWeight (Urho3D::StringHash(nameHash)); } DllExport unsigned int AnimationState_GetTrackIndex (Urho3D::AnimationState *_target, Urho3D::Node * node) { return _target->GetTrackIndex (node); } DllExport unsigned int AnimationState_GetTrackIndex5 (Urho3D::AnimationState *_target, const char * name) { return _target->GetTrackIndex (Urho3D::String(name)); } DllExport unsigned int AnimationState_GetTrackIndex6 (Urho3D::AnimationState *_target, int nameHash) { return _target->GetTrackIndex (Urho3D::StringHash(nameHash)); } DllExport int AnimationState_IsEnabled (Urho3D::AnimationState *_target) { return _target->IsEnabled (); } DllExport int AnimationState_IsLooped (Urho3D::AnimationState *_target) { return _target->IsLooped (); } DllExport float AnimationState_GetWeight (Urho3D::AnimationState *_target) { return _target->GetWeight (); } DllExport enum Urho3D::AnimationBlendMode AnimationState_GetBlendMode (Urho3D::AnimationState *_target) { return _target->GetBlendMode (); } DllExport float AnimationState_GetTime (Urho3D::AnimationState *_target) { return _target->GetTime (); } DllExport float AnimationState_GetLength (Urho3D::AnimationState *_target) { return _target->GetLength (); } DllExport unsigned char AnimationState_GetLayer (Urho3D::AnimationState *_target) { return _target->GetLayer (); } DllExport void AnimationState_Apply (Urho3D::AnimationState *_target) { _target->Apply (); } DllExport int AnimationController_GetType (Urho3D::AnimationController *_target) { return (_target->GetType ()).Value (); } DllExport const char * AnimationController_GetTypeName (Urho3D::AnimationController *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int AnimationController_GetTypeStatic () { return (AnimationController::GetTypeStatic ()).Value (); } DllExport const char * AnimationController_GetTypeNameStatic () { return stringdup((AnimationController::GetTypeNameStatic ()).CString ()); } DllExport void * AnimationController_AnimationController (Urho3D::Context * context) { return WeakPtr<AnimationController>(new AnimationController(context)); } DllExport void AnimationController_RegisterObject (Urho3D::Context * context) { AnimationController::RegisterObject (context); } DllExport void AnimationController_OnSetEnabled (Urho3D::AnimationController *_target) { _target->OnSetEnabled (); } DllExport void AnimationController_Update (Urho3D::AnimationController *_target, float timeStep) { _target->Update (timeStep); } DllExport int AnimationController_Play (Urho3D::AnimationController *_target, const char * name, unsigned char layer, bool looped, float fadeInTime) { return _target->Play (Urho3D::String(name), layer, looped, fadeInTime); } DllExport int AnimationController_PlayExclusive (Urho3D::AnimationController *_target, const char * name, unsigned char layer, bool looped, float fadeTime) { return _target->PlayExclusive (Urho3D::String(name), layer, looped, fadeTime); } DllExport int AnimationController_Stop (Urho3D::AnimationController *_target, const char * name, float fadeOutTime) { return _target->Stop (Urho3D::String(name), fadeOutTime); } DllExport void AnimationController_StopLayer (Urho3D::AnimationController *_target, unsigned char layer, float fadeOutTime) { _target->StopLayer (layer, fadeOutTime); } DllExport void AnimationController_StopAll (Urho3D::AnimationController *_target, float fadeTime) { _target->StopAll (fadeTime); } DllExport int AnimationController_Fade (Urho3D::AnimationController *_target, const char * name, float targetWeight, float fadeTime) { return _target->Fade (Urho3D::String(name), targetWeight, fadeTime); } DllExport int AnimationController_FadeOthers (Urho3D::AnimationController *_target, const char * name, float targetWeight, float fadeTime) { return _target->FadeOthers (Urho3D::String(name), targetWeight, fadeTime); } DllExport int AnimationController_SetLayer (Urho3D::AnimationController *_target, const char * name, unsigned char layer) { return _target->SetLayer (Urho3D::String(name), layer); } DllExport int AnimationController_SetStartBone (Urho3D::AnimationController *_target, const char * name, const char * startBoneName) { return _target->SetStartBone (Urho3D::String(name), Urho3D::String(startBoneName)); } DllExport int AnimationController_SetTime (Urho3D::AnimationController *_target, const char * name, float time) { return _target->SetTime (Urho3D::String(name), time); } DllExport int AnimationController_SetWeight (Urho3D::AnimationController *_target, const char * name, float weight) { return _target->SetWeight (Urho3D::String(name), weight); } DllExport int AnimationController_SetLooped (Urho3D::AnimationController *_target, const char * name, bool enable) { return _target->SetLooped (Urho3D::String(name), enable); } DllExport int AnimationController_SetSpeed (Urho3D::AnimationController *_target, const char * name, float speed) { return _target->SetSpeed (Urho3D::String(name), speed); } DllExport int AnimationController_SetAutoFade (Urho3D::AnimationController *_target, const char * name, float fadeOutTime) { return _target->SetAutoFade (Urho3D::String(name), fadeOutTime); } DllExport int AnimationController_SetRemoveOnCompletion (Urho3D::AnimationController *_target, const char * name, bool removeOnCompletion) { return _target->SetRemoveOnCompletion (Urho3D::String(name), removeOnCompletion); } DllExport int AnimationController_SetBlendMode (Urho3D::AnimationController *_target, const char * name, enum Urho3D::AnimationBlendMode mode) { return _target->SetBlendMode (Urho3D::String(name), mode); } DllExport int AnimationController_IsPlaying (Urho3D::AnimationController *_target, const char * name) { return _target->IsPlaying (Urho3D::String(name)); } DllExport int AnimationController_IsPlaying0 (Urho3D::AnimationController *_target, unsigned char layer) { return _target->IsPlaying (layer); } DllExport int AnimationController_IsFadingIn (Urho3D::AnimationController *_target, const char * name) { return _target->IsFadingIn (Urho3D::String(name)); } DllExport int AnimationController_IsFadingOut (Urho3D::AnimationController *_target, const char * name) { return _target->IsFadingOut (Urho3D::String(name)); } DllExport int AnimationController_IsAtEnd (Urho3D::AnimationController *_target, const char * name) { return _target->IsAtEnd (Urho3D::String(name)); } DllExport unsigned char AnimationController_GetLayer (Urho3D::AnimationController *_target, const char * name) { return _target->GetLayer (Urho3D::String(name)); } DllExport Urho3D::Bone * AnimationController_GetStartBone (Urho3D::AnimationController *_target, const char * name) { return _target->GetStartBone (Urho3D::String(name)); } DllExport const char * AnimationController_GetStartBoneName (Urho3D::AnimationController *_target, const char * name) { return stringdup((_target->GetStartBoneName (Urho3D::String(name))).CString ()); } DllExport float AnimationController_GetTime (Urho3D::AnimationController *_target, const char * name) { return _target->GetTime (Urho3D::String(name)); } DllExport float AnimationController_GetWeight (Urho3D::AnimationController *_target, const char * name) { return _target->GetWeight (Urho3D::String(name)); } DllExport int AnimationController_IsLooped (Urho3D::AnimationController *_target, const char * name) { return _target->IsLooped (Urho3D::String(name)); } DllExport enum Urho3D::AnimationBlendMode AnimationController_GetBlendMode (Urho3D::AnimationController *_target, const char * name) { return _target->GetBlendMode (Urho3D::String(name)); } DllExport float AnimationController_GetLength (Urho3D::AnimationController *_target, const char * name) { return _target->GetLength (Urho3D::String(name)); } DllExport float AnimationController_GetSpeed (Urho3D::AnimationController *_target, const char * name) { return _target->GetSpeed (Urho3D::String(name)); } DllExport float AnimationController_GetFadeTarget (Urho3D::AnimationController *_target, const char * name) { return _target->GetFadeTarget (Urho3D::String(name)); } DllExport float AnimationController_GetFadeTime (Urho3D::AnimationController *_target, const char * name) { return _target->GetFadeTime (Urho3D::String(name)); } DllExport float AnimationController_GetAutoFade (Urho3D::AnimationController *_target, const char * name) { return _target->GetAutoFade (Urho3D::String(name)); } DllExport int AnimationController_GetRemoveOnCompletion (Urho3D::AnimationController *_target, const char * name) { return _target->GetRemoveOnCompletion (Urho3D::String(name)); } DllExport Urho3D::AnimationState * AnimationController_GetAnimationState (Urho3D::AnimationController *_target, const char * name) { return _target->GetAnimationState (Urho3D::String(name)); } DllExport Urho3D::AnimationState * AnimationController_GetAnimationState1 (Urho3D::AnimationController *_target, int nameHash) { return _target->GetAnimationState (Urho3D::StringHash(nameHash)); } DllExport void * Sphere_Sphere () { return new Sphere(); } DllExport void * Sphere_Sphere0 (const class Urho3D::Sphere & sphere) { return new Sphere(sphere); } DllExport void * Sphere_Sphere1 (const class Urho3D::Vector3 & center, float radius) { return new Sphere(center, radius); } DllExport void * Sphere_Sphere2 (const class Urho3D::Vector3 * vertices, unsigned int count) { return new Sphere(vertices, count); } DllExport void * Sphere_Sphere3 (const class Urho3D::BoundingBox & box) { return new Sphere(box); } DllExport void * Sphere_Sphere4 (const class Urho3D::Frustum & frustum) { return new Sphere(frustum); } DllExport void * Sphere_Sphere5 (const class Urho3D::Polyhedron & poly) { return new Sphere(poly); } DllExport void Sphere_Define (Urho3D::Sphere *_target, const class Urho3D::Sphere & sphere) { _target->Define (sphere); } DllExport void Sphere_Define6 (Urho3D::Sphere *_target, const class Urho3D::Vector3 & center, float radius) { _target->Define (center, radius); } DllExport void Sphere_Define7 (Urho3D::Sphere *_target, const class Urho3D::Vector3 * vertices, unsigned int count) { _target->Define (vertices, count); } DllExport void Sphere_Define8 (Urho3D::Sphere *_target, const class Urho3D::BoundingBox & box) { _target->Define (box); } DllExport void Sphere_Define9 (Urho3D::Sphere *_target, const class Urho3D::Frustum & frustum) { _target->Define (frustum); } DllExport void Sphere_Define10 (Urho3D::Sphere *_target, const class Urho3D::Polyhedron & poly) { _target->Define (poly); } DllExport void Sphere_Merge (Urho3D::Sphere *_target, const class Urho3D::Vector3 & point) { _target->Merge (point); } DllExport void Sphere_Merge11 (Urho3D::Sphere *_target, const class Urho3D::Vector3 * vertices, unsigned int count) { _target->Merge (vertices, count); } DllExport void Sphere_Merge12 (Urho3D::Sphere *_target, const class Urho3D::BoundingBox & box) { _target->Merge (box); } DllExport void Sphere_Merge13 (Urho3D::Sphere *_target, const class Urho3D::Frustum & frustum) { _target->Merge (frustum); } DllExport void Sphere_Merge14 (Urho3D::Sphere *_target, const class Urho3D::Polyhedron & poly) { _target->Merge (poly); } DllExport void Sphere_Merge15 (Urho3D::Sphere *_target, const class Urho3D::Sphere & sphere) { _target->Merge (sphere); } DllExport void Sphere_Clear (Urho3D::Sphere *_target) { _target->Clear (); } DllExport int Sphere_Defined (Urho3D::Sphere *_target) { return _target->Defined (); } DllExport enum Urho3D::Intersection Sphere_IsInside (Urho3D::Sphere *_target, const class Urho3D::Vector3 & point) { return _target->IsInside (point); } DllExport enum Urho3D::Intersection Sphere_IsInside16 (Urho3D::Sphere *_target, const class Urho3D::Sphere & sphere) { return _target->IsInside (sphere); } DllExport enum Urho3D::Intersection Sphere_IsInsideFast (Urho3D::Sphere *_target, const class Urho3D::Sphere & sphere) { return _target->IsInsideFast (sphere); } DllExport enum Urho3D::Intersection Sphere_IsInside17 (Urho3D::Sphere *_target, const class Urho3D::BoundingBox & box) { return _target->IsInside (box); } DllExport enum Urho3D::Intersection Sphere_IsInsideFast18 (Urho3D::Sphere *_target, const class Urho3D::BoundingBox & box) { return _target->IsInsideFast (box); } DllExport float Sphere_Distance (Urho3D::Sphere *_target, const class Urho3D::Vector3 & point) { return _target->Distance (point); } DllExport Interop::Vector3 Sphere_GetLocalPoint (Urho3D::Sphere *_target, float theta, float phi) { return *((Interop::Vector3 *) &(_target->GetLocalPoint (theta, phi))); } DllExport Interop::Vector3 Sphere_GetPoint (Urho3D::Sphere *_target, float theta, float phi) { return *((Interop::Vector3 *) &(_target->GetPoint (theta, phi))); } DllExport void * Frustum_Frustum () { return new Frustum(); } DllExport void * Frustum_Frustum0 (const class Urho3D::Frustum & frustum) { return new Frustum(frustum); } DllExport void Frustum_Define (Urho3D::Frustum *_target, float fov, float aspectRatio, float zoom, float nearZ, float farZ, const class Urho3D::Matrix3x4 & transform) { _target->Define (fov, aspectRatio, zoom, nearZ, farZ, transform); } DllExport void Frustum_Define1 (Urho3D::Frustum *_target, const class Urho3D::Vector3 & nearValue, const class Urho3D::Vector3 & farValue, const class Urho3D::Matrix3x4 & transform) { _target->Define (nearValue, farValue, transform); } DllExport void Frustum_Define2 (Urho3D::Frustum *_target, const class Urho3D::BoundingBox & box, const class Urho3D::Matrix3x4 & transform) { _target->Define (box, transform); } DllExport void Frustum_Define3 (Urho3D::Frustum *_target, const class Urho3D::Matrix4 & projection) { _target->Define (projection); } DllExport void Frustum_DefineOrtho (Urho3D::Frustum *_target, float orthoSize, float aspectRatio, float zoom, float nearZ, float farZ, const class Urho3D::Matrix3x4 & transform) { _target->DefineOrtho (orthoSize, aspectRatio, zoom, nearZ, farZ, transform); } DllExport void Frustum_DefineSplit (Urho3D::Frustum *_target, const class Urho3D::Matrix4 & projection, float nearValue, float farValue) { _target->DefineSplit (projection, nearValue, farValue); } DllExport void Frustum_Transform (Urho3D::Frustum *_target, const class Urho3D::Matrix3x4 & transform) { _target->Transform (transform); } DllExport enum Urho3D::Intersection Frustum_IsInside (Urho3D::Frustum *_target, const class Urho3D::Vector3 & point) { return _target->IsInside (point); } DllExport enum Urho3D::Intersection Frustum_IsInside4 (Urho3D::Frustum *_target, const class Urho3D::Sphere & sphere) { return _target->IsInside (sphere); } DllExport enum Urho3D::Intersection Frustum_IsInsideFast (Urho3D::Frustum *_target, const class Urho3D::Sphere & sphere) { return _target->IsInsideFast (sphere); } DllExport enum Urho3D::Intersection Frustum_IsInside5 (Urho3D::Frustum *_target, const class Urho3D::BoundingBox & box) { return _target->IsInside (box); } DllExport enum Urho3D::Intersection Frustum_IsInsideFast6 (Urho3D::Frustum *_target, const class Urho3D::BoundingBox & box) { return _target->IsInsideFast (box); } DllExport float Frustum_Distance (Urho3D::Frustum *_target, const class Urho3D::Vector3 & point) { return _target->Distance (point); } DllExport Urho3D::Frustum * Frustum_Transformed (Urho3D::Frustum *_target, const class Urho3D::Matrix3x4 & transform) { return new Urho3D::Frustum (_target->Transformed (transform)); } DllExport Urho3D::Rect Frustum_Projected (Urho3D::Frustum *_target, const class Urho3D::Matrix4 & transform) { return _target->Projected (transform); } DllExport void Frustum_UpdatePlanes (Urho3D::Frustum *_target) { _target->UpdatePlanes (); } DllExport void * GPUObject_GPUObject (Urho3D::Graphics * graphics) { return new GPUObject(graphics); } DllExport void GPUObject_OnDeviceLost (Urho3D::GPUObject *_target) { _target->OnDeviceLost (); } DllExport void GPUObject_OnDeviceReset (Urho3D::GPUObject *_target) { _target->OnDeviceReset (); } DllExport void GPUObject_Release (Urho3D::GPUObject *_target) { _target->Release (); } DllExport void GPUObject_ClearDataLost (Urho3D::GPUObject *_target) { _target->ClearDataLost (); } DllExport Urho3D::Graphics * GPUObject_GetGraphics (Urho3D::GPUObject *_target) { return _target->GetGraphics (); } DllExport void * GPUObject_GetGPUObject (Urho3D::GPUObject *_target) { return _target->GetGPUObject (); } DllExport unsigned int GPUObject_GetGPUObjectName (Urho3D::GPUObject *_target) { return _target->GetGPUObjectName (); } DllExport int GPUObject_IsDataLost (Urho3D::GPUObject *_target) { return _target->IsDataLost (); } DllExport int GPUObject_HasPendingData (Urho3D::GPUObject *_target) { return _target->HasPendingData (); } DllExport GPUObject* Texture_CastToGPUObject(Urho3D::Texture *_target) { return static_cast<GPUObject*>(_target); } DllExport void * Texture_Texture (Urho3D::Context * context) { return WeakPtr<Texture>(new Texture(context)); } DllExport void Texture_SetNumLevels (Urho3D::Texture *_target, unsigned int levels) { _target->SetNumLevels (levels); } DllExport void Texture_SetFilterMode (Urho3D::Texture *_target, enum Urho3D::TextureFilterMode filter) { _target->SetFilterMode (filter); } DllExport void Texture_SetAddressMode (Urho3D::Texture *_target, enum Urho3D::TextureCoordinate coord, enum Urho3D::TextureAddressMode address) { _target->SetAddressMode (coord, address); } DllExport void Texture_SetAnisotropy (Urho3D::Texture *_target, unsigned int level) { _target->SetAnisotropy (level); } DllExport void Texture_SetShadowCompare (Urho3D::Texture *_target, bool enable) { _target->SetShadowCompare (enable); } DllExport void Texture_SetBorderColor (Urho3D::Texture *_target, const class Urho3D::Color & color) { _target->SetBorderColor (color); } DllExport void Texture_SetSRGB (Urho3D::Texture *_target, bool enable) { _target->SetSRGB (enable); } DllExport void Texture_SetBackupTexture (Urho3D::Texture *_target, Urho3D::Texture * texture) { _target->SetBackupTexture (texture); } DllExport void Texture_SetMipsToSkip (Urho3D::Texture *_target, int quality, int toSkip) { _target->SetMipsToSkip (quality, toSkip); } DllExport unsigned int Texture_GetFormat (Urho3D::Texture *_target) { return _target->GetFormat (); } DllExport int Texture_IsCompressed (Urho3D::Texture *_target) { return _target->IsCompressed (); } DllExport unsigned int Texture_GetLevels (Urho3D::Texture *_target) { return _target->GetLevels (); } DllExport int Texture_GetWidth (Urho3D::Texture *_target) { return _target->GetWidth (); } DllExport int Texture_GetHeight (Urho3D::Texture *_target) { return _target->GetHeight (); } DllExport int Texture_GetDepth (Urho3D::Texture *_target) { return _target->GetDepth (); } DllExport enum Urho3D::TextureFilterMode Texture_GetFilterMode (Urho3D::Texture *_target) { return _target->GetFilterMode (); } DllExport enum Urho3D::TextureAddressMode Texture_GetAddressMode (Urho3D::Texture *_target, enum Urho3D::TextureCoordinate coord) { return _target->GetAddressMode (coord); } DllExport unsigned int Texture_GetAnisotropy (Urho3D::Texture *_target) { return _target->GetAnisotropy (); } DllExport int Texture_GetShadowCompare (Urho3D::Texture *_target) { return _target->GetShadowCompare (); } DllExport Interop::Color Texture_GetBorderColor (Urho3D::Texture *_target) { return *((Interop::Color *) &(_target->GetBorderColor ())); } DllExport int Texture_GetSRGB (Urho3D::Texture *_target) { return _target->GetSRGB (); } DllExport int Texture_GetMultiSample (Urho3D::Texture *_target) { return _target->GetMultiSample (); } DllExport int Texture_GetAutoResolve (Urho3D::Texture *_target) { return _target->GetAutoResolve (); } DllExport int Texture_IsResolveDirty (Urho3D::Texture *_target) { return _target->IsResolveDirty (); } DllExport int Texture_GetLevelsDirty (Urho3D::Texture *_target) { return _target->GetLevelsDirty (); } DllExport Urho3D::Texture * Texture_GetBackupTexture (Urho3D::Texture *_target) { return _target->GetBackupTexture (); } DllExport int Texture_GetMipsToSkip (Urho3D::Texture *_target, int quality) { return _target->GetMipsToSkip (quality); } DllExport int Texture_GetLevelWidth (Urho3D::Texture *_target, unsigned int level) { return _target->GetLevelWidth (level); } DllExport int Texture_GetLevelHeight (Urho3D::Texture *_target, unsigned int level) { return _target->GetLevelHeight (level); } DllExport int Texture_GetLevelDepth (Urho3D::Texture *_target, unsigned int level) { return _target->GetLevelDepth (level); } DllExport enum Urho3D::TextureUsage Texture_GetUsage (Urho3D::Texture *_target) { return _target->GetUsage (); } DllExport unsigned int Texture_GetDataSize (Urho3D::Texture *_target, int width, int height) { return _target->GetDataSize (width, height); } DllExport unsigned int Texture_GetDataSize0 (Urho3D::Texture *_target, int width, int height, int depth) { return _target->GetDataSize (width, height, depth); } DllExport unsigned int Texture_GetRowDataSize (Urho3D::Texture *_target, int width) { return _target->GetRowDataSize (width); } DllExport unsigned int Texture_GetComponents (Urho3D::Texture *_target) { return _target->GetComponents (); } DllExport int Texture_GetParametersDirty (Urho3D::Texture *_target) { return _target->GetParametersDirty (); } DllExport void Texture_SetParameters (Urho3D::Texture *_target, Urho3D::XMLFile * xml) { _target->SetParameters (xml); } DllExport void Texture_SetParameters1 (Urho3D::Texture *_target, const class Urho3D::XMLElement & element) { _target->SetParameters (element); } DllExport void Texture_SetParametersDirty (Urho3D::Texture *_target) { _target->SetParametersDirty (); } DllExport void Texture_UpdateParameters (Urho3D::Texture *_target) { _target->UpdateParameters (); } DllExport void * Texture_GetShaderResourceView (Urho3D::Texture *_target) { return _target->GetShaderResourceView (); } DllExport void * Texture_GetSampler (Urho3D::Texture *_target) { return _target->GetSampler (); } DllExport void * Texture_GetResolveTexture (Urho3D::Texture *_target) { return _target->GetResolveTexture (); } DllExport unsigned int Texture_GetSRGBFormat (Urho3D::Texture *_target, unsigned int format) { return _target->GetSRGBFormat (format); } DllExport void Texture_SetResolveDirty (Urho3D::Texture *_target, bool enable) { _target->SetResolveDirty (enable); } DllExport void Texture_SetLevelsDirty (Urho3D::Texture *_target) { _target->SetLevelsDirty (); } DllExport void Texture_RegenerateLevels (Urho3D::Texture *_target) { _target->RegenerateLevels (); } DllExport unsigned int Texture_CheckMaxLevels (int width, int height, unsigned int requestedLevels) { return Texture::CheckMaxLevels (width, height, requestedLevels); } DllExport unsigned int Texture_CheckMaxLevels2 (int width, int height, int depth, unsigned int requestedLevels) { return Texture::CheckMaxLevels (width, height, depth, requestedLevels); } DllExport int Light_GetType (Urho3D::Light *_target) { return (_target->GetType ()).Value (); } DllExport const char * Light_GetTypeName (Urho3D::Light *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Light_GetTypeStatic () { return (Light::GetTypeStatic ()).Value (); } DllExport const char * Light_GetTypeNameStatic () { return stringdup((Light::GetTypeNameStatic ()).CString ()); } DllExport void * Light_Light (Urho3D::Context * context) { return WeakPtr<Light>(new Light(context)); } DllExport void Light_RegisterObject (Urho3D::Context * context) { Light::RegisterObject (context); } DllExport void Light_DrawDebugGeometry (Urho3D::Light *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void Light_SetLightType (Urho3D::Light *_target, enum Urho3D::LightType type) { _target->SetLightType (type); } DllExport void Light_SetPerVertex (Urho3D::Light *_target, bool enable) { _target->SetPerVertex (enable); } DllExport void Light_SetColor (Urho3D::Light *_target, const class Urho3D::Color & color) { _target->SetColor (color); } DllExport void Light_SetTemperature (Urho3D::Light *_target, float temperature) { _target->SetTemperature (temperature); } DllExport void Light_SetRadius (Urho3D::Light *_target, float radius) { _target->SetRadius (radius); } DllExport void Light_SetLength (Urho3D::Light *_target, float length) { _target->SetLength (length); } DllExport void Light_SetUsePhysicalValues (Urho3D::Light *_target, bool enable) { _target->SetUsePhysicalValues (enable); } DllExport void Light_SetSpecularIntensity (Urho3D::Light *_target, float intensity) { _target->SetSpecularIntensity (intensity); } DllExport void Light_SetBrightness (Urho3D::Light *_target, float brightness) { _target->SetBrightness (brightness); } DllExport void Light_SetRange (Urho3D::Light *_target, float range) { _target->SetRange (range); } DllExport void Light_SetFov (Urho3D::Light *_target, float fov) { _target->SetFov (fov); } DllExport void Light_SetAspectRatio (Urho3D::Light *_target, float aspectRatio) { _target->SetAspectRatio (aspectRatio); } DllExport void Light_SetFadeDistance (Urho3D::Light *_target, float distance) { _target->SetFadeDistance (distance); } DllExport void Light_SetShadowFadeDistance (Urho3D::Light *_target, float distance) { _target->SetShadowFadeDistance (distance); } DllExport void Light_SetShadowBias (Urho3D::Light *_target, const struct Urho3D::BiasParameters & parameters) { _target->SetShadowBias (parameters); } DllExport void Light_SetShadowCascade (Urho3D::Light *_target, const struct Urho3D::CascadeParameters & parameters) { _target->SetShadowCascade (parameters); } DllExport void Light_SetShadowFocus (Urho3D::Light *_target, const struct Urho3D::FocusParameters & parameters) { _target->SetShadowFocus (parameters); } DllExport void Light_SetShadowIntensity (Urho3D::Light *_target, float intensity) { _target->SetShadowIntensity (intensity); } DllExport void Light_SetShadowResolution (Urho3D::Light *_target, float resolution) { _target->SetShadowResolution (resolution); } DllExport void Light_SetShadowNearFarRatio (Urho3D::Light *_target, float nearFarRatio) { _target->SetShadowNearFarRatio (nearFarRatio); } DllExport void Light_SetShadowMaxExtrusion (Urho3D::Light *_target, float extrusion) { _target->SetShadowMaxExtrusion (extrusion); } DllExport void Light_SetRampTexture (Urho3D::Light *_target, Urho3D::Texture * texture) { _target->SetRampTexture (texture); } DllExport void Light_SetShapeTexture (Urho3D::Light *_target, Urho3D::Texture * texture) { _target->SetShapeTexture (texture); } DllExport enum Urho3D::LightType Light_GetLightType (Urho3D::Light *_target) { return _target->GetLightType (); } DllExport int Light_GetPerVertex (Urho3D::Light *_target) { return _target->GetPerVertex (); } DllExport Interop::Color Light_GetColor (Urho3D::Light *_target) { return *((Interop::Color *) &(_target->GetColor ())); } DllExport float Light_GetTemperature (Urho3D::Light *_target) { return _target->GetTemperature (); } DllExport float Light_GetRadius (Urho3D::Light *_target) { return _target->GetRadius (); } DllExport float Light_GetLength (Urho3D::Light *_target) { return _target->GetLength (); } DllExport int Light_GetUsePhysicalValues (Urho3D::Light *_target) { return _target->GetUsePhysicalValues (); } DllExport Interop::Color Light_GetColorFromTemperature (Urho3D::Light *_target) { return *((Interop::Color *) &(_target->GetColorFromTemperature ())); } DllExport float Light_GetSpecularIntensity (Urho3D::Light *_target) { return _target->GetSpecularIntensity (); } DllExport float Light_GetBrightness (Urho3D::Light *_target) { return _target->GetBrightness (); } DllExport Interop::Color Light_GetEffectiveColor (Urho3D::Light *_target) { return *((Interop::Color *) &(_target->GetEffectiveColor ())); } DllExport float Light_GetEffectiveSpecularIntensity (Urho3D::Light *_target) { return _target->GetEffectiveSpecularIntensity (); } DllExport float Light_GetRange (Urho3D::Light *_target) { return _target->GetRange (); } DllExport float Light_GetFov (Urho3D::Light *_target) { return _target->GetFov (); } DllExport float Light_GetAspectRatio (Urho3D::Light *_target) { return _target->GetAspectRatio (); } DllExport float Light_GetFadeDistance (Urho3D::Light *_target) { return _target->GetFadeDistance (); } DllExport float Light_GetShadowFadeDistance (Urho3D::Light *_target) { return _target->GetShadowFadeDistance (); } DllExport const struct Urho3D::BiasParameters & Light_GetShadowBias (Urho3D::Light *_target) { return _target->GetShadowBias (); } DllExport const struct Urho3D::CascadeParameters & Light_GetShadowCascade (Urho3D::Light *_target) { return _target->GetShadowCascade (); } DllExport const struct Urho3D::FocusParameters & Light_GetShadowFocus (Urho3D::Light *_target) { return _target->GetShadowFocus (); } DllExport float Light_GetShadowIntensity (Urho3D::Light *_target) { return _target->GetShadowIntensity (); } DllExport float Light_GetShadowResolution (Urho3D::Light *_target) { return _target->GetShadowResolution (); } DllExport float Light_GetShadowNearFarRatio (Urho3D::Light *_target) { return _target->GetShadowNearFarRatio (); } DllExport float Light_GetShadowMaxExtrusion (Urho3D::Light *_target) { return _target->GetShadowMaxExtrusion (); } DllExport Urho3D::Texture * Light_GetRampTexture (Urho3D::Light *_target) { return _target->GetRampTexture (); } DllExport Urho3D::Texture * Light_GetShapeTexture (Urho3D::Light *_target) { return _target->GetShapeTexture (); } DllExport Urho3D::Frustum * Light_GetFrustum (Urho3D::Light *_target) { return new Urho3D::Frustum (_target->GetFrustum ()); } DllExport Urho3D::Frustum * Light_GetViewSpaceFrustum (Urho3D::Light *_target, const class Urho3D::Matrix3x4 & view) { return new Urho3D::Frustum (_target->GetViewSpaceFrustum (view)); } DllExport int Light_GetNumShadowSplits (Urho3D::Light *_target) { return _target->GetNumShadowSplits (); } DllExport int Light_IsNegative (Urho3D::Light *_target) { return _target->IsNegative (); } DllExport void Light_SetIntensitySortValue (Urho3D::Light *_target, float distance) { _target->SetIntensitySortValue (distance); } DllExport void Light_SetIntensitySortValue0 (Urho3D::Light *_target, const class Urho3D::BoundingBox & box) { _target->SetIntensitySortValue (box); } DllExport void Light_SetLightQueue (Urho3D::Light *_target, Urho3D::LightBatchQueue * queue) { _target->SetLightQueue (queue); } DllExport Interop::Matrix3x4 Light_GetVolumeTransform (Urho3D::Light *_target, Urho3D::Camera * camera) { return *((Interop::Matrix3x4 *) &(_target->GetVolumeTransform (camera))); } DllExport Urho3D::LightBatchQueue * Light_GetLightQueue (Urho3D::Light *_target) { return _target->GetLightQueue (); } DllExport float Light_GetIntensityDivisor (Urho3D::Light *_target, float attenuation) { return _target->GetIntensityDivisor (attenuation); } DllExport Urho3D::ResourceRef Light_GetRampTextureAttr (Urho3D::Light *_target) { return _target->GetRampTextureAttr (); } DllExport Urho3D::ResourceRef Light_GetShapeTextureAttr (Urho3D::Light *_target) { return _target->GetShapeTextureAttr (); } DllExport Interop::Matrix3x4 Light_GetFullscreenQuadTransform (Urho3D::Camera * camera) { return *((Interop::Matrix3x4 *) &(Light::GetFullscreenQuadTransform (camera))); } DllExport void * ShaderParameterAnimationInfo_ShaderParameterAnimationInfo (Urho3D::Material * material, const char * name, Urho3D::ValueAnimation * attributeAnimation, enum Urho3D::WrapMode wrapMode, float speed) { return WeakPtr<ShaderParameterAnimationInfo>(new ShaderParameterAnimationInfo(material, Urho3D::String(name), attributeAnimation, wrapMode, speed)); } DllExport const char * ShaderParameterAnimationInfo_GetName (Urho3D::ShaderParameterAnimationInfo *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport int Material_GetType (Urho3D::Material *_target) { return (_target->GetType ()).Value (); } DllExport const char * Material_GetTypeName (Urho3D::Material *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Material_GetTypeStatic () { return (Material::GetTypeStatic ()).Value (); } DllExport const char * Material_GetTypeNameStatic () { return stringdup((Material::GetTypeNameStatic ()).CString ()); } DllExport void * Material_Material (Urho3D::Context * context) { return WeakPtr<Material>(new Material(context)); } DllExport void Material_RegisterObject (Urho3D::Context * context) { Material::RegisterObject (context); } DllExport int Material_BeginLoad_File (Urho3D::Material *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Material_BeginLoad_MemoryBuffer (Urho3D::Material *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Material_EndLoad (Urho3D::Material *_target) { return _target->EndLoad (); } DllExport int Material_Save_File (Urho3D::Material *_target, File * dest) { return _target->Save (*dest); } DllExport int Material_Save_MemoryBuffer (Urho3D::Material *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int Material_Load (Urho3D::Material *_target, const class Urho3D::XMLElement & source) { return _target->Load (source); } DllExport int Material_Save0 (Urho3D::Material *_target, Urho3D::XMLElement & dest) { return _target->Save (dest); } DllExport void Material_SetNumTechniques (Urho3D::Material *_target, unsigned int num) { _target->SetNumTechniques (num); } DllExport void Material_SetTechnique (Urho3D::Material *_target, unsigned int index, Urho3D::Technique * tech, unsigned int qualityLevel, float lodDistance) { _target->SetTechnique (index, tech, qualityLevel, lodDistance); } DllExport void Material_SetVertexShaderDefines (Urho3D::Material *_target, const char * defines) { _target->SetVertexShaderDefines (Urho3D::String(defines)); } DllExport void Material_SetPixelShaderDefines (Urho3D::Material *_target, const char * defines) { _target->SetPixelShaderDefines (Urho3D::String(defines)); } // Urho3D::Variant overloads begin: DllExport void Material_SetShaderParameter_0 (Urho3D::Material *_target, const char * name, const class Urho3D::Vector3 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_1 (Urho3D::Material *_target, const char * name, const class Urho3D::IntRect & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_2 (Urho3D::Material *_target, const char * name, const class Urho3D::Color & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_3 (Urho3D::Material *_target, const char * name, const class Urho3D::Vector2 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_4 (Urho3D::Material *_target, const char * name, const class Urho3D::Vector4 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_5 (Urho3D::Material *_target, const char * name, const class Urho3D::IntVector2 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_6 (Urho3D::Material *_target, const char * name, const class Urho3D::Quaternion & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_7 (Urho3D::Material *_target, const char * name, const class Urho3D::Matrix4 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_8 (Urho3D::Material *_target, const char * name, const class Urho3D::Matrix3x4 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_9 (Urho3D::Material *_target, const char * name, int value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_10 (Urho3D::Material *_target, const char * name, float value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void Material_SetShaderParameter_11 (Urho3D::Material *_target, const char * name, const char * value) { _target->SetShaderParameter (Urho3D::String(name), Urho3D::String(value)); } DllExport void Material_SetShaderParameter_12 (Urho3D::Material *_target, const char * name, bool value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } // Urho3D::Variant overloads end. DllExport void Material_SetShaderParameterAnimation (Urho3D::Material *_target, const char * name, Urho3D::ValueAnimation * animation, enum Urho3D::WrapMode wrapMode, float speed) { _target->SetShaderParameterAnimation (Urho3D::String(name), animation, wrapMode, speed); } DllExport void Material_SetShaderParameterAnimationWrapMode (Urho3D::Material *_target, const char * name, enum Urho3D::WrapMode wrapMode) { _target->SetShaderParameterAnimationWrapMode (Urho3D::String(name), wrapMode); } DllExport void Material_SetShaderParameterAnimationSpeed (Urho3D::Material *_target, const char * name, float speed) { _target->SetShaderParameterAnimationSpeed (Urho3D::String(name), speed); } DllExport void Material_SetTexture (Urho3D::Material *_target, enum Urho3D::TextureUnit unit, Urho3D::Texture * texture) { _target->SetTexture (unit, texture); } DllExport void Material_SetUVTransform (Urho3D::Material *_target, const class Urho3D::Vector2 & offset, float rotation, const class Urho3D::Vector2 & repeat) { _target->SetUVTransform (offset, rotation, repeat); } DllExport void Material_SetUVTransform1 (Urho3D::Material *_target, const class Urho3D::Vector2 & offset, float rotation, float repeat) { _target->SetUVTransform (offset, rotation, repeat); } DllExport void Material_SetCullMode (Urho3D::Material *_target, enum Urho3D::CullMode mode) { _target->SetCullMode (mode); } DllExport void Material_SetShadowCullMode (Urho3D::Material *_target, enum Urho3D::CullMode mode) { _target->SetShadowCullMode (mode); } DllExport void Material_SetFillMode (Urho3D::Material *_target, enum Urho3D::FillMode mode) { _target->SetFillMode (mode); } DllExport void Material_SetDepthBias (Urho3D::Material *_target, const struct Urho3D::BiasParameters & parameters) { _target->SetDepthBias (parameters); } DllExport void Material_SetAlphaToCoverage (Urho3D::Material *_target, bool enable) { _target->SetAlphaToCoverage (enable); } DllExport void Material_SetLineAntiAlias (Urho3D::Material *_target, bool enable) { _target->SetLineAntiAlias (enable); } DllExport void Material_SetRenderOrder (Urho3D::Material *_target, unsigned char order) { _target->SetRenderOrder (order); } DllExport void Material_SetOcclusion (Urho3D::Material *_target, bool enable) { _target->SetOcclusion (enable); } DllExport void Material_SetScene (Urho3D::Material *_target, Urho3D::Scene * scene) { _target->SetScene (scene); } DllExport void Material_RemoveShaderParameter (Urho3D::Material *_target, const char * name) { _target->RemoveShaderParameter (Urho3D::String(name)); } DllExport void Material_ReleaseShaders (Urho3D::Material *_target) { _target->ReleaseShaders (); } DllExport Urho3D::Material * Material_Clone (Urho3D::Material *_target, const char * cloneName) { auto copy = _target->Clone (Urho3D::String(cloneName)); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport void Material_SortTechniques (Urho3D::Material *_target) { _target->SortTechniques (); } DllExport void Material_MarkForAuxView (Urho3D::Material *_target, unsigned int frameNumber) { _target->MarkForAuxView (frameNumber); } DllExport unsigned int Material_GetNumTechniques (Urho3D::Material *_target) { return _target->GetNumTechniques (); } DllExport Urho3D::Technique * Material_GetTechnique (Urho3D::Material *_target, unsigned int index) { return _target->GetTechnique (index); } DllExport Urho3D::Pass * Material_GetPass (Urho3D::Material *_target, unsigned int index, const char * passName) { return _target->GetPass (index, Urho3D::String(passName)); } DllExport Urho3D::Texture * Material_GetTexture (Urho3D::Material *_target, enum Urho3D::TextureUnit unit) { return _target->GetTexture (unit); } DllExport const char * Material_GetVertexShaderDefines (Urho3D::Material *_target) { return stringdup((_target->GetVertexShaderDefines ()).CString ()); } DllExport const char * Material_GetPixelShaderDefines (Urho3D::Material *_target) { return stringdup((_target->GetPixelShaderDefines ()).CString ()); } // Urho3D::Variant overloads begin: DllExport Interop::Vector3 Material_GetShaderParameter_0 (Urho3D::Material *_target, const char * name) { return *((Interop::Vector3 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetVector3())); } DllExport Interop::IntRect Material_GetShaderParameter_1 (Urho3D::Material *_target, const char * name) { return *((Interop::IntRect *) &(_target->GetShaderParameter (Urho3D::String(name)).GetIntRect())); } DllExport Interop::Color Material_GetShaderParameter_2 (Urho3D::Material *_target, const char * name) { return *((Interop::Color *) &(_target->GetShaderParameter (Urho3D::String(name)).GetColor())); } DllExport Interop::Vector2 Material_GetShaderParameter_3 (Urho3D::Material *_target, const char * name) { return *((Interop::Vector2 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetVector2())); } DllExport Interop::Vector4 Material_GetShaderParameter_4 (Urho3D::Material *_target, const char * name) { return *((Interop::Vector4 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetVector4())); } DllExport Interop::IntVector2 Material_GetShaderParameter_5 (Urho3D::Material *_target, const char * name) { return *((Interop::IntVector2 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetIntVector2())); } DllExport Interop::Quaternion Material_GetShaderParameter_6 (Urho3D::Material *_target, const char * name) { return *((Interop::Quaternion *) &(_target->GetShaderParameter (Urho3D::String(name)).GetQuaternion())); } DllExport Interop::Matrix4 Material_GetShaderParameter_7 (Urho3D::Material *_target, const char * name) { return *((Interop::Matrix4 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetMatrix4())); } DllExport Interop::Matrix3x4 Material_GetShaderParameter_8 (Urho3D::Material *_target, const char * name) { return *((Interop::Matrix3x4 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetMatrix3x4())); } DllExport int Material_GetShaderParameter_9 (Urho3D::Material *_target, const char * name) { return (_target->GetShaderParameter (Urho3D::String(name)).GetInt()); } DllExport float Material_GetShaderParameter_10 (Urho3D::Material *_target, const char * name) { return (_target->GetShaderParameter (Urho3D::String(name)).GetFloat()); } DllExport const char * Material_GetShaderParameter_11 (Urho3D::Material *_target, const char * name) { return stringdup(_target->GetShaderParameter (Urho3D::String(name)).GetString().CString()); } DllExport bool Material_GetShaderParameter_12 (Urho3D::Material *_target, const char * name) { return (_target->GetShaderParameter (Urho3D::String(name)).GetBool()); } // Urho3D::Variant overloads end. DllExport Urho3D::ValueAnimation * Material_GetShaderParameterAnimation (Urho3D::Material *_target, const char * name) { return _target->GetShaderParameterAnimation (Urho3D::String(name)); } DllExport enum Urho3D::WrapMode Material_GetShaderParameterAnimationWrapMode (Urho3D::Material *_target, const char * name) { return _target->GetShaderParameterAnimationWrapMode (Urho3D::String(name)); } DllExport float Material_GetShaderParameterAnimationSpeed (Urho3D::Material *_target, const char * name) { return _target->GetShaderParameterAnimationSpeed (Urho3D::String(name)); } DllExport enum Urho3D::CullMode Material_GetCullMode (Urho3D::Material *_target) { return _target->GetCullMode (); } DllExport enum Urho3D::CullMode Material_GetShadowCullMode (Urho3D::Material *_target) { return _target->GetShadowCullMode (); } DllExport enum Urho3D::FillMode Material_GetFillMode (Urho3D::Material *_target) { return _target->GetFillMode (); } DllExport const struct Urho3D::BiasParameters & Material_GetDepthBias (Urho3D::Material *_target) { return _target->GetDepthBias (); } DllExport int Material_GetAlphaToCoverage (Urho3D::Material *_target) { return _target->GetAlphaToCoverage (); } DllExport int Material_GetLineAntiAlias (Urho3D::Material *_target) { return _target->GetLineAntiAlias (); } DllExport unsigned char Material_GetRenderOrder (Urho3D::Material *_target) { return _target->GetRenderOrder (); } DllExport unsigned int Material_GetAuxViewFrameNumber (Urho3D::Material *_target) { return _target->GetAuxViewFrameNumber (); } DllExport int Material_GetOcclusion (Urho3D::Material *_target) { return _target->GetOcclusion (); } DllExport int Material_GetSpecular (Urho3D::Material *_target) { return _target->GetSpecular (); } DllExport Urho3D::Scene * Material_GetScene (Urho3D::Material *_target) { return _target->GetScene (); } DllExport unsigned int Material_GetShaderParameterHash (Urho3D::Material *_target) { return _target->GetShaderParameterHash (); } DllExport const char * Material_GetTextureUnitName (enum Urho3D::TextureUnit unit) { return stringdup((Material::GetTextureUnitName (unit)).CString ()); } DllExport Urho3D::Variant Material_ParseShaderParameterValue (const char * value) { return Material::ParseShaderParameterValue (Urho3D::String(value)); } DllExport int BillboardSet_GetType (Urho3D::BillboardSet *_target) { return (_target->GetType ()).Value (); } DllExport const char * BillboardSet_GetTypeName (Urho3D::BillboardSet *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int BillboardSet_GetTypeStatic () { return (BillboardSet::GetTypeStatic ()).Value (); } DllExport const char * BillboardSet_GetTypeNameStatic () { return stringdup((BillboardSet::GetTypeNameStatic ()).CString ()); } DllExport void * BillboardSet_BillboardSet (Urho3D::Context * context) { return WeakPtr<BillboardSet>(new BillboardSet(context)); } DllExport void BillboardSet_RegisterObject (Urho3D::Context * context) { BillboardSet::RegisterObject (context); } DllExport enum Urho3D::UpdateGeometryType BillboardSet_GetUpdateGeometryType (Urho3D::BillboardSet *_target) { return _target->GetUpdateGeometryType (); } DllExport void BillboardSet_SetMaterial (Urho3D::BillboardSet *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport void BillboardSet_SetNumBillboards (Urho3D::BillboardSet *_target, unsigned int num) { _target->SetNumBillboards (num); } DllExport void BillboardSet_SetRelative (Urho3D::BillboardSet *_target, bool enable) { _target->SetRelative (enable); } DllExport void BillboardSet_SetScaled (Urho3D::BillboardSet *_target, bool enable) { _target->SetScaled (enable); } DllExport void BillboardSet_SetSorted (Urho3D::BillboardSet *_target, bool enable) { _target->SetSorted (enable); } DllExport void BillboardSet_SetFixedScreenSize (Urho3D::BillboardSet *_target, bool enable) { _target->SetFixedScreenSize (enable); } DllExport void BillboardSet_SetFaceCameraMode (Urho3D::BillboardSet *_target, enum Urho3D::FaceCameraMode mode) { _target->SetFaceCameraMode (mode); } DllExport void BillboardSet_SetMinAngle (Urho3D::BillboardSet *_target, float angle) { _target->SetMinAngle (angle); } DllExport void BillboardSet_SetAnimationLodBias (Urho3D::BillboardSet *_target, float bias) { _target->SetAnimationLodBias (bias); } DllExport void BillboardSet_Commit (Urho3D::BillboardSet *_target) { _target->Commit (); } DllExport Urho3D::Material * BillboardSet_GetMaterial (Urho3D::BillboardSet *_target) { return _target->GetMaterial (); } DllExport unsigned int BillboardSet_GetNumBillboards (Urho3D::BillboardSet *_target) { return _target->GetNumBillboards (); } DllExport Urho3D::Billboard * BillboardSet_GetBillboard (Urho3D::BillboardSet *_target, unsigned int index) { return _target->GetBillboard (index); } DllExport int BillboardSet_IsRelative (Urho3D::BillboardSet *_target) { return _target->IsRelative (); } DllExport int BillboardSet_IsScaled (Urho3D::BillboardSet *_target) { return _target->IsScaled (); } DllExport int BillboardSet_IsSorted (Urho3D::BillboardSet *_target) { return _target->IsSorted (); } DllExport int BillboardSet_IsFixedScreenSize (Urho3D::BillboardSet *_target) { return _target->IsFixedScreenSize (); } DllExport enum Urho3D::FaceCameraMode BillboardSet_GetFaceCameraMode (Urho3D::BillboardSet *_target) { return _target->GetFaceCameraMode (); } DllExport float BillboardSet_GetMinAngle (Urho3D::BillboardSet *_target) { return _target->GetMinAngle (); } DllExport float BillboardSet_GetAnimationLodBias (Urho3D::BillboardSet *_target) { return _target->GetAnimationLodBias (); } DllExport Urho3D::ResourceRef BillboardSet_GetMaterialAttr (Urho3D::BillboardSet *_target) { return _target->GetMaterialAttr (); } DllExport int Camera_GetType (Urho3D::Camera *_target) { return (_target->GetType ()).Value (); } DllExport const char * Camera_GetTypeName (Urho3D::Camera *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Camera_GetTypeStatic () { return (Camera::GetTypeStatic ()).Value (); } DllExport const char * Camera_GetTypeNameStatic () { return stringdup((Camera::GetTypeNameStatic ()).CString ()); } DllExport void * Camera_Camera (Urho3D::Context * context) { return WeakPtr<Camera>(new Camera(context)); } DllExport void Camera_RegisterObject (Urho3D::Context * context) { Camera::RegisterObject (context); } DllExport void Camera_DrawDebugGeometry (Urho3D::Camera *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void Camera_SetNearClip (Urho3D::Camera *_target, float nearClip) { _target->SetNearClip (nearClip); } DllExport void Camera_SetFarClip (Urho3D::Camera *_target, float farClip) { _target->SetFarClip (farClip); } DllExport void Camera_SetFov (Urho3D::Camera *_target, float fov) { _target->SetFov (fov); } DllExport void Camera_SetSkew (Urho3D::Camera *_target, float skew) { _target->SetSkew (skew); } DllExport void Camera_SetOrthoSize (Urho3D::Camera *_target, float orthoSize) { _target->SetOrthoSize (orthoSize); } DllExport void Camera_SetOrthoSize0 (Urho3D::Camera *_target, const class Urho3D::Vector2 & orthoSize) { _target->SetOrthoSize (orthoSize); } DllExport void Camera_SetAspectRatio (Urho3D::Camera *_target, float aspectRatio) { _target->SetAspectRatio (aspectRatio); } DllExport void Camera_SetFillMode (Urho3D::Camera *_target, enum Urho3D::FillMode mode) { _target->SetFillMode (mode); } DllExport void Camera_SetZoom (Urho3D::Camera *_target, float zoom) { _target->SetZoom (zoom); } DllExport void Camera_SetLodBias (Urho3D::Camera *_target, float bias) { _target->SetLodBias (bias); } DllExport void Camera_SetViewMask (Urho3D::Camera *_target, unsigned int mask) { _target->SetViewMask (mask); } DllExport void Camera_SetViewOverrideFlags (Urho3D::Camera *_target, unsigned int flags) { _target->SetViewOverrideFlags (flags); } DllExport void Camera_SetOrthographic (Urho3D::Camera *_target, bool enable) { _target->SetOrthographic (enable); } DllExport void Camera_SetAutoAspectRatio (Urho3D::Camera *_target, bool enable) { _target->SetAutoAspectRatio (enable); } DllExport void Camera_SetProjectionOffset (Urho3D::Camera *_target, const class Urho3D::Vector2 & offset) { _target->SetProjectionOffset (offset); } DllExport void Camera_SetUseReflection (Urho3D::Camera *_target, bool enable) { _target->SetUseReflection (enable); } DllExport void Camera_SetReflectionPlane (Urho3D::Camera *_target, const class Urho3D::Plane & plane) { _target->SetReflectionPlane (plane); } DllExport void Camera_SetUseClipping (Urho3D::Camera *_target, bool enable) { _target->SetUseClipping (enable); } DllExport void Camera_SetClipPlane (Urho3D::Camera *_target, const class Urho3D::Plane & plane) { _target->SetClipPlane (plane); } DllExport void Camera_SetFlipVertical (Urho3D::Camera *_target, bool enable) { _target->SetFlipVertical (enable); } DllExport void Camera_SetProjection (Urho3D::Camera *_target, const class Urho3D::Matrix4 & projection) { _target->SetProjection (projection); } DllExport float Camera_GetFarClip (Urho3D::Camera *_target) { return _target->GetFarClip (); } DllExport float Camera_GetNearClip (Urho3D::Camera *_target) { return _target->GetNearClip (); } DllExport float Camera_GetSkew (Urho3D::Camera *_target) { return _target->GetSkew (); } DllExport float Camera_GetFov (Urho3D::Camera *_target) { return _target->GetFov (); } DllExport float Camera_GetOrthoSize (Urho3D::Camera *_target) { return _target->GetOrthoSize (); } DllExport float Camera_GetAspectRatio (Urho3D::Camera *_target) { return _target->GetAspectRatio (); } DllExport float Camera_GetZoom (Urho3D::Camera *_target) { return _target->GetZoom (); } DllExport float Camera_GetLodBias (Urho3D::Camera *_target) { return _target->GetLodBias (); } DllExport unsigned int Camera_GetViewMask (Urho3D::Camera *_target) { return _target->GetViewMask (); } DllExport unsigned int Camera_GetViewOverrideFlags (Urho3D::Camera *_target) { return _target->GetViewOverrideFlags (); } DllExport enum Urho3D::FillMode Camera_GetFillMode (Urho3D::Camera *_target) { return _target->GetFillMode (); } DllExport int Camera_IsOrthographic (Urho3D::Camera *_target) { return _target->IsOrthographic (); } DllExport int Camera_GetAutoAspectRatio (Urho3D::Camera *_target) { return _target->GetAutoAspectRatio (); } DllExport const class Urho3D::Frustum & Camera_GetFrustum (Urho3D::Camera *_target) { return _target->GetFrustum (); } DllExport Interop::Matrix4 Camera_GetProjection (Urho3D::Camera *_target) { return *((Interop::Matrix4 *) &(_target->GetProjection ())); } DllExport Interop::Matrix4 Camera_GetGPUProjection (Urho3D::Camera *_target) { return *((Interop::Matrix4 *) &(_target->GetGPUProjection ())); } DllExport Interop::Matrix3x4 Camera_GetView (Urho3D::Camera *_target) { return *((Interop::Matrix3x4 *) &(_target->GetView ())); } DllExport float Camera_GetHalfViewSize (Urho3D::Camera *_target) { return _target->GetHalfViewSize (); } DllExport Urho3D::Frustum * Camera_GetSplitFrustum (Urho3D::Camera *_target, float nearClip, float farClip) { return new Urho3D::Frustum (_target->GetSplitFrustum (nearClip, farClip)); } DllExport Urho3D::Frustum * Camera_GetViewSpaceFrustum (Urho3D::Camera *_target) { return new Urho3D::Frustum (_target->GetViewSpaceFrustum ()); } DllExport Urho3D::Frustum * Camera_GetViewSpaceSplitFrustum (Urho3D::Camera *_target, float nearClip, float farClip) { return new Urho3D::Frustum (_target->GetViewSpaceSplitFrustum (nearClip, farClip)); } DllExport Urho3D::Ray Camera_GetScreenRay (Urho3D::Camera *_target, float x, float y) { return _target->GetScreenRay (x, y); } DllExport Interop::Vector2 Camera_WorldToScreenPoint (Urho3D::Camera *_target, const class Urho3D::Vector3 & worldPos) { return *((Interop::Vector2 *) &(_target->WorldToScreenPoint (worldPos))); } DllExport Interop::Vector3 Camera_ScreenToWorldPoint (Urho3D::Camera *_target, const class Urho3D::Vector3 & screenPos) { return *((Interop::Vector3 *) &(_target->ScreenToWorldPoint (screenPos))); } DllExport Interop::Vector2 Camera_GetProjectionOffset (Urho3D::Camera *_target) { return *((Interop::Vector2 *) &(_target->GetProjectionOffset ())); } DllExport int Camera_GetUseReflection (Urho3D::Camera *_target) { return _target->GetUseReflection (); } DllExport Interop::Plane Camera_GetReflectionPlane (Urho3D::Camera *_target) { return *((Interop::Plane *) &(_target->GetReflectionPlane ())); } DllExport int Camera_GetUseClipping (Urho3D::Camera *_target) { return _target->GetUseClipping (); } DllExport Interop::Plane Camera_GetClipPlane (Urho3D::Camera *_target) { return *((Interop::Plane *) &(_target->GetClipPlane ())); } DllExport int Camera_GetFlipVertical (Urho3D::Camera *_target) { return _target->GetFlipVertical (); } DllExport int Camera_GetReverseCulling (Urho3D::Camera *_target) { return _target->GetReverseCulling (); } DllExport float Camera_GetDistance (Urho3D::Camera *_target, const class Urho3D::Vector3 & worldPos) { return _target->GetDistance (worldPos); } DllExport float Camera_GetDistanceSquared (Urho3D::Camera *_target, const class Urho3D::Vector3 & worldPos) { return _target->GetDistanceSquared (worldPos); } DllExport float Camera_GetLodDistance (Urho3D::Camera *_target, float distance, float scale, float bias) { return _target->GetLodDistance (distance, scale, bias); } DllExport Interop::Quaternion Camera_GetFaceCameraRotation (Urho3D::Camera *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, enum Urho3D::FaceCameraMode mode, float minAngle) { return *((Interop::Quaternion *) &(_target->GetFaceCameraRotation (position, rotation, mode, minAngle))); } DllExport Interop::Matrix3x4 Camera_GetEffectiveWorldTransform (Urho3D::Camera *_target) { return *((Interop::Matrix3x4 *) &(_target->GetEffectiveWorldTransform ())); } DllExport int Camera_IsProjectionValid (Urho3D::Camera *_target) { return _target->IsProjectionValid (); } DllExport void Camera_SetAspectRatioInternal (Urho3D::Camera *_target, float aspectRatio) { _target->SetAspectRatioInternal (aspectRatio); } DllExport void Camera_SetOrthoSizeAttr (Urho3D::Camera *_target, float orthoSize) { _target->SetOrthoSizeAttr (orthoSize); } DllExport void Camera_SetReflectionPlaneAttr (Urho3D::Camera *_target, const class Urho3D::Vector4 & value) { _target->SetReflectionPlaneAttr (value); } DllExport Interop::Vector4 Camera_GetReflectionPlaneAttr (Urho3D::Camera *_target) { return *((Interop::Vector4 *) &(_target->GetReflectionPlaneAttr ())); } DllExport void Camera_SetClipPlaneAttr (Urho3D::Camera *_target, const class Urho3D::Vector4 & value) { _target->SetClipPlaneAttr (value); } DllExport Interop::Vector4 Camera_GetClipPlaneAttr (Urho3D::Camera *_target) { return *((Interop::Vector4 *) &(_target->GetClipPlaneAttr ())); } DllExport GPUObject* ConstantBuffer_CastToGPUObject(Urho3D::ConstantBuffer *_target) { return static_cast<GPUObject*>(_target); } DllExport int ConstantBuffer_GetType (Urho3D::ConstantBuffer *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstantBuffer_GetTypeName (Urho3D::ConstantBuffer *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstantBuffer_GetTypeStatic () { return (ConstantBuffer::GetTypeStatic ()).Value (); } DllExport const char * ConstantBuffer_GetTypeNameStatic () { return stringdup((ConstantBuffer::GetTypeNameStatic ()).CString ()); } DllExport void * ConstantBuffer_ConstantBuffer (Urho3D::Context * context) { return WeakPtr<ConstantBuffer>(new ConstantBuffer(context)); } DllExport void ConstantBuffer_Release (Urho3D::ConstantBuffer *_target) { _target->Release (); } DllExport int ConstantBuffer_SetSize (Urho3D::ConstantBuffer *_target, unsigned int size) { return _target->SetSize (size); } DllExport void ConstantBuffer_SetParameter (Urho3D::ConstantBuffer *_target, unsigned int offset, unsigned int size, const void * data) { _target->SetParameter (offset, size, data); } DllExport void ConstantBuffer_SetVector3ArrayParameter (Urho3D::ConstantBuffer *_target, unsigned int offset, unsigned int rows, const void * data) { _target->SetVector3ArrayParameter (offset, rows, data); } DllExport void ConstantBuffer_Apply (Urho3D::ConstantBuffer *_target) { _target->Apply (); } DllExport unsigned int ConstantBuffer_GetSize (Urho3D::ConstantBuffer *_target) { return _target->GetSize (); } DllExport int ConstantBuffer_IsDirty (Urho3D::ConstantBuffer *_target) { return _target->IsDirty (); } DllExport int CustomGeometry_GetType (Urho3D::CustomGeometry *_target) { return (_target->GetType ()).Value (); } DllExport const char * CustomGeometry_GetTypeName (Urho3D::CustomGeometry *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CustomGeometry_GetTypeStatic () { return (CustomGeometry::GetTypeStatic ()).Value (); } DllExport const char * CustomGeometry_GetTypeNameStatic () { return stringdup((CustomGeometry::GetTypeNameStatic ()).CString ()); } DllExport void * CustomGeometry_CustomGeometry (Urho3D::Context * context) { return WeakPtr<CustomGeometry>(new CustomGeometry(context)); } DllExport void CustomGeometry_RegisterObject (Urho3D::Context * context) { CustomGeometry::RegisterObject (context); } DllExport Urho3D::Geometry * CustomGeometry_GetLodGeometry (Urho3D::CustomGeometry *_target, unsigned int batchIndex, unsigned int level) { return _target->GetLodGeometry (batchIndex, level); } DllExport unsigned int CustomGeometry_GetNumOccluderTriangles (Urho3D::CustomGeometry *_target) { return _target->GetNumOccluderTriangles (); } DllExport int CustomGeometry_DrawOcclusion (Urho3D::CustomGeometry *_target, Urho3D::OcclusionBuffer * buffer) { return _target->DrawOcclusion (buffer); } DllExport void CustomGeometry_Clear (Urho3D::CustomGeometry *_target) { _target->Clear (); } DllExport void CustomGeometry_SetNumGeometries (Urho3D::CustomGeometry *_target, unsigned int num) { _target->SetNumGeometries (num); } DllExport void CustomGeometry_SetDynamic (Urho3D::CustomGeometry *_target, bool enable) { _target->SetDynamic (enable); } DllExport void CustomGeometry_BeginGeometry (Urho3D::CustomGeometry *_target, unsigned int index, enum Urho3D::PrimitiveType type) { _target->BeginGeometry (index, type); } DllExport void CustomGeometry_DefineVertex (Urho3D::CustomGeometry *_target, const class Urho3D::Vector3 & position) { _target->DefineVertex (position); } DllExport void CustomGeometry_DefineNormal (Urho3D::CustomGeometry *_target, const class Urho3D::Vector3 & normal) { _target->DefineNormal (normal); } DllExport void CustomGeometry_DefineColor (Urho3D::CustomGeometry *_target, const class Urho3D::Color & color) { _target->DefineColor (color); } DllExport void CustomGeometry_DefineTexCoord (Urho3D::CustomGeometry *_target, const class Urho3D::Vector2 & texCoord) { _target->DefineTexCoord (texCoord); } DllExport void CustomGeometry_DefineTangent (Urho3D::CustomGeometry *_target, const class Urho3D::Vector4 & tangent) { _target->DefineTangent (tangent); } DllExport void CustomGeometry_DefineGeometry (Urho3D::CustomGeometry *_target, unsigned int index, enum Urho3D::PrimitiveType type, unsigned int numVertices, bool hasNormals, bool hasColors, bool hasTexCoords, bool hasTangents) { _target->DefineGeometry (index, type, numVertices, hasNormals, hasColors, hasTexCoords, hasTangents); } DllExport void CustomGeometry_Commit (Urho3D::CustomGeometry *_target) { _target->Commit (); } DllExport void CustomGeometry_SetMaterial (Urho3D::CustomGeometry *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport int CustomGeometry_SetMaterial0 (Urho3D::CustomGeometry *_target, unsigned int index, Urho3D::Material * material) { return _target->SetMaterial (index, material); } DllExport unsigned int CustomGeometry_GetNumGeometries (Urho3D::CustomGeometry *_target) { return _target->GetNumGeometries (); } DllExport unsigned int CustomGeometry_GetNumVertices (Urho3D::CustomGeometry *_target, unsigned int index) { return _target->GetNumVertices (index); } DllExport int CustomGeometry_IsDynamic (Urho3D::CustomGeometry *_target) { return _target->IsDynamic (); } DllExport Urho3D::Material * CustomGeometry_GetMaterial (Urho3D::CustomGeometry *_target, unsigned int index) { return _target->GetMaterial (index); } DllExport Urho3D::CustomGeometryVertex * CustomGeometry_GetVertex (Urho3D::CustomGeometry *_target, unsigned int geometryIndex, unsigned int vertexNum) { return _target->GetVertex (geometryIndex, vertexNum); } DllExport int DebugRenderer_GetType (Urho3D::DebugRenderer *_target) { return (_target->GetType ()).Value (); } DllExport const char * DebugRenderer_GetTypeName (Urho3D::DebugRenderer *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int DebugRenderer_GetTypeStatic () { return (DebugRenderer::GetTypeStatic ()).Value (); } DllExport const char * DebugRenderer_GetTypeNameStatic () { return stringdup((DebugRenderer::GetTypeNameStatic ()).CString ()); } DllExport void * DebugRenderer_DebugRenderer (Urho3D::Context * context) { return WeakPtr<DebugRenderer>(new DebugRenderer(context)); } DllExport void DebugRenderer_RegisterObject (Urho3D::Context * context) { DebugRenderer::RegisterObject (context); } DllExport void DebugRenderer_SetLineAntiAlias (Urho3D::DebugRenderer *_target, bool enable) { _target->SetLineAntiAlias (enable); } DllExport void DebugRenderer_SetView (Urho3D::DebugRenderer *_target, Urho3D::Camera * camera) { _target->SetView (camera); } DllExport void DebugRenderer_AddLine (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & start, const class Urho3D::Vector3 & end, const class Urho3D::Color & color, bool depthTest) { _target->AddLine (start, end, color, depthTest); } DllExport void DebugRenderer_AddLine0 (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & start, const class Urho3D::Vector3 & end, unsigned int color, bool depthTest) { _target->AddLine (start, end, color, depthTest); } DllExport void DebugRenderer_AddTriangle (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & v1, const class Urho3D::Vector3 & v2, const class Urho3D::Vector3 & v3, const class Urho3D::Color & color, bool depthTest) { _target->AddTriangle (v1, v2, v3, color, depthTest); } DllExport void DebugRenderer_AddTriangle1 (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & v1, const class Urho3D::Vector3 & v2, const class Urho3D::Vector3 & v3, unsigned int color, bool depthTest) { _target->AddTriangle (v1, v2, v3, color, depthTest); } DllExport void DebugRenderer_AddPolygon (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & v1, const class Urho3D::Vector3 & v2, const class Urho3D::Vector3 & v3, const class Urho3D::Vector3 & v4, const class Urho3D::Color & color, bool depthTest) { _target->AddPolygon (v1, v2, v3, v4, color, depthTest); } DllExport void DebugRenderer_AddPolygon2 (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & v1, const class Urho3D::Vector3 & v2, const class Urho3D::Vector3 & v3, const class Urho3D::Vector3 & v4, unsigned int color, bool depthTest) { _target->AddPolygon (v1, v2, v3, v4, color, depthTest); } DllExport void DebugRenderer_AddNode (Urho3D::DebugRenderer *_target, Urho3D::Node * node, float scale, bool depthTest) { _target->AddNode (node, scale, depthTest); } DllExport void DebugRenderer_AddBoundingBox (Urho3D::DebugRenderer *_target, const class Urho3D::BoundingBox & box, const class Urho3D::Color & color, bool depthTest, bool solid) { _target->AddBoundingBox (box, color, depthTest, solid); } DllExport void DebugRenderer_AddBoundingBox3 (Urho3D::DebugRenderer *_target, const class Urho3D::BoundingBox & box, const class Urho3D::Matrix3x4 & transform, const class Urho3D::Color & color, bool depthTest, bool solid) { _target->AddBoundingBox (box, transform, color, depthTest, solid); } DllExport void DebugRenderer_AddFrustum (Urho3D::DebugRenderer *_target, const class Urho3D::Frustum & frustum, const class Urho3D::Color & color, bool depthTest) { _target->AddFrustum (frustum, color, depthTest); } DllExport void DebugRenderer_AddPolyhedron (Urho3D::DebugRenderer *_target, const class Urho3D::Polyhedron & poly, const class Urho3D::Color & color, bool depthTest) { _target->AddPolyhedron (poly, color, depthTest); } DllExport void DebugRenderer_AddSphere (Urho3D::DebugRenderer *_target, const class Urho3D::Sphere & sphere, const class Urho3D::Color & color, bool depthTest) { _target->AddSphere (sphere, color, depthTest); } DllExport void DebugRenderer_AddSphereSector (Urho3D::DebugRenderer *_target, const class Urho3D::Sphere & sphere, const class Urho3D::Quaternion & rotation, float angle, bool drawLines, const class Urho3D::Color & color, bool depthTest) { _target->AddSphereSector (sphere, rotation, angle, drawLines, color, depthTest); } DllExport void DebugRenderer_AddCylinder (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & position, float radius, float height, const class Urho3D::Color & color, bool depthTest) { _target->AddCylinder (position, radius, height, color, depthTest); } DllExport void DebugRenderer_AddTriangleMesh (Urho3D::DebugRenderer *_target, const void * vertexData, unsigned int vertexSize, const void * indexData, unsigned int indexSize, unsigned int indexStart, unsigned int indexCount, const class Urho3D::Matrix3x4 & transform, const class Urho3D::Color & color, bool depthTest) { _target->AddTriangleMesh (vertexData, vertexSize, indexData, indexSize, indexStart, indexCount, transform, color, depthTest); } DllExport void DebugRenderer_AddTriangleMesh4 (Urho3D::DebugRenderer *_target, const void * vertexData, unsigned int vertexSize, unsigned int vertexStart, const void * indexData, unsigned int indexSize, unsigned int indexStart, unsigned int indexCount, const class Urho3D::Matrix3x4 & transform, const class Urho3D::Color & color, bool depthTest) { _target->AddTriangleMesh (vertexData, vertexSize, vertexStart, indexData, indexSize, indexStart, indexCount, transform, color, depthTest); } DllExport void DebugRenderer_AddCircle (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & center, const class Urho3D::Vector3 & normal, float radius, const class Urho3D::Color & color, int steps, bool depthTest) { _target->AddCircle (center, normal, radius, color, steps, depthTest); } DllExport void DebugRenderer_AddCross (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & center, float size, const class Urho3D::Color & color, bool depthTest) { _target->AddCross (center, size, color, depthTest); } DllExport void DebugRenderer_AddQuad (Urho3D::DebugRenderer *_target, const class Urho3D::Vector3 & center, float width, float height, const class Urho3D::Color & color, bool depthTest) { _target->AddQuad (center, width, height, color, depthTest); } DllExport void DebugRenderer_Render (Urho3D::DebugRenderer *_target) { _target->Render (); } DllExport int DebugRenderer_GetLineAntiAlias (Urho3D::DebugRenderer *_target) { return _target->GetLineAntiAlias (); } DllExport Interop::Matrix3x4 DebugRenderer_GetView (Urho3D::DebugRenderer *_target) { return *((Interop::Matrix3x4 *) &(_target->GetView ())); } DllExport Interop::Matrix4 DebugRenderer_GetProjection (Urho3D::DebugRenderer *_target) { return *((Interop::Matrix4 *) &(_target->GetProjection ())); } DllExport const class Urho3D::Frustum & DebugRenderer_GetFrustum (Urho3D::DebugRenderer *_target) { return _target->GetFrustum (); } DllExport int DebugRenderer_IsInside (Urho3D::DebugRenderer *_target, const class Urho3D::BoundingBox & box) { return _target->IsInside (box); } DllExport int DebugRenderer_HasContent (Urho3D::DebugRenderer *_target) { return _target->HasContent (); } DllExport int DecalSet_GetType (Urho3D::DecalSet *_target) { return (_target->GetType ()).Value (); } DllExport const char * DecalSet_GetTypeName (Urho3D::DecalSet *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int DecalSet_GetTypeStatic () { return (DecalSet::GetTypeStatic ()).Value (); } DllExport const char * DecalSet_GetTypeNameStatic () { return stringdup((DecalSet::GetTypeNameStatic ()).CString ()); } DllExport void * DecalSet_DecalSet (Urho3D::Context * context) { return WeakPtr<DecalSet>(new DecalSet(context)); } DllExport void DecalSet_RegisterObject (Urho3D::Context * context) { DecalSet::RegisterObject (context); } DllExport void DecalSet_ApplyAttributes (Urho3D::DecalSet *_target) { _target->ApplyAttributes (); } DllExport void DecalSet_OnSetEnabled (Urho3D::DecalSet *_target) { _target->OnSetEnabled (); } DllExport enum Urho3D::UpdateGeometryType DecalSet_GetUpdateGeometryType (Urho3D::DecalSet *_target) { return _target->GetUpdateGeometryType (); } DllExport void DecalSet_SetMaterial (Urho3D::DecalSet *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport void DecalSet_SetMaxVertices (Urho3D::DecalSet *_target, unsigned int num) { _target->SetMaxVertices (num); } DllExport void DecalSet_SetMaxIndices (Urho3D::DecalSet *_target, unsigned int num) { _target->SetMaxIndices (num); } DllExport void DecalSet_SetOptimizeBufferSize (Urho3D::DecalSet *_target, bool enable) { _target->SetOptimizeBufferSize (enable); } DllExport int DecalSet_AddDecal (Urho3D::DecalSet *_target, Urho3D::Drawable * target, const class Urho3D::Vector3 & worldPosition, const class Urho3D::Quaternion & worldRotation, float size, float aspectRatio, float depth, const class Urho3D::Vector2 & topLeftUV, const class Urho3D::Vector2 & bottomRightUV, float timeToLive, float normalCutoff, unsigned int subGeometry) { return _target->AddDecal (target, worldPosition, worldRotation, size, aspectRatio, depth, topLeftUV, bottomRightUV, timeToLive, normalCutoff, subGeometry); } DllExport void DecalSet_RemoveDecals (Urho3D::DecalSet *_target, unsigned int num) { _target->RemoveDecals (num); } DllExport void DecalSet_RemoveAllDecals (Urho3D::DecalSet *_target) { _target->RemoveAllDecals (); } DllExport Urho3D::Material * DecalSet_GetMaterial (Urho3D::DecalSet *_target) { return _target->GetMaterial (); } DllExport unsigned int DecalSet_GetNumDecals (Urho3D::DecalSet *_target) { return _target->GetNumDecals (); } DllExport unsigned int DecalSet_GetNumVertices (Urho3D::DecalSet *_target) { return _target->GetNumVertices (); } DllExport unsigned int DecalSet_GetNumIndices (Urho3D::DecalSet *_target) { return _target->GetNumIndices (); } DllExport unsigned int DecalSet_GetMaxVertices (Urho3D::DecalSet *_target) { return _target->GetMaxVertices (); } DllExport unsigned int DecalSet_GetMaxIndices (Urho3D::DecalSet *_target) { return _target->GetMaxIndices (); } DllExport int DecalSet_GetOptimizeBufferSize (Urho3D::DecalSet *_target) { return _target->GetOptimizeBufferSize (); } DllExport Urho3D::ResourceRef DecalSet_GetMaterialAttr (Urho3D::DecalSet *_target) { return _target->GetMaterialAttr (); } DllExport int Geometry_GetType (Urho3D::Geometry *_target) { return (_target->GetType ()).Value (); } DllExport const char * Geometry_GetTypeName (Urho3D::Geometry *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Geometry_GetTypeStatic () { return (Geometry::GetTypeStatic ()).Value (); } DllExport const char * Geometry_GetTypeNameStatic () { return stringdup((Geometry::GetTypeNameStatic ()).CString ()); } DllExport void * Geometry_Geometry (Urho3D::Context * context) { return WeakPtr<Geometry>(new Geometry(context)); } DllExport int Geometry_SetNumVertexBuffers (Urho3D::Geometry *_target, unsigned int num) { return _target->SetNumVertexBuffers (num); } DllExport int Geometry_SetVertexBuffer (Urho3D::Geometry *_target, unsigned int index, Urho3D::VertexBuffer * buffer) { return _target->SetVertexBuffer (index, buffer); } DllExport void Geometry_SetIndexBuffer (Urho3D::Geometry *_target, Urho3D::IndexBuffer * buffer) { _target->SetIndexBuffer (buffer); } DllExport int Geometry_SetDrawRange (Urho3D::Geometry *_target, enum Urho3D::PrimitiveType type, unsigned int indexStart, unsigned int indexCount, bool getUsedVertexRange) { return _target->SetDrawRange (type, indexStart, indexCount, getUsedVertexRange); } DllExport int Geometry_SetDrawRange0 (Urho3D::Geometry *_target, enum Urho3D::PrimitiveType type, unsigned int indexStart, unsigned int indexCount, unsigned int vertexStart, unsigned int vertexCount, bool checkIllegal) { return _target->SetDrawRange (type, indexStart, indexCount, vertexStart, vertexCount, checkIllegal); } DllExport void Geometry_SetLodDistance (Urho3D::Geometry *_target, float distance) { _target->SetLodDistance (distance); } DllExport void Geometry_Draw (Urho3D::Geometry *_target, Urho3D::Graphics * graphics) { _target->Draw (graphics); } DllExport const Vector<SharedPtr<class Urho3D::VertexBuffer> > & Geometry_GetVertexBuffers (Urho3D::Geometry *_target) { return _target->GetVertexBuffers (); } DllExport unsigned int Geometry_GetNumVertexBuffers (Urho3D::Geometry *_target) { return _target->GetNumVertexBuffers (); } DllExport Urho3D::VertexBuffer * Geometry_GetVertexBuffer (Urho3D::Geometry *_target, unsigned int index) { return _target->GetVertexBuffer (index); } DllExport Urho3D::IndexBuffer * Geometry_GetIndexBuffer (Urho3D::Geometry *_target) { return _target->GetIndexBuffer (); } DllExport enum Urho3D::PrimitiveType Geometry_GetPrimitiveType (Urho3D::Geometry *_target) { return _target->GetPrimitiveType (); } DllExport unsigned int Geometry_GetIndexStart (Urho3D::Geometry *_target) { return _target->GetIndexStart (); } DllExport unsigned int Geometry_GetIndexCount (Urho3D::Geometry *_target) { return _target->GetIndexCount (); } DllExport unsigned int Geometry_GetVertexStart (Urho3D::Geometry *_target) { return _target->GetVertexStart (); } DllExport unsigned int Geometry_GetVertexCount (Urho3D::Geometry *_target) { return _target->GetVertexCount (); } DllExport float Geometry_GetLodDistance (Urho3D::Geometry *_target) { return _target->GetLodDistance (); } DllExport unsigned short Geometry_GetBufferHash (Urho3D::Geometry *_target) { return _target->GetBufferHash (); } DllExport float Geometry_GetHitDistance (Urho3D::Geometry *_target, const class Urho3D::Ray & ray, Urho3D::Vector3 * outNormal, Urho3D::Vector2 * outUV) { return _target->GetHitDistance (ray, outNormal, outUV); } DllExport int Geometry_IsInside (Urho3D::Geometry *_target, const class Urho3D::Ray & ray) { return _target->IsInside (ray); } DllExport int Geometry_IsEmpty (Urho3D::Geometry *_target) { return _target->IsEmpty (); } DllExport GPUObject* ShaderVariation_CastToGPUObject(Urho3D::ShaderVariation *_target) { return static_cast<GPUObject*>(_target); } DllExport void * ShaderVariation_ShaderVariation (Urho3D::Shader * owner, enum Urho3D::ShaderType type) { return WeakPtr<ShaderVariation>(new ShaderVariation(owner, type)); } DllExport void ShaderVariation_Release (Urho3D::ShaderVariation *_target) { _target->Release (); } DllExport int ShaderVariation_Create (Urho3D::ShaderVariation *_target) { return _target->Create (); } DllExport void ShaderVariation_SetName (Urho3D::ShaderVariation *_target, const char * name) { _target->SetName (Urho3D::String(name)); } DllExport void ShaderVariation_SetDefines (Urho3D::ShaderVariation *_target, const char * defines) { _target->SetDefines (Urho3D::String(defines)); } DllExport Urho3D::Shader * ShaderVariation_GetOwner (Urho3D::ShaderVariation *_target) { return _target->GetOwner (); } DllExport enum Urho3D::ShaderType ShaderVariation_GetShaderType (Urho3D::ShaderVariation *_target) { return _target->GetShaderType (); } DllExport const char * ShaderVariation_GetName (Urho3D::ShaderVariation *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport const char * ShaderVariation_GetFullName (Urho3D::ShaderVariation *_target) { return stringdup((_target->GetFullName ()).CString ()); } DllExport int ShaderVariation_HasParameter (Urho3D::ShaderVariation *_target, int param) { return _target->HasParameter (Urho3D::StringHash(param)); } DllExport int ShaderVariation_HasTextureUnit (Urho3D::ShaderVariation *_target, enum Urho3D::TextureUnit unit) { return _target->HasTextureUnit (unit); } DllExport unsigned long long ShaderVariation_GetElementHash (Urho3D::ShaderVariation *_target) { return _target->GetElementHash (); } DllExport const char * ShaderVariation_GetDefines (Urho3D::ShaderVariation *_target) { return stringdup((_target->GetDefines ()).CString ()); } DllExport const char * ShaderVariation_GetCompilerOutput (Urho3D::ShaderVariation *_target) { return stringdup((_target->GetCompilerOutput ()).CString ()); } DllExport const unsigned int * ShaderVariation_GetConstantBufferSizes (Urho3D::ShaderVariation *_target) { return _target->GetConstantBufferSizes (); } DllExport const char * ShaderVariation_GetDefinesClipPlane (Urho3D::ShaderVariation *_target) { return stringdup((_target->GetDefinesClipPlane ()).CString ()); } DllExport int Image_GetType (Urho3D::Image *_target) { return (_target->GetType ()).Value (); } DllExport const char * Image_GetTypeName (Urho3D::Image *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Image_GetTypeStatic () { return (Image::GetTypeStatic ()).Value (); } DllExport const char * Image_GetTypeNameStatic () { return stringdup((Image::GetTypeNameStatic ()).CString ()); } DllExport void * Image_Image (Urho3D::Context * context) { return WeakPtr<Image>(new Image(context)); } DllExport void Image_RegisterObject (Urho3D::Context * context) { Image::RegisterObject (context); } DllExport int Image_BeginLoad_File (Urho3D::Image *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Image_BeginLoad_MemoryBuffer (Urho3D::Image *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Image_Save_File (Urho3D::Image *_target, File * dest) { return _target->Save (*dest); } DllExport int Image_Save_MemoryBuffer (Urho3D::Image *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int Image_SaveFile (Urho3D::Image *_target, const char * fileName) { return _target->SaveFile (Urho3D::String(fileName)); } DllExport int Image_SetSize (Urho3D::Image *_target, int width, int height, unsigned int components) { return _target->SetSize (width, height, components); } DllExport int Image_SetSize0 (Urho3D::Image *_target, int width, int height, int depth, unsigned int components) { return _target->SetSize (width, height, depth, components); } DllExport void Image_SetData (Urho3D::Image *_target, const unsigned char * pixelData) { _target->SetData (pixelData); } DllExport void Image_SetPixel (Urho3D::Image *_target, int x, int y, const class Urho3D::Color & color) { _target->SetPixel (x, y, color); } DllExport void Image_SetPixel1 (Urho3D::Image *_target, int x, int y, int z, const class Urho3D::Color & color) { _target->SetPixel (x, y, z, color); } DllExport void Image_SetPixelInt (Urho3D::Image *_target, int x, int y, unsigned int uintColor) { _target->SetPixelInt (x, y, uintColor); } DllExport void Image_SetPixelInt2 (Urho3D::Image *_target, int x, int y, int z, unsigned int uintColor) { _target->SetPixelInt (x, y, z, uintColor); } DllExport int Image_LoadColorLUT_File (Urho3D::Image *_target, File * source) { return _target->LoadColorLUT (*source); } DllExport int Image_LoadColorLUT_MemoryBuffer (Urho3D::Image *_target, MemoryBuffer * source) { return _target->LoadColorLUT (*source); } DllExport int Image_FlipHorizontal (Urho3D::Image *_target) { return _target->FlipHorizontal (); } DllExport int Image_FlipVertical (Urho3D::Image *_target) { return _target->FlipVertical (); } DllExport int Image_Resize (Urho3D::Image *_target, int width, int height) { return _target->Resize (width, height); } DllExport void Image_Clear (Urho3D::Image *_target, const class Urho3D::Color & color) { _target->Clear (color); } DllExport void Image_ClearInt (Urho3D::Image *_target, unsigned int uintColor) { _target->ClearInt (uintColor); } DllExport int Image_SaveBMP (Urho3D::Image *_target, const char * fileName) { return _target->SaveBMP (Urho3D::String(fileName)); } DllExport int Image_SavePNG (Urho3D::Image *_target, const char * fileName) { return _target->SavePNG (Urho3D::String(fileName)); } DllExport int Image_SaveTGA (Urho3D::Image *_target, const char * fileName) { return _target->SaveTGA (Urho3D::String(fileName)); } DllExport int Image_SaveJPG (Urho3D::Image *_target, const char * fileName, int quality) { return _target->SaveJPG (Urho3D::String(fileName), quality); } DllExport int Image_SaveDDS (Urho3D::Image *_target, const char * fileName) { return _target->SaveDDS (Urho3D::String(fileName)); } DllExport int Image_SaveWEBP (Urho3D::Image *_target, const char * fileName, float compression) { return _target->SaveWEBP (Urho3D::String(fileName), compression); } DllExport int Image_IsCubemap (Urho3D::Image *_target) { return _target->IsCubemap (); } DllExport int Image_IsArray (Urho3D::Image *_target) { return _target->IsArray (); } DllExport int Image_IsSRGB (Urho3D::Image *_target) { return _target->IsSRGB (); } DllExport Interop::Color Image_GetPixel (Urho3D::Image *_target, int x, int y) { return *((Interop::Color *) &(_target->GetPixel (x, y))); } DllExport Interop::Color Image_GetPixel3 (Urho3D::Image *_target, int x, int y, int z) { return *((Interop::Color *) &(_target->GetPixel (x, y, z))); } DllExport unsigned int Image_GetPixelInt (Urho3D::Image *_target, int x, int y) { return _target->GetPixelInt (x, y); } DllExport unsigned int Image_GetPixelInt4 (Urho3D::Image *_target, int x, int y, int z) { return _target->GetPixelInt (x, y, z); } DllExport Interop::Color Image_GetPixelBilinear (Urho3D::Image *_target, float x, float y) { return *((Interop::Color *) &(_target->GetPixelBilinear (x, y))); } DllExport Interop::Color Image_GetPixelTrilinear (Urho3D::Image *_target, float x, float y, float z) { return *((Interop::Color *) &(_target->GetPixelTrilinear (x, y, z))); } DllExport int Image_GetWidth (Urho3D::Image *_target) { return _target->GetWidth (); } DllExport int Image_GetHeight (Urho3D::Image *_target) { return _target->GetHeight (); } DllExport int Image_GetDepth (Urho3D::Image *_target) { return _target->GetDepth (); } DllExport unsigned int Image_GetComponents (Urho3D::Image *_target) { return _target->GetComponents (); } DllExport unsigned char * Image_GetData (Urho3D::Image *_target) { return _target->GetData (); } DllExport int Image_IsCompressed (Urho3D::Image *_target) { return _target->IsCompressed (); } DllExport enum Urho3D::CompressedFormat Image_GetCompressedFormat (Urho3D::Image *_target) { return _target->GetCompressedFormat (); } DllExport unsigned int Image_GetNumCompressedLevels (Urho3D::Image *_target) { return _target->GetNumCompressedLevels (); } DllExport Urho3D::Image * Image_GetNextLevel (Urho3D::Image *_target) { auto copy = _target->GetNextLevel (); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::Image * Image_GetNextSibling (Urho3D::Image *_target) { auto copy = _target->GetNextSibling (); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::Image * Image_ConvertToRGBA (Urho3D::Image *_target) { auto copy = _target->ConvertToRGBA (); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::CompressedLevel Image_GetCompressedLevel (Urho3D::Image *_target, unsigned int index) { return _target->GetCompressedLevel (index); } DllExport Urho3D::Image * Image_GetSubimage (Urho3D::Image *_target, const class Urho3D::IntRect & rect) { return _target->GetSubimage (rect); } DllExport void Image_PrecalculateLevels (Urho3D::Image *_target) { _target->PrecalculateLevels (); } DllExport int Image_HasAlphaChannel (Urho3D::Image *_target) { return _target->HasAlphaChannel (); } DllExport int Image_SetSubimage (Urho3D::Image *_target, const class Urho3D::Image * image, const class Urho3D::IntRect & rect) { return _target->SetSubimage (image, rect); } DllExport void Image_CleanupLevels (Urho3D::Image *_target) { _target->CleanupLevels (); } DllExport int Graphics_GetType (Urho3D::Graphics *_target) { return (_target->GetType ()).Value (); } DllExport const char * Graphics_GetTypeName (Urho3D::Graphics *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Graphics_GetTypeStatic () { return (Graphics::GetTypeStatic ()).Value (); } DllExport const char * Graphics_GetTypeNameStatic () { return stringdup((Graphics::GetTypeNameStatic ()).CString ()); } DllExport void * Graphics_Graphics (Urho3D::Context * context) { return WeakPtr<Graphics>(new Graphics(context)); } DllExport void Graphics_SetExternalWindow (Urho3D::Graphics *_target, void * window) { _target->SetExternalWindow (window); } DllExport void Graphics_SetWindowTitle (Urho3D::Graphics *_target, const char * windowTitle) { _target->SetWindowTitle (Urho3D::String(windowTitle)); } DllExport void Graphics_SetWindowIcon (Urho3D::Graphics *_target, Urho3D::Image * windowIcon) { _target->SetWindowIcon (windowIcon); } DllExport void Graphics_SetWindowPosition (Urho3D::Graphics *_target, const class Urho3D::IntVector2 & position) { _target->SetWindowPosition (position); } DllExport void Graphics_SetWindowPosition0 (Urho3D::Graphics *_target, int x, int y) { _target->SetWindowPosition (x, y); } DllExport int Graphics_SetMode (Urho3D::Graphics *_target, int width, int height, bool fullscreen, bool borderless, bool resizable, bool highDPI, bool vsync, bool tripleBuffer, int multiSample, int monitor, int refreshRate) { return _target->SetMode (width, height, fullscreen, borderless, resizable, highDPI, vsync, tripleBuffer, multiSample, monitor, refreshRate); } DllExport int Graphics_SetMode1 (Urho3D::Graphics *_target, int width, int height) { return _target->SetMode (width, height); } DllExport void Graphics_SetSRGB (Urho3D::Graphics *_target, bool enable) { _target->SetSRGB (enable); } DllExport void Graphics_SetDither (Urho3D::Graphics *_target, bool enable) { _target->SetDither (enable); } DllExport void Graphics_SetFlushGPU (Urho3D::Graphics *_target, bool enable) { _target->SetFlushGPU (enable); } DllExport void Graphics_SetOrientations (Urho3D::Graphics *_target, const char * orientations) { _target->SetOrientations (Urho3D::String(orientations)); } DllExport int Graphics_ToggleFullscreen (Urho3D::Graphics *_target) { return _target->ToggleFullscreen (); } DllExport void Graphics_Close (Urho3D::Graphics *_target) { _target->Close (); } DllExport int Graphics_TakeScreenShot (Urho3D::Graphics *_target, Image * destImage) { return _target->TakeScreenShot (*destImage); } DllExport int Graphics_BeginFrame (Urho3D::Graphics *_target) { return _target->BeginFrame (); } DllExport void Graphics_EndFrame (Urho3D::Graphics *_target) { _target->EndFrame (); } DllExport void Graphics_Clear (Urho3D::Graphics *_target, unsigned int flags, const class Urho3D::Color & color, float depth, unsigned int stencil) { _target->Clear (flags, color, depth, stencil); } DllExport int Graphics_ResolveToTexture (Urho3D::Graphics *_target, Urho3D::Texture2D * destination, const class Urho3D::IntRect & viewport) { return _target->ResolveToTexture (destination, viewport); } DllExport int Graphics_ResolveToTexture2 (Urho3D::Graphics *_target, Urho3D::Texture2D * texture) { return _target->ResolveToTexture (texture); } DllExport int Graphics_ResolveToTexture3 (Urho3D::Graphics *_target, Urho3D::TextureCube * texture) { return _target->ResolveToTexture (texture); } DllExport void Graphics_Draw (Urho3D::Graphics *_target, enum Urho3D::PrimitiveType type, unsigned int vertexStart, unsigned int vertexCount) { _target->Draw (type, vertexStart, vertexCount); } DllExport void Graphics_Draw4 (Urho3D::Graphics *_target, enum Urho3D::PrimitiveType type, unsigned int indexStart, unsigned int indexCount, unsigned int minVertex, unsigned int vertexCount) { _target->Draw (type, indexStart, indexCount, minVertex, vertexCount); } DllExport void Graphics_Draw5 (Urho3D::Graphics *_target, enum Urho3D::PrimitiveType type, unsigned int indexStart, unsigned int indexCount, unsigned int baseVertexIndex, unsigned int minVertex, unsigned int vertexCount) { _target->Draw (type, indexStart, indexCount, baseVertexIndex, minVertex, vertexCount); } DllExport void Graphics_DrawInstanced (Urho3D::Graphics *_target, enum Urho3D::PrimitiveType type, unsigned int indexStart, unsigned int indexCount, unsigned int minVertex, unsigned int vertexCount, unsigned int instanceCount) { _target->DrawInstanced (type, indexStart, indexCount, minVertex, vertexCount, instanceCount); } DllExport void Graphics_DrawInstanced6 (Urho3D::Graphics *_target, enum Urho3D::PrimitiveType type, unsigned int indexStart, unsigned int indexCount, unsigned int baseVertexIndex, unsigned int minVertex, unsigned int vertexCount, unsigned int instanceCount) { _target->DrawInstanced (type, indexStart, indexCount, baseVertexIndex, minVertex, vertexCount, instanceCount); } DllExport void Graphics_SetVertexBuffer (Urho3D::Graphics *_target, Urho3D::VertexBuffer * buffer) { _target->SetVertexBuffer (buffer); } DllExport void Graphics_SetIndexBuffer (Urho3D::Graphics *_target, Urho3D::IndexBuffer * buffer) { _target->SetIndexBuffer (buffer); } DllExport void Graphics_SetShaders (Urho3D::Graphics *_target, Urho3D::ShaderVariation * vs, Urho3D::ShaderVariation * ps) { _target->SetShaders (vs, ps); } DllExport void Graphics_SetShaderParameter (Urho3D::Graphics *_target, int param, const float * data, unsigned int count) { _target->SetShaderParameter (Urho3D::StringHash(param), data, count); } DllExport void Graphics_SetShaderParameter7 (Urho3D::Graphics *_target, int param, float value) { _target->SetShaderParameter (Urho3D::StringHash(param), value); } DllExport void Graphics_SetShaderParameter8 (Urho3D::Graphics *_target, int param, int value) { _target->SetShaderParameter (Urho3D::StringHash(param), value); } DllExport void Graphics_SetShaderParameter9 (Urho3D::Graphics *_target, int param, bool value) { _target->SetShaderParameter (Urho3D::StringHash(param), value); } DllExport void Graphics_SetShaderParameter10 (Urho3D::Graphics *_target, int param, const class Urho3D::Color & color) { _target->SetShaderParameter (Urho3D::StringHash(param), color); } DllExport void Graphics_SetShaderParameter11 (Urho3D::Graphics *_target, int param, const class Urho3D::Vector2 & vector) { _target->SetShaderParameter (Urho3D::StringHash(param), vector); } DllExport void Graphics_SetShaderParameter12 (Urho3D::Graphics *_target, int param, const class Urho3D::Vector3 & vector) { _target->SetShaderParameter (Urho3D::StringHash(param), vector); } DllExport void Graphics_SetShaderParameter13 (Urho3D::Graphics *_target, int param, const class Urho3D::Matrix4 & matrix) { _target->SetShaderParameter (Urho3D::StringHash(param), matrix); } DllExport void Graphics_SetShaderParameter14 (Urho3D::Graphics *_target, int param, const class Urho3D::Vector4 & vector) { _target->SetShaderParameter (Urho3D::StringHash(param), vector); } DllExport void Graphics_SetShaderParameter15 (Urho3D::Graphics *_target, int param, const class Urho3D::Matrix3x4 & matrix) { _target->SetShaderParameter (Urho3D::StringHash(param), matrix); } DllExport int Graphics_NeedParameterUpdate (Urho3D::Graphics *_target, enum Urho3D::ShaderParameterGroup group, const void * source) { return _target->NeedParameterUpdate (group, source); } DllExport int Graphics_HasShaderParameter (Urho3D::Graphics *_target, int param) { return _target->HasShaderParameter (Urho3D::StringHash(param)); } DllExport int Graphics_HasTextureUnit (Urho3D::Graphics *_target, enum Urho3D::TextureUnit unit) { return _target->HasTextureUnit (unit); } DllExport void Graphics_ClearParameterSource (Urho3D::Graphics *_target, enum Urho3D::ShaderParameterGroup group) { _target->ClearParameterSource (group); } DllExport void Graphics_ClearParameterSources (Urho3D::Graphics *_target) { _target->ClearParameterSources (); } DllExport void Graphics_ClearTransformSources (Urho3D::Graphics *_target) { _target->ClearTransformSources (); } DllExport void Graphics_SetTexture (Urho3D::Graphics *_target, unsigned int index, Urho3D::Texture * texture) { _target->SetTexture (index, texture); } DllExport void Graphics_SetTextureParametersDirty (Urho3D::Graphics *_target) { _target->SetTextureParametersDirty (); } DllExport void Graphics_SetDefaultTextureFilterMode (Urho3D::Graphics *_target, enum Urho3D::TextureFilterMode mode) { _target->SetDefaultTextureFilterMode (mode); } DllExport void Graphics_SetDefaultTextureAnisotropy (Urho3D::Graphics *_target, unsigned int level) { _target->SetDefaultTextureAnisotropy (level); } DllExport void Graphics_ResetRenderTargets (Urho3D::Graphics *_target) { _target->ResetRenderTargets (); } DllExport void Graphics_ResetRenderTarget (Urho3D::Graphics *_target, unsigned int index) { _target->ResetRenderTarget (index); } DllExport void Graphics_ResetDepthStencil (Urho3D::Graphics *_target) { _target->ResetDepthStencil (); } DllExport void Graphics_SetRenderTarget (Urho3D::Graphics *_target, unsigned int index, Urho3D::RenderSurface * renderTarget) { _target->SetRenderTarget (index, renderTarget); } DllExport void Graphics_SetRenderTarget16 (Urho3D::Graphics *_target, unsigned int index, Urho3D::Texture2D * texture) { _target->SetRenderTarget (index, texture); } DllExport void Graphics_SetDepthStencil (Urho3D::Graphics *_target, Urho3D::RenderSurface * depthStencil) { _target->SetDepthStencil (depthStencil); } DllExport void Graphics_SetDepthStencil17 (Urho3D::Graphics *_target, Urho3D::Texture2D * texture) { _target->SetDepthStencil (texture); } DllExport void Graphics_SetViewport (Urho3D::Graphics *_target, const class Urho3D::IntRect & rect) { _target->SetViewport (rect); } DllExport void Graphics_SetBlendMode (Urho3D::Graphics *_target, enum Urho3D::BlendMode mode, bool alphaToCoverage) { _target->SetBlendMode (mode, alphaToCoverage); } DllExport void Graphics_SetColorWrite (Urho3D::Graphics *_target, bool enable) { _target->SetColorWrite (enable); } DllExport void Graphics_SetCullMode (Urho3D::Graphics *_target, enum Urho3D::CullMode mode) { _target->SetCullMode (mode); } DllExport void Graphics_SetDepthBias (Urho3D::Graphics *_target, float constantBias, float slopeScaledBias) { _target->SetDepthBias (constantBias, slopeScaledBias); } DllExport void Graphics_SetDepthTest (Urho3D::Graphics *_target, enum Urho3D::CompareMode mode) { _target->SetDepthTest (mode); } DllExport void Graphics_SetDepthWrite (Urho3D::Graphics *_target, bool enable) { _target->SetDepthWrite (enable); } DllExport void Graphics_SetFillMode (Urho3D::Graphics *_target, enum Urho3D::FillMode mode) { _target->SetFillMode (mode); } DllExport void Graphics_SetStereo (Urho3D::Graphics *_target, bool stereo) { _target->SetStereo (stereo); } DllExport void Graphics_SetLineAntiAlias (Urho3D::Graphics *_target, bool enable) { _target->SetLineAntiAlias (enable); } DllExport void Graphics_SetScissorTest (Urho3D::Graphics *_target, bool enable, const class Urho3D::IntRect & rect) { _target->SetScissorTest (enable, rect); } DllExport void Graphics_SetStencilTest (Urho3D::Graphics *_target, bool enable, enum Urho3D::CompareMode mode, enum Urho3D::StencilOp pass, enum Urho3D::StencilOp fail, enum Urho3D::StencilOp zFail, unsigned int stencilRef, unsigned int compareMask, unsigned int writeMask) { _target->SetStencilTest (enable, mode, pass, fail, zFail, stencilRef, compareMask, writeMask); } DllExport void Graphics_SetClipPlane (Urho3D::Graphics *_target, bool enable, const class Urho3D::Plane & clipPlane, const class Urho3D::Matrix3x4 & view, const class Urho3D::Matrix4 & projection) { _target->SetClipPlane (enable, clipPlane, view, projection); } DllExport void Graphics_BeginDumpShaders (Urho3D::Graphics *_target, const char * fileName) { _target->BeginDumpShaders (Urho3D::String(fileName)); } DllExport void Graphics_EndDumpShaders (Urho3D::Graphics *_target) { _target->EndDumpShaders (); } DllExport void Graphics_PrecacheShaders_File (Urho3D::Graphics *_target, File * source) { _target->PrecacheShaders (*source); } DllExport void Graphics_PrecacheShaders_MemoryBuffer (Urho3D::Graphics *_target, MemoryBuffer * source) { _target->PrecacheShaders (*source); } DllExport void Graphics_SetShaderCacheDir (Urho3D::Graphics *_target, const char * path) { _target->SetShaderCacheDir (Urho3D::String(path)); } DllExport int Graphics_IsInitialized (Urho3D::Graphics *_target) { return _target->IsInitialized (); } DllExport Urho3D::GraphicsImpl * Graphics_GetImpl (Urho3D::Graphics *_target) { return _target->GetImpl (); } DllExport void * Graphics_GetExternalWindow (Urho3D::Graphics *_target) { return _target->GetExternalWindow (); } DllExport const char * Graphics_GetWindowTitle (Urho3D::Graphics *_target) { return stringdup((_target->GetWindowTitle ()).CString ()); } DllExport const char * Graphics_GetApiName (Urho3D::Graphics *_target) { return stringdup((_target->GetApiName ()).CString ()); } DllExport Interop::IntVector2 Graphics_GetWindowPosition (Urho3D::Graphics *_target) { return *((Interop::IntVector2 *) &(_target->GetWindowPosition ())); } DllExport int Graphics_GetWidth (Urho3D::Graphics *_target) { return _target->GetWidth (); } DllExport int Graphics_GetHeight (Urho3D::Graphics *_target) { return _target->GetHeight (); } DllExport int Graphics_GetMultiSample (Urho3D::Graphics *_target) { return _target->GetMultiSample (); } DllExport Interop::IntVector2 Graphics_GetSize (Urho3D::Graphics *_target) { return *((Interop::IntVector2 *) &(_target->GetSize ())); } DllExport int Graphics_GetFullscreen (Urho3D::Graphics *_target) { return _target->GetFullscreen (); } DllExport int Graphics_GetBorderless (Urho3D::Graphics *_target) { return _target->GetBorderless (); } DllExport int Graphics_GetResizable (Urho3D::Graphics *_target) { return _target->GetResizable (); } DllExport int Graphics_GetHighDPI (Urho3D::Graphics *_target) { return _target->GetHighDPI (); } DllExport int Graphics_GetVSync (Urho3D::Graphics *_target) { return _target->GetVSync (); } DllExport int Graphics_GetRefreshRate (Urho3D::Graphics *_target) { return _target->GetRefreshRate (); } DllExport int Graphics_GetMonitor (Urho3D::Graphics *_target) { return _target->GetMonitor (); } DllExport int Graphics_GetTripleBuffer (Urho3D::Graphics *_target) { return _target->GetTripleBuffer (); } DllExport int Graphics_GetSRGB (Urho3D::Graphics *_target) { return _target->GetSRGB (); } DllExport int Graphics_GetDither (Urho3D::Graphics *_target) { return _target->GetDither (); } DllExport int Graphics_GetFlushGPU (Urho3D::Graphics *_target) { return _target->GetFlushGPU (); } DllExport const char * Graphics_GetOrientations (Urho3D::Graphics *_target) { return stringdup((_target->GetOrientations ()).CString ()); } DllExport int Graphics_IsDeviceLost (Urho3D::Graphics *_target) { return _target->IsDeviceLost (); } DllExport unsigned int Graphics_GetNumPrimitives (Urho3D::Graphics *_target) { return _target->GetNumPrimitives (); } DllExport unsigned int Graphics_GetNumBatches (Urho3D::Graphics *_target) { return _target->GetNumBatches (); } DllExport unsigned int Graphics_GetDummyColorFormat (Urho3D::Graphics *_target) { return _target->GetDummyColorFormat (); } DllExport unsigned int Graphics_GetShadowMapFormat (Urho3D::Graphics *_target) { return _target->GetShadowMapFormat (); } DllExport unsigned int Graphics_GetHiresShadowMapFormat (Urho3D::Graphics *_target) { return _target->GetHiresShadowMapFormat (); } DllExport int Graphics_GetInstancingSupport (Urho3D::Graphics *_target) { return _target->GetInstancingSupport (); } DllExport int Graphics_GetLightPrepassSupport (Urho3D::Graphics *_target) { return _target->GetLightPrepassSupport (); } DllExport int Graphics_GetDeferredSupport (Urho3D::Graphics *_target) { return _target->GetDeferredSupport (); } DllExport int Graphics_GetHardwareShadowSupport (Urho3D::Graphics *_target) { return _target->GetHardwareShadowSupport (); } DllExport int Graphics_GetReadableDepthSupport (Urho3D::Graphics *_target) { return _target->GetReadableDepthSupport (); } DllExport int Graphics_GetSRGBSupport (Urho3D::Graphics *_target) { return _target->GetSRGBSupport (); } DllExport int Graphics_GetSRGBWriteSupport (Urho3D::Graphics *_target) { return _target->GetSRGBWriteSupport (); } DllExport Interop::IntVector2 Graphics_GetDesktopResolution (Urho3D::Graphics *_target, int monitor) { return *((Interop::IntVector2 *) &(_target->GetDesktopResolution (monitor))); } DllExport int Graphics_GetMonitorCount (Urho3D::Graphics *_target) { return _target->GetMonitorCount (); } DllExport int Graphics_GetCurrentMonitor (Urho3D::Graphics *_target) { return _target->GetCurrentMonitor (); } DllExport int Graphics_GetMaximized (Urho3D::Graphics *_target) { return _target->GetMaximized (); } DllExport Interop::Vector3 Graphics_GetDisplayDPI (Urho3D::Graphics *_target, int monitor) { return *((Interop::Vector3 *) &(_target->GetDisplayDPI (monitor))); } DllExport unsigned int Graphics_GetFormat (Urho3D::Graphics *_target, enum Urho3D::CompressedFormat format) { return _target->GetFormat (format); } DllExport Urho3D::ShaderVariation * Graphics_GetShader (Urho3D::Graphics *_target, enum Urho3D::ShaderType type, const char * name, const char * defines) { return _target->GetShader (type, Urho3D::String(name), Urho3D::String(defines)); } DllExport Urho3D::VertexBuffer * Graphics_GetVertexBuffer (Urho3D::Graphics *_target, unsigned int index) { return _target->GetVertexBuffer (index); } DllExport Urho3D::IndexBuffer * Graphics_GetIndexBuffer (Urho3D::Graphics *_target) { return _target->GetIndexBuffer (); } DllExport Urho3D::ShaderVariation * Graphics_GetVertexShader (Urho3D::Graphics *_target) { return _target->GetVertexShader (); } DllExport Urho3D::ShaderVariation * Graphics_GetPixelShader (Urho3D::Graphics *_target) { return _target->GetPixelShader (); } DllExport enum Urho3D::TextureUnit Graphics_GetTextureUnit (Urho3D::Graphics *_target, const char * name) { return _target->GetTextureUnit (Urho3D::String(name)); } DllExport const char * Graphics_GetTextureUnitName (Urho3D::Graphics *_target, enum Urho3D::TextureUnit unit) { return stringdup((_target->GetTextureUnitName (unit)).CString ()); } DllExport Urho3D::Texture * Graphics_GetTexture (Urho3D::Graphics *_target, unsigned int index) { return _target->GetTexture (index); } DllExport enum Urho3D::TextureFilterMode Graphics_GetDefaultTextureFilterMode (Urho3D::Graphics *_target) { return _target->GetDefaultTextureFilterMode (); } DllExport unsigned int Graphics_GetDefaultTextureAnisotropy (Urho3D::Graphics *_target) { return _target->GetDefaultTextureAnisotropy (); } DllExport Urho3D::RenderSurface * Graphics_GetRenderTarget (Urho3D::Graphics *_target, unsigned int index) { return _target->GetRenderTarget (index); } DllExport Urho3D::RenderSurface * Graphics_GetDepthStencil (Urho3D::Graphics *_target) { return _target->GetDepthStencil (); } DllExport Interop::IntRect Graphics_GetViewport (Urho3D::Graphics *_target) { return *((Interop::IntRect *) &(_target->GetViewport ())); } DllExport enum Urho3D::BlendMode Graphics_GetBlendMode (Urho3D::Graphics *_target) { return _target->GetBlendMode (); } DllExport int Graphics_GetAlphaToCoverage (Urho3D::Graphics *_target) { return _target->GetAlphaToCoverage (); } DllExport int Graphics_GetColorWrite (Urho3D::Graphics *_target) { return _target->GetColorWrite (); } DllExport enum Urho3D::CullMode Graphics_GetCullMode (Urho3D::Graphics *_target) { return _target->GetCullMode (); } DllExport float Graphics_GetDepthConstantBias (Urho3D::Graphics *_target) { return _target->GetDepthConstantBias (); } DllExport float Graphics_GetDepthSlopeScaledBias (Urho3D::Graphics *_target) { return _target->GetDepthSlopeScaledBias (); } DllExport enum Urho3D::CompareMode Graphics_GetDepthTest (Urho3D::Graphics *_target) { return _target->GetDepthTest (); } DllExport int Graphics_GetDepthWrite (Urho3D::Graphics *_target) { return _target->GetDepthWrite (); } DllExport enum Urho3D::FillMode Graphics_GetFillMode (Urho3D::Graphics *_target) { return _target->GetFillMode (); } DllExport int Graphics_GetLineAntiAlias (Urho3D::Graphics *_target) { return _target->GetLineAntiAlias (); } DllExport int Graphics_GetStencilTest (Urho3D::Graphics *_target) { return _target->GetStencilTest (); } DllExport int Graphics_GetScissorTest (Urho3D::Graphics *_target) { return _target->GetScissorTest (); } DllExport Interop::IntRect Graphics_GetScissorRect (Urho3D::Graphics *_target) { return *((Interop::IntRect *) &(_target->GetScissorRect ())); } DllExport enum Urho3D::CompareMode Graphics_GetStencilTestMode (Urho3D::Graphics *_target) { return _target->GetStencilTestMode (); } DllExport enum Urho3D::StencilOp Graphics_GetStencilPass (Urho3D::Graphics *_target) { return _target->GetStencilPass (); } DllExport enum Urho3D::StencilOp Graphics_GetStencilFail (Urho3D::Graphics *_target) { return _target->GetStencilFail (); } DllExport enum Urho3D::StencilOp Graphics_GetStencilZFail (Urho3D::Graphics *_target) { return _target->GetStencilZFail (); } DllExport unsigned int Graphics_GetStencilRef (Urho3D::Graphics *_target) { return _target->GetStencilRef (); } DllExport unsigned int Graphics_GetStencilCompareMask (Urho3D::Graphics *_target) { return _target->GetStencilCompareMask (); } DllExport unsigned int Graphics_GetStencilWriteMask (Urho3D::Graphics *_target) { return _target->GetStencilWriteMask (); } DllExport int Graphics_GetUseClipPlane (Urho3D::Graphics *_target) { return _target->GetUseClipPlane (); } DllExport const char * Graphics_GetShaderCacheDir (Urho3D::Graphics *_target) { return stringdup((_target->GetShaderCacheDir ()).CString ()); } DllExport Interop::IntVector2 Graphics_GetRenderTargetDimensions (Urho3D::Graphics *_target) { return *((Interop::IntVector2 *) &(_target->GetRenderTargetDimensions ())); } DllExport void Graphics_OnWindowResized (Urho3D::Graphics *_target) { _target->OnWindowResized (); } DllExport void Graphics_OnWindowMoved (Urho3D::Graphics *_target) { _target->OnWindowMoved (); } DllExport void Graphics_Maximize (Urho3D::Graphics *_target) { _target->Maximize (); } DllExport void Graphics_Minimize (Urho3D::Graphics *_target) { _target->Minimize (); } DllExport void Graphics_Raise (Urho3D::Graphics *_target) { _target->Raise (); } DllExport void Graphics_AddGPUObject (Urho3D::Graphics *_target, Urho3D::GPUObject * object) { _target->AddGPUObject (object); } DllExport void Graphics_RemoveGPUObject (Urho3D::Graphics *_target, Urho3D::GPUObject * object) { _target->RemoveGPUObject (object); } DllExport void * Graphics_ReserveScratchBuffer (Urho3D::Graphics *_target, unsigned int size) { return _target->ReserveScratchBuffer (size); } DllExport void Graphics_FreeScratchBuffer (Urho3D::Graphics *_target, void * buffer) { _target->FreeScratchBuffer (buffer); } DllExport void Graphics_CleanupScratchBuffers (Urho3D::Graphics *_target) { _target->CleanupScratchBuffers (); } DllExport unsigned int Graphics_GetAlphaFormat () { return Graphics::GetAlphaFormat (); } DllExport unsigned int Graphics_GetLuminanceFormat () { return Graphics::GetLuminanceFormat (); } DllExport unsigned int Graphics_GetLuminanceAlphaFormat () { return Graphics::GetLuminanceAlphaFormat (); } DllExport unsigned int Graphics_GetRGBFormat () { return Graphics::GetRGBFormat (); } DllExport unsigned int Graphics_GetRGBAFormat () { return Graphics::GetRGBAFormat (); } DllExport unsigned int Graphics_GetRGBA16Format () { return Graphics::GetRGBA16Format (); } DllExport unsigned int Graphics_GetRGBAFloat16Format () { return Graphics::GetRGBAFloat16Format (); } DllExport unsigned int Graphics_GetRGBAFloat32Format () { return Graphics::GetRGBAFloat32Format (); } DllExport unsigned int Graphics_GetRG16Format () { return Graphics::GetRG16Format (); } DllExport unsigned int Graphics_GetRGFloat16Format () { return Graphics::GetRGFloat16Format (); } DllExport unsigned int Graphics_GetRGFloat32Format () { return Graphics::GetRGFloat32Format (); } DllExport unsigned int Graphics_GetFloat16Format () { return Graphics::GetFloat16Format (); } DllExport unsigned int Graphics_GetFloat32Format () { return Graphics::GetFloat32Format (); } DllExport unsigned int Graphics_GetLinearDepthFormat () { return Graphics::GetLinearDepthFormat (); } DllExport unsigned int Graphics_GetDepthStencilFormat () { return Graphics::GetDepthStencilFormat (); } DllExport unsigned int Graphics_GetReadableDepthFormat () { return Graphics::GetReadableDepthFormat (); } DllExport unsigned int Graphics_GetFormat18 (const char * formatName) { return Graphics::GetFormat (Urho3D::String(formatName)); } DllExport Interop::Vector2 Graphics_GetPixelUVOffset () { return *((Interop::Vector2 *) &(Graphics::GetPixelUVOffset ())); } DllExport unsigned int Graphics_GetMaxBones () { return Graphics::GetMaxBones (); } #if defined(URHO3D_OPENGL) DllExport GPUObject* ShaderProgram_CastToGPUObject(Urho3D::ShaderProgram *_target) { return static_cast<GPUObject*>(_target); } #endif DllExport void * ShaderProgram_ShaderProgram (Urho3D::Graphics * graphics, Urho3D::ShaderVariation * vertexShader, Urho3D::ShaderVariation * pixelShader) { return WeakPtr<ShaderProgram>(new ShaderProgram(graphics, vertexShader, pixelShader)); } DllExport int Viewport_GetType (Urho3D::Viewport *_target) { return (_target->GetType ()).Value (); } DllExport const char * Viewport_GetTypeName (Urho3D::Viewport *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Viewport_GetTypeStatic () { return (Viewport::GetTypeStatic ()).Value (); } DllExport const char * Viewport_GetTypeNameStatic () { return stringdup((Viewport::GetTypeNameStatic ()).CString ()); } DllExport void * Viewport_Viewport (Urho3D::Context * context) { return WeakPtr<Viewport>(new Viewport(context)); } DllExport void * Viewport_Viewport0 (Urho3D::Context * context, Urho3D::Scene * scene, Urho3D::Camera * camera, Urho3D::RenderPath * renderPath) { return WeakPtr<Viewport>(new Viewport(context, scene, camera, renderPath)); } DllExport void * Viewport_Viewport1 (Urho3D::Context * context, Urho3D::Scene * scene, Urho3D::Camera * camera, const class Urho3D::IntRect & rect, Urho3D::RenderPath * renderPath) { return WeakPtr<Viewport>(new Viewport(context, scene, camera, rect, renderPath)); } DllExport void Viewport_SetScene (Urho3D::Viewport *_target, Urho3D::Scene * scene) { _target->SetScene (scene); } DllExport void Viewport_SetCamera (Urho3D::Viewport *_target, Urho3D::Camera * camera) { _target->SetCamera (camera); } DllExport void Viewport_SetRect (Urho3D::Viewport *_target, const class Urho3D::IntRect & rect) { _target->SetRect (rect); } DllExport void Viewport_SetRenderPath (Urho3D::Viewport *_target, Urho3D::RenderPath * path) { _target->SetRenderPath (path); } DllExport void Viewport_SetStereoMode (Urho3D::Viewport *_target, bool stereo) { _target->SetStereoMode (stereo); } DllExport void Viewport_SetRenderPath2 (Urho3D::Viewport *_target, Urho3D::XMLFile * file) { _target->SetRenderPath (file); } DllExport void Viewport_SetDrawDebug (Urho3D::Viewport *_target, bool enable) { _target->SetDrawDebug (enable); } DllExport void Viewport_SetCullCamera (Urho3D::Viewport *_target, Urho3D::Camera * camera) { _target->SetCullCamera (camera); } DllExport Urho3D::Scene * Viewport_GetScene (Urho3D::Viewport *_target) { return _target->GetScene (); } DllExport Urho3D::Camera * Viewport_GetCamera (Urho3D::Viewport *_target) { return _target->GetCamera (); } DllExport Urho3D::View * Viewport_GetView (Urho3D::Viewport *_target) { return _target->GetView (); } DllExport Interop::IntRect Viewport_GetRect (Urho3D::Viewport *_target) { return *((Interop::IntRect *) &(_target->GetRect ())); } DllExport Urho3D::RenderPath * Viewport_GetRenderPath (Urho3D::Viewport *_target) { return _target->GetRenderPath (); } DllExport int Viewport_GetDrawDebug (Urho3D::Viewport *_target) { return _target->GetDrawDebug (); } DllExport Urho3D::Camera * Viewport_GetCullCamera (Urho3D::Viewport *_target) { return _target->GetCullCamera (); } DllExport Urho3D::Ray Viewport_GetScreenRay (Urho3D::Viewport *_target, int x, int y) { return _target->GetScreenRay (x, y); } DllExport Interop::IntVector2 Viewport_WorldToScreenPoint (Urho3D::Viewport *_target, const class Urho3D::Vector3 & worldPos) { return *((Interop::IntVector2 *) &(_target->WorldToScreenPoint (worldPos))); } DllExport Interop::Vector3 Viewport_ScreenToWorldPoint (Urho3D::Viewport *_target, int x, int y, float depth) { return *((Interop::Vector3 *) &(_target->ScreenToWorldPoint (x, y, depth))); } DllExport void Viewport_AllocateView (Urho3D::Viewport *_target) { _target->AllocateView (); } DllExport void * RenderSurface_RenderSurface (Urho3D::Texture * parentTexture) { return WeakPtr<RenderSurface>(new RenderSurface(parentTexture)); } DllExport void RenderSurface_SetNumViewports (Urho3D::RenderSurface *_target, unsigned int num) { _target->SetNumViewports (num); } DllExport void RenderSurface_SetViewport (Urho3D::RenderSurface *_target, unsigned int index, Urho3D::Viewport * viewport) { _target->SetViewport (index, viewport); } DllExport void RenderSurface_SetUpdateMode (Urho3D::RenderSurface *_target, enum Urho3D::RenderSurfaceUpdateMode mode) { _target->SetUpdateMode (mode); } DllExport void RenderSurface_SetLinkedRenderTarget (Urho3D::RenderSurface *_target, Urho3D::RenderSurface * renderTarget) { _target->SetLinkedRenderTarget (renderTarget); } DllExport void RenderSurface_SetLinkedDepthStencil (Urho3D::RenderSurface *_target, Urho3D::RenderSurface * depthStencil) { _target->SetLinkedDepthStencil (depthStencil); } DllExport void RenderSurface_QueueUpdate (Urho3D::RenderSurface *_target) { _target->QueueUpdate (); } DllExport void RenderSurface_Release (Urho3D::RenderSurface *_target) { _target->Release (); } DllExport int RenderSurface_CreateRenderBuffer (Urho3D::RenderSurface *_target, unsigned int width, unsigned int height, unsigned int format, int multiSample) { return _target->CreateRenderBuffer (width, height, format, multiSample); } DllExport int RenderSurface_GetWidth (Urho3D::RenderSurface *_target) { return _target->GetWidth (); } DllExport int RenderSurface_GetHeight (Urho3D::RenderSurface *_target) { return _target->GetHeight (); } DllExport enum Urho3D::TextureUsage RenderSurface_GetUsage (Urho3D::RenderSurface *_target) { return _target->GetUsage (); } DllExport int RenderSurface_GetMultiSample (Urho3D::RenderSurface *_target) { return _target->GetMultiSample (); } DllExport int RenderSurface_GetAutoResolve (Urho3D::RenderSurface *_target) { return _target->GetAutoResolve (); } DllExport unsigned int RenderSurface_GetNumViewports (Urho3D::RenderSurface *_target) { return _target->GetNumViewports (); } DllExport Urho3D::Viewport * RenderSurface_GetViewport (Urho3D::RenderSurface *_target, unsigned int index) { return _target->GetViewport (index); } DllExport enum Urho3D::RenderSurfaceUpdateMode RenderSurface_GetUpdateMode (Urho3D::RenderSurface *_target) { return _target->GetUpdateMode (); } DllExport Urho3D::RenderSurface * RenderSurface_GetLinkedRenderTarget (Urho3D::RenderSurface *_target) { return _target->GetLinkedRenderTarget (); } DllExport Urho3D::RenderSurface * RenderSurface_GetLinkedDepthStencil (Urho3D::RenderSurface *_target) { return _target->GetLinkedDepthStencil (); } DllExport int RenderSurface_IsUpdateQueued (Urho3D::RenderSurface *_target) { return _target->IsUpdateQueued (); } DllExport void RenderSurface_ResetUpdateQueued (Urho3D::RenderSurface *_target) { _target->ResetUpdateQueued (); } DllExport Urho3D::Texture * RenderSurface_GetParentTexture (Urho3D::RenderSurface *_target) { return _target->GetParentTexture (); } DllExport void * RenderSurface_GetSurface (Urho3D::RenderSurface *_target) { return _target->GetSurface (); } DllExport void * RenderSurface_GetRenderTargetView (Urho3D::RenderSurface *_target) { return _target->GetRenderTargetView (); } DllExport void * RenderSurface_GetReadOnlyView (Urho3D::RenderSurface *_target) { return _target->GetReadOnlyView (); } DllExport unsigned int RenderSurface_GetTarget (Urho3D::RenderSurface *_target) { return _target->GetTarget (); } DllExport unsigned int RenderSurface_GetRenderBuffer (Urho3D::RenderSurface *_target) { return _target->GetRenderBuffer (); } DllExport int RenderSurface_IsResolveDirty (Urho3D::RenderSurface *_target) { return _target->IsResolveDirty (); } DllExport void RenderSurface_SetResolveDirty (Urho3D::RenderSurface *_target, bool enable) { _target->SetResolveDirty (enable); } DllExport int Texture2D_GetType (Urho3D::Texture2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * Texture2D_GetTypeName (Urho3D::Texture2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Texture2D_GetTypeStatic () { return (Texture2D::GetTypeStatic ()).Value (); } DllExport const char * Texture2D_GetTypeNameStatic () { return stringdup((Texture2D::GetTypeNameStatic ()).CString ()); } DllExport void * Texture2D_Texture2D (Urho3D::Context * context) { return WeakPtr<Texture2D>(new Texture2D(context)); } DllExport void Texture2D_RegisterObject (Urho3D::Context * context) { Texture2D::RegisterObject (context); } DllExport int Texture2D_BeginLoad_File (Urho3D::Texture2D *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Texture2D_BeginLoad_MemoryBuffer (Urho3D::Texture2D *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Texture2D_EndLoad (Urho3D::Texture2D *_target) { return _target->EndLoad (); } DllExport void Texture2D_Release (Urho3D::Texture2D *_target) { _target->Release (); } DllExport void Texture2D_SetCustomTarget (Urho3D::Texture2D *_target, unsigned int target) { _target->SetCustomTarget (target); } DllExport int Texture2D_SetSize (Urho3D::Texture2D *_target, int width, int height, unsigned int format, enum Urho3D::TextureUsage usage, int multiSample, bool autoResolve) { return _target->SetSize (width, height, format, usage, multiSample, autoResolve); } DllExport int Texture2D_SetData (Urho3D::Texture2D *_target, unsigned int level, int x, int y, int width, int height, const void * data) { return _target->SetData (level, x, y, width, height, data); } DllExport int Texture2D_SetData0 (Urho3D::Texture2D *_target, Urho3D::Image * image, bool useAlpha) { return _target->SetData (image, useAlpha); } DllExport int Texture2D_GetData (Urho3D::Texture2D *_target, unsigned int level, void * dest) { return _target->GetData (level, dest); } DllExport int Texture2D_GetImage (Urho3D::Texture2D *_target, Image * image) { return _target->GetImage (*image); } DllExport Urho3D::Image * Texture2D_GetImage1 (Urho3D::Texture2D *_target) { auto copy = _target->GetImage (); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::RenderSurface * Texture2D_GetRenderSurface (Urho3D::Texture2D *_target) { return _target->GetRenderSurface (); } DllExport GPUObject* IndexBuffer_CastToGPUObject(Urho3D::IndexBuffer *_target) { return static_cast<GPUObject*>(_target); } DllExport int IndexBuffer_GetType (Urho3D::IndexBuffer *_target) { return (_target->GetType ()).Value (); } DllExport const char * IndexBuffer_GetTypeName (Urho3D::IndexBuffer *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int IndexBuffer_GetTypeStatic () { return (IndexBuffer::GetTypeStatic ()).Value (); } DllExport const char * IndexBuffer_GetTypeNameStatic () { return stringdup((IndexBuffer::GetTypeNameStatic ()).CString ()); } DllExport void * IndexBuffer_IndexBuffer (Urho3D::Context * context, bool forceHeadless) { return WeakPtr<IndexBuffer>(new IndexBuffer(context, forceHeadless)); } DllExport void IndexBuffer_OnDeviceLost (Urho3D::IndexBuffer *_target) { _target->OnDeviceLost (); } DllExport void IndexBuffer_Release (Urho3D::IndexBuffer *_target) { _target->Release (); } DllExport void IndexBuffer_SetShadowed (Urho3D::IndexBuffer *_target, bool enable) { _target->SetShadowed (enable); } DllExport int IndexBuffer_SetSize (Urho3D::IndexBuffer *_target, unsigned int indexCount, bool largeIndices, bool dynamic) { return _target->SetSize (indexCount, largeIndices, dynamic); } DllExport int IndexBuffer_SetData (Urho3D::IndexBuffer *_target, const void * data) { return _target->SetData (data); } DllExport int IndexBuffer_SetDataRange (Urho3D::IndexBuffer *_target, const void * data, unsigned int start, unsigned int count, bool discard) { return _target->SetDataRange (data, start, count, discard); } DllExport void * IndexBuffer_Lock (Urho3D::IndexBuffer *_target, unsigned int start, unsigned int count, bool discard) { return _target->Lock (start, count, discard); } DllExport void IndexBuffer_Unlock (Urho3D::IndexBuffer *_target) { _target->Unlock (); } DllExport int IndexBuffer_IsShadowed (Urho3D::IndexBuffer *_target) { return _target->IsShadowed (); } DllExport int IndexBuffer_IsDynamic (Urho3D::IndexBuffer *_target) { return _target->IsDynamic (); } DllExport int IndexBuffer_IsLocked (Urho3D::IndexBuffer *_target) { return _target->IsLocked (); } DllExport unsigned int IndexBuffer_GetIndexCount (Urho3D::IndexBuffer *_target) { return _target->GetIndexCount (); } DllExport unsigned int IndexBuffer_GetIndexSize (Urho3D::IndexBuffer *_target) { return _target->GetIndexSize (); } DllExport unsigned char * IndexBuffer_GetShadowData (Urho3D::IndexBuffer *_target) { return _target->GetShadowData (); } DllExport int OcclusionBuffer_GetType (Urho3D::OcclusionBuffer *_target) { return (_target->GetType ()).Value (); } DllExport const char * OcclusionBuffer_GetTypeName (Urho3D::OcclusionBuffer *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int OcclusionBuffer_GetTypeStatic () { return (OcclusionBuffer::GetTypeStatic ()).Value (); } DllExport const char * OcclusionBuffer_GetTypeNameStatic () { return stringdup((OcclusionBuffer::GetTypeNameStatic ()).CString ()); } DllExport void * OcclusionBuffer_OcclusionBuffer (Urho3D::Context * context) { return WeakPtr<OcclusionBuffer>(new OcclusionBuffer(context)); } DllExport int OcclusionBuffer_SetSize (Urho3D::OcclusionBuffer *_target, int width, int height, bool threaded) { return _target->SetSize (width, height, threaded); } DllExport void OcclusionBuffer_SetView (Urho3D::OcclusionBuffer *_target, Urho3D::Camera * camera) { _target->SetView (camera); } DllExport void OcclusionBuffer_SetMaxTriangles (Urho3D::OcclusionBuffer *_target, unsigned int triangles) { _target->SetMaxTriangles (triangles); } DllExport void OcclusionBuffer_SetCullMode (Urho3D::OcclusionBuffer *_target, enum Urho3D::CullMode mode) { _target->SetCullMode (mode); } DllExport void OcclusionBuffer_Reset (Urho3D::OcclusionBuffer *_target) { _target->Reset (); } DllExport void OcclusionBuffer_Clear (Urho3D::OcclusionBuffer *_target) { _target->Clear (); } DllExport int OcclusionBuffer_AddTriangles (Urho3D::OcclusionBuffer *_target, const class Urho3D::Matrix3x4 & model, const void * vertexData, unsigned int vertexSize, unsigned int vertexStart, unsigned int vertexCount) { return _target->AddTriangles (model, vertexData, vertexSize, vertexStart, vertexCount); } DllExport int OcclusionBuffer_AddTriangles0 (Urho3D::OcclusionBuffer *_target, const class Urho3D::Matrix3x4 & model, const void * vertexData, unsigned int vertexSize, const void * indexData, unsigned int indexSize, unsigned int indexStart, unsigned int indexCount) { return _target->AddTriangles (model, vertexData, vertexSize, indexData, indexSize, indexStart, indexCount); } DllExport void OcclusionBuffer_DrawTriangles (Urho3D::OcclusionBuffer *_target) { _target->DrawTriangles (); } DllExport void OcclusionBuffer_BuildDepthHierarchy (Urho3D::OcclusionBuffer *_target) { _target->BuildDepthHierarchy (); } DllExport void OcclusionBuffer_ResetUseTimer (Urho3D::OcclusionBuffer *_target) { _target->ResetUseTimer (); } DllExport int * OcclusionBuffer_GetBuffer (Urho3D::OcclusionBuffer *_target) { return _target->GetBuffer (); } DllExport Interop::Matrix3x4 OcclusionBuffer_GetView (Urho3D::OcclusionBuffer *_target) { return *((Interop::Matrix3x4 *) &(_target->GetView ())); } DllExport Interop::Matrix4 OcclusionBuffer_GetProjection (Urho3D::OcclusionBuffer *_target) { return *((Interop::Matrix4 *) &(_target->GetProjection ())); } DllExport int OcclusionBuffer_GetWidth (Urho3D::OcclusionBuffer *_target) { return _target->GetWidth (); } DllExport int OcclusionBuffer_GetHeight (Urho3D::OcclusionBuffer *_target) { return _target->GetHeight (); } DllExport unsigned int OcclusionBuffer_GetNumTriangles (Urho3D::OcclusionBuffer *_target) { return _target->GetNumTriangles (); } DllExport unsigned int OcclusionBuffer_GetMaxTriangles (Urho3D::OcclusionBuffer *_target) { return _target->GetMaxTriangles (); } DllExport enum Urho3D::CullMode OcclusionBuffer_GetCullMode (Urho3D::OcclusionBuffer *_target) { return _target->GetCullMode (); } DllExport int OcclusionBuffer_IsThreaded (Urho3D::OcclusionBuffer *_target) { return _target->IsThreaded (); } DllExport int OcclusionBuffer_IsVisible (Urho3D::OcclusionBuffer *_target, const class Urho3D::BoundingBox & worldSpaceBox) { return _target->IsVisible (worldSpaceBox); } DllExport unsigned int OcclusionBuffer_GetUseTimer (Urho3D::OcclusionBuffer *_target) { return _target->GetUseTimer (); } DllExport int Octree_GetType (Urho3D::Octree *_target) { return (_target->GetType ()).Value (); } DllExport const char * Octree_GetTypeName (Urho3D::Octree *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Octree_GetTypeStatic () { return (Octree::GetTypeStatic ()).Value (); } DllExport const char * Octree_GetTypeNameStatic () { return stringdup((Octree::GetTypeNameStatic ()).CString ()); } DllExport void * Octree_Octree (Urho3D::Context * context) { return WeakPtr<Octree>(new Octree(context)); } DllExport void Octree_RegisterObject (Urho3D::Context * context) { Octree::RegisterObject (context); } DllExport void Octree_DrawDebugGeometry (Urho3D::Octree *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void Octree_SetSize (Urho3D::Octree *_target, const class Urho3D::BoundingBox & box, unsigned int numLevels) { _target->SetSize (box, numLevels); } DllExport void Octree_AddManualDrawable (Urho3D::Octree *_target, Urho3D::Drawable * drawable) { _target->AddManualDrawable (drawable); } DllExport void Octree_RemoveManualDrawable (Urho3D::Octree *_target, Urho3D::Drawable * drawable) { _target->RemoveManualDrawable (drawable); } DllExport unsigned int Octree_GetNumLevels (Urho3D::Octree *_target) { return _target->GetNumLevels (); } DllExport void Octree_QueueUpdate (Urho3D::Octree *_target, Urho3D::Drawable * drawable) { _target->QueueUpdate (drawable); } DllExport void Octree_CancelUpdate (Urho3D::Octree *_target, Urho3D::Drawable * drawable) { _target->CancelUpdate (drawable); } DllExport void Octree_DrawDebugGeometry0 (Urho3D::Octree *_target, bool depthTest) { _target->DrawDebugGeometry (depthTest); } DllExport int ParticleEffect_GetType (Urho3D::ParticleEffect *_target) { return (_target->GetType ()).Value (); } DllExport const char * ParticleEffect_GetTypeName (Urho3D::ParticleEffect *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ParticleEffect_GetTypeStatic () { return (ParticleEffect::GetTypeStatic ()).Value (); } DllExport const char * ParticleEffect_GetTypeNameStatic () { return stringdup((ParticleEffect::GetTypeNameStatic ()).CString ()); } DllExport void * ParticleEffect_ParticleEffect (Urho3D::Context * context) { return WeakPtr<ParticleEffect>(new ParticleEffect(context)); } DllExport void ParticleEffect_RegisterObject (Urho3D::Context * context) { ParticleEffect::RegisterObject (context); } DllExport int ParticleEffect_BeginLoad_File (Urho3D::ParticleEffect *_target, File * source) { return _target->BeginLoad (*source); } DllExport int ParticleEffect_BeginLoad_MemoryBuffer (Urho3D::ParticleEffect *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int ParticleEffect_EndLoad (Urho3D::ParticleEffect *_target) { return _target->EndLoad (); } DllExport int ParticleEffect_Save_File (Urho3D::ParticleEffect *_target, File * dest) { return _target->Save (*dest); } DllExport int ParticleEffect_Save_MemoryBuffer (Urho3D::ParticleEffect *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int ParticleEffect_Save0 (Urho3D::ParticleEffect *_target, Urho3D::XMLElement & dest) { return _target->Save (dest); } DllExport int ParticleEffect_Load (Urho3D::ParticleEffect *_target, const class Urho3D::XMLElement & source) { return _target->Load (source); } DllExport void ParticleEffect_SetMaterial (Urho3D::ParticleEffect *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport void ParticleEffect_SetNumParticles (Urho3D::ParticleEffect *_target, unsigned int num) { _target->SetNumParticles (num); } DllExport void ParticleEffect_SetUpdateInvisible (Urho3D::ParticleEffect *_target, bool enable) { _target->SetUpdateInvisible (enable); } DllExport void ParticleEffect_SetRelative (Urho3D::ParticleEffect *_target, bool enable) { _target->SetRelative (enable); } DllExport void ParticleEffect_SetScaled (Urho3D::ParticleEffect *_target, bool enable) { _target->SetScaled (enable); } DllExport void ParticleEffect_SetSorted (Urho3D::ParticleEffect *_target, bool enable) { _target->SetSorted (enable); } DllExport void ParticleEffect_SetFixedScreenSize (Urho3D::ParticleEffect *_target, bool enable) { _target->SetFixedScreenSize (enable); } DllExport void ParticleEffect_SetAnimationLodBias (Urho3D::ParticleEffect *_target, float lodBias) { _target->SetAnimationLodBias (lodBias); } DllExport void ParticleEffect_SetEmitterType (Urho3D::ParticleEffect *_target, enum Urho3D::EmitterType type) { _target->SetEmitterType (type); } DllExport void ParticleEffect_SetEmitterSize (Urho3D::ParticleEffect *_target, const class Urho3D::Vector3 & size) { _target->SetEmitterSize (size); } DllExport void ParticleEffect_SetMinDirection (Urho3D::ParticleEffect *_target, const class Urho3D::Vector3 & direction) { _target->SetMinDirection (direction); } DllExport void ParticleEffect_SetMaxDirection (Urho3D::ParticleEffect *_target, const class Urho3D::Vector3 & direction) { _target->SetMaxDirection (direction); } DllExport void ParticleEffect_SetConstantForce (Urho3D::ParticleEffect *_target, const class Urho3D::Vector3 & force) { _target->SetConstantForce (force); } DllExport void ParticleEffect_SetDampingForce (Urho3D::ParticleEffect *_target, float force) { _target->SetDampingForce (force); } DllExport void ParticleEffect_SetActiveTime (Urho3D::ParticleEffect *_target, float time) { _target->SetActiveTime (time); } DllExport void ParticleEffect_SetInactiveTime (Urho3D::ParticleEffect *_target, float time) { _target->SetInactiveTime (time); } DllExport void ParticleEffect_SetMinEmissionRate (Urho3D::ParticleEffect *_target, float rate) { _target->SetMinEmissionRate (rate); } DllExport void ParticleEffect_SetMaxEmissionRate (Urho3D::ParticleEffect *_target, float rate) { _target->SetMaxEmissionRate (rate); } DllExport void ParticleEffect_SetMinParticleSize (Urho3D::ParticleEffect *_target, const class Urho3D::Vector2 & size) { _target->SetMinParticleSize (size); } DllExport void ParticleEffect_SetMaxParticleSize (Urho3D::ParticleEffect *_target, const class Urho3D::Vector2 & size) { _target->SetMaxParticleSize (size); } DllExport void ParticleEffect_SetMinTimeToLive (Urho3D::ParticleEffect *_target, float time) { _target->SetMinTimeToLive (time); } DllExport void ParticleEffect_SetMaxTimeToLive (Urho3D::ParticleEffect *_target, float time) { _target->SetMaxTimeToLive (time); } DllExport void ParticleEffect_SetMinVelocity (Urho3D::ParticleEffect *_target, float velocity) { _target->SetMinVelocity (velocity); } DllExport void ParticleEffect_SetMaxVelocity (Urho3D::ParticleEffect *_target, float velocity) { _target->SetMaxVelocity (velocity); } DllExport void ParticleEffect_SetMinRotation (Urho3D::ParticleEffect *_target, float rotation) { _target->SetMinRotation (rotation); } DllExport void ParticleEffect_SetMaxRotation (Urho3D::ParticleEffect *_target, float rotation) { _target->SetMaxRotation (rotation); } DllExport void ParticleEffect_SetMinRotationSpeed (Urho3D::ParticleEffect *_target, float speed) { _target->SetMinRotationSpeed (speed); } DllExport void ParticleEffect_SetMaxRotationSpeed (Urho3D::ParticleEffect *_target, float speed) { _target->SetMaxRotationSpeed (speed); } DllExport void ParticleEffect_SetSizeAdd (Urho3D::ParticleEffect *_target, float sizeAdd) { _target->SetSizeAdd (sizeAdd); } DllExport void ParticleEffect_SetSizeMul (Urho3D::ParticleEffect *_target, float sizeMul) { _target->SetSizeMul (sizeMul); } DllExport void ParticleEffect_SetFaceCameraMode (Urho3D::ParticleEffect *_target, enum Urho3D::FaceCameraMode mode) { _target->SetFaceCameraMode (mode); } DllExport void ParticleEffect_AddColorTime (Urho3D::ParticleEffect *_target, const class Urho3D::Color & color, float time) { _target->AddColorTime (color, time); } DllExport void ParticleEffect_RemoveColorFrame (Urho3D::ParticleEffect *_target, unsigned int index) { _target->RemoveColorFrame (index); } DllExport void ParticleEffect_SetNumColorFrames (Urho3D::ParticleEffect *_target, unsigned int number) { _target->SetNumColorFrames (number); } DllExport void ParticleEffect_SortColorFrames (Urho3D::ParticleEffect *_target) { _target->SortColorFrames (); } DllExport void ParticleEffect_RemoveTextureFrame (Urho3D::ParticleEffect *_target, unsigned int index) { _target->RemoveTextureFrame (index); } DllExport void ParticleEffect_SetNumTextureFrames (Urho3D::ParticleEffect *_target, unsigned int number) { _target->SetNumTextureFrames (number); } DllExport void ParticleEffect_SortTextureFrames (Urho3D::ParticleEffect *_target) { _target->SortTextureFrames (); } DllExport Urho3D::ParticleEffect * ParticleEffect_Clone (Urho3D::ParticleEffect *_target, const char * cloneName) { auto copy = _target->Clone (Urho3D::String(cloneName)); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::Material * ParticleEffect_GetMaterial (Urho3D::ParticleEffect *_target) { return _target->GetMaterial (); } DllExport unsigned int ParticleEffect_GetNumParticles (Urho3D::ParticleEffect *_target) { return _target->GetNumParticles (); } DllExport int ParticleEffect_GetUpdateInvisible (Urho3D::ParticleEffect *_target) { return _target->GetUpdateInvisible (); } DllExport int ParticleEffect_IsRelative (Urho3D::ParticleEffect *_target) { return _target->IsRelative (); } DllExport int ParticleEffect_IsScaled (Urho3D::ParticleEffect *_target) { return _target->IsScaled (); } DllExport int ParticleEffect_IsSorted (Urho3D::ParticleEffect *_target) { return _target->IsSorted (); } DllExport int ParticleEffect_IsFixedScreenSize (Urho3D::ParticleEffect *_target) { return _target->IsFixedScreenSize (); } DllExport float ParticleEffect_GetAnimationLodBias (Urho3D::ParticleEffect *_target) { return _target->GetAnimationLodBias (); } DllExport enum Urho3D::EmitterType ParticleEffect_GetEmitterType (Urho3D::ParticleEffect *_target) { return _target->GetEmitterType (); } DllExport Interop::Vector3 ParticleEffect_GetEmitterSize (Urho3D::ParticleEffect *_target) { return *((Interop::Vector3 *) &(_target->GetEmitterSize ())); } DllExport Interop::Vector3 ParticleEffect_GetMinDirection (Urho3D::ParticleEffect *_target) { return *((Interop::Vector3 *) &(_target->GetMinDirection ())); } DllExport Interop::Vector3 ParticleEffect_GetMaxDirection (Urho3D::ParticleEffect *_target) { return *((Interop::Vector3 *) &(_target->GetMaxDirection ())); } DllExport Interop::Vector3 ParticleEffect_GetConstantForce (Urho3D::ParticleEffect *_target) { return *((Interop::Vector3 *) &(_target->GetConstantForce ())); } DllExport float ParticleEffect_GetDampingForce (Urho3D::ParticleEffect *_target) { return _target->GetDampingForce (); } DllExport float ParticleEffect_GetActiveTime (Urho3D::ParticleEffect *_target) { return _target->GetActiveTime (); } DllExport float ParticleEffect_GetInactiveTime (Urho3D::ParticleEffect *_target) { return _target->GetInactiveTime (); } DllExport float ParticleEffect_GetMinEmissionRate (Urho3D::ParticleEffect *_target) { return _target->GetMinEmissionRate (); } DllExport float ParticleEffect_GetMaxEmissionRate (Urho3D::ParticleEffect *_target) { return _target->GetMaxEmissionRate (); } DllExport Interop::Vector2 ParticleEffect_GetMinParticleSize (Urho3D::ParticleEffect *_target) { return *((Interop::Vector2 *) &(_target->GetMinParticleSize ())); } DllExport Interop::Vector2 ParticleEffect_GetMaxParticleSize (Urho3D::ParticleEffect *_target) { return *((Interop::Vector2 *) &(_target->GetMaxParticleSize ())); } DllExport float ParticleEffect_GetMinTimeToLive (Urho3D::ParticleEffect *_target) { return _target->GetMinTimeToLive (); } DllExport float ParticleEffect_GetMaxTimeToLive (Urho3D::ParticleEffect *_target) { return _target->GetMaxTimeToLive (); } DllExport float ParticleEffect_GetMinVelocity (Urho3D::ParticleEffect *_target) { return _target->GetMinVelocity (); } DllExport float ParticleEffect_GetMaxVelocity (Urho3D::ParticleEffect *_target) { return _target->GetMaxVelocity (); } DllExport float ParticleEffect_GetMinRotation (Urho3D::ParticleEffect *_target) { return _target->GetMinRotation (); } DllExport float ParticleEffect_GetMaxRotation (Urho3D::ParticleEffect *_target) { return _target->GetMaxRotation (); } DllExport float ParticleEffect_GetMinRotationSpeed (Urho3D::ParticleEffect *_target) { return _target->GetMinRotationSpeed (); } DllExport float ParticleEffect_GetMaxRotationSpeed (Urho3D::ParticleEffect *_target) { return _target->GetMaxRotationSpeed (); } DllExport float ParticleEffect_GetSizeAdd (Urho3D::ParticleEffect *_target) { return _target->GetSizeAdd (); } DllExport float ParticleEffect_GetSizeMul (Urho3D::ParticleEffect *_target) { return _target->GetSizeMul (); } DllExport unsigned int ParticleEffect_GetNumColorFrames (Urho3D::ParticleEffect *_target) { return _target->GetNumColorFrames (); } DllExport const struct Urho3D::ColorFrame * ParticleEffect_GetColorFrame (Urho3D::ParticleEffect *_target, unsigned int index) { return _target->GetColorFrame (index); } DllExport unsigned int ParticleEffect_GetNumTextureFrames (Urho3D::ParticleEffect *_target) { return _target->GetNumTextureFrames (); } DllExport const struct Urho3D::TextureFrame * ParticleEffect_GetTextureFrame (Urho3D::ParticleEffect *_target, unsigned int index) { return _target->GetTextureFrame (index); } DllExport enum Urho3D::FaceCameraMode ParticleEffect_GetFaceCameraMode (Urho3D::ParticleEffect *_target) { return _target->GetFaceCameraMode (); } DllExport Interop::Vector3 ParticleEffect_GetRandomDirection (Urho3D::ParticleEffect *_target) { return *((Interop::Vector3 *) &(_target->GetRandomDirection ())); } DllExport Interop::Vector2 ParticleEffect_GetRandomSize (Urho3D::ParticleEffect *_target) { return *((Interop::Vector2 *) &(_target->GetRandomSize ())); } DllExport float ParticleEffect_GetRandomVelocity (Urho3D::ParticleEffect *_target) { return _target->GetRandomVelocity (); } DllExport float ParticleEffect_GetRandomTimeToLive (Urho3D::ParticleEffect *_target) { return _target->GetRandomTimeToLive (); } DllExport float ParticleEffect_GetRandomRotationSpeed (Urho3D::ParticleEffect *_target) { return _target->GetRandomRotationSpeed (); } DllExport float ParticleEffect_GetRandomRotation (Urho3D::ParticleEffect *_target) { return _target->GetRandomRotation (); } DllExport int ParticleEmitter_GetType (Urho3D::ParticleEmitter *_target) { return (_target->GetType ()).Value (); } DllExport const char * ParticleEmitter_GetTypeName (Urho3D::ParticleEmitter *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ParticleEmitter_GetTypeStatic () { return (ParticleEmitter::GetTypeStatic ()).Value (); } DllExport const char * ParticleEmitter_GetTypeNameStatic () { return stringdup((ParticleEmitter::GetTypeNameStatic ()).CString ()); } DllExport void * ParticleEmitter_ParticleEmitter (Urho3D::Context * context) { return WeakPtr<ParticleEmitter>(new ParticleEmitter(context)); } DllExport void ParticleEmitter_RegisterObject (Urho3D::Context * context) { ParticleEmitter::RegisterObject (context); } DllExport void ParticleEmitter_OnSetEnabled (Urho3D::ParticleEmitter *_target) { _target->OnSetEnabled (); } DllExport void ParticleEmitter_SetEffect (Urho3D::ParticleEmitter *_target, Urho3D::ParticleEffect * effect) { _target->SetEffect (effect); } DllExport void ParticleEmitter_SetNumParticles (Urho3D::ParticleEmitter *_target, unsigned int num) { _target->SetNumParticles (num); } DllExport void ParticleEmitter_SetEmitting (Urho3D::ParticleEmitter *_target, bool enable) { _target->SetEmitting (enable); } DllExport void ParticleEmitter_SetSerializeParticles (Urho3D::ParticleEmitter *_target, bool enable) { _target->SetSerializeParticles (enable); } DllExport void ParticleEmitter_SetAutoRemoveMode (Urho3D::ParticleEmitter *_target, enum Urho3D::AutoRemoveMode mode) { _target->SetAutoRemoveMode (mode); } DllExport void ParticleEmitter_ResetEmissionTimer (Urho3D::ParticleEmitter *_target) { _target->ResetEmissionTimer (); } DllExport void ParticleEmitter_RemoveAllParticles (Urho3D::ParticleEmitter *_target) { _target->RemoveAllParticles (); } DllExport void ParticleEmitter_Reset (Urho3D::ParticleEmitter *_target) { _target->Reset (); } DllExport void ParticleEmitter_ApplyEffect (Urho3D::ParticleEmitter *_target) { _target->ApplyEffect (); } DllExport Urho3D::ParticleEffect * ParticleEmitter_GetEffect (Urho3D::ParticleEmitter *_target) { return _target->GetEffect (); } DllExport unsigned int ParticleEmitter_GetNumParticles (Urho3D::ParticleEmitter *_target) { return _target->GetNumParticles (); } DllExport int ParticleEmitter_IsEmitting (Urho3D::ParticleEmitter *_target) { return _target->IsEmitting (); } DllExport int ParticleEmitter_GetSerializeParticles (Urho3D::ParticleEmitter *_target) { return _target->GetSerializeParticles (); } DllExport enum Urho3D::AutoRemoveMode ParticleEmitter_GetAutoRemoveMode (Urho3D::ParticleEmitter *_target) { return _target->GetAutoRemoveMode (); } DllExport Urho3D::ResourceRef ParticleEmitter_GetEffectAttr (Urho3D::ParticleEmitter *_target) { return _target->GetEffectAttr (); } DllExport void * RenderPath_RenderPath () { return WeakPtr<RenderPath>(new RenderPath()); } DllExport Urho3D::RenderPath * RenderPath_Clone (Urho3D::RenderPath *_target) { auto copy = _target->Clone (); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport int RenderPath_Load (Urho3D::RenderPath *_target, Urho3D::XMLFile * file) { return _target->Load (file); } DllExport int RenderPath_Append (Urho3D::RenderPath *_target, Urho3D::XMLFile * file) { return _target->Append (file); } DllExport void RenderPath_SetEnabled (Urho3D::RenderPath *_target, const char * tag, bool active) { _target->SetEnabled (Urho3D::String(tag), active); } DllExport int RenderPath_IsEnabled (Urho3D::RenderPath *_target, const char * tag) { return _target->IsEnabled (Urho3D::String(tag)); } DllExport int RenderPath_IsAdded (Urho3D::RenderPath *_target, const char * tag) { return _target->IsAdded (Urho3D::String(tag)); } DllExport void RenderPath_ToggleEnabled (Urho3D::RenderPath *_target, const char * tag) { _target->ToggleEnabled (Urho3D::String(tag)); } DllExport void RenderPath_RemoveRenderTarget (Urho3D::RenderPath *_target, unsigned int index) { _target->RemoveRenderTarget (index); } DllExport void RenderPath_RemoveRenderTarget0 (Urho3D::RenderPath *_target, const char * name) { _target->RemoveRenderTarget (Urho3D::String(name)); } DllExport void RenderPath_RemoveRenderTargets (Urho3D::RenderPath *_target, const char * tag) { _target->RemoveRenderTargets (Urho3D::String(tag)); } DllExport void RenderPath_SetCommand (Urho3D::RenderPath *_target, unsigned int index, const struct Urho3D::RenderPathCommand & command) { _target->SetCommand (index, command); } DllExport void RenderPath_AddCommand (Urho3D::RenderPath *_target, const struct Urho3D::RenderPathCommand & command) { _target->AddCommand (command); } DllExport void RenderPath_InsertCommand (Urho3D::RenderPath *_target, unsigned int index, const struct Urho3D::RenderPathCommand & command) { _target->InsertCommand (index, command); } DllExport void RenderPath_RemoveCommand (Urho3D::RenderPath *_target, unsigned int index) { _target->RemoveCommand (index); } DllExport void RenderPath_RemoveCommands (Urho3D::RenderPath *_target, const char * tag) { _target->RemoveCommands (Urho3D::String(tag)); } // Urho3D::Variant overloads begin: DllExport void RenderPath_SetShaderParameter_0 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::Vector3 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_1 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::IntRect & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_2 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::Color & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_3 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::Vector2 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_4 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::Vector4 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_5 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::IntVector2 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_6 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::Quaternion & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_7 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::Matrix4 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_8 (Urho3D::RenderPath *_target, const char * name, const class Urho3D::Matrix3x4 & value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_9 (Urho3D::RenderPath *_target, const char * name, int value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_10 (Urho3D::RenderPath *_target, const char * name, float value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } DllExport void RenderPath_SetShaderParameter_11 (Urho3D::RenderPath *_target, const char * name, const char * value) { _target->SetShaderParameter (Urho3D::String(name), Urho3D::String(value)); } DllExport void RenderPath_SetShaderParameter_12 (Urho3D::RenderPath *_target, const char * name, bool value) { _target->SetShaderParameter (Urho3D::String(name), (value)); } // Urho3D::Variant overloads end. DllExport unsigned int RenderPath_GetNumRenderTargets (Urho3D::RenderPath *_target) { return _target->GetNumRenderTargets (); } DllExport unsigned int RenderPath_GetNumCommands (Urho3D::RenderPath *_target) { return _target->GetNumCommands (); } DllExport Urho3D::RenderPathCommand * RenderPath_GetCommand (Urho3D::RenderPath *_target, unsigned int index) { return _target->GetCommand (index); } // Urho3D::Variant overloads begin: DllExport Interop::Vector3 RenderPath_GetShaderParameter_0 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::Vector3 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetVector3())); } DllExport Interop::IntRect RenderPath_GetShaderParameter_1 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::IntRect *) &(_target->GetShaderParameter (Urho3D::String(name)).GetIntRect())); } DllExport Interop::Color RenderPath_GetShaderParameter_2 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::Color *) &(_target->GetShaderParameter (Urho3D::String(name)).GetColor())); } DllExport Interop::Vector2 RenderPath_GetShaderParameter_3 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::Vector2 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetVector2())); } DllExport Interop::Vector4 RenderPath_GetShaderParameter_4 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::Vector4 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetVector4())); } DllExport Interop::IntVector2 RenderPath_GetShaderParameter_5 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::IntVector2 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetIntVector2())); } DllExport Interop::Quaternion RenderPath_GetShaderParameter_6 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::Quaternion *) &(_target->GetShaderParameter (Urho3D::String(name)).GetQuaternion())); } DllExport Interop::Matrix4 RenderPath_GetShaderParameter_7 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::Matrix4 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetMatrix4())); } DllExport Interop::Matrix3x4 RenderPath_GetShaderParameter_8 (Urho3D::RenderPath *_target, const char * name) { return *((Interop::Matrix3x4 *) &(_target->GetShaderParameter (Urho3D::String(name)).GetMatrix3x4())); } DllExport int RenderPath_GetShaderParameter_9 (Urho3D::RenderPath *_target, const char * name) { return (_target->GetShaderParameter (Urho3D::String(name)).GetInt()); } DllExport float RenderPath_GetShaderParameter_10 (Urho3D::RenderPath *_target, const char * name) { return (_target->GetShaderParameter (Urho3D::String(name)).GetFloat()); } DllExport const char * RenderPath_GetShaderParameter_11 (Urho3D::RenderPath *_target, const char * name) { return stringdup(_target->GetShaderParameter (Urho3D::String(name)).GetString().CString()); } DllExport bool RenderPath_GetShaderParameter_12 (Urho3D::RenderPath *_target, const char * name) { return (_target->GetShaderParameter (Urho3D::String(name)).GetBool()); } // Urho3D::Variant overloads end. DllExport int Renderer_GetType (Urho3D::Renderer *_target) { return (_target->GetType ()).Value (); } DllExport const char * Renderer_GetTypeName (Urho3D::Renderer *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Renderer_GetTypeStatic () { return (Renderer::GetTypeStatic ()).Value (); } DllExport const char * Renderer_GetTypeNameStatic () { return stringdup((Renderer::GetTypeNameStatic ()).CString ()); } DllExport void * Renderer_Renderer (Urho3D::Context * context) { return WeakPtr<Renderer>(new Renderer(context)); } DllExport void Renderer_SetNumViewports (Urho3D::Renderer *_target, unsigned int num) { _target->SetNumViewports (num); } DllExport void Renderer_SetViewport (Urho3D::Renderer *_target, unsigned int index, Urho3D::Viewport * viewport) { _target->SetViewport (index, viewport); } DllExport void Renderer_SetDefaultRenderPath (Urho3D::Renderer *_target, Urho3D::RenderPath * renderPath) { _target->SetDefaultRenderPath (renderPath); } DllExport void Renderer_SetDefaultRenderPath0 (Urho3D::Renderer *_target, Urho3D::XMLFile * file) { _target->SetDefaultRenderPath (file); } DllExport void Renderer_SetDefaultTechnique (Urho3D::Renderer *_target, Urho3D::Technique * tech) { _target->SetDefaultTechnique (tech); } DllExport void Renderer_SetHDRRendering (Urho3D::Renderer *_target, bool enable) { _target->SetHDRRendering (enable); } DllExport void Renderer_SetSpecularLighting (Urho3D::Renderer *_target, bool enable) { _target->SetSpecularLighting (enable); } DllExport void Renderer_SetTextureAnisotropy (Urho3D::Renderer *_target, int level) { _target->SetTextureAnisotropy (level); } DllExport void Renderer_SetTextureFilterMode (Urho3D::Renderer *_target, enum Urho3D::TextureFilterMode mode) { _target->SetTextureFilterMode (mode); } DllExport void Renderer_SetTextureQuality (Urho3D::Renderer *_target, int quality) { _target->SetTextureQuality (quality); } DllExport void Renderer_SetMaterialQuality (Urho3D::Renderer *_target, int quality) { _target->SetMaterialQuality (quality); } DllExport void Renderer_SetDrawShadows (Urho3D::Renderer *_target, bool enable) { _target->SetDrawShadows (enable); } DllExport void Renderer_SetShadowMapSize (Urho3D::Renderer *_target, int size) { _target->SetShadowMapSize (size); } DllExport void Renderer_SetShadowQuality (Urho3D::Renderer *_target, enum Urho3D::ShadowQuality quality) { _target->SetShadowQuality (quality); } DllExport void Renderer_SetShadowSoftness (Urho3D::Renderer *_target, float shadowSoftness) { _target->SetShadowSoftness (shadowSoftness); } DllExport void Renderer_SetVSMShadowParameters (Urho3D::Renderer *_target, float minVariance, float lightBleedingReduction) { _target->SetVSMShadowParameters (minVariance, lightBleedingReduction); } DllExport void Renderer_SetVSMMultiSample (Urho3D::Renderer *_target, int multiSample) { _target->SetVSMMultiSample (multiSample); } DllExport void Renderer_SetReuseShadowMaps (Urho3D::Renderer *_target, bool enable) { _target->SetReuseShadowMaps (enable); } DllExport void Renderer_SetMaxShadowMaps (Urho3D::Renderer *_target, int shadowMaps) { _target->SetMaxShadowMaps (shadowMaps); } DllExport void Renderer_SetDynamicInstancing (Urho3D::Renderer *_target, bool enable) { _target->SetDynamicInstancing (enable); } DllExport void Renderer_SetNumExtraInstancingBufferElements (Urho3D::Renderer *_target, int elements) { _target->SetNumExtraInstancingBufferElements (elements); } DllExport void Renderer_SetMinInstances (Urho3D::Renderer *_target, int instances) { _target->SetMinInstances (instances); } DllExport void Renderer_SetMaxSortedInstances (Urho3D::Renderer *_target, int instances) { _target->SetMaxSortedInstances (instances); } DllExport void Renderer_SetMaxOccluderTriangles (Urho3D::Renderer *_target, int triangles) { _target->SetMaxOccluderTriangles (triangles); } DllExport void Renderer_SetOcclusionBufferSize (Urho3D::Renderer *_target, int size) { _target->SetOcclusionBufferSize (size); } DllExport void Renderer_SetOccluderSizeThreshold (Urho3D::Renderer *_target, float screenSize) { _target->SetOccluderSizeThreshold (screenSize); } DllExport void Renderer_SetThreadedOcclusion (Urho3D::Renderer *_target, bool enable) { _target->SetThreadedOcclusion (enable); } DllExport void Renderer_SetMobileShadowBiasMul (Urho3D::Renderer *_target, float mul) { _target->SetMobileShadowBiasMul (mul); } DllExport void Renderer_SetMobileShadowBiasAdd (Urho3D::Renderer *_target, float add) { _target->SetMobileShadowBiasAdd (add); } DllExport void Renderer_SetMobileNormalOffsetMul (Urho3D::Renderer *_target, float mul) { _target->SetMobileNormalOffsetMul (mul); } DllExport void Renderer_ReloadShaders (Urho3D::Renderer *_target) { _target->ReloadShaders (); } DllExport void Renderer_ApplyShadowMapFilter (Urho3D::Renderer *_target, Urho3D::View * view, Urho3D::Texture2D * shadowMap, float blurScale) { _target->ApplyShadowMapFilter (view, shadowMap, blurScale); } DllExport unsigned int Renderer_GetNumViewports (Urho3D::Renderer *_target) { return _target->GetNumViewports (); } DllExport Urho3D::Viewport * Renderer_GetViewport (Urho3D::Renderer *_target, unsigned int index) { return _target->GetViewport (index); } DllExport Urho3D::Viewport * Renderer_GetViewportForScene (Urho3D::Renderer *_target, Urho3D::Scene * scene, unsigned int index) { return _target->GetViewportForScene (scene, index); } DllExport Urho3D::RenderPath * Renderer_GetDefaultRenderPath (Urho3D::Renderer *_target) { return _target->GetDefaultRenderPath (); } DllExport Urho3D::Technique * Renderer_GetDefaultTechnique (Urho3D::Renderer *_target) { return _target->GetDefaultTechnique (); } DllExport int Renderer_GetHDRRendering (Urho3D::Renderer *_target) { return _target->GetHDRRendering (); } DllExport int Renderer_GetSpecularLighting (Urho3D::Renderer *_target) { return _target->GetSpecularLighting (); } DllExport int Renderer_GetDrawShadows (Urho3D::Renderer *_target) { return _target->GetDrawShadows (); } DllExport int Renderer_GetTextureAnisotropy (Urho3D::Renderer *_target) { return _target->GetTextureAnisotropy (); } DllExport enum Urho3D::TextureFilterMode Renderer_GetTextureFilterMode (Urho3D::Renderer *_target) { return _target->GetTextureFilterMode (); } DllExport int Renderer_GetTextureQuality (Urho3D::Renderer *_target) { return _target->GetTextureQuality (); } DllExport int Renderer_GetMaterialQuality (Urho3D::Renderer *_target) { return _target->GetMaterialQuality (); } DllExport int Renderer_GetShadowMapSize (Urho3D::Renderer *_target) { return _target->GetShadowMapSize (); } DllExport enum Urho3D::ShadowQuality Renderer_GetShadowQuality (Urho3D::Renderer *_target) { return _target->GetShadowQuality (); } DllExport float Renderer_GetShadowSoftness (Urho3D::Renderer *_target) { return _target->GetShadowSoftness (); } DllExport Interop::Vector2 Renderer_GetVSMShadowParameters (Urho3D::Renderer *_target) { return *((Interop::Vector2 *) &(_target->GetVSMShadowParameters ())); } DllExport int Renderer_GetVSMMultiSample (Urho3D::Renderer *_target) { return _target->GetVSMMultiSample (); } DllExport int Renderer_GetReuseShadowMaps (Urho3D::Renderer *_target) { return _target->GetReuseShadowMaps (); } DllExport int Renderer_GetMaxShadowMaps (Urho3D::Renderer *_target) { return _target->GetMaxShadowMaps (); } DllExport int Renderer_GetDynamicInstancing (Urho3D::Renderer *_target) { return _target->GetDynamicInstancing (); } DllExport int Renderer_GetNumExtraInstancingBufferElements (Urho3D::Renderer *_target) { return _target->GetNumExtraInstancingBufferElements (); } DllExport int Renderer_GetMinInstances (Urho3D::Renderer *_target) { return _target->GetMinInstances (); } DllExport int Renderer_GetMaxSortedInstances (Urho3D::Renderer *_target) { return _target->GetMaxSortedInstances (); } DllExport int Renderer_GetMaxOccluderTriangles (Urho3D::Renderer *_target) { return _target->GetMaxOccluderTriangles (); } DllExport int Renderer_GetOcclusionBufferSize (Urho3D::Renderer *_target) { return _target->GetOcclusionBufferSize (); } DllExport float Renderer_GetOccluderSizeThreshold (Urho3D::Renderer *_target) { return _target->GetOccluderSizeThreshold (); } DllExport int Renderer_GetThreadedOcclusion (Urho3D::Renderer *_target) { return _target->GetThreadedOcclusion (); } DllExport float Renderer_GetMobileShadowBiasMul (Urho3D::Renderer *_target) { return _target->GetMobileShadowBiasMul (); } DllExport float Renderer_GetMobileShadowBiasAdd (Urho3D::Renderer *_target) { return _target->GetMobileShadowBiasAdd (); } DllExport float Renderer_GetMobileNormalOffsetMul (Urho3D::Renderer *_target) { return _target->GetMobileNormalOffsetMul (); } DllExport unsigned int Renderer_GetNumViews (Urho3D::Renderer *_target) { return _target->GetNumViews (); } DllExport unsigned int Renderer_GetNumPrimitives (Urho3D::Renderer *_target) { return _target->GetNumPrimitives (); } DllExport unsigned int Renderer_GetNumBatches (Urho3D::Renderer *_target) { return _target->GetNumBatches (); } DllExport unsigned int Renderer_GetNumGeometries (Urho3D::Renderer *_target, bool allViews) { return _target->GetNumGeometries (allViews); } DllExport unsigned int Renderer_GetNumLights (Urho3D::Renderer *_target, bool allViews) { return _target->GetNumLights (allViews); } DllExport unsigned int Renderer_GetNumShadowMaps (Urho3D::Renderer *_target, bool allViews) { return _target->GetNumShadowMaps (allViews); } DllExport unsigned int Renderer_GetNumOccluders (Urho3D::Renderer *_target, bool allViews) { return _target->GetNumOccluders (allViews); } DllExport Urho3D::Zone * Renderer_GetDefaultZone (Urho3D::Renderer *_target) { return _target->GetDefaultZone (); } DllExport Urho3D::Material * Renderer_GetDefaultMaterial (Urho3D::Renderer *_target) { return _target->GetDefaultMaterial (); } DllExport Urho3D::Texture2D * Renderer_GetDefaultLightRamp (Urho3D::Renderer *_target) { return _target->GetDefaultLightRamp (); } DllExport Urho3D::Texture2D * Renderer_GetDefaultLightSpot (Urho3D::Renderer *_target) { return _target->GetDefaultLightSpot (); } DllExport Urho3D::TextureCube * Renderer_GetFaceSelectCubeMap (Urho3D::Renderer *_target) { return _target->GetFaceSelectCubeMap (); } DllExport Urho3D::TextureCube * Renderer_GetIndirectionCubeMap (Urho3D::Renderer *_target) { return _target->GetIndirectionCubeMap (); } DllExport Urho3D::VertexBuffer * Renderer_GetInstancingBuffer (Urho3D::Renderer *_target) { return _target->GetInstancingBuffer (); } DllExport void Renderer_Update (Urho3D::Renderer *_target, float timeStep) { _target->Update (timeStep); } DllExport void Renderer_Render (Urho3D::Renderer *_target) { _target->Render (); } DllExport void Renderer_DrawDebugGeometry (Urho3D::Renderer *_target, bool depthTest) { _target->DrawDebugGeometry (depthTest); } DllExport void Renderer_QueueRenderSurface (Urho3D::Renderer *_target, Urho3D::RenderSurface * renderTarget) { _target->QueueRenderSurface (renderTarget); } DllExport void Renderer_QueueViewport (Urho3D::Renderer *_target, Urho3D::RenderSurface * renderTarget, Urho3D::Viewport * viewport) { _target->QueueViewport (renderTarget, viewport); } DllExport Urho3D::Geometry * Renderer_GetLightGeometry (Urho3D::Renderer *_target, Urho3D::Light * light) { return _target->GetLightGeometry (light); } DllExport Urho3D::Geometry * Renderer_GetQuadGeometry (Urho3D::Renderer *_target) { return _target->GetQuadGeometry (); } DllExport Urho3D::Texture2D * Renderer_GetShadowMap (Urho3D::Renderer *_target, Urho3D::Light * light, Urho3D::Camera * camera, unsigned int viewWidth, unsigned int viewHeight) { return _target->GetShadowMap (light, camera, viewWidth, viewHeight); } DllExport Urho3D::Texture * Renderer_GetScreenBuffer (Urho3D::Renderer *_target, int width, int height, unsigned int format, int multiSample, bool autoResolve, bool cubemap, bool filtered, bool srgb, unsigned int persistentKey) { return _target->GetScreenBuffer (width, height, format, multiSample, autoResolve, cubemap, filtered, srgb, persistentKey); } DllExport Urho3D::RenderSurface * Renderer_GetDepthStencil (Urho3D::Renderer *_target, int width, int height, int multiSample, bool autoResolve) { return _target->GetDepthStencil (width, height, multiSample, autoResolve); } DllExport Urho3D::OcclusionBuffer * Renderer_GetOcclusionBuffer (Urho3D::Renderer *_target, Urho3D::Camera * camera) { return _target->GetOcclusionBuffer (camera); } DllExport Urho3D::Camera * Renderer_GetShadowCamera (Urho3D::Renderer *_target) { return _target->GetShadowCamera (); } DllExport void Renderer_StorePreparedView (Urho3D::Renderer *_target, Urho3D::View * view, Urho3D::Camera * cullCamera) { _target->StorePreparedView (view, cullCamera); } DllExport Urho3D::View * Renderer_GetPreparedView (Urho3D::Renderer *_target, Urho3D::Camera * cullCamera) { return _target->GetPreparedView (cullCamera); } DllExport void Renderer_SetCullMode (Urho3D::Renderer *_target, enum Urho3D::CullMode mode, Urho3D::Camera * camera) { _target->SetCullMode (mode, camera); } DllExport int Renderer_ResizeInstancingBuffer (Urho3D::Renderer *_target, unsigned int numInstances) { return _target->ResizeInstancingBuffer (numInstances); } DllExport void Renderer_OptimizeLightByScissor (Urho3D::Renderer *_target, Urho3D::Light * light, Urho3D::Camera * camera) { _target->OptimizeLightByScissor (light, camera); } DllExport void Renderer_OptimizeLightByStencil (Urho3D::Renderer *_target, Urho3D::Light * light, Urho3D::Camera * camera) { _target->OptimizeLightByStencil (light, camera); } DllExport Urho3D::View * Renderer_GetActualView (Urho3D::View * view) { return Renderer::GetActualView (view); } DllExport int Shader_GetType (Urho3D::Shader *_target) { return (_target->GetType ()).Value (); } DllExport const char * Shader_GetTypeName (Urho3D::Shader *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Shader_GetTypeStatic () { return (Shader::GetTypeStatic ()).Value (); } DllExport const char * Shader_GetTypeNameStatic () { return stringdup((Shader::GetTypeNameStatic ()).CString ()); } DllExport void * Shader_Shader (Urho3D::Context * context) { return WeakPtr<Shader>(new Shader(context)); } DllExport void Shader_RegisterObject (Urho3D::Context * context) { Shader::RegisterObject (context); } DllExport int Shader_BeginLoad_File (Urho3D::Shader *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Shader_BeginLoad_MemoryBuffer (Urho3D::Shader *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Shader_EndLoad (Urho3D::Shader *_target) { return _target->EndLoad (); } DllExport Urho3D::ShaderVariation * Shader_GetVariation (Urho3D::Shader *_target, enum Urho3D::ShaderType type, const char * defines) { return _target->GetVariation (type, Urho3D::String(defines)); } DllExport const char * Shader_GetSourceCode (Urho3D::Shader *_target, enum Urho3D::ShaderType type) { return stringdup((_target->GetSourceCode (type)).CString ()); } DllExport unsigned int Shader_GetTimeStamp (Urho3D::Shader *_target) { return _target->GetTimeStamp (); } DllExport int RibbonTrail_GetType (Urho3D::RibbonTrail *_target) { return (_target->GetType ()).Value (); } DllExport const char * RibbonTrail_GetTypeName (Urho3D::RibbonTrail *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int RibbonTrail_GetTypeStatic () { return (RibbonTrail::GetTypeStatic ()).Value (); } DllExport const char * RibbonTrail_GetTypeNameStatic () { return stringdup((RibbonTrail::GetTypeNameStatic ()).CString ()); } DllExport void * RibbonTrail_RibbonTrail (Urho3D::Context * context) { return WeakPtr<RibbonTrail>(new RibbonTrail(context)); } DllExport void RibbonTrail_RegisterObject (Urho3D::Context * context) { RibbonTrail::RegisterObject (context); } DllExport void RibbonTrail_OnSetEnabled (Urho3D::RibbonTrail *_target) { _target->OnSetEnabled (); } DllExport enum Urho3D::UpdateGeometryType RibbonTrail_GetUpdateGeometryType (Urho3D::RibbonTrail *_target) { return _target->GetUpdateGeometryType (); } DllExport void RibbonTrail_SetMaterial (Urho3D::RibbonTrail *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport void RibbonTrail_SetVertexDistance (Urho3D::RibbonTrail *_target, float length) { _target->SetVertexDistance (length); } DllExport void RibbonTrail_SetWidth (Urho3D::RibbonTrail *_target, float width) { _target->SetWidth (width); } DllExport void RibbonTrail_SetStartColor (Urho3D::RibbonTrail *_target, const class Urho3D::Color & color) { _target->SetStartColor (color); } DllExport void RibbonTrail_SetEndColor (Urho3D::RibbonTrail *_target, const class Urho3D::Color & color) { _target->SetEndColor (color); } DllExport void RibbonTrail_SetStartScale (Urho3D::RibbonTrail *_target, float startScale) { _target->SetStartScale (startScale); } DllExport void RibbonTrail_SetEndScale (Urho3D::RibbonTrail *_target, float endScale) { _target->SetEndScale (endScale); } DllExport void RibbonTrail_SetTrailType (Urho3D::RibbonTrail *_target, enum Urho3D::TrailType type) { _target->SetTrailType (type); } DllExport void RibbonTrail_SetSorted (Urho3D::RibbonTrail *_target, bool enable) { _target->SetSorted (enable); } DllExport void RibbonTrail_SetLifetime (Urho3D::RibbonTrail *_target, float time) { _target->SetLifetime (time); } DllExport void RibbonTrail_SetEmitting (Urho3D::RibbonTrail *_target, bool emitting) { _target->SetEmitting (emitting); } DllExport void RibbonTrail_SetUpdateInvisible (Urho3D::RibbonTrail *_target, bool enable) { _target->SetUpdateInvisible (enable); } DllExport void RibbonTrail_SetTailColumn (Urho3D::RibbonTrail *_target, unsigned int tailColumn) { _target->SetTailColumn (tailColumn); } DllExport void RibbonTrail_SetAnimationLodBias (Urho3D::RibbonTrail *_target, float bias) { _target->SetAnimationLodBias (bias); } DllExport void RibbonTrail_Commit (Urho3D::RibbonTrail *_target) { _target->Commit (); } DllExport Urho3D::Material * RibbonTrail_GetMaterial (Urho3D::RibbonTrail *_target) { return _target->GetMaterial (); } DllExport Urho3D::ResourceRef RibbonTrail_GetMaterialAttr (Urho3D::RibbonTrail *_target) { return _target->GetMaterialAttr (); } DllExport float RibbonTrail_GetVertexDistance (Urho3D::RibbonTrail *_target) { return _target->GetVertexDistance (); } DllExport float RibbonTrail_GetWidth (Urho3D::RibbonTrail *_target) { return _target->GetWidth (); } DllExport Interop::Color RibbonTrail_GetStartColor (Urho3D::RibbonTrail *_target) { return *((Interop::Color *) &(_target->GetStartColor ())); } DllExport Interop::Color RibbonTrail_GetEndColor (Urho3D::RibbonTrail *_target) { return *((Interop::Color *) &(_target->GetEndColor ())); } DllExport float RibbonTrail_GetStartScale (Urho3D::RibbonTrail *_target) { return _target->GetStartScale (); } DllExport float RibbonTrail_GetEndScale (Urho3D::RibbonTrail *_target) { return _target->GetEndScale (); } DllExport int RibbonTrail_IsSorted (Urho3D::RibbonTrail *_target) { return _target->IsSorted (); } DllExport float RibbonTrail_GetLifetime (Urho3D::RibbonTrail *_target) { return _target->GetLifetime (); } DllExport float RibbonTrail_GetAnimationLodBias (Urho3D::RibbonTrail *_target) { return _target->GetAnimationLodBias (); } DllExport enum Urho3D::TrailType RibbonTrail_GetTrailType (Urho3D::RibbonTrail *_target) { return _target->GetTrailType (); } DllExport unsigned int RibbonTrail_GetTailColumn (Urho3D::RibbonTrail *_target) { return _target->GetTailColumn (); } DllExport int RibbonTrail_IsEmitting (Urho3D::RibbonTrail *_target) { return _target->IsEmitting (); } DllExport int RibbonTrail_GetUpdateInvisible (Urho3D::RibbonTrail *_target) { return _target->GetUpdateInvisible (); } DllExport void * XmlElement_XMLElement () { return new XMLElement(); } DllExport void * XmlElement_XMLElement0 (const class Urho3D::XMLElement & rhs) { return new XMLElement(rhs); } DllExport Urho3D::XMLElement * XmlElement_CreateChild (Urho3D::XMLElement *_target, const char * name) { return new Urho3D::XMLElement (_target->CreateChild (Urho3D::String(name))); } DllExport Urho3D::XMLElement * XmlElement_GetOrCreateChild (Urho3D::XMLElement *_target, const char * name) { return new Urho3D::XMLElement (_target->GetOrCreateChild (Urho3D::String(name))); } DllExport int XmlElement_AppendChild (Urho3D::XMLElement *_target, Urho3D::XMLElement element, bool asCopy) { return _target->AppendChild (element, asCopy); } DllExport int XmlElement_Remove (Urho3D::XMLElement *_target) { return _target->Remove (); } DllExport int XmlElement_RemoveChild (Urho3D::XMLElement *_target, const class Urho3D::XMLElement & element) { return _target->RemoveChild (element); } DllExport int XmlElement_RemoveChild1 (Urho3D::XMLElement *_target, const char * name) { return _target->RemoveChild (Urho3D::String(name)); } DllExport int XmlElement_RemoveChildren (Urho3D::XMLElement *_target, const char * name) { return _target->RemoveChildren (Urho3D::String(name)); } DllExport int XmlElement_RemoveAttribute (Urho3D::XMLElement *_target, const char * name) { return _target->RemoveAttribute (Urho3D::String(name)); } DllExport int XmlElement_SetValue (Urho3D::XMLElement *_target, const char * value) { return _target->SetValue (Urho3D::String(value)); } DllExport int XmlElement_SetAttribute (Urho3D::XMLElement *_target, const char * name, const char * value) { return _target->SetAttribute (Urho3D::String(name), Urho3D::String(value)); } DllExport int XmlElement_SetAttribute2 (Urho3D::XMLElement *_target, const char * value) { return _target->SetAttribute (Urho3D::String(value)); } DllExport int XmlElement_SetBool (Urho3D::XMLElement *_target, const char * name, bool value) { return _target->SetBool (Urho3D::String(name), value); } DllExport int XmlElement_SetBoundingBox (Urho3D::XMLElement *_target, const class Urho3D::BoundingBox & value) { return _target->SetBoundingBox (value); } DllExport int XmlElement_SetBuffer (Urho3D::XMLElement *_target, const char * name, const void * data, unsigned int size) { return _target->SetBuffer (Urho3D::String(name), data, size); } DllExport int XmlElement_SetColor (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Color & value) { return _target->SetColor (Urho3D::String(name), value); } DllExport int XmlElement_SetFloat (Urho3D::XMLElement *_target, const char * name, float value) { return _target->SetFloat (Urho3D::String(name), value); } DllExport int XmlElement_SetDouble (Urho3D::XMLElement *_target, const char * name, double value) { return _target->SetDouble (Urho3D::String(name), value); } DllExport int XmlElement_SetUInt (Urho3D::XMLElement *_target, const char * name, unsigned int value) { return _target->SetUInt (Urho3D::String(name), value); } DllExport int XmlElement_SetInt (Urho3D::XMLElement *_target, const char * name, int value) { return _target->SetInt (Urho3D::String(name), value); } DllExport int XmlElement_SetUInt64 (Urho3D::XMLElement *_target, const char * name, unsigned long long value) { return _target->SetUInt64 (Urho3D::String(name), value); } DllExport int XmlElement_SetInt64 (Urho3D::XMLElement *_target, const char * name, long long value) { return _target->SetInt64 (Urho3D::String(name), value); } DllExport int XmlElement_SetIntRect (Urho3D::XMLElement *_target, const char * name, const class Urho3D::IntRect & value) { return _target->SetIntRect (Urho3D::String(name), value); } DllExport int XmlElement_SetIntVector2 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::IntVector2 & value) { return _target->SetIntVector2 (Urho3D::String(name), value); } DllExport int XmlElement_SetQuaternion (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Quaternion & value) { return _target->SetQuaternion (Urho3D::String(name), value); } DllExport int XmlElement_SetString (Urho3D::XMLElement *_target, const char * name, const char * value) { return _target->SetString (Urho3D::String(name), Urho3D::String(value)); } // Urho3D::Variant overloads begin: DllExport int XmlElement_SetVariant_0 (Urho3D::XMLElement *_target, const class Urho3D::Vector3 & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_1 (Urho3D::XMLElement *_target, const class Urho3D::IntRect & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_2 (Urho3D::XMLElement *_target, const class Urho3D::Color & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_3 (Urho3D::XMLElement *_target, const class Urho3D::Vector2 & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_4 (Urho3D::XMLElement *_target, const class Urho3D::Vector4 & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_5 (Urho3D::XMLElement *_target, const class Urho3D::IntVector2 & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_6 (Urho3D::XMLElement *_target, const class Urho3D::Quaternion & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_7 (Urho3D::XMLElement *_target, const class Urho3D::Matrix4 & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_8 (Urho3D::XMLElement *_target, const class Urho3D::Matrix3x4 & value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_9 (Urho3D::XMLElement *_target, int value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_10 (Urho3D::XMLElement *_target, float value) { return _target->SetVariant ((value)); } DllExport int XmlElement_SetVariant_11 (Urho3D::XMLElement *_target, const char * value) { return _target->SetVariant (Urho3D::String(value)); } DllExport int XmlElement_SetVariant_12 (Urho3D::XMLElement *_target, bool value) { return _target->SetVariant ((value)); } // Urho3D::Variant overloads end. // Urho3D::Variant overloads begin: DllExport int XmlElement_SetVariantValue_0 (Urho3D::XMLElement *_target, const class Urho3D::Vector3 & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_1 (Urho3D::XMLElement *_target, const class Urho3D::IntRect & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_2 (Urho3D::XMLElement *_target, const class Urho3D::Color & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_3 (Urho3D::XMLElement *_target, const class Urho3D::Vector2 & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_4 (Urho3D::XMLElement *_target, const class Urho3D::Vector4 & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_5 (Urho3D::XMLElement *_target, const class Urho3D::IntVector2 & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_6 (Urho3D::XMLElement *_target, const class Urho3D::Quaternion & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_7 (Urho3D::XMLElement *_target, const class Urho3D::Matrix4 & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_8 (Urho3D::XMLElement *_target, const class Urho3D::Matrix3x4 & value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_9 (Urho3D::XMLElement *_target, int value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_10 (Urho3D::XMLElement *_target, float value) { return _target->SetVariantValue ((value)); } DllExport int XmlElement_SetVariantValue_11 (Urho3D::XMLElement *_target, const char * value) { return _target->SetVariantValue (Urho3D::String(value)); } DllExport int XmlElement_SetVariantValue_12 (Urho3D::XMLElement *_target, bool value) { return _target->SetVariantValue ((value)); } // Urho3D::Variant overloads end. DllExport int XmlElement_SetVector2 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Vector2 & value) { return _target->SetVector2 (Urho3D::String(name), value); } DllExport int XmlElement_SetVector3 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Vector3 & value) { return _target->SetVector3 (Urho3D::String(name), value); } DllExport int XmlElement_SetVector4 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Vector4 & value) { return _target->SetVector4 (Urho3D::String(name), value); } // Urho3D::Variant overloads begin: DllExport int XmlElement_SetVectorVariant_0 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Vector3 & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_1 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::IntRect & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_2 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Color & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_3 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Vector2 & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_4 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Vector4 & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_5 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::IntVector2 & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_6 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Quaternion & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_7 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Matrix4 & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_8 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Matrix3x4 & value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_9 (Urho3D::XMLElement *_target, const char * name, int value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_10 (Urho3D::XMLElement *_target, const char * name, float value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } DllExport int XmlElement_SetVectorVariant_11 (Urho3D::XMLElement *_target, const char * name, const char * value) { return _target->SetVectorVariant (Urho3D::String(name), Urho3D::String(value)); } DllExport int XmlElement_SetVectorVariant_12 (Urho3D::XMLElement *_target, const char * name, bool value) { return _target->SetVectorVariant (Urho3D::String(name), (value)); } // Urho3D::Variant overloads end. DllExport int XmlElement_SetMatrix3x4 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Matrix3x4 & value) { return _target->SetMatrix3x4 (Urho3D::String(name), value); } DllExport int XmlElement_SetMatrix4 (Urho3D::XMLElement *_target, const char * name, const class Urho3D::Matrix4 & value) { return _target->SetMatrix4 (Urho3D::String(name), value); } DllExport int XmlElement_IsNull (Urho3D::XMLElement *_target) { return _target->IsNull (); } DllExport int XmlElement_NotNull (Urho3D::XMLElement *_target) { return _target->NotNull (); } DllExport const char * XmlElement_GetName (Urho3D::XMLElement *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport int XmlElement_HasChild (Urho3D::XMLElement *_target, const char * name) { return _target->HasChild (Urho3D::String(name)); } DllExport Urho3D::XMLElement * XmlElement_GetChild (Urho3D::XMLElement *_target, const char * name) { return new Urho3D::XMLElement (_target->GetChild (Urho3D::String(name))); } DllExport Urho3D::XMLElement * XmlElement_GetNext (Urho3D::XMLElement *_target, const char * name) { return new Urho3D::XMLElement (_target->GetNext (Urho3D::String(name))); } DllExport Urho3D::XMLElement * XmlElement_GetParent (Urho3D::XMLElement *_target) { return new Urho3D::XMLElement (_target->GetParent ()); } DllExport unsigned int XmlElement_GetNumAttributes (Urho3D::XMLElement *_target) { return _target->GetNumAttributes (); } DllExport int XmlElement_HasAttribute (Urho3D::XMLElement *_target, const char * name) { return _target->HasAttribute (Urho3D::String(name)); } DllExport const char * XmlElement_GetValue (Urho3D::XMLElement *_target) { return stringdup((_target->GetValue ()).CString ()); } DllExport const char * XmlElement_GetAttribute (Urho3D::XMLElement *_target, const char * name) { return stringdup((_target->GetAttribute (Urho3D::String(name))).CString ()); } DllExport const char * XmlElement_GetAttributeLower (Urho3D::XMLElement *_target, const char * name) { return stringdup((_target->GetAttributeLower (Urho3D::String(name))).CString ()); } DllExport const char * XmlElement_GetAttributeUpper (Urho3D::XMLElement *_target, const char * name) { return stringdup((_target->GetAttributeUpper (Urho3D::String(name))).CString ()); } DllExport int XmlElement_GetBool (Urho3D::XMLElement *_target, const char * name) { return _target->GetBool (Urho3D::String(name)); } DllExport int XmlElement_GetBuffer (Urho3D::XMLElement *_target, const char * name, void * dest, unsigned int size) { return _target->GetBuffer (Urho3D::String(name), dest, size); } DllExport Interop::BoundingBox XmlElement_GetBoundingBox (Urho3D::XMLElement *_target) { return *((Interop::BoundingBox *) &(_target->GetBoundingBox ())); } DllExport Interop::Color XmlElement_GetColor (Urho3D::XMLElement *_target, const char * name) { return *((Interop::Color *) &(_target->GetColor (Urho3D::String(name)))); } DllExport float XmlElement_GetFloat (Urho3D::XMLElement *_target, const char * name) { return _target->GetFloat (Urho3D::String(name)); } DllExport double XmlElement_GetDouble (Urho3D::XMLElement *_target, const char * name) { return _target->GetDouble (Urho3D::String(name)); } DllExport unsigned int XmlElement_GetUInt (Urho3D::XMLElement *_target, const char * name) { return _target->GetUInt (Urho3D::String(name)); } DllExport int XmlElement_GetInt (Urho3D::XMLElement *_target, const char * name) { return _target->GetInt (Urho3D::String(name)); } DllExport unsigned long long XmlElement_GetUInt64 (Urho3D::XMLElement *_target, const char * name) { return _target->GetUInt64 (Urho3D::String(name)); } DllExport long long XmlElement_GetInt64 (Urho3D::XMLElement *_target, const char * name) { return _target->GetInt64 (Urho3D::String(name)); } DllExport Interop::IntRect XmlElement_GetIntRect (Urho3D::XMLElement *_target, const char * name) { return *((Interop::IntRect *) &(_target->GetIntRect (Urho3D::String(name)))); } DllExport Interop::IntVector2 XmlElement_GetIntVector2 (Urho3D::XMLElement *_target, const char * name) { return *((Interop::IntVector2 *) &(_target->GetIntVector2 (Urho3D::String(name)))); } DllExport Urho3D::IntVector3 XmlElement_GetIntVector3 (Urho3D::XMLElement *_target, const char * name) { return _target->GetIntVector3 (Urho3D::String(name)); } DllExport Urho3D::Rect XmlElement_GetRect (Urho3D::XMLElement *_target, const char * name) { return _target->GetRect (Urho3D::String(name)); } DllExport Interop::Quaternion XmlElement_GetQuaternion (Urho3D::XMLElement *_target, const char * name) { return *((Interop::Quaternion *) &(_target->GetQuaternion (Urho3D::String(name)))); } DllExport Urho3D::Variant XmlElement_GetVariant (Urho3D::XMLElement *_target) { return _target->GetVariant (); } DllExport Urho3D::Variant XmlElement_GetVariantValue (Urho3D::XMLElement *_target, enum Urho3D::VariantType type) { return _target->GetVariantValue (type); } DllExport Urho3D::ResourceRef XmlElement_GetResourceRef (Urho3D::XMLElement *_target) { return _target->GetResourceRef (); } DllExport Urho3D::ResourceRefList XmlElement_GetResourceRefList (Urho3D::XMLElement *_target) { return _target->GetResourceRefList (); } DllExport Interop::Vector2 XmlElement_GetVector2 (Urho3D::XMLElement *_target, const char * name) { return *((Interop::Vector2 *) &(_target->GetVector2 (Urho3D::String(name)))); } DllExport Interop::Vector3 XmlElement_GetVector3 (Urho3D::XMLElement *_target, const char * name) { return *((Interop::Vector3 *) &(_target->GetVector3 (Urho3D::String(name)))); } DllExport Interop::Vector4 XmlElement_GetVector4 (Urho3D::XMLElement *_target, const char * name) { return *((Interop::Vector4 *) &(_target->GetVector4 (Urho3D::String(name)))); } DllExport Interop::Vector4 XmlElement_GetVector (Urho3D::XMLElement *_target, const char * name) { return *((Interop::Vector4 *) &(_target->GetVector (Urho3D::String(name)))); } DllExport Urho3D::Variant XmlElement_GetVectorVariant (Urho3D::XMLElement *_target, const char * name) { return _target->GetVectorVariant (Urho3D::String(name)); } DllExport Urho3D::Matrix3 XmlElement_GetMatrix3 (Urho3D::XMLElement *_target, const char * name) { return _target->GetMatrix3 (Urho3D::String(name)); } DllExport Interop::Matrix3x4 XmlElement_GetMatrix3x4 (Urho3D::XMLElement *_target, const char * name) { return *((Interop::Matrix3x4 *) &(_target->GetMatrix3x4 (Urho3D::String(name)))); } DllExport Interop::Matrix4 XmlElement_GetMatrix4 (Urho3D::XMLElement *_target, const char * name) { return *((Interop::Matrix4 *) &(_target->GetMatrix4 (Urho3D::String(name)))); } DllExport Urho3D::XMLFile * XmlElement_GetFile (Urho3D::XMLElement *_target) { return _target->GetFile (); } DllExport const class Urho3D::XPathResultSet * XmlElement_GetXPathResultSet (Urho3D::XMLElement *_target) { return _target->GetXPathResultSet (); } DllExport unsigned int XmlElement_GetXPathResultIndex (Urho3D::XMLElement *_target) { return _target->GetXPathResultIndex (); } DllExport Urho3D::XMLElement * XmlElement_NextResult (Urho3D::XMLElement *_target) { return new Urho3D::XMLElement (_target->NextResult ()); } DllExport int XmlFile_GetType (Urho3D::XMLFile *_target) { return (_target->GetType ()).Value (); } DllExport const char * XmlFile_GetTypeName (Urho3D::XMLFile *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int XmlFile_GetTypeStatic () { return (XMLFile::GetTypeStatic ()).Value (); } DllExport const char * XmlFile_GetTypeNameStatic () { return stringdup((XMLFile::GetTypeNameStatic ()).CString ()); } DllExport void * XmlFile_XMLFile (Urho3D::Context * context) { return WeakPtr<XMLFile>(new XMLFile(context)); } DllExport void XmlFile_RegisterObject (Urho3D::Context * context) { XMLFile::RegisterObject (context); } DllExport int XmlFile_BeginLoad_File (Urho3D::XMLFile *_target, File * source) { return _target->BeginLoad (*source); } DllExport int XmlFile_BeginLoad_MemoryBuffer (Urho3D::XMLFile *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int XmlFile_Save_File (Urho3D::XMLFile *_target, File * dest) { return _target->Save (*dest); } DllExport int XmlFile_Save_MemoryBuffer (Urho3D::XMLFile *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int XmlFile_Save0_File (Urho3D::XMLFile *_target, File * dest, const char * indentation) { return _target->Save (*dest, Urho3D::String(indentation)); } DllExport int XmlFile_Save0_MemoryBuffer (Urho3D::XMLFile *_target, MemoryBuffer * dest, const char * indentation) { return _target->Save (*dest, Urho3D::String(indentation)); } DllExport int XmlFile_FromString (Urho3D::XMLFile *_target, const char * source) { return _target->FromString (Urho3D::String(source)); } DllExport Urho3D::XMLElement * XmlFile_CreateRoot (Urho3D::XMLFile *_target, const char * name) { return new Urho3D::XMLElement (_target->CreateRoot (Urho3D::String(name))); } DllExport Urho3D::XMLElement * XmlFile_GetOrCreateRoot (Urho3D::XMLFile *_target, const char * name) { return new Urho3D::XMLElement (_target->GetOrCreateRoot (Urho3D::String(name))); } DllExport Urho3D::XMLElement * XmlFile_GetRoot (Urho3D::XMLFile *_target, const char * name) { return new Urho3D::XMLElement (_target->GetRoot (Urho3D::String(name))); } DllExport const char * XmlFile_ToString (Urho3D::XMLFile *_target, const char * indentation) { return stringdup((_target->ToString (Urho3D::String(indentation))).CString ()); } DllExport void XmlFile_Patch (Urho3D::XMLFile *_target, Urho3D::XMLFile * patchFile) { _target->Patch (patchFile); } DllExport void XmlFile_Patch1 (Urho3D::XMLFile *_target, Urho3D::XMLElement patchElement) { _target->Patch (patchElement); } DllExport int ShaderPrecache_GetType (Urho3D::ShaderPrecache *_target) { return (_target->GetType ()).Value (); } DllExport const char * ShaderPrecache_GetTypeName (Urho3D::ShaderPrecache *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ShaderPrecache_GetTypeStatic () { return (ShaderPrecache::GetTypeStatic ()).Value (); } DllExport const char * ShaderPrecache_GetTypeNameStatic () { return stringdup((ShaderPrecache::GetTypeNameStatic ()).CString ()); } DllExport void * ShaderPrecache_ShaderPrecache (Urho3D::Context * context, const char * fileName) { return WeakPtr<ShaderPrecache>(new ShaderPrecache(context, Urho3D::String(fileName))); } DllExport void ShaderPrecache_StoreShaders (Urho3D::ShaderPrecache *_target, Urho3D::ShaderVariation * vs, Urho3D::ShaderVariation * ps) { _target->StoreShaders (vs, ps); } DllExport void ShaderPrecache_LoadShaders_File (Urho3D::Graphics * graphics, File * source) { ShaderPrecache::LoadShaders (graphics, *source); } DllExport void ShaderPrecache_LoadShaders_MemoryBuffer (Urho3D::Graphics * graphics, MemoryBuffer * source) { ShaderPrecache::LoadShaders (graphics, *source); } DllExport int Skybox_GetType (Urho3D::Skybox *_target) { return (_target->GetType ()).Value (); } DllExport const char * Skybox_GetTypeName (Urho3D::Skybox *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Skybox_GetTypeStatic () { return (Skybox::GetTypeStatic ()).Value (); } DllExport const char * Skybox_GetTypeNameStatic () { return stringdup((Skybox::GetTypeNameStatic ()).CString ()); } DllExport void * Skybox_Skybox (Urho3D::Context * context) { return WeakPtr<Skybox>(new Skybox(context)); } DllExport void Skybox_RegisterObject (Urho3D::Context * context) { Skybox::RegisterObject (context); } DllExport int StaticModelGroup_GetType (Urho3D::StaticModelGroup *_target) { return (_target->GetType ()).Value (); } DllExport const char * StaticModelGroup_GetTypeName (Urho3D::StaticModelGroup *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int StaticModelGroup_GetTypeStatic () { return (StaticModelGroup::GetTypeStatic ()).Value (); } DllExport const char * StaticModelGroup_GetTypeNameStatic () { return stringdup((StaticModelGroup::GetTypeNameStatic ()).CString ()); } DllExport void * StaticModelGroup_StaticModelGroup (Urho3D::Context * context) { return WeakPtr<StaticModelGroup>(new StaticModelGroup(context)); } DllExport void StaticModelGroup_RegisterObject (Urho3D::Context * context) { StaticModelGroup::RegisterObject (context); } DllExport void StaticModelGroup_ApplyAttributes (Urho3D::StaticModelGroup *_target) { _target->ApplyAttributes (); } DllExport unsigned int StaticModelGroup_GetNumOccluderTriangles (Urho3D::StaticModelGroup *_target) { return _target->GetNumOccluderTriangles (); } DllExport int StaticModelGroup_DrawOcclusion (Urho3D::StaticModelGroup *_target, Urho3D::OcclusionBuffer * buffer) { return _target->DrawOcclusion (buffer); } DllExport void StaticModelGroup_AddInstanceNode (Urho3D::StaticModelGroup *_target, Urho3D::Node * node) { _target->AddInstanceNode (node); } DllExport void StaticModelGroup_RemoveInstanceNode (Urho3D::StaticModelGroup *_target, Urho3D::Node * node) { _target->RemoveInstanceNode (node); } DllExport void StaticModelGroup_RemoveAllInstanceNodes (Urho3D::StaticModelGroup *_target) { _target->RemoveAllInstanceNodes (); } DllExport unsigned int StaticModelGroup_GetNumInstanceNodes (Urho3D::StaticModelGroup *_target) { return _target->GetNumInstanceNodes (); } DllExport Urho3D::Node * StaticModelGroup_GetInstanceNode (Urho3D::StaticModelGroup *_target, unsigned int index) { return _target->GetInstanceNode (index); } DllExport void * Pass_Pass (const char * passName) { return WeakPtr<Pass>(new Pass(Urho3D::String(passName))); } DllExport void Pass_SetBlendMode (Urho3D::Pass *_target, enum Urho3D::BlendMode mode) { _target->SetBlendMode (mode); } DllExport void Pass_SetCullMode (Urho3D::Pass *_target, enum Urho3D::CullMode mode) { _target->SetCullMode (mode); } DllExport void Pass_SetDepthTestMode (Urho3D::Pass *_target, enum Urho3D::CompareMode mode) { _target->SetDepthTestMode (mode); } DllExport void Pass_SetLightingMode (Urho3D::Pass *_target, enum Urho3D::PassLightingMode mode) { _target->SetLightingMode (mode); } DllExport void Pass_SetDepthWrite (Urho3D::Pass *_target, bool enable) { _target->SetDepthWrite (enable); } DllExport void Pass_SetAlphaToCoverage (Urho3D::Pass *_target, bool enable) { _target->SetAlphaToCoverage (enable); } DllExport void Pass_SetIsDesktop (Urho3D::Pass *_target, bool enable) { _target->SetIsDesktop (enable); } DllExport void Pass_SetVertexShader (Urho3D::Pass *_target, const char * name) { _target->SetVertexShader (Urho3D::String(name)); } DllExport void Pass_SetPixelShader (Urho3D::Pass *_target, const char * name) { _target->SetPixelShader (Urho3D::String(name)); } DllExport void Pass_SetVertexShaderDefines (Urho3D::Pass *_target, const char * defines) { _target->SetVertexShaderDefines (Urho3D::String(defines)); } DllExport void Pass_SetPixelShaderDefines (Urho3D::Pass *_target, const char * defines) { _target->SetPixelShaderDefines (Urho3D::String(defines)); } DllExport void Pass_SetVertexShaderDefineExcludes (Urho3D::Pass *_target, const char * excludes) { _target->SetVertexShaderDefineExcludes (Urho3D::String(excludes)); } DllExport void Pass_SetPixelShaderDefineExcludes (Urho3D::Pass *_target, const char * excludes) { _target->SetPixelShaderDefineExcludes (Urho3D::String(excludes)); } DllExport void Pass_ReleaseShaders (Urho3D::Pass *_target) { _target->ReleaseShaders (); } DllExport void Pass_MarkShadersLoaded (Urho3D::Pass *_target, unsigned int frameNumber) { _target->MarkShadersLoaded (frameNumber); } DllExport const char * Pass_GetName (Urho3D::Pass *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport unsigned int Pass_GetIndex (Urho3D::Pass *_target) { return _target->GetIndex (); } DllExport enum Urho3D::BlendMode Pass_GetBlendMode (Urho3D::Pass *_target) { return _target->GetBlendMode (); } DllExport enum Urho3D::CullMode Pass_GetCullMode (Urho3D::Pass *_target) { return _target->GetCullMode (); } DllExport enum Urho3D::CompareMode Pass_GetDepthTestMode (Urho3D::Pass *_target) { return _target->GetDepthTestMode (); } DllExport enum Urho3D::PassLightingMode Pass_GetLightingMode (Urho3D::Pass *_target) { return _target->GetLightingMode (); } DllExport unsigned int Pass_GetShadersLoadedFrameNumber (Urho3D::Pass *_target) { return _target->GetShadersLoadedFrameNumber (); } DllExport int Pass_GetDepthWrite (Urho3D::Pass *_target) { return _target->GetDepthWrite (); } DllExport int Pass_GetAlphaToCoverage (Urho3D::Pass *_target) { return _target->GetAlphaToCoverage (); } DllExport int Pass_IsDesktop (Urho3D::Pass *_target) { return _target->IsDesktop (); } DllExport const char * Pass_GetVertexShader (Urho3D::Pass *_target) { return stringdup((_target->GetVertexShader ()).CString ()); } DllExport const char * Pass_GetPixelShader (Urho3D::Pass *_target) { return stringdup((_target->GetPixelShader ()).CString ()); } DllExport const char * Pass_GetVertexShaderDefines (Urho3D::Pass *_target) { return stringdup((_target->GetVertexShaderDefines ()).CString ()); } DllExport const char * Pass_GetPixelShaderDefines (Urho3D::Pass *_target) { return stringdup((_target->GetPixelShaderDefines ()).CString ()); } DllExport const char * Pass_GetVertexShaderDefineExcludes (Urho3D::Pass *_target) { return stringdup((_target->GetVertexShaderDefineExcludes ()).CString ()); } DllExport const char * Pass_GetPixelShaderDefineExcludes (Urho3D::Pass *_target) { return stringdup((_target->GetPixelShaderDefineExcludes ()).CString ()); } DllExport const char * Pass_GetEffectiveVertexShaderDefines (Urho3D::Pass *_target) { return stringdup((_target->GetEffectiveVertexShaderDefines ()).CString ()); } DllExport const char * Pass_GetEffectivePixelShaderDefines (Urho3D::Pass *_target) { return stringdup((_target->GetEffectivePixelShaderDefines ()).CString ()); } DllExport int Technique_GetType (Urho3D::Technique *_target) { return (_target->GetType ()).Value (); } DllExport const char * Technique_GetTypeName (Urho3D::Technique *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Technique_GetTypeStatic () { return (Technique::GetTypeStatic ()).Value (); } DllExport const char * Technique_GetTypeNameStatic () { return stringdup((Technique::GetTypeNameStatic ()).CString ()); } DllExport void * Technique_Technique (Urho3D::Context * context) { return WeakPtr<Technique>(new Technique(context)); } DllExport void Technique_RegisterObject (Urho3D::Context * context) { Technique::RegisterObject (context); } DllExport int Technique_BeginLoad_File (Urho3D::Technique *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Technique_BeginLoad_MemoryBuffer (Urho3D::Technique *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport void Technique_SetIsDesktop (Urho3D::Technique *_target, bool enable) { _target->SetIsDesktop (enable); } DllExport Urho3D::Pass * Technique_CreatePass (Urho3D::Technique *_target, const char * passName) { return _target->CreatePass (Urho3D::String(passName)); } DllExport void Technique_RemovePass (Urho3D::Technique *_target, const char * passName) { _target->RemovePass (Urho3D::String(passName)); } DllExport void Technique_ReleaseShaders (Urho3D::Technique *_target) { _target->ReleaseShaders (); } DllExport Urho3D::Technique * Technique_Clone (Urho3D::Technique *_target, const char * cloneName) { auto copy = _target->Clone (Urho3D::String(cloneName)); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport int Technique_IsDesktop (Urho3D::Technique *_target) { return _target->IsDesktop (); } DllExport int Technique_IsSupported (Urho3D::Technique *_target) { return _target->IsSupported (); } DllExport int Technique_HasPass (Urho3D::Technique *_target, unsigned int passIndex) { return _target->HasPass (passIndex); } DllExport int Technique_HasPass0 (Urho3D::Technique *_target, const char * passName) { return _target->HasPass (Urho3D::String(passName)); } DllExport Urho3D::Pass * Technique_GetPass (Urho3D::Technique *_target, unsigned int passIndex) { return _target->GetPass (passIndex); } DllExport Urho3D::Pass * Technique_GetPass1 (Urho3D::Technique *_target, const char * passName) { return _target->GetPass (Urho3D::String(passName)); } DllExport Urho3D::Pass * Technique_GetSupportedPass (Urho3D::Technique *_target, unsigned int passIndex) { return _target->GetSupportedPass (passIndex); } DllExport Urho3D::Pass * Technique_GetSupportedPass2 (Urho3D::Technique *_target, const char * passName) { return _target->GetSupportedPass (Urho3D::String(passName)); } DllExport unsigned int Technique_GetNumPasses (Urho3D::Technique *_target) { return _target->GetNumPasses (); } DllExport Urho3D::Technique * Technique_CloneWithDefines (Urho3D::Technique *_target, const char * vsDefines, const char * psDefines) { auto copy = _target->CloneWithDefines (Urho3D::String(vsDefines), Urho3D::String(psDefines)); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport unsigned int Technique_GetPassIndex (const char * passName) { return Technique::GetPassIndex (Urho3D::String(passName)); } DllExport int Terrain_GetType (Urho3D::Terrain *_target) { return (_target->GetType ()).Value (); } DllExport const char * Terrain_GetTypeName (Urho3D::Terrain *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Terrain_GetTypeStatic () { return (Terrain::GetTypeStatic ()).Value (); } DllExport const char * Terrain_GetTypeNameStatic () { return stringdup((Terrain::GetTypeNameStatic ()).CString ()); } DllExport void * Terrain_Terrain (Urho3D::Context * context) { return WeakPtr<Terrain>(new Terrain(context)); } DllExport void Terrain_RegisterObject (Urho3D::Context * context) { Terrain::RegisterObject (context); } DllExport void Terrain_ApplyAttributes (Urho3D::Terrain *_target) { _target->ApplyAttributes (); } DllExport void Terrain_OnSetEnabled (Urho3D::Terrain *_target) { _target->OnSetEnabled (); } DllExport void Terrain_SetPatchSize (Urho3D::Terrain *_target, int size) { _target->SetPatchSize (size); } DllExport void Terrain_SetSpacing (Urho3D::Terrain *_target, const class Urho3D::Vector3 & spacing) { _target->SetSpacing (spacing); } DllExport void Terrain_SetMaxLodLevels (Urho3D::Terrain *_target, unsigned int levels) { _target->SetMaxLodLevels (levels); } DllExport void Terrain_SetOcclusionLodLevel (Urho3D::Terrain *_target, unsigned int level) { _target->SetOcclusionLodLevel (level); } DllExport void Terrain_SetSmoothing (Urho3D::Terrain *_target, bool enable) { _target->SetSmoothing (enable); } DllExport int Terrain_SetHeightMap (Urho3D::Terrain *_target, Urho3D::Image * image) { return _target->SetHeightMap (image); } DllExport void Terrain_SetMaterial (Urho3D::Terrain *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport void Terrain_SetNorthNeighbor (Urho3D::Terrain *_target, Urho3D::Terrain * north) { _target->SetNorthNeighbor (north); } DllExport void Terrain_SetSouthNeighbor (Urho3D::Terrain *_target, Urho3D::Terrain * south) { _target->SetSouthNeighbor (south); } DllExport void Terrain_SetWestNeighbor (Urho3D::Terrain *_target, Urho3D::Terrain * west) { _target->SetWestNeighbor (west); } DllExport void Terrain_SetEastNeighbor (Urho3D::Terrain *_target, Urho3D::Terrain * east) { _target->SetEastNeighbor (east); } DllExport void Terrain_SetNeighbors (Urho3D::Terrain *_target, Urho3D::Terrain * north, Urho3D::Terrain * south, Urho3D::Terrain * west, Urho3D::Terrain * east) { _target->SetNeighbors (north, south, west, east); } DllExport void Terrain_SetDrawDistance (Urho3D::Terrain *_target, float distance) { _target->SetDrawDistance (distance); } DllExport void Terrain_SetShadowDistance (Urho3D::Terrain *_target, float distance) { _target->SetShadowDistance (distance); } DllExport void Terrain_SetLodBias (Urho3D::Terrain *_target, float bias) { _target->SetLodBias (bias); } DllExport void Terrain_SetViewMask (Urho3D::Terrain *_target, unsigned int mask) { _target->SetViewMask (mask); } DllExport void Terrain_SetLightMask (Urho3D::Terrain *_target, unsigned int mask) { _target->SetLightMask (mask); } DllExport void Terrain_SetShadowMask (Urho3D::Terrain *_target, unsigned int mask) { _target->SetShadowMask (mask); } DllExport void Terrain_SetZoneMask (Urho3D::Terrain *_target, unsigned int mask) { _target->SetZoneMask (mask); } DllExport void Terrain_SetMaxLights (Urho3D::Terrain *_target, unsigned int num) { _target->SetMaxLights (num); } DllExport void Terrain_SetCastShadows (Urho3D::Terrain *_target, bool enable) { _target->SetCastShadows (enable); } DllExport void Terrain_SetOccluder (Urho3D::Terrain *_target, bool enable) { _target->SetOccluder (enable); } DllExport void Terrain_SetOccludee (Urho3D::Terrain *_target, bool enable) { _target->SetOccludee (enable); } DllExport void Terrain_ApplyHeightMap (Urho3D::Terrain *_target) { _target->ApplyHeightMap (); } DllExport int Terrain_GetPatchSize (Urho3D::Terrain *_target) { return _target->GetPatchSize (); } DllExport Interop::Vector3 Terrain_GetSpacing (Urho3D::Terrain *_target) { return *((Interop::Vector3 *) &(_target->GetSpacing ())); } DllExport Interop::IntVector2 Terrain_GetNumVertices (Urho3D::Terrain *_target) { return *((Interop::IntVector2 *) &(_target->GetNumVertices ())); } DllExport Interop::IntVector2 Terrain_GetNumPatches (Urho3D::Terrain *_target) { return *((Interop::IntVector2 *) &(_target->GetNumPatches ())); } DllExport unsigned int Terrain_GetMaxLodLevels (Urho3D::Terrain *_target) { return _target->GetMaxLodLevels (); } DllExport unsigned int Terrain_GetOcclusionLodLevel (Urho3D::Terrain *_target) { return _target->GetOcclusionLodLevel (); } DllExport int Terrain_GetSmoothing (Urho3D::Terrain *_target) { return _target->GetSmoothing (); } DllExport Urho3D::Image * Terrain_GetHeightMap (Urho3D::Terrain *_target) { return _target->GetHeightMap (); } DllExport Urho3D::Material * Terrain_GetMaterial (Urho3D::Terrain *_target) { return _target->GetMaterial (); } DllExport Urho3D::TerrainPatch * Terrain_GetPatch (Urho3D::Terrain *_target, unsigned int index) { return _target->GetPatch (index); } DllExport Urho3D::TerrainPatch * Terrain_GetPatch0 (Urho3D::Terrain *_target, int x, int z) { return _target->GetPatch (x, z); } DllExport Urho3D::TerrainPatch * Terrain_GetNeighborPatch (Urho3D::Terrain *_target, int x, int z) { return _target->GetNeighborPatch (x, z); } DllExport float Terrain_GetHeight (Urho3D::Terrain *_target, const class Urho3D::Vector3 & worldPosition) { return _target->GetHeight (worldPosition); } DllExport Interop::Vector3 Terrain_GetNormal (Urho3D::Terrain *_target, const class Urho3D::Vector3 & worldPosition) { return *((Interop::Vector3 *) &(_target->GetNormal (worldPosition))); } DllExport Interop::IntVector2 Terrain_WorldToHeightMap (Urho3D::Terrain *_target, const class Urho3D::Vector3 & worldPosition) { return *((Interop::IntVector2 *) &(_target->WorldToHeightMap (worldPosition))); } DllExport Interop::Vector3 Terrain_HeightMapToWorld (Urho3D::Terrain *_target, const class Urho3D::IntVector2 & pixelPosition) { return *((Interop::Vector3 *) &(_target->HeightMapToWorld (pixelPosition))); } DllExport Urho3D::Terrain * Terrain_GetNorthNeighbor (Urho3D::Terrain *_target) { return _target->GetNorthNeighbor (); } DllExport Urho3D::Terrain * Terrain_GetSouthNeighbor (Urho3D::Terrain *_target) { return _target->GetSouthNeighbor (); } DllExport Urho3D::Terrain * Terrain_GetWestNeighbor (Urho3D::Terrain *_target) { return _target->GetWestNeighbor (); } DllExport Urho3D::Terrain * Terrain_GetEastNeighbor (Urho3D::Terrain *_target) { return _target->GetEastNeighbor (); } DllExport float Terrain_GetDrawDistance (Urho3D::Terrain *_target) { return _target->GetDrawDistance (); } DllExport float Terrain_GetShadowDistance (Urho3D::Terrain *_target) { return _target->GetShadowDistance (); } DllExport float Terrain_GetLodBias (Urho3D::Terrain *_target) { return _target->GetLodBias (); } DllExport unsigned int Terrain_GetViewMask (Urho3D::Terrain *_target) { return _target->GetViewMask (); } DllExport unsigned int Terrain_GetLightMask (Urho3D::Terrain *_target) { return _target->GetLightMask (); } DllExport unsigned int Terrain_GetShadowMask (Urho3D::Terrain *_target) { return _target->GetShadowMask (); } DllExport unsigned int Terrain_GetZoneMask (Urho3D::Terrain *_target) { return _target->GetZoneMask (); } DllExport unsigned int Terrain_GetMaxLights (Urho3D::Terrain *_target) { return _target->GetMaxLights (); } DllExport int Terrain_IsVisible (Urho3D::Terrain *_target) { return _target->IsVisible (); } DllExport int Terrain_GetCastShadows (Urho3D::Terrain *_target) { return _target->GetCastShadows (); } DllExport int Terrain_IsOccluder (Urho3D::Terrain *_target) { return _target->IsOccluder (); } DllExport int Terrain_IsOccludee (Urho3D::Terrain *_target) { return _target->IsOccludee (); } DllExport void Terrain_CreatePatchGeometry (Urho3D::Terrain *_target, Urho3D::TerrainPatch * patch) { _target->CreatePatchGeometry (patch); } DllExport void Terrain_UpdatePatchLod (Urho3D::Terrain *_target, Urho3D::TerrainPatch * patch) { _target->UpdatePatchLod (patch); } DllExport void Terrain_SetPatchSizeAttr (Urho3D::Terrain *_target, int value) { _target->SetPatchSizeAttr (value); } DllExport void Terrain_SetMaxLodLevelsAttr (Urho3D::Terrain *_target, unsigned int value) { _target->SetMaxLodLevelsAttr (value); } DllExport void Terrain_SetOcclusionLodLevelAttr (Urho3D::Terrain *_target, unsigned int value) { _target->SetOcclusionLodLevelAttr (value); } DllExport Urho3D::ResourceRef Terrain_GetHeightMapAttr (Urho3D::Terrain *_target) { return _target->GetHeightMapAttr (); } DllExport Urho3D::ResourceRef Terrain_GetMaterialAttr (Urho3D::Terrain *_target) { return _target->GetMaterialAttr (); } DllExport int TerrainPatch_GetType (Urho3D::TerrainPatch *_target) { return (_target->GetType ()).Value (); } DllExport const char * TerrainPatch_GetTypeName (Urho3D::TerrainPatch *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int TerrainPatch_GetTypeStatic () { return (TerrainPatch::GetTypeStatic ()).Value (); } DllExport const char * TerrainPatch_GetTypeNameStatic () { return stringdup((TerrainPatch::GetTypeNameStatic ()).CString ()); } DllExport void * TerrainPatch_TerrainPatch (Urho3D::Context * context) { return WeakPtr<TerrainPatch>(new TerrainPatch(context)); } DllExport void TerrainPatch_RegisterObject (Urho3D::Context * context) { TerrainPatch::RegisterObject (context); } DllExport enum Urho3D::UpdateGeometryType TerrainPatch_GetUpdateGeometryType (Urho3D::TerrainPatch *_target) { return _target->GetUpdateGeometryType (); } DllExport Urho3D::Geometry * TerrainPatch_GetLodGeometry (Urho3D::TerrainPatch *_target, unsigned int batchIndex, unsigned int level) { return _target->GetLodGeometry (batchIndex, level); } DllExport unsigned int TerrainPatch_GetNumOccluderTriangles (Urho3D::TerrainPatch *_target) { return _target->GetNumOccluderTriangles (); } DllExport int TerrainPatch_DrawOcclusion (Urho3D::TerrainPatch *_target, Urho3D::OcclusionBuffer * buffer) { return _target->DrawOcclusion (buffer); } DllExport void TerrainPatch_DrawDebugGeometry (Urho3D::TerrainPatch *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void TerrainPatch_SetOwner (Urho3D::TerrainPatch *_target, Urho3D::Terrain * terrain) { _target->SetOwner (terrain); } DllExport void TerrainPatch_SetNeighbors (Urho3D::TerrainPatch *_target, Urho3D::TerrainPatch * north, Urho3D::TerrainPatch * south, Urho3D::TerrainPatch * west, Urho3D::TerrainPatch * east) { _target->SetNeighbors (north, south, west, east); } DllExport void TerrainPatch_SetMaterial (Urho3D::TerrainPatch *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport void TerrainPatch_SetBoundingBox (Urho3D::TerrainPatch *_target, const class Urho3D::BoundingBox & box) { _target->SetBoundingBox (box); } DllExport void TerrainPatch_SetCoordinates (Urho3D::TerrainPatch *_target, const class Urho3D::IntVector2 & coordinates) { _target->SetCoordinates (coordinates); } DllExport void TerrainPatch_ResetLod (Urho3D::TerrainPatch *_target) { _target->ResetLod (); } DllExport Urho3D::Geometry * TerrainPatch_GetGeometry (Urho3D::TerrainPatch *_target) { return _target->GetGeometry (); } DllExport Urho3D::Geometry * TerrainPatch_GetMaxLodGeometry (Urho3D::TerrainPatch *_target) { return _target->GetMaxLodGeometry (); } DllExport Urho3D::Geometry * TerrainPatch_GetOcclusionGeometry (Urho3D::TerrainPatch *_target) { return _target->GetOcclusionGeometry (); } DllExport Urho3D::VertexBuffer * TerrainPatch_GetVertexBuffer (Urho3D::TerrainPatch *_target) { return _target->GetVertexBuffer (); } DllExport Urho3D::Terrain * TerrainPatch_GetOwner (Urho3D::TerrainPatch *_target) { return _target->GetOwner (); } DllExport Urho3D::TerrainPatch * TerrainPatch_GetNorthPatch (Urho3D::TerrainPatch *_target) { return _target->GetNorthPatch (); } DllExport Urho3D::TerrainPatch * TerrainPatch_GetSouthPatch (Urho3D::TerrainPatch *_target) { return _target->GetSouthPatch (); } DllExport Urho3D::TerrainPatch * TerrainPatch_GetWestPatch (Urho3D::TerrainPatch *_target) { return _target->GetWestPatch (); } DllExport Urho3D::TerrainPatch * TerrainPatch_GetEastPatch (Urho3D::TerrainPatch *_target) { return _target->GetEastPatch (); } DllExport Interop::IntVector2 TerrainPatch_GetCoordinates (Urho3D::TerrainPatch *_target) { return *((Interop::IntVector2 *) &(_target->GetCoordinates ())); } DllExport unsigned int TerrainPatch_GetLodLevel (Urho3D::TerrainPatch *_target) { return _target->GetLodLevel (); } DllExport int Texture2DArray_GetType (Urho3D::Texture2DArray *_target) { return (_target->GetType ()).Value (); } DllExport const char * Texture2DArray_GetTypeName (Urho3D::Texture2DArray *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Texture2DArray_GetTypeStatic () { return (Texture2DArray::GetTypeStatic ()).Value (); } DllExport const char * Texture2DArray_GetTypeNameStatic () { return stringdup((Texture2DArray::GetTypeNameStatic ()).CString ()); } DllExport void * Texture2DArray_Texture2DArray (Urho3D::Context * context) { return WeakPtr<Texture2DArray>(new Texture2DArray(context)); } DllExport void Texture2DArray_RegisterObject (Urho3D::Context * context) { Texture2DArray::RegisterObject (context); } DllExport int Texture2DArray_BeginLoad_File (Urho3D::Texture2DArray *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Texture2DArray_BeginLoad_MemoryBuffer (Urho3D::Texture2DArray *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Texture2DArray_EndLoad (Urho3D::Texture2DArray *_target) { return _target->EndLoad (); } DllExport void Texture2DArray_OnDeviceLost (Urho3D::Texture2DArray *_target) { _target->OnDeviceLost (); } DllExport void Texture2DArray_OnDeviceReset (Urho3D::Texture2DArray *_target) { _target->OnDeviceReset (); } DllExport void Texture2DArray_Release (Urho3D::Texture2DArray *_target) { _target->Release (); } DllExport void Texture2DArray_SetLayers (Urho3D::Texture2DArray *_target, unsigned int layers) { _target->SetLayers (layers); } DllExport int Texture2DArray_SetSize (Urho3D::Texture2DArray *_target, unsigned int layers, int width, int height, unsigned int format, enum Urho3D::TextureUsage usage) { return _target->SetSize (layers, width, height, format, usage); } DllExport int Texture2DArray_SetData (Urho3D::Texture2DArray *_target, unsigned int layer, unsigned int level, int x, int y, int width, int height, const void * data) { return _target->SetData (layer, level, x, y, width, height, data); } DllExport int Texture2DArray_SetData0_File (Urho3D::Texture2DArray *_target, unsigned int layer, File * source) { return _target->SetData (layer, *source); } DllExport int Texture2DArray_SetData0_MemoryBuffer (Urho3D::Texture2DArray *_target, unsigned int layer, MemoryBuffer * source) { return _target->SetData (layer, *source); } DllExport int Texture2DArray_SetData1 (Urho3D::Texture2DArray *_target, unsigned int layer, Urho3D::Image * image, bool useAlpha) { return _target->SetData (layer, image, useAlpha); } DllExport unsigned int Texture2DArray_GetLayers (Urho3D::Texture2DArray *_target) { return _target->GetLayers (); } DllExport int Texture2DArray_GetData (Urho3D::Texture2DArray *_target, unsigned int layer, unsigned int level, void * dest) { return _target->GetData (layer, level, dest); } DllExport Urho3D::RenderSurface * Texture2DArray_GetRenderSurface (Urho3D::Texture2DArray *_target) { return _target->GetRenderSurface (); } DllExport int Texture3D_GetType (Urho3D::Texture3D *_target) { return (_target->GetType ()).Value (); } DllExport const char * Texture3D_GetTypeName (Urho3D::Texture3D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Texture3D_GetTypeStatic () { return (Texture3D::GetTypeStatic ()).Value (); } DllExport const char * Texture3D_GetTypeNameStatic () { return stringdup((Texture3D::GetTypeNameStatic ()).CString ()); } DllExport void * Texture3D_Texture3D (Urho3D::Context * context) { return WeakPtr<Texture3D>(new Texture3D(context)); } DllExport void Texture3D_RegisterObject (Urho3D::Context * context) { Texture3D::RegisterObject (context); } DllExport int Texture3D_BeginLoad_File (Urho3D::Texture3D *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Texture3D_BeginLoad_MemoryBuffer (Urho3D::Texture3D *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Texture3D_EndLoad (Urho3D::Texture3D *_target) { return _target->EndLoad (); } DllExport void Texture3D_Release (Urho3D::Texture3D *_target) { _target->Release (); } DllExport int Texture3D_SetSize (Urho3D::Texture3D *_target, int width, int height, int depth, unsigned int format, enum Urho3D::TextureUsage usage) { return _target->SetSize (width, height, depth, format, usage); } DllExport int Texture3D_SetData (Urho3D::Texture3D *_target, unsigned int level, int x, int y, int z, int width, int height, int depth, const void * data) { return _target->SetData (level, x, y, z, width, height, depth, data); } DllExport int Texture3D_SetData0 (Urho3D::Texture3D *_target, Urho3D::Image * image, bool useAlpha) { return _target->SetData (image, useAlpha); } DllExport int Texture3D_GetData (Urho3D::Texture3D *_target, unsigned int level, void * dest) { return _target->GetData (level, dest); } DllExport int TextureCube_GetType (Urho3D::TextureCube *_target) { return (_target->GetType ()).Value (); } DllExport const char * TextureCube_GetTypeName (Urho3D::TextureCube *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int TextureCube_GetTypeStatic () { return (TextureCube::GetTypeStatic ()).Value (); } DllExport const char * TextureCube_GetTypeNameStatic () { return stringdup((TextureCube::GetTypeNameStatic ()).CString ()); } DllExport void * TextureCube_TextureCube (Urho3D::Context * context) { return WeakPtr<TextureCube>(new TextureCube(context)); } DllExport void TextureCube_RegisterObject (Urho3D::Context * context) { TextureCube::RegisterObject (context); } DllExport int TextureCube_BeginLoad_File (Urho3D::TextureCube *_target, File * source) { return _target->BeginLoad (*source); } DllExport int TextureCube_BeginLoad_MemoryBuffer (Urho3D::TextureCube *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int TextureCube_EndLoad (Urho3D::TextureCube *_target) { return _target->EndLoad (); } DllExport void TextureCube_Release (Urho3D::TextureCube *_target) { _target->Release (); } DllExport int TextureCube_SetSize (Urho3D::TextureCube *_target, int size, unsigned int format, enum Urho3D::TextureUsage usage, int multiSample) { return _target->SetSize (size, format, usage, multiSample); } DllExport int TextureCube_SetData (Urho3D::TextureCube *_target, enum Urho3D::CubeMapFace face, unsigned int level, int x, int y, int width, int height, const void * data) { return _target->SetData (face, level, x, y, width, height, data); } DllExport int TextureCube_SetData0_File (Urho3D::TextureCube *_target, enum Urho3D::CubeMapFace face, File * source) { return _target->SetData (face, *source); } DllExport int TextureCube_SetData0_MemoryBuffer (Urho3D::TextureCube *_target, enum Urho3D::CubeMapFace face, MemoryBuffer * source) { return _target->SetData (face, *source); } DllExport int TextureCube_SetData1 (Urho3D::TextureCube *_target, enum Urho3D::CubeMapFace face, Urho3D::Image * image, bool useAlpha) { return _target->SetData (face, image, useAlpha); } DllExport int TextureCube_GetData (Urho3D::TextureCube *_target, enum Urho3D::CubeMapFace face, unsigned int level, void * dest) { return _target->GetData (face, level, dest); } DllExport Urho3D::Image * TextureCube_GetImage (Urho3D::TextureCube *_target, enum Urho3D::CubeMapFace face) { auto copy = _target->GetImage (face); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::RenderSurface * TextureCube_GetRenderSurface (Urho3D::TextureCube *_target, enum Urho3D::CubeMapFace face) { return _target->GetRenderSurface (face); } DllExport GPUObject* VertexBuffer_CastToGPUObject(Urho3D::VertexBuffer *_target) { return static_cast<GPUObject*>(_target); } DllExport int VertexBuffer_GetType (Urho3D::VertexBuffer *_target) { return (_target->GetType ()).Value (); } DllExport const char * VertexBuffer_GetTypeName (Urho3D::VertexBuffer *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int VertexBuffer_GetTypeStatic () { return (VertexBuffer::GetTypeStatic ()).Value (); } DllExport const char * VertexBuffer_GetTypeNameStatic () { return stringdup((VertexBuffer::GetTypeNameStatic ()).CString ()); } DllExport void * VertexBuffer_VertexBuffer (Urho3D::Context * context, bool forceHeadless) { return WeakPtr<VertexBuffer>(new VertexBuffer(context, forceHeadless)); } DllExport void VertexBuffer_OnDeviceLost (Urho3D::VertexBuffer *_target) { _target->OnDeviceLost (); } DllExport void VertexBuffer_Release (Urho3D::VertexBuffer *_target) { _target->Release (); } DllExport void VertexBuffer_SetShadowed (Urho3D::VertexBuffer *_target, bool enable) { _target->SetShadowed (enable); } DllExport int VertexBuffer_SetSize (Urho3D::VertexBuffer *_target, unsigned int vertexCount, unsigned int elementMask, bool dynamic) { return _target->SetSize (vertexCount, elementMask, dynamic); } DllExport int VertexBuffer_SetData (Urho3D::VertexBuffer *_target, const void * data) { return _target->SetData (data); } DllExport int VertexBuffer_SetDataRange (Urho3D::VertexBuffer *_target, const void * data, unsigned int start, unsigned int count, bool discard) { return _target->SetDataRange (data, start, count, discard); } DllExport void * VertexBuffer_Lock (Urho3D::VertexBuffer *_target, unsigned int start, unsigned int count, bool discard) { return _target->Lock (start, count, discard); } DllExport void VertexBuffer_Unlock (Urho3D::VertexBuffer *_target) { _target->Unlock (); } DllExport int VertexBuffer_IsShadowed (Urho3D::VertexBuffer *_target) { return _target->IsShadowed (); } DllExport int VertexBuffer_IsDynamic (Urho3D::VertexBuffer *_target) { return _target->IsDynamic (); } DllExport int VertexBuffer_IsLocked (Urho3D::VertexBuffer *_target) { return _target->IsLocked (); } DllExport unsigned int VertexBuffer_GetVertexCount (Urho3D::VertexBuffer *_target) { return _target->GetVertexCount (); } DllExport unsigned int VertexBuffer_GetVertexSize (Urho3D::VertexBuffer *_target) { return _target->GetVertexSize (); } DllExport const struct Urho3D::VertexElement * VertexBuffer_GetElement (Urho3D::VertexBuffer *_target, enum Urho3D::VertexElementSemantic semantic, unsigned char index) { return _target->GetElement (semantic, index); } DllExport const struct Urho3D::VertexElement * VertexBuffer_GetElement0 (Urho3D::VertexBuffer *_target, enum Urho3D::VertexElementType type, enum Urho3D::VertexElementSemantic semantic, unsigned char index) { return _target->GetElement (type, semantic, index); } DllExport int VertexBuffer_HasElement (Urho3D::VertexBuffer *_target, enum Urho3D::VertexElementSemantic semantic, unsigned char index) { return _target->HasElement (semantic, index); } DllExport int VertexBuffer_HasElement1 (Urho3D::VertexBuffer *_target, enum Urho3D::VertexElementType type, enum Urho3D::VertexElementSemantic semantic, unsigned char index) { return _target->HasElement (type, semantic, index); } DllExport unsigned int VertexBuffer_GetElementOffset (Urho3D::VertexBuffer *_target, enum Urho3D::VertexElementSemantic semantic, unsigned char index) { return _target->GetElementOffset (semantic, index); } DllExport unsigned int VertexBuffer_GetElementOffset2 (Urho3D::VertexBuffer *_target, enum Urho3D::VertexElementType type, enum Urho3D::VertexElementSemantic semantic, unsigned char index) { return _target->GetElementOffset (type, semantic, index); } DllExport unsigned int VertexBuffer_GetElementMask (Urho3D::VertexBuffer *_target) { return _target->GetElementMask (); } DllExport unsigned char * VertexBuffer_GetShadowData (Urho3D::VertexBuffer *_target) { return _target->GetShadowData (); } DllExport unsigned long long VertexBuffer_GetBufferHash (Urho3D::VertexBuffer *_target, unsigned int streamIndex) { return _target->GetBufferHash (streamIndex); } DllExport unsigned int VertexBuffer_GetVertexSize3 (unsigned int elementMask) { return VertexBuffer::GetVertexSize (elementMask); } DllExport int Zone_GetType (Urho3D::Zone *_target) { return (_target->GetType ()).Value (); } DllExport const char * Zone_GetTypeName (Urho3D::Zone *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Zone_GetTypeStatic () { return (Zone::GetTypeStatic ()).Value (); } DllExport const char * Zone_GetTypeNameStatic () { return stringdup((Zone::GetTypeNameStatic ()).CString ()); } DllExport void * Zone_Zone (Urho3D::Context * context) { return WeakPtr<Zone>(new Zone(context)); } DllExport void Zone_RegisterObject (Urho3D::Context * context) { Zone::RegisterObject (context); } DllExport void Zone_DrawDebugGeometry (Urho3D::Zone *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void Zone_SetBoundingBox (Urho3D::Zone *_target, const class Urho3D::BoundingBox & box) { _target->SetBoundingBox (box); } DllExport void Zone_SetAmbientColor (Urho3D::Zone *_target, const class Urho3D::Color & color) { _target->SetAmbientColor (color); } DllExport void Zone_SetFogColor (Urho3D::Zone *_target, const class Urho3D::Color & color) { _target->SetFogColor (color); } DllExport void Zone_SetFogStart (Urho3D::Zone *_target, float start) { _target->SetFogStart (start); } DllExport void Zone_SetFogEnd (Urho3D::Zone *_target, float end) { _target->SetFogEnd (end); } DllExport void Zone_SetFogHeight (Urho3D::Zone *_target, float height) { _target->SetFogHeight (height); } DllExport void Zone_SetFogHeightScale (Urho3D::Zone *_target, float scale) { _target->SetFogHeightScale (scale); } DllExport void Zone_SetPriority (Urho3D::Zone *_target, int priority) { _target->SetPriority (priority); } DllExport void Zone_SetHeightFog (Urho3D::Zone *_target, bool enable) { _target->SetHeightFog (enable); } DllExport void Zone_SetOverride (Urho3D::Zone *_target, bool enable) { _target->SetOverride (enable); } DllExport void Zone_SetAmbientGradient (Urho3D::Zone *_target, bool enable) { _target->SetAmbientGradient (enable); } DllExport void Zone_SetZoneTexture (Urho3D::Zone *_target, Urho3D::Texture * texture) { _target->SetZoneTexture (texture); } DllExport Interop::Matrix3x4 Zone_GetInverseWorldTransform (Urho3D::Zone *_target) { return *((Interop::Matrix3x4 *) &(_target->GetInverseWorldTransform ())); } DllExport Interop::Color Zone_GetAmbientColor (Urho3D::Zone *_target) { return *((Interop::Color *) &(_target->GetAmbientColor ())); } DllExport Interop::Color Zone_GetAmbientStartColor (Urho3D::Zone *_target) { return *((Interop::Color *) &(_target->GetAmbientStartColor ())); } DllExport Interop::Color Zone_GetAmbientEndColor (Urho3D::Zone *_target) { return *((Interop::Color *) &(_target->GetAmbientEndColor ())); } DllExport Interop::Color Zone_GetFogColor (Urho3D::Zone *_target) { return *((Interop::Color *) &(_target->GetFogColor ())); } DllExport float Zone_GetFogStart (Urho3D::Zone *_target) { return _target->GetFogStart (); } DllExport float Zone_GetFogEnd (Urho3D::Zone *_target) { return _target->GetFogEnd (); } DllExport float Zone_GetFogHeight (Urho3D::Zone *_target) { return _target->GetFogHeight (); } DllExport float Zone_GetFogHeightScale (Urho3D::Zone *_target) { return _target->GetFogHeightScale (); } DllExport int Zone_GetPriority (Urho3D::Zone *_target) { return _target->GetPriority (); } DllExport int Zone_GetHeightFog (Urho3D::Zone *_target) { return _target->GetHeightFog (); } DllExport int Zone_GetOverride (Urho3D::Zone *_target) { return _target->GetOverride (); } DllExport int Zone_GetAmbientGradient (Urho3D::Zone *_target) { return _target->GetAmbientGradient (); } DllExport Urho3D::Texture * Zone_GetZoneTexture (Urho3D::Zone *_target) { return _target->GetZoneTexture (); } DllExport int Zone_IsInside (Urho3D::Zone *_target, const class Urho3D::Vector3 & point) { return _target->IsInside (point); } DllExport Urho3D::ResourceRef Zone_GetZoneTextureAttr (Urho3D::Zone *_target) { return _target->GetZoneTextureAttr (); } DllExport void * Polyhedron_Polyhedron () { return new Polyhedron(); } DllExport void * Polyhedron_Polyhedron0 (const class Urho3D::Polyhedron & polyhedron) { return new Polyhedron(polyhedron); } DllExport void * Polyhedron_Polyhedron1 (const class Urho3D::BoundingBox & box) { return new Polyhedron(box); } DllExport void * Polyhedron_Polyhedron2 (const class Urho3D::Frustum & frustum) { return new Polyhedron(frustum); } DllExport void Polyhedron_Define (Urho3D::Polyhedron *_target, const class Urho3D::BoundingBox & box) { _target->Define (box); } DllExport void Polyhedron_Define3 (Urho3D::Polyhedron *_target, const class Urho3D::Frustum & frustum) { _target->Define (frustum); } DllExport void Polyhedron_AddFace (Urho3D::Polyhedron *_target, const class Urho3D::Vector3 & v0, const class Urho3D::Vector3 & v1, const class Urho3D::Vector3 & v2) { _target->AddFace (v0, v1, v2); } DllExport void Polyhedron_AddFace4 (Urho3D::Polyhedron *_target, const class Urho3D::Vector3 & v0, const class Urho3D::Vector3 & v1, const class Urho3D::Vector3 & v2, const class Urho3D::Vector3 & v3) { _target->AddFace (v0, v1, v2, v3); } DllExport void Polyhedron_Clip (Urho3D::Polyhedron *_target, const class Urho3D::Plane & plane) { _target->Clip (plane); } DllExport void Polyhedron_Clip5 (Urho3D::Polyhedron *_target, const class Urho3D::BoundingBox & box) { _target->Clip (box); } DllExport void Polyhedron_Clip6 (Urho3D::Polyhedron *_target, const class Urho3D::Frustum & box) { _target->Clip (box); } DllExport void Polyhedron_Clear (Urho3D::Polyhedron *_target) { _target->Clear (); } DllExport void Polyhedron_Transform (Urho3D::Polyhedron *_target, const class Urho3D::Matrix3x4 & transform) { _target->Transform (transform); } DllExport Urho3D::Polyhedron * Polyhedron_Transformed (Urho3D::Polyhedron *_target, const class Urho3D::Matrix3x4 & transform) { return new Urho3D::Polyhedron (_target->Transformed (transform)); } DllExport int Polyhedron_Empty (Urho3D::Polyhedron *_target) { return _target->Empty (); } DllExport int View_GetType (Urho3D::View *_target) { return (_target->GetType ()).Value (); } DllExport const char * View_GetTypeName (Urho3D::View *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int View_GetTypeStatic () { return (View::GetTypeStatic ()).Value (); } DllExport const char * View_GetTypeNameStatic () { return stringdup((View::GetTypeNameStatic ()).CString ()); } DllExport void * View_View (Urho3D::Context * context) { return WeakPtr<View>(new View(context)); } DllExport int View_Define (Urho3D::View *_target, Urho3D::RenderSurface * renderTarget, Urho3D::Viewport * viewport) { return _target->Define (renderTarget, viewport); } DllExport void View_Render (Urho3D::View *_target) { _target->Render (); } DllExport Urho3D::Graphics * View_GetGraphics (Urho3D::View *_target) { return _target->GetGraphics (); } DllExport Urho3D::Renderer * View_GetRenderer (Urho3D::View *_target) { return _target->GetRenderer (); } DllExport Urho3D::Scene * View_GetScene (Urho3D::View *_target) { return _target->GetScene (); } DllExport Urho3D::Octree * View_GetOctree (Urho3D::View *_target) { return _target->GetOctree (); } DllExport Urho3D::Camera * View_GetCamera (Urho3D::View *_target) { return _target->GetCamera (); } DllExport Urho3D::Camera * View_GetCullCamera (Urho3D::View *_target) { return _target->GetCullCamera (); } DllExport Urho3D::RenderSurface * View_GetRenderTarget (Urho3D::View *_target) { return _target->GetRenderTarget (); } DllExport int View_GetDrawDebug (Urho3D::View *_target) { return _target->GetDrawDebug (); } DllExport Interop::IntRect View_GetViewRect (Urho3D::View *_target) { return *((Interop::IntRect *) &(_target->GetViewRect ())); } DllExport Interop::IntVector2 View_GetViewSize (Urho3D::View *_target) { return *((Interop::IntVector2 *) &(_target->GetViewSize ())); } DllExport Urho3D::OcclusionBuffer * View_GetOcclusionBuffer (Urho3D::View *_target) { return _target->GetOcclusionBuffer (); } DllExport unsigned int View_GetNumActiveOccluders (Urho3D::View *_target) { return _target->GetNumActiveOccluders (); } DllExport Urho3D::View * View_GetSourceView (Urho3D::View *_target) { return _target->GetSourceView (); } DllExport void View_SetGlobalShaderParameters (Urho3D::View *_target) { _target->SetGlobalShaderParameters (); } DllExport void View_SetCameraShaderParameters (Urho3D::View *_target, Urho3D::Camera * camera) { _target->SetCameraShaderParameters (camera); } DllExport void View_SetCommandShaderParameters (Urho3D::View *_target, const struct Urho3D::RenderPathCommand & command) { _target->SetCommandShaderParameters (command); } DllExport void View_SetGBufferShaderParameters (Urho3D::View *_target, const class Urho3D::IntVector2 & texSize, const class Urho3D::IntRect & viewRect) { _target->SetGBufferShaderParameters (texSize, viewRect); } DllExport void View_SetStereoMode (Urho3D::View *_target, bool stereo) { _target->SetStereoMode (stereo); } DllExport void View_DrawFullscreenQuad (Urho3D::View *_target, bool setIdentityProjection) { _target->DrawFullscreenQuad (setIdentityProjection); } DllExport Urho3D::Texture * View_FindNamedTexture (Urho3D::View *_target, const char * name, bool isRenderTarget, bool isVolumeMap) { return _target->FindNamedTexture (Urho3D::String(name), isRenderTarget, isVolumeMap); } DllExport int File_GetType (Urho3D::File *_target) { return (_target->GetType ()).Value (); } DllExport const char * File_GetTypeName (Urho3D::File *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int File_GetTypeStatic () { return (File::GetTypeStatic ()).Value (); } DllExport const char * File_GetTypeNameStatic () { return stringdup((File::GetTypeNameStatic ()).CString ()); } DllExport void * File_File (Urho3D::Context * context) { return WeakPtr<File>(new File(context)); } DllExport void * File_File0 (Urho3D::Context * context, const char * fileName, enum Urho3D::FileMode mode) { return WeakPtr<File>(new File(context, Urho3D::String(fileName), mode)); } DllExport void * File_File1 (Urho3D::Context * context, Urho3D::PackageFile * package, const char * fileName) { return WeakPtr<File>(new File(context, package, Urho3D::String(fileName))); } DllExport unsigned int File_Read (Urho3D::File *_target, void * dest, unsigned int size) { return _target->Read (dest, size); } DllExport unsigned int File_Seek (Urho3D::File *_target, unsigned int position) { return _target->Seek (position); } DllExport unsigned int File_Write (Urho3D::File *_target, const void * data, unsigned int size) { return _target->Write (data, size); } DllExport const char * File_GetName (Urho3D::File *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport unsigned int File_GetChecksum (Urho3D::File *_target) { return _target->GetChecksum (); } DllExport int File_Open (Urho3D::File *_target, const char * fileName, enum Urho3D::FileMode mode) { return _target->Open (Urho3D::String(fileName), mode); } DllExport int File_Open2 (Urho3D::File *_target, Urho3D::PackageFile * package, const char * fileName) { return _target->Open (package, Urho3D::String(fileName)); } DllExport void File_Close (Urho3D::File *_target) { _target->Close (); } DllExport void File_Flush (Urho3D::File *_target) { _target->Flush (); } DllExport void File_SetName (Urho3D::File *_target, const char * name) { _target->SetName (Urho3D::String(name)); } DllExport enum Urho3D::FileMode File_GetMode (Urho3D::File *_target) { return _target->GetMode (); } DllExport int File_IsOpen (Urho3D::File *_target) { return _target->IsOpen (); } DllExport void * File_GetHandle (Urho3D::File *_target) { return _target->GetHandle (); } DllExport int File_IsPackaged (Urho3D::File *_target) { return _target->IsPackaged (); } DllExport int FileSystem_GetType (Urho3D::FileSystem *_target) { return (_target->GetType ()).Value (); } DllExport const char * FileSystem_GetTypeName (Urho3D::FileSystem *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int FileSystem_GetTypeStatic () { return (FileSystem::GetTypeStatic ()).Value (); } DllExport const char * FileSystem_GetTypeNameStatic () { return stringdup((FileSystem::GetTypeNameStatic ()).CString ()); } DllExport void * FileSystem_FileSystem (Urho3D::Context * context) { return WeakPtr<FileSystem>(new FileSystem(context)); } DllExport int FileSystem_SetCurrentDir (Urho3D::FileSystem *_target, const char * pathName) { return _target->SetCurrentDir (Urho3D::String(pathName)); } DllExport int FileSystem_CreateDir (Urho3D::FileSystem *_target, const char * pathName) { return _target->CreateDir (Urho3D::String(pathName)); } DllExport void FileSystem_SetExecuteConsoleCommands (Urho3D::FileSystem *_target, bool enable) { _target->SetExecuteConsoleCommands (enable); } DllExport int FileSystem_SystemCommand (Urho3D::FileSystem *_target, const char * commandLine, bool redirectStdOutToLog) { return _target->SystemCommand (Urho3D::String(commandLine), redirectStdOutToLog); } DllExport unsigned int FileSystem_SystemCommandAsync (Urho3D::FileSystem *_target, const char * commandLine) { return _target->SystemCommandAsync (Urho3D::String(commandLine)); } DllExport int FileSystem_SystemOpen (Urho3D::FileSystem *_target, const char * fileName, const char * mode) { return _target->SystemOpen (Urho3D::String(fileName), Urho3D::String(mode)); } DllExport int FileSystem_Copy (Urho3D::FileSystem *_target, const char * srcFileName, const char * destFileName) { return _target->Copy (Urho3D::String(srcFileName), Urho3D::String(destFileName)); } DllExport int FileSystem_Rename (Urho3D::FileSystem *_target, const char * srcFileName, const char * destFileName) { return _target->Rename (Urho3D::String(srcFileName), Urho3D::String(destFileName)); } DllExport int FileSystem_Delete (Urho3D::FileSystem *_target, const char * fileName) { return _target->Delete (Urho3D::String(fileName)); } DllExport void FileSystem_RegisterPath (Urho3D::FileSystem *_target, const char * pathName) { _target->RegisterPath (Urho3D::String(pathName)); } DllExport int FileSystem_SetLastModifiedTime (Urho3D::FileSystem *_target, const char * fileName, unsigned int newTime) { return _target->SetLastModifiedTime (Urho3D::String(fileName), newTime); } DllExport const char * FileSystem_GetCurrentDir (Urho3D::FileSystem *_target) { return stringdup((_target->GetCurrentDir ()).CString ()); } DllExport int FileSystem_GetExecuteConsoleCommands (Urho3D::FileSystem *_target) { return _target->GetExecuteConsoleCommands (); } DllExport int FileSystem_HasRegisteredPaths (Urho3D::FileSystem *_target) { return _target->HasRegisteredPaths (); } DllExport int FileSystem_CheckAccess (Urho3D::FileSystem *_target, const char * pathName) { return _target->CheckAccess (Urho3D::String(pathName)); } DllExport unsigned int FileSystem_GetLastModifiedTime (Urho3D::FileSystem *_target, const char * fileName) { return _target->GetLastModifiedTime (Urho3D::String(fileName)); } DllExport int FileSystem_FileExists (Urho3D::FileSystem *_target, const char * fileName) { return _target->FileExists (Urho3D::String(fileName)); } DllExport int FileSystem_DirExists (Urho3D::FileSystem *_target, const char * pathName) { return _target->DirExists (Urho3D::String(pathName)); } DllExport const char * FileSystem_GetProgramDir (Urho3D::FileSystem *_target) { return stringdup((_target->GetProgramDir ()).CString ()); } DllExport const char * FileSystem_GetUserDocumentsDir (Urho3D::FileSystem *_target) { return stringdup((_target->GetUserDocumentsDir ()).CString ()); } DllExport const char * FileSystem_GetAppPreferencesDir (Urho3D::FileSystem *_target, const char * org, const char * app) { return stringdup((_target->GetAppPreferencesDir (Urho3D::String(org), Urho3D::String(app))).CString ()); } DllExport const char * FileSystem_GetTemporaryDir (Urho3D::FileSystem *_target) { return stringdup((_target->GetTemporaryDir ()).CString ()); } DllExport int FileWatcher_GetType (Urho3D::FileWatcher *_target) { return (_target->GetType ()).Value (); } DllExport const char * FileWatcher_GetTypeName (Urho3D::FileWatcher *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int FileWatcher_GetTypeStatic () { return (FileWatcher::GetTypeStatic ()).Value (); } DllExport const char * FileWatcher_GetTypeNameStatic () { return stringdup((FileWatcher::GetTypeNameStatic ()).CString ()); } DllExport void * FileWatcher_FileWatcher (Urho3D::Context * context) { return WeakPtr<FileWatcher>(new FileWatcher(context)); } DllExport void FileWatcher_ThreadFunction (Urho3D::FileWatcher *_target) { _target->ThreadFunction (); } DllExport int FileWatcher_StartWatching (Urho3D::FileWatcher *_target, const char * pathName, bool watchSubDirs) { return _target->StartWatching (Urho3D::String(pathName), watchSubDirs); } DllExport void FileWatcher_StopWatching (Urho3D::FileWatcher *_target) { _target->StopWatching (); } DllExport void FileWatcher_SetDelay (Urho3D::FileWatcher *_target, float interval) { _target->SetDelay (interval); } DllExport void FileWatcher_AddChange (Urho3D::FileWatcher *_target, const char * fileName) { _target->AddChange (Urho3D::String(fileName)); } DllExport const char * FileWatcher_GetPath (Urho3D::FileWatcher *_target) { return stringdup((_target->GetPath ()).CString ()); } DllExport float FileWatcher_GetDelay (Urho3D::FileWatcher *_target) { return _target->GetDelay (); } DllExport int Log_GetType (Urho3D::Log *_target) { return (_target->GetType ()).Value (); } DllExport const char * Log_GetTypeName (Urho3D::Log *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Log_GetTypeStatic () { return (Log::GetTypeStatic ()).Value (); } DllExport const char * Log_GetTypeNameStatic () { return stringdup((Log::GetTypeNameStatic ()).CString ()); } DllExport void * Log_Log (Urho3D::Context * context) { return WeakPtr<Log>(new Log(context)); } DllExport void Log_Open (Urho3D::Log *_target, const char * fileName) { _target->Open (Urho3D::String(fileName)); } DllExport void Log_Close (Urho3D::Log *_target) { _target->Close (); } DllExport void Log_SetLevel (Urho3D::Log *_target, int level) { _target->SetLevel (level); } DllExport void Log_SetTimeStamp (Urho3D::Log *_target, bool enable) { _target->SetTimeStamp (enable); } DllExport void Log_SetQuiet (Urho3D::Log *_target, bool quiet) { _target->SetQuiet (quiet); } DllExport int Log_GetLevel (Urho3D::Log *_target) { return _target->GetLevel (); } DllExport int Log_GetTimeStamp (Urho3D::Log *_target) { return _target->GetTimeStamp (); } DllExport const char * Log_GetLastMessage (Urho3D::Log *_target) { return stringdup((_target->GetLastMessage ()).CString ()); } DllExport int Log_IsQuiet (Urho3D::Log *_target) { return _target->IsQuiet (); } DllExport void Log_Write (int level, const char * message) { Log::Write (level, Urho3D::String(message)); } DllExport void Log_WriteRaw (const char * message, bool error) { Log::WriteRaw (Urho3D::String(message), error); } DllExport int PackageFile_GetType (Urho3D::PackageFile *_target) { return (_target->GetType ()).Value (); } DllExport const char * PackageFile_GetTypeName (Urho3D::PackageFile *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int PackageFile_GetTypeStatic () { return (PackageFile::GetTypeStatic ()).Value (); } DllExport const char * PackageFile_GetTypeNameStatic () { return stringdup((PackageFile::GetTypeNameStatic ()).CString ()); } DllExport void * PackageFile_PackageFile (Urho3D::Context * context) { return WeakPtr<PackageFile>(new PackageFile(context)); } DllExport void * PackageFile_PackageFile0 (Urho3D::Context * context, const char * fileName, unsigned int startOffset) { return WeakPtr<PackageFile>(new PackageFile(context, Urho3D::String(fileName), startOffset)); } DllExport int PackageFile_Open (Urho3D::PackageFile *_target, const char * fileName, unsigned int startOffset) { return _target->Open (Urho3D::String(fileName), startOffset); } DllExport int PackageFile_Exists (Urho3D::PackageFile *_target, const char * fileName) { return _target->Exists (Urho3D::String(fileName)); } DllExport const struct Urho3D::PackageEntry * PackageFile_GetEntry (Urho3D::PackageFile *_target, const char * fileName) { return _target->GetEntry (Urho3D::String(fileName)); } DllExport const char * PackageFile_GetName (Urho3D::PackageFile *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport int PackageFile_GetNameHash (Urho3D::PackageFile *_target) { return (_target->GetNameHash ()).Value (); } DllExport unsigned int PackageFile_GetNumFiles (Urho3D::PackageFile *_target) { return _target->GetNumFiles (); } DllExport unsigned int PackageFile_GetTotalSize (Urho3D::PackageFile *_target) { return _target->GetTotalSize (); } DllExport unsigned int PackageFile_GetTotalDataSize (Urho3D::PackageFile *_target) { return _target->GetTotalDataSize (); } DllExport unsigned int PackageFile_GetChecksum (Urho3D::PackageFile *_target) { return _target->GetChecksum (); } DllExport int PackageFile_IsCompressed (Urho3D::PackageFile *_target) { return _target->IsCompressed (); } DllExport void * UIBatch_UIBatch () { return new UIBatch(); } DllExport void UIBatch_SetColor (Urho3D::UIBatch *_target, const class Urho3D::Color & color, bool overrideAlpha) { _target->SetColor (color, overrideAlpha); } DllExport void UIBatch_SetDefaultColor (Urho3D::UIBatch *_target) { _target->SetDefaultColor (); } DllExport void UIBatch_AddQuad (Urho3D::UIBatch *_target, float x, float y, float width, float height, int texOffsetX, int texOffsetY, int texWidth, int texHeight) { _target->AddQuad (x, y, width, height, texOffsetX, texOffsetY, texWidth, texHeight); } DllExport void UIBatch_AddQuad0 (Urho3D::UIBatch *_target, const class Urho3D::Matrix3x4 & transform, int x, int y, int width, int height, int texOffsetX, int texOffsetY, int texWidth, int texHeight) { _target->AddQuad (transform, x, y, width, height, texOffsetX, texOffsetY, texWidth, texHeight); } DllExport void UIBatch_AddQuad1 (Urho3D::UIBatch *_target, int x, int y, int width, int height, int texOffsetX, int texOffsetY, int texWidth, int texHeight, bool tiled) { _target->AddQuad (x, y, width, height, texOffsetX, texOffsetY, texWidth, texHeight, tiled); } DllExport void UIBatch_AddQuad2 (Urho3D::UIBatch *_target, const class Urho3D::Matrix3x4 & transform, const class Urho3D::IntVector2 & a, const class Urho3D::IntVector2 & b, const class Urho3D::IntVector2 & c, const class Urho3D::IntVector2 & d, const class Urho3D::IntVector2 & texA, const class Urho3D::IntVector2 & texB, const class Urho3D::IntVector2 & texC, const class Urho3D::IntVector2 & texD) { _target->AddQuad (transform, a, b, c, d, texA, texB, texC, texD); } DllExport void UIBatch_AddQuad3 (Urho3D::UIBatch *_target, const class Urho3D::Matrix3x4 & transform, const class Urho3D::IntVector2 & a, const class Urho3D::IntVector2 & b, const class Urho3D::IntVector2 & c, const class Urho3D::IntVector2 & d, const class Urho3D::IntVector2 & texA, const class Urho3D::IntVector2 & texB, const class Urho3D::IntVector2 & texC, const class Urho3D::IntVector2 & texD, const class Urho3D::Color & colA, const class Urho3D::Color & colB, const class Urho3D::Color & colC, const class Urho3D::Color & colD) { _target->AddQuad (transform, a, b, c, d, texA, texB, texC, texD, colA, colB, colC, colD); } DllExport unsigned int UIBatch_GetInterpolatedColor (Urho3D::UIBatch *_target, float x, float y) { return _target->GetInterpolatedColor (x, y); } DllExport int UIElement_GetType (Urho3D::UIElement *_target) { return (_target->GetType ()).Value (); } DllExport const char * UIElement_GetTypeName (Urho3D::UIElement *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int UIElement_GetTypeStatic () { return (UIElement::GetTypeStatic ()).Value (); } DllExport const char * UIElement_GetTypeNameStatic () { return stringdup((UIElement::GetTypeNameStatic ()).CString ()); } DllExport void * UIElement_UIElement (Urho3D::Context * context) { return WeakPtr<UIElement>(new UIElement(context)); } DllExport void UIElement_RegisterObject (Urho3D::Context * context) { UIElement::RegisterObject (context); } DllExport void UIElement_ApplyAttributes (Urho3D::UIElement *_target) { _target->ApplyAttributes (); } DllExport int UIElement_LoadXML (Urho3D::UIElement *_target, const class Urho3D::XMLElement & source, bool setInstanceDefault) { return _target->LoadXML (source, setInstanceDefault); } DllExport int UIElement_LoadXML0 (Urho3D::UIElement *_target, const class Urho3D::XMLElement & source, Urho3D::XMLFile * styleFile, bool setInstanceDefault) { return _target->LoadXML (source, styleFile, setInstanceDefault); } DllExport Urho3D::UIElement * UIElement_LoadChildXML (Urho3D::UIElement *_target, const class Urho3D::XMLElement & childElem, Urho3D::XMLFile * styleFile, bool setInstanceDefault) { return _target->LoadChildXML (childElem, styleFile, setInstanceDefault); } DllExport int UIElement_SaveXML (Urho3D::UIElement *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void UIElement_Update (Urho3D::UIElement *_target, float timeStep) { _target->Update (timeStep); } DllExport int UIElement_IsWithinScissor (Urho3D::UIElement *_target, const class Urho3D::IntRect & currentScissor) { return _target->IsWithinScissor (currentScissor); } DllExport Interop::IntVector2 UIElement_GetScreenPosition (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetScreenPosition ())); } DllExport void UIElement_OnHover (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnHover (position, screenPosition, buttons, qualifiers, cursor); } DllExport void UIElement_OnClickBegin (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnClickBegin (position, screenPosition, button, buttons, qualifiers, cursor); } DllExport void UIElement_OnClickEnd (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor, Urho3D::UIElement * beginElement) { _target->OnClickEnd (position, screenPosition, button, buttons, qualifiers, cursor, beginElement); } DllExport void UIElement_OnDoubleClick (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnDoubleClick (position, screenPosition, button, buttons, qualifiers, cursor); } DllExport void UIElement_OnWheel (Urho3D::UIElement *_target, int delta, int buttons, int qualifiers) { _target->OnWheel (delta, buttons, qualifiers); } DllExport void UIElement_OnKey (Urho3D::UIElement *_target, int key, int buttons, int qualifiers) { _target->OnKey (key, buttons, qualifiers); } DllExport void UIElement_OnTextInput (Urho3D::UIElement *_target, const char * text) { _target->OnTextInput (Urho3D::String(text)); } DllExport void UIElement_OnResize (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & newSize, const class Urho3D::IntVector2 & delta) { _target->OnResize (newSize, delta); } DllExport void UIElement_OnPositionSet (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & newPosition) { _target->OnPositionSet (newPosition); } DllExport void UIElement_OnSetEditable (Urho3D::UIElement *_target) { _target->OnSetEditable (); } DllExport void UIElement_OnIndentSet (Urho3D::UIElement *_target) { _target->OnIndentSet (); } DllExport Interop::IntVector2 UIElement_ScreenToElement (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & screenPosition) { return *((Interop::IntVector2 *) &(_target->ScreenToElement (screenPosition))); } DllExport Interop::IntVector2 UIElement_ElementToScreen (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & position) { return *((Interop::IntVector2 *) &(_target->ElementToScreen (position))); } DllExport int UIElement_IsWheelHandler (Urho3D::UIElement *_target) { return _target->IsWheelHandler (); } DllExport int UIElement_LoadXML1_File (Urho3D::UIElement *_target, File * source) { return _target->LoadXML (*source); } DllExport int UIElement_LoadXML1_MemoryBuffer (Urho3D::UIElement *_target, MemoryBuffer * source) { return _target->LoadXML (*source); } DllExport int UIElement_SaveXML2_File (Urho3D::UIElement *_target, File * dest, const char * indentation) { return _target->SaveXML (*dest, Urho3D::String(indentation)); } DllExport int UIElement_SaveXML2_MemoryBuffer (Urho3D::UIElement *_target, MemoryBuffer * dest, const char * indentation) { return _target->SaveXML (*dest, Urho3D::String(indentation)); } DllExport int UIElement_FilterAttributes (Urho3D::UIElement *_target, Urho3D::XMLElement & dest) { return _target->FilterAttributes (dest); } DllExport void UIElement_SetName (Urho3D::UIElement *_target, const char * name) { _target->SetName (Urho3D::String(name)); } DllExport void UIElement_SetPosition (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & position) { _target->SetPosition (position); } DllExport void UIElement_SetPosition3 (Urho3D::UIElement *_target, int x, int y) { _target->SetPosition (x, y); } DllExport void UIElement_SetSize (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & size) { _target->SetSize (size); } DllExport void UIElement_SetSize4 (Urho3D::UIElement *_target, int width, int height) { _target->SetSize (width, height); } DllExport void UIElement_SetWidth (Urho3D::UIElement *_target, int width) { _target->SetWidth (width); } DllExport void UIElement_SetHeight (Urho3D::UIElement *_target, int height) { _target->SetHeight (height); } DllExport void UIElement_SetMinSize (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & minSize) { _target->SetMinSize (minSize); } DllExport void UIElement_SetMinSize5 (Urho3D::UIElement *_target, int width, int height) { _target->SetMinSize (width, height); } DllExport void UIElement_SetMinWidth (Urho3D::UIElement *_target, int width) { _target->SetMinWidth (width); } DllExport void UIElement_SetMinHeight (Urho3D::UIElement *_target, int height) { _target->SetMinHeight (height); } DllExport void UIElement_SetMaxSize (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & maxSize) { _target->SetMaxSize (maxSize); } DllExport void UIElement_SetMaxSize6 (Urho3D::UIElement *_target, int width, int height) { _target->SetMaxSize (width, height); } DllExport void UIElement_SetMaxWidth (Urho3D::UIElement *_target, int width) { _target->SetMaxWidth (width); } DllExport void UIElement_SetMaxHeight (Urho3D::UIElement *_target, int height) { _target->SetMaxHeight (height); } DllExport void UIElement_SetFixedSize (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & size) { _target->SetFixedSize (size); } DllExport void UIElement_SetFixedSize7 (Urho3D::UIElement *_target, int width, int height) { _target->SetFixedSize (width, height); } DllExport void UIElement_SetFixedWidth (Urho3D::UIElement *_target, int width) { _target->SetFixedWidth (width); } DllExport void UIElement_SetFixedHeight (Urho3D::UIElement *_target, int height) { _target->SetFixedHeight (height); } DllExport void UIElement_SetAlignment (Urho3D::UIElement *_target, enum Urho3D::HorizontalAlignment hAlign, enum Urho3D::VerticalAlignment vAlign) { _target->SetAlignment (hAlign, vAlign); } DllExport void UIElement_SetHorizontalAlignment (Urho3D::UIElement *_target, enum Urho3D::HorizontalAlignment align) { _target->SetHorizontalAlignment (align); } DllExport void UIElement_SetVerticalAlignment (Urho3D::UIElement *_target, enum Urho3D::VerticalAlignment align) { _target->SetVerticalAlignment (align); } DllExport void UIElement_SetEnableAnchor (Urho3D::UIElement *_target, bool enable) { _target->SetEnableAnchor (enable); } DllExport void UIElement_SetMinAnchor (Urho3D::UIElement *_target, const class Urho3D::Vector2 & anchor) { _target->SetMinAnchor (anchor); } DllExport void UIElement_SetMinAnchor8 (Urho3D::UIElement *_target, float x, float y) { _target->SetMinAnchor (x, y); } DllExport void UIElement_SetMaxAnchor (Urho3D::UIElement *_target, const class Urho3D::Vector2 & anchor) { _target->SetMaxAnchor (anchor); } DllExport void UIElement_SetMaxAnchor9 (Urho3D::UIElement *_target, float x, float y) { _target->SetMaxAnchor (x, y); } DllExport void UIElement_SetMinOffset (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & offset) { _target->SetMinOffset (offset); } DllExport void UIElement_SetMaxOffset (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & offset) { _target->SetMaxOffset (offset); } DllExport void UIElement_SetPivot (Urho3D::UIElement *_target, const class Urho3D::Vector2 & pivot) { _target->SetPivot (pivot); } DllExport void UIElement_SetPivot10 (Urho3D::UIElement *_target, float x, float y) { _target->SetPivot (x, y); } DllExport void UIElement_SetClipBorder (Urho3D::UIElement *_target, const class Urho3D::IntRect & rect) { _target->SetClipBorder (rect); } DllExport void UIElement_SetColor (Urho3D::UIElement *_target, const class Urho3D::Color & color) { _target->SetColor (color); } DllExport void UIElement_SetColor11 (Urho3D::UIElement *_target, enum Urho3D::Corner corner, const class Urho3D::Color & color) { _target->SetColor (corner, color); } DllExport void UIElement_SetPriority (Urho3D::UIElement *_target, int priority) { _target->SetPriority (priority); } DllExport void UIElement_SetOpacity (Urho3D::UIElement *_target, float opacity) { _target->SetOpacity (opacity); } DllExport void UIElement_SetBringToFront (Urho3D::UIElement *_target, bool enable) { _target->SetBringToFront (enable); } DllExport void UIElement_SetBringToBack (Urho3D::UIElement *_target, bool enable) { _target->SetBringToBack (enable); } DllExport void UIElement_SetClipChildren (Urho3D::UIElement *_target, bool enable) { _target->SetClipChildren (enable); } DllExport void UIElement_SetSortChildren (Urho3D::UIElement *_target, bool enable) { _target->SetSortChildren (enable); } DllExport void UIElement_SetUseDerivedOpacity (Urho3D::UIElement *_target, bool enable) { _target->SetUseDerivedOpacity (enable); } DllExport void UIElement_SetEnabled (Urho3D::UIElement *_target, bool enable) { _target->SetEnabled (enable); } DllExport void UIElement_SetDeepEnabled (Urho3D::UIElement *_target, bool enable) { _target->SetDeepEnabled (enable); } DllExport void UIElement_ResetDeepEnabled (Urho3D::UIElement *_target) { _target->ResetDeepEnabled (); } DllExport void UIElement_SetEnabledRecursive (Urho3D::UIElement *_target, bool enable) { _target->SetEnabledRecursive (enable); } DllExport void UIElement_SetEditable (Urho3D::UIElement *_target, bool enable) { _target->SetEditable (enable); } DllExport void UIElement_SetFocus (Urho3D::UIElement *_target, bool enable) { _target->SetFocus (enable); } DllExport void UIElement_SetSelected (Urho3D::UIElement *_target, bool enable) { _target->SetSelected (enable); } DllExport void UIElement_SetVisible (Urho3D::UIElement *_target, bool enable) { _target->SetVisible (enable); } DllExport void UIElement_SetFocusMode (Urho3D::UIElement *_target, enum Urho3D::FocusMode mode) { _target->SetFocusMode (mode); } DllExport void UIElement_SetDragDropMode (Urho3D::UIElement *_target, unsigned int mode) { _target->SetDragDropMode (mode); } DllExport int UIElement_SetStyle (Urho3D::UIElement *_target, const char * styleName, Urho3D::XMLFile * file) { return _target->SetStyle (Urho3D::String(styleName), file); } DllExport int UIElement_SetStyle12 (Urho3D::UIElement *_target, const class Urho3D::XMLElement & element) { return _target->SetStyle (element); } DllExport int UIElement_SetStyleAuto (Urho3D::UIElement *_target, Urho3D::XMLFile * file) { return _target->SetStyleAuto (file); } DllExport void UIElement_SetDefaultStyle (Urho3D::UIElement *_target, Urho3D::XMLFile * style) { _target->SetDefaultStyle (style); } DllExport void UIElement_SetLayout (Urho3D::UIElement *_target, enum Urho3D::LayoutMode mode, int spacing, const class Urho3D::IntRect & border) { _target->SetLayout (mode, spacing, border); } DllExport void UIElement_SetLayoutMode (Urho3D::UIElement *_target, enum Urho3D::LayoutMode mode) { _target->SetLayoutMode (mode); } DllExport void UIElement_SetLayoutSpacing (Urho3D::UIElement *_target, int spacing) { _target->SetLayoutSpacing (spacing); } DllExport void UIElement_SetLayoutBorder (Urho3D::UIElement *_target, const class Urho3D::IntRect & border) { _target->SetLayoutBorder (border); } DllExport void UIElement_SetLayoutFlexScale (Urho3D::UIElement *_target, const class Urho3D::Vector2 & scale) { _target->SetLayoutFlexScale (scale); } DllExport void UIElement_SetIndent (Urho3D::UIElement *_target, int indent) { _target->SetIndent (indent); } DllExport void UIElement_SetIndentSpacing (Urho3D::UIElement *_target, int indentSpacing) { _target->SetIndentSpacing (indentSpacing); } DllExport void UIElement_UpdateLayout (Urho3D::UIElement *_target) { _target->UpdateLayout (); } DllExport void UIElement_DisableLayoutUpdate (Urho3D::UIElement *_target) { _target->DisableLayoutUpdate (); } DllExport void UIElement_EnableLayoutUpdate (Urho3D::UIElement *_target) { _target->EnableLayoutUpdate (); } DllExport void UIElement_BringToFront (Urho3D::UIElement *_target) { _target->BringToFront (); } DllExport Urho3D::UIElement * UIElement_CreateChild (Urho3D::UIElement *_target, int type, const char * name, unsigned int index) { return _target->CreateChild (Urho3D::StringHash(type), Urho3D::String(name), index); } DllExport void UIElement_AddChild (Urho3D::UIElement *_target, Urho3D::UIElement * element) { _target->AddChild (element); } DllExport void UIElement_InsertChild (Urho3D::UIElement *_target, unsigned int index, Urho3D::UIElement * element) { _target->InsertChild (index, element); } DllExport void UIElement_RemoveChild (Urho3D::UIElement *_target, Urho3D::UIElement * element, unsigned int index) { _target->RemoveChild (element, index); } DllExport void UIElement_RemoveChildAtIndex (Urho3D::UIElement *_target, unsigned int index) { _target->RemoveChildAtIndex (index); } DllExport void UIElement_RemoveAllChildren (Urho3D::UIElement *_target) { _target->RemoveAllChildren (); } DllExport void UIElement_Remove (Urho3D::UIElement *_target) { _target->Remove (); } DllExport unsigned int UIElement_FindChild (Urho3D::UIElement *_target, Urho3D::UIElement * element) { return _target->FindChild (element); } DllExport void UIElement_SetParent (Urho3D::UIElement *_target, Urho3D::UIElement * parent, unsigned int index) { _target->SetParent (parent, index); } // Urho3D::Variant overloads begin: DllExport void UIElement_SetVar_0 (Urho3D::UIElement *_target, int key, const class Urho3D::Vector3 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_1 (Urho3D::UIElement *_target, int key, const class Urho3D::IntRect & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_2 (Urho3D::UIElement *_target, int key, const class Urho3D::Color & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_3 (Urho3D::UIElement *_target, int key, const class Urho3D::Vector2 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_4 (Urho3D::UIElement *_target, int key, const class Urho3D::Vector4 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_5 (Urho3D::UIElement *_target, int key, const class Urho3D::IntVector2 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_6 (Urho3D::UIElement *_target, int key, const class Urho3D::Quaternion & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_7 (Urho3D::UIElement *_target, int key, const class Urho3D::Matrix4 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_8 (Urho3D::UIElement *_target, int key, const class Urho3D::Matrix3x4 & value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_9 (Urho3D::UIElement *_target, int key, int value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_10 (Urho3D::UIElement *_target, int key, float value) { _target->SetVar (Urho3D::StringHash(key), (value)); } DllExport void UIElement_SetVar_11 (Urho3D::UIElement *_target, int key, const char * value) { _target->SetVar (Urho3D::StringHash(key), Urho3D::String(value)); } DllExport void UIElement_SetVar_12 (Urho3D::UIElement *_target, int key, bool value) { _target->SetVar (Urho3D::StringHash(key), (value)); } // Urho3D::Variant overloads end. DllExport void UIElement_SetInternal (Urho3D::UIElement *_target, bool enable) { _target->SetInternal (enable); } DllExport void UIElement_SetTraversalMode (Urho3D::UIElement *_target, enum Urho3D::TraversalMode traversalMode) { _target->SetTraversalMode (traversalMode); } DllExport void UIElement_SetElementEventSender (Urho3D::UIElement *_target, bool flag) { _target->SetElementEventSender (flag); } DllExport void UIElement_AddTag (Urho3D::UIElement *_target, const char * tag) { _target->AddTag (Urho3D::String(tag)); } DllExport int UIElement_RemoveTag (Urho3D::UIElement *_target, const char * tag) { return _target->RemoveTag (Urho3D::String(tag)); } DllExport void UIElement_RemoveAllTags (Urho3D::UIElement *_target) { _target->RemoveAllTags (); } DllExport const char * UIElement_GetName (Urho3D::UIElement *_target) { return stringdup((_target->GetName ()).CString ()); } DllExport Interop::IntVector2 UIElement_GetPosition (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetPosition ())); } DllExport Interop::IntVector2 UIElement_GetSize (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetSize ())); } DllExport int UIElement_GetWidth (Urho3D::UIElement *_target) { return _target->GetWidth (); } DllExport int UIElement_GetHeight (Urho3D::UIElement *_target) { return _target->GetHeight (); } DllExport Interop::IntVector2 UIElement_GetMinSize (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetMinSize ())); } DllExport int UIElement_GetMinWidth (Urho3D::UIElement *_target) { return _target->GetMinWidth (); } DllExport int UIElement_GetMinHeight (Urho3D::UIElement *_target) { return _target->GetMinHeight (); } DllExport Interop::IntVector2 UIElement_GetMaxSize (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetMaxSize ())); } DllExport int UIElement_GetMaxWidth (Urho3D::UIElement *_target) { return _target->GetMaxWidth (); } DllExport int UIElement_GetMaxHeight (Urho3D::UIElement *_target) { return _target->GetMaxHeight (); } DllExport int UIElement_IsFixedSize (Urho3D::UIElement *_target) { return _target->IsFixedSize (); } DllExport int UIElement_IsFixedWidth (Urho3D::UIElement *_target) { return _target->IsFixedWidth (); } DllExport int UIElement_IsFixedHeight (Urho3D::UIElement *_target) { return _target->IsFixedHeight (); } DllExport Interop::IntVector2 UIElement_GetChildOffset (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetChildOffset ())); } DllExport enum Urho3D::HorizontalAlignment UIElement_GetHorizontalAlignment (Urho3D::UIElement *_target) { return _target->GetHorizontalAlignment (); } DllExport enum Urho3D::VerticalAlignment UIElement_GetVerticalAlignment (Urho3D::UIElement *_target) { return _target->GetVerticalAlignment (); } DllExport int UIElement_GetEnableAnchor (Urho3D::UIElement *_target) { return _target->GetEnableAnchor (); } DllExport Interop::Vector2 UIElement_GetMinAnchor (Urho3D::UIElement *_target) { return *((Interop::Vector2 *) &(_target->GetMinAnchor ())); } DllExport Interop::Vector2 UIElement_GetMaxAnchor (Urho3D::UIElement *_target) { return *((Interop::Vector2 *) &(_target->GetMaxAnchor ())); } DllExport Interop::IntVector2 UIElement_GetMinOffset (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetMinOffset ())); } DllExport Interop::IntVector2 UIElement_GetMaxOffset (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetMaxOffset ())); } DllExport Interop::Vector2 UIElement_GetPivot (Urho3D::UIElement *_target) { return *((Interop::Vector2 *) &(_target->GetPivot ())); } DllExport Interop::IntRect UIElement_GetClipBorder (Urho3D::UIElement *_target) { return *((Interop::IntRect *) &(_target->GetClipBorder ())); } DllExport Interop::Color UIElement_GetColor (Urho3D::UIElement *_target, enum Urho3D::Corner corner) { return *((Interop::Color *) &(_target->GetColor (corner))); } DllExport int UIElement_GetPriority (Urho3D::UIElement *_target) { return _target->GetPriority (); } DllExport float UIElement_GetOpacity (Urho3D::UIElement *_target) { return _target->GetOpacity (); } DllExport float UIElement_GetDerivedOpacity (Urho3D::UIElement *_target) { return _target->GetDerivedOpacity (); } DllExport int UIElement_GetBringToFront (Urho3D::UIElement *_target) { return _target->GetBringToFront (); } DllExport int UIElement_GetBringToBack (Urho3D::UIElement *_target) { return _target->GetBringToBack (); } DllExport int UIElement_GetClipChildren (Urho3D::UIElement *_target) { return _target->GetClipChildren (); } DllExport int UIElement_GetSortChildren (Urho3D::UIElement *_target) { return _target->GetSortChildren (); } DllExport int UIElement_GetUseDerivedOpacity (Urho3D::UIElement *_target) { return _target->GetUseDerivedOpacity (); } DllExport int UIElement_HasFocus (Urho3D::UIElement *_target) { return _target->HasFocus (); } DllExport int UIElement_IsChildOf (Urho3D::UIElement *_target, Urho3D::UIElement * element) { return _target->IsChildOf (element); } DllExport int UIElement_IsEnabled (Urho3D::UIElement *_target) { return _target->IsEnabled (); } DllExport int UIElement_IsEnabledSelf (Urho3D::UIElement *_target) { return _target->IsEnabledSelf (); } DllExport int UIElement_IsEditable (Urho3D::UIElement *_target) { return _target->IsEditable (); } DllExport int UIElement_IsSelected (Urho3D::UIElement *_target) { return _target->IsSelected (); } DllExport int UIElement_IsVisible (Urho3D::UIElement *_target) { return _target->IsVisible (); } DllExport int UIElement_IsVisibleEffective (Urho3D::UIElement *_target) { return _target->IsVisibleEffective (); } DllExport int UIElement_IsHovering (Urho3D::UIElement *_target) { return _target->IsHovering (); } DllExport int UIElement_IsInternal (Urho3D::UIElement *_target) { return _target->IsInternal (); } DllExport int UIElement_HasColorGradient (Urho3D::UIElement *_target) { return _target->HasColorGradient (); } DllExport enum Urho3D::FocusMode UIElement_GetFocusMode (Urho3D::UIElement *_target) { return _target->GetFocusMode (); } DllExport unsigned int UIElement_GetDragDropMode (Urho3D::UIElement *_target) { return _target->GetDragDropMode (); } DllExport const char * UIElement_GetAppliedStyle (Urho3D::UIElement *_target) { return stringdup((_target->GetAppliedStyle ()).CString ()); } DllExport Urho3D::XMLFile * UIElement_GetDefaultStyle (Urho3D::UIElement *_target, bool recursiveUp) { return _target->GetDefaultStyle (recursiveUp); } DllExport enum Urho3D::LayoutMode UIElement_GetLayoutMode (Urho3D::UIElement *_target) { return _target->GetLayoutMode (); } DllExport int UIElement_GetLayoutSpacing (Urho3D::UIElement *_target) { return _target->GetLayoutSpacing (); } DllExport Interop::IntRect UIElement_GetLayoutBorder (Urho3D::UIElement *_target) { return *((Interop::IntRect *) &(_target->GetLayoutBorder ())); } DllExport Interop::Vector2 UIElement_GetLayoutFlexScale (Urho3D::UIElement *_target) { return *((Interop::Vector2 *) &(_target->GetLayoutFlexScale ())); } DllExport unsigned int UIElement_GetNumChildren (Urho3D::UIElement *_target, bool recursive) { return _target->GetNumChildren (recursive); } DllExport Urho3D::UIElement * UIElement_GetChild (Urho3D::UIElement *_target, unsigned int index) { return _target->GetChild (index); } DllExport Urho3D::UIElement * UIElement_GetChild13 (Urho3D::UIElement *_target, const char * name, bool recursive) { return _target->GetChild (Urho3D::String(name), recursive); } DllExport const Vector<SharedPtr<class Urho3D::UIElement> > & UIElement_GetChildren (Urho3D::UIElement *_target) { return _target->GetChildren (); } DllExport Urho3D::UIElement * UIElement_GetParent (Urho3D::UIElement *_target) { return _target->GetParent (); } DllExport Urho3D::UIElement * UIElement_GetRoot (Urho3D::UIElement *_target) { return _target->GetRoot (); } DllExport Interop::Color UIElement_GetDerivedColor (Urho3D::UIElement *_target) { return *((Interop::Color *) &(_target->GetDerivedColor ())); } DllExport int UIElement_HasTag (Urho3D::UIElement *_target, const char * tag) { return _target->HasTag (Urho3D::String(tag)); } DllExport int UIElement_GetDragButtonCombo (Urho3D::UIElement *_target) { return _target->GetDragButtonCombo (); } DllExport unsigned int UIElement_GetDragButtonCount (Urho3D::UIElement *_target) { return _target->GetDragButtonCount (); } DllExport int UIElement_IsInside (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & position, bool isScreen) { return _target->IsInside (position, isScreen); } DllExport int UIElement_IsInsideCombined (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & position, bool isScreen) { return _target->IsInsideCombined (position, isScreen); } DllExport Interop::IntRect UIElement_GetCombinedScreenRect (Urho3D::UIElement *_target) { return *((Interop::IntRect *) &(_target->GetCombinedScreenRect ())); } DllExport void UIElement_SortChildren (Urho3D::UIElement *_target) { _target->SortChildren (); } DllExport int UIElement_GetLayoutElementMaxSize (Urho3D::UIElement *_target) { return _target->GetLayoutElementMaxSize (); } DllExport int UIElement_GetIndent (Urho3D::UIElement *_target) { return _target->GetIndent (); } DllExport int UIElement_GetIndentSpacing (Urho3D::UIElement *_target) { return _target->GetIndentSpacing (); } DllExport int UIElement_GetIndentWidth (Urho3D::UIElement *_target) { return _target->GetIndentWidth (); } DllExport void UIElement_SetChildOffset (Urho3D::UIElement *_target, const class Urho3D::IntVector2 & offset) { _target->SetChildOffset (offset); } DllExport void UIElement_SetHovering (Urho3D::UIElement *_target, bool enable) { _target->SetHovering (enable); } DllExport Interop::Color UIElement_GetColorAttr (Urho3D::UIElement *_target) { return *((Interop::Color *) &(_target->GetColorAttr ())); } DllExport enum Urho3D::TraversalMode UIElement_GetTraversalMode (Urho3D::UIElement *_target) { return _target->GetTraversalMode (); } DllExport int UIElement_IsElementEventSender (Urho3D::UIElement *_target) { return _target->IsElementEventSender (); } DllExport Urho3D::UIElement * UIElement_GetElementEventSender (Urho3D::UIElement *_target) { return _target->GetElementEventSender (); } DllExport Interop::IntVector2 UIElement_GetEffectiveMinSize (Urho3D::UIElement *_target) { return *((Interop::IntVector2 *) &(_target->GetEffectiveMinSize ())); } DllExport int BorderImage_GetType (Urho3D::BorderImage *_target) { return (_target->GetType ()).Value (); } DllExport const char * BorderImage_GetTypeName (Urho3D::BorderImage *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int BorderImage_GetTypeStatic () { return (BorderImage::GetTypeStatic ()).Value (); } DllExport const char * BorderImage_GetTypeNameStatic () { return stringdup((BorderImage::GetTypeNameStatic ()).CString ()); } DllExport void * BorderImage_BorderImage (Urho3D::Context * context) { return WeakPtr<BorderImage>(new BorderImage(context)); } DllExport void BorderImage_RegisterObject (Urho3D::Context * context) { BorderImage::RegisterObject (context); } DllExport void BorderImage_SetTexture (Urho3D::BorderImage *_target, Urho3D::Texture * texture) { _target->SetTexture (texture); } DllExport void BorderImage_SetImageRect (Urho3D::BorderImage *_target, const class Urho3D::IntRect & rect) { _target->SetImageRect (rect); } DllExport void BorderImage_SetFullImageRect (Urho3D::BorderImage *_target) { _target->SetFullImageRect (); } DllExport void BorderImage_SetBorder (Urho3D::BorderImage *_target, const class Urho3D::IntRect & rect) { _target->SetBorder (rect); } DllExport void BorderImage_SetImageBorder (Urho3D::BorderImage *_target, const class Urho3D::IntRect & rect) { _target->SetImageBorder (rect); } DllExport void BorderImage_SetHoverOffset (Urho3D::BorderImage *_target, const class Urho3D::IntVector2 & offset) { _target->SetHoverOffset (offset); } DllExport void BorderImage_SetHoverOffset0 (Urho3D::BorderImage *_target, int x, int y) { _target->SetHoverOffset (x, y); } DllExport void BorderImage_SetBlendMode (Urho3D::BorderImage *_target, enum Urho3D::BlendMode mode) { _target->SetBlendMode (mode); } DllExport void BorderImage_SetTiled (Urho3D::BorderImage *_target, bool enable) { _target->SetTiled (enable); } DllExport Urho3D::Texture * BorderImage_GetTexture (Urho3D::BorderImage *_target) { return _target->GetTexture (); } DllExport Interop::IntRect BorderImage_GetImageRect (Urho3D::BorderImage *_target) { return *((Interop::IntRect *) &(_target->GetImageRect ())); } DllExport Interop::IntRect BorderImage_GetBorder (Urho3D::BorderImage *_target) { return *((Interop::IntRect *) &(_target->GetBorder ())); } DllExport Interop::IntRect BorderImage_GetImageBorder (Urho3D::BorderImage *_target) { return *((Interop::IntRect *) &(_target->GetImageBorder ())); } DllExport Interop::IntVector2 BorderImage_GetHoverOffset (Urho3D::BorderImage *_target) { return *((Interop::IntVector2 *) &(_target->GetHoverOffset ())); } DllExport enum Urho3D::BlendMode BorderImage_GetBlendMode (Urho3D::BorderImage *_target) { return _target->GetBlendMode (); } DllExport int BorderImage_IsTiled (Urho3D::BorderImage *_target) { return _target->IsTiled (); } DllExport Urho3D::ResourceRef BorderImage_GetTextureAttr (Urho3D::BorderImage *_target) { return _target->GetTextureAttr (); } DllExport int Cursor_GetType (Urho3D::Cursor *_target) { return (_target->GetType ()).Value (); } DllExport const char * Cursor_GetTypeName (Urho3D::Cursor *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Cursor_GetTypeStatic () { return (Cursor::GetTypeStatic ()).Value (); } DllExport const char * Cursor_GetTypeNameStatic () { return stringdup((Cursor::GetTypeNameStatic ()).CString ()); } DllExport void * Cursor_Cursor (Urho3D::Context * context) { return WeakPtr<Cursor>(new Cursor(context)); } DllExport void Cursor_RegisterObject (Urho3D::Context * context) { Cursor::RegisterObject (context); } DllExport void Cursor_DefineShape (Urho3D::Cursor *_target, const char * shape, Urho3D::Image * image, const class Urho3D::IntRect & imageRect, const class Urho3D::IntVector2 & hotSpot) { _target->DefineShape (Urho3D::String(shape), image, imageRect, hotSpot); } DllExport void Cursor_DefineShape0 (Urho3D::Cursor *_target, enum Urho3D::CursorShape shape, Urho3D::Image * image, const class Urho3D::IntRect & imageRect, const class Urho3D::IntVector2 & hotSpot) { _target->DefineShape (shape, image, imageRect, hotSpot); } DllExport void Cursor_SetShape (Urho3D::Cursor *_target, const char * shape) { _target->SetShape (Urho3D::String(shape)); } DllExport void Cursor_SetShape1 (Urho3D::Cursor *_target, enum Urho3D::CursorShape shape) { _target->SetShape (shape); } DllExport void Cursor_SetUseSystemShapes (Urho3D::Cursor *_target, bool enable) { _target->SetUseSystemShapes (enable); } DllExport const char * Cursor_GetShape (Urho3D::Cursor *_target) { return stringdup((_target->GetShape ()).CString ()); } DllExport int Cursor_GetUseSystemShapes (Urho3D::Cursor *_target) { return _target->GetUseSystemShapes (); } DllExport void Cursor_ApplyOSCursorShape (Urho3D::Cursor *_target) { _target->ApplyOSCursorShape (); } DllExport int Input_GetType (Urho3D::Input *_target) { return (_target->GetType ()).Value (); } DllExport const char * Input_GetTypeName (Urho3D::Input *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Input_GetTypeStatic () { return (Input::GetTypeStatic ()).Value (); } DllExport const char * Input_GetTypeNameStatic () { return stringdup((Input::GetTypeNameStatic ()).CString ()); } DllExport void * Input_Input (Urho3D::Context * context) { return WeakPtr<Input>(new Input(context)); } DllExport void Input_Update (Urho3D::Input *_target) { _target->Update (); } DllExport void Input_SetToggleFullscreen (Urho3D::Input *_target, bool enable) { _target->SetToggleFullscreen (enable); } DllExport void Input_SetMouseVisible (Urho3D::Input *_target, bool enable, bool suppressEvent) { _target->SetMouseVisible (enable, suppressEvent); } DllExport void Input_ResetMouseVisible (Urho3D::Input *_target) { _target->ResetMouseVisible (); } DllExport void Input_SetMouseGrabbed (Urho3D::Input *_target, bool grab, bool suppressEvent) { _target->SetMouseGrabbed (grab, suppressEvent); } DllExport void Input_ResetMouseGrabbed (Urho3D::Input *_target) { _target->ResetMouseGrabbed (); } DllExport void Input_SetMouseMode (Urho3D::Input *_target, enum Urho3D::MouseMode mode, bool suppressEvent) { _target->SetMouseMode (mode, suppressEvent); } DllExport void Input_ResetMouseMode (Urho3D::Input *_target) { _target->ResetMouseMode (); } DllExport SDL_JoystickID Input_AddScreenJoystick (Urho3D::Input *_target, Urho3D::XMLFile * layoutFile, Urho3D::XMLFile * styleFile) { return _target->AddScreenJoystick (layoutFile, styleFile); } DllExport int Input_RemoveScreenJoystick (Urho3D::Input *_target, SDL_JoystickID id) { return _target->RemoveScreenJoystick (id); } DllExport void Input_SetScreenJoystickVisible (Urho3D::Input *_target, SDL_JoystickID id, bool enable) { _target->SetScreenJoystickVisible (id, enable); } DllExport void Input_SetScreenKeyboardVisible (Urho3D::Input *_target, bool enable) { _target->SetScreenKeyboardVisible (enable); } DllExport void Input_SetTouchEmulation (Urho3D::Input *_target, bool enable) { _target->SetTouchEmulation (enable); } DllExport void Input_SetEnabled (Urho3D::Input *_target, bool enable) { _target->SetEnabled (enable); } DllExport int Input_RecordGesture (Urho3D::Input *_target) { return _target->RecordGesture (); } DllExport int Input_SaveGestures_File (Urho3D::Input *_target, File * dest) { return _target->SaveGestures (*dest); } DllExport int Input_SaveGestures_MemoryBuffer (Urho3D::Input *_target, MemoryBuffer * dest) { return _target->SaveGestures (*dest); } DllExport int Input_SaveGesture_File (Urho3D::Input *_target, File * dest, unsigned int gestureID) { return _target->SaveGesture (*dest, gestureID); } DllExport int Input_SaveGesture_MemoryBuffer (Urho3D::Input *_target, MemoryBuffer * dest, unsigned int gestureID) { return _target->SaveGesture (*dest, gestureID); } DllExport unsigned int Input_LoadGestures_File (Urho3D::Input *_target, File * source) { return _target->LoadGestures (*source); } DllExport unsigned int Input_LoadGestures_MemoryBuffer (Urho3D::Input *_target, MemoryBuffer * source) { return _target->LoadGestures (*source); } DllExport int Input_RemoveGesture (Urho3D::Input *_target, unsigned int gestureID) { return _target->RemoveGesture (gestureID); } DllExport void Input_RemoveAllGestures (Urho3D::Input *_target) { _target->RemoveAllGestures (); } DllExport void Input_SetMousePosition (Urho3D::Input *_target, const class Urho3D::IntVector2 & position) { _target->SetMousePosition (position); } DllExport void Input_CenterMousePosition (Urho3D::Input *_target) { _target->CenterMousePosition (); } DllExport int Input_GetKeyFromName (Urho3D::Input *_target, const char * name) { return _target->GetKeyFromName (Urho3D::String(name)); } DllExport int Input_GetKeyFromScancode (Urho3D::Input *_target, int scancode) { return _target->GetKeyFromScancode (scancode); } DllExport const char * Input_GetKeyName (Urho3D::Input *_target, int key) { return stringdup((_target->GetKeyName (key)).CString ()); } DllExport int Input_GetScancodeFromKey (Urho3D::Input *_target, int key) { return _target->GetScancodeFromKey (key); } DllExport int Input_GetScancodeFromName (Urho3D::Input *_target, const char * name) { return _target->GetScancodeFromName (Urho3D::String(name)); } DllExport const char * Input_GetScancodeName (Urho3D::Input *_target, int scancode) { return stringdup((_target->GetScancodeName (scancode)).CString ()); } DllExport int Input_GetKeyDown (Urho3D::Input *_target, int key) { return _target->GetKeyDown (key); } DllExport int Input_GetKeyPress (Urho3D::Input *_target, int key) { return _target->GetKeyPress (key); } DllExport int Input_GetScancodeDown (Urho3D::Input *_target, int scancode) { return _target->GetScancodeDown (scancode); } DllExport int Input_GetScancodePress (Urho3D::Input *_target, int scancode) { return _target->GetScancodePress (scancode); } DllExport int Input_GetMouseButtonDown (Urho3D::Input *_target, int button) { return _target->GetMouseButtonDown (button); } DllExport int Input_GetMouseButtonPress (Urho3D::Input *_target, int button) { return _target->GetMouseButtonPress (button); } DllExport int Input_GetQualifierDown (Urho3D::Input *_target, int qualifier) { return _target->GetQualifierDown (qualifier); } DllExport int Input_GetQualifierPress (Urho3D::Input *_target, int qualifier) { return _target->GetQualifierPress (qualifier); } DllExport int Input_GetQualifiers (Urho3D::Input *_target) { return _target->GetQualifiers (); } DllExport Interop::IntVector2 Input_GetMousePosition (Urho3D::Input *_target) { return *((Interop::IntVector2 *) &(_target->GetMousePosition ())); } DllExport Interop::IntVector2 Input_GetMouseMove (Urho3D::Input *_target) { return *((Interop::IntVector2 *) &(_target->GetMouseMove ())); } DllExport int Input_GetMouseMoveX (Urho3D::Input *_target) { return _target->GetMouseMoveX (); } DllExport int Input_GetMouseMoveY (Urho3D::Input *_target) { return _target->GetMouseMoveY (); } DllExport int Input_GetMouseMoveWheel (Urho3D::Input *_target) { return _target->GetMouseMoveWheel (); } DllExport Interop::Vector2 Input_GetInputScale (Urho3D::Input *_target) { return *((Interop::Vector2 *) &(_target->GetInputScale ())); } DllExport unsigned int Input_GetNumTouches (Urho3D::Input *_target) { return _target->GetNumTouches (); } DllExport Urho3D::TouchState * Input_GetTouch (Urho3D::Input *_target, unsigned int index) { return _target->GetTouch (index); } DllExport unsigned int Input_GetNumJoysticks (Urho3D::Input *_target) { return _target->GetNumJoysticks (); } DllExport Urho3D::JoystickState * Input_GetJoystick (Urho3D::Input *_target, SDL_JoystickID id) { return _target->GetJoystick (id); } DllExport Urho3D::JoystickState * Input_GetJoystickByIndex (Urho3D::Input *_target, unsigned int index) { return _target->GetJoystickByIndex (index); } DllExport Urho3D::JoystickState * Input_GetJoystickByName (Urho3D::Input *_target, const char * name) { return _target->GetJoystickByName (Urho3D::String(name)); } DllExport int Input_GetToggleFullscreen (Urho3D::Input *_target) { return _target->GetToggleFullscreen (); } DllExport int Input_IsScreenJoystickVisible (Urho3D::Input *_target, SDL_JoystickID id) { return _target->IsScreenJoystickVisible (id); } DllExport int Input_GetScreenKeyboardSupport (Urho3D::Input *_target) { return _target->GetScreenKeyboardSupport (); } DllExport int Input_IsScreenKeyboardVisible (Urho3D::Input *_target) { return _target->IsScreenKeyboardVisible (); } DllExport int Input_GetTouchEmulation (Urho3D::Input *_target) { return _target->GetTouchEmulation (); } DllExport int Input_IsMouseVisible (Urho3D::Input *_target) { return _target->IsMouseVisible (); } DllExport int Input_IsMouseGrabbed (Urho3D::Input *_target) { return _target->IsMouseGrabbed (); } DllExport int Input_IsMouseLocked (Urho3D::Input *_target) { return _target->IsMouseLocked (); } DllExport enum Urho3D::MouseMode Input_GetMouseMode (Urho3D::Input *_target) { return _target->GetMouseMode (); } DllExport int Input_HasFocus (Urho3D::Input *_target) { return _target->HasFocus (); } DllExport int Input_IsEnabled (Urho3D::Input *_target) { return _target->IsEnabled (); } DllExport int Input_IsMinimized (Urho3D::Input *_target) { return _target->IsMinimized (); } DllExport void * AreaAllocator_AreaAllocator () { return new AreaAllocator(); } DllExport void * AreaAllocator_AreaAllocator0 (int width, int height, bool fastMode) { return new AreaAllocator(width, height, fastMode); } DllExport void * AreaAllocator_AreaAllocator1 (int width, int height, int maxWidth, int maxHeight, bool fastMode) { return new AreaAllocator(width, height, maxWidth, maxHeight, fastMode); } DllExport void AreaAllocator_Reset (Urho3D::AreaAllocator *_target, int width, int height, int maxWidth, int maxHeight, bool fastMode) { _target->Reset (width, height, maxWidth, maxHeight, fastMode); } DllExport int AreaAllocator_Allocate (Urho3D::AreaAllocator *_target, int width, int height, int & x, int & y) { return _target->Allocate (width, height, x, y); } DllExport int AreaAllocator_GetWidth (Urho3D::AreaAllocator *_target) { return _target->GetWidth (); } DllExport int AreaAllocator_GetHeight (Urho3D::AreaAllocator *_target) { return _target->GetHeight (); } DllExport int AreaAllocator_GetFastMode (Urho3D::AreaAllocator *_target) { return _target->GetFastMode (); } DllExport int CrowdManager_GetType (Urho3D::CrowdManager *_target) { return (_target->GetType ()).Value (); } DllExport const char * CrowdManager_GetTypeName (Urho3D::CrowdManager *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CrowdManager_GetTypeStatic () { return (CrowdManager::GetTypeStatic ()).Value (); } DllExport const char * CrowdManager_GetTypeNameStatic () { return stringdup((CrowdManager::GetTypeNameStatic ()).CString ()); } DllExport void * CrowdManager_CrowdManager (Urho3D::Context * context) { return WeakPtr<CrowdManager>(new CrowdManager(context)); } DllExport void CrowdManager_RegisterObject (Urho3D::Context * context) { CrowdManager::RegisterObject (context); } DllExport void CrowdManager_ApplyAttributes (Urho3D::CrowdManager *_target) { _target->ApplyAttributes (); } DllExport void CrowdManager_DrawDebugGeometry (Urho3D::CrowdManager *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void CrowdManager_DrawDebugGeometry0 (Urho3D::CrowdManager *_target, bool depthTest) { _target->DrawDebugGeometry (depthTest); } DllExport void CrowdManager_SetCrowdTarget (Urho3D::CrowdManager *_target, const class Urho3D::Vector3 & position, Urho3D::Node * node) { _target->SetCrowdTarget (position, node); } DllExport void CrowdManager_SetCrowdVelocity (Urho3D::CrowdManager *_target, const class Urho3D::Vector3 & velocity, Urho3D::Node * node) { _target->SetCrowdVelocity (velocity, node); } DllExport void CrowdManager_ResetCrowdTarget (Urho3D::CrowdManager *_target, Urho3D::Node * node) { _target->ResetCrowdTarget (node); } DllExport void CrowdManager_SetMaxAgents (Urho3D::CrowdManager *_target, unsigned int maxAgents) { _target->SetMaxAgents (maxAgents); } DllExport void CrowdManager_SetMaxAgentRadius (Urho3D::CrowdManager *_target, float maxAgentRadius) { _target->SetMaxAgentRadius (maxAgentRadius); } DllExport void CrowdManager_SetNavigationMesh (Urho3D::CrowdManager *_target, Urho3D::NavigationMesh * navMesh) { _target->SetNavigationMesh (navMesh); } DllExport void CrowdManager_SetIncludeFlags (Urho3D::CrowdManager *_target, unsigned int queryFilterType, unsigned short flags) { _target->SetIncludeFlags (queryFilterType, flags); } DllExport void CrowdManager_SetExcludeFlags (Urho3D::CrowdManager *_target, unsigned int queryFilterType, unsigned short flags) { _target->SetExcludeFlags (queryFilterType, flags); } DllExport void CrowdManager_SetAreaCost (Urho3D::CrowdManager *_target, unsigned int queryFilterType, unsigned int areaID, float cost) { _target->SetAreaCost (queryFilterType, areaID, cost); } DllExport void CrowdManager_SetObstacleAvoidanceParams (Urho3D::CrowdManager *_target, unsigned int obstacleAvoidanceType, const struct Urho3D::CrowdObstacleAvoidanceParams & params) { _target->SetObstacleAvoidanceParams (obstacleAvoidanceType, params); } DllExport Interop::Vector3 CrowdManager_FindNearestPoint (Urho3D::CrowdManager *_target, const class Urho3D::Vector3 & point, int queryFilterType, dtPolyRef * nearestRef) { return *((Interop::Vector3 *) &(_target->FindNearestPoint (point, queryFilterType, nearestRef))); } DllExport Interop::Vector3 CrowdManager_MoveAlongSurface (Urho3D::CrowdManager *_target, const class Urho3D::Vector3 & start, const class Urho3D::Vector3 & end, int queryFilterType, int maxVisited) { return *((Interop::Vector3 *) &(_target->MoveAlongSurface (start, end, queryFilterType, maxVisited))); } DllExport Interop::Vector3 CrowdManager_GetRandomPoint (Urho3D::CrowdManager *_target, int queryFilterType, dtPolyRef * randomRef) { return *((Interop::Vector3 *) &(_target->GetRandomPoint (queryFilterType, randomRef))); } DllExport Interop::Vector3 CrowdManager_GetRandomPointInCircle (Urho3D::CrowdManager *_target, const class Urho3D::Vector3 & center, float radius, int queryFilterType, dtPolyRef * randomRef) { return *((Interop::Vector3 *) &(_target->GetRandomPointInCircle (center, radius, queryFilterType, randomRef))); } DllExport float CrowdManager_GetDistanceToWall (Urho3D::CrowdManager *_target, const class Urho3D::Vector3 & point, float radius, int queryFilterType, Urho3D::Vector3 * hitPos, Urho3D::Vector3 * hitNormal) { return _target->GetDistanceToWall (point, radius, queryFilterType, hitPos, hitNormal); } DllExport Interop::Vector3 CrowdManager_Raycast (Urho3D::CrowdManager *_target, const class Urho3D::Vector3 & start, const class Urho3D::Vector3 & end, int queryFilterType, Urho3D::Vector3 * hitNormal) { return *((Interop::Vector3 *) &(_target->Raycast (start, end, queryFilterType, hitNormal))); } DllExport unsigned int CrowdManager_GetMaxAgents (Urho3D::CrowdManager *_target) { return _target->GetMaxAgents (); } DllExport float CrowdManager_GetMaxAgentRadius (Urho3D::CrowdManager *_target) { return _target->GetMaxAgentRadius (); } DllExport Urho3D::NavigationMesh * CrowdManager_GetNavigationMesh (Urho3D::CrowdManager *_target) { return _target->GetNavigationMesh (); } DllExport unsigned int CrowdManager_GetNumQueryFilterTypes (Urho3D::CrowdManager *_target) { return _target->GetNumQueryFilterTypes (); } DllExport unsigned int CrowdManager_GetNumAreas (Urho3D::CrowdManager *_target, unsigned int queryFilterType) { return _target->GetNumAreas (queryFilterType); } DllExport unsigned short CrowdManager_GetIncludeFlags (Urho3D::CrowdManager *_target, unsigned int queryFilterType) { return _target->GetIncludeFlags (queryFilterType); } DllExport unsigned short CrowdManager_GetExcludeFlags (Urho3D::CrowdManager *_target, unsigned int queryFilterType) { return _target->GetExcludeFlags (queryFilterType); } DllExport float CrowdManager_GetAreaCost (Urho3D::CrowdManager *_target, unsigned int queryFilterType, unsigned int areaID) { return _target->GetAreaCost (queryFilterType, areaID); } DllExport unsigned int CrowdManager_GetNumObstacleAvoidanceTypes (Urho3D::CrowdManager *_target) { return _target->GetNumObstacleAvoidanceTypes (); } DllExport Urho3D::CrowdObstacleAvoidanceParams CrowdManager_GetObstacleAvoidanceParams (Urho3D::CrowdManager *_target, unsigned int obstacleAvoidanceType) { return _target->GetObstacleAvoidanceParams (obstacleAvoidanceType); } DllExport int CrowdAgent_GetType (Urho3D::CrowdAgent *_target) { return (_target->GetType ()).Value (); } DllExport const char * CrowdAgent_GetTypeName (Urho3D::CrowdAgent *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CrowdAgent_GetTypeStatic () { return (CrowdAgent::GetTypeStatic ()).Value (); } DllExport const char * CrowdAgent_GetTypeNameStatic () { return stringdup((CrowdAgent::GetTypeNameStatic ()).CString ()); } DllExport void * CrowdAgent_CrowdAgent (Urho3D::Context * context) { return WeakPtr<CrowdAgent>(new CrowdAgent(context)); } DllExport void CrowdAgent_RegisterObject (Urho3D::Context * context) { CrowdAgent::RegisterObject (context); } DllExport void CrowdAgent_ApplyAttributes (Urho3D::CrowdAgent *_target) { _target->ApplyAttributes (); } DllExport void CrowdAgent_OnSetEnabled (Urho3D::CrowdAgent *_target) { _target->OnSetEnabled (); } DllExport void CrowdAgent_DrawDebugGeometry (Urho3D::CrowdAgent *_target, bool depthTest) { _target->DrawDebugGeometry (depthTest); } DllExport void CrowdAgent_DrawDebugGeometry0 (Urho3D::CrowdAgent *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void CrowdAgent_SetTargetPosition (Urho3D::CrowdAgent *_target, const class Urho3D::Vector3 & position) { _target->SetTargetPosition (position); } DllExport void CrowdAgent_SetTargetVelocity (Urho3D::CrowdAgent *_target, const class Urho3D::Vector3 & velocity) { _target->SetTargetVelocity (velocity); } DllExport void CrowdAgent_ResetTarget (Urho3D::CrowdAgent *_target) { _target->ResetTarget (); } DllExport void CrowdAgent_SetUpdateNodePosition (Urho3D::CrowdAgent *_target, bool unodepos) { _target->SetUpdateNodePosition (unodepos); } DllExport void CrowdAgent_SetMaxAccel (Urho3D::CrowdAgent *_target, float maxAccel) { _target->SetMaxAccel (maxAccel); } DllExport void CrowdAgent_SetMaxSpeed (Urho3D::CrowdAgent *_target, float maxSpeed) { _target->SetMaxSpeed (maxSpeed); } DllExport void CrowdAgent_SetRadius (Urho3D::CrowdAgent *_target, float radius) { _target->SetRadius (radius); } DllExport void CrowdAgent_SetHeight (Urho3D::CrowdAgent *_target, float height) { _target->SetHeight (height); } DllExport void CrowdAgent_SetQueryFilterType (Urho3D::CrowdAgent *_target, unsigned int queryFilterType) { _target->SetQueryFilterType (queryFilterType); } DllExport void CrowdAgent_SetObstacleAvoidanceType (Urho3D::CrowdAgent *_target, unsigned int obstacleAvoidanceType) { _target->SetObstacleAvoidanceType (obstacleAvoidanceType); } DllExport void CrowdAgent_SetNavigationQuality (Urho3D::CrowdAgent *_target, enum Urho3D::NavigationQuality val) { _target->SetNavigationQuality (val); } DllExport void CrowdAgent_SetNavigationPushiness (Urho3D::CrowdAgent *_target, enum Urho3D::NavigationPushiness val) { _target->SetNavigationPushiness (val); } DllExport Interop::Vector3 CrowdAgent_GetPosition (Urho3D::CrowdAgent *_target) { return *((Interop::Vector3 *) &(_target->GetPosition ())); } DllExport Interop::Vector3 CrowdAgent_GetDesiredVelocity (Urho3D::CrowdAgent *_target) { return *((Interop::Vector3 *) &(_target->GetDesiredVelocity ())); } DllExport Interop::Vector3 CrowdAgent_GetActualVelocity (Urho3D::CrowdAgent *_target) { return *((Interop::Vector3 *) &(_target->GetActualVelocity ())); } DllExport Interop::Vector3 CrowdAgent_GetTargetPosition (Urho3D::CrowdAgent *_target) { return *((Interop::Vector3 *) &(_target->GetTargetPosition ())); } DllExport Interop::Vector3 CrowdAgent_GetTargetVelocity (Urho3D::CrowdAgent *_target) { return *((Interop::Vector3 *) &(_target->GetTargetVelocity ())); } DllExport enum Urho3D::CrowdAgentRequestedTarget CrowdAgent_GetRequestedTargetType (Urho3D::CrowdAgent *_target) { return _target->GetRequestedTargetType (); } DllExport enum Urho3D::CrowdAgentState CrowdAgent_GetAgentState (Urho3D::CrowdAgent *_target) { return _target->GetAgentState (); } DllExport enum Urho3D::CrowdAgentTargetState CrowdAgent_GetTargetState (Urho3D::CrowdAgent *_target) { return _target->GetTargetState (); } DllExport int CrowdAgent_GetUpdateNodePosition (Urho3D::CrowdAgent *_target) { return _target->GetUpdateNodePosition (); } DllExport int CrowdAgent_GetAgentCrowdId (Urho3D::CrowdAgent *_target) { return _target->GetAgentCrowdId (); } DllExport float CrowdAgent_GetMaxAccel (Urho3D::CrowdAgent *_target) { return _target->GetMaxAccel (); } DllExport float CrowdAgent_GetMaxSpeed (Urho3D::CrowdAgent *_target) { return _target->GetMaxSpeed (); } DllExport float CrowdAgent_GetRadius (Urho3D::CrowdAgent *_target) { return _target->GetRadius (); } DllExport float CrowdAgent_GetHeight (Urho3D::CrowdAgent *_target) { return _target->GetHeight (); } DllExport unsigned int CrowdAgent_GetQueryFilterType (Urho3D::CrowdAgent *_target) { return _target->GetQueryFilterType (); } DllExport unsigned int CrowdAgent_GetObstacleAvoidanceType (Urho3D::CrowdAgent *_target) { return _target->GetObstacleAvoidanceType (); } DllExport enum Urho3D::NavigationQuality CrowdAgent_GetNavigationQuality (Urho3D::CrowdAgent *_target) { return _target->GetNavigationQuality (); } DllExport enum Urho3D::NavigationPushiness CrowdAgent_GetNavigationPushiness (Urho3D::CrowdAgent *_target) { return _target->GetNavigationPushiness (); } DllExport int CrowdAgent_HasRequestedTarget (Urho3D::CrowdAgent *_target) { return _target->HasRequestedTarget (); } DllExport int CrowdAgent_HasArrived (Urho3D::CrowdAgent *_target) { return _target->HasArrived (); } DllExport int CrowdAgent_IsInCrowd (Urho3D::CrowdAgent *_target) { return _target->IsInCrowd (); } DllExport int NavigationMesh_GetType (Urho3D::NavigationMesh *_target) { return (_target->GetType ()).Value (); } DllExport const char * NavigationMesh_GetTypeName (Urho3D::NavigationMesh *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int NavigationMesh_GetTypeStatic () { return (NavigationMesh::GetTypeStatic ()).Value (); } DllExport const char * NavigationMesh_GetTypeNameStatic () { return stringdup((NavigationMesh::GetTypeNameStatic ()).CString ()); } DllExport void * NavigationMesh_NavigationMesh (Urho3D::Context * context) { return WeakPtr<NavigationMesh>(new NavigationMesh(context)); } DllExport void NavigationMesh_RegisterObject (Urho3D::Context * context) { NavigationMesh::RegisterObject (context); } DllExport void NavigationMesh_DrawDebugGeometry (Urho3D::NavigationMesh *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void NavigationMesh_SetTileSize (Urho3D::NavigationMesh *_target, int size) { _target->SetTileSize (size); } DllExport void NavigationMesh_SetCellSize (Urho3D::NavigationMesh *_target, float size) { _target->SetCellSize (size); } DllExport void NavigationMesh_SetCellHeight (Urho3D::NavigationMesh *_target, float height) { _target->SetCellHeight (height); } DllExport void NavigationMesh_SetAgentHeight (Urho3D::NavigationMesh *_target, float height) { _target->SetAgentHeight (height); } DllExport void NavigationMesh_SetAgentRadius (Urho3D::NavigationMesh *_target, float radius) { _target->SetAgentRadius (radius); } DllExport void NavigationMesh_SetAgentMaxClimb (Urho3D::NavigationMesh *_target, float maxClimb) { _target->SetAgentMaxClimb (maxClimb); } DllExport void NavigationMesh_SetAgentMaxSlope (Urho3D::NavigationMesh *_target, float maxSlope) { _target->SetAgentMaxSlope (maxSlope); } DllExport void NavigationMesh_SetRegionMinSize (Urho3D::NavigationMesh *_target, float size) { _target->SetRegionMinSize (size); } DllExport void NavigationMesh_SetRegionMergeSize (Urho3D::NavigationMesh *_target, float size) { _target->SetRegionMergeSize (size); } DllExport void NavigationMesh_SetEdgeMaxLength (Urho3D::NavigationMesh *_target, float length) { _target->SetEdgeMaxLength (length); } DllExport void NavigationMesh_SetEdgeMaxError (Urho3D::NavigationMesh *_target, float error) { _target->SetEdgeMaxError (error); } DllExport void NavigationMesh_SetDetailSampleDistance (Urho3D::NavigationMesh *_target, float distance) { _target->SetDetailSampleDistance (distance); } DllExport void NavigationMesh_SetDetailSampleMaxError (Urho3D::NavigationMesh *_target, float error) { _target->SetDetailSampleMaxError (error); } DllExport void NavigationMesh_SetPadding (Urho3D::NavigationMesh *_target, const class Urho3D::Vector3 & padding) { _target->SetPadding (padding); } DllExport void NavigationMesh_SetAreaCost (Urho3D::NavigationMesh *_target, unsigned int areaID, float cost) { _target->SetAreaCost (areaID, cost); } DllExport int NavigationMesh_Allocate (Urho3D::NavigationMesh *_target, const class Urho3D::BoundingBox & boundingBox, unsigned int maxTiles) { return _target->Allocate (boundingBox, maxTiles); } DllExport int NavigationMesh_Build (Urho3D::NavigationMesh *_target) { return _target->Build (); } DllExport int NavigationMesh_Build0 (Urho3D::NavigationMesh *_target, const class Urho3D::BoundingBox & boundingBox) { return _target->Build (boundingBox); } DllExport int NavigationMesh_Build1 (Urho3D::NavigationMesh *_target, const class Urho3D::IntVector2 & from, const class Urho3D::IntVector2 & to) { return _target->Build (from, to); } DllExport void NavigationMesh_RemoveTile (Urho3D::NavigationMesh *_target, const class Urho3D::IntVector2 & tile) { _target->RemoveTile (tile); } DllExport void NavigationMesh_RemoveAllTiles (Urho3D::NavigationMesh *_target) { _target->RemoveAllTiles (); } DllExport int NavigationMesh_HasTile (Urho3D::NavigationMesh *_target, const class Urho3D::IntVector2 & tile) { return _target->HasTile (tile); } DllExport Interop::BoundingBox NavigationMesh_GetTileBoudningBox (Urho3D::NavigationMesh *_target, const class Urho3D::IntVector2 & tile) { return *((Interop::BoundingBox *) &(_target->GetTileBoudningBox (tile))); } DllExport Interop::IntVector2 NavigationMesh_GetTileIndex (Urho3D::NavigationMesh *_target, const class Urho3D::Vector3 & position) { return *((Interop::IntVector2 *) &(_target->GetTileIndex (position))); } DllExport Interop::Vector3 NavigationMesh_FindNearestPoint (Urho3D::NavigationMesh *_target, const class Urho3D::Vector3 & point, const class Urho3D::Vector3 & extents, const class dtQueryFilter * filter, dtPolyRef * nearestRef) { return *((Interop::Vector3 *) &(_target->FindNearestPoint (point, extents, filter, nearestRef))); } DllExport Interop::Vector3 NavigationMesh_MoveAlongSurface (Urho3D::NavigationMesh *_target, const class Urho3D::Vector3 & start, const class Urho3D::Vector3 & end, const class Urho3D::Vector3 & extents, int maxVisited, const class dtQueryFilter * filter) { return *((Interop::Vector3 *) &(_target->MoveAlongSurface (start, end, extents, maxVisited, filter))); } DllExport Interop::Vector3 NavigationMesh_GetRandomPoint (Urho3D::NavigationMesh *_target, const class dtQueryFilter * filter, dtPolyRef * randomRef) { return *((Interop::Vector3 *) &(_target->GetRandomPoint (filter, randomRef))); } DllExport Interop::Vector3 NavigationMesh_GetRandomPointInCircle (Urho3D::NavigationMesh *_target, const class Urho3D::Vector3 & center, float radius, const class Urho3D::Vector3 & extents, const class dtQueryFilter * filter, dtPolyRef * randomRef) { return *((Interop::Vector3 *) &(_target->GetRandomPointInCircle (center, radius, extents, filter, randomRef))); } DllExport float NavigationMesh_GetDistanceToWall (Urho3D::NavigationMesh *_target, const class Urho3D::Vector3 & point, float radius, const class Urho3D::Vector3 & extents, const class dtQueryFilter * filter, Urho3D::Vector3 * hitPos, Urho3D::Vector3 * hitNormal) { return _target->GetDistanceToWall (point, radius, extents, filter, hitPos, hitNormal); } DllExport Interop::Vector3 NavigationMesh_Raycast (Urho3D::NavigationMesh *_target, const class Urho3D::Vector3 & start, const class Urho3D::Vector3 & end, const class Urho3D::Vector3 & extents, const class dtQueryFilter * filter, Urho3D::Vector3 * hitNormal) { return *((Interop::Vector3 *) &(_target->Raycast (start, end, extents, filter, hitNormal))); } DllExport void NavigationMesh_DrawDebugGeometry2 (Urho3D::NavigationMesh *_target, bool depthTest) { _target->DrawDebugGeometry (depthTest); } DllExport const char * NavigationMesh_GetMeshName (Urho3D::NavigationMesh *_target) { return stringdup((_target->GetMeshName ()).CString ()); } DllExport void NavigationMesh_SetMeshName (Urho3D::NavigationMesh *_target, const char * newName) { _target->SetMeshName (Urho3D::String(newName)); } DllExport int NavigationMesh_GetTileSize (Urho3D::NavigationMesh *_target) { return _target->GetTileSize (); } DllExport float NavigationMesh_GetCellSize (Urho3D::NavigationMesh *_target) { return _target->GetCellSize (); } DllExport float NavigationMesh_GetCellHeight (Urho3D::NavigationMesh *_target) { return _target->GetCellHeight (); } DllExport float NavigationMesh_GetAgentHeight (Urho3D::NavigationMesh *_target) { return _target->GetAgentHeight (); } DllExport float NavigationMesh_GetAgentRadius (Urho3D::NavigationMesh *_target) { return _target->GetAgentRadius (); } DllExport float NavigationMesh_GetAgentMaxClimb (Urho3D::NavigationMesh *_target) { return _target->GetAgentMaxClimb (); } DllExport float NavigationMesh_GetAgentMaxSlope (Urho3D::NavigationMesh *_target) { return _target->GetAgentMaxSlope (); } DllExport float NavigationMesh_GetRegionMinSize (Urho3D::NavigationMesh *_target) { return _target->GetRegionMinSize (); } DllExport float NavigationMesh_GetRegionMergeSize (Urho3D::NavigationMesh *_target) { return _target->GetRegionMergeSize (); } DllExport float NavigationMesh_GetEdgeMaxLength (Urho3D::NavigationMesh *_target) { return _target->GetEdgeMaxLength (); } DllExport float NavigationMesh_GetEdgeMaxError (Urho3D::NavigationMesh *_target) { return _target->GetEdgeMaxError (); } DllExport float NavigationMesh_GetDetailSampleDistance (Urho3D::NavigationMesh *_target) { return _target->GetDetailSampleDistance (); } DllExport float NavigationMesh_GetDetailSampleMaxError (Urho3D::NavigationMesh *_target) { return _target->GetDetailSampleMaxError (); } DllExport Interop::Vector3 NavigationMesh_GetPadding (Urho3D::NavigationMesh *_target) { return *((Interop::Vector3 *) &(_target->GetPadding ())); } DllExport float NavigationMesh_GetAreaCost (Urho3D::NavigationMesh *_target, unsigned int areaID) { return _target->GetAreaCost (areaID); } DllExport int NavigationMesh_IsInitialized (Urho3D::NavigationMesh *_target) { return _target->IsInitialized (); } DllExport Interop::BoundingBox NavigationMesh_GetBoundingBox (Urho3D::NavigationMesh *_target) { return *((Interop::BoundingBox *) &(_target->GetBoundingBox ())); } DllExport Interop::BoundingBox NavigationMesh_GetWorldBoundingBox (Urho3D::NavigationMesh *_target) { return *((Interop::BoundingBox *) &(_target->GetWorldBoundingBox ())); } DllExport Interop::IntVector2 NavigationMesh_GetNumTiles (Urho3D::NavigationMesh *_target) { return *((Interop::IntVector2 *) &(_target->GetNumTiles ())); } DllExport void NavigationMesh_SetPartitionType (Urho3D::NavigationMesh *_target, enum Urho3D::NavmeshPartitionType aType) { _target->SetPartitionType (aType); } DllExport enum Urho3D::NavmeshPartitionType NavigationMesh_GetPartitionType (Urho3D::NavigationMesh *_target) { return _target->GetPartitionType (); } DllExport void NavigationMesh_SetDrawOffMeshConnections (Urho3D::NavigationMesh *_target, bool enable) { _target->SetDrawOffMeshConnections (enable); } DllExport int NavigationMesh_GetDrawOffMeshConnections (Urho3D::NavigationMesh *_target) { return _target->GetDrawOffMeshConnections (); } DllExport void NavigationMesh_SetDrawNavAreas (Urho3D::NavigationMesh *_target, bool enable) { _target->SetDrawNavAreas (enable); } DllExport int NavigationMesh_GetDrawNavAreas (Urho3D::NavigationMesh *_target) { return _target->GetDrawNavAreas (); } DllExport int DynamicNavigationMesh_GetType (Urho3D::DynamicNavigationMesh *_target) { return (_target->GetType ()).Value (); } DllExport const char * DynamicNavigationMesh_GetTypeName (Urho3D::DynamicNavigationMesh *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int DynamicNavigationMesh_GetTypeStatic () { return (DynamicNavigationMesh::GetTypeStatic ()).Value (); } DllExport const char * DynamicNavigationMesh_GetTypeNameStatic () { return stringdup((DynamicNavigationMesh::GetTypeNameStatic ()).CString ()); } DllExport void * DynamicNavigationMesh_DynamicNavigationMesh (Urho3D::Context * param1) { return WeakPtr<DynamicNavigationMesh>(new DynamicNavigationMesh(param1)); } DllExport void DynamicNavigationMesh_RegisterObject (Urho3D::Context * param1) { DynamicNavigationMesh::RegisterObject (param1); } DllExport int DynamicNavigationMesh_Allocate (Urho3D::DynamicNavigationMesh *_target, const class Urho3D::BoundingBox & boundingBox, unsigned int maxTiles) { return _target->Allocate (boundingBox, maxTiles); } DllExport int DynamicNavigationMesh_Build (Urho3D::DynamicNavigationMesh *_target) { return _target->Build (); } DllExport int DynamicNavigationMesh_Build0 (Urho3D::DynamicNavigationMesh *_target, const class Urho3D::BoundingBox & boundingBox) { return _target->Build (boundingBox); } DllExport int DynamicNavigationMesh_Build1 (Urho3D::DynamicNavigationMesh *_target, const class Urho3D::IntVector2 & from, const class Urho3D::IntVector2 & to) { return _target->Build (from, to); } DllExport int DynamicNavigationMesh_IsObstacleInTile (Urho3D::DynamicNavigationMesh *_target, Urho3D::Obstacle * obstacle, const class Urho3D::IntVector2 & tile) { return _target->IsObstacleInTile (obstacle, tile); } DllExport void DynamicNavigationMesh_RemoveTile (Urho3D::DynamicNavigationMesh *_target, const class Urho3D::IntVector2 & tile) { _target->RemoveTile (tile); } DllExport void DynamicNavigationMesh_RemoveAllTiles (Urho3D::DynamicNavigationMesh *_target) { _target->RemoveAllTiles (); } DllExport void DynamicNavigationMesh_DrawDebugGeometry (Urho3D::DynamicNavigationMesh *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void DynamicNavigationMesh_DrawDebugGeometry2 (Urho3D::DynamicNavigationMesh *_target, bool depthTest) { _target->DrawDebugGeometry (depthTest); } DllExport void DynamicNavigationMesh_SetMaxObstacles (Urho3D::DynamicNavigationMesh *_target, unsigned int maxObstacles) { _target->SetMaxObstacles (maxObstacles); } DllExport void DynamicNavigationMesh_SetMaxLayers (Urho3D::DynamicNavigationMesh *_target, unsigned int maxLayers) { _target->SetMaxLayers (maxLayers); } DllExport unsigned int DynamicNavigationMesh_GetMaxObstacles (Urho3D::DynamicNavigationMesh *_target) { return _target->GetMaxObstacles (); } DllExport unsigned int DynamicNavigationMesh_GetMaxLayers (Urho3D::DynamicNavigationMesh *_target) { return _target->GetMaxLayers (); } DllExport void DynamicNavigationMesh_SetDrawObstacles (Urho3D::DynamicNavigationMesh *_target, bool enable) { _target->SetDrawObstacles (enable); } DllExport int DynamicNavigationMesh_GetDrawObstacles (Urho3D::DynamicNavigationMesh *_target) { return _target->GetDrawObstacles (); } DllExport int NavArea_GetType (Urho3D::NavArea *_target) { return (_target->GetType ()).Value (); } DllExport const char * NavArea_GetTypeName (Urho3D::NavArea *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int NavArea_GetTypeStatic () { return (NavArea::GetTypeStatic ()).Value (); } DllExport const char * NavArea_GetTypeNameStatic () { return stringdup((NavArea::GetTypeNameStatic ()).CString ()); } DllExport void * NavArea_NavArea (Urho3D::Context * param1) { return WeakPtr<NavArea>(new NavArea(param1)); } DllExport void NavArea_RegisterObject (Urho3D::Context * param1) { NavArea::RegisterObject (param1); } DllExport void NavArea_DrawDebugGeometry (Urho3D::NavArea *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport unsigned int NavArea_GetAreaID (Urho3D::NavArea *_target) { return _target->GetAreaID (); } DllExport void NavArea_SetAreaID (Urho3D::NavArea *_target, unsigned int newID) { _target->SetAreaID (newID); } DllExport Interop::BoundingBox NavArea_GetBoundingBox (Urho3D::NavArea *_target) { return *((Interop::BoundingBox *) &(_target->GetBoundingBox ())); } DllExport void NavArea_SetBoundingBox (Urho3D::NavArea *_target, const class Urho3D::BoundingBox & bnds) { _target->SetBoundingBox (bnds); } DllExport Interop::BoundingBox NavArea_GetWorldBoundingBox (Urho3D::NavArea *_target) { return *((Interop::BoundingBox *) &(_target->GetWorldBoundingBox ())); } DllExport int Navigable_GetType (Urho3D::Navigable *_target) { return (_target->GetType ()).Value (); } DllExport const char * Navigable_GetTypeName (Urho3D::Navigable *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Navigable_GetTypeStatic () { return (Navigable::GetTypeStatic ()).Value (); } DllExport const char * Navigable_GetTypeNameStatic () { return stringdup((Navigable::GetTypeNameStatic ()).CString ()); } DllExport void * Navigable_Navigable (Urho3D::Context * context) { return WeakPtr<Navigable>(new Navigable(context)); } DllExport void Navigable_RegisterObject (Urho3D::Context * context) { Navigable::RegisterObject (context); } DllExport void Navigable_SetRecursive (Urho3D::Navigable *_target, bool enable) { _target->SetRecursive (enable); } DllExport int Navigable_IsRecursive (Urho3D::Navigable *_target) { return _target->IsRecursive (); } DllExport int Obstacle_GetType (Urho3D::Obstacle *_target) { return (_target->GetType ()).Value (); } DllExport const char * Obstacle_GetTypeName (Urho3D::Obstacle *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Obstacle_GetTypeStatic () { return (Obstacle::GetTypeStatic ()).Value (); } DllExport const char * Obstacle_GetTypeNameStatic () { return stringdup((Obstacle::GetTypeNameStatic ()).CString ()); } DllExport void * Obstacle_Obstacle (Urho3D::Context * param1) { return WeakPtr<Obstacle>(new Obstacle(param1)); } DllExport void Obstacle_RegisterObject (Urho3D::Context * param1) { Obstacle::RegisterObject (param1); } DllExport void Obstacle_OnSetEnabled (Urho3D::Obstacle *_target) { _target->OnSetEnabled (); } DllExport float Obstacle_GetHeight (Urho3D::Obstacle *_target) { return _target->GetHeight (); } DllExport void Obstacle_SetHeight (Urho3D::Obstacle *_target, float newHeight) { _target->SetHeight (newHeight); } DllExport float Obstacle_GetRadius (Urho3D::Obstacle *_target) { return _target->GetRadius (); } DllExport void Obstacle_SetRadius (Urho3D::Obstacle *_target, float newRadius) { _target->SetRadius (newRadius); } DllExport unsigned int Obstacle_GetObstacleID (Urho3D::Obstacle *_target) { return _target->GetObstacleID (); } DllExport void Obstacle_DrawDebugGeometry (Urho3D::Obstacle *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void Obstacle_DrawDebugGeometry0 (Urho3D::Obstacle *_target, bool depthTest) { _target->DrawDebugGeometry (depthTest); } DllExport int OffMeshConnection_GetType (Urho3D::OffMeshConnection *_target) { return (_target->GetType ()).Value (); } DllExport const char * OffMeshConnection_GetTypeName (Urho3D::OffMeshConnection *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int OffMeshConnection_GetTypeStatic () { return (OffMeshConnection::GetTypeStatic ()).Value (); } DllExport const char * OffMeshConnection_GetTypeNameStatic () { return stringdup((OffMeshConnection::GetTypeNameStatic ()).CString ()); } DllExport void * OffMeshConnection_OffMeshConnection (Urho3D::Context * context) { return WeakPtr<OffMeshConnection>(new OffMeshConnection(context)); } DllExport void OffMeshConnection_RegisterObject (Urho3D::Context * context) { OffMeshConnection::RegisterObject (context); } DllExport void OffMeshConnection_ApplyAttributes (Urho3D::OffMeshConnection *_target) { _target->ApplyAttributes (); } DllExport void OffMeshConnection_DrawDebugGeometry (Urho3D::OffMeshConnection *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void OffMeshConnection_SetEndPoint (Urho3D::OffMeshConnection *_target, Urho3D::Node * node) { _target->SetEndPoint (node); } DllExport void OffMeshConnection_SetRadius (Urho3D::OffMeshConnection *_target, float radius) { _target->SetRadius (radius); } DllExport void OffMeshConnection_SetBidirectional (Urho3D::OffMeshConnection *_target, bool enabled) { _target->SetBidirectional (enabled); } DllExport void OffMeshConnection_SetMask (Urho3D::OffMeshConnection *_target, unsigned int newMask) { _target->SetMask (newMask); } DllExport void OffMeshConnection_SetAreaID (Urho3D::OffMeshConnection *_target, unsigned int newAreaID) { _target->SetAreaID (newAreaID); } DllExport Urho3D::Node * OffMeshConnection_GetEndPoint (Urho3D::OffMeshConnection *_target) { return _target->GetEndPoint (); } DllExport float OffMeshConnection_GetRadius (Urho3D::OffMeshConnection *_target) { return _target->GetRadius (); } DllExport int OffMeshConnection_IsBidirectional (Urho3D::OffMeshConnection *_target) { return _target->IsBidirectional (); } DllExport unsigned int OffMeshConnection_GetMask (Urho3D::OffMeshConnection *_target) { return _target->GetMask (); } DllExport unsigned int OffMeshConnection_GetAreaID (Urho3D::OffMeshConnection *_target) { return _target->GetAreaID (); } DllExport int Connection_GetType (Urho3D::Connection *_target) { return (_target->GetType ()).Value (); } DllExport const char * Connection_GetTypeName (Urho3D::Connection *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Connection_GetTypeStatic () { return (Connection::GetTypeStatic ()).Value (); } DllExport const char * Connection_GetTypeNameStatic () { return stringdup((Connection::GetTypeNameStatic ()).CString ()); } DllExport void Connection_SendMessage (Urho3D::Connection *_target, int msgID, bool reliable, bool inOrder, const unsigned char * data, unsigned int numBytes, unsigned int contentID) { _target->SendMessage (msgID, reliable, inOrder, data, numBytes, contentID); } DllExport void Connection_SetScene (Urho3D::Connection *_target, Urho3D::Scene * newScene) { _target->SetScene (newScene); } DllExport void Connection_SetPosition (Urho3D::Connection *_target, const class Urho3D::Vector3 & position) { _target->SetPosition (position); } DllExport void Connection_SetRotation (Urho3D::Connection *_target, const class Urho3D::Quaternion & rotation) { _target->SetRotation (rotation); } DllExport void Connection_SetConnectPending (Urho3D::Connection *_target, bool connectPending) { _target->SetConnectPending (connectPending); } DllExport void Connection_SetLogStatistics (Urho3D::Connection *_target, bool enable) { _target->SetLogStatistics (enable); } DllExport void Connection_Disconnect (Urho3D::Connection *_target, int waitMSec) { _target->Disconnect (waitMSec); } DllExport void Connection_SendServerUpdate (Urho3D::Connection *_target) { _target->SendServerUpdate (); } DllExport void Connection_SendClientUpdate (Urho3D::Connection *_target) { _target->SendClientUpdate (); } DllExport void Connection_SendRemoteEvents (Urho3D::Connection *_target) { _target->SendRemoteEvents (); } DllExport void Connection_SendPackages (Urho3D::Connection *_target) { _target->SendPackages (); } DllExport void Connection_ProcessPendingLatestData (Urho3D::Connection *_target) { _target->ProcessPendingLatestData (); } DllExport Urho3D::Scene * Connection_GetScene (Urho3D::Connection *_target) { return _target->GetScene (); } DllExport unsigned char Connection_GetTimeStamp (Urho3D::Connection *_target) { return _target->GetTimeStamp (); } DllExport Interop::Vector3 Connection_GetPosition (Urho3D::Connection *_target) { return *((Interop::Vector3 *) &(_target->GetPosition ())); } DllExport Interop::Quaternion Connection_GetRotation (Urho3D::Connection *_target) { return *((Interop::Quaternion *) &(_target->GetRotation ())); } DllExport int Connection_IsClient (Urho3D::Connection *_target) { return _target->IsClient (); } DllExport int Connection_IsConnected (Urho3D::Connection *_target) { return _target->IsConnected (); } DllExport int Connection_IsConnectPending (Urho3D::Connection *_target) { return _target->IsConnectPending (); } DllExport int Connection_IsSceneLoaded (Urho3D::Connection *_target) { return _target->IsSceneLoaded (); } DllExport int Connection_GetLogStatistics (Urho3D::Connection *_target) { return _target->GetLogStatistics (); } DllExport const char * Connection_GetAddress (Urho3D::Connection *_target) { return stringdup((_target->GetAddress ()).CString ()); } DllExport unsigned short Connection_GetPort (Urho3D::Connection *_target) { return _target->GetPort (); } DllExport float Connection_GetRoundTripTime (Urho3D::Connection *_target) { return _target->GetRoundTripTime (); } DllExport float Connection_GetLastHeardTime (Urho3D::Connection *_target) { return _target->GetLastHeardTime (); } DllExport float Connection_GetBytesInPerSec (Urho3D::Connection *_target) { return _target->GetBytesInPerSec (); } DllExport float Connection_GetBytesOutPerSec (Urho3D::Connection *_target) { return _target->GetBytesOutPerSec (); } DllExport float Connection_GetPacketsInPerSec (Urho3D::Connection *_target) { return _target->GetPacketsInPerSec (); } DllExport float Connection_GetPacketsOutPerSec (Urho3D::Connection *_target) { return _target->GetPacketsOutPerSec (); } DllExport const char * Connection_ToString (Urho3D::Connection *_target) { return stringdup((_target->ToString ()).CString ()); } DllExport unsigned int Connection_GetNumDownloads (Urho3D::Connection *_target) { return _target->GetNumDownloads (); } DllExport const char * Connection_GetDownloadName (Urho3D::Connection *_target) { return stringdup((_target->GetDownloadName ()).CString ()); } DllExport float Connection_GetDownloadProgress (Urho3D::Connection *_target) { return _target->GetDownloadProgress (); } DllExport void Connection_SendPackageToClient (Urho3D::Connection *_target, Urho3D::PackageFile * package) { _target->SendPackageToClient (package); } DllExport void Connection_ConfigureNetworkSimulator (Urho3D::Connection *_target, int latencyMs, float packetLoss) { _target->ConfigureNetworkSimulator (latencyMs, packetLoss); } DllExport void HttpRequest_ThreadFunction (Urho3D::HttpRequest *_target) { _target->ThreadFunction (); } DllExport unsigned int HttpRequest_Read (Urho3D::HttpRequest *_target, void * dest, unsigned int size) { return _target->Read (dest, size); } DllExport unsigned int HttpRequest_Seek (Urho3D::HttpRequest *_target, unsigned int position) { return _target->Seek (position); } DllExport int HttpRequest_IsEof (Urho3D::HttpRequest *_target) { return _target->IsEof (); } DllExport const char * HttpRequest_GetURL (Urho3D::HttpRequest *_target) { return stringdup((_target->GetURL ()).CString ()); } DllExport const char * HttpRequest_GetVerb (Urho3D::HttpRequest *_target) { return stringdup((_target->GetVerb ()).CString ()); } DllExport const char * HttpRequest_GetError (Urho3D::HttpRequest *_target) { return stringdup((_target->GetError ()).CString ()); } DllExport enum Urho3D::HttpRequestState HttpRequest_GetState (Urho3D::HttpRequest *_target) { return _target->GetState (); } DllExport unsigned int HttpRequest_GetAvailableSize (Urho3D::HttpRequest *_target) { return _target->GetAvailableSize (); } DllExport int HttpRequest_IsOpen (Urho3D::HttpRequest *_target) { return _target->IsOpen (); } DllExport int Network_GetType (Urho3D::Network *_target) { return (_target->GetType ()).Value (); } DllExport const char * Network_GetTypeName (Urho3D::Network *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Network_GetTypeStatic () { return (Network::GetTypeStatic ()).Value (); } DllExport const char * Network_GetTypeNameStatic () { return stringdup((Network::GetTypeNameStatic ()).CString ()); } DllExport void * Network_Network (Urho3D::Context * context) { return WeakPtr<Network>(new Network(context)); } DllExport void Network_Disconnect (Urho3D::Network *_target, int waitMSec) { _target->Disconnect (waitMSec); } DllExport int Network_StartServer (Urho3D::Network *_target, unsigned short port) { return _target->StartServer (port); } DllExport void Network_StopServer (Urho3D::Network *_target) { _target->StopServer (); } DllExport void Network_BroadcastMessage (Urho3D::Network *_target, int msgID, bool reliable, bool inOrder, const unsigned char * data, unsigned int numBytes, unsigned int contentID) { _target->BroadcastMessage (msgID, reliable, inOrder, data, numBytes, contentID); } DllExport void Network_SetUpdateFps (Urho3D::Network *_target, int fps) { _target->SetUpdateFps (fps); } DllExport void Network_SetSimulatedLatency (Urho3D::Network *_target, int ms) { _target->SetSimulatedLatency (ms); } DllExport void Network_SetSimulatedPacketLoss (Urho3D::Network *_target, float probability) { _target->SetSimulatedPacketLoss (probability); } DllExport void Network_RegisterRemoteEvent (Urho3D::Network *_target, int eventType) { _target->RegisterRemoteEvent (Urho3D::StringHash(eventType)); } DllExport void Network_UnregisterRemoteEvent (Urho3D::Network *_target, int eventType) { _target->UnregisterRemoteEvent (Urho3D::StringHash(eventType)); } DllExport void Network_UnregisterAllRemoteEvents (Urho3D::Network *_target) { _target->UnregisterAllRemoteEvents (); } DllExport void Network_SetPackageCacheDir (Urho3D::Network *_target, const char * path) { _target->SetPackageCacheDir (Urho3D::String(path)); } DllExport void Network_SendPackageToClients (Urho3D::Network *_target, Urho3D::Scene * scene, Urho3D::PackageFile * package) { _target->SendPackageToClients (scene, package); } DllExport int Network_GetUpdateFps (Urho3D::Network *_target) { return _target->GetUpdateFps (); } DllExport int Network_GetSimulatedLatency (Urho3D::Network *_target) { return _target->GetSimulatedLatency (); } DllExport float Network_GetSimulatedPacketLoss (Urho3D::Network *_target) { return _target->GetSimulatedPacketLoss (); } DllExport Urho3D::Connection * Network_GetServerConnection (Urho3D::Network *_target) { return _target->GetServerConnection (); } DllExport int Network_IsServerRunning (Urho3D::Network *_target) { return _target->IsServerRunning (); } DllExport int Network_CheckRemoteEvent (Urho3D::Network *_target, int eventType) { return _target->CheckRemoteEvent (Urho3D::StringHash(eventType)); } DllExport const char * Network_GetPackageCacheDir (Urho3D::Network *_target) { return stringdup((_target->GetPackageCacheDir ()).CString ()); } DllExport void Network_Update (Urho3D::Network *_target, float timeStep) { _target->Update (timeStep); } DllExport void Network_PostUpdate (Urho3D::Network *_target, float timeStep) { _target->PostUpdate (timeStep); } DllExport int NetworkPriority_GetType (Urho3D::NetworkPriority *_target) { return (_target->GetType ()).Value (); } DllExport const char * NetworkPriority_GetTypeName (Urho3D::NetworkPriority *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int NetworkPriority_GetTypeStatic () { return (NetworkPriority::GetTypeStatic ()).Value (); } DllExport const char * NetworkPriority_GetTypeNameStatic () { return stringdup((NetworkPriority::GetTypeNameStatic ()).CString ()); } DllExport void * NetworkPriority_NetworkPriority (Urho3D::Context * context) { return WeakPtr<NetworkPriority>(new NetworkPriority(context)); } DllExport void NetworkPriority_RegisterObject (Urho3D::Context * context) { NetworkPriority::RegisterObject (context); } DllExport void NetworkPriority_SetBasePriority (Urho3D::NetworkPriority *_target, float priority) { _target->SetBasePriority (priority); } DllExport void NetworkPriority_SetDistanceFactor (Urho3D::NetworkPriority *_target, float factor) { _target->SetDistanceFactor (factor); } DllExport void NetworkPriority_SetMinPriority (Urho3D::NetworkPriority *_target, float priority) { _target->SetMinPriority (priority); } DllExport void NetworkPriority_SetAlwaysUpdateOwner (Urho3D::NetworkPriority *_target, bool enable) { _target->SetAlwaysUpdateOwner (enable); } DllExport float NetworkPriority_GetBasePriority (Urho3D::NetworkPriority *_target) { return _target->GetBasePriority (); } DllExport float NetworkPriority_GetDistanceFactor (Urho3D::NetworkPriority *_target) { return _target->GetDistanceFactor (); } DllExport float NetworkPriority_GetMinPriority (Urho3D::NetworkPriority *_target) { return _target->GetMinPriority (); } DllExport int NetworkPriority_GetAlwaysUpdateOwner (Urho3D::NetworkPriority *_target) { return _target->GetAlwaysUpdateOwner (); } DllExport int NetworkPriority_CheckUpdate (Urho3D::NetworkPriority *_target, float distance, float & accumulator) { return _target->CheckUpdate (distance, accumulator); } DllExport void * TriangleMeshData_TriangleMeshData (Urho3D::Model * model, unsigned int lodLevel) { return WeakPtr<TriangleMeshData>(new TriangleMeshData(model, lodLevel)); } DllExport void * TriangleMeshData_TriangleMeshData0 (Urho3D::CustomGeometry * custom) { return WeakPtr<TriangleMeshData>(new TriangleMeshData(custom)); } DllExport void * GImpactMeshData_GImpactMeshData (Urho3D::Model * model, unsigned int lodLevel) { return WeakPtr<GImpactMeshData>(new GImpactMeshData(model, lodLevel)); } DllExport void * GImpactMeshData_GImpactMeshData0 (Urho3D::CustomGeometry * custom) { return WeakPtr<GImpactMeshData>(new GImpactMeshData(custom)); } DllExport void * ConvexData_ConvexData (Urho3D::Model * model, unsigned int lodLevel) { return WeakPtr<ConvexData>(new ConvexData(model, lodLevel)); } DllExport void * ConvexData_ConvexData0 (Urho3D::CustomGeometry * custom) { return WeakPtr<ConvexData>(new ConvexData(custom)); } DllExport void * HeightfieldData_HeightfieldData (Urho3D::Terrain * terrain, unsigned int lodLevel) { return WeakPtr<HeightfieldData>(new HeightfieldData(terrain, lodLevel)); } DllExport int CollisionShape_GetType (Urho3D::CollisionShape *_target) { return (_target->GetType ()).Value (); } DllExport const char * CollisionShape_GetTypeName (Urho3D::CollisionShape *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CollisionShape_GetTypeStatic () { return (CollisionShape::GetTypeStatic ()).Value (); } DllExport const char * CollisionShape_GetTypeNameStatic () { return stringdup((CollisionShape::GetTypeNameStatic ()).CString ()); } DllExport void * CollisionShape_CollisionShape (Urho3D::Context * context) { return WeakPtr<CollisionShape>(new CollisionShape(context)); } DllExport void CollisionShape_RegisterObject (Urho3D::Context * context) { CollisionShape::RegisterObject (context); } DllExport void CollisionShape_ApplyAttributes (Urho3D::CollisionShape *_target) { _target->ApplyAttributes (); } DllExport void CollisionShape_OnSetEnabled (Urho3D::CollisionShape *_target) { _target->OnSetEnabled (); } DllExport void CollisionShape_DrawDebugGeometry (Urho3D::CollisionShape *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void CollisionShape_SetBox (Urho3D::CollisionShape *_target, const class Urho3D::Vector3 & size, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetBox (size, position, rotation); } DllExport void CollisionShape_SetSphere (Urho3D::CollisionShape *_target, float diameter, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetSphere (diameter, position, rotation); } DllExport void CollisionShape_SetStaticPlane (Urho3D::CollisionShape *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetStaticPlane (position, rotation); } DllExport void CollisionShape_SetCylinder (Urho3D::CollisionShape *_target, float diameter, float height, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetCylinder (diameter, height, position, rotation); } DllExport void CollisionShape_SetCapsule (Urho3D::CollisionShape *_target, float diameter, float height, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetCapsule (diameter, height, position, rotation); } DllExport void CollisionShape_SetCone (Urho3D::CollisionShape *_target, float diameter, float height, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetCone (diameter, height, position, rotation); } DllExport void CollisionShape_SetTriangleMesh (Urho3D::CollisionShape *_target, Urho3D::Model * model, unsigned int lodLevel, const class Urho3D::Vector3 & scale, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetTriangleMesh (model, lodLevel, scale, position, rotation); } DllExport void CollisionShape_SetCustomTriangleMesh (Urho3D::CollisionShape *_target, Urho3D::CustomGeometry * custom, const class Urho3D::Vector3 & scale, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetCustomTriangleMesh (custom, scale, position, rotation); } DllExport void CollisionShape_SetConvexHull (Urho3D::CollisionShape *_target, Urho3D::Model * model, unsigned int lodLevel, const class Urho3D::Vector3 & scale, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetConvexHull (model, lodLevel, scale, position, rotation); } DllExport void CollisionShape_SetCustomConvexHull (Urho3D::CollisionShape *_target, Urho3D::CustomGeometry * custom, const class Urho3D::Vector3 & scale, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetCustomConvexHull (custom, scale, position, rotation); } DllExport void CollisionShape_SetGImpactMesh (Urho3D::CollisionShape *_target, Urho3D::Model * model, unsigned int lodLevel, const class Urho3D::Vector3 & scale, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetGImpactMesh (model, lodLevel, scale, position, rotation); } DllExport void CollisionShape_SetCustomGImpactMesh (Urho3D::CollisionShape *_target, Urho3D::CustomGeometry * custom, const class Urho3D::Vector3 & scale, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetCustomGImpactMesh (custom, scale, position, rotation); } DllExport void CollisionShape_SetTerrain (Urho3D::CollisionShape *_target, unsigned int lodLevel) { _target->SetTerrain (lodLevel); } DllExport void CollisionShape_SetShapeType (Urho3D::CollisionShape *_target, enum Urho3D::ShapeType type) { _target->SetShapeType (type); } DllExport void CollisionShape_SetSize (Urho3D::CollisionShape *_target, const class Urho3D::Vector3 & size) { _target->SetSize (size); } DllExport void CollisionShape_SetPosition (Urho3D::CollisionShape *_target, const class Urho3D::Vector3 & position) { _target->SetPosition (position); } DllExport void CollisionShape_SetRotation (Urho3D::CollisionShape *_target, const class Urho3D::Quaternion & rotation) { _target->SetRotation (rotation); } DllExport void CollisionShape_SetTransform (Urho3D::CollisionShape *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetTransform (position, rotation); } DllExport void CollisionShape_SetMargin (Urho3D::CollisionShape *_target, float margin) { _target->SetMargin (margin); } DllExport void CollisionShape_SetModel (Urho3D::CollisionShape *_target, Urho3D::Model * model) { _target->SetModel (model); } DllExport void CollisionShape_SetLodLevel (Urho3D::CollisionShape *_target, unsigned int lodLevel) { _target->SetLodLevel (lodLevel); } DllExport Urho3D::PhysicsWorld * CollisionShape_GetPhysicsWorld (Urho3D::CollisionShape *_target) { return _target->GetPhysicsWorld (); } DllExport enum Urho3D::ShapeType CollisionShape_GetShapeType (Urho3D::CollisionShape *_target) { return _target->GetShapeType (); } DllExport Interop::Vector3 CollisionShape_GetSize (Urho3D::CollisionShape *_target) { return *((Interop::Vector3 *) &(_target->GetSize ())); } DllExport Interop::Vector3 CollisionShape_GetPosition (Urho3D::CollisionShape *_target) { return *((Interop::Vector3 *) &(_target->GetPosition ())); } DllExport Interop::Quaternion CollisionShape_GetRotation (Urho3D::CollisionShape *_target) { return *((Interop::Quaternion *) &(_target->GetRotation ())); } DllExport float CollisionShape_GetMargin (Urho3D::CollisionShape *_target) { return _target->GetMargin (); } DllExport Urho3D::Model * CollisionShape_GetModel (Urho3D::CollisionShape *_target) { return _target->GetModel (); } DllExport unsigned int CollisionShape_GetLodLevel (Urho3D::CollisionShape *_target) { return _target->GetLodLevel (); } DllExport Interop::BoundingBox CollisionShape_GetWorldBoundingBox (Urho3D::CollisionShape *_target) { return *((Interop::BoundingBox *) &(_target->GetWorldBoundingBox ())); } DllExport void CollisionShape_NotifyRigidBody (Urho3D::CollisionShape *_target, bool updateMass) { _target->NotifyRigidBody (updateMass); } DllExport Urho3D::ResourceRef CollisionShape_GetModelAttr (Urho3D::CollisionShape *_target) { return _target->GetModelAttr (); } DllExport void CollisionShape_ReleaseShape (Urho3D::CollisionShape *_target) { _target->ReleaseShape (); } DllExport int Constraint_GetType (Urho3D::Constraint *_target) { return (_target->GetType ()).Value (); } DllExport const char * Constraint_GetTypeName (Urho3D::Constraint *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Constraint_GetTypeStatic () { return (Constraint::GetTypeStatic ()).Value (); } DllExport const char * Constraint_GetTypeNameStatic () { return stringdup((Constraint::GetTypeNameStatic ()).CString ()); } DllExport void * Constraint_Constraint (Urho3D::Context * context) { return WeakPtr<Constraint>(new Constraint(context)); } DllExport void Constraint_RegisterObject (Urho3D::Context * context) { Constraint::RegisterObject (context); } DllExport void Constraint_ApplyAttributes (Urho3D::Constraint *_target) { _target->ApplyAttributes (); } DllExport void Constraint_OnSetEnabled (Urho3D::Constraint *_target) { _target->OnSetEnabled (); } DllExport void Constraint_DrawDebugGeometry (Urho3D::Constraint *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void Constraint_SetConstraintType (Urho3D::Constraint *_target, enum Urho3D::ConstraintType type) { _target->SetConstraintType (type); } DllExport void Constraint_SetOtherBody (Urho3D::Constraint *_target, Urho3D::RigidBody * body) { _target->SetOtherBody (body); } DllExport void Constraint_SetPosition (Urho3D::Constraint *_target, const class Urho3D::Vector3 & position) { _target->SetPosition (position); } DllExport void Constraint_SetRotation (Urho3D::Constraint *_target, const class Urho3D::Quaternion & rotation) { _target->SetRotation (rotation); } DllExport void Constraint_SetAxis (Urho3D::Constraint *_target, const class Urho3D::Vector3 & axis) { _target->SetAxis (axis); } DllExport void Constraint_SetOtherPosition (Urho3D::Constraint *_target, const class Urho3D::Vector3 & position) { _target->SetOtherPosition (position); } DllExport void Constraint_SetOtherRotation (Urho3D::Constraint *_target, const class Urho3D::Quaternion & rotation) { _target->SetOtherRotation (rotation); } DllExport void Constraint_SetOtherAxis (Urho3D::Constraint *_target, const class Urho3D::Vector3 & axis) { _target->SetOtherAxis (axis); } DllExport void Constraint_SetWorldPosition (Urho3D::Constraint *_target, const class Urho3D::Vector3 & position) { _target->SetWorldPosition (position); } DllExport void Constraint_SetHighLimit (Urho3D::Constraint *_target, const class Urho3D::Vector2 & limit) { _target->SetHighLimit (limit); } DllExport void Constraint_SetLowLimit (Urho3D::Constraint *_target, const class Urho3D::Vector2 & limit) { _target->SetLowLimit (limit); } DllExport void Constraint_SetERP (Urho3D::Constraint *_target, float erp) { _target->SetERP (erp); } DllExport void Constraint_SetCFM (Urho3D::Constraint *_target, float cfm) { _target->SetCFM (cfm); } DllExport void Constraint_SetDisableCollision (Urho3D::Constraint *_target, bool disable) { _target->SetDisableCollision (disable); } DllExport Urho3D::PhysicsWorld * Constraint_GetPhysicsWorld (Urho3D::Constraint *_target) { return _target->GetPhysicsWorld (); } DllExport enum Urho3D::ConstraintType Constraint_GetConstraintType (Urho3D::Constraint *_target) { return _target->GetConstraintType (); } DllExport Urho3D::RigidBody * Constraint_GetOwnBody (Urho3D::Constraint *_target) { return _target->GetOwnBody (); } DllExport Urho3D::RigidBody * Constraint_GetOtherBody (Urho3D::Constraint *_target) { return _target->GetOtherBody (); } DllExport Interop::Vector3 Constraint_GetPosition (Urho3D::Constraint *_target) { return *((Interop::Vector3 *) &(_target->GetPosition ())); } DllExport Interop::Quaternion Constraint_GetRotation (Urho3D::Constraint *_target) { return *((Interop::Quaternion *) &(_target->GetRotation ())); } DllExport Interop::Vector3 Constraint_GetOtherPosition (Urho3D::Constraint *_target) { return *((Interop::Vector3 *) &(_target->GetOtherPosition ())); } DllExport Interop::Quaternion Constraint_GetOtherRotation (Urho3D::Constraint *_target) { return *((Interop::Quaternion *) &(_target->GetOtherRotation ())); } DllExport Interop::Vector3 Constraint_GetWorldPosition (Urho3D::Constraint *_target) { return *((Interop::Vector3 *) &(_target->GetWorldPosition ())); } DllExport Interop::Vector2 Constraint_GetHighLimit (Urho3D::Constraint *_target) { return *((Interop::Vector2 *) &(_target->GetHighLimit ())); } DllExport Interop::Vector2 Constraint_GetLowLimit (Urho3D::Constraint *_target) { return *((Interop::Vector2 *) &(_target->GetLowLimit ())); } DllExport float Constraint_GetERP (Urho3D::Constraint *_target) { return _target->GetERP (); } DllExport float Constraint_GetCFM (Urho3D::Constraint *_target) { return _target->GetCFM (); } DllExport int Constraint_GetDisableCollision (Urho3D::Constraint *_target) { return _target->GetDisableCollision (); } DllExport void Constraint_ReleaseConstraint (Urho3D::Constraint *_target) { _target->ReleaseConstraint (); } DllExport void Constraint_ApplyFrames (Urho3D::Constraint *_target) { _target->ApplyFrames (); } DllExport int PhysicsWorld_GetType (Urho3D::PhysicsWorld *_target) { return (_target->GetType ()).Value (); } DllExport const char * PhysicsWorld_GetTypeName (Urho3D::PhysicsWorld *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int PhysicsWorld_GetTypeStatic () { return (PhysicsWorld::GetTypeStatic ()).Value (); } DllExport const char * PhysicsWorld_GetTypeNameStatic () { return stringdup((PhysicsWorld::GetTypeNameStatic ()).CString ()); } DllExport void * PhysicsWorld_PhysicsWorld (Urho3D::Context * scontext) { return WeakPtr<PhysicsWorld>(new PhysicsWorld(scontext)); } DllExport void PhysicsWorld_RegisterObject (Urho3D::Context * context) { PhysicsWorld::RegisterObject (context); } DllExport void PhysicsWorld_setDebugMode (Urho3D::PhysicsWorld *_target, int debugMode) { _target->setDebugMode (debugMode); } DllExport int PhysicsWorld_getDebugMode (Urho3D::PhysicsWorld *_target) { return _target->getDebugMode (); } DllExport void PhysicsWorld_DrawDebugGeometry (Urho3D::PhysicsWorld *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void PhysicsWorld_Update (Urho3D::PhysicsWorld *_target, float timeStep) { _target->Update (timeStep); } DllExport void PhysicsWorld_UpdateCollisions (Urho3D::PhysicsWorld *_target) { _target->UpdateCollisions (); } DllExport void PhysicsWorld_SetFps (Urho3D::PhysicsWorld *_target, int fps) { _target->SetFps (fps); } DllExport void PhysicsWorld_SetGravity (Urho3D::PhysicsWorld *_target, const class Urho3D::Vector3 & gravity) { _target->SetGravity (gravity); } DllExport void PhysicsWorld_SetMaxSubSteps (Urho3D::PhysicsWorld *_target, int num) { _target->SetMaxSubSteps (num); } DllExport void PhysicsWorld_SetNumIterations (Urho3D::PhysicsWorld *_target, int num) { _target->SetNumIterations (num); } DllExport void PhysicsWorld_SetUpdateEnabled (Urho3D::PhysicsWorld *_target, bool enable) { _target->SetUpdateEnabled (enable); } DllExport void PhysicsWorld_SetInterpolation (Urho3D::PhysicsWorld *_target, bool enable) { _target->SetInterpolation (enable); } DllExport void PhysicsWorld_SetInternalEdge (Urho3D::PhysicsWorld *_target, bool enable) { _target->SetInternalEdge (enable); } DllExport void PhysicsWorld_SetSplitImpulse (Urho3D::PhysicsWorld *_target, bool enable) { _target->SetSplitImpulse (enable); } DllExport void PhysicsWorld_SetMaxNetworkAngularVelocity (Urho3D::PhysicsWorld *_target, float velocity) { _target->SetMaxNetworkAngularVelocity (velocity); } DllExport void PhysicsWorld_RaycastSingle (Urho3D::PhysicsWorld *_target, Urho3D::PhysicsRaycastResult & result, const class Urho3D::Ray & ray, float maxDistance, unsigned int collisionMask) { _target->RaycastSingle (result, ray, maxDistance, collisionMask); } DllExport void PhysicsWorld_RaycastSingleSegmented (Urho3D::PhysicsWorld *_target, Urho3D::PhysicsRaycastResult & result, const class Urho3D::Ray & ray, float maxDistance, float segmentDistance, unsigned int collisionMask) { _target->RaycastSingleSegmented (result, ray, maxDistance, segmentDistance, collisionMask); } DllExport void PhysicsWorld_SphereCast (Urho3D::PhysicsWorld *_target, Urho3D::PhysicsRaycastResult & result, const class Urho3D::Ray & ray, float radius, float maxDistance, unsigned int collisionMask) { _target->SphereCast (result, ray, radius, maxDistance, collisionMask); } DllExport void PhysicsWorld_ConvexCast (Urho3D::PhysicsWorld *_target, Urho3D::PhysicsRaycastResult & result, Urho3D::CollisionShape * shape, const class Urho3D::Vector3 & startPos, const class Urho3D::Quaternion & startRot, const class Urho3D::Vector3 & endPos, const class Urho3D::Quaternion & endRot, unsigned int collisionMask) { _target->ConvexCast (result, shape, startPos, startRot, endPos, endRot, collisionMask); } DllExport void PhysicsWorld_RemoveCachedGeometry (Urho3D::PhysicsWorld *_target, Urho3D::Model * model) { _target->RemoveCachedGeometry (model); } DllExport Interop::Vector3 PhysicsWorld_GetGravity (Urho3D::PhysicsWorld *_target) { return *((Interop::Vector3 *) &(_target->GetGravity ())); } DllExport int PhysicsWorld_GetMaxSubSteps (Urho3D::PhysicsWorld *_target) { return _target->GetMaxSubSteps (); } DllExport int PhysicsWorld_GetNumIterations (Urho3D::PhysicsWorld *_target) { return _target->GetNumIterations (); } DllExport int PhysicsWorld_IsUpdateEnabled (Urho3D::PhysicsWorld *_target) { return _target->IsUpdateEnabled (); } DllExport int PhysicsWorld_GetInterpolation (Urho3D::PhysicsWorld *_target) { return _target->GetInterpolation (); } DllExport int PhysicsWorld_GetInternalEdge (Urho3D::PhysicsWorld *_target) { return _target->GetInternalEdge (); } DllExport int PhysicsWorld_GetSplitImpulse (Urho3D::PhysicsWorld *_target) { return _target->GetSplitImpulse (); } DllExport int PhysicsWorld_GetFps (Urho3D::PhysicsWorld *_target) { return _target->GetFps (); } DllExport float PhysicsWorld_GetMaxNetworkAngularVelocity (Urho3D::PhysicsWorld *_target) { return _target->GetMaxNetworkAngularVelocity (); } DllExport void PhysicsWorld_AddRigidBody (Urho3D::PhysicsWorld *_target, Urho3D::RigidBody * body) { _target->AddRigidBody (body); } DllExport void PhysicsWorld_RemoveRigidBody (Urho3D::PhysicsWorld *_target, Urho3D::RigidBody * body) { _target->RemoveRigidBody (body); } DllExport void PhysicsWorld_AddCollisionShape (Urho3D::PhysicsWorld *_target, Urho3D::CollisionShape * shape) { _target->AddCollisionShape (shape); } DllExport void PhysicsWorld_RemoveCollisionShape (Urho3D::PhysicsWorld *_target, Urho3D::CollisionShape * shape) { _target->RemoveCollisionShape (shape); } DllExport void PhysicsWorld_AddConstraint (Urho3D::PhysicsWorld *_target, Urho3D::Constraint * joint) { _target->AddConstraint (joint); } DllExport void PhysicsWorld_RemoveConstraint (Urho3D::PhysicsWorld *_target, Urho3D::Constraint * joint) { _target->RemoveConstraint (joint); } DllExport void PhysicsWorld_DrawDebugGeometry0 (Urho3D::PhysicsWorld *_target, bool depthTest) { _target->DrawDebugGeometry (depthTest); } DllExport void PhysicsWorld_SetDebugRenderer (Urho3D::PhysicsWorld *_target, Urho3D::DebugRenderer * debug) { _target->SetDebugRenderer (debug); } DllExport void PhysicsWorld_SetDebugDepthTest (Urho3D::PhysicsWorld *_target, bool enable) { _target->SetDebugDepthTest (enable); } DllExport void PhysicsWorld_CleanupGeometryCache (Urho3D::PhysicsWorld *_target) { _target->CleanupGeometryCache (); } DllExport void PhysicsWorld_SetApplyingTransforms (Urho3D::PhysicsWorld *_target, bool enable) { _target->SetApplyingTransforms (enable); } DllExport int PhysicsWorld_IsApplyingTransforms (Urho3D::PhysicsWorld *_target) { return _target->IsApplyingTransforms (); } DllExport int PhysicsWorld_IsSimulating (Urho3D::PhysicsWorld *_target) { return _target->IsSimulating (); } DllExport int RigidBody_GetType (Urho3D::RigidBody *_target) { return (_target->GetType ()).Value (); } DllExport const char * RigidBody_GetTypeName (Urho3D::RigidBody *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int RigidBody_GetTypeStatic () { return (RigidBody::GetTypeStatic ()).Value (); } DllExport const char * RigidBody_GetTypeNameStatic () { return stringdup((RigidBody::GetTypeNameStatic ()).CString ()); } DllExport void * RigidBody_RigidBody (Urho3D::Context * context) { return WeakPtr<RigidBody>(new RigidBody(context)); } DllExport void RigidBody_RegisterObject (Urho3D::Context * context) { RigidBody::RegisterObject (context); } DllExport void RigidBody_ApplyAttributes (Urho3D::RigidBody *_target) { _target->ApplyAttributes (); } DllExport void RigidBody_OnSetEnabled (Urho3D::RigidBody *_target) { _target->OnSetEnabled (); } DllExport void RigidBody_DrawDebugGeometry (Urho3D::RigidBody *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void RigidBody_SetMass (Urho3D::RigidBody *_target, float mass) { _target->SetMass (mass); } DllExport void RigidBody_SetPosition (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & position) { _target->SetPosition (position); } DllExport void RigidBody_SetRotation (Urho3D::RigidBody *_target, const class Urho3D::Quaternion & rotation) { _target->SetRotation (rotation); } DllExport void RigidBody_SetTransform (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation) { _target->SetTransform (position, rotation); } DllExport void RigidBody_SetLinearVelocity (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & velocity) { _target->SetLinearVelocity (velocity); } DllExport void RigidBody_SetLinearFactor (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & factor) { _target->SetLinearFactor (factor); } DllExport void RigidBody_SetLinearRestThreshold (Urho3D::RigidBody *_target, float threshold) { _target->SetLinearRestThreshold (threshold); } DllExport void RigidBody_SetLinearDamping (Urho3D::RigidBody *_target, float damping) { _target->SetLinearDamping (damping); } DllExport void RigidBody_SetAngularVelocity (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & angularVelocity) { _target->SetAngularVelocity (angularVelocity); } DllExport void RigidBody_SetAngularFactor (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & factor) { _target->SetAngularFactor (factor); } DllExport void RigidBody_SetAngularRestThreshold (Urho3D::RigidBody *_target, float threshold) { _target->SetAngularRestThreshold (threshold); } DllExport void RigidBody_SetAngularDamping (Urho3D::RigidBody *_target, float factor) { _target->SetAngularDamping (factor); } DllExport void RigidBody_SetFriction (Urho3D::RigidBody *_target, float friction) { _target->SetFriction (friction); } DllExport void RigidBody_SetAnisotropicFriction (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & friction) { _target->SetAnisotropicFriction (friction); } DllExport void RigidBody_SetRollingFriction (Urho3D::RigidBody *_target, float friction) { _target->SetRollingFriction (friction); } DllExport void RigidBody_SetRestitution (Urho3D::RigidBody *_target, float restitution) { _target->SetRestitution (restitution); } DllExport void RigidBody_SetContactProcessingThreshold (Urho3D::RigidBody *_target, float threshold) { _target->SetContactProcessingThreshold (threshold); } DllExport void RigidBody_SetCcdRadius (Urho3D::RigidBody *_target, float radius) { _target->SetCcdRadius (radius); } DllExport void RigidBody_SetCcdMotionThreshold (Urho3D::RigidBody *_target, float threshold) { _target->SetCcdMotionThreshold (threshold); } DllExport void RigidBody_SetUseGravity (Urho3D::RigidBody *_target, bool enable) { _target->SetUseGravity (enable); } DllExport void RigidBody_SetGravityOverride (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & gravity) { _target->SetGravityOverride (gravity); } DllExport void RigidBody_SetKinematic (Urho3D::RigidBody *_target, bool enable) { _target->SetKinematic (enable); } DllExport void RigidBody_SetTrigger (Urho3D::RigidBody *_target, bool enable) { _target->SetTrigger (enable); } DllExport void RigidBody_SetCollisionLayer (Urho3D::RigidBody *_target, unsigned int layer) { _target->SetCollisionLayer (layer); } DllExport void RigidBody_SetCollisionMask (Urho3D::RigidBody *_target, unsigned int mask) { _target->SetCollisionMask (mask); } DllExport void RigidBody_SetCollisionLayerAndMask (Urho3D::RigidBody *_target, unsigned int layer, unsigned int mask) { _target->SetCollisionLayerAndMask (layer, mask); } DllExport void RigidBody_SetCollisionEventMode (Urho3D::RigidBody *_target, enum Urho3D::CollisionEventMode mode) { _target->SetCollisionEventMode (mode); } DllExport void RigidBody_ApplyForce (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & force) { _target->ApplyForce (force); } DllExport void RigidBody_ApplyForce0 (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & force, const class Urho3D::Vector3 & position) { _target->ApplyForce (force, position); } DllExport void RigidBody_ApplyTorque (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & torque) { _target->ApplyTorque (torque); } DllExport void RigidBody_ApplyImpulse (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & impulse) { _target->ApplyImpulse (impulse); } DllExport void RigidBody_ApplyImpulse1 (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & impulse, const class Urho3D::Vector3 & position) { _target->ApplyImpulse (impulse, position); } DllExport void RigidBody_ApplyTorqueImpulse (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & torque) { _target->ApplyTorqueImpulse (torque); } DllExport void RigidBody_ResetForces (Urho3D::RigidBody *_target) { _target->ResetForces (); } DllExport void RigidBody_Activate (Urho3D::RigidBody *_target) { _target->Activate (); } DllExport void RigidBody_ReAddBodyToWorld (Urho3D::RigidBody *_target) { _target->ReAddBodyToWorld (); } DllExport void RigidBody_DisableMassUpdate (Urho3D::RigidBody *_target) { _target->DisableMassUpdate (); } DllExport void RigidBody_EnableMassUpdate (Urho3D::RigidBody *_target) { _target->EnableMassUpdate (); } DllExport Urho3D::PhysicsWorld * RigidBody_GetPhysicsWorld (Urho3D::RigidBody *_target) { return _target->GetPhysicsWorld (); } DllExport float RigidBody_GetMass (Urho3D::RigidBody *_target) { return _target->GetMass (); } DllExport Interop::Vector3 RigidBody_GetPosition (Urho3D::RigidBody *_target) { return *((Interop::Vector3 *) &(_target->GetPosition ())); } DllExport Interop::Quaternion RigidBody_GetRotation (Urho3D::RigidBody *_target) { return *((Interop::Quaternion *) &(_target->GetRotation ())); } DllExport Interop::Vector3 RigidBody_GetLinearVelocity (Urho3D::RigidBody *_target) { return *((Interop::Vector3 *) &(_target->GetLinearVelocity ())); } DllExport Interop::Vector3 RigidBody_GetLinearFactor (Urho3D::RigidBody *_target) { return *((Interop::Vector3 *) &(_target->GetLinearFactor ())); } DllExport Interop::Vector3 RigidBody_GetVelocityAtPoint (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & position) { return *((Interop::Vector3 *) &(_target->GetVelocityAtPoint (position))); } DllExport float RigidBody_GetLinearRestThreshold (Urho3D::RigidBody *_target) { return _target->GetLinearRestThreshold (); } DllExport float RigidBody_GetLinearDamping (Urho3D::RigidBody *_target) { return _target->GetLinearDamping (); } DllExport Interop::Vector3 RigidBody_GetAngularVelocity (Urho3D::RigidBody *_target) { return *((Interop::Vector3 *) &(_target->GetAngularVelocity ())); } DllExport Interop::Vector3 RigidBody_GetAngularFactor (Urho3D::RigidBody *_target) { return *((Interop::Vector3 *) &(_target->GetAngularFactor ())); } DllExport float RigidBody_GetAngularRestThreshold (Urho3D::RigidBody *_target) { return _target->GetAngularRestThreshold (); } DllExport float RigidBody_GetAngularDamping (Urho3D::RigidBody *_target) { return _target->GetAngularDamping (); } DllExport float RigidBody_GetFriction (Urho3D::RigidBody *_target) { return _target->GetFriction (); } DllExport Interop::Vector3 RigidBody_GetAnisotropicFriction (Urho3D::RigidBody *_target) { return *((Interop::Vector3 *) &(_target->GetAnisotropicFriction ())); } DllExport float RigidBody_GetRollingFriction (Urho3D::RigidBody *_target) { return _target->GetRollingFriction (); } DllExport float RigidBody_GetRestitution (Urho3D::RigidBody *_target) { return _target->GetRestitution (); } DllExport float RigidBody_GetContactProcessingThreshold (Urho3D::RigidBody *_target) { return _target->GetContactProcessingThreshold (); } DllExport float RigidBody_GetCcdRadius (Urho3D::RigidBody *_target) { return _target->GetCcdRadius (); } DllExport float RigidBody_GetCcdMotionThreshold (Urho3D::RigidBody *_target) { return _target->GetCcdMotionThreshold (); } DllExport int RigidBody_GetUseGravity (Urho3D::RigidBody *_target) { return _target->GetUseGravity (); } DllExport Interop::Vector3 RigidBody_GetGravityOverride (Urho3D::RigidBody *_target) { return *((Interop::Vector3 *) &(_target->GetGravityOverride ())); } DllExport Interop::Vector3 RigidBody_GetCenterOfMass (Urho3D::RigidBody *_target) { return *((Interop::Vector3 *) &(_target->GetCenterOfMass ())); } DllExport int RigidBody_IsKinematic (Urho3D::RigidBody *_target) { return _target->IsKinematic (); } DllExport int RigidBody_IsTrigger (Urho3D::RigidBody *_target) { return _target->IsTrigger (); } DllExport int RigidBody_IsActive (Urho3D::RigidBody *_target) { return _target->IsActive (); } DllExport unsigned int RigidBody_GetCollisionLayer (Urho3D::RigidBody *_target) { return _target->GetCollisionLayer (); } DllExport unsigned int RigidBody_GetCollisionMask (Urho3D::RigidBody *_target) { return _target->GetCollisionMask (); } DllExport enum Urho3D::CollisionEventMode RigidBody_GetCollisionEventMode (Urho3D::RigidBody *_target) { return _target->GetCollisionEventMode (); } DllExport void RigidBody_ApplyWorldTransform (Urho3D::RigidBody *_target, const class Urho3D::Vector3 & newWorldPosition, const class Urho3D::Quaternion & newWorldRotation) { _target->ApplyWorldTransform (newWorldPosition, newWorldRotation); } DllExport void RigidBody_UpdateMass (Urho3D::RigidBody *_target) { _target->UpdateMass (); } DllExport void RigidBody_UpdateGravity (Urho3D::RigidBody *_target) { _target->UpdateGravity (); } DllExport void RigidBody_AddConstraint (Urho3D::RigidBody *_target, Urho3D::Constraint * constraint) { _target->AddConstraint (constraint); } DllExport void RigidBody_RemoveConstraint (Urho3D::RigidBody *_target, Urho3D::Constraint * constraint) { _target->RemoveConstraint (constraint); } DllExport void RigidBody_ReleaseBody (Urho3D::RigidBody *_target) { _target->ReleaseBody (); } DllExport int JsonFile_GetType (Urho3D::JSONFile *_target) { return (_target->GetType ()).Value (); } DllExport const char * JsonFile_GetTypeName (Urho3D::JSONFile *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int JsonFile_GetTypeStatic () { return (JSONFile::GetTypeStatic ()).Value (); } DllExport const char * JsonFile_GetTypeNameStatic () { return stringdup((JSONFile::GetTypeNameStatic ()).CString ()); } DllExport void * JsonFile_JSONFile (Urho3D::Context * context) { return WeakPtr<JSONFile>(new JSONFile(context)); } DllExport void JsonFile_RegisterObject (Urho3D::Context * context) { JSONFile::RegisterObject (context); } DllExport int JsonFile_BeginLoad_File (Urho3D::JSONFile *_target, File * source) { return _target->BeginLoad (*source); } DllExport int JsonFile_BeginLoad_MemoryBuffer (Urho3D::JSONFile *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int JsonFile_Save_File (Urho3D::JSONFile *_target, File * dest) { return _target->Save (*dest); } DllExport int JsonFile_Save_MemoryBuffer (Urho3D::JSONFile *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int JsonFile_Save0_File (Urho3D::JSONFile *_target, File * dest, const char * indendation) { return _target->Save (*dest, Urho3D::String(indendation)); } DllExport int JsonFile_Save0_MemoryBuffer (Urho3D::JSONFile *_target, MemoryBuffer * dest, const char * indendation) { return _target->Save (*dest, Urho3D::String(indendation)); } DllExport int JsonFile_FromString (Urho3D::JSONFile *_target, const char * source) { return _target->FromString (Urho3D::String(source)); } DllExport int PListFile_GetType (Urho3D::PListFile *_target) { return (_target->GetType ()).Value (); } DllExport const char * PListFile_GetTypeName (Urho3D::PListFile *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int PListFile_GetTypeStatic () { return (PListFile::GetTypeStatic ()).Value (); } DllExport const char * PListFile_GetTypeNameStatic () { return stringdup((PListFile::GetTypeNameStatic ()).CString ()); } DllExport void * PListFile_PListFile (Urho3D::Context * context) { return WeakPtr<PListFile>(new PListFile(context)); } DllExport void PListFile_RegisterObject (Urho3D::Context * context) { PListFile::RegisterObject (context); } DllExport int PListFile_BeginLoad_File (Urho3D::PListFile *_target, File * source) { return _target->BeginLoad (*source); } DllExport int PListFile_BeginLoad_MemoryBuffer (Urho3D::PListFile *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Localization_GetType (Urho3D::Localization *_target) { return (_target->GetType ()).Value (); } DllExport const char * Localization_GetTypeName (Urho3D::Localization *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Localization_GetTypeStatic () { return (Localization::GetTypeStatic ()).Value (); } DllExport const char * Localization_GetTypeNameStatic () { return stringdup((Localization::GetTypeNameStatic ()).CString ()); } DllExport void * Localization_Localization (Urho3D::Context * context) { return WeakPtr<Localization>(new Localization(context)); } DllExport int Localization_GetNumLanguages (Urho3D::Localization *_target) { return _target->GetNumLanguages (); } DllExport int Localization_GetLanguageIndex (Urho3D::Localization *_target) { return _target->GetLanguageIndex (); } DllExport int Localization_GetLanguageIndex0 (Urho3D::Localization *_target, const char * language) { return _target->GetLanguageIndex (Urho3D::String(language)); } DllExport const char * Localization_GetLanguage (Urho3D::Localization *_target) { return stringdup((_target->GetLanguage ()).CString ()); } DllExport const char * Localization_GetLanguage1 (Urho3D::Localization *_target, int index) { return stringdup((_target->GetLanguage (index)).CString ()); } DllExport void Localization_SetLanguage (Urho3D::Localization *_target, int index) { _target->SetLanguage (index); } DllExport void Localization_SetLanguage2 (Urho3D::Localization *_target, const char * language) { _target->SetLanguage (Urho3D::String(language)); } DllExport const char * Localization_Get (Urho3D::Localization *_target, const char * id) { return stringdup((_target->Get (Urho3D::String(id))).CString ()); } DllExport void Localization_Reset (Urho3D::Localization *_target) { _target->Reset (); } DllExport void Localization_LoadJSONFile (Urho3D::Localization *_target, const char * name) { _target->LoadJSONFile (Urho3D::String(name)); } DllExport int ResourceCache_GetType (Urho3D::ResourceCache *_target) { return (_target->GetType ()).Value (); } DllExport const char * ResourceCache_GetTypeName (Urho3D::ResourceCache *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ResourceCache_GetTypeStatic () { return (ResourceCache::GetTypeStatic ()).Value (); } DllExport const char * ResourceCache_GetTypeNameStatic () { return stringdup((ResourceCache::GetTypeNameStatic ()).CString ()); } DllExport void * ResourceCache_ResourceCache (Urho3D::Context * context) { return WeakPtr<ResourceCache>(new ResourceCache(context)); } DllExport int ResourceCache_AddResourceDir (Urho3D::ResourceCache *_target, const char * pathName, unsigned int priority) { return _target->AddResourceDir (Urho3D::String(pathName), priority); } DllExport int ResourceCache_AddPackageFile (Urho3D::ResourceCache *_target, Urho3D::PackageFile * package, unsigned int priority) { return _target->AddPackageFile (package, priority); } DllExport int ResourceCache_AddPackageFile0 (Urho3D::ResourceCache *_target, const char * fileName, unsigned int priority) { return _target->AddPackageFile (Urho3D::String(fileName), priority); } DllExport int ResourceCache_AddManualResource (Urho3D::ResourceCache *_target, Urho3D::Resource * resource) { return _target->AddManualResource (resource); } DllExport void ResourceCache_RemoveResourceDir (Urho3D::ResourceCache *_target, const char * pathName) { _target->RemoveResourceDir (Urho3D::String(pathName)); } DllExport void ResourceCache_RemovePackageFile (Urho3D::ResourceCache *_target, Urho3D::PackageFile * package, bool releaseResources, bool forceRelease) { _target->RemovePackageFile (package, releaseResources, forceRelease); } DllExport void ResourceCache_RemovePackageFile1 (Urho3D::ResourceCache *_target, const char * fileName, bool releaseResources, bool forceRelease) { _target->RemovePackageFile (Urho3D::String(fileName), releaseResources, forceRelease); } DllExport void ResourceCache_ReleaseResource (Urho3D::ResourceCache *_target, int type, const char * name, bool force) { _target->ReleaseResource (Urho3D::StringHash(type), Urho3D::String(name), force); } DllExport void ResourceCache_ReleaseResources (Urho3D::ResourceCache *_target, int type, bool force) { _target->ReleaseResources (Urho3D::StringHash(type), force); } DllExport void ResourceCache_ReleaseResources2 (Urho3D::ResourceCache *_target, int type, const char * partialName, bool force) { _target->ReleaseResources (Urho3D::StringHash(type), Urho3D::String(partialName), force); } DllExport void ResourceCache_ReleaseResources3 (Urho3D::ResourceCache *_target, const char * partialName, bool force) { _target->ReleaseResources (Urho3D::String(partialName), force); } DllExport void ResourceCache_ReleaseAllResources (Urho3D::ResourceCache *_target, bool force) { _target->ReleaseAllResources (force); } DllExport int ResourceCache_ReloadResource (Urho3D::ResourceCache *_target, Urho3D::Resource * resource) { return _target->ReloadResource (resource); } DllExport void ResourceCache_ReloadResourceWithDependencies (Urho3D::ResourceCache *_target, const char * fileName) { _target->ReloadResourceWithDependencies (Urho3D::String(fileName)); } DllExport void ResourceCache_SetMemoryBudget (Urho3D::ResourceCache *_target, int type, unsigned long long budget) { _target->SetMemoryBudget (Urho3D::StringHash(type), budget); } DllExport void ResourceCache_SetAutoReloadResources (Urho3D::ResourceCache *_target, bool enable) { _target->SetAutoReloadResources (enable); } DllExport void ResourceCache_SetReturnFailedResources (Urho3D::ResourceCache *_target, bool enable) { _target->SetReturnFailedResources (enable); } DllExport void ResourceCache_SetSearchPackagesFirst (Urho3D::ResourceCache *_target, bool value) { _target->SetSearchPackagesFirst (value); } DllExport void ResourceCache_SetFinishBackgroundResourcesMs (Urho3D::ResourceCache *_target, int ms) { _target->SetFinishBackgroundResourcesMs (ms); } DllExport void ResourceCache_AddResourceRouter (Urho3D::ResourceCache *_target, Urho3D::ResourceRouter * router, bool addAsFirst) { _target->AddResourceRouter (router, addAsFirst); } DllExport void ResourceCache_RemoveResourceRouter (Urho3D::ResourceCache *_target, Urho3D::ResourceRouter * router) { _target->RemoveResourceRouter (router); } DllExport Urho3D::File * ResourceCache_GetFile (Urho3D::ResourceCache *_target, const char * name, bool sendEventOnFailure) { auto copy = _target->GetFile (Urho3D::String(name), sendEventOnFailure); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::Resource * ResourceCache_GetResource (Urho3D::ResourceCache *_target, int type, const char * name, bool sendEventOnFailure) { return _target->GetResource (Urho3D::StringHash(type), Urho3D::String(name), sendEventOnFailure); } DllExport Urho3D::Resource * ResourceCache_GetTempResource (Urho3D::ResourceCache *_target, int type, const char * name, bool sendEventOnFailure) { auto copy = _target->GetTempResource (Urho3D::StringHash(type), Urho3D::String(name), sendEventOnFailure); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport int ResourceCache_BackgroundLoadResource (Urho3D::ResourceCache *_target, int type, const char * name, bool sendEventOnFailure, Urho3D::Resource * caller) { return _target->BackgroundLoadResource (Urho3D::StringHash(type), Urho3D::String(name), sendEventOnFailure, caller); } DllExport unsigned int ResourceCache_GetNumBackgroundLoadResources (Urho3D::ResourceCache *_target) { return _target->GetNumBackgroundLoadResources (); } DllExport Urho3D::Resource * ResourceCache_GetExistingResource (Urho3D::ResourceCache *_target, int type, const char * name) { return _target->GetExistingResource (Urho3D::StringHash(type), Urho3D::String(name)); } DllExport const Vector<SharedPtr<class Urho3D::PackageFile> > & ResourceCache_GetPackageFiles (Urho3D::ResourceCache *_target) { return _target->GetPackageFiles (); } DllExport int ResourceCache_Exists (Urho3D::ResourceCache *_target, const char * name) { return _target->Exists (Urho3D::String(name)); } DllExport unsigned long long ResourceCache_GetMemoryBudget (Urho3D::ResourceCache *_target, int type) { return _target->GetMemoryBudget (Urho3D::StringHash(type)); } DllExport unsigned long long ResourceCache_GetMemoryUse (Urho3D::ResourceCache *_target, int type) { return _target->GetMemoryUse (Urho3D::StringHash(type)); } DllExport unsigned long long ResourceCache_GetTotalMemoryUse (Urho3D::ResourceCache *_target) { return _target->GetTotalMemoryUse (); } DllExport const char * ResourceCache_GetResourceFileName (Urho3D::ResourceCache *_target, const char * name) { return stringdup((_target->GetResourceFileName (Urho3D::String(name))).CString ()); } DllExport int ResourceCache_GetAutoReloadResources (Urho3D::ResourceCache *_target) { return _target->GetAutoReloadResources (); } DllExport int ResourceCache_GetReturnFailedResources (Urho3D::ResourceCache *_target) { return _target->GetReturnFailedResources (); } DllExport int ResourceCache_GetSearchPackagesFirst (Urho3D::ResourceCache *_target) { return _target->GetSearchPackagesFirst (); } DllExport int ResourceCache_GetFinishBackgroundResourcesMs (Urho3D::ResourceCache *_target) { return _target->GetFinishBackgroundResourcesMs (); } DllExport Urho3D::ResourceRouter * ResourceCache_GetResourceRouter (Urho3D::ResourceCache *_target, unsigned int index) { return _target->GetResourceRouter (index); } DllExport const char * ResourceCache_GetPreferredResourceDir (Urho3D::ResourceCache *_target, const char * path) { return stringdup((_target->GetPreferredResourceDir (Urho3D::String(path))).CString ()); } DllExport const char * ResourceCache_SanitateResourceName (Urho3D::ResourceCache *_target, const char * name) { return stringdup((_target->SanitateResourceName (Urho3D::String(name))).CString ()); } DllExport const char * ResourceCache_SanitateResourceDirName (Urho3D::ResourceCache *_target, const char * name) { return stringdup((_target->SanitateResourceDirName (Urho3D::String(name))).CString ()); } DllExport void ResourceCache_StoreResourceDependency (Urho3D::ResourceCache *_target, Urho3D::Resource * resource, const char * dependency) { _target->StoreResourceDependency (resource, Urho3D::String(dependency)); } DllExport void ResourceCache_ResetDependencies (Urho3D::ResourceCache *_target, Urho3D::Resource * resource) { _target->ResetDependencies (resource); } DllExport const char * ResourceCache_PrintMemoryUsage (Urho3D::ResourceCache *_target) { return stringdup((_target->PrintMemoryUsage ()).CString ()); } DllExport int LogicComponent_GetType (Urho3D::LogicComponent *_target) { return (_target->GetType ()).Value (); } DllExport const char * LogicComponent_GetTypeName (Urho3D::LogicComponent *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int LogicComponent_GetTypeStatic () { return (LogicComponent::GetTypeStatic ()).Value (); } DllExport const char * LogicComponent_GetTypeNameStatic () { return stringdup((LogicComponent::GetTypeNameStatic ()).CString ()); } DllExport void * LogicComponent_LogicComponent (Urho3D::Context * context) { return WeakPtr<LogicComponent>(new LogicComponent(context)); } DllExport void LogicComponent_OnSetEnabled (Urho3D::LogicComponent *_target) { _target->OnSetEnabled (); } DllExport void LogicComponent_Start (Urho3D::LogicComponent *_target) { _target->Start (); } DllExport void LogicComponent_DelayedStart (Urho3D::LogicComponent *_target) { _target->DelayedStart (); } DllExport void LogicComponent_Stop (Urho3D::LogicComponent *_target) { _target->Stop (); } DllExport void LogicComponent_Update (Urho3D::LogicComponent *_target, float timeStep) { _target->Update (timeStep); } DllExport void LogicComponent_PostUpdate (Urho3D::LogicComponent *_target, float timeStep) { _target->PostUpdate (timeStep); } DllExport void LogicComponent_FixedUpdate (Urho3D::LogicComponent *_target, float timeStep) { _target->FixedUpdate (timeStep); } DllExport void LogicComponent_FixedPostUpdate (Urho3D::LogicComponent *_target, float timeStep) { _target->FixedPostUpdate (timeStep); } DllExport void LogicComponent_SetUpdateEventMask (Urho3D::LogicComponent *_target, unsigned char mask) { _target->SetUpdateEventMask (mask); } DllExport unsigned char LogicComponent_GetUpdateEventMask (Urho3D::LogicComponent *_target) { return _target->GetUpdateEventMask (); } DllExport int LogicComponent_IsDelayedStartCalled (Urho3D::LogicComponent *_target) { return _target->IsDelayedStartCalled (); } DllExport int ObjectAnimation_GetType (Urho3D::ObjectAnimation *_target) { return (_target->GetType ()).Value (); } DllExport const char * ObjectAnimation_GetTypeName (Urho3D::ObjectAnimation *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ObjectAnimation_GetTypeStatic () { return (ObjectAnimation::GetTypeStatic ()).Value (); } DllExport const char * ObjectAnimation_GetTypeNameStatic () { return stringdup((ObjectAnimation::GetTypeNameStatic ()).CString ()); } DllExport void * ObjectAnimation_ObjectAnimation (Urho3D::Context * context) { return WeakPtr<ObjectAnimation>(new ObjectAnimation(context)); } DllExport void ObjectAnimation_RegisterObject (Urho3D::Context * context) { ObjectAnimation::RegisterObject (context); } DllExport int ObjectAnimation_BeginLoad_File (Urho3D::ObjectAnimation *_target, File * source) { return _target->BeginLoad (*source); } DllExport int ObjectAnimation_BeginLoad_MemoryBuffer (Urho3D::ObjectAnimation *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int ObjectAnimation_Save_File (Urho3D::ObjectAnimation *_target, File * dest) { return _target->Save (*dest); } DllExport int ObjectAnimation_Save_MemoryBuffer (Urho3D::ObjectAnimation *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int ObjectAnimation_LoadXML (Urho3D::ObjectAnimation *_target, const class Urho3D::XMLElement & source) { return _target->LoadXML (source); } DllExport int ObjectAnimation_SaveXML (Urho3D::ObjectAnimation *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void ObjectAnimation_AddAttributeAnimation (Urho3D::ObjectAnimation *_target, const char * name, Urho3D::ValueAnimation * attributeAnimation, enum Urho3D::WrapMode wrapMode, float speed) { _target->AddAttributeAnimation (Urho3D::String(name), attributeAnimation, wrapMode, speed); } DllExport void ObjectAnimation_RemoveAttributeAnimation (Urho3D::ObjectAnimation *_target, const char * name) { _target->RemoveAttributeAnimation (Urho3D::String(name)); } DllExport void ObjectAnimation_RemoveAttributeAnimation0 (Urho3D::ObjectAnimation *_target, Urho3D::ValueAnimation * attributeAnimation) { _target->RemoveAttributeAnimation (attributeAnimation); } DllExport Urho3D::ValueAnimation * ObjectAnimation_GetAttributeAnimation (Urho3D::ObjectAnimation *_target, const char * name) { return _target->GetAttributeAnimation (Urho3D::String(name)); } DllExport enum Urho3D::WrapMode ObjectAnimation_GetAttributeAnimationWrapMode (Urho3D::ObjectAnimation *_target, const char * name) { return _target->GetAttributeAnimationWrapMode (Urho3D::String(name)); } DllExport float ObjectAnimation_GetAttributeAnimationSpeed (Urho3D::ObjectAnimation *_target, const char * name) { return _target->GetAttributeAnimationSpeed (Urho3D::String(name)); } DllExport Urho3D::ValueAnimationInfo * ObjectAnimation_GetAttributeAnimationInfo (Urho3D::ObjectAnimation *_target, const char * name) { return _target->GetAttributeAnimationInfo (Urho3D::String(name)); } DllExport void * SceneResolver_SceneResolver () { return new SceneResolver(); } DllExport void SceneResolver_Reset (Urho3D::SceneResolver *_target) { _target->Reset (); } DllExport void SceneResolver_AddNode (Urho3D::SceneResolver *_target, unsigned int oldID, Urho3D::Node * node) { _target->AddNode (oldID, node); } DllExport void SceneResolver_AddComponent (Urho3D::SceneResolver *_target, unsigned int oldID, Urho3D::Component * component) { _target->AddComponent (oldID, component); } DllExport void SceneResolver_Resolve (Urho3D::SceneResolver *_target) { _target->Resolve (); } DllExport int Scene_GetType (Urho3D::Scene *_target) { return (_target->GetType ()).Value (); } DllExport const char * Scene_GetTypeName (Urho3D::Scene *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Scene_GetTypeStatic () { return (Scene::GetTypeStatic ()).Value (); } DllExport const char * Scene_GetTypeNameStatic () { return stringdup((Scene::GetTypeNameStatic ()).CString ()); } DllExport void * Scene_Scene (Urho3D::Context * context) { return WeakPtr<Scene>(new Scene(context)); } DllExport void Scene_RegisterObject (Urho3D::Context * context) { Scene::RegisterObject (context); } DllExport int Scene_Load_File (Urho3D::Scene *_target, File * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int Scene_Load_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int Scene_Save_File (Urho3D::Scene *_target, File * dest) { return _target->Save (*dest); } DllExport int Scene_Save_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int Scene_LoadXML (Urho3D::Scene *_target, const class Urho3D::XMLElement & source, bool setInstanceDefault) { return _target->LoadXML (source, setInstanceDefault); } DllExport void Scene_MarkNetworkUpdate (Urho3D::Scene *_target) { _target->MarkNetworkUpdate (); } DllExport void Scene_AddReplicationState (Urho3D::Scene *_target, Urho3D::NodeReplicationState * state) { _target->AddReplicationState (state); } DllExport int Scene_LoadXML0_File (Urho3D::Scene *_target, File * source) { return _target->LoadXML (*source); } DllExport int Scene_LoadXML0_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * source) { return _target->LoadXML (*source); } DllExport int Scene_LoadJSON_File (Urho3D::Scene *_target, File * source) { return _target->LoadJSON (*source); } DllExport int Scene_LoadJSON_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * source) { return _target->LoadJSON (*source); } DllExport int Scene_SaveXML_File (Urho3D::Scene *_target, File * dest, const char * indentation) { return _target->SaveXML (*dest, Urho3D::String(indentation)); } DllExport int Scene_SaveXML_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * dest, const char * indentation) { return _target->SaveXML (*dest, Urho3D::String(indentation)); } DllExport int Scene_SaveJSON_File (Urho3D::Scene *_target, File * dest, const char * indentation) { return _target->SaveJSON (*dest, Urho3D::String(indentation)); } DllExport int Scene_SaveJSON_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * dest, const char * indentation) { return _target->SaveJSON (*dest, Urho3D::String(indentation)); } DllExport int Scene_LoadAsync (Urho3D::Scene *_target, Urho3D::File * file, enum Urho3D::LoadMode mode) { return _target->LoadAsync (file, mode); } DllExport int Scene_LoadAsyncXML (Urho3D::Scene *_target, Urho3D::File * file, enum Urho3D::LoadMode mode) { return _target->LoadAsyncXML (file, mode); } DllExport int Scene_LoadAsyncJSON (Urho3D::Scene *_target, Urho3D::File * file, enum Urho3D::LoadMode mode) { return _target->LoadAsyncJSON (file, mode); } DllExport void Scene_StopAsyncLoading (Urho3D::Scene *_target) { _target->StopAsyncLoading (); } DllExport Urho3D::Node * Scene_Instantiate_File (Urho3D::Scene *_target, File * source, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, enum Urho3D::CreateMode mode) { return _target->Instantiate (*source, position, rotation, mode); } DllExport Urho3D::Node * Scene_Instantiate_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * source, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, enum Urho3D::CreateMode mode) { return _target->Instantiate (*source, position, rotation, mode); } DllExport Urho3D::Node * Scene_InstantiateXML (Urho3D::Scene *_target, const class Urho3D::XMLElement & source, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, enum Urho3D::CreateMode mode) { return _target->InstantiateXML (source, position, rotation, mode); } DllExport Urho3D::Node * Scene_InstantiateXML1_File (Urho3D::Scene *_target, File * source, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, enum Urho3D::CreateMode mode) { return _target->InstantiateXML (*source, position, rotation, mode); } DllExport Urho3D::Node * Scene_InstantiateXML1_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * source, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, enum Urho3D::CreateMode mode) { return _target->InstantiateXML (*source, position, rotation, mode); } DllExport Urho3D::Node * Scene_InstantiateJSON_File (Urho3D::Scene *_target, File * source, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, enum Urho3D::CreateMode mode) { return _target->InstantiateJSON (*source, position, rotation, mode); } DllExport Urho3D::Node * Scene_InstantiateJSON_MemoryBuffer (Urho3D::Scene *_target, MemoryBuffer * source, const class Urho3D::Vector3 & position, const class Urho3D::Quaternion & rotation, enum Urho3D::CreateMode mode) { return _target->InstantiateJSON (*source, position, rotation, mode); } DllExport void Scene_Clear (Urho3D::Scene *_target, bool clearReplicated, bool clearLocal) { _target->Clear (clearReplicated, clearLocal); } DllExport void Scene_SetUpdateEnabled (Urho3D::Scene *_target, bool enable) { _target->SetUpdateEnabled (enable); } DllExport void Scene_SetTimeScale (Urho3D::Scene *_target, float scale) { _target->SetTimeScale (scale); } DllExport void Scene_SetElapsedTime (Urho3D::Scene *_target, float time) { _target->SetElapsedTime (time); } DllExport void Scene_SetSmoothingConstant (Urho3D::Scene *_target, float constant) { _target->SetSmoothingConstant (constant); } DllExport void Scene_SetSnapThreshold (Urho3D::Scene *_target, float threshold) { _target->SetSnapThreshold (threshold); } DllExport void Scene_SetAsyncLoadingMs (Urho3D::Scene *_target, int ms) { _target->SetAsyncLoadingMs (ms); } DllExport void Scene_AddRequiredPackageFile (Urho3D::Scene *_target, Urho3D::PackageFile * package) { _target->AddRequiredPackageFile (package); } DllExport void Scene_ClearRequiredPackageFiles (Urho3D::Scene *_target) { _target->ClearRequiredPackageFiles (); } DllExport void Scene_RegisterVar (Urho3D::Scene *_target, const char * name) { _target->RegisterVar (Urho3D::String(name)); } DllExport void Scene_UnregisterVar (Urho3D::Scene *_target, const char * name) { _target->UnregisterVar (Urho3D::String(name)); } DllExport void Scene_UnregisterAllVars (Urho3D::Scene *_target) { _target->UnregisterAllVars (); } DllExport Urho3D::Node * Scene_GetNode (Urho3D::Scene *_target, unsigned int id) { return _target->GetNode (id); } DllExport Urho3D::Component * Scene_GetComponent (Urho3D::Scene *_target, unsigned int id) { return _target->GetComponent (id); } DllExport int Scene_IsUpdateEnabled (Urho3D::Scene *_target) { return _target->IsUpdateEnabled (); } DllExport int Scene_IsAsyncLoading (Urho3D::Scene *_target) { return _target->IsAsyncLoading (); } DllExport float Scene_GetAsyncProgress (Urho3D::Scene *_target) { return _target->GetAsyncProgress (); } DllExport enum Urho3D::LoadMode Scene_GetAsyncLoadMode (Urho3D::Scene *_target) { return _target->GetAsyncLoadMode (); } DllExport const char * Scene_GetFileName (Urho3D::Scene *_target) { return stringdup((_target->GetFileName ()).CString ()); } DllExport unsigned int Scene_GetChecksum (Urho3D::Scene *_target) { return _target->GetChecksum (); } DllExport float Scene_GetTimeScale (Urho3D::Scene *_target) { return _target->GetTimeScale (); } DllExport float Scene_GetElapsedTime (Urho3D::Scene *_target) { return _target->GetElapsedTime (); } DllExport float Scene_GetSmoothingConstant (Urho3D::Scene *_target) { return _target->GetSmoothingConstant (); } DllExport float Scene_GetSnapThreshold (Urho3D::Scene *_target) { return _target->GetSnapThreshold (); } DllExport int Scene_GetAsyncLoadingMs (Urho3D::Scene *_target) { return _target->GetAsyncLoadingMs (); } DllExport const Vector<SharedPtr<class Urho3D::PackageFile> > & Scene_GetRequiredPackageFiles (Urho3D::Scene *_target) { return _target->GetRequiredPackageFiles (); } DllExport const char * Scene_GetVarName (Urho3D::Scene *_target, int hash) { return stringdup((_target->GetVarName (Urho3D::StringHash(hash))).CString ()); } DllExport void Scene_Update (Urho3D::Scene *_target, float timeStep) { _target->Update (timeStep); } DllExport void Scene_BeginThreadedUpdate (Urho3D::Scene *_target) { _target->BeginThreadedUpdate (); } DllExport void Scene_EndThreadedUpdate (Urho3D::Scene *_target) { _target->EndThreadedUpdate (); } DllExport void Scene_DelayedMarkedDirty (Urho3D::Scene *_target, Urho3D::Component * component) { _target->DelayedMarkedDirty (component); } DllExport int Scene_IsThreadedUpdate (Urho3D::Scene *_target) { return _target->IsThreadedUpdate (); } DllExport unsigned int Scene_GetFreeNodeID (Urho3D::Scene *_target, enum Urho3D::CreateMode mode) { return _target->GetFreeNodeID (mode); } DllExport unsigned int Scene_GetFreeComponentID (Urho3D::Scene *_target, enum Urho3D::CreateMode mode) { return _target->GetFreeComponentID (mode); } DllExport void Scene_NodeTagAdded (Urho3D::Scene *_target, Urho3D::Node * node, const char * tag) { _target->NodeTagAdded (node, Urho3D::String(tag)); } DllExport void Scene_NodeTagRemoved (Urho3D::Scene *_target, Urho3D::Node * node, const char * tag) { _target->NodeTagRemoved (node, Urho3D::String(tag)); } DllExport void Scene_SetVarNamesAttr (Urho3D::Scene *_target, const char * value) { _target->SetVarNamesAttr (Urho3D::String(value)); } DllExport const char * Scene_GetVarNamesAttr (Urho3D::Scene *_target) { return stringdup((_target->GetVarNamesAttr ()).CString ()); } DllExport void Scene_PrepareNetworkUpdate (Urho3D::Scene *_target) { _target->PrepareNetworkUpdate (); } DllExport void Scene_CleanupConnection (Urho3D::Scene *_target, Urho3D::Connection * connection) { _target->CleanupConnection (connection); } DllExport void Scene_MarkNetworkUpdate2 (Urho3D::Scene *_target, Urho3D::Node * node) { _target->MarkNetworkUpdate (node); } DllExport void Scene_MarkNetworkUpdate3 (Urho3D::Scene *_target, Urho3D::Component * component) { _target->MarkNetworkUpdate (component); } DllExport void Scene_MarkReplicationDirty (Urho3D::Scene *_target, Urho3D::Node * node) { _target->MarkReplicationDirty (node); } DllExport int SmoothedTransform_GetType (Urho3D::SmoothedTransform *_target) { return (_target->GetType ()).Value (); } DllExport const char * SmoothedTransform_GetTypeName (Urho3D::SmoothedTransform *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int SmoothedTransform_GetTypeStatic () { return (SmoothedTransform::GetTypeStatic ()).Value (); } DllExport const char * SmoothedTransform_GetTypeNameStatic () { return stringdup((SmoothedTransform::GetTypeNameStatic ()).CString ()); } DllExport void * SmoothedTransform_SmoothedTransform (Urho3D::Context * context) { return WeakPtr<SmoothedTransform>(new SmoothedTransform(context)); } DllExport void SmoothedTransform_RegisterObject (Urho3D::Context * context) { SmoothedTransform::RegisterObject (context); } DllExport void SmoothedTransform_Update (Urho3D::SmoothedTransform *_target, float constant, float squaredSnapThreshold) { _target->Update (constant, squaredSnapThreshold); } DllExport void SmoothedTransform_SetTargetPosition (Urho3D::SmoothedTransform *_target, const class Urho3D::Vector3 & position) { _target->SetTargetPosition (position); } DllExport void SmoothedTransform_SetTargetRotation (Urho3D::SmoothedTransform *_target, const class Urho3D::Quaternion & rotation) { _target->SetTargetRotation (rotation); } DllExport void SmoothedTransform_SetTargetWorldPosition (Urho3D::SmoothedTransform *_target, const class Urho3D::Vector3 & position) { _target->SetTargetWorldPosition (position); } DllExport void SmoothedTransform_SetTargetWorldRotation (Urho3D::SmoothedTransform *_target, const class Urho3D::Quaternion & rotation) { _target->SetTargetWorldRotation (rotation); } DllExport Interop::Vector3 SmoothedTransform_GetTargetPosition (Urho3D::SmoothedTransform *_target) { return *((Interop::Vector3 *) &(_target->GetTargetPosition ())); } DllExport Interop::Quaternion SmoothedTransform_GetTargetRotation (Urho3D::SmoothedTransform *_target) { return *((Interop::Quaternion *) &(_target->GetTargetRotation ())); } DllExport Interop::Vector3 SmoothedTransform_GetTargetWorldPosition (Urho3D::SmoothedTransform *_target) { return *((Interop::Vector3 *) &(_target->GetTargetWorldPosition ())); } DllExport Interop::Quaternion SmoothedTransform_GetTargetWorldRotation (Urho3D::SmoothedTransform *_target) { return *((Interop::Quaternion *) &(_target->GetTargetWorldRotation ())); } DllExport int SmoothedTransform_IsInProgress (Urho3D::SmoothedTransform *_target) { return _target->IsInProgress (); } DllExport int SplinePath_GetType (Urho3D::SplinePath *_target) { return (_target->GetType ()).Value (); } DllExport const char * SplinePath_GetTypeName (Urho3D::SplinePath *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int SplinePath_GetTypeStatic () { return (SplinePath::GetTypeStatic ()).Value (); } DllExport const char * SplinePath_GetTypeNameStatic () { return stringdup((SplinePath::GetTypeNameStatic ()).CString ()); } DllExport void * SplinePath_SplinePath (Urho3D::Context * context) { return WeakPtr<SplinePath>(new SplinePath(context)); } DllExport void SplinePath_RegisterObject (Urho3D::Context * context) { SplinePath::RegisterObject (context); } DllExport void SplinePath_ApplyAttributes (Urho3D::SplinePath *_target) { _target->ApplyAttributes (); } DllExport void SplinePath_DrawDebugGeometry (Urho3D::SplinePath *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void SplinePath_AddControlPoint (Urho3D::SplinePath *_target, Urho3D::Node * point, unsigned int index) { _target->AddControlPoint (point, index); } DllExport void SplinePath_RemoveControlPoint (Urho3D::SplinePath *_target, Urho3D::Node * point) { _target->RemoveControlPoint (point); } DllExport void SplinePath_ClearControlPoints (Urho3D::SplinePath *_target) { _target->ClearControlPoints (); } DllExport void SplinePath_SetInterpolationMode (Urho3D::SplinePath *_target, enum Urho3D::InterpolationMode interpolationMode) { _target->SetInterpolationMode (interpolationMode); } DllExport void SplinePath_SetSpeed (Urho3D::SplinePath *_target, float speed) { _target->SetSpeed (speed); } DllExport void SplinePath_SetPosition (Urho3D::SplinePath *_target, float factor) { _target->SetPosition (factor); } DllExport void SplinePath_SetControlledNode (Urho3D::SplinePath *_target, Urho3D::Node * controlled) { _target->SetControlledNode (controlled); } DllExport enum Urho3D::InterpolationMode SplinePath_GetInterpolationMode (Urho3D::SplinePath *_target) { return _target->GetInterpolationMode (); } DllExport float SplinePath_GetSpeed (Urho3D::SplinePath *_target) { return _target->GetSpeed (); } DllExport float SplinePath_GetLength (Urho3D::SplinePath *_target) { return _target->GetLength (); } DllExport Interop::Vector3 SplinePath_GetPosition (Urho3D::SplinePath *_target) { return *((Interop::Vector3 *) &(_target->GetPosition ())); } DllExport Urho3D::Node * SplinePath_GetControlledNode (Urho3D::SplinePath *_target) { return _target->GetControlledNode (); } DllExport Interop::Vector3 SplinePath_GetPoint (Urho3D::SplinePath *_target, float factor) { return *((Interop::Vector3 *) &(_target->GetPoint (factor))); } DllExport void SplinePath_Move (Urho3D::SplinePath *_target, float timeStep) { _target->Move (timeStep); } DllExport void SplinePath_Reset (Urho3D::SplinePath *_target) { _target->Reset (); } DllExport int SplinePath_IsFinished (Urho3D::SplinePath *_target) { return _target->IsFinished (); } DllExport void SplinePath_SetControlledIdAttr (Urho3D::SplinePath *_target, unsigned int value) { _target->SetControlledIdAttr (value); } DllExport unsigned int SplinePath_GetControlledIdAttr (Urho3D::SplinePath *_target) { return _target->GetControlledIdAttr (); } DllExport void * UnknownComponent_UnknownComponent (Urho3D::Context * context) { return WeakPtr<UnknownComponent>(new UnknownComponent(context)); } DllExport void UnknownComponent_RegisterObject (Urho3D::Context * context) { UnknownComponent::RegisterObject (context); } DllExport int UnknownComponent_GetType (Urho3D::UnknownComponent *_target) { return (_target->GetType ()).Value (); } DllExport const char * UnknownComponent_GetTypeName (Urho3D::UnknownComponent *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int UnknownComponent_Load_File (Urho3D::UnknownComponent *_target, File * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int UnknownComponent_Load_MemoryBuffer (Urho3D::UnknownComponent *_target, MemoryBuffer * source, bool setInstanceDefault) { return _target->Load (*source, setInstanceDefault); } DllExport int UnknownComponent_LoadXML (Urho3D::UnknownComponent *_target, const class Urho3D::XMLElement & source, bool setInstanceDefault) { return _target->LoadXML (source, setInstanceDefault); } DllExport int UnknownComponent_Save_File (Urho3D::UnknownComponent *_target, File * dest) { return _target->Save (*dest); } DllExport int UnknownComponent_Save_MemoryBuffer (Urho3D::UnknownComponent *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int UnknownComponent_SaveXML (Urho3D::UnknownComponent *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void UnknownComponent_SetTypeName (Urho3D::UnknownComponent *_target, const char * typeName) { _target->SetTypeName (Urho3D::String(typeName)); } DllExport void UnknownComponent_SetType (Urho3D::UnknownComponent *_target, int typeHash) { _target->SetType (Urho3D::StringHash(typeHash)); } DllExport int UnknownComponent_GetUseXML (Urho3D::UnknownComponent *_target) { return _target->GetUseXML (); } DllExport int UnknownComponent_GetTypeStatic () { return (UnknownComponent::GetTypeStatic ()).Value (); } DllExport const char * UnknownComponent_GetTypeNameStatic () { return stringdup((UnknownComponent::GetTypeNameStatic ()).CString ()); } DllExport int ValueAnimation_GetType (Urho3D::ValueAnimation *_target) { return (_target->GetType ()).Value (); } DllExport const char * ValueAnimation_GetTypeName (Urho3D::ValueAnimation *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ValueAnimation_GetTypeStatic () { return (ValueAnimation::GetTypeStatic ()).Value (); } DllExport const char * ValueAnimation_GetTypeNameStatic () { return stringdup((ValueAnimation::GetTypeNameStatic ()).CString ()); } DllExport void * ValueAnimation_ValueAnimation (Urho3D::Context * context) { return WeakPtr<ValueAnimation>(new ValueAnimation(context)); } DllExport void ValueAnimation_RegisterObject (Urho3D::Context * context) { ValueAnimation::RegisterObject (context); } DllExport int ValueAnimation_BeginLoad_File (Urho3D::ValueAnimation *_target, File * source) { return _target->BeginLoad (*source); } DllExport int ValueAnimation_BeginLoad_MemoryBuffer (Urho3D::ValueAnimation *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int ValueAnimation_Save_File (Urho3D::ValueAnimation *_target, File * dest) { return _target->Save (*dest); } DllExport int ValueAnimation_Save_MemoryBuffer (Urho3D::ValueAnimation *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport int ValueAnimation_LoadXML (Urho3D::ValueAnimation *_target, const class Urho3D::XMLElement & source) { return _target->LoadXML (source); } DllExport int ValueAnimation_SaveXML (Urho3D::ValueAnimation *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void ValueAnimation_SetOwner (Urho3D::ValueAnimation *_target, void * owner) { _target->SetOwner (owner); } DllExport void ValueAnimation_SetInterpolationMethod (Urho3D::ValueAnimation *_target, enum Urho3D::InterpMethod method) { _target->SetInterpolationMethod (method); } DllExport void ValueAnimation_SetSplineTension (Urho3D::ValueAnimation *_target, float tension) { _target->SetSplineTension (tension); } DllExport void ValueAnimation_SetValueType (Urho3D::ValueAnimation *_target, enum Urho3D::VariantType valueType) { _target->SetValueType (valueType); } // Urho3D::Variant overloads begin: DllExport int ValueAnimation_SetKeyFrame_0 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::Vector3 & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_1 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::IntRect & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_2 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::Color & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_3 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::Vector2 & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_4 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::Vector4 & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_5 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::IntVector2 & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_6 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::Quaternion & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_7 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::Matrix4 & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_8 (Urho3D::ValueAnimation *_target, float time, const class Urho3D::Matrix3x4 & value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_9 (Urho3D::ValueAnimation *_target, float time, int value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_10 (Urho3D::ValueAnimation *_target, float time, float value) { return _target->SetKeyFrame (time, (value)); } DllExport int ValueAnimation_SetKeyFrame_11 (Urho3D::ValueAnimation *_target, float time, const char * value) { return _target->SetKeyFrame (time, Urho3D::String(value)); } DllExport int ValueAnimation_SetKeyFrame_12 (Urho3D::ValueAnimation *_target, float time, bool value) { return _target->SetKeyFrame (time, (value)); } // Urho3D::Variant overloads end. DllExport int ValueAnimation_IsValid (Urho3D::ValueAnimation *_target) { return _target->IsValid (); } DllExport void * ValueAnimation_GetOwner (Urho3D::ValueAnimation *_target) { return _target->GetOwner (); } DllExport enum Urho3D::InterpMethod ValueAnimation_GetInterpolationMethod (Urho3D::ValueAnimation *_target) { return _target->GetInterpolationMethod (); } DllExport float ValueAnimation_GetSplineTension (Urho3D::ValueAnimation *_target) { return _target->GetSplineTension (); } DllExport enum Urho3D::VariantType ValueAnimation_GetValueType (Urho3D::ValueAnimation *_target) { return _target->GetValueType (); } DllExport float ValueAnimation_GetBeginTime (Urho3D::ValueAnimation *_target) { return _target->GetBeginTime (); } DllExport float ValueAnimation_GetEndTime (Urho3D::ValueAnimation *_target) { return _target->GetEndTime (); } DllExport Urho3D::Variant ValueAnimation_GetAnimationValue (Urho3D::ValueAnimation *_target, float scaledTime) { return _target->GetAnimationValue (scaledTime); } DllExport int ValueAnimation_HasEventFrames (Urho3D::ValueAnimation *_target) { return _target->HasEventFrames (); } DllExport int Button_GetType (Urho3D::Button *_target) { return (_target->GetType ()).Value (); } DllExport const char * Button_GetTypeName (Urho3D::Button *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Button_GetTypeStatic () { return (Button::GetTypeStatic ()).Value (); } DllExport const char * Button_GetTypeNameStatic () { return stringdup((Button::GetTypeNameStatic ()).CString ()); } DllExport void * Button_Button (Urho3D::Context * context) { return WeakPtr<Button>(new Button(context)); } DllExport void Button_RegisterObject (Urho3D::Context * context) { Button::RegisterObject (context); } DllExport void Button_Update (Urho3D::Button *_target, float timeStep) { _target->Update (timeStep); } DllExport void Button_OnClickBegin (Urho3D::Button *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnClickBegin (position, screenPosition, button, buttons, qualifiers, cursor); } DllExport void Button_OnClickEnd (Urho3D::Button *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor, Urho3D::UIElement * beginElement) { _target->OnClickEnd (position, screenPosition, button, buttons, qualifiers, cursor, beginElement); } DllExport void Button_OnKey (Urho3D::Button *_target, int key, int buttons, int qualifiers) { _target->OnKey (key, buttons, qualifiers); } DllExport void Button_SetPressedOffset (Urho3D::Button *_target, const class Urho3D::IntVector2 & offset) { _target->SetPressedOffset (offset); } DllExport void Button_SetPressedOffset0 (Urho3D::Button *_target, int x, int y) { _target->SetPressedOffset (x, y); } DllExport void Button_SetDisabledOffset (Urho3D::Button *_target, const class Urho3D::IntVector2 & offset) { _target->SetDisabledOffset (offset); } DllExport void Button_SetDisabledOffset1 (Urho3D::Button *_target, int x, int y) { _target->SetDisabledOffset (x, y); } DllExport void Button_SetPressedChildOffset (Urho3D::Button *_target, const class Urho3D::IntVector2 & offset) { _target->SetPressedChildOffset (offset); } DllExport void Button_SetPressedChildOffset2 (Urho3D::Button *_target, int x, int y) { _target->SetPressedChildOffset (x, y); } DllExport void Button_SetRepeat (Urho3D::Button *_target, float delay, float rate) { _target->SetRepeat (delay, rate); } DllExport void Button_SetRepeatDelay (Urho3D::Button *_target, float delay) { _target->SetRepeatDelay (delay); } DllExport void Button_SetRepeatRate (Urho3D::Button *_target, float rate) { _target->SetRepeatRate (rate); } DllExport Interop::IntVector2 Button_GetPressedOffset (Urho3D::Button *_target) { return *((Interop::IntVector2 *) &(_target->GetPressedOffset ())); } DllExport Interop::IntVector2 Button_GetDisabledOffset (Urho3D::Button *_target) { return *((Interop::IntVector2 *) &(_target->GetDisabledOffset ())); } DllExport Interop::IntVector2 Button_GetPressedChildOffset (Urho3D::Button *_target) { return *((Interop::IntVector2 *) &(_target->GetPressedChildOffset ())); } DllExport float Button_GetRepeatDelay (Urho3D::Button *_target) { return _target->GetRepeatDelay (); } DllExport float Button_GetRepeatRate (Urho3D::Button *_target) { return _target->GetRepeatRate (); } DllExport int Button_IsPressed (Urho3D::Button *_target) { return _target->IsPressed (); } DllExport int CheckBox_GetType (Urho3D::CheckBox *_target) { return (_target->GetType ()).Value (); } DllExport const char * CheckBox_GetTypeName (Urho3D::CheckBox *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CheckBox_GetTypeStatic () { return (CheckBox::GetTypeStatic ()).Value (); } DllExport const char * CheckBox_GetTypeNameStatic () { return stringdup((CheckBox::GetTypeNameStatic ()).CString ()); } DllExport void * CheckBox_CheckBox (Urho3D::Context * context) { return WeakPtr<CheckBox>(new CheckBox(context)); } DllExport void CheckBox_RegisterObject (Urho3D::Context * context) { CheckBox::RegisterObject (context); } DllExport void CheckBox_OnClickBegin (Urho3D::CheckBox *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnClickBegin (position, screenPosition, button, buttons, qualifiers, cursor); } DllExport void CheckBox_OnKey (Urho3D::CheckBox *_target, int key, int buttons, int qualifiers) { _target->OnKey (key, buttons, qualifiers); } DllExport void CheckBox_SetChecked (Urho3D::CheckBox *_target, bool enable) { _target->SetChecked (enable); } DllExport void CheckBox_SetCheckedOffset (Urho3D::CheckBox *_target, const class Urho3D::IntVector2 & rect) { _target->SetCheckedOffset (rect); } DllExport void CheckBox_SetCheckedOffset0 (Urho3D::CheckBox *_target, int x, int y) { _target->SetCheckedOffset (x, y); } DllExport int CheckBox_IsChecked (Urho3D::CheckBox *_target) { return _target->IsChecked (); } DllExport Interop::IntVector2 CheckBox_GetCheckedOffset (Urho3D::CheckBox *_target) { return *((Interop::IntVector2 *) &(_target->GetCheckedOffset ())); } DllExport int Menu_GetType (Urho3D::Menu *_target) { return (_target->GetType ()).Value (); } DllExport const char * Menu_GetTypeName (Urho3D::Menu *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Menu_GetTypeStatic () { return (Menu::GetTypeStatic ()).Value (); } DllExport const char * Menu_GetTypeNameStatic () { return stringdup((Menu::GetTypeNameStatic ()).CString ()); } DllExport void * Menu_Menu (Urho3D::Context * context) { return WeakPtr<Menu>(new Menu(context)); } DllExport void Menu_RegisterObject (Urho3D::Context * context) { Menu::RegisterObject (context); } DllExport int Menu_LoadXML (Urho3D::Menu *_target, const class Urho3D::XMLElement & source, Urho3D::XMLFile * styleFile, bool setInstanceDefault) { return _target->LoadXML (source, styleFile, setInstanceDefault); } DllExport int Menu_SaveXML (Urho3D::Menu *_target, Urho3D::XMLElement & dest) { return _target->SaveXML (dest); } DllExport void Menu_Update (Urho3D::Menu *_target, float timeStep) { _target->Update (timeStep); } DllExport void Menu_OnHover (Urho3D::Menu *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnHover (position, screenPosition, buttons, qualifiers, cursor); } DllExport void Menu_OnShowPopup (Urho3D::Menu *_target) { _target->OnShowPopup (); } DllExport void Menu_OnHidePopup (Urho3D::Menu *_target) { _target->OnHidePopup (); } DllExport void Menu_SetPopup (Urho3D::Menu *_target, Urho3D::UIElement * element) { _target->SetPopup (element); } DllExport void Menu_SetPopupOffset (Urho3D::Menu *_target, const class Urho3D::IntVector2 & offset) { _target->SetPopupOffset (offset); } DllExport void Menu_SetPopupOffset0 (Urho3D::Menu *_target, int x, int y) { _target->SetPopupOffset (x, y); } DllExport void Menu_ShowPopup (Urho3D::Menu *_target, bool enable) { _target->ShowPopup (enable); } DllExport void Menu_SetAccelerator (Urho3D::Menu *_target, int key, int qualifiers) { _target->SetAccelerator (key, qualifiers); } DllExport Urho3D::UIElement * Menu_GetPopup (Urho3D::Menu *_target) { return _target->GetPopup (); } DllExport Interop::IntVector2 Menu_GetPopupOffset (Urho3D::Menu *_target) { return *((Interop::IntVector2 *) &(_target->GetPopupOffset ())); } DllExport int Menu_GetShowPopup (Urho3D::Menu *_target) { return _target->GetShowPopup (); } DllExport int Menu_GetAcceleratorKey (Urho3D::Menu *_target) { return _target->GetAcceleratorKey (); } DllExport int Menu_GetAcceleratorQualifiers (Urho3D::Menu *_target) { return _target->GetAcceleratorQualifiers (); } DllExport int DropDownList_GetType (Urho3D::DropDownList *_target) { return (_target->GetType ()).Value (); } DllExport const char * DropDownList_GetTypeName (Urho3D::DropDownList *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int DropDownList_GetTypeStatic () { return (DropDownList::GetTypeStatic ()).Value (); } DllExport const char * DropDownList_GetTypeNameStatic () { return stringdup((DropDownList::GetTypeNameStatic ()).CString ()); } DllExport void * DropDownList_DropDownList (Urho3D::Context * context) { return WeakPtr<DropDownList>(new DropDownList(context)); } DllExport void DropDownList_RegisterObject (Urho3D::Context * context) { DropDownList::RegisterObject (context); } DllExport void DropDownList_ApplyAttributes (Urho3D::DropDownList *_target) { _target->ApplyAttributes (); } DllExport void DropDownList_OnShowPopup (Urho3D::DropDownList *_target) { _target->OnShowPopup (); } DllExport void DropDownList_OnHidePopup (Urho3D::DropDownList *_target) { _target->OnHidePopup (); } DllExport void DropDownList_OnSetEditable (Urho3D::DropDownList *_target) { _target->OnSetEditable (); } DllExport void DropDownList_AddItem (Urho3D::DropDownList *_target, Urho3D::UIElement * item) { _target->AddItem (item); } DllExport void DropDownList_InsertItem (Urho3D::DropDownList *_target, unsigned int index, Urho3D::UIElement * item) { _target->InsertItem (index, item); } DllExport void DropDownList_RemoveItem (Urho3D::DropDownList *_target, Urho3D::UIElement * item) { _target->RemoveItem (item); } DllExport void DropDownList_RemoveItem0 (Urho3D::DropDownList *_target, unsigned int index) { _target->RemoveItem (index); } DllExport void DropDownList_RemoveAllItems (Urho3D::DropDownList *_target) { _target->RemoveAllItems (); } DllExport void DropDownList_SetSelection (Urho3D::DropDownList *_target, unsigned int index) { _target->SetSelection (index); } DllExport void DropDownList_SetPlaceholderText (Urho3D::DropDownList *_target, const char * text) { _target->SetPlaceholderText (Urho3D::String(text)); } DllExport void DropDownList_SetResizePopup (Urho3D::DropDownList *_target, bool enable) { _target->SetResizePopup (enable); } DllExport unsigned int DropDownList_GetNumItems (Urho3D::DropDownList *_target) { return _target->GetNumItems (); } DllExport Urho3D::UIElement * DropDownList_GetItem (Urho3D::DropDownList *_target, unsigned int index) { return _target->GetItem (index); } DllExport unsigned int DropDownList_GetSelection (Urho3D::DropDownList *_target) { return _target->GetSelection (); } DllExport Urho3D::UIElement * DropDownList_GetSelectedItem (Urho3D::DropDownList *_target) { return _target->GetSelectedItem (); } DllExport Urho3D::ListView * DropDownList_GetListView (Urho3D::DropDownList *_target) { return _target->GetListView (); } DllExport Urho3D::UIElement * DropDownList_GetPlaceholder (Urho3D::DropDownList *_target) { return _target->GetPlaceholder (); } DllExport const char * DropDownList_GetPlaceholderText (Urho3D::DropDownList *_target) { return stringdup((_target->GetPlaceholderText ()).CString ()); } DllExport int DropDownList_GetResizePopup (Urho3D::DropDownList *_target) { return _target->GetResizePopup (); } DllExport void DropDownList_SetSelectionAttr (Urho3D::DropDownList *_target, unsigned int index) { _target->SetSelectionAttr (index); } DllExport int FileSelector_GetType (Urho3D::FileSelector *_target) { return (_target->GetType ()).Value (); } DllExport const char * FileSelector_GetTypeName (Urho3D::FileSelector *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int FileSelector_GetTypeStatic () { return (FileSelector::GetTypeStatic ()).Value (); } DllExport const char * FileSelector_GetTypeNameStatic () { return stringdup((FileSelector::GetTypeNameStatic ()).CString ()); } DllExport void * FileSelector_FileSelector (Urho3D::Context * context) { return WeakPtr<FileSelector>(new FileSelector(context)); } DllExport void FileSelector_RegisterObject (Urho3D::Context * context) { FileSelector::RegisterObject (context); } DllExport void FileSelector_SetDefaultStyle (Urho3D::FileSelector *_target, Urho3D::XMLFile * style) { _target->SetDefaultStyle (style); } DllExport void FileSelector_SetTitle (Urho3D::FileSelector *_target, const char * text) { _target->SetTitle (Urho3D::String(text)); } DllExport void FileSelector_SetButtonTexts (Urho3D::FileSelector *_target, const char * okText, const char * cancelText) { _target->SetButtonTexts (Urho3D::String(okText), Urho3D::String(cancelText)); } DllExport void FileSelector_SetPath (Urho3D::FileSelector *_target, const char * path) { _target->SetPath (Urho3D::String(path)); } DllExport void FileSelector_SetFileName (Urho3D::FileSelector *_target, const char * fileName) { _target->SetFileName (Urho3D::String(fileName)); } DllExport void FileSelector_SetDirectoryMode (Urho3D::FileSelector *_target, bool enable) { _target->SetDirectoryMode (enable); } DllExport void FileSelector_UpdateElements (Urho3D::FileSelector *_target) { _target->UpdateElements (); } DllExport Urho3D::XMLFile * FileSelector_GetDefaultStyle (Urho3D::FileSelector *_target) { return _target->GetDefaultStyle (); } DllExport Urho3D::Window * FileSelector_GetWindow (Urho3D::FileSelector *_target) { return _target->GetWindow (); } DllExport Urho3D::Text * FileSelector_GetTitleText (Urho3D::FileSelector *_target) { return _target->GetTitleText (); } DllExport Urho3D::ListView * FileSelector_GetFileList (Urho3D::FileSelector *_target) { return _target->GetFileList (); } DllExport Urho3D::LineEdit * FileSelector_GetPathEdit (Urho3D::FileSelector *_target) { return _target->GetPathEdit (); } DllExport Urho3D::LineEdit * FileSelector_GetFileNameEdit (Urho3D::FileSelector *_target) { return _target->GetFileNameEdit (); } DllExport Urho3D::DropDownList * FileSelector_GetFilterList (Urho3D::FileSelector *_target) { return _target->GetFilterList (); } DllExport Urho3D::Button * FileSelector_GetOKButton (Urho3D::FileSelector *_target) { return _target->GetOKButton (); } DllExport Urho3D::Button * FileSelector_GetCancelButton (Urho3D::FileSelector *_target) { return _target->GetCancelButton (); } DllExport Urho3D::Button * FileSelector_GetCloseButton (Urho3D::FileSelector *_target) { return _target->GetCloseButton (); } DllExport const char * FileSelector_GetTitle (Urho3D::FileSelector *_target) { return stringdup((_target->GetTitle ()).CString ()); } DllExport const char * FileSelector_GetPath (Urho3D::FileSelector *_target) { return stringdup((_target->GetPath ()).CString ()); } DllExport const char * FileSelector_GetFileName (Urho3D::FileSelector *_target) { return stringdup((_target->GetFileName ()).CString ()); } DllExport const char * FileSelector_GetFilter (Urho3D::FileSelector *_target) { return stringdup((_target->GetFilter ()).CString ()); } DllExport unsigned int FileSelector_GetFilterIndex (Urho3D::FileSelector *_target) { return _target->GetFilterIndex (); } DllExport int FileSelector_GetDirectoryMode (Urho3D::FileSelector *_target) { return _target->GetDirectoryMode (); } DllExport int Font_GetType (Urho3D::Font *_target) { return (_target->GetType ()).Value (); } DllExport const char * Font_GetTypeName (Urho3D::Font *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Font_GetTypeStatic () { return (Font::GetTypeStatic ()).Value (); } DllExport const char * Font_GetTypeNameStatic () { return stringdup((Font::GetTypeNameStatic ()).CString ()); } DllExport void * Font_Font (Urho3D::Context * context) { return WeakPtr<Font>(new Font(context)); } DllExport void Font_RegisterObject (Urho3D::Context * context) { Font::RegisterObject (context); } DllExport int Font_BeginLoad_File (Urho3D::Font *_target, File * source) { return _target->BeginLoad (*source); } DllExport int Font_BeginLoad_MemoryBuffer (Urho3D::Font *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int Font_SaveXML_File (Urho3D::Font *_target, File * dest, int pointSize, bool usedGlyphs, const char * indentation) { return _target->SaveXML (*dest, pointSize, usedGlyphs, Urho3D::String(indentation)); } DllExport int Font_SaveXML_MemoryBuffer (Urho3D::Font *_target, MemoryBuffer * dest, int pointSize, bool usedGlyphs, const char * indentation) { return _target->SaveXML (*dest, pointSize, usedGlyphs, Urho3D::String(indentation)); } DllExport void Font_SetAbsoluteGlyphOffset (Urho3D::Font *_target, const class Urho3D::IntVector2 & offset) { _target->SetAbsoluteGlyphOffset (offset); } DllExport void Font_SetScaledGlyphOffset (Urho3D::Font *_target, const class Urho3D::Vector2 & offset) { _target->SetScaledGlyphOffset (offset); } DllExport Urho3D::FontFace * Font_GetFace (Urho3D::Font *_target, float pointSize) { return _target->GetFace (pointSize); } DllExport enum Urho3D::FontType Font_GetFontType (Urho3D::Font *_target) { return _target->GetFontType (); } DllExport int Font_IsSDFFont (Urho3D::Font *_target) { return _target->IsSDFFont (); } DllExport Interop::IntVector2 Font_GetAbsoluteGlyphOffset (Urho3D::Font *_target) { return *((Interop::IntVector2 *) &(_target->GetAbsoluteGlyphOffset ())); } DllExport Interop::Vector2 Font_GetScaledGlyphOffset (Urho3D::Font *_target) { return *((Interop::Vector2 *) &(_target->GetScaledGlyphOffset ())); } DllExport Interop::IntVector2 Font_GetTotalGlyphOffset (Urho3D::Font *_target, float pointSize) { return *((Interop::IntVector2 *) &(_target->GetTotalGlyphOffset (pointSize))); } DllExport void Font_ReleaseFaces (Urho3D::Font *_target) { _target->ReleaseFaces (); } DllExport int FontFace_Load (Urho3D::FontFace *_target, const unsigned char * fontData, unsigned int fontDataSize, float pointSize) { return _target->Load (fontData, fontDataSize, pointSize); } DllExport const struct Urho3D::FontGlyph * FontFace_GetGlyph (Urho3D::FontFace *_target, unsigned int c) { return _target->GetGlyph (c); } DllExport int FontFace_HasMutableGlyphs (Urho3D::FontFace *_target) { return _target->HasMutableGlyphs (); } DllExport float FontFace_GetKerning (Urho3D::FontFace *_target, unsigned int c, unsigned int d) { return _target->GetKerning (c, d); } DllExport int FontFace_IsDataLost (Urho3D::FontFace *_target) { return _target->IsDataLost (); } DllExport float FontFace_GetPointSize (Urho3D::FontFace *_target) { return _target->GetPointSize (); } DllExport float FontFace_GetRowHeight (Urho3D::FontFace *_target) { return _target->GetRowHeight (); } DllExport const Vector<SharedPtr<class Urho3D::Texture2D> > & FontFace_GetTextures (Urho3D::FontFace *_target) { return _target->GetTextures (); } DllExport void * FontFaceBitmap_FontFaceBitmap (Urho3D::Font * font) { return WeakPtr<FontFaceBitmap>(new FontFaceBitmap(font)); } DllExport int FontFaceBitmap_Load (Urho3D::FontFaceBitmap *_target, const unsigned char * fontData, unsigned int fontDataSize, float pointSize) { return _target->Load (fontData, fontDataSize, pointSize); } DllExport int FontFaceBitmap_Load0 (Urho3D::FontFaceBitmap *_target, Urho3D::FontFace * fontFace, bool usedGlyphs) { return _target->Load (fontFace, usedGlyphs); } DllExport int FontFaceBitmap_Save_File (Urho3D::FontFaceBitmap *_target, File * dest, int pointSize, const char * indentation) { return _target->Save (*dest, pointSize, Urho3D::String(indentation)); } DllExport int FontFaceBitmap_Save_MemoryBuffer (Urho3D::FontFaceBitmap *_target, MemoryBuffer * dest, int pointSize, const char * indentation) { return _target->Save (*dest, pointSize, Urho3D::String(indentation)); } DllExport void * FontFaceFreeType_FontFaceFreeType (Urho3D::Font * font) { return WeakPtr<FontFaceFreeType>(new FontFaceFreeType(font)); } DllExport int FontFaceFreeType_Load (Urho3D::FontFaceFreeType *_target, const unsigned char * fontData, unsigned int fontDataSize, float pointSize) { return _target->Load (fontData, fontDataSize, pointSize); } DllExport const struct Urho3D::FontGlyph * FontFaceFreeType_GetGlyph (Urho3D::FontFaceFreeType *_target, unsigned int c) { return _target->GetGlyph (c); } DllExport int FontFaceFreeType_HasMutableGlyphs (Urho3D::FontFaceFreeType *_target) { return _target->HasMutableGlyphs (); } DllExport int LineEdit_GetType (Urho3D::LineEdit *_target) { return (_target->GetType ()).Value (); } DllExport const char * LineEdit_GetTypeName (Urho3D::LineEdit *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int LineEdit_GetTypeStatic () { return (LineEdit::GetTypeStatic ()).Value (); } DllExport const char * LineEdit_GetTypeNameStatic () { return stringdup((LineEdit::GetTypeNameStatic ()).CString ()); } DllExport void * LineEdit_LineEdit (Urho3D::Context * context) { return WeakPtr<LineEdit>(new LineEdit(context)); } DllExport void LineEdit_RegisterObject (Urho3D::Context * context) { LineEdit::RegisterObject (context); } DllExport void LineEdit_ApplyAttributes (Urho3D::LineEdit *_target) { _target->ApplyAttributes (); } DllExport void LineEdit_Update (Urho3D::LineEdit *_target, float timeStep) { _target->Update (timeStep); } DllExport void LineEdit_OnClickBegin (Urho3D::LineEdit *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnClickBegin (position, screenPosition, button, buttons, qualifiers, cursor); } DllExport void LineEdit_OnDoubleClick (Urho3D::LineEdit *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnDoubleClick (position, screenPosition, button, buttons, qualifiers, cursor); } DllExport void LineEdit_OnKey (Urho3D::LineEdit *_target, int key, int buttons, int qualifiers) { _target->OnKey (key, buttons, qualifiers); } DllExport void LineEdit_OnTextInput (Urho3D::LineEdit *_target, const char * text) { _target->OnTextInput (Urho3D::String(text)); } DllExport void LineEdit_SetText (Urho3D::LineEdit *_target, const char * text) { _target->SetText (Urho3D::String(text)); } DllExport void LineEdit_SetCursorPosition (Urho3D::LineEdit *_target, unsigned int position) { _target->SetCursorPosition (position); } DllExport void LineEdit_SetCursorBlinkRate (Urho3D::LineEdit *_target, float rate) { _target->SetCursorBlinkRate (rate); } DllExport void LineEdit_SetMaxLength (Urho3D::LineEdit *_target, unsigned int length) { _target->SetMaxLength (length); } DllExport void LineEdit_SetEchoCharacter (Urho3D::LineEdit *_target, unsigned int c) { _target->SetEchoCharacter (c); } DllExport void LineEdit_SetCursorMovable (Urho3D::LineEdit *_target, bool enable) { _target->SetCursorMovable (enable); } DllExport void LineEdit_SetTextSelectable (Urho3D::LineEdit *_target, bool enable) { _target->SetTextSelectable (enable); } DllExport void LineEdit_SetTextCopyable (Urho3D::LineEdit *_target, bool enable) { _target->SetTextCopyable (enable); } DllExport const char * LineEdit_GetText (Urho3D::LineEdit *_target) { return stringdup((_target->GetText ()).CString ()); } DllExport unsigned int LineEdit_GetCursorPosition (Urho3D::LineEdit *_target) { return _target->GetCursorPosition (); } DllExport float LineEdit_GetCursorBlinkRate (Urho3D::LineEdit *_target) { return _target->GetCursorBlinkRate (); } DllExport unsigned int LineEdit_GetMaxLength (Urho3D::LineEdit *_target) { return _target->GetMaxLength (); } DllExport unsigned int LineEdit_GetEchoCharacter (Urho3D::LineEdit *_target) { return _target->GetEchoCharacter (); } DllExport int LineEdit_IsCursorMovable (Urho3D::LineEdit *_target) { return _target->IsCursorMovable (); } DllExport int LineEdit_IsTextSelectable (Urho3D::LineEdit *_target) { return _target->IsTextSelectable (); } DllExport int LineEdit_IsTextCopyable (Urho3D::LineEdit *_target) { return _target->IsTextCopyable (); } DllExport Urho3D::Text * LineEdit_GetTextElement (Urho3D::LineEdit *_target) { return _target->GetTextElement (); } DllExport Urho3D::BorderImage * LineEdit_GetCursor (Urho3D::LineEdit *_target) { return _target->GetCursor (); } DllExport int ScrollView_GetType (Urho3D::ScrollView *_target) { return (_target->GetType ()).Value (); } DllExport const char * ScrollView_GetTypeName (Urho3D::ScrollView *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ScrollView_GetTypeStatic () { return (ScrollView::GetTypeStatic ()).Value (); } DllExport const char * ScrollView_GetTypeNameStatic () { return stringdup((ScrollView::GetTypeNameStatic ()).CString ()); } DllExport void * ScrollView_ScrollView (Urho3D::Context * context) { return WeakPtr<ScrollView>(new ScrollView(context)); } DllExport void ScrollView_RegisterObject (Urho3D::Context * context) { ScrollView::RegisterObject (context); } DllExport void ScrollView_Update (Urho3D::ScrollView *_target, float timeStep) { _target->Update (timeStep); } DllExport void ScrollView_ApplyAttributes (Urho3D::ScrollView *_target) { _target->ApplyAttributes (); } DllExport void ScrollView_OnWheel (Urho3D::ScrollView *_target, int delta, int buttons, int qualifiers) { _target->OnWheel (delta, buttons, qualifiers); } DllExport void ScrollView_OnKey (Urho3D::ScrollView *_target, int key, int buttons, int qualifiers) { _target->OnKey (key, buttons, qualifiers); } DllExport void ScrollView_OnResize (Urho3D::ScrollView *_target, const class Urho3D::IntVector2 & newSize, const class Urho3D::IntVector2 & delta) { _target->OnResize (newSize, delta); } DllExport int ScrollView_IsWheelHandler (Urho3D::ScrollView *_target) { return _target->IsWheelHandler (); } DllExport void ScrollView_SetContentElement (Urho3D::ScrollView *_target, Urho3D::UIElement * element) { _target->SetContentElement (element); } DllExport void ScrollView_SetViewPosition (Urho3D::ScrollView *_target, const class Urho3D::IntVector2 & position) { _target->SetViewPosition (position); } DllExport void ScrollView_SetViewPosition0 (Urho3D::ScrollView *_target, int x, int y) { _target->SetViewPosition (x, y); } DllExport void ScrollView_SetScrollBarsVisible (Urho3D::ScrollView *_target, bool horizontal, bool vertical) { _target->SetScrollBarsVisible (horizontal, vertical); } DllExport void ScrollView_SetHorizontalScrollBarVisible (Urho3D::ScrollView *_target, bool visible) { _target->SetHorizontalScrollBarVisible (visible); } DllExport void ScrollView_SetVerticalScrollBarVisible (Urho3D::ScrollView *_target, bool visible) { _target->SetVerticalScrollBarVisible (visible); } DllExport void ScrollView_SetScrollBarsAutoVisible (Urho3D::ScrollView *_target, bool enable) { _target->SetScrollBarsAutoVisible (enable); } DllExport void ScrollView_SetScrollStep (Urho3D::ScrollView *_target, float step) { _target->SetScrollStep (step); } DllExport void ScrollView_SetPageStep (Urho3D::ScrollView *_target, float step) { _target->SetPageStep (step); } DllExport void ScrollView_SetScrollDeceleration (Urho3D::ScrollView *_target, float deceleration) { _target->SetScrollDeceleration (deceleration); } DllExport void ScrollView_SetScrollSnapEpsilon (Urho3D::ScrollView *_target, float snap) { _target->SetScrollSnapEpsilon (snap); } DllExport void ScrollView_SetAutoDisableChildren (Urho3D::ScrollView *_target, bool disable) { _target->SetAutoDisableChildren (disable); } DllExport void ScrollView_SetAutoDisableThreshold (Urho3D::ScrollView *_target, float amount) { _target->SetAutoDisableThreshold (amount); } DllExport Interop::IntVector2 ScrollView_GetViewPosition (Urho3D::ScrollView *_target) { return *((Interop::IntVector2 *) &(_target->GetViewPosition ())); } DllExport Urho3D::UIElement * ScrollView_GetContentElement (Urho3D::ScrollView *_target) { return _target->GetContentElement (); } DllExport Urho3D::ScrollBar * ScrollView_GetHorizontalScrollBar (Urho3D::ScrollView *_target) { return _target->GetHorizontalScrollBar (); } DllExport Urho3D::ScrollBar * ScrollView_GetVerticalScrollBar (Urho3D::ScrollView *_target) { return _target->GetVerticalScrollBar (); } DllExport Urho3D::BorderImage * ScrollView_GetScrollPanel (Urho3D::ScrollView *_target) { return _target->GetScrollPanel (); } DllExport int ScrollView_GetScrollBarsAutoVisible (Urho3D::ScrollView *_target) { return _target->GetScrollBarsAutoVisible (); } DllExport int ScrollView_GetHorizontalScrollBarVisible (Urho3D::ScrollView *_target) { return _target->GetHorizontalScrollBarVisible (); } DllExport int ScrollView_GetVerticalScrollBarVisible (Urho3D::ScrollView *_target) { return _target->GetVerticalScrollBarVisible (); } DllExport float ScrollView_GetScrollStep (Urho3D::ScrollView *_target) { return _target->GetScrollStep (); } DllExport float ScrollView_GetPageStep (Urho3D::ScrollView *_target) { return _target->GetPageStep (); } DllExport float ScrollView_GetScrollDeceleration (Urho3D::ScrollView *_target) { return _target->GetScrollDeceleration (); } DllExport float ScrollView_GetScrollSnapEpsilon (Urho3D::ScrollView *_target) { return _target->GetScrollSnapEpsilon (); } DllExport int ScrollView_GetAutoDisableChildren (Urho3D::ScrollView *_target) { return _target->GetAutoDisableChildren (); } DllExport float ScrollView_GetAutoDisableThreshold (Urho3D::ScrollView *_target) { return _target->GetAutoDisableThreshold (); } DllExport void ScrollView_SetViewPositionAttr (Urho3D::ScrollView *_target, const class Urho3D::IntVector2 & value) { _target->SetViewPositionAttr (value); } DllExport int ListView_GetType (Urho3D::ListView *_target) { return (_target->GetType ()).Value (); } DllExport const char * ListView_GetTypeName (Urho3D::ListView *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ListView_GetTypeStatic () { return (ListView::GetTypeStatic ()).Value (); } DllExport const char * ListView_GetTypeNameStatic () { return stringdup((ListView::GetTypeNameStatic ()).CString ()); } DllExport void * ListView_ListView (Urho3D::Context * context) { return WeakPtr<ListView>(new ListView(context)); } DllExport void ListView_RegisterObject (Urho3D::Context * context) { ListView::RegisterObject (context); } DllExport void ListView_OnKey (Urho3D::ListView *_target, int key, int buttons, int qualifiers) { _target->OnKey (key, buttons, qualifiers); } DllExport void ListView_OnResize (Urho3D::ListView *_target, const class Urho3D::IntVector2 & newSize, const class Urho3D::IntVector2 & delta) { _target->OnResize (newSize, delta); } DllExport void ListView_UpdateInternalLayout (Urho3D::ListView *_target) { _target->UpdateInternalLayout (); } DllExport void ListView_DisableInternalLayoutUpdate (Urho3D::ListView *_target) { _target->DisableInternalLayoutUpdate (); } DllExport void ListView_EnableInternalLayoutUpdate (Urho3D::ListView *_target) { _target->EnableInternalLayoutUpdate (); } DllExport void ListView_AddItem (Urho3D::ListView *_target, Urho3D::UIElement * item) { _target->AddItem (item); } DllExport void ListView_InsertItem (Urho3D::ListView *_target, unsigned int index, Urho3D::UIElement * item, Urho3D::UIElement * parentItem) { _target->InsertItem (index, item, parentItem); } DllExport void ListView_RemoveItem (Urho3D::ListView *_target, Urho3D::UIElement * item, unsigned int index) { _target->RemoveItem (item, index); } DllExport void ListView_RemoveItem0 (Urho3D::ListView *_target, unsigned int index) { _target->RemoveItem (index); } DllExport void ListView_RemoveAllItems (Urho3D::ListView *_target) { _target->RemoveAllItems (); } DllExport void ListView_SetSelection (Urho3D::ListView *_target, unsigned int index) { _target->SetSelection (index); } DllExport void ListView_AddSelection (Urho3D::ListView *_target, unsigned int index) { _target->AddSelection (index); } DllExport void ListView_RemoveSelection (Urho3D::ListView *_target, unsigned int index) { _target->RemoveSelection (index); } DllExport void ListView_ToggleSelection (Urho3D::ListView *_target, unsigned int index) { _target->ToggleSelection (index); } DllExport void ListView_ChangeSelection (Urho3D::ListView *_target, int delta, bool additive) { _target->ChangeSelection (delta, additive); } DllExport void ListView_ClearSelection (Urho3D::ListView *_target) { _target->ClearSelection (); } DllExport void ListView_SetHighlightMode (Urho3D::ListView *_target, enum Urho3D::HighlightMode mode) { _target->SetHighlightMode (mode); } DllExport void ListView_SetMultiselect (Urho3D::ListView *_target, bool enable) { _target->SetMultiselect (enable); } DllExport void ListView_SetHierarchyMode (Urho3D::ListView *_target, bool enable) { _target->SetHierarchyMode (enable); } DllExport void ListView_SetBaseIndent (Urho3D::ListView *_target, int baseIndent) { _target->SetBaseIndent (baseIndent); } DllExport void ListView_SetClearSelectionOnDefocus (Urho3D::ListView *_target, bool enable) { _target->SetClearSelectionOnDefocus (enable); } DllExport void ListView_SetSelectOnClickEnd (Urho3D::ListView *_target, bool enable) { _target->SetSelectOnClickEnd (enable); } DllExport void ListView_Expand (Urho3D::ListView *_target, unsigned int index, bool enable, bool recursive) { _target->Expand (index, enable, recursive); } DllExport void ListView_ToggleExpand (Urho3D::ListView *_target, unsigned int index, bool recursive) { _target->ToggleExpand (index, recursive); } DllExport unsigned int ListView_GetNumItems (Urho3D::ListView *_target) { return _target->GetNumItems (); } DllExport Urho3D::UIElement * ListView_GetItem (Urho3D::ListView *_target, unsigned int index) { return _target->GetItem (index); } DllExport unsigned int ListView_FindItem (Urho3D::ListView *_target, Urho3D::UIElement * item) { return _target->FindItem (item); } DllExport unsigned int ListView_GetSelection (Urho3D::ListView *_target) { return _target->GetSelection (); } DllExport void ListView_CopySelectedItemsToClipboard (Urho3D::ListView *_target) { _target->CopySelectedItemsToClipboard (); } DllExport Urho3D::UIElement * ListView_GetSelectedItem (Urho3D::ListView *_target) { return _target->GetSelectedItem (); } DllExport int ListView_IsSelected (Urho3D::ListView *_target, unsigned int index) { return _target->IsSelected (index); } DllExport int ListView_IsExpanded (Urho3D::ListView *_target, unsigned int index) { return _target->IsExpanded (index); } DllExport enum Urho3D::HighlightMode ListView_GetHighlightMode (Urho3D::ListView *_target) { return _target->GetHighlightMode (); } DllExport int ListView_GetMultiselect (Urho3D::ListView *_target) { return _target->GetMultiselect (); } DllExport int ListView_GetClearSelectionOnDefocus (Urho3D::ListView *_target) { return _target->GetClearSelectionOnDefocus (); } DllExport int ListView_GetSelectOnClickEnd (Urho3D::ListView *_target) { return _target->GetSelectOnClickEnd (); } DllExport int ListView_GetHierarchyMode (Urho3D::ListView *_target) { return _target->GetHierarchyMode (); } DllExport int ListView_GetBaseIndent (Urho3D::ListView *_target) { return _target->GetBaseIndent (); } DllExport void ListView_EnsureItemVisibility (Urho3D::ListView *_target, unsigned int index) { _target->EnsureItemVisibility (index); } DllExport void ListView_EnsureItemVisibility1 (Urho3D::ListView *_target, Urho3D::UIElement * item) { _target->EnsureItemVisibility (item); } DllExport int UIComponent_GetType (Urho3D::UIComponent *_target) { return (_target->GetType ()).Value (); } DllExport const char * UIComponent_GetTypeName (Urho3D::UIComponent *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int UIComponent_GetTypeStatic () { return (UIComponent::GetTypeStatic ()).Value (); } DllExport const char * UIComponent_GetTypeNameStatic () { return stringdup((UIComponent::GetTypeNameStatic ()).CString ()); } DllExport void * UIComponent_UIComponent (Urho3D::Context * context) { return WeakPtr<UIComponent>(new UIComponent(context)); } DllExport void UIComponent_RegisterObject (Urho3D::Context * context) { UIComponent::RegisterObject (context); } DllExport Urho3D::UIElement * UIComponent_GetRoot (Urho3D::UIComponent *_target) { return _target->GetRoot (); } DllExport Urho3D::Material * UIComponent_GetMaterial (Urho3D::UIComponent *_target) { return _target->GetMaterial (); } DllExport Urho3D::Texture2D * UIComponent_GetTexture (Urho3D::UIComponent *_target) { return _target->GetTexture (); } DllExport int ScrollBar_GetType (Urho3D::ScrollBar *_target) { return (_target->GetType ()).Value (); } DllExport const char * ScrollBar_GetTypeName (Urho3D::ScrollBar *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ScrollBar_GetTypeStatic () { return (ScrollBar::GetTypeStatic ()).Value (); } DllExport const char * ScrollBar_GetTypeNameStatic () { return stringdup((ScrollBar::GetTypeNameStatic ()).CString ()); } DllExport void * ScrollBar_ScrollBar (Urho3D::Context * context) { return WeakPtr<ScrollBar>(new ScrollBar(context)); } DllExport void ScrollBar_RegisterObject (Urho3D::Context * context) { ScrollBar::RegisterObject (context); } DllExport void ScrollBar_ApplyAttributes (Urho3D::ScrollBar *_target) { _target->ApplyAttributes (); } DllExport void ScrollBar_OnResize (Urho3D::ScrollBar *_target, const class Urho3D::IntVector2 & newSize, const class Urho3D::IntVector2 & delta) { _target->OnResize (newSize, delta); } DllExport void ScrollBar_OnSetEditable (Urho3D::ScrollBar *_target) { _target->OnSetEditable (); } DllExport void ScrollBar_SetOrientation (Urho3D::ScrollBar *_target, enum Urho3D::Orientation orientation) { _target->SetOrientation (orientation); } DllExport void ScrollBar_SetRange (Urho3D::ScrollBar *_target, float range) { _target->SetRange (range); } DllExport void ScrollBar_SetValue (Urho3D::ScrollBar *_target, float value) { _target->SetValue (value); } DllExport void ScrollBar_ChangeValue (Urho3D::ScrollBar *_target, float delta) { _target->ChangeValue (delta); } DllExport void ScrollBar_SetScrollStep (Urho3D::ScrollBar *_target, float step) { _target->SetScrollStep (step); } DllExport void ScrollBar_SetStepFactor (Urho3D::ScrollBar *_target, float factor) { _target->SetStepFactor (factor); } DllExport void ScrollBar_StepBack (Urho3D::ScrollBar *_target) { _target->StepBack (); } DllExport void ScrollBar_StepForward (Urho3D::ScrollBar *_target) { _target->StepForward (); } DllExport enum Urho3D::Orientation ScrollBar_GetOrientation (Urho3D::ScrollBar *_target) { return _target->GetOrientation (); } DllExport float ScrollBar_GetRange (Urho3D::ScrollBar *_target) { return _target->GetRange (); } DllExport float ScrollBar_GetValue (Urho3D::ScrollBar *_target) { return _target->GetValue (); } DllExport float ScrollBar_GetScrollStep (Urho3D::ScrollBar *_target) { return _target->GetScrollStep (); } DllExport float ScrollBar_GetStepFactor (Urho3D::ScrollBar *_target) { return _target->GetStepFactor (); } DllExport float ScrollBar_GetEffectiveScrollStep (Urho3D::ScrollBar *_target) { return _target->GetEffectiveScrollStep (); } DllExport Urho3D::Button * ScrollBar_GetBackButton (Urho3D::ScrollBar *_target) { return _target->GetBackButton (); } DllExport Urho3D::Button * ScrollBar_GetForwardButton (Urho3D::ScrollBar *_target) { return _target->GetForwardButton (); } DllExport Urho3D::Slider * ScrollBar_GetSlider (Urho3D::ScrollBar *_target) { return _target->GetSlider (); } DllExport int Slider_GetType (Urho3D::Slider *_target) { return (_target->GetType ()).Value (); } DllExport const char * Slider_GetTypeName (Urho3D::Slider *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Slider_GetTypeStatic () { return (Slider::GetTypeStatic ()).Value (); } DllExport const char * Slider_GetTypeNameStatic () { return stringdup((Slider::GetTypeNameStatic ()).CString ()); } DllExport void * Slider_Slider (Urho3D::Context * context) { return WeakPtr<Slider>(new Slider(context)); } DllExport void Slider_RegisterObject (Urho3D::Context * context) { Slider::RegisterObject (context); } DllExport void Slider_Update (Urho3D::Slider *_target, float timeStep) { _target->Update (timeStep); } DllExport void Slider_OnHover (Urho3D::Slider *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnHover (position, screenPosition, buttons, qualifiers, cursor); } DllExport void Slider_OnClickBegin (Urho3D::Slider *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnClickBegin (position, screenPosition, button, buttons, qualifiers, cursor); } DllExport void Slider_OnClickEnd (Urho3D::Slider *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int button, int buttons, int qualifiers, Urho3D::Cursor * cursor, Urho3D::UIElement * beginElement) { _target->OnClickEnd (position, screenPosition, button, buttons, qualifiers, cursor, beginElement); } DllExport void Slider_OnResize (Urho3D::Slider *_target, const class Urho3D::IntVector2 & newSize, const class Urho3D::IntVector2 & delta) { _target->OnResize (newSize, delta); } DllExport void Slider_SetOrientation (Urho3D::Slider *_target, enum Urho3D::Orientation orientation) { _target->SetOrientation (orientation); } DllExport void Slider_SetRange (Urho3D::Slider *_target, float range) { _target->SetRange (range); } DllExport void Slider_SetValue (Urho3D::Slider *_target, float value) { _target->SetValue (value); } DllExport void Slider_ChangeValue (Urho3D::Slider *_target, float delta) { _target->ChangeValue (delta); } DllExport void Slider_SetRepeatRate (Urho3D::Slider *_target, float rate) { _target->SetRepeatRate (rate); } DllExport enum Urho3D::Orientation Slider_GetOrientation (Urho3D::Slider *_target) { return _target->GetOrientation (); } DllExport float Slider_GetRange (Urho3D::Slider *_target) { return _target->GetRange (); } DllExport float Slider_GetValue (Urho3D::Slider *_target) { return _target->GetValue (); } DllExport Urho3D::BorderImage * Slider_GetKnob (Urho3D::Slider *_target) { return _target->GetKnob (); } DllExport float Slider_GetRepeatRate (Urho3D::Slider *_target) { return _target->GetRepeatRate (); } DllExport int Sprite_GetType (Urho3D::Sprite *_target) { return (_target->GetType ()).Value (); } DllExport const char * Sprite_GetTypeName (Urho3D::Sprite *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Sprite_GetTypeStatic () { return (Sprite::GetTypeStatic ()).Value (); } DllExport const char * Sprite_GetTypeNameStatic () { return stringdup((Sprite::GetTypeNameStatic ()).CString ()); } DllExport void * Sprite_Sprite (Urho3D::Context * context) { return WeakPtr<Sprite>(new Sprite(context)); } DllExport void Sprite_RegisterObject (Urho3D::Context * context) { Sprite::RegisterObject (context); } DllExport int Sprite_IsWithinScissor (Urho3D::Sprite *_target, const class Urho3D::IntRect & currentScissor) { return _target->IsWithinScissor (currentScissor); } DllExport Interop::IntVector2 Sprite_GetScreenPosition (Urho3D::Sprite *_target) { return *((Interop::IntVector2 *) &(_target->GetScreenPosition ())); } DllExport void Sprite_OnPositionSet (Urho3D::Sprite *_target, const class Urho3D::IntVector2 & newPosition) { _target->OnPositionSet (newPosition); } DllExport Interop::IntVector2 Sprite_ScreenToElement (Urho3D::Sprite *_target, const class Urho3D::IntVector2 & screenPosition) { return *((Interop::IntVector2 *) &(_target->ScreenToElement (screenPosition))); } DllExport Interop::IntVector2 Sprite_ElementToScreen (Urho3D::Sprite *_target, const class Urho3D::IntVector2 & position) { return *((Interop::IntVector2 *) &(_target->ElementToScreen (position))); } DllExport void Sprite_SetPosition (Urho3D::Sprite *_target, const class Urho3D::Vector2 & position) { _target->SetPosition (position); } DllExport void Sprite_SetPosition0 (Urho3D::Sprite *_target, float x, float y) { _target->SetPosition (x, y); } DllExport void Sprite_SetHotSpot (Urho3D::Sprite *_target, const class Urho3D::IntVector2 & hotSpot) { _target->SetHotSpot (hotSpot); } DllExport void Sprite_SetHotSpot1 (Urho3D::Sprite *_target, int x, int y) { _target->SetHotSpot (x, y); } DllExport void Sprite_SetScale (Urho3D::Sprite *_target, const class Urho3D::Vector2 & scale) { _target->SetScale (scale); } DllExport void Sprite_SetScale2 (Urho3D::Sprite *_target, float x, float y) { _target->SetScale (x, y); } DllExport void Sprite_SetScale3 (Urho3D::Sprite *_target, float scale) { _target->SetScale (scale); } DllExport void Sprite_SetRotation (Urho3D::Sprite *_target, float angle) { _target->SetRotation (angle); } DllExport void Sprite_SetTexture (Urho3D::Sprite *_target, Urho3D::Texture * texture) { _target->SetTexture (texture); } DllExport void Sprite_SetImageRect (Urho3D::Sprite *_target, const class Urho3D::IntRect & rect) { _target->SetImageRect (rect); } DllExport void Sprite_SetFullImageRect (Urho3D::Sprite *_target) { _target->SetFullImageRect (); } DllExport void Sprite_SetBlendMode (Urho3D::Sprite *_target, enum Urho3D::BlendMode mode) { _target->SetBlendMode (mode); } DllExport Interop::Vector2 Sprite_GetPosition (Urho3D::Sprite *_target) { return *((Interop::Vector2 *) &(_target->GetPosition ())); } DllExport Interop::IntVector2 Sprite_GetHotSpot (Urho3D::Sprite *_target) { return *((Interop::IntVector2 *) &(_target->GetHotSpot ())); } DllExport Interop::Vector2 Sprite_GetScale (Urho3D::Sprite *_target) { return *((Interop::Vector2 *) &(_target->GetScale ())); } DllExport float Sprite_GetRotation (Urho3D::Sprite *_target) { return _target->GetRotation (); } DllExport Urho3D::Texture * Sprite_GetTexture (Urho3D::Sprite *_target) { return _target->GetTexture (); } DllExport Interop::IntRect Sprite_GetImageRect (Urho3D::Sprite *_target) { return *((Interop::IntRect *) &(_target->GetImageRect ())); } DllExport enum Urho3D::BlendMode Sprite_GetBlendMode (Urho3D::Sprite *_target) { return _target->GetBlendMode (); } DllExport Urho3D::ResourceRef Sprite_GetTextureAttr (Urho3D::Sprite *_target) { return _target->GetTextureAttr (); } DllExport Interop::Matrix3x4 Sprite_GetTransform (Urho3D::Sprite *_target) { return *((Interop::Matrix3x4 *) &(_target->GetTransform ())); } DllExport int Text_GetType (Urho3D::Text *_target) { return (_target->GetType ()).Value (); } DllExport const char * Text_GetTypeName (Urho3D::Text *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Text_GetTypeStatic () { return (Text::GetTypeStatic ()).Value (); } DllExport const char * Text_GetTypeNameStatic () { return stringdup((Text::GetTypeNameStatic ()).CString ()); } DllExport void * Text_Text (Urho3D::Context * context) { return WeakPtr<Text>(new Text(context)); } DllExport void Text_RegisterObject (Urho3D::Context * context) { Text::RegisterObject (context); } DllExport void Text_ApplyAttributes (Urho3D::Text *_target) { _target->ApplyAttributes (); } DllExport void Text_OnResize (Urho3D::Text *_target, const class Urho3D::IntVector2 & newSize, const class Urho3D::IntVector2 & delta) { _target->OnResize (newSize, delta); } DllExport void Text_OnIndentSet (Urho3D::Text *_target) { _target->OnIndentSet (); } DllExport int Text_SetFont (Urho3D::Text *_target, const char * fontName, float size) { return _target->SetFont (Urho3D::String(fontName), size); } DllExport int Text_SetFont0 (Urho3D::Text *_target, Urho3D::Font * font, float size) { return _target->SetFont (font, size); } DllExport int Text_SetFontSize (Urho3D::Text *_target, float size) { return _target->SetFontSize (size); } DllExport void Text_SetText (Urho3D::Text *_target, const char * text) { _target->SetText (Urho3D::String(text)); } DllExport void Text_SetTextAlignment (Urho3D::Text *_target, enum Urho3D::HorizontalAlignment align) { _target->SetTextAlignment (align); } DllExport void Text_SetRowSpacing (Urho3D::Text *_target, float spacing) { _target->SetRowSpacing (spacing); } DllExport void Text_SetWordwrap (Urho3D::Text *_target, bool enable) { _target->SetWordwrap (enable); } DllExport void Text_SetAutoLocalizable (Urho3D::Text *_target, bool enable) { _target->SetAutoLocalizable (enable); } DllExport void Text_SetSelection (Urho3D::Text *_target, unsigned int start, unsigned int length) { _target->SetSelection (start, length); } DllExport void Text_ClearSelection (Urho3D::Text *_target) { _target->ClearSelection (); } DllExport void Text_SetSelectionColor (Urho3D::Text *_target, const class Urho3D::Color & color) { _target->SetSelectionColor (color); } DllExport void Text_SetHoverColor (Urho3D::Text *_target, const class Urho3D::Color & color) { _target->SetHoverColor (color); } DllExport void Text_SetTextEffect (Urho3D::Text *_target, enum Urho3D::TextEffect textEffect) { _target->SetTextEffect (textEffect); } DllExport void Text_SetEffectShadowOffset (Urho3D::Text *_target, const class Urho3D::IntVector2 & offset) { _target->SetEffectShadowOffset (offset); } DllExport void Text_SetEffectStrokeThickness (Urho3D::Text *_target, int thickness) { _target->SetEffectStrokeThickness (thickness); } DllExport void Text_SetEffectRoundStroke (Urho3D::Text *_target, bool roundStroke) { _target->SetEffectRoundStroke (roundStroke); } DllExport void Text_SetEffectColor (Urho3D::Text *_target, const class Urho3D::Color & effectColor) { _target->SetEffectColor (effectColor); } DllExport Urho3D::Font * Text_GetFont (Urho3D::Text *_target) { return _target->GetFont (); } DllExport float Text_GetFontSize (Urho3D::Text *_target) { return _target->GetFontSize (); } DllExport const char * Text_GetText (Urho3D::Text *_target) { return stringdup((_target->GetText ()).CString ()); } DllExport enum Urho3D::HorizontalAlignment Text_GetTextAlignment (Urho3D::Text *_target) { return _target->GetTextAlignment (); } DllExport float Text_GetRowSpacing (Urho3D::Text *_target) { return _target->GetRowSpacing (); } DllExport int Text_GetWordwrap (Urho3D::Text *_target) { return _target->GetWordwrap (); } DllExport int Text_GetAutoLocalizable (Urho3D::Text *_target) { return _target->GetAutoLocalizable (); } DllExport unsigned int Text_GetSelectionStart (Urho3D::Text *_target) { return _target->GetSelectionStart (); } DllExport unsigned int Text_GetSelectionLength (Urho3D::Text *_target) { return _target->GetSelectionLength (); } DllExport Interop::Color Text_GetSelectionColor (Urho3D::Text *_target) { return *((Interop::Color *) &(_target->GetSelectionColor ())); } DllExport Interop::Color Text_GetHoverColor (Urho3D::Text *_target) { return *((Interop::Color *) &(_target->GetHoverColor ())); } DllExport enum Urho3D::TextEffect Text_GetTextEffect (Urho3D::Text *_target) { return _target->GetTextEffect (); } DllExport Interop::IntVector2 Text_GetEffectShadowOffset (Urho3D::Text *_target) { return *((Interop::IntVector2 *) &(_target->GetEffectShadowOffset ())); } DllExport int Text_GetEffectStrokeThickness (Urho3D::Text *_target) { return _target->GetEffectStrokeThickness (); } DllExport int Text_GetEffectRoundStroke (Urho3D::Text *_target) { return _target->GetEffectRoundStroke (); } DllExport Interop::Color Text_GetEffectColor (Urho3D::Text *_target) { return *((Interop::Color *) &(_target->GetEffectColor ())); } DllExport float Text_GetRowHeight (Urho3D::Text *_target) { return _target->GetRowHeight (); } DllExport unsigned int Text_GetNumRows (Urho3D::Text *_target) { return _target->GetNumRows (); } DllExport unsigned int Text_GetNumChars (Urho3D::Text *_target) { return _target->GetNumChars (); } DllExport float Text_GetRowWidth (Urho3D::Text *_target, unsigned int index) { return _target->GetRowWidth (index); } DllExport Interop::Vector2 Text_GetCharPosition (Urho3D::Text *_target, unsigned int index) { return *((Interop::Vector2 *) &(_target->GetCharPosition (index))); } DllExport Interop::Vector2 Text_GetCharSize (Urho3D::Text *_target, unsigned int index) { return *((Interop::Vector2 *) &(_target->GetCharSize (index))); } DllExport void Text_SetEffectDepthBias (Urho3D::Text *_target, float bias) { _target->SetEffectDepthBias (bias); } DllExport float Text_GetEffectDepthBias (Urho3D::Text *_target) { return _target->GetEffectDepthBias (); } DllExport Urho3D::ResourceRef Text_GetFontAttr (Urho3D::Text *_target) { return _target->GetFontAttr (); } DllExport void Text_SetTextAttr (Urho3D::Text *_target, const char * value) { _target->SetTextAttr (Urho3D::String(value)); } DllExport const char * Text_GetTextAttr (Urho3D::Text *_target) { return stringdup((_target->GetTextAttr ()).CString ()); } DllExport int Text3D_GetType (Urho3D::Text3D *_target) { return (_target->GetType ()).Value (); } DllExport const char * Text3D_GetTypeName (Urho3D::Text3D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Text3D_GetTypeStatic () { return (Text3D::GetTypeStatic ()).Value (); } DllExport const char * Text3D_GetTypeNameStatic () { return stringdup((Text3D::GetTypeNameStatic ()).CString ()); } DllExport void * Text3D_Text3D (Urho3D::Context * context) { return WeakPtr<Text3D>(new Text3D(context)); } DllExport void Text3D_RegisterObject (Urho3D::Context * context) { Text3D::RegisterObject (context); } DllExport void Text3D_ApplyAttributes (Urho3D::Text3D *_target) { _target->ApplyAttributes (); } DllExport enum Urho3D::UpdateGeometryType Text3D_GetUpdateGeometryType (Urho3D::Text3D *_target) { return _target->GetUpdateGeometryType (); } DllExport int Text3D_SetFont (Urho3D::Text3D *_target, const char * fontName, float size) { return _target->SetFont (Urho3D::String(fontName), size); } DllExport int Text3D_SetFont0 (Urho3D::Text3D *_target, Urho3D::Font * font, float size) { return _target->SetFont (font, size); } DllExport int Text3D_SetFontSize (Urho3D::Text3D *_target, float size) { return _target->SetFontSize (size); } DllExport void Text3D_SetMaterial (Urho3D::Text3D *_target, Urho3D::Material * material) { _target->SetMaterial (material); } DllExport void Text3D_SetText (Urho3D::Text3D *_target, const char * text) { _target->SetText (Urho3D::String(text)); } DllExport void Text3D_SetAlignment (Urho3D::Text3D *_target, enum Urho3D::HorizontalAlignment hAlign, enum Urho3D::VerticalAlignment vAlign) { _target->SetAlignment (hAlign, vAlign); } DllExport void Text3D_SetHorizontalAlignment (Urho3D::Text3D *_target, enum Urho3D::HorizontalAlignment align) { _target->SetHorizontalAlignment (align); } DllExport void Text3D_SetVerticalAlignment (Urho3D::Text3D *_target, enum Urho3D::VerticalAlignment align) { _target->SetVerticalAlignment (align); } DllExport void Text3D_SetTextAlignment (Urho3D::Text3D *_target, enum Urho3D::HorizontalAlignment align) { _target->SetTextAlignment (align); } DllExport void Text3D_SetRowSpacing (Urho3D::Text3D *_target, float spacing) { _target->SetRowSpacing (spacing); } DllExport void Text3D_SetWordwrap (Urho3D::Text3D *_target, bool enable) { _target->SetWordwrap (enable); } DllExport void Text3D_SetTextEffect (Urho3D::Text3D *_target, enum Urho3D::TextEffect textEffect) { _target->SetTextEffect (textEffect); } DllExport void Text3D_SetEffectShadowOffset (Urho3D::Text3D *_target, const class Urho3D::IntVector2 & offset) { _target->SetEffectShadowOffset (offset); } DllExport void Text3D_SetEffectStrokeThickness (Urho3D::Text3D *_target, int thickness) { _target->SetEffectStrokeThickness (thickness); } DllExport void Text3D_SetEffectRoundStroke (Urho3D::Text3D *_target, bool roundStroke) { _target->SetEffectRoundStroke (roundStroke); } DllExport void Text3D_SetEffectColor (Urho3D::Text3D *_target, const class Urho3D::Color & effectColor) { _target->SetEffectColor (effectColor); } DllExport void Text3D_SetEffectDepthBias (Urho3D::Text3D *_target, float bias) { _target->SetEffectDepthBias (bias); } DllExport void Text3D_SetWidth (Urho3D::Text3D *_target, int width) { _target->SetWidth (width); } DllExport void Text3D_SetColor (Urho3D::Text3D *_target, const class Urho3D::Color & color) { _target->SetColor (color); } DllExport void Text3D_SetColor1 (Urho3D::Text3D *_target, enum Urho3D::Corner corner, const class Urho3D::Color & color) { _target->SetColor (corner, color); } DllExport void Text3D_SetOpacity (Urho3D::Text3D *_target, float opacity) { _target->SetOpacity (opacity); } DllExport void Text3D_SetFixedScreenSize (Urho3D::Text3D *_target, bool enable) { _target->SetFixedScreenSize (enable); } DllExport void Text3D_SetFaceCameraMode (Urho3D::Text3D *_target, enum Urho3D::FaceCameraMode mode) { _target->SetFaceCameraMode (mode); } DllExport Urho3D::Font * Text3D_GetFont (Urho3D::Text3D *_target) { return _target->GetFont (); } DllExport float Text3D_GetFontSize (Urho3D::Text3D *_target) { return _target->GetFontSize (); } DllExport Urho3D::Material * Text3D_GetMaterial (Urho3D::Text3D *_target) { return _target->GetMaterial (); } DllExport const char * Text3D_GetText (Urho3D::Text3D *_target) { return stringdup((_target->GetText ()).CString ()); } DllExport enum Urho3D::HorizontalAlignment Text3D_GetTextAlignment (Urho3D::Text3D *_target) { return _target->GetTextAlignment (); } DllExport enum Urho3D::HorizontalAlignment Text3D_GetHorizontalAlignment (Urho3D::Text3D *_target) { return _target->GetHorizontalAlignment (); } DllExport enum Urho3D::VerticalAlignment Text3D_GetVerticalAlignment (Urho3D::Text3D *_target) { return _target->GetVerticalAlignment (); } DllExport float Text3D_GetRowSpacing (Urho3D::Text3D *_target) { return _target->GetRowSpacing (); } DllExport int Text3D_GetWordwrap (Urho3D::Text3D *_target) { return _target->GetWordwrap (); } DllExport enum Urho3D::TextEffect Text3D_GetTextEffect (Urho3D::Text3D *_target) { return _target->GetTextEffect (); } DllExport Interop::IntVector2 Text3D_GetEffectShadowOffset (Urho3D::Text3D *_target) { return *((Interop::IntVector2 *) &(_target->GetEffectShadowOffset ())); } DllExport int Text3D_GetEffectStrokeThickness (Urho3D::Text3D *_target) { return _target->GetEffectStrokeThickness (); } DllExport int Text3D_GetEffectRoundStroke (Urho3D::Text3D *_target) { return _target->GetEffectRoundStroke (); } DllExport Interop::Color Text3D_GetEffectColor (Urho3D::Text3D *_target) { return *((Interop::Color *) &(_target->GetEffectColor ())); } DllExport float Text3D_GetEffectDepthBias (Urho3D::Text3D *_target) { return _target->GetEffectDepthBias (); } DllExport int Text3D_GetWidth (Urho3D::Text3D *_target) { return _target->GetWidth (); } DllExport int Text3D_GetHeight (Urho3D::Text3D *_target) { return _target->GetHeight (); } DllExport int Text3D_GetRowHeight (Urho3D::Text3D *_target) { return _target->GetRowHeight (); } DllExport unsigned int Text3D_GetNumRows (Urho3D::Text3D *_target) { return _target->GetNumRows (); } DllExport unsigned int Text3D_GetNumChars (Urho3D::Text3D *_target) { return _target->GetNumChars (); } DllExport int Text3D_GetRowWidth (Urho3D::Text3D *_target, unsigned int index) { return _target->GetRowWidth (index); } DllExport Interop::Vector2 Text3D_GetCharPosition (Urho3D::Text3D *_target, unsigned int index) { return *((Interop::Vector2 *) &(_target->GetCharPosition (index))); } DllExport Interop::Vector2 Text3D_GetCharSize (Urho3D::Text3D *_target, unsigned int index) { return *((Interop::Vector2 *) &(_target->GetCharSize (index))); } DllExport Interop::Color Text3D_GetColor (Urho3D::Text3D *_target, enum Urho3D::Corner corner) { return *((Interop::Color *) &(_target->GetColor (corner))); } DllExport float Text3D_GetOpacity (Urho3D::Text3D *_target) { return _target->GetOpacity (); } DllExport int Text3D_IsFixedScreenSize (Urho3D::Text3D *_target) { return _target->IsFixedScreenSize (); } DllExport enum Urho3D::FaceCameraMode Text3D_GetFaceCameraMode (Urho3D::Text3D *_target) { return _target->GetFaceCameraMode (); } DllExport Urho3D::ResourceRef Text3D_GetFontAttr (Urho3D::Text3D *_target) { return _target->GetFontAttr (); } DllExport Urho3D::ResourceRef Text3D_GetMaterialAttr (Urho3D::Text3D *_target) { return _target->GetMaterialAttr (); } DllExport void Text3D_SetTextAttr (Urho3D::Text3D *_target, const char * value) { _target->SetTextAttr (Urho3D::String(value)); } DllExport const char * Text3D_GetTextAttr (Urho3D::Text3D *_target) { return stringdup((_target->GetTextAttr ()).CString ()); } DllExport Interop::Color Text3D_GetColorAttr (Urho3D::Text3D *_target) { return *((Interop::Color *) &(_target->GetColorAttr ())); } DllExport int ToolTip_GetType (Urho3D::ToolTip *_target) { return (_target->GetType ()).Value (); } DllExport const char * ToolTip_GetTypeName (Urho3D::ToolTip *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ToolTip_GetTypeStatic () { return (ToolTip::GetTypeStatic ()).Value (); } DllExport const char * ToolTip_GetTypeNameStatic () { return stringdup((ToolTip::GetTypeNameStatic ()).CString ()); } DllExport void * ToolTip_ToolTip (Urho3D::Context * context) { return WeakPtr<ToolTip>(new ToolTip(context)); } DllExport void ToolTip_RegisterObject (Urho3D::Context * context) { ToolTip::RegisterObject (context); } DllExport void ToolTip_Update (Urho3D::ToolTip *_target, float timeStep) { _target->Update (timeStep); } DllExport void ToolTip_SetDelay (Urho3D::ToolTip *_target, float delay) { _target->SetDelay (delay); } DllExport float ToolTip_GetDelay (Urho3D::ToolTip *_target) { return _target->GetDelay (); } DllExport int UI_GetType (Urho3D::UI *_target) { return (_target->GetType ()).Value (); } DllExport const char * UI_GetTypeName (Urho3D::UI *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int UI_GetTypeStatic () { return (UI::GetTypeStatic ()).Value (); } DllExport const char * UI_GetTypeNameStatic () { return stringdup((UI::GetTypeNameStatic ()).CString ()); } DllExport void * UI_UI (Urho3D::Context * context) { return WeakPtr<UI>(new UI(context)); } DllExport void UI_SetCursor (Urho3D::UI *_target, Urho3D::Cursor * cursor) { _target->SetCursor (cursor); } DllExport void UI_SetFocusElement (Urho3D::UI *_target, Urho3D::UIElement * element, bool byKey) { _target->SetFocusElement (element, byKey); } DllExport int UI_SetModalElement (Urho3D::UI *_target, Urho3D::UIElement * modalElement, bool enable) { return _target->SetModalElement (modalElement, enable); } DllExport void UI_Clear (Urho3D::UI *_target) { _target->Clear (); } DllExport void UI_Update (Urho3D::UI *_target, float timeStep) { _target->Update (timeStep); } DllExport void UI_RenderUpdate (Urho3D::UI *_target) { _target->RenderUpdate (); } DllExport void UI_Render (Urho3D::UI *_target, bool renderUICommand) { _target->Render (renderUICommand); } DllExport void UI_DebugDraw (Urho3D::UI *_target, Urho3D::UIElement * element) { _target->DebugDraw (element); } DllExport Urho3D::UIElement * UI_LoadLayout_File (Urho3D::UI *_target, File * source, Urho3D::XMLFile * styleFile) { auto copy = _target->LoadLayout (*source, styleFile); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::UIElement * UI_LoadLayout_MemoryBuffer (Urho3D::UI *_target, MemoryBuffer * source, Urho3D::XMLFile * styleFile) { auto copy = _target->LoadLayout (*source, styleFile); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::UIElement * UI_LoadLayout0 (Urho3D::UI *_target, Urho3D::XMLFile * file, Urho3D::XMLFile * styleFile) { auto copy = _target->LoadLayout (file, styleFile); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport int UI_SaveLayout_File (Urho3D::UI *_target, File * dest, Urho3D::UIElement * element) { return _target->SaveLayout (*dest, element); } DllExport int UI_SaveLayout_MemoryBuffer (Urho3D::UI *_target, MemoryBuffer * dest, Urho3D::UIElement * element) { return _target->SaveLayout (*dest, element); } DllExport void UI_SetClipboardText (Urho3D::UI *_target, const char * text) { _target->SetClipboardText (Urho3D::String(text)); } DllExport void UI_SetDoubleClickInterval (Urho3D::UI *_target, float interval) { _target->SetDoubleClickInterval (interval); } DllExport void UI_SetDragBeginInterval (Urho3D::UI *_target, float interval) { _target->SetDragBeginInterval (interval); } DllExport void UI_SetDragBeginDistance (Urho3D::UI *_target, int pixels) { _target->SetDragBeginDistance (pixels); } DllExport void UI_SetDefaultToolTipDelay (Urho3D::UI *_target, float delay) { _target->SetDefaultToolTipDelay (delay); } DllExport void UI_SetMaxFontTextureSize (Urho3D::UI *_target, int size) { _target->SetMaxFontTextureSize (size); } DllExport void UI_SetNonFocusedMouseWheel (Urho3D::UI *_target, bool nonFocusedMouseWheel) { _target->SetNonFocusedMouseWheel (nonFocusedMouseWheel); } DllExport void UI_SetUseSystemClipboard (Urho3D::UI *_target, bool enable) { _target->SetUseSystemClipboard (enable); } DllExport void UI_SetUseScreenKeyboard (Urho3D::UI *_target, bool enable) { _target->SetUseScreenKeyboard (enable); } DllExport void UI_SetUseMutableGlyphs (Urho3D::UI *_target, bool enable) { _target->SetUseMutableGlyphs (enable); } DllExport void UI_SetForceAutoHint (Urho3D::UI *_target, bool enable) { _target->SetForceAutoHint (enable); } DllExport void UI_SetFontHintLevel (Urho3D::UI *_target, enum Urho3D::FontHintLevel level) { _target->SetFontHintLevel (level); } DllExport void UI_SetFontSubpixelThreshold (Urho3D::UI *_target, float threshold) { _target->SetFontSubpixelThreshold (threshold); } DllExport void UI_SetFontOversampling (Urho3D::UI *_target, int oversampling) { _target->SetFontOversampling (oversampling); } DllExport void UI_SetScale (Urho3D::UI *_target, float scale) { _target->SetScale (scale); } DllExport void UI_SetWidth (Urho3D::UI *_target, float width) { _target->SetWidth (width); } DllExport void UI_SetHeight (Urho3D::UI *_target, float height) { _target->SetHeight (height); } DllExport void UI_SetCustomSize (Urho3D::UI *_target, const class Urho3D::IntVector2 & size) { _target->SetCustomSize (size); } DllExport void UI_SetCustomSize1 (Urho3D::UI *_target, int width, int height) { _target->SetCustomSize (width, height); } DllExport Urho3D::UIElement * UI_GetRoot (Urho3D::UI *_target) { return _target->GetRoot (); } DllExport Urho3D::UIElement * UI_GetRootModalElement (Urho3D::UI *_target) { return _target->GetRootModalElement (); } DllExport Urho3D::Cursor * UI_GetCursor (Urho3D::UI *_target) { return _target->GetCursor (); } DllExport Interop::IntVector2 UI_GetCursorPosition (Urho3D::UI *_target) { return *((Interop::IntVector2 *) &(_target->GetCursorPosition ())); } DllExport Urho3D::UIElement * UI_GetElementAt (Urho3D::UI *_target, const class Urho3D::IntVector2 & position, bool enabledOnly) { return _target->GetElementAt (position, enabledOnly); } DllExport Urho3D::UIElement * UI_GetElementAt2 (Urho3D::UI *_target, int x, int y, bool enabledOnly) { return _target->GetElementAt (x, y, enabledOnly); } DllExport Urho3D::UIElement * UI_GetElementAt3 (Urho3D::UI *_target, Urho3D::UIElement * root, const class Urho3D::IntVector2 & position, bool enabledOnly) { return _target->GetElementAt (root, position, enabledOnly); } DllExport Urho3D::UIElement * UI_GetFocusElement (Urho3D::UI *_target) { return _target->GetFocusElement (); } DllExport Urho3D::UIElement * UI_GetFrontElement (Urho3D::UI *_target) { return _target->GetFrontElement (); } DllExport unsigned int UI_GetNumDragElements (Urho3D::UI *_target) { return _target->GetNumDragElements (); } DllExport Urho3D::UIElement * UI_GetDragElement (Urho3D::UI *_target, unsigned int index) { return _target->GetDragElement (index); } DllExport const char * UI_GetClipboardText (Urho3D::UI *_target) { return stringdup((_target->GetClipboardText ()).CString ()); } DllExport float UI_GetDoubleClickInterval (Urho3D::UI *_target) { return _target->GetDoubleClickInterval (); } DllExport float UI_GetDragBeginInterval (Urho3D::UI *_target) { return _target->GetDragBeginInterval (); } DllExport int UI_GetDragBeginDistance (Urho3D::UI *_target) { return _target->GetDragBeginDistance (); } DllExport float UI_GetDefaultToolTipDelay (Urho3D::UI *_target) { return _target->GetDefaultToolTipDelay (); } DllExport int UI_GetMaxFontTextureSize (Urho3D::UI *_target) { return _target->GetMaxFontTextureSize (); } DllExport int UI_IsNonFocusedMouseWheel (Urho3D::UI *_target) { return _target->IsNonFocusedMouseWheel (); } DllExport int UI_GetUseSystemClipboard (Urho3D::UI *_target) { return _target->GetUseSystemClipboard (); } DllExport int UI_GetUseScreenKeyboard (Urho3D::UI *_target) { return _target->GetUseScreenKeyboard (); } DllExport int UI_GetUseMutableGlyphs (Urho3D::UI *_target) { return _target->GetUseMutableGlyphs (); } DllExport int UI_GetForceAutoHint (Urho3D::UI *_target) { return _target->GetForceAutoHint (); } DllExport enum Urho3D::FontHintLevel UI_GetFontHintLevel (Urho3D::UI *_target) { return _target->GetFontHintLevel (); } DllExport float UI_GetFontSubpixelThreshold (Urho3D::UI *_target) { return _target->GetFontSubpixelThreshold (); } DllExport int UI_GetFontOversampling (Urho3D::UI *_target) { return _target->GetFontOversampling (); } DllExport int UI_HasModalElement (Urho3D::UI *_target) { return _target->HasModalElement (); } DllExport int UI_IsDragging (Urho3D::UI *_target) { return _target->IsDragging (); } DllExport float UI_GetScale (Urho3D::UI *_target) { return _target->GetScale (); } DllExport Interop::IntVector2 UI_GetCustomSize (Urho3D::UI *_target) { return *((Interop::IntVector2 *) &(_target->GetCustomSize ())); } DllExport void UI_SetRenderToTexture (Urho3D::UI *_target, Urho3D::UIComponent * component, bool enable) { _target->SetRenderToTexture (component, enable); } DllExport int Window_GetType (Urho3D::Window *_target) { return (_target->GetType ()).Value (); } DllExport const char * Window_GetTypeName (Urho3D::Window *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Window_GetTypeStatic () { return (Window::GetTypeStatic ()).Value (); } DllExport const char * Window_GetTypeNameStatic () { return stringdup((Window::GetTypeNameStatic ()).CString ()); } DllExport void * Window_Window (Urho3D::Context * context) { return WeakPtr<Window>(new Window(context)); } DllExport void Window_RegisterObject (Urho3D::Context * context) { Window::RegisterObject (context); } DllExport void Window_OnHover (Urho3D::Window *_target, const class Urho3D::IntVector2 & position, const class Urho3D::IntVector2 & screenPosition, int buttons, int qualifiers, Urho3D::Cursor * cursor) { _target->OnHover (position, screenPosition, buttons, qualifiers, cursor); } DllExport void Window_SetMovable (Urho3D::Window *_target, bool enable) { _target->SetMovable (enable); } DllExport void Window_SetResizable (Urho3D::Window *_target, bool enable) { _target->SetResizable (enable); } DllExport void Window_SetFixedWidthResizing (Urho3D::Window *_target, bool enable) { _target->SetFixedWidthResizing (enable); } DllExport void Window_SetFixedHeightResizing (Urho3D::Window *_target, bool enable) { _target->SetFixedHeightResizing (enable); } DllExport void Window_SetResizeBorder (Urho3D::Window *_target, const class Urho3D::IntRect & rect) { _target->SetResizeBorder (rect); } DllExport void Window_SetModal (Urho3D::Window *_target, bool modal) { _target->SetModal (modal); } DllExport void Window_SetModalShadeColor (Urho3D::Window *_target, const class Urho3D::Color & color) { _target->SetModalShadeColor (color); } DllExport void Window_SetModalFrameColor (Urho3D::Window *_target, const class Urho3D::Color & color) { _target->SetModalFrameColor (color); } DllExport void Window_SetModalFrameSize (Urho3D::Window *_target, const class Urho3D::IntVector2 & size) { _target->SetModalFrameSize (size); } DllExport void Window_SetModalAutoDismiss (Urho3D::Window *_target, bool enable) { _target->SetModalAutoDismiss (enable); } DllExport int Window_IsMovable (Urho3D::Window *_target) { return _target->IsMovable (); } DllExport int Window_IsResizable (Urho3D::Window *_target) { return _target->IsResizable (); } DllExport int Window_GetFixedWidthResizing (Urho3D::Window *_target) { return _target->GetFixedWidthResizing (); } DllExport int Window_GetFixedHeightResizing (Urho3D::Window *_target) { return _target->GetFixedHeightResizing (); } DllExport Interop::IntRect Window_GetResizeBorder (Urho3D::Window *_target) { return *((Interop::IntRect *) &(_target->GetResizeBorder ())); } DllExport int Window_IsModal (Urho3D::Window *_target) { return _target->IsModal (); } DllExport Interop::Color Window_GetModalShadeColor (Urho3D::Window *_target) { return *((Interop::Color *) &(_target->GetModalShadeColor ())); } DllExport Interop::Color Window_GetModalFrameColor (Urho3D::Window *_target) { return *((Interop::Color *) &(_target->GetModalFrameColor ())); } DllExport Interop::IntVector2 Window_GetModalFrameSize (Urho3D::Window *_target) { return *((Interop::IntVector2 *) &(_target->GetModalFrameSize ())); } DllExport int Window_GetModalAutoDismiss (Urho3D::Window *_target) { return _target->GetModalAutoDismiss (); } DllExport int View3D_GetType (Urho3D::View3D *_target) { return (_target->GetType ()).Value (); } DllExport const char * View3D_GetTypeName (Urho3D::View3D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int View3D_GetTypeStatic () { return (View3D::GetTypeStatic ()).Value (); } DllExport const char * View3D_GetTypeNameStatic () { return stringdup((View3D::GetTypeNameStatic ()).CString ()); } DllExport void * View3D_View3D (Urho3D::Context * context) { return WeakPtr<View3D>(new View3D(context)); } DllExport void View3D_RegisterObject (Urho3D::Context * context) { View3D::RegisterObject (context); } DllExport void View3D_OnResize (Urho3D::View3D *_target, const class Urho3D::IntVector2 & newSize, const class Urho3D::IntVector2 & delta) { _target->OnResize (newSize, delta); } DllExport void View3D_SetView (Urho3D::View3D *_target, Urho3D::Scene * scene, Urho3D::Camera * camera, bool ownScene) { _target->SetView (scene, camera, ownScene); } DllExport void View3D_SetFormat (Urho3D::View3D *_target, unsigned int format) { _target->SetFormat (format); } DllExport void View3D_SetAutoUpdate (Urho3D::View3D *_target, bool enable) { _target->SetAutoUpdate (enable); } DllExport void View3D_QueueUpdate (Urho3D::View3D *_target) { _target->QueueUpdate (); } DllExport unsigned int View3D_GetFormat (Urho3D::View3D *_target) { return _target->GetFormat (); } DllExport int View3D_GetAutoUpdate (Urho3D::View3D *_target) { return _target->GetAutoUpdate (); } DllExport Urho3D::Scene * View3D_GetScene (Urho3D::View3D *_target) { return _target->GetScene (); } DllExport Urho3D::Node * View3D_GetCameraNode (Urho3D::View3D *_target) { return _target->GetCameraNode (); } DllExport Urho3D::Texture2D * View3D_GetRenderTexture (Urho3D::View3D *_target) { return _target->GetRenderTexture (); } DllExport Urho3D::Texture2D * View3D_GetDepthTexture (Urho3D::View3D *_target) { return _target->GetDepthTexture (); } DllExport Urho3D::Viewport * View3D_GetViewport (Urho3D::View3D *_target) { return _target->GetViewport (); } DllExport int Drawable2D_GetType (Urho3D::Drawable2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * Drawable2D_GetTypeName (Urho3D::Drawable2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Drawable2D_GetTypeStatic () { return (Drawable2D::GetTypeStatic ()).Value (); } DllExport const char * Drawable2D_GetTypeNameStatic () { return stringdup((Drawable2D::GetTypeNameStatic ()).CString ()); } DllExport void Drawable2D_RegisterObject (Urho3D::Context * context) { Drawable2D::RegisterObject (context); } DllExport void Drawable2D_OnSetEnabled (Urho3D::Drawable2D *_target) { _target->OnSetEnabled (); } DllExport void Drawable2D_SetLayer (Urho3D::Drawable2D *_target, int layer) { _target->SetLayer (layer); } DllExport void Drawable2D_SetOrderInLayer (Urho3D::Drawable2D *_target, int orderInLayer) { _target->SetOrderInLayer (orderInLayer); } DllExport int Drawable2D_GetLayer (Urho3D::Drawable2D *_target) { return _target->GetLayer (); } DllExport int Drawable2D_GetOrderInLayer (Urho3D::Drawable2D *_target) { return _target->GetOrderInLayer (); } DllExport int StaticSprite2D_GetType (Urho3D::StaticSprite2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * StaticSprite2D_GetTypeName (Urho3D::StaticSprite2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int StaticSprite2D_GetTypeStatic () { return (StaticSprite2D::GetTypeStatic ()).Value (); } DllExport const char * StaticSprite2D_GetTypeNameStatic () { return stringdup((StaticSprite2D::GetTypeNameStatic ()).CString ()); } DllExport void * StaticSprite2D_StaticSprite2D (Urho3D::Context * context) { return WeakPtr<StaticSprite2D>(new StaticSprite2D(context)); } DllExport void StaticSprite2D_RegisterObject (Urho3D::Context * context) { StaticSprite2D::RegisterObject (context); } DllExport void StaticSprite2D_SetSprite (Urho3D::StaticSprite2D *_target, Urho3D::Sprite2D * sprite) { _target->SetSprite (sprite); } DllExport void StaticSprite2D_SetBlendMode (Urho3D::StaticSprite2D *_target, enum Urho3D::BlendMode blendMode) { _target->SetBlendMode (blendMode); } DllExport void StaticSprite2D_SetFlip (Urho3D::StaticSprite2D *_target, bool flipX, bool flipY) { _target->SetFlip (flipX, flipY); } DllExport void StaticSprite2D_SetFlipX (Urho3D::StaticSprite2D *_target, bool flipX) { _target->SetFlipX (flipX); } DllExport void StaticSprite2D_SetFlipY (Urho3D::StaticSprite2D *_target, bool flipY) { _target->SetFlipY (flipY); } DllExport void StaticSprite2D_SetColor (Urho3D::StaticSprite2D *_target, const class Urho3D::Color & color) { _target->SetColor (color); } DllExport void StaticSprite2D_SetAlpha (Urho3D::StaticSprite2D *_target, float alpha) { _target->SetAlpha (alpha); } DllExport void StaticSprite2D_SetUseHotSpot (Urho3D::StaticSprite2D *_target, bool useHotSpot) { _target->SetUseHotSpot (useHotSpot); } DllExport void StaticSprite2D_SetUseDrawRect (Urho3D::StaticSprite2D *_target, bool useDrawRect) { _target->SetUseDrawRect (useDrawRect); } DllExport void StaticSprite2D_SetUseTextureRect (Urho3D::StaticSprite2D *_target, bool useTextureRect) { _target->SetUseTextureRect (useTextureRect); } DllExport void StaticSprite2D_SetHotSpot (Urho3D::StaticSprite2D *_target, const class Urho3D::Vector2 & hotspot) { _target->SetHotSpot (hotspot); } DllExport void StaticSprite2D_SetCustomMaterial (Urho3D::StaticSprite2D *_target, Urho3D::Material * customMaterial) { _target->SetCustomMaterial (customMaterial); } DllExport Urho3D::Sprite2D * StaticSprite2D_GetSprite (Urho3D::StaticSprite2D *_target) { return _target->GetSprite (); } DllExport enum Urho3D::BlendMode StaticSprite2D_GetBlendMode (Urho3D::StaticSprite2D *_target) { return _target->GetBlendMode (); } DllExport int StaticSprite2D_GetFlipX (Urho3D::StaticSprite2D *_target) { return _target->GetFlipX (); } DllExport int StaticSprite2D_GetFlipY (Urho3D::StaticSprite2D *_target) { return _target->GetFlipY (); } DllExport Interop::Color StaticSprite2D_GetColor (Urho3D::StaticSprite2D *_target) { return *((Interop::Color *) &(_target->GetColor ())); } DllExport float StaticSprite2D_GetAlpha (Urho3D::StaticSprite2D *_target) { return _target->GetAlpha (); } DllExport int StaticSprite2D_GetUseHotSpot (Urho3D::StaticSprite2D *_target) { return _target->GetUseHotSpot (); } DllExport int StaticSprite2D_GetUseDrawRect (Urho3D::StaticSprite2D *_target) { return _target->GetUseDrawRect (); } DllExport int StaticSprite2D_GetUseTextureRect (Urho3D::StaticSprite2D *_target) { return _target->GetUseTextureRect (); } DllExport Interop::Vector2 StaticSprite2D_GetHotSpot (Urho3D::StaticSprite2D *_target) { return *((Interop::Vector2 *) &(_target->GetHotSpot ())); } DllExport Urho3D::Material * StaticSprite2D_GetCustomMaterial (Urho3D::StaticSprite2D *_target) { return _target->GetCustomMaterial (); } DllExport Urho3D::ResourceRef StaticSprite2D_GetSpriteAttr (Urho3D::StaticSprite2D *_target) { return _target->GetSpriteAttr (); } DllExport Urho3D::ResourceRef StaticSprite2D_GetCustomMaterialAttr (Urho3D::StaticSprite2D *_target) { return _target->GetCustomMaterialAttr (); } DllExport int AnimatedSprite2D_GetType (Urho3D::AnimatedSprite2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * AnimatedSprite2D_GetTypeName (Urho3D::AnimatedSprite2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int AnimatedSprite2D_GetTypeStatic () { return (AnimatedSprite2D::GetTypeStatic ()).Value (); } DllExport const char * AnimatedSprite2D_GetTypeNameStatic () { return stringdup((AnimatedSprite2D::GetTypeNameStatic ()).CString ()); } DllExport void * AnimatedSprite2D_AnimatedSprite2D (Urho3D::Context * context) { return WeakPtr<AnimatedSprite2D>(new AnimatedSprite2D(context)); } DllExport void AnimatedSprite2D_RegisterObject (Urho3D::Context * context) { AnimatedSprite2D::RegisterObject (context); } DllExport void AnimatedSprite2D_OnSetEnabled (Urho3D::AnimatedSprite2D *_target) { _target->OnSetEnabled (); } DllExport void AnimatedSprite2D_SetAnimationSet (Urho3D::AnimatedSprite2D *_target, Urho3D::AnimationSet2D * animationSet) { _target->SetAnimationSet (animationSet); } DllExport void AnimatedSprite2D_SetEntity (Urho3D::AnimatedSprite2D *_target, const char * name) { _target->SetEntity (Urho3D::String(name)); } DllExport void AnimatedSprite2D_SetAnimation (Urho3D::AnimatedSprite2D *_target, const char * name, enum LoopMode2D loopMode) { _target->SetAnimation (Urho3D::String(name), loopMode); } DllExport void AnimatedSprite2D_SetLoopMode (Urho3D::AnimatedSprite2D *_target, enum LoopMode2D loopMode) { _target->SetLoopMode (loopMode); } DllExport void AnimatedSprite2D_SetSpeed (Urho3D::AnimatedSprite2D *_target, float speed) { _target->SetSpeed (speed); } DllExport Urho3D::AnimationSet2D * AnimatedSprite2D_GetAnimationSet (Urho3D::AnimatedSprite2D *_target) { return _target->GetAnimationSet (); } DllExport const char * AnimatedSprite2D_GetEntity (Urho3D::AnimatedSprite2D *_target) { return stringdup((_target->GetEntity ()).CString ()); } DllExport const char * AnimatedSprite2D_GetAnimation (Urho3D::AnimatedSprite2D *_target) { return stringdup((_target->GetAnimation ()).CString ()); } DllExport enum LoopMode2D AnimatedSprite2D_GetLoopMode (Urho3D::AnimatedSprite2D *_target) { return _target->GetLoopMode (); } DllExport float AnimatedSprite2D_GetSpeed (Urho3D::AnimatedSprite2D *_target) { return _target->GetSpeed (); } DllExport Urho3D::ResourceRef AnimatedSprite2D_GetAnimationSetAttr (Urho3D::AnimatedSprite2D *_target) { return _target->GetAnimationSetAttr (); } DllExport void AnimatedSprite2D_SetAnimationAttr (Urho3D::AnimatedSprite2D *_target, const char * name) { _target->SetAnimationAttr (Urho3D::String(name)); } DllExport int AnimationSet2D_GetType (Urho3D::AnimationSet2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * AnimationSet2D_GetTypeName (Urho3D::AnimationSet2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int AnimationSet2D_GetTypeStatic () { return (AnimationSet2D::GetTypeStatic ()).Value (); } DllExport const char * AnimationSet2D_GetTypeNameStatic () { return stringdup((AnimationSet2D::GetTypeNameStatic ()).CString ()); } DllExport void * AnimationSet2D_AnimationSet2D (Urho3D::Context * context) { return WeakPtr<AnimationSet2D>(new AnimationSet2D(context)); } DllExport void AnimationSet2D_RegisterObject (Urho3D::Context * context) { AnimationSet2D::RegisterObject (context); } DllExport int AnimationSet2D_BeginLoad_File (Urho3D::AnimationSet2D *_target, File * source) { return _target->BeginLoad (*source); } DllExport int AnimationSet2D_BeginLoad_MemoryBuffer (Urho3D::AnimationSet2D *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int AnimationSet2D_EndLoad (Urho3D::AnimationSet2D *_target) { return _target->EndLoad (); } DllExport unsigned int AnimationSet2D_GetNumAnimations (Urho3D::AnimationSet2D *_target) { return _target->GetNumAnimations (); } DllExport const char * AnimationSet2D_GetAnimation (Urho3D::AnimationSet2D *_target, unsigned int index) { return stringdup((_target->GetAnimation (index)).CString ()); } DllExport int AnimationSet2D_HasAnimation (Urho3D::AnimationSet2D *_target, const char * animation) { return _target->HasAnimation (Urho3D::String(animation)); } DllExport Urho3D::Sprite2D * AnimationSet2D_GetSprite (Urho3D::AnimationSet2D *_target) { return _target->GetSprite (); } DllExport Urho3D::Sprite2D * AnimationSet2D_GetSpriterFileSprite (Urho3D::AnimationSet2D *_target, int folderId, int fileId) { return _target->GetSpriterFileSprite (folderId, fileId); } DllExport int CollisionShape2D_GetType (Urho3D::CollisionShape2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * CollisionShape2D_GetTypeName (Urho3D::CollisionShape2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CollisionShape2D_GetTypeStatic () { return (CollisionShape2D::GetTypeStatic ()).Value (); } DllExport const char * CollisionShape2D_GetTypeNameStatic () { return stringdup((CollisionShape2D::GetTypeNameStatic ()).CString ()); } DllExport void CollisionShape2D_RegisterObject (Urho3D::Context * context) { CollisionShape2D::RegisterObject (context); } DllExport void CollisionShape2D_OnSetEnabled (Urho3D::CollisionShape2D *_target) { _target->OnSetEnabled (); } DllExport void CollisionShape2D_SetTrigger (Urho3D::CollisionShape2D *_target, bool trigger) { _target->SetTrigger (trigger); } DllExport void CollisionShape2D_SetCategoryBits (Urho3D::CollisionShape2D *_target, int categoryBits) { _target->SetCategoryBits (categoryBits); } DllExport void CollisionShape2D_SetMaskBits (Urho3D::CollisionShape2D *_target, int maskBits) { _target->SetMaskBits (maskBits); } DllExport void CollisionShape2D_SetGroupIndex (Urho3D::CollisionShape2D *_target, int groupIndex) { _target->SetGroupIndex (groupIndex); } DllExport void CollisionShape2D_SetDensity (Urho3D::CollisionShape2D *_target, float density) { _target->SetDensity (density); } DllExport void CollisionShape2D_SetFriction (Urho3D::CollisionShape2D *_target, float friction) { _target->SetFriction (friction); } DllExport void CollisionShape2D_SetRestitution (Urho3D::CollisionShape2D *_target, float restitution) { _target->SetRestitution (restitution); } DllExport void CollisionShape2D_CreateFixture (Urho3D::CollisionShape2D *_target) { _target->CreateFixture (); } DllExport void CollisionShape2D_ReleaseFixture (Urho3D::CollisionShape2D *_target) { _target->ReleaseFixture (); } DllExport int CollisionShape2D_IsTrigger (Urho3D::CollisionShape2D *_target) { return _target->IsTrigger (); } DllExport int CollisionShape2D_GetCategoryBits (Urho3D::CollisionShape2D *_target) { return _target->GetCategoryBits (); } DllExport int CollisionShape2D_GetMaskBits (Urho3D::CollisionShape2D *_target) { return _target->GetMaskBits (); } DllExport int CollisionShape2D_GetGroupIndex (Urho3D::CollisionShape2D *_target) { return _target->GetGroupIndex (); } DllExport float CollisionShape2D_GetDensity (Urho3D::CollisionShape2D *_target) { return _target->GetDensity (); } DllExport float CollisionShape2D_GetFriction (Urho3D::CollisionShape2D *_target) { return _target->GetFriction (); } DllExport float CollisionShape2D_GetRestitution (Urho3D::CollisionShape2D *_target) { return _target->GetRestitution (); } DllExport float CollisionShape2D_GetMass (Urho3D::CollisionShape2D *_target) { return _target->GetMass (); } DllExport float CollisionShape2D_GetInertia (Urho3D::CollisionShape2D *_target) { return _target->GetInertia (); } DllExport Interop::Vector2 CollisionShape2D_GetMassCenter (Urho3D::CollisionShape2D *_target) { return *((Interop::Vector2 *) &(_target->GetMassCenter ())); } DllExport int CollisionBox2D_GetType (Urho3D::CollisionBox2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * CollisionBox2D_GetTypeName (Urho3D::CollisionBox2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CollisionBox2D_GetTypeStatic () { return (CollisionBox2D::GetTypeStatic ()).Value (); } DllExport const char * CollisionBox2D_GetTypeNameStatic () { return stringdup((CollisionBox2D::GetTypeNameStatic ()).CString ()); } DllExport void * CollisionBox2D_CollisionBox2D (Urho3D::Context * context) { return WeakPtr<CollisionBox2D>(new CollisionBox2D(context)); } DllExport void CollisionBox2D_RegisterObject (Urho3D::Context * context) { CollisionBox2D::RegisterObject (context); } DllExport void CollisionBox2D_SetSize (Urho3D::CollisionBox2D *_target, const class Urho3D::Vector2 & size) { _target->SetSize (size); } DllExport void CollisionBox2D_SetSize0 (Urho3D::CollisionBox2D *_target, float width, float height) { _target->SetSize (width, height); } DllExport void CollisionBox2D_SetCenter (Urho3D::CollisionBox2D *_target, const class Urho3D::Vector2 & center) { _target->SetCenter (center); } DllExport void CollisionBox2D_SetCenter1 (Urho3D::CollisionBox2D *_target, float x, float y) { _target->SetCenter (x, y); } DllExport void CollisionBox2D_SetAngle (Urho3D::CollisionBox2D *_target, float angle) { _target->SetAngle (angle); } DllExport Interop::Vector2 CollisionBox2D_GetSize (Urho3D::CollisionBox2D *_target) { return *((Interop::Vector2 *) &(_target->GetSize ())); } DllExport Interop::Vector2 CollisionBox2D_GetCenter (Urho3D::CollisionBox2D *_target) { return *((Interop::Vector2 *) &(_target->GetCenter ())); } DllExport float CollisionBox2D_GetAngle (Urho3D::CollisionBox2D *_target) { return _target->GetAngle (); } DllExport int CollisionChain2D_GetType (Urho3D::CollisionChain2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * CollisionChain2D_GetTypeName (Urho3D::CollisionChain2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CollisionChain2D_GetTypeStatic () { return (CollisionChain2D::GetTypeStatic ()).Value (); } DllExport const char * CollisionChain2D_GetTypeNameStatic () { return stringdup((CollisionChain2D::GetTypeNameStatic ()).CString ()); } DllExport void * CollisionChain2D_CollisionChain2D (Urho3D::Context * context) { return WeakPtr<CollisionChain2D>(new CollisionChain2D(context)); } DllExport void CollisionChain2D_RegisterObject (Urho3D::Context * context) { CollisionChain2D::RegisterObject (context); } DllExport void CollisionChain2D_SetLoop (Urho3D::CollisionChain2D *_target, bool loop) { _target->SetLoop (loop); } DllExport void CollisionChain2D_SetVertexCount (Urho3D::CollisionChain2D *_target, unsigned int count) { _target->SetVertexCount (count); } DllExport void CollisionChain2D_SetVertex (Urho3D::CollisionChain2D *_target, unsigned int index, const class Urho3D::Vector2 & vertex) { _target->SetVertex (index, vertex); } DllExport int CollisionChain2D_GetLoop (Urho3D::CollisionChain2D *_target) { return _target->GetLoop (); } DllExport unsigned int CollisionChain2D_GetVertexCount (Urho3D::CollisionChain2D *_target) { return _target->GetVertexCount (); } DllExport Interop::Vector2 CollisionChain2D_GetVertex (Urho3D::CollisionChain2D *_target, unsigned int index) { return *((Interop::Vector2 *) &(_target->GetVertex (index))); } DllExport int CollisionCircle2D_GetType (Urho3D::CollisionCircle2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * CollisionCircle2D_GetTypeName (Urho3D::CollisionCircle2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CollisionCircle2D_GetTypeStatic () { return (CollisionCircle2D::GetTypeStatic ()).Value (); } DllExport const char * CollisionCircle2D_GetTypeNameStatic () { return stringdup((CollisionCircle2D::GetTypeNameStatic ()).CString ()); } DllExport void * CollisionCircle2D_CollisionCircle2D (Urho3D::Context * context) { return WeakPtr<CollisionCircle2D>(new CollisionCircle2D(context)); } DllExport void CollisionCircle2D_RegisterObject (Urho3D::Context * context) { CollisionCircle2D::RegisterObject (context); } DllExport void CollisionCircle2D_SetRadius (Urho3D::CollisionCircle2D *_target, float radius) { _target->SetRadius (radius); } DllExport void CollisionCircle2D_SetCenter (Urho3D::CollisionCircle2D *_target, const class Urho3D::Vector2 & center) { _target->SetCenter (center); } DllExport void CollisionCircle2D_SetCenter0 (Urho3D::CollisionCircle2D *_target, float x, float y) { _target->SetCenter (x, y); } DllExport float CollisionCircle2D_GetRadius (Urho3D::CollisionCircle2D *_target) { return _target->GetRadius (); } DllExport Interop::Vector2 CollisionCircle2D_GetCenter (Urho3D::CollisionCircle2D *_target) { return *((Interop::Vector2 *) &(_target->GetCenter ())); } DllExport int CollisionEdge2D_GetType (Urho3D::CollisionEdge2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * CollisionEdge2D_GetTypeName (Urho3D::CollisionEdge2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CollisionEdge2D_GetTypeStatic () { return (CollisionEdge2D::GetTypeStatic ()).Value (); } DllExport const char * CollisionEdge2D_GetTypeNameStatic () { return stringdup((CollisionEdge2D::GetTypeNameStatic ()).CString ()); } DllExport void * CollisionEdge2D_CollisionEdge2D (Urho3D::Context * context) { return WeakPtr<CollisionEdge2D>(new CollisionEdge2D(context)); } DllExport void CollisionEdge2D_RegisterObject (Urho3D::Context * context) { CollisionEdge2D::RegisterObject (context); } DllExport void CollisionEdge2D_SetVertex1 (Urho3D::CollisionEdge2D *_target, const class Urho3D::Vector2 & vertex) { _target->SetVertex1 (vertex); } DllExport void CollisionEdge2D_SetVertex2 (Urho3D::CollisionEdge2D *_target, const class Urho3D::Vector2 & vertex) { _target->SetVertex2 (vertex); } DllExport void CollisionEdge2D_SetVertices (Urho3D::CollisionEdge2D *_target, const class Urho3D::Vector2 & vertex1, const class Urho3D::Vector2 & vertex2) { _target->SetVertices (vertex1, vertex2); } DllExport Interop::Vector2 CollisionEdge2D_GetVertex1 (Urho3D::CollisionEdge2D *_target) { return *((Interop::Vector2 *) &(_target->GetVertex1 ())); } DllExport Interop::Vector2 CollisionEdge2D_GetVertex2 (Urho3D::CollisionEdge2D *_target) { return *((Interop::Vector2 *) &(_target->GetVertex2 ())); } DllExport int CollisionPolygon2D_GetType (Urho3D::CollisionPolygon2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * CollisionPolygon2D_GetTypeName (Urho3D::CollisionPolygon2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int CollisionPolygon2D_GetTypeStatic () { return (CollisionPolygon2D::GetTypeStatic ()).Value (); } DllExport const char * CollisionPolygon2D_GetTypeNameStatic () { return stringdup((CollisionPolygon2D::GetTypeNameStatic ()).CString ()); } DllExport void * CollisionPolygon2D_CollisionPolygon2D (Urho3D::Context * context) { return WeakPtr<CollisionPolygon2D>(new CollisionPolygon2D(context)); } DllExport void CollisionPolygon2D_RegisterObject (Urho3D::Context * context) { CollisionPolygon2D::RegisterObject (context); } DllExport void CollisionPolygon2D_SetVertexCount (Urho3D::CollisionPolygon2D *_target, unsigned int count) { _target->SetVertexCount (count); } DllExport void CollisionPolygon2D_SetVertex (Urho3D::CollisionPolygon2D *_target, unsigned int index, const class Urho3D::Vector2 & vertex) { _target->SetVertex (index, vertex); } DllExport unsigned int CollisionPolygon2D_GetVertexCount (Urho3D::CollisionPolygon2D *_target) { return _target->GetVertexCount (); } DllExport Interop::Vector2 CollisionPolygon2D_GetVertex (Urho3D::CollisionPolygon2D *_target, unsigned int index) { return *((Interop::Vector2 *) &(_target->GetVertex (index))); } DllExport int Constraint2D_GetType (Urho3D::Constraint2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * Constraint2D_GetTypeName (Urho3D::Constraint2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Constraint2D_GetTypeStatic () { return (Constraint2D::GetTypeStatic ()).Value (); } DllExport const char * Constraint2D_GetTypeNameStatic () { return stringdup((Constraint2D::GetTypeNameStatic ()).CString ()); } DllExport void * Constraint2D_Constraint2D (Urho3D::Context * context) { return WeakPtr<Constraint2D>(new Constraint2D(context)); } DllExport void Constraint2D_RegisterObject (Urho3D::Context * context) { Constraint2D::RegisterObject (context); } DllExport void Constraint2D_ApplyAttributes (Urho3D::Constraint2D *_target) { _target->ApplyAttributes (); } DllExport void Constraint2D_OnSetEnabled (Urho3D::Constraint2D *_target) { _target->OnSetEnabled (); } DllExport void Constraint2D_CreateJoint (Urho3D::Constraint2D *_target) { _target->CreateJoint (); } DllExport void Constraint2D_ReleaseJoint (Urho3D::Constraint2D *_target) { _target->ReleaseJoint (); } DllExport void Constraint2D_SetOtherBody (Urho3D::Constraint2D *_target, Urho3D::RigidBody2D * body) { _target->SetOtherBody (body); } DllExport void Constraint2D_SetCollideConnected (Urho3D::Constraint2D *_target, bool collideConnected) { _target->SetCollideConnected (collideConnected); } DllExport void Constraint2D_SetAttachedConstraint (Urho3D::Constraint2D *_target, Urho3D::Constraint2D * constraint) { _target->SetAttachedConstraint (constraint); } DllExport Urho3D::RigidBody2D * Constraint2D_GetOwnerBody (Urho3D::Constraint2D *_target) { return _target->GetOwnerBody (); } DllExport Urho3D::RigidBody2D * Constraint2D_GetOtherBody (Urho3D::Constraint2D *_target) { return _target->GetOtherBody (); } DllExport int Constraint2D_GetCollideConnected (Urho3D::Constraint2D *_target) { return _target->GetCollideConnected (); } DllExport Urho3D::Constraint2D * Constraint2D_GetAttachedConstraint (Urho3D::Constraint2D *_target) { return _target->GetAttachedConstraint (); } DllExport int ConstraintDistance2D_GetType (Urho3D::ConstraintDistance2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintDistance2D_GetTypeName (Urho3D::ConstraintDistance2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintDistance2D_GetTypeStatic () { return (ConstraintDistance2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintDistance2D_GetTypeNameStatic () { return stringdup((ConstraintDistance2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintDistance2D_ConstraintDistance2D (Urho3D::Context * context) { return WeakPtr<ConstraintDistance2D>(new ConstraintDistance2D(context)); } DllExport void ConstraintDistance2D_RegisterObject (Urho3D::Context * context) { ConstraintDistance2D::RegisterObject (context); } DllExport void ConstraintDistance2D_SetOwnerBodyAnchor (Urho3D::ConstraintDistance2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetOwnerBodyAnchor (anchor); } DllExport void ConstraintDistance2D_SetOtherBodyAnchor (Urho3D::ConstraintDistance2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetOtherBodyAnchor (anchor); } DllExport void ConstraintDistance2D_SetFrequencyHz (Urho3D::ConstraintDistance2D *_target, float frequencyHz) { _target->SetFrequencyHz (frequencyHz); } DllExport void ConstraintDistance2D_SetDampingRatio (Urho3D::ConstraintDistance2D *_target, float dampingRatio) { _target->SetDampingRatio (dampingRatio); } DllExport void ConstraintDistance2D_SetLength (Urho3D::ConstraintDistance2D *_target, float length) { _target->SetLength (length); } DllExport Interop::Vector2 ConstraintDistance2D_GetOwnerBodyAnchor (Urho3D::ConstraintDistance2D *_target) { return *((Interop::Vector2 *) &(_target->GetOwnerBodyAnchor ())); } DllExport Interop::Vector2 ConstraintDistance2D_GetOtherBodyAnchor (Urho3D::ConstraintDistance2D *_target) { return *((Interop::Vector2 *) &(_target->GetOtherBodyAnchor ())); } DllExport float ConstraintDistance2D_GetFrequencyHz (Urho3D::ConstraintDistance2D *_target) { return _target->GetFrequencyHz (); } DllExport float ConstraintDistance2D_GetDampingRatio (Urho3D::ConstraintDistance2D *_target) { return _target->GetDampingRatio (); } DllExport float ConstraintDistance2D_GetLength (Urho3D::ConstraintDistance2D *_target) { return _target->GetLength (); } DllExport int ConstraintFriction2D_GetType (Urho3D::ConstraintFriction2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintFriction2D_GetTypeName (Urho3D::ConstraintFriction2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintFriction2D_GetTypeStatic () { return (ConstraintFriction2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintFriction2D_GetTypeNameStatic () { return stringdup((ConstraintFriction2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintFriction2D_ConstraintFriction2D (Urho3D::Context * context) { return WeakPtr<ConstraintFriction2D>(new ConstraintFriction2D(context)); } DllExport void ConstraintFriction2D_RegisterObject (Urho3D::Context * context) { ConstraintFriction2D::RegisterObject (context); } DllExport void ConstraintFriction2D_SetAnchor (Urho3D::ConstraintFriction2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetAnchor (anchor); } DllExport void ConstraintFriction2D_SetMaxForce (Urho3D::ConstraintFriction2D *_target, float maxForce) { _target->SetMaxForce (maxForce); } DllExport void ConstraintFriction2D_SetMaxTorque (Urho3D::ConstraintFriction2D *_target, float maxTorque) { _target->SetMaxTorque (maxTorque); } DllExport Interop::Vector2 ConstraintFriction2D_GetAnchor (Urho3D::ConstraintFriction2D *_target) { return *((Interop::Vector2 *) &(_target->GetAnchor ())); } DllExport float ConstraintFriction2D_GetMaxForce (Urho3D::ConstraintFriction2D *_target) { return _target->GetMaxForce (); } DllExport float ConstraintFriction2D_GetMaxTorque (Urho3D::ConstraintFriction2D *_target) { return _target->GetMaxTorque (); } DllExport int ConstraintGear2D_GetType (Urho3D::ConstraintGear2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintGear2D_GetTypeName (Urho3D::ConstraintGear2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintGear2D_GetTypeStatic () { return (ConstraintGear2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintGear2D_GetTypeNameStatic () { return stringdup((ConstraintGear2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintGear2D_ConstraintGear2D (Urho3D::Context * context) { return WeakPtr<ConstraintGear2D>(new ConstraintGear2D(context)); } DllExport void ConstraintGear2D_RegisterObject (Urho3D::Context * context) { ConstraintGear2D::RegisterObject (context); } DllExport void ConstraintGear2D_SetOwnerConstraint (Urho3D::ConstraintGear2D *_target, Urho3D::Constraint2D * constraint) { _target->SetOwnerConstraint (constraint); } DllExport void ConstraintGear2D_SetOtherConstraint (Urho3D::ConstraintGear2D *_target, Urho3D::Constraint2D * constraint) { _target->SetOtherConstraint (constraint); } DllExport void ConstraintGear2D_SetRatio (Urho3D::ConstraintGear2D *_target, float ratio) { _target->SetRatio (ratio); } DllExport Urho3D::Constraint2D * ConstraintGear2D_GetOwnerConstraint (Urho3D::ConstraintGear2D *_target) { return _target->GetOwnerConstraint (); } DllExport Urho3D::Constraint2D * ConstraintGear2D_GetOtherConstraint (Urho3D::ConstraintGear2D *_target) { return _target->GetOtherConstraint (); } DllExport float ConstraintGear2D_GetRatio (Urho3D::ConstraintGear2D *_target) { return _target->GetRatio (); } DllExport int ConstraintMotor2D_GetType (Urho3D::ConstraintMotor2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintMotor2D_GetTypeName (Urho3D::ConstraintMotor2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintMotor2D_GetTypeStatic () { return (ConstraintMotor2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintMotor2D_GetTypeNameStatic () { return stringdup((ConstraintMotor2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintMotor2D_ConstraintMotor2D (Urho3D::Context * context) { return WeakPtr<ConstraintMotor2D>(new ConstraintMotor2D(context)); } DllExport void ConstraintMotor2D_RegisterObject (Urho3D::Context * context) { ConstraintMotor2D::RegisterObject (context); } DllExport void ConstraintMotor2D_SetLinearOffset (Urho3D::ConstraintMotor2D *_target, const class Urho3D::Vector2 & linearOffset) { _target->SetLinearOffset (linearOffset); } DllExport void ConstraintMotor2D_SetAngularOffset (Urho3D::ConstraintMotor2D *_target, float angularOffset) { _target->SetAngularOffset (angularOffset); } DllExport void ConstraintMotor2D_SetMaxForce (Urho3D::ConstraintMotor2D *_target, float maxForce) { _target->SetMaxForce (maxForce); } DllExport void ConstraintMotor2D_SetMaxTorque (Urho3D::ConstraintMotor2D *_target, float maxTorque) { _target->SetMaxTorque (maxTorque); } DllExport void ConstraintMotor2D_SetCorrectionFactor (Urho3D::ConstraintMotor2D *_target, float correctionFactor) { _target->SetCorrectionFactor (correctionFactor); } DllExport Interop::Vector2 ConstraintMotor2D_GetLinearOffset (Urho3D::ConstraintMotor2D *_target) { return *((Interop::Vector2 *) &(_target->GetLinearOffset ())); } DllExport float ConstraintMotor2D_GetAngularOffset (Urho3D::ConstraintMotor2D *_target) { return _target->GetAngularOffset (); } DllExport float ConstraintMotor2D_GetMaxForce (Urho3D::ConstraintMotor2D *_target) { return _target->GetMaxForce (); } DllExport float ConstraintMotor2D_GetMaxTorque (Urho3D::ConstraintMotor2D *_target) { return _target->GetMaxTorque (); } DllExport float ConstraintMotor2D_GetCorrectionFactor (Urho3D::ConstraintMotor2D *_target) { return _target->GetCorrectionFactor (); } DllExport int ConstraintMouse2D_GetType (Urho3D::ConstraintMouse2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintMouse2D_GetTypeName (Urho3D::ConstraintMouse2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintMouse2D_GetTypeStatic () { return (ConstraintMouse2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintMouse2D_GetTypeNameStatic () { return stringdup((ConstraintMouse2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintMouse2D_ConstraintMouse2D (Urho3D::Context * context) { return WeakPtr<ConstraintMouse2D>(new ConstraintMouse2D(context)); } DllExport void ConstraintMouse2D_RegisterObject (Urho3D::Context * context) { ConstraintMouse2D::RegisterObject (context); } DllExport void ConstraintMouse2D_SetTarget (Urho3D::ConstraintMouse2D *_target, const class Urho3D::Vector2 & target) { _target->SetTarget (target); } DllExport void ConstraintMouse2D_SetMaxForce (Urho3D::ConstraintMouse2D *_target, float maxForce) { _target->SetMaxForce (maxForce); } DllExport void ConstraintMouse2D_SetFrequencyHz (Urho3D::ConstraintMouse2D *_target, float frequencyHz) { _target->SetFrequencyHz (frequencyHz); } DllExport void ConstraintMouse2D_SetDampingRatio (Urho3D::ConstraintMouse2D *_target, float dampingRatio) { _target->SetDampingRatio (dampingRatio); } DllExport Interop::Vector2 ConstraintMouse2D_GetTarget (Urho3D::ConstraintMouse2D *_target) { return *((Interop::Vector2 *) &(_target->GetTarget ())); } DllExport float ConstraintMouse2D_GetMaxForce (Urho3D::ConstraintMouse2D *_target) { return _target->GetMaxForce (); } DllExport float ConstraintMouse2D_GetFrequencyHz (Urho3D::ConstraintMouse2D *_target) { return _target->GetFrequencyHz (); } DllExport float ConstraintMouse2D_GetDampingRatio (Urho3D::ConstraintMouse2D *_target) { return _target->GetDampingRatio (); } DllExport int ConstraintPrismatic2D_GetType (Urho3D::ConstraintPrismatic2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintPrismatic2D_GetTypeName (Urho3D::ConstraintPrismatic2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintPrismatic2D_GetTypeStatic () { return (ConstraintPrismatic2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintPrismatic2D_GetTypeNameStatic () { return stringdup((ConstraintPrismatic2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintPrismatic2D_ConstraintPrismatic2D (Urho3D::Context * context) { return WeakPtr<ConstraintPrismatic2D>(new ConstraintPrismatic2D(context)); } DllExport void ConstraintPrismatic2D_RegisterObject (Urho3D::Context * context) { ConstraintPrismatic2D::RegisterObject (context); } DllExport void ConstraintPrismatic2D_SetAnchor (Urho3D::ConstraintPrismatic2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetAnchor (anchor); } DllExport void ConstraintPrismatic2D_SetAxis (Urho3D::ConstraintPrismatic2D *_target, const class Urho3D::Vector2 & axis) { _target->SetAxis (axis); } DllExport void ConstraintPrismatic2D_SetEnableLimit (Urho3D::ConstraintPrismatic2D *_target, bool enableLimit) { _target->SetEnableLimit (enableLimit); } DllExport void ConstraintPrismatic2D_SetLowerTranslation (Urho3D::ConstraintPrismatic2D *_target, float lowerTranslation) { _target->SetLowerTranslation (lowerTranslation); } DllExport void ConstraintPrismatic2D_SetUpperTranslation (Urho3D::ConstraintPrismatic2D *_target, float upperTranslation) { _target->SetUpperTranslation (upperTranslation); } DllExport void ConstraintPrismatic2D_SetEnableMotor (Urho3D::ConstraintPrismatic2D *_target, bool enableMotor) { _target->SetEnableMotor (enableMotor); } DllExport void ConstraintPrismatic2D_SetMaxMotorForce (Urho3D::ConstraintPrismatic2D *_target, float maxMotorForce) { _target->SetMaxMotorForce (maxMotorForce); } DllExport void ConstraintPrismatic2D_SetMotorSpeed (Urho3D::ConstraintPrismatic2D *_target, float motorSpeed) { _target->SetMotorSpeed (motorSpeed); } DllExport Interop::Vector2 ConstraintPrismatic2D_GetAnchor (Urho3D::ConstraintPrismatic2D *_target) { return *((Interop::Vector2 *) &(_target->GetAnchor ())); } DllExport Interop::Vector2 ConstraintPrismatic2D_GetAxis (Urho3D::ConstraintPrismatic2D *_target) { return *((Interop::Vector2 *) &(_target->GetAxis ())); } DllExport int ConstraintPrismatic2D_GetEnableLimit (Urho3D::ConstraintPrismatic2D *_target) { return _target->GetEnableLimit (); } DllExport float ConstraintPrismatic2D_GetLowerTranslation (Urho3D::ConstraintPrismatic2D *_target) { return _target->GetLowerTranslation (); } DllExport float ConstraintPrismatic2D_GetUpperTranslation (Urho3D::ConstraintPrismatic2D *_target) { return _target->GetUpperTranslation (); } DllExport int ConstraintPrismatic2D_GetEnableMotor (Urho3D::ConstraintPrismatic2D *_target) { return _target->GetEnableMotor (); } DllExport float ConstraintPrismatic2D_GetMaxMotorForce (Urho3D::ConstraintPrismatic2D *_target) { return _target->GetMaxMotorForce (); } DllExport float ConstraintPrismatic2D_GetMotorSpeed (Urho3D::ConstraintPrismatic2D *_target) { return _target->GetMotorSpeed (); } DllExport int ConstraintPulley2D_GetType (Urho3D::ConstraintPulley2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintPulley2D_GetTypeName (Urho3D::ConstraintPulley2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintPulley2D_GetTypeStatic () { return (ConstraintPulley2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintPulley2D_GetTypeNameStatic () { return stringdup((ConstraintPulley2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintPulley2D_ConstraintPulley2D (Urho3D::Context * context) { return WeakPtr<ConstraintPulley2D>(new ConstraintPulley2D(context)); } DllExport void ConstraintPulley2D_RegisterObject (Urho3D::Context * context) { ConstraintPulley2D::RegisterObject (context); } DllExport void ConstraintPulley2D_SetOwnerBodyGroundAnchor (Urho3D::ConstraintPulley2D *_target, const class Urho3D::Vector2 & groundAnchor) { _target->SetOwnerBodyGroundAnchor (groundAnchor); } DllExport void ConstraintPulley2D_SetOtherBodyGroundAnchor (Urho3D::ConstraintPulley2D *_target, const class Urho3D::Vector2 & groundAnchor) { _target->SetOtherBodyGroundAnchor (groundAnchor); } DllExport void ConstraintPulley2D_SetOwnerBodyAnchor (Urho3D::ConstraintPulley2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetOwnerBodyAnchor (anchor); } DllExport void ConstraintPulley2D_SetOtherBodyAnchor (Urho3D::ConstraintPulley2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetOtherBodyAnchor (anchor); } DllExport void ConstraintPulley2D_SetRatio (Urho3D::ConstraintPulley2D *_target, float ratio) { _target->SetRatio (ratio); } DllExport Interop::Vector2 ConstraintPulley2D_GetOwnerBodyGroundAnchor (Urho3D::ConstraintPulley2D *_target) { return *((Interop::Vector2 *) &(_target->GetOwnerBodyGroundAnchor ())); } DllExport Interop::Vector2 ConstraintPulley2D_GetOtherBodyGroundAnchor (Urho3D::ConstraintPulley2D *_target) { return *((Interop::Vector2 *) &(_target->GetOtherBodyGroundAnchor ())); } DllExport Interop::Vector2 ConstraintPulley2D_GetOwnerBodyAnchor (Urho3D::ConstraintPulley2D *_target) { return *((Interop::Vector2 *) &(_target->GetOwnerBodyAnchor ())); } DllExport Interop::Vector2 ConstraintPulley2D_GetOtherBodyAnchor (Urho3D::ConstraintPulley2D *_target) { return *((Interop::Vector2 *) &(_target->GetOtherBodyAnchor ())); } DllExport float ConstraintPulley2D_GetRatio (Urho3D::ConstraintPulley2D *_target) { return _target->GetRatio (); } DllExport int ConstraintRevolute2D_GetType (Urho3D::ConstraintRevolute2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintRevolute2D_GetTypeName (Urho3D::ConstraintRevolute2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintRevolute2D_GetTypeStatic () { return (ConstraintRevolute2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintRevolute2D_GetTypeNameStatic () { return stringdup((ConstraintRevolute2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintRevolute2D_ConstraintRevolute2D (Urho3D::Context * context) { return WeakPtr<ConstraintRevolute2D>(new ConstraintRevolute2D(context)); } DllExport void ConstraintRevolute2D_RegisterObject (Urho3D::Context * context) { ConstraintRevolute2D::RegisterObject (context); } DllExport void ConstraintRevolute2D_SetAnchor (Urho3D::ConstraintRevolute2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetAnchor (anchor); } DllExport void ConstraintRevolute2D_SetEnableLimit (Urho3D::ConstraintRevolute2D *_target, bool enableLimit) { _target->SetEnableLimit (enableLimit); } DllExport void ConstraintRevolute2D_SetLowerAngle (Urho3D::ConstraintRevolute2D *_target, float lowerAngle) { _target->SetLowerAngle (lowerAngle); } DllExport void ConstraintRevolute2D_SetUpperAngle (Urho3D::ConstraintRevolute2D *_target, float upperAngle) { _target->SetUpperAngle (upperAngle); } DllExport void ConstraintRevolute2D_SetEnableMotor (Urho3D::ConstraintRevolute2D *_target, bool enableMotor) { _target->SetEnableMotor (enableMotor); } DllExport void ConstraintRevolute2D_SetMotorSpeed (Urho3D::ConstraintRevolute2D *_target, float motorSpeed) { _target->SetMotorSpeed (motorSpeed); } DllExport void ConstraintRevolute2D_SetMaxMotorTorque (Urho3D::ConstraintRevolute2D *_target, float maxMotorTorque) { _target->SetMaxMotorTorque (maxMotorTorque); } DllExport Interop::Vector2 ConstraintRevolute2D_GetAnchor (Urho3D::ConstraintRevolute2D *_target) { return *((Interop::Vector2 *) &(_target->GetAnchor ())); } DllExport int ConstraintRevolute2D_GetEnableLimit (Urho3D::ConstraintRevolute2D *_target) { return _target->GetEnableLimit (); } DllExport float ConstraintRevolute2D_GetLowerAngle (Urho3D::ConstraintRevolute2D *_target) { return _target->GetLowerAngle (); } DllExport float ConstraintRevolute2D_GetUpperAngle (Urho3D::ConstraintRevolute2D *_target) { return _target->GetUpperAngle (); } DllExport int ConstraintRevolute2D_GetEnableMotor (Urho3D::ConstraintRevolute2D *_target) { return _target->GetEnableMotor (); } DllExport float ConstraintRevolute2D_GetMotorSpeed (Urho3D::ConstraintRevolute2D *_target) { return _target->GetMotorSpeed (); } DllExport float ConstraintRevolute2D_GetMaxMotorTorque (Urho3D::ConstraintRevolute2D *_target) { return _target->GetMaxMotorTorque (); } DllExport int ConstraintRope2D_GetType (Urho3D::ConstraintRope2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintRope2D_GetTypeName (Urho3D::ConstraintRope2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintRope2D_GetTypeStatic () { return (ConstraintRope2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintRope2D_GetTypeNameStatic () { return stringdup((ConstraintRope2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintRope2D_ConstraintRope2D (Urho3D::Context * context) { return WeakPtr<ConstraintRope2D>(new ConstraintRope2D(context)); } DllExport void ConstraintRope2D_RegisterObject (Urho3D::Context * context) { ConstraintRope2D::RegisterObject (context); } DllExport void ConstraintRope2D_SetOwnerBodyAnchor (Urho3D::ConstraintRope2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetOwnerBodyAnchor (anchor); } DllExport void ConstraintRope2D_SetOtherBodyAnchor (Urho3D::ConstraintRope2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetOtherBodyAnchor (anchor); } DllExport void ConstraintRope2D_SetMaxLength (Urho3D::ConstraintRope2D *_target, float maxLength) { _target->SetMaxLength (maxLength); } DllExport Interop::Vector2 ConstraintRope2D_GetOwnerBodyAnchor (Urho3D::ConstraintRope2D *_target) { return *((Interop::Vector2 *) &(_target->GetOwnerBodyAnchor ())); } DllExport Interop::Vector2 ConstraintRope2D_GetOtherBodyAnchor (Urho3D::ConstraintRope2D *_target) { return *((Interop::Vector2 *) &(_target->GetOtherBodyAnchor ())); } DllExport float ConstraintRope2D_GetMaxLength (Urho3D::ConstraintRope2D *_target) { return _target->GetMaxLength (); } DllExport int ConstraintWeld2D_GetType (Urho3D::ConstraintWeld2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintWeld2D_GetTypeName (Urho3D::ConstraintWeld2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintWeld2D_GetTypeStatic () { return (ConstraintWeld2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintWeld2D_GetTypeNameStatic () { return stringdup((ConstraintWeld2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintWeld2D_ConstraintWeld2D (Urho3D::Context * context) { return WeakPtr<ConstraintWeld2D>(new ConstraintWeld2D(context)); } DllExport void ConstraintWeld2D_RegisterObject (Urho3D::Context * context) { ConstraintWeld2D::RegisterObject (context); } DllExport void ConstraintWeld2D_SetAnchor (Urho3D::ConstraintWeld2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetAnchor (anchor); } DllExport void ConstraintWeld2D_SetFrequencyHz (Urho3D::ConstraintWeld2D *_target, float frequencyHz) { _target->SetFrequencyHz (frequencyHz); } DllExport void ConstraintWeld2D_SetDampingRatio (Urho3D::ConstraintWeld2D *_target, float dampingRatio) { _target->SetDampingRatio (dampingRatio); } DllExport Interop::Vector2 ConstraintWeld2D_GetAnchor (Urho3D::ConstraintWeld2D *_target) { return *((Interop::Vector2 *) &(_target->GetAnchor ())); } DllExport float ConstraintWeld2D_GetFrequencyHz (Urho3D::ConstraintWeld2D *_target) { return _target->GetFrequencyHz (); } DllExport float ConstraintWeld2D_GetDampingRatio (Urho3D::ConstraintWeld2D *_target) { return _target->GetDampingRatio (); } DllExport int ConstraintWheel2D_GetType (Urho3D::ConstraintWheel2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ConstraintWheel2D_GetTypeName (Urho3D::ConstraintWheel2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ConstraintWheel2D_GetTypeStatic () { return (ConstraintWheel2D::GetTypeStatic ()).Value (); } DllExport const char * ConstraintWheel2D_GetTypeNameStatic () { return stringdup((ConstraintWheel2D::GetTypeNameStatic ()).CString ()); } DllExport void * ConstraintWheel2D_ConstraintWheel2D (Urho3D::Context * context) { return WeakPtr<ConstraintWheel2D>(new ConstraintWheel2D(context)); } DllExport void ConstraintWheel2D_RegisterObject (Urho3D::Context * context) { ConstraintWheel2D::RegisterObject (context); } DllExport void ConstraintWheel2D_SetAnchor (Urho3D::ConstraintWheel2D *_target, const class Urho3D::Vector2 & anchor) { _target->SetAnchor (anchor); } DllExport void ConstraintWheel2D_SetAxis (Urho3D::ConstraintWheel2D *_target, const class Urho3D::Vector2 & axis) { _target->SetAxis (axis); } DllExport void ConstraintWheel2D_SetEnableMotor (Urho3D::ConstraintWheel2D *_target, bool enableMotor) { _target->SetEnableMotor (enableMotor); } DllExport void ConstraintWheel2D_SetMaxMotorTorque (Urho3D::ConstraintWheel2D *_target, float maxMotorTorque) { _target->SetMaxMotorTorque (maxMotorTorque); } DllExport void ConstraintWheel2D_SetMotorSpeed (Urho3D::ConstraintWheel2D *_target, float motorSpeed) { _target->SetMotorSpeed (motorSpeed); } DllExport void ConstraintWheel2D_SetFrequencyHz (Urho3D::ConstraintWheel2D *_target, float frequencyHz) { _target->SetFrequencyHz (frequencyHz); } DllExport void ConstraintWheel2D_SetDampingRatio (Urho3D::ConstraintWheel2D *_target, float dampingRatio) { _target->SetDampingRatio (dampingRatio); } DllExport Interop::Vector2 ConstraintWheel2D_GetAnchor (Urho3D::ConstraintWheel2D *_target) { return *((Interop::Vector2 *) &(_target->GetAnchor ())); } DllExport Interop::Vector2 ConstraintWheel2D_GetAxis (Urho3D::ConstraintWheel2D *_target) { return *((Interop::Vector2 *) &(_target->GetAxis ())); } DllExport int ConstraintWheel2D_GetEnableMotor (Urho3D::ConstraintWheel2D *_target) { return _target->GetEnableMotor (); } DllExport float ConstraintWheel2D_GetMaxMotorTorque (Urho3D::ConstraintWheel2D *_target) { return _target->GetMaxMotorTorque (); } DllExport float ConstraintWheel2D_GetMotorSpeed (Urho3D::ConstraintWheel2D *_target) { return _target->GetMotorSpeed (); } DllExport float ConstraintWheel2D_GetFrequencyHz (Urho3D::ConstraintWheel2D *_target) { return _target->GetFrequencyHz (); } DllExport float ConstraintWheel2D_GetDampingRatio (Urho3D::ConstraintWheel2D *_target) { return _target->GetDampingRatio (); } DllExport int ParticleEffect2D_GetType (Urho3D::ParticleEffect2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ParticleEffect2D_GetTypeName (Urho3D::ParticleEffect2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ParticleEffect2D_GetTypeStatic () { return (ParticleEffect2D::GetTypeStatic ()).Value (); } DllExport const char * ParticleEffect2D_GetTypeNameStatic () { return stringdup((ParticleEffect2D::GetTypeNameStatic ()).CString ()); } DllExport void * ParticleEffect2D_ParticleEffect2D (Urho3D::Context * context) { return WeakPtr<ParticleEffect2D>(new ParticleEffect2D(context)); } DllExport void ParticleEffect2D_RegisterObject (Urho3D::Context * context) { ParticleEffect2D::RegisterObject (context); } DllExport int ParticleEffect2D_BeginLoad_File (Urho3D::ParticleEffect2D *_target, File * source) { return _target->BeginLoad (*source); } DllExport int ParticleEffect2D_BeginLoad_MemoryBuffer (Urho3D::ParticleEffect2D *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int ParticleEffect2D_EndLoad (Urho3D::ParticleEffect2D *_target) { return _target->EndLoad (); } DllExport int ParticleEffect2D_Save_File (Urho3D::ParticleEffect2D *_target, File * dest) { return _target->Save (*dest); } DllExport int ParticleEffect2D_Save_MemoryBuffer (Urho3D::ParticleEffect2D *_target, MemoryBuffer * dest) { return _target->Save (*dest); } DllExport void ParticleEffect2D_SetSprite (Urho3D::ParticleEffect2D *_target, Urho3D::Sprite2D * sprite) { _target->SetSprite (sprite); } DllExport void ParticleEffect2D_SetSourcePositionVariance (Urho3D::ParticleEffect2D *_target, const class Urho3D::Vector2 & sourcePositionVariance) { _target->SetSourcePositionVariance (sourcePositionVariance); } DllExport void ParticleEffect2D_SetSpeed (Urho3D::ParticleEffect2D *_target, float speed) { _target->SetSpeed (speed); } DllExport void ParticleEffect2D_SetSpeedVariance (Urho3D::ParticleEffect2D *_target, float speedVariance) { _target->SetSpeedVariance (speedVariance); } DllExport void ParticleEffect2D_SetParticleLifeSpan (Urho3D::ParticleEffect2D *_target, float particleLifeSpan) { _target->SetParticleLifeSpan (particleLifeSpan); } DllExport void ParticleEffect2D_SetParticleLifespanVariance (Urho3D::ParticleEffect2D *_target, float particleLifespanVariance) { _target->SetParticleLifespanVariance (particleLifespanVariance); } DllExport void ParticleEffect2D_SetAngle (Urho3D::ParticleEffect2D *_target, float angle) { _target->SetAngle (angle); } DllExport void ParticleEffect2D_SetAngleVariance (Urho3D::ParticleEffect2D *_target, float angleVariance) { _target->SetAngleVariance (angleVariance); } DllExport void ParticleEffect2D_SetGravity (Urho3D::ParticleEffect2D *_target, const class Urho3D::Vector2 & gravity) { _target->SetGravity (gravity); } DllExport void ParticleEffect2D_SetRadialAcceleration (Urho3D::ParticleEffect2D *_target, float radialAcceleration) { _target->SetRadialAcceleration (radialAcceleration); } DllExport void ParticleEffect2D_SetTangentialAcceleration (Urho3D::ParticleEffect2D *_target, float tangentialAcceleration) { _target->SetTangentialAcceleration (tangentialAcceleration); } DllExport void ParticleEffect2D_SetRadialAccelVariance (Urho3D::ParticleEffect2D *_target, float radialAccelVariance) { _target->SetRadialAccelVariance (radialAccelVariance); } DllExport void ParticleEffect2D_SetTangentialAccelVariance (Urho3D::ParticleEffect2D *_target, float tangentialAccelVariance) { _target->SetTangentialAccelVariance (tangentialAccelVariance); } DllExport void ParticleEffect2D_SetStartColor (Urho3D::ParticleEffect2D *_target, const class Urho3D::Color & startColor) { _target->SetStartColor (startColor); } DllExport void ParticleEffect2D_SetStartColorVariance (Urho3D::ParticleEffect2D *_target, const class Urho3D::Color & startColorVariance) { _target->SetStartColorVariance (startColorVariance); } DllExport void ParticleEffect2D_SetFinishColor (Urho3D::ParticleEffect2D *_target, const class Urho3D::Color & finishColor) { _target->SetFinishColor (finishColor); } DllExport void ParticleEffect2D_SetFinishColorVariance (Urho3D::ParticleEffect2D *_target, const class Urho3D::Color & finishColorVariance) { _target->SetFinishColorVariance (finishColorVariance); } DllExport void ParticleEffect2D_SetMaxParticles (Urho3D::ParticleEffect2D *_target, int maxParticles) { _target->SetMaxParticles (maxParticles); } DllExport void ParticleEffect2D_SetStartParticleSize (Urho3D::ParticleEffect2D *_target, float startParticleSize) { _target->SetStartParticleSize (startParticleSize); } DllExport void ParticleEffect2D_SetStartParticleSizeVariance (Urho3D::ParticleEffect2D *_target, float startParticleSizeVariance) { _target->SetStartParticleSizeVariance (startParticleSizeVariance); } DllExport void ParticleEffect2D_SetFinishParticleSize (Urho3D::ParticleEffect2D *_target, float finishParticleSize) { _target->SetFinishParticleSize (finishParticleSize); } DllExport void ParticleEffect2D_SetFinishParticleSizeVariance (Urho3D::ParticleEffect2D *_target, float FinishParticleSizeVariance) { _target->SetFinishParticleSizeVariance (FinishParticleSizeVariance); } DllExport void ParticleEffect2D_SetDuration (Urho3D::ParticleEffect2D *_target, float duration) { _target->SetDuration (duration); } DllExport void ParticleEffect2D_SetEmitterType (Urho3D::ParticleEffect2D *_target, enum Urho3D::EmitterType2D emitterType) { _target->SetEmitterType (emitterType); } DllExport void ParticleEffect2D_SetMaxRadius (Urho3D::ParticleEffect2D *_target, float maxRadius) { _target->SetMaxRadius (maxRadius); } DllExport void ParticleEffect2D_SetMaxRadiusVariance (Urho3D::ParticleEffect2D *_target, float maxRadiusVariance) { _target->SetMaxRadiusVariance (maxRadiusVariance); } DllExport void ParticleEffect2D_SetMinRadius (Urho3D::ParticleEffect2D *_target, float minRadius) { _target->SetMinRadius (minRadius); } DllExport void ParticleEffect2D_SetMinRadiusVariance (Urho3D::ParticleEffect2D *_target, float minRadiusVariance) { _target->SetMinRadiusVariance (minRadiusVariance); } DllExport void ParticleEffect2D_SetRotatePerSecond (Urho3D::ParticleEffect2D *_target, float rotatePerSecond) { _target->SetRotatePerSecond (rotatePerSecond); } DllExport void ParticleEffect2D_SetRotatePerSecondVariance (Urho3D::ParticleEffect2D *_target, float rotatePerSecondVariance) { _target->SetRotatePerSecondVariance (rotatePerSecondVariance); } DllExport void ParticleEffect2D_SetBlendMode (Urho3D::ParticleEffect2D *_target, enum Urho3D::BlendMode blendMode) { _target->SetBlendMode (blendMode); } DllExport void ParticleEffect2D_SetRotationStart (Urho3D::ParticleEffect2D *_target, float rotationStart) { _target->SetRotationStart (rotationStart); } DllExport void ParticleEffect2D_SetRotationStartVariance (Urho3D::ParticleEffect2D *_target, float rotationStartVariance) { _target->SetRotationStartVariance (rotationStartVariance); } DllExport void ParticleEffect2D_SetRotationEnd (Urho3D::ParticleEffect2D *_target, float rotationEnd) { _target->SetRotationEnd (rotationEnd); } DllExport void ParticleEffect2D_SetRotationEndVariance (Urho3D::ParticleEffect2D *_target, float rotationEndVariance) { _target->SetRotationEndVariance (rotationEndVariance); } DllExport Urho3D::ParticleEffect2D * ParticleEffect2D_Clone (Urho3D::ParticleEffect2D *_target, const char * cloneName) { auto copy = _target->Clone (Urho3D::String(cloneName)); auto plain = copy.Get(); copy.Detach(); delete copy; return plain; } DllExport Urho3D::Sprite2D * ParticleEffect2D_GetSprite (Urho3D::ParticleEffect2D *_target) { return _target->GetSprite (); } DllExport Interop::Vector2 ParticleEffect2D_GetSourcePositionVariance (Urho3D::ParticleEffect2D *_target) { return *((Interop::Vector2 *) &(_target->GetSourcePositionVariance ())); } DllExport float ParticleEffect2D_GetSpeed (Urho3D::ParticleEffect2D *_target) { return _target->GetSpeed (); } DllExport float ParticleEffect2D_GetSpeedVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetSpeedVariance (); } DllExport float ParticleEffect2D_GetParticleLifeSpan (Urho3D::ParticleEffect2D *_target) { return _target->GetParticleLifeSpan (); } DllExport float ParticleEffect2D_GetParticleLifespanVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetParticleLifespanVariance (); } DllExport float ParticleEffect2D_GetAngle (Urho3D::ParticleEffect2D *_target) { return _target->GetAngle (); } DllExport float ParticleEffect2D_GetAngleVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetAngleVariance (); } DllExport Interop::Vector2 ParticleEffect2D_GetGravity (Urho3D::ParticleEffect2D *_target) { return *((Interop::Vector2 *) &(_target->GetGravity ())); } DllExport float ParticleEffect2D_GetRadialAcceleration (Urho3D::ParticleEffect2D *_target) { return _target->GetRadialAcceleration (); } DllExport float ParticleEffect2D_GetTangentialAcceleration (Urho3D::ParticleEffect2D *_target) { return _target->GetTangentialAcceleration (); } DllExport float ParticleEffect2D_GetRadialAccelVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetRadialAccelVariance (); } DllExport float ParticleEffect2D_GetTangentialAccelVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetTangentialAccelVariance (); } DllExport Interop::Color ParticleEffect2D_GetStartColor (Urho3D::ParticleEffect2D *_target) { return *((Interop::Color *) &(_target->GetStartColor ())); } DllExport Interop::Color ParticleEffect2D_GetStartColorVariance (Urho3D::ParticleEffect2D *_target) { return *((Interop::Color *) &(_target->GetStartColorVariance ())); } DllExport Interop::Color ParticleEffect2D_GetFinishColor (Urho3D::ParticleEffect2D *_target) { return *((Interop::Color *) &(_target->GetFinishColor ())); } DllExport Interop::Color ParticleEffect2D_GetFinishColorVariance (Urho3D::ParticleEffect2D *_target) { return *((Interop::Color *) &(_target->GetFinishColorVariance ())); } DllExport int ParticleEffect2D_GetMaxParticles (Urho3D::ParticleEffect2D *_target) { return _target->GetMaxParticles (); } DllExport float ParticleEffect2D_GetStartParticleSize (Urho3D::ParticleEffect2D *_target) { return _target->GetStartParticleSize (); } DllExport float ParticleEffect2D_GetStartParticleSizeVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetStartParticleSizeVariance (); } DllExport float ParticleEffect2D_GetFinishParticleSize (Urho3D::ParticleEffect2D *_target) { return _target->GetFinishParticleSize (); } DllExport float ParticleEffect2D_GetFinishParticleSizeVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetFinishParticleSizeVariance (); } DllExport float ParticleEffect2D_GetDuration (Urho3D::ParticleEffect2D *_target) { return _target->GetDuration (); } DllExport enum Urho3D::EmitterType2D ParticleEffect2D_GetEmitterType (Urho3D::ParticleEffect2D *_target) { return _target->GetEmitterType (); } DllExport float ParticleEffect2D_GetMaxRadius (Urho3D::ParticleEffect2D *_target) { return _target->GetMaxRadius (); } DllExport float ParticleEffect2D_GetMaxRadiusVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetMaxRadiusVariance (); } DllExport float ParticleEffect2D_GetMinRadius (Urho3D::ParticleEffect2D *_target) { return _target->GetMinRadius (); } DllExport float ParticleEffect2D_GetMinRadiusVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetMinRadiusVariance (); } DllExport float ParticleEffect2D_GetRotatePerSecond (Urho3D::ParticleEffect2D *_target) { return _target->GetRotatePerSecond (); } DllExport float ParticleEffect2D_GetRotatePerSecondVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetRotatePerSecondVariance (); } DllExport enum Urho3D::BlendMode ParticleEffect2D_GetBlendMode (Urho3D::ParticleEffect2D *_target) { return _target->GetBlendMode (); } DllExport float ParticleEffect2D_GetRotationStart (Urho3D::ParticleEffect2D *_target) { return _target->GetRotationStart (); } DllExport float ParticleEffect2D_GetRotationStartVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetRotationStartVariance (); } DllExport float ParticleEffect2D_GetRotationEnd (Urho3D::ParticleEffect2D *_target) { return _target->GetRotationEnd (); } DllExport float ParticleEffect2D_GetRotationEndVariance (Urho3D::ParticleEffect2D *_target) { return _target->GetRotationEndVariance (); } DllExport int ParticleEmitter2D_GetType (Urho3D::ParticleEmitter2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * ParticleEmitter2D_GetTypeName (Urho3D::ParticleEmitter2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int ParticleEmitter2D_GetTypeStatic () { return (ParticleEmitter2D::GetTypeStatic ()).Value (); } DllExport const char * ParticleEmitter2D_GetTypeNameStatic () { return stringdup((ParticleEmitter2D::GetTypeNameStatic ()).CString ()); } DllExport void * ParticleEmitter2D_ParticleEmitter2D (Urho3D::Context * context) { return WeakPtr<ParticleEmitter2D>(new ParticleEmitter2D(context)); } DllExport void ParticleEmitter2D_RegisterObject (Urho3D::Context * context) { ParticleEmitter2D::RegisterObject (context); } DllExport void ParticleEmitter2D_OnSetEnabled (Urho3D::ParticleEmitter2D *_target) { _target->OnSetEnabled (); } DllExport void ParticleEmitter2D_SetEffect (Urho3D::ParticleEmitter2D *_target, Urho3D::ParticleEffect2D * effect) { _target->SetEffect (effect); } DllExport void ParticleEmitter2D_SetSprite (Urho3D::ParticleEmitter2D *_target, Urho3D::Sprite2D * sprite) { _target->SetSprite (sprite); } DllExport void ParticleEmitter2D_SetBlendMode (Urho3D::ParticleEmitter2D *_target, enum Urho3D::BlendMode blendMode) { _target->SetBlendMode (blendMode); } DllExport void ParticleEmitter2D_SetMaxParticles (Urho3D::ParticleEmitter2D *_target, unsigned int maxParticles) { _target->SetMaxParticles (maxParticles); } DllExport void ParticleEmitter2D_SetEmitting (Urho3D::ParticleEmitter2D *_target, bool enable) { _target->SetEmitting (enable); } DllExport Urho3D::ParticleEffect2D * ParticleEmitter2D_GetEffect (Urho3D::ParticleEmitter2D *_target) { return _target->GetEffect (); } DllExport Urho3D::Sprite2D * ParticleEmitter2D_GetSprite (Urho3D::ParticleEmitter2D *_target) { return _target->GetSprite (); } DllExport enum Urho3D::BlendMode ParticleEmitter2D_GetBlendMode (Urho3D::ParticleEmitter2D *_target) { return _target->GetBlendMode (); } DllExport unsigned int ParticleEmitter2D_GetMaxParticles (Urho3D::ParticleEmitter2D *_target) { return _target->GetMaxParticles (); } DllExport Urho3D::ResourceRef ParticleEmitter2D_GetParticleEffectAttr (Urho3D::ParticleEmitter2D *_target) { return _target->GetParticleEffectAttr (); } DllExport Urho3D::ResourceRef ParticleEmitter2D_GetSpriteAttr (Urho3D::ParticleEmitter2D *_target) { return _target->GetSpriteAttr (); } DllExport int ParticleEmitter2D_IsEmitting (Urho3D::ParticleEmitter2D *_target) { return _target->IsEmitting (); } DllExport int PhysicsWorld2D_GetType (Urho3D::PhysicsWorld2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * PhysicsWorld2D_GetTypeName (Urho3D::PhysicsWorld2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int PhysicsWorld2D_GetTypeStatic () { return (PhysicsWorld2D::GetTypeStatic ()).Value (); } DllExport const char * PhysicsWorld2D_GetTypeNameStatic () { return stringdup((PhysicsWorld2D::GetTypeNameStatic ()).CString ()); } DllExport void * PhysicsWorld2D_PhysicsWorld2D (Urho3D::Context * context) { return WeakPtr<PhysicsWorld2D>(new PhysicsWorld2D(context)); } DllExport void PhysicsWorld2D_RegisterObject (Urho3D::Context * context) { PhysicsWorld2D::RegisterObject (context); } DllExport void PhysicsWorld2D_DrawDebugGeometry (Urho3D::PhysicsWorld2D *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void PhysicsWorld2D_Update (Urho3D::PhysicsWorld2D *_target, float timeStep) { _target->Update (timeStep); } DllExport void PhysicsWorld2D_DrawDebugGeometry0 (Urho3D::PhysicsWorld2D *_target) { _target->DrawDebugGeometry (); } DllExport void PhysicsWorld2D_SetUpdateEnabled (Urho3D::PhysicsWorld2D *_target, bool enable) { _target->SetUpdateEnabled (enable); } DllExport void PhysicsWorld2D_SetDrawShape (Urho3D::PhysicsWorld2D *_target, bool drawShape) { _target->SetDrawShape (drawShape); } DllExport void PhysicsWorld2D_SetDrawJoint (Urho3D::PhysicsWorld2D *_target, bool drawJoint) { _target->SetDrawJoint (drawJoint); } DllExport void PhysicsWorld2D_SetDrawAabb (Urho3D::PhysicsWorld2D *_target, bool drawAabb) { _target->SetDrawAabb (drawAabb); } DllExport void PhysicsWorld2D_SetDrawPair (Urho3D::PhysicsWorld2D *_target, bool drawPair) { _target->SetDrawPair (drawPair); } DllExport void PhysicsWorld2D_SetDrawCenterOfMass (Urho3D::PhysicsWorld2D *_target, bool drawCenterOfMass) { _target->SetDrawCenterOfMass (drawCenterOfMass); } DllExport void PhysicsWorld2D_SetAllowSleeping (Urho3D::PhysicsWorld2D *_target, bool enable) { _target->SetAllowSleeping (enable); } DllExport void PhysicsWorld2D_SetWarmStarting (Urho3D::PhysicsWorld2D *_target, bool enable) { _target->SetWarmStarting (enable); } DllExport void PhysicsWorld2D_SetContinuousPhysics (Urho3D::PhysicsWorld2D *_target, bool enable) { _target->SetContinuousPhysics (enable); } DllExport void PhysicsWorld2D_SetSubStepping (Urho3D::PhysicsWorld2D *_target, bool enable) { _target->SetSubStepping (enable); } DllExport void PhysicsWorld2D_SetGravity (Urho3D::PhysicsWorld2D *_target, const class Urho3D::Vector2 & gravity) { _target->SetGravity (gravity); } DllExport void PhysicsWorld2D_SetAutoClearForces (Urho3D::PhysicsWorld2D *_target, bool enable) { _target->SetAutoClearForces (enable); } DllExport void PhysicsWorld2D_SetVelocityIterations (Urho3D::PhysicsWorld2D *_target, int velocityIterations) { _target->SetVelocityIterations (velocityIterations); } DllExport void PhysicsWorld2D_SetPositionIterations (Urho3D::PhysicsWorld2D *_target, int positionIterations) { _target->SetPositionIterations (positionIterations); } DllExport void PhysicsWorld2D_AddRigidBody (Urho3D::PhysicsWorld2D *_target, Urho3D::RigidBody2D * rigidBody) { _target->AddRigidBody (rigidBody); } DllExport void PhysicsWorld2D_RemoveRigidBody (Urho3D::PhysicsWorld2D *_target, Urho3D::RigidBody2D * rigidBody) { _target->RemoveRigidBody (rigidBody); } DllExport Urho3D::RigidBody2D * PhysicsWorld2D_GetRigidBody (Urho3D::PhysicsWorld2D *_target, const class Urho3D::Vector2 & point, unsigned int collisionMask) { return _target->GetRigidBody (point, collisionMask); } DllExport Urho3D::RigidBody2D * PhysicsWorld2D_GetRigidBody1 (Urho3D::PhysicsWorld2D *_target, int screenX, int screenY, unsigned int collisionMask) { return _target->GetRigidBody (screenX, screenY, collisionMask); } DllExport int PhysicsWorld2D_IsUpdateEnabled (Urho3D::PhysicsWorld2D *_target) { return _target->IsUpdateEnabled (); } DllExport int PhysicsWorld2D_GetDrawShape (Urho3D::PhysicsWorld2D *_target) { return _target->GetDrawShape (); } DllExport int PhysicsWorld2D_GetDrawJoint (Urho3D::PhysicsWorld2D *_target) { return _target->GetDrawJoint (); } DllExport int PhysicsWorld2D_GetDrawAabb (Urho3D::PhysicsWorld2D *_target) { return _target->GetDrawAabb (); } DllExport int PhysicsWorld2D_GetDrawPair (Urho3D::PhysicsWorld2D *_target) { return _target->GetDrawPair (); } DllExport int PhysicsWorld2D_GetDrawCenterOfMass (Urho3D::PhysicsWorld2D *_target) { return _target->GetDrawCenterOfMass (); } DllExport int PhysicsWorld2D_GetAllowSleeping (Urho3D::PhysicsWorld2D *_target) { return _target->GetAllowSleeping (); } DllExport int PhysicsWorld2D_GetWarmStarting (Urho3D::PhysicsWorld2D *_target) { return _target->GetWarmStarting (); } DllExport int PhysicsWorld2D_GetContinuousPhysics (Urho3D::PhysicsWorld2D *_target) { return _target->GetContinuousPhysics (); } DllExport int PhysicsWorld2D_GetSubStepping (Urho3D::PhysicsWorld2D *_target) { return _target->GetSubStepping (); } DllExport int PhysicsWorld2D_GetAutoClearForces (Urho3D::PhysicsWorld2D *_target) { return _target->GetAutoClearForces (); } DllExport Interop::Vector2 PhysicsWorld2D_GetGravity (Urho3D::PhysicsWorld2D *_target) { return *((Interop::Vector2 *) &(_target->GetGravity ())); } DllExport int PhysicsWorld2D_GetVelocityIterations (Urho3D::PhysicsWorld2D *_target) { return _target->GetVelocityIterations (); } DllExport int PhysicsWorld2D_GetPositionIterations (Urho3D::PhysicsWorld2D *_target) { return _target->GetPositionIterations (); } DllExport void PhysicsWorld2D_SetApplyingTransforms (Urho3D::PhysicsWorld2D *_target, bool enable) { _target->SetApplyingTransforms (enable); } DllExport int PhysicsWorld2D_IsApplyingTransforms (Urho3D::PhysicsWorld2D *_target) { return _target->IsApplyingTransforms (); } DllExport int Renderer2D_GetType (Urho3D::Renderer2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * Renderer2D_GetTypeName (Urho3D::Renderer2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int Renderer2D_GetTypeStatic () { return (Renderer2D::GetTypeStatic ()).Value (); } DllExport const char * Renderer2D_GetTypeNameStatic () { return stringdup((Renderer2D::GetTypeNameStatic ()).CString ()); } DllExport void * Renderer2D_Renderer2D (Urho3D::Context * context) { return WeakPtr<Renderer2D>(new Renderer2D(context)); } DllExport void Renderer2D_RegisterObject (Urho3D::Context * context) { Renderer2D::RegisterObject (context); } DllExport enum Urho3D::UpdateGeometryType Renderer2D_GetUpdateGeometryType (Urho3D::Renderer2D *_target) { return _target->GetUpdateGeometryType (); } DllExport void Renderer2D_AddDrawable (Urho3D::Renderer2D *_target, Urho3D::Drawable2D * drawable) { _target->AddDrawable (drawable); } DllExport void Renderer2D_RemoveDrawable (Urho3D::Renderer2D *_target, Urho3D::Drawable2D * drawable) { _target->RemoveDrawable (drawable); } DllExport Urho3D::Material * Renderer2D_GetMaterial (Urho3D::Renderer2D *_target, Urho3D::Texture2D * texture, enum Urho3D::BlendMode blendMode) { return _target->GetMaterial (texture, blendMode); } DllExport int Renderer2D_CheckVisibility (Urho3D::Renderer2D *_target, Urho3D::Drawable2D * drawable) { return _target->CheckVisibility (drawable); } DllExport int RigidBody2D_GetType (Urho3D::RigidBody2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * RigidBody2D_GetTypeName (Urho3D::RigidBody2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int RigidBody2D_GetTypeStatic () { return (RigidBody2D::GetTypeStatic ()).Value (); } DllExport const char * RigidBody2D_GetTypeNameStatic () { return stringdup((RigidBody2D::GetTypeNameStatic ()).CString ()); } DllExport void * RigidBody2D_RigidBody2D (Urho3D::Context * context) { return WeakPtr<RigidBody2D>(new RigidBody2D(context)); } DllExport void RigidBody2D_RegisterObject (Urho3D::Context * context) { RigidBody2D::RegisterObject (context); } DllExport void RigidBody2D_OnSetEnabled (Urho3D::RigidBody2D *_target) { _target->OnSetEnabled (); } DllExport void RigidBody2D_SetBodyType (Urho3D::RigidBody2D *_target, enum Urho3D::BodyType2D bodyType) { _target->SetBodyType (bodyType); } DllExport void RigidBody2D_SetMass (Urho3D::RigidBody2D *_target, float mass) { _target->SetMass (mass); } DllExport void RigidBody2D_SetInertia (Urho3D::RigidBody2D *_target, float inertia) { _target->SetInertia (inertia); } DllExport void RigidBody2D_SetMassCenter (Urho3D::RigidBody2D *_target, const class Urho3D::Vector2 & center) { _target->SetMassCenter (center); } DllExport void RigidBody2D_SetUseFixtureMass (Urho3D::RigidBody2D *_target, bool useFixtureMass) { _target->SetUseFixtureMass (useFixtureMass); } DllExport void RigidBody2D_SetLinearDamping (Urho3D::RigidBody2D *_target, float linearDamping) { _target->SetLinearDamping (linearDamping); } DllExport void RigidBody2D_SetAngularDamping (Urho3D::RigidBody2D *_target, float angularDamping) { _target->SetAngularDamping (angularDamping); } DllExport void RigidBody2D_SetAllowSleep (Urho3D::RigidBody2D *_target, bool allowSleep) { _target->SetAllowSleep (allowSleep); } DllExport void RigidBody2D_SetFixedRotation (Urho3D::RigidBody2D *_target, bool fixedRotation) { _target->SetFixedRotation (fixedRotation); } DllExport void RigidBody2D_SetBullet (Urho3D::RigidBody2D *_target, bool bullet) { _target->SetBullet (bullet); } DllExport void RigidBody2D_SetGravityScale (Urho3D::RigidBody2D *_target, float gravityScale) { _target->SetGravityScale (gravityScale); } DllExport void RigidBody2D_SetAwake (Urho3D::RigidBody2D *_target, bool awake) { _target->SetAwake (awake); } DllExport void RigidBody2D_SetLinearVelocity (Urho3D::RigidBody2D *_target, const class Urho3D::Vector2 & linearVelocity) { _target->SetLinearVelocity (linearVelocity); } DllExport void RigidBody2D_SetAngularVelocity (Urho3D::RigidBody2D *_target, float angularVelocity) { _target->SetAngularVelocity (angularVelocity); } DllExport void RigidBody2D_ApplyForce (Urho3D::RigidBody2D *_target, const class Urho3D::Vector2 & force, const class Urho3D::Vector2 & point, bool wake) { _target->ApplyForce (force, point, wake); } DllExport void RigidBody2D_ApplyForceToCenter (Urho3D::RigidBody2D *_target, const class Urho3D::Vector2 & force, bool wake) { _target->ApplyForceToCenter (force, wake); } DllExport void RigidBody2D_ApplyTorque (Urho3D::RigidBody2D *_target, float torque, bool wake) { _target->ApplyTorque (torque, wake); } DllExport void RigidBody2D_ApplyLinearImpulse (Urho3D::RigidBody2D *_target, const class Urho3D::Vector2 & impulse, const class Urho3D::Vector2 & point, bool wake) { _target->ApplyLinearImpulse (impulse, point, wake); } DllExport void RigidBody2D_ApplyLinearImpulseToCenter (Urho3D::RigidBody2D *_target, const class Urho3D::Vector2 & impulse, bool wake) { _target->ApplyLinearImpulseToCenter (impulse, wake); } DllExport void RigidBody2D_ApplyAngularImpulse (Urho3D::RigidBody2D *_target, float impulse, bool wake) { _target->ApplyAngularImpulse (impulse, wake); } DllExport void RigidBody2D_CreateBody (Urho3D::RigidBody2D *_target) { _target->CreateBody (); } DllExport void RigidBody2D_ReleaseBody (Urho3D::RigidBody2D *_target) { _target->ReleaseBody (); } DllExport void RigidBody2D_ApplyWorldTransform (Urho3D::RigidBody2D *_target) { _target->ApplyWorldTransform (); } DllExport void RigidBody2D_ApplyWorldTransform0 (Urho3D::RigidBody2D *_target, const class Urho3D::Vector3 & newWorldPosition, const class Urho3D::Quaternion & newWorldRotation) { _target->ApplyWorldTransform (newWorldPosition, newWorldRotation); } DllExport void RigidBody2D_AddCollisionShape2D (Urho3D::RigidBody2D *_target, Urho3D::CollisionShape2D * collisionShape) { _target->AddCollisionShape2D (collisionShape); } DllExport void RigidBody2D_RemoveCollisionShape2D (Urho3D::RigidBody2D *_target, Urho3D::CollisionShape2D * collisionShape) { _target->RemoveCollisionShape2D (collisionShape); } DllExport void RigidBody2D_AddConstraint2D (Urho3D::RigidBody2D *_target, Urho3D::Constraint2D * constraint) { _target->AddConstraint2D (constraint); } DllExport void RigidBody2D_RemoveConstraint2D (Urho3D::RigidBody2D *_target, Urho3D::Constraint2D * constraint) { _target->RemoveConstraint2D (constraint); } DllExport enum Urho3D::BodyType2D RigidBody2D_GetBodyType (Urho3D::RigidBody2D *_target) { return _target->GetBodyType (); } DllExport float RigidBody2D_GetMass (Urho3D::RigidBody2D *_target) { return _target->GetMass (); } DllExport float RigidBody2D_GetInertia (Urho3D::RigidBody2D *_target) { return _target->GetInertia (); } DllExport Interop::Vector2 RigidBody2D_GetMassCenter (Urho3D::RigidBody2D *_target) { return *((Interop::Vector2 *) &(_target->GetMassCenter ())); } DllExport int RigidBody2D_GetUseFixtureMass (Urho3D::RigidBody2D *_target) { return _target->GetUseFixtureMass (); } DllExport float RigidBody2D_GetLinearDamping (Urho3D::RigidBody2D *_target) { return _target->GetLinearDamping (); } DllExport float RigidBody2D_GetAngularDamping (Urho3D::RigidBody2D *_target) { return _target->GetAngularDamping (); } DllExport int RigidBody2D_IsAllowSleep (Urho3D::RigidBody2D *_target) { return _target->IsAllowSleep (); } DllExport int RigidBody2D_IsFixedRotation (Urho3D::RigidBody2D *_target) { return _target->IsFixedRotation (); } DllExport int RigidBody2D_IsBullet (Urho3D::RigidBody2D *_target) { return _target->IsBullet (); } DllExport float RigidBody2D_GetGravityScale (Urho3D::RigidBody2D *_target) { return _target->GetGravityScale (); } DllExport int RigidBody2D_IsAwake (Urho3D::RigidBody2D *_target) { return _target->IsAwake (); } DllExport Interop::Vector2 RigidBody2D_GetLinearVelocity (Urho3D::RigidBody2D *_target) { return *((Interop::Vector2 *) &(_target->GetLinearVelocity ())); } DllExport float RigidBody2D_GetAngularVelocity (Urho3D::RigidBody2D *_target) { return _target->GetAngularVelocity (); } DllExport int SpriteSheet2D_GetType (Urho3D::SpriteSheet2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * SpriteSheet2D_GetTypeName (Urho3D::SpriteSheet2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int SpriteSheet2D_GetTypeStatic () { return (SpriteSheet2D::GetTypeStatic ()).Value (); } DllExport const char * SpriteSheet2D_GetTypeNameStatic () { return stringdup((SpriteSheet2D::GetTypeNameStatic ()).CString ()); } DllExport void * SpriteSheet2D_SpriteSheet2D (Urho3D::Context * context) { return WeakPtr<SpriteSheet2D>(new SpriteSheet2D(context)); } DllExport void SpriteSheet2D_RegisterObject (Urho3D::Context * context) { SpriteSheet2D::RegisterObject (context); } DllExport int SpriteSheet2D_BeginLoad_File (Urho3D::SpriteSheet2D *_target, File * source) { return _target->BeginLoad (*source); } DllExport int SpriteSheet2D_BeginLoad_MemoryBuffer (Urho3D::SpriteSheet2D *_target, MemoryBuffer * source) { return _target->BeginLoad (*source); } DllExport int SpriteSheet2D_EndLoad (Urho3D::SpriteSheet2D *_target) { return _target->EndLoad (); } DllExport void SpriteSheet2D_SetTexture (Urho3D::SpriteSheet2D *_target, Urho3D::Texture2D * texture) { _target->SetTexture (texture); } DllExport void SpriteSheet2D_DefineSprite (Urho3D::SpriteSheet2D *_target, const char * name, const class Urho3D::IntRect & rectangle, const class Urho3D::Vector2 & hotSpot, const class Urho3D::IntVector2 & offset) { _target->DefineSprite (Urho3D::String(name), rectangle, hotSpot, offset); } DllExport Urho3D::Texture2D * SpriteSheet2D_GetTexture (Urho3D::SpriteSheet2D *_target) { return _target->GetTexture (); } DllExport Urho3D::Sprite2D * SpriteSheet2D_GetSprite (Urho3D::SpriteSheet2D *_target, const char * name) { return _target->GetSprite (Urho3D::String(name)); } DllExport int TileMap2D_GetType (Urho3D::TileMap2D *_target) { return (_target->GetType ()).Value (); } DllExport const char * TileMap2D_GetTypeName (Urho3D::TileMap2D *_target) { return stringdup((_target->GetTypeName ()).CString ()); } DllExport int TileMap2D_GetTypeStatic () { return (TileMap2D::GetTypeStatic ()).Value (); } DllExport const char * TileMap2D_GetTypeNameStatic () { return stringdup((TileMap2D::GetTypeNameStatic ()).CString ()); } DllExport void * TileMap2D_TileMap2D (Urho3D::Context * context) { return WeakPtr<TileMap2D>(new TileMap2D(context)); } DllExport void TileMap2D_RegisterObject (Urho3D::Context * context) { TileMap2D::RegisterObject (context); } DllExport void TileMap2D_DrawDebugGeometry (Urho3D::TileMap2D *_target, Urho3D::DebugRenderer * debug, bool depthTest) { _target->DrawDebugGeometry (debug, depthTest); } DllExport void TileMap2D_SetTmxFile (Urho3D::TileMap2D *_target, Urho3D::TmxFile2D * tmxFile) { _target->SetTmxFile (tmxFile); } DllExport void TileMap2D_DrawDebugGeometry0 (Urho3D::TileMap2D *_target) { _target->DrawDebugGeometry (); } DllExport Urho3D::TmxFile2D * TileMap2D_GetTmxFile (Urho3D::TileMap2D *_target) { return _target->GetTmxFile (); } DllExport Urho3D::TileMapInfo2D TileMap2D_GetInfo (Urho3D::TileMap2D *_target) { return _target->GetInfo (); } DllExport unsigned int TileMap2D_GetNumLayers (Urho3D::TileMap2D *_target) { return _target->GetNumLayers (); } DllExport Urho3D::TileMapLayer2D * TileMap2D_GetLayer (Urho3D::TileMap2D *_target, unsigned int index) { return _target->GetLayer (index); } DllExport Interop::Vector2 TileMap2D_TileIndexToPosition (Urho3D::TileMap2D *_target, int x, int y) { return *((Interop::Vector2 *) &(_target->TileIndexToPosition (x, y))); } DllExport int TileMap2D_PositionToTileIndex (Urho3D::TileMap2D *_target, int & x, int & y, const class Urho3D::Vector2 & position) { return _target->PositionToTileIndex (x, y, position); } DllExport Urho3D::ResourceRef TileMap2D_GetTmxFileAttr (Urho3D::TileMap2D *_target) { return _target->GetTmxFileAttr (); } }
20.165097
522
0.769186
[ "geometry", "render", "object", "shape", "vector", "model", "transform", "solid" ]
1dc69a43a81130c150f964998bab66939d9954fe
823
cpp
C++
src/system/system_entity.cpp
jthomperoo/JamJarNative
20105167f8a81b924356704ac5b982e768e86a3f
[ "MIT" ]
1
2019-10-27T22:30:37.000Z
2019-10-27T22:30:37.000Z
src/system/system_entity.cpp
jthomperoo/JamJarNative
20105167f8a81b924356704ac5b982e768e86a3f
[ "MIT" ]
14
2020-02-01T22:48:56.000Z
2020-02-06T17:41:29.000Z
src/system/system_entity.cpp
jthomperoo/JamJarNative
20105167f8a81b924356704ac5b982e768e86a3f
[ "MIT" ]
null
null
null
#include "system/system_entity.hpp" #include "component/component.hpp" #include "entity/entity.hpp" JamJar::SystemEntity::SystemEntity(Entity *entity, const std::vector<JamJar::Component *> &components) : m_entity(entity) { for (const auto &component : components) { this->m_components[component->m_key] = component; } } JamJar::Component *JamJar::SystemEntity::Get(uint32_t key) { return this->m_components[key]; } void JamJar::SystemEntity::Remove(uint32_t key) { this->m_components.erase(key); this->m_entity->Remove(key); } void JamJar::SystemEntity::Add(std::unique_ptr<JamJar::Component> component) { this->m_components[component->m_key] = component.get(); this->m_entity->Add(std::move(component)); } void JamJar::SystemEntity::Destroy() const { this->m_entity->Destroy(); }
32.92
102
0.714459
[ "vector" ]
1dc9381dcce6b2cd2b974bd946c8adf2f8ad566f
8,523
cpp
C++
src/opr-mm/impl/mm_handler.cpp
jonrzhang/MegEngine
94b72022156a068d3e87bceed7e1c7ae77dada16
[ "Apache-2.0" ]
3
2020-10-23T06:33:57.000Z
2020-10-23T06:34:06.000Z
src/opr-mm/impl/mm_handler.cpp
yang-shuohao/MegEngine
2e8742086563ea442c357b14560245c54e0aa0a3
[ "Apache-2.0" ]
null
null
null
src/opr-mm/impl/mm_handler.cpp
yang-shuohao/MegEngine
2e8742086563ea442c357b14560245c54e0aa0a3
[ "Apache-2.0" ]
1
2022-02-21T10:41:55.000Z
2022-02-21T10:41:55.000Z
/** * \file python_module/src/cpp/mm_handler.cpp * * This file is part of MegBrain, a deep learning framework developed by Megvii. * * \copyright Copyright (c) 2014-2020 Megvii Inc. All rights reserved. * */ #include "megbrain/opr/mm_handler.h" #include "megbrain/exception.h" #include "megbrain_build_config.h" #if MGB_ENABLE_OPR_MM #include "megbrain/opr/zmq_rpc.h" #include "mm_handler.pb.h" #include <future> /* ======================== GroupServerProxy ========================== */ /*! * A proxy that receives zmqrpc call, direct call to NCCL Manager */ #define RUNSERVER(rpc_name) \ if (std::strcmp(describe, #rpc_name) == 0) { \ std::string output; \ rpc_name(input_ptr, input_len, &output); \ reply.rebuild(output.length()); \ memcpy(reply.data(), output.data(), output.length()); \ return; \ } class GroupServerProxy final : public ZmqRpc::ZmqRpcServerImpl { public: void solve_request(zmq::message_t& request, zmq::message_t& reply) override { char* describe = (char*)request.data(); void* input_ptr = (char*)request.data() + strlen(describe) + 1; size_t input_len = request.size() - strlen(describe) - 1; RUNSERVER(opr_register); RUNSERVER(set_output_shape); RUNSERVER(get_output_shape); RUNSERVER(bcast_addr); RUNSERVER(group_barrier); mgb_assert(false, "invalid rpc request"); } private: void opr_register(void* input_ptr, size_t input_len, std::string *output); void set_output_shape(void* input_ptr, size_t input_len, std::string *output); void get_output_shape(void* input_ptr, size_t input_len, std::string *output); void bcast_addr(void* input_ptr, size_t input_len, std::string *output); void group_barrier(void* input_ptr, size_t input_len, std::string *output); private: GroupManager m_mgr; }; #undef RUNSERVER #define INFO_INIT(space, name) \ using Request = space::name##Request; \ using Response = space::name##Response; \ Request req; \ Response rsp; \ req.ParseFromArray(input_ptr, input_len); void GroupServerProxy::opr_register(void* input_ptr, size_t input_len, std::string *output) { INFO_INIT(mm_handler, OprRegister); auto ret = m_mgr.opr_register(req.key(), req.nr_expected_devices(), req.is_root(), req.rank(), req.comp_node_hash()); rsp.set_hash(ret.hash); rsp.set_rank(ret.rank); rsp.set_root_rank(ret.root_rank); rsp.SerializeToString(output); } void GroupServerProxy::set_output_shape(void* input_ptr, size_t input_len, std::string *output) { INFO_INIT(mm_handler, SetOutputShape); auto&& shape_proto = req.shape(); TensorShape shape; shape.ndim = shape_proto.ndim(); for (size_t i = 0; i < shape.ndim; ++i) { shape.shape[i] = shape_proto.shape(i); } m_mgr.set_output_shape(req.key(), shape); rsp.SerializeToString(output); } void GroupServerProxy::get_output_shape(void* input_ptr, size_t input_len, std::string *output) { INFO_INIT(mm_handler, GetOutputShape); auto shape = m_mgr.get_output_shape(req.key()); auto&& shape_proto = *rsp.mutable_shape(); shape_proto.set_ndim(shape.ndim); for (size_t i = 0; i < shape.ndim; ++i) { shape_proto.add_shape(shape[i]); } rsp.SerializeToString(output); } void GroupServerProxy::bcast_addr(void* input_ptr, size_t input_len, std::string *output) { INFO_INIT(mm_handler, BcastAddr); std::string master_ip = req.master_ip(); int port = req.port(); m_mgr.bcast_addr(master_ip, port, req.key(), req.size(), req.rank(), req.root()); rsp.set_master_ip(master_ip); rsp.set_port(port); rsp.SerializeToString(output); } void GroupServerProxy::group_barrier(void* input_ptr, size_t input_len, std::string *output) { INFO_INIT(mm_handler, GroupBarrier); uint32_t rsp_size = m_mgr.group_barrier(req.size(), req.rank()); rsp.set_size(rsp_size); rsp.SerializeToString(output); } #undef INFO_INIT /* ======================== GroupClientProxy ========================== */ #define INFO_INIT(space, f_name, name) \ using Request = space::name##Request; \ using Response = space::name##Response; \ std::string func_name = #f_name; \ Request req; \ Response rsp; #define SOLVE_REQUEST(name, req, rsp) \ std::string req_str; \ mgb_assert(req.SerializeToString(&req_str)); \ zmq::message_t send(req_str.length() + name.length() + 1); \ zmq::message_t recv; \ memcpy(send.data(), name.data(), name.length() + 1); \ memcpy((char*)send.data() + name.length() + 1, req_str.data(), \ req_str.length()); \ static_cast<ZmqRpc::ZmqRpcClient*>(m_stub)->request(send, recv); \ mgb_assert(rsp.ParseFromArray(recv.data(), recv.size())); GroupClientProxy::GroupClientProxy(const std::string& server_addr) : m_addr(server_addr), m_stub{ZmqRpc::ZmqRpcClient::get_client("tcp://" + server_addr)} { } GroupManager::RegisterInfo GroupClientProxy::opr_register( const std::string& key, size_t nr_devices, bool is_root, int rank, uint64_t comp_node_hash) { INFO_INIT(mm_handler, opr_register, OprRegister) req.set_key(key); req.set_is_root(is_root); req.set_rank(rank); req.set_comp_node_hash(comp_node_hash); req.set_nr_expected_devices(nr_devices); SOLVE_REQUEST(func_name, req, rsp); GroupManager::RegisterInfo ret{rsp.hash(), rsp.rank(), rsp.root_rank()}; return ret; } void GroupClientProxy::set_output_shape(const std::string& key, const TensorShape& shape) { INFO_INIT(mm_handler, set_output_shape, SetOutputShape) req.set_key(key); auto&& shape_proto = *req.mutable_shape(); shape_proto.set_ndim(shape.ndim); for (size_t i = 0; i < shape.ndim; ++i) { shape_proto.add_shape(shape[i]); } SOLVE_REQUEST(func_name, req, rsp); } TensorShape GroupClientProxy::get_output_shape(const std::string& key) { INFO_INIT(mm_handler, get_output_shape, GetOutputShape) req.set_key(key); SOLVE_REQUEST(func_name, req, rsp); TensorShape shape; shape.ndim = rsp.shape().ndim(); for (size_t i = 0; i < shape.ndim; ++i) { shape[i] = rsp.shape().shape(i); } return shape; } void GroupClientProxy::bcast_addr(std::string& master_ip, int& port, const std::string& key, uint32_t size, uint32_t rank, uint32_t root) { INFO_INIT(mm_handler, bcast_addr, BcastAddr); req.set_master_ip(master_ip.data(), master_ip.size()); req.set_port(port); req.set_key(key.data(), key.size()); req.set_size(size); req.set_rank(rank); req.set_root(root); SOLVE_REQUEST(func_name, req, rsp); master_ip = rsp.master_ip(); port = rsp.port(); } uint32_t GroupClientProxy::group_barrier(uint32_t size, uint32_t rank) { INFO_INIT(mm_handler, group_barrier, GroupBarrier); req.set_size(size); req.set_rank(rank); SOLVE_REQUEST(func_name, req, rsp); return rsp.size(); } #undef INFO_INIT #undef SOLVE_REQUEST struct ServerInfo { std::unique_ptr<ZmqRpc::ZmqRpcServer> server; }; int create_zmqrpc_server(const std::string& server_addr, int port) { static std::unordered_map<std::string, ServerInfo> addr2server; static std::mutex mtx; MGB_LOCK_GUARD(mtx); auto service = std::make_unique<GroupServerProxy>(); auto server = std::make_unique<ZmqRpc::ZmqRpcServer>("tcp://" + server_addr, port, std::move(service)); port = server->port(); auto full_srv_addr = ssprintf("%s:%d", server_addr.c_str(), port); server->run(); auto ins = addr2server.emplace( full_srv_addr, ServerInfo{std::move(server)}); mgb_assert(ins.second); return port; } #endif // vim: syntax=cpp.doxygen foldmethod=marker foldmarker=f{{{,f}}}
35.810924
85
0.618092
[ "shape" ]
1dcad965a495445c4a6a924ce134ce2330dadde9
6,644
cxx
C++
engine/src/graphics/render_pass.cxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
null
null
null
engine/src/graphics/render_pass.cxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
null
null
null
engine/src/graphics/render_pass.cxx
Alabuta/VulkanIsland
f33a16fa163527270bc14d03bcfed06dbddbb416
[ "MIT" ]
1
2018-10-03T17:05:43.000Z
2018-10-03T17:05:43.000Z
#include <algorithm> #include <string> using namespace std::string_literals; #include <fmt/format.h> #include "utility/exceptions.hxx" #include "graphics_api.hxx" #include "render_pass.hxx" namespace { struct subpass_invariant final { std::vector<VkAttachmentReference> input_attachments; std::vector<VkAttachmentReference> color_attachments; std::vector<VkAttachmentReference> resolve_attachments; std::optional<VkAttachmentReference> depth_stencil_attachment; std::vector<std::uint32_t> preserve_attachments; }; } namespace graphics { std::shared_ptr<graphics::render_pass> render_pass_manager::create_render_pass(std::vector<graphics::attachment_description> const &attachment_descriptions, std::vector<graphics::subpass_description> const &subpass_descriptions, std::vector<graphics::subpass_dependency> const &subpass_dependencies) { auto const subpass_count = std::size(subpass_descriptions); std::vector<subpass_invariant> subpass_invariants(subpass_count); std::vector<VkAttachmentDescription> attachments; attachments.reserve(attachment_descriptions.size()); for (auto &&description : attachment_descriptions) { attachments.push_back(VkAttachmentDescription{ 0, //VK_ATTACHMENT_DESCRIPTION_MAY_ALIAS_BIT, convert_to::vulkan(description.format), convert_to::vulkan(description.samples_count), convert_to::vulkan(description.load_op), convert_to::vulkan(description.store_op), convert_to::vulkan(graphics::ATTACHMENT_LOAD_TREATMENT::DONT_CARE), convert_to::vulkan(graphics::ATTACHMENT_STORE_TREATMENT::DONT_CARE), convert_to::vulkan(description.initial_layout), convert_to::vulkan(description.final_layout) }); } std::vector<VkSubpassDependency> dependencies; dependencies.reserve(subpass_dependencies.size()); for (auto &&dependency : subpass_dependencies) { dependencies.push_back(VkSubpassDependency{ dependency.source_index ? *dependency.source_index : VK_SUBPASS_EXTERNAL, dependency.destination_index ? *dependency.destination_index : VK_SUBPASS_EXTERNAL, convert_to::vulkan(dependency.source_stage), convert_to::vulkan(dependency.destination_stage), dependency.source_access ? convert_to::vulkan(*dependency.source_access) : 0, dependency.destination_access ? convert_to::vulkan(*dependency.destination_access) : 0, 0 }); } std::vector<VkSubpassDescription> subpasses; for (std::size_t subpass_index = 0; auto &&description : subpass_descriptions) { auto &&input_attachments = subpass_invariants.at(subpass_index).input_attachments; for (auto &&attachment : description.input_attachments) { input_attachments.push_back({ attachment.attachment_index, convert_to::vulkan(attachment.subpass_layout) }); } auto &&color_attachments = subpass_invariants.at(subpass_index).color_attachments; for (auto &&attachment : description.color_attachments) { color_attachments.push_back({ attachment.attachment_index, convert_to::vulkan(attachment.subpass_layout) }); } auto &&depth_stencil_attachment = subpass_invariants.at(subpass_index).depth_stencil_attachment; if (description.depth_stencil_attachment) { depth_stencil_attachment = VkAttachmentReference{ description.depth_stencil_attachment->attachment_index, convert_to::vulkan(description.depth_stencil_attachment->subpass_layout) }; } auto &&resolve_attachments = subpass_invariants.at(subpass_index).resolve_attachments; for (auto &&attachment : description.resolve_attachments) { resolve_attachments.push_back({ attachment.attachment_index, convert_to::vulkan(attachment.subpass_layout) }); } auto &&preserve_attachments = subpass_invariants.at(subpass_index).preserve_attachments; preserve_attachments = description.preserve_attachments; subpasses.push_back(VkSubpassDescription{ 0, VK_PIPELINE_BIND_POINT_GRAPHICS, static_cast<std::uint32_t>(std::size(input_attachments)), std::data(input_attachments), static_cast<std::uint32_t>(std::size(color_attachments)), std::data(color_attachments), std::data(resolve_attachments), depth_stencil_attachment ? &depth_stencil_attachment.value() : nullptr, static_cast<std::uint32_t>(std::size(preserve_attachments)), std::data(preserve_attachments) }); ++subpass_index; } #if NOT_YET_IMPLEMENTED VkInputAttachmentAspectReference const depthAttachmentAspectReference{ 0, 0, VK_IMAGE_ASPECT_DEPTH_BIT }; VkRenderPassInputAttachmentAspectCreateInfo const depthAttachmentAspect{ VK_STRUCTURE_TYPE_RENDER_PASS_INPUT_ATTACHMENT_ASPECT_CREATE_INFO, nullptr, 1, &depthAttachmentAspectReference }; #endif VkRenderPassCreateInfo const create_info{ VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, nullptr, 0, static_cast<std::uint32_t>(std::size(attachments)), std::data(attachments), static_cast<std::uint32_t>(std::size(subpasses)), std::data(subpasses), static_cast<std::uint32_t>(std::size(dependencies)), std::data(dependencies), }; std::shared_ptr<graphics::render_pass> render_pass; VkRenderPass handle; if (auto result = vkCreateRenderPass(device_.handle(), &create_info, nullptr, &handle); result != VK_SUCCESS) throw vulkan::exception(fmt::format("failed to create render pass: {0:#x}"s, result)); else render_pass.reset(new graphics::render_pass{handle}, [device = device_.handle()] (graphics::render_pass *ptr_render_pass) { vkDestroyRenderPass(device, ptr_render_pass->handle(), nullptr); delete ptr_render_pass; }); return render_pass; } }
42.050633
134
0.653974
[ "render", "vector" ]
1dcfd42afafb5ebb9e35726756fff753c7f741ee
1,608
cpp
C++
2018/Day05/Day05.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
2018/Day05/Day05.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
2018/Day05/Day05.cpp
jloehr/AdventOfCode
11fa8f52b7ba156cecb729c7a3d24fbec27203d0
[ "MIT" ]
null
null
null
// Day05.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" std::string Collapse(std::istream & Input); int main() { std::ifstream Input("Input.txt"); std::string Polymer = Collapse(Input); std::cout << "Part One: " << Polymer.size() << std::endl; std::string UnitsToTest(std::begin(Polymer), std::end(Polymer)); std::transform(std::begin(UnitsToTest), std::end(UnitsToTest), std::begin(UnitsToTest), std::toupper); std::sort(std::begin(UnitsToTest), std::end(UnitsToTest)); auto Last = std::unique(std::begin(UnitsToTest), std::end(UnitsToTest)); UnitsToTest.erase(Last, std::end(UnitsToTest)); size_t Smallest = SIZE_MAX; for (const char UnitDeleted : UnitsToTest) { std::stringstream PolymerCopy; std::ostream_iterator<char> Inserter(PolymerCopy); std::copy_if(std::begin(Polymer), std::end(Polymer), Inserter, [UnitDeleted](const char Character) { return (std::toupper(Character) != UnitDeleted); }); std::string Collapsed = Collapse(PolymerCopy); Smallest = std::min(Smallest, Collapsed.size()); } std::cout << "Part Two: " << Smallest << std::endl; } std::string Collapse(std::istream & Input) { std::string Polymer; size_t Pointer = 0; char Character; while (Input.get(Character)) { if ((Pointer == 0) || !((Character == (Polymer[Pointer - 1] + 32)) || (Character == (Polymer[Pointer - 1] - 32)))) { if ((Pointer == Polymer.size())) Polymer.push_back(Character); else Polymer[Pointer] = Character; ++Pointer; } else --Pointer; } Polymer.resize(Pointer); return Polymer; }
26.8
155
0.674129
[ "transform" ]
1b91b78c4f3fd6710a1414c74f594c904b666e82
22,187
hpp
C++
libqvr/manager.hpp
insonifi/vr-maze
15093b4b3ff0e7df970cc83315c016b43f67b257
[ "MIT" ]
null
null
null
libqvr/manager.hpp
insonifi/vr-maze
15093b4b3ff0e7df970cc83315c016b43f67b257
[ "MIT" ]
null
null
null
libqvr/manager.hpp
insonifi/vr-maze
15093b4b3ff0e7df970cc83315c016b43f67b257
[ "MIT" ]
null
null
null
/* * Copyright (C) 2016, 2017, 2018 Computer Graphics Group, University of Siegen * Written by Martin Lambers <martin.lambers@uni-siegen.de> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef QVR_MANAGER_HPP #define QVR_MANAGER_HPP /*! * \mainpage QVR: A library to build Virtual Reality applications * * \section Overview * * QVR provides the base class \a QVRApp for Virtual Reality applications. * An application implements the subset of \a QVRApp functions that it needs. * See \a QVRApp for function descriptions. * * To run a QVR application, the main() function creates and initializes a * \a QVRManager instances and then calls QApplication::exec() as usual. See * \a QVRManager for a minimal code example. * * The \a QVRManager manages three basic types of objects: observers, processes, * and windows: * - Observers view the virtual scene. Often there is only one observer. * Observers are configured via \a QVRObserverConfig and implemented as \a QVRObserver. * - Processes all run the same application binary. The first process initially * run by the user is the master process. Slave processes are automatically * launched by QVRManager as needed. Each process is connected to one display * which can have multiple screens attached. Processes can run on the same host * or across a network. Often there is only the master process. * Processes are configured via \a QVRProcessConfig and implemented as \a QVRProcess. * - Windows belong to processes and appear on the display that their process is * connected to. They can have different positions and sizes on different screens * attached to that display. Each window shows a view for exactly one observer * (typically that observer views multiple windows). * Windows are configured via \a QVRWindowConfig and implemented as \a QVRWindow. * * All QVR applications support a set of command line options. The most important * option lets the user choose a configuration file. See QVRManager::QVRManager(). * The same application binary can run on different Virtual Reality display setups * by specifying different configuration files. * * To get started, see the main descriptions of \a QVRManager and \a QVRApp, and * then look at the source code of an example application to understand how it is * implemented. * * \section conffile Configuration files * * A configuration file defines the observers, processes, and windows that the * \a QVRManager will manage. * * Each observer, process, and window definition is mapped directly to the * \a QVRObserverConfig, \a QVRProcessConfig, or \a QVRWindowConfig classes. * * A configuration file starts with a list of observers and their properties. * * After that, the list of processes starts. There is always at least one process: * the master process. The master process is connected to the display that Qt initially * uses by default; if a different display is configured, the master process will be * relaunched automatically to take this into account. Slave processes typcially connect * to different displays. Optionally, a launcher command can be specified, e.g. to run a * slave process on a different host using ssh. * * Each process definition contains a list of windows for that process. * Since windows provide views into the virtual world, the geometry of the * screen wall represented by a window must be known. This geometry is either * given by screen wall center coordinates, or by coordinates for three of its * corners. * * Please see the configuration file examples distributed with QVR to understand * how typical configurations look like. * * Device definition (see \a QVRDevice and \a QVRDeviceConfig): * - `device <id>`<br> * Start a new device definition with the given unique id. * - `tracking <none|static|oculus|openvr|vprn>`<br> * Use the specified tracking method for this device. * - `buttons <none|static|gamepad|vprn|oculus|openvr>`<br> * Use the specified method to query digital buttons for this device. * - `analogs <none|static|gamepad|vrpn|oculus|openvr>`<br> * Use the specified method to query analog joystick elements for this device. * * Observer definition (see \a QVRObserver and \a QVRObserverConfig): * - `observer <id>`<br> * Start a new observer definition with the given unique id. * - `navigation <stationary|vrpn|wasdqe|custom> [parameters...]`<br> * Set the navigation type and parameters. * - `navigation_position <x> <y> <z>`<br> * Set the initial navigation position. * - `navigation_forward <x> <y> <z>`<br> * Set the initial navigation forward (or viewing) direction. * - `navigation_up <x> <y> <z>`<br> * Set the initial navigation up direction. * - `tracking <stationary|vrpn|oculus|custom> [parameters...]`<br> * Set the tracking type and parameters. * - `eye_distance <meters>`<br> * Set the interpupillary distance. * - `tracking_position <x> <y> <z>`<br> * Set the initial tracking position. * - `tracking_forward <x> <y> <z>`<br> * Set the initial tracking forward (or viewing) direction. * - `tracking_up <x> <y> <z>`<br> * Set the initial tracking up direction. * * Process definition (see \a QVRProcess and \a QVRProcessConfig): * - `process <id>`<br> * Start a new process definition with the given unique id. * - `ipc <tcp-socket|local-socket|shared-memory|auto>`<br> * Select the inter-process communication method. * - `address <ip-address>`<br> * Set the IP address to bind the server to when using tcp-based inter-process communication. * - `launcher <prg-and-args>`<br> * Launcher commando used to start this process. * - `display <name>`<br> * Display that this process is connected to. * - `sync_to_vblank <true|false>`<br> * Whether windows of this process are synchronized with the vertical refresh of the display. * - `decoupled_rendering <true|false>`<br> * Whether the rendering of this slave process is decoupled from the master process. * * Window definition (see \a QVRWindow and \a QVRWindowConfig): * - `window <id>`<br> * Start a new window definition with the given unique id, within the current process definition. * - `observer <id>`<br> * Set the observer that this window provides a view for. * - `output <center|left|right|stereo|red_cyan|green_magenta|amber_blue|oculus|openvr|googlevr>`<br> * Set the output mode. For center, left, right, and stereo, you can set an additional output plugin. * - `display_screen <screen>`<br> * Select the Qt screen index on the Qt display that this process is connected to.<br> * - `fullscreen <true|false>` * Whether to show the window in fullscreen mode.<br> * - `position <x> <y>`<br> * Set the window position on the Qt screen in pixels. * - `size <w> <h>`<br> * Set the window size on the Qt screen in pixels. * - `screen_is_fixed_to_observer <true|false>`<br> * Whether the screen wall represented by this window is fixed to the observer, * like a head-mounted display, or it is fixed in virtual world space. * - `screen_is_given_by_center <true|false>`<br> * Whether the screen wall represented by this window is given by its center * or by three of its corners. * - `screen_center <x> <y> <z>`<br> * Set screen wall center coordinates. * - `screen_wall <blx> <bly> <blz> <brx> <bry> <brz> <tlx> <tly> <tlz>`<br> * Set the screen wall geometry defined by three points: bottom left corner, bottom * right corner, and top left corner. * - `render_resolution_factor <factor>`<br> * Set the render resolution factor. * * \section Implementation * * The \a QVRManager creates an invisible main OpenGL context for each process. This * context is used for all calls to \a QVRApp application functions: the application * only has to deal with this one context. The rendering results are directed into a * set of textures that cover all the windows of the process. * * When all window textures have been rendered, they are put on screen by the * actual visible windows who all have access to the textures from the main * window. The windows themselves render in separate rendering threads. On buffer * swap, only these rendering threads block. The main thread fills the waiting * time with CPU work such as processing events and calling the \a QVRApp::update() * function of the application. * * The process initially started by the user is the master process. \a QVRManager * launch slave processes as required by the configuration file, and it will * handle all necessary synchronization and data exchange with these slave * processes. */ #include <QObject> #include <QVector3D> #include <QByteArray> template <typename T> class QList; class QTimer; class QKeyEvent; class QMouseEvent; class QWheelEvent; class QElapsedTimer; #include "config.hpp" class QVRApp; class QVRDevice; class QVRObserver; class QVRWindow; class QVRProcess; class QVRRenderContext; class QVRServer; class QVRClient; /*! * \brief Level of logging of the QVR framework * * You can use the command line or an environment variable to set * the log level: * \code{.unparsed} * <application> --qvr-log-level=fatal|warning|info|debug|firehose * export QVR_LOG_LEVEL=FATAL|WARNING|INFO|DEBUG|FIREHOSE * \endcode */ typedef enum { /*! Print only fatal errors */ QVR_Log_Level_Fatal = 0, /*! Additionally print warnings (default) */ QVR_Log_Level_Warning = 1, /*! Additionally print informational messages */ QVR_Log_Level_Info = 2, /*! Additionally print debugging information */ QVR_Log_Level_Debug = 3, /*! Additionally print verbose per-frame debugging information */ QVR_Log_Level_Firehose = 4 } QVRLogLevel; /*! * \brief Manager of the QVR application's control flow and its processes and windows. * * The QVRManager object is typically created right after the QApplication object. * Afterwards, the application typically sets its preferred OpenGL context properties, * and then initializes the QVRManager object: * \code{.cpp} * QApplication app(argc, argv); * QVRManager manager(argc, argv); * // Set OpenGL context properties: * QSurfaceFormat format; * format.setProfile(QSurfaceFormat::CoreProfile); * format.setVersion(3, 3); * QSurfaceFormat::setDefaultFormat(format); * // Start the QVR application * MyQVRApp myqvrapp; * if (!manager.init(&myqvrapp)) * return 1; * return app.exec(); * \endcode */ class QVRManager : public QObject { Q_OBJECT private: // Data initialized by the constructor: QTimer* _triggerTimer; QTimer* _fpsTimer; QVRLogLevel _logLevel; QString _workingDir; int _processIndex; bool _syncToVBlankWasSet; bool _syncToVBlank; unsigned int _fpsMsecs; unsigned int _fpsCounter; QString _configFilename; QString _masterName; QVRConfig::Autodetect _autodetect; QStringList _appArgs; bool _isRelaunchedMaster; // Data initialized by init(): QByteArray _serializationBuffer; QVRServer* _server; // only on the master process QVRClient* _client; // only on a client process QVRApp* _app; QVRConfig* _config; QList<QVRDevice*> _devices; QList<QVRDevice> _deviceLastStates; QList<QVRObserver*> _observers; QList<int> _observerNavigationDevices; QList<int> _observerTrackingDevices0; QList<int> _observerTrackingDevices1; QVRWindow* _masterWindow; QList<QVRWindow*> _windows; QVRProcess* _thisProcess; QList<QVRProcess*> _slaveProcesses; float _near, _far; bool _wantExit; QElapsedTimer* _wandNavigationTimer; // Wand-based observers: framerate-independent speed QVector3D _wandNavigationPos; // Wand-based observers: position float _wandNavigationRotY; // Wand-based observers: angle around the y axis bool _haveWasdqeObservers; // WASDQE observers: do we have at least one? QElapsedTimer* _wasdqeTimer; // WASDQE observers: framerate-independent speed bool _wasdqeIsPressed[6]; // WASDQE observers: keys int _wasdqeMouseProcessIndex; // WASDQE observers: process with mouse grab int _wasdqeMouseWindowIndex; // WASDQE observers: window with mouse grab bool _wasdqeMouseInitialized; // WASDQE observers: was mouse grab initialized QVector3D _wasdqePos; // WASDQE observers: position float _wasdqeHorzAngle; // WASDQE observers: angle around the y axis float _wasdqeVertAngle; // WASDQE observers: angle around the x axis bool _initialized; void buildProcessCommandLine(int processIndex, QString* prg, QStringList* args); void processEventQueue(); void updateDevices(); void render(); void waitForBufferSwaps(); void quit(); friend void QVRMsg(QVRLogLevel level, const char* s); private slots: void masterLoop(); void slaveLoop(); void printFps(); public: /** * \name Constructor, Destructor, Initialization */ /*@{*/ /*! * \brief This constructor creates the manager object. * * The following command line options are intereted by the QVR manager * and removed from \a argc and \a argv: * - \-\-qvr-config=\<config.qvr\><br> * Specify a QVR configuration file. * - \-\-qvr-timeout=\<msecs\><br> * Set a timeout value in milliseconds for all interprocess communication. * The default is -1, which means to never timeout. * - \-\-qvr-log-level=\<level\><br> * See \a QVRLogLevel. * - \-\-qvr-log-file=\<filename\><br> * Write all log messages to the given file instead of the standard error stream. * - \-\-qvr-sync-to-vblank=<0|1><br> * Disable (0) or enable (1) sync-to-vblank. This overrides the per-process setting in the configuration file. * - \-\-qvr-fps=\<n\><br> * Make QVR report frames per second measurements every n milliseconds. * - \-\-qvr-autodetect=\<list\><br> * Comma-separated list of VR hardware that QVR should attempt to detect automatically. * Currently supported keywords are 'all' for all hardware, 'oculus' for Oculus Rift, * 'openvr' for OpenVR hardware, 'googlevr' for Google VR hardware, * 'gamepads' for gamepads. Each entry can be preceded with '~' to negate it. For example, * use '\-\-qvr-autodetect=all,~oculus' to try autodetection for all hardware except Oculus Rift. * This option only takes effect if no \-\-qvr-config option was given. */ QVRManager(int& argc, char* argv[]); /*! \brief Destructor. */ ~QVRManager(); /*! * \brief Return the QVR manager instance. * * There can be only one instance of \a QVRManager. This function returns it. */ static QVRManager* instance(); /*! * \brief Initialize the QVR application. * \param app The QVR application. * \param preferCustomNavigation Whether the application prefers its own navigation methods. * \return False on failure. * * This function will create all slave processes and all windows, depending * on the QVR configuration, and it will call the initialization functions * of \a app. * * Applications that implement their own navigation methods in \a QVRApp::update() should * set the \a preferCustomNavigation flag. */ bool init(QVRApp* app, bool preferCustomNavigation = false); /*! * \brief Returns whether the manager was successfully initialized. */ static bool isInitialized(); /*@}*/ /** * \name Configuration access. * * This is only guaranteed to work after a successfull call to \a init(). See \a isInitialized(). */ /*@{*/ /*! * \brief Return the log level. */ static QVRLogLevel logLevel(); /*! * \brief Return the active configuration. */ static const QVRConfig& config(); /*! * \brief Return the number of devices in the configuration. * * This is a convenience function, you can also get this information from \a config(). */ static int deviceCount() { return config().deviceConfigs().size(); } /*! * \brief Return the configuration of the device with index \a deviceIndex. * * This is a convenience function, you can also get this information from \a config(). */ static const QVRDeviceConfig& deviceConfig(int deviceIndex) { return config().deviceConfigs().at(deviceIndex); } /*! * \brief Return the number of observers in the configuration. * * This is a convenience function, you can also get this information from \a config(). */ static int observerCount() { return config().observerConfigs().size(); } /*! * \brief Return the configuration of the observer with index \a observerIndex. * * This is a convenience function, you can also get this information from \a config(). */ static const QVRObserverConfig& observerConfig(int observerIndex) { return config().observerConfigs().at(observerIndex); } /*! * \brief Return the number of processes in the configuration. * * This is a convenience function, you can also get this information from \a config(). */ static int processCount() { return config().processConfigs().size(); } /*! * \brief Return the index of the running process. The process with index 0 is the master process. */ static int processIndex(); /*! * \brief Return the configuration of the process with the index \a pi. * * This is a convenience function, you can also get this information from \a config(). */ static const QVRProcessConfig& processConfig(int pi = processIndex()) { return config().processConfigs().at(pi); } /*! * \brief Return the number of windows in the configuration of the process with index \a pi. * * This is a convenience function, you can also get this information from \a config(). */ static int windowCount(int pi = processIndex()) { return config().processConfigs().at(pi).windowConfigs().size(); } /*! * \brief Return the configuration of the window with the index \a windowIndex on * the process with index \a processIndex. * * This is a convenience function, you can also get this information from \a config(). */ static const QVRWindowConfig& windowConfig(int processIndex, int windowIndex) { return config().processConfigs().at(processIndex).windowConfigs().at(windowIndex); } /*@}*/ /** * \name Object access */ /*@{*/ /*! \brief Return the device with index \a deviceIndex. See \a deviceCount(). */ static const QVRDevice& device(int deviceIndex); /*! \brief Return the observer with index \a observerIndex. See \a observerCount(). */ static const QVRObserver& observer(int observerIndex); /*! \brief Return the process. Only the running process is accessible in this way. See \a processIndex(). */ static const QVRProcess& process(); /*! \brief Return the window with the given index in the running process. */ static const QVRWindow& window(int windowIndex); /*@}*/ /** * \name Renderable device models * * See the documentation of \a QVRDevice for information on how to use this model data to render * representations of interaction devices into the virtual world. * * The data returned by these functions does not change, so you can upload it once to the GPU * and reuse it. */ /*@{*/ /*! \brief Return the number of vertex data blocks. */ static int deviceModelVertexDataCount(); /*! \brief Return the number of vertices in vertex data block \a vertexDataIndex. */ static int deviceModelVertexCount(int vertexDataIndex); /*! \brief Return the vertex positions in vertex data block \a vertexDataIndex. Each position consists of three values (x, y, z). */ static const float* deviceModelVertexPositions(int vertexDataIndex); /*! \brief Return the vertex normals in vertex data block \a vertexDataIndex. Each normal consists of three values (nx, ny, nz). */ static const float* deviceModelVertexNormals(int vertexDataIndex); /*! \brief Return the vertex texture coordinates in vertex data block \a vertexDataIndex. Each texture coordinate consists of two values (u, v). */ static const float* deviceModelVertexTexCoords(int vertexDataIndex); /*! \brief Return the number of vertex indices in vertex data block \a vertexDataIndex. */ static int deviceModelVertexIndexCount(int vertexDataIndex); /*! \brief Return the vertex indices in vertex data block \a vertexDataIndex. */ static const unsigned short* deviceModelVertexIndices(int vertexDataIndex); /*! \brief Return the number of textures. */ static int deviceModelTextureCount(); /*! \brief Return the texture \a textureIndex. */ static const QImage& deviceModelTexture(int textureIndex); /*@}*/ }; #endif
40.635531
151
0.702844
[ "geometry", "render", "object", "model" ]
1b937237d127fda7d0f7002278f7b5fb611e6a60
2,085
cpp
C++
Products/UnstoreWorks/unstore.cpp
TrevorDArcyEvans/DivingMagpieSoftware
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
1
2021-05-27T10:27:25.000Z
2021-05-27T10:27:25.000Z
Products/UnstoreWorks/unstore.cpp
TrevorDArcyEvans/Diving-Magpie-Software
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
null
null
null
Products/UnstoreWorks/unstore.cpp
TrevorDArcyEvans/Diving-Magpie-Software
7ffcfef653b110e514d5db735d11be0aae9953ec
[ "MIT" ]
null
null
null
// Unstore.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <Windows.h> #include <comdef.h> #include <io.h> #include <sys/types.h> #include <sys/stat.h> #include <tchar.h> //------------------------------------------ HWND g_hWnd = NULL; int UnStore(TCHAR *pcFileName); //------------------------------------------ BOOL CALLBACK UW_EnumWindows( HWND hWnd, LPARAM lParam) { CHAR cBuffer[MAX_PATH]; GetWindowText(hWnd, cBuffer, sizeof(cBuffer)); if (strstr(_strlwr(cBuffer), _strlwr("unstore.exe"))) { g_hWnd = hWnd; return FALSE; } return TRUE; } //------------------------------------------ int UnStore(TCHAR *pcFileName) { HRESULT hr; IStorage* pRoot; IStorage* pContents; if (S_OK == (hr = ::StgOpenStorage(_bstr_t(pcFileName), NULL, STGM_DIRECT | STGM_READWRITE | STGM_SHARE_EXCLUSIVE, NULL, 0, &pRoot))) { if (S_OK != pRoot->DestroyElement(_bstr_t("Preview"))) { MessageBox(NULL, "failed to remove: Bitmap Preview", "Unstore", MB_OK | MB_ICONERROR | MB_DEFBUTTON1); } if (S_OK == pRoot->OpenStorage(_bstr_t("Contents"), NULL, STGM_DIRECT | STGM_READWRITE | STGM_SHARE_EXCLUSIVE, NULL, 0, &pContents)) { if (NULL != pContents) { if (S_OK != pContents->DestroyElement(_bstr_t("DisplayLists__Zip"))) { MessageBox(NULL, "failed to remove: Geometry Display List", "Unstore", MB_OK | MB_ICONERROR | MB_DEFBUTTON1); } pContents->Release(); } } pRoot->Release(); } return 0; } //------------------------------------------ int main(int argc, char* argv[]) { EnumWindows(UW_EnumWindows, 0); if (NULL != g_hWnd) { SetWindowPos(g_hWnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_HIDEWINDOW); } if (2 == argc) { UnStore(argv[1]); } return 0; } // --------------------------------
21.947368
86
0.508873
[ "geometry" ]
1b9e1a077f72ebfee97972d5491a5bb62470ed40
2,038
cpp
C++
Final Src/Common/Campaign.cpp
vdwtanner/Crusade
f6531de9bc85c98283d34b68f20b52d49339d98c
[ "MIT" ]
1
2019-02-09T08:19:23.000Z
2019-02-09T08:19:23.000Z
Final Src/Common/Campaign.cpp
vdwtanner/Crusade
f6531de9bc85c98283d34b68f20b52d49339d98c
[ "MIT" ]
null
null
null
Final Src/Common/Campaign.cpp
vdwtanner/Crusade
f6531de9bc85c98283d34b68f20b52d49339d98c
[ "MIT" ]
null
null
null
#include "pch.h" #include "Campaign.h" Campaign::Campaign(LPWSTR filepath){ m_name = wstring(filepath).substr(0, wstring(filepath).length() - 4); loadCampaign(filepath); m_currentLevel = 0; } Campaign::~Campaign(){ } //parse csv at LPWSTR filepath to load campaign data. void Campaign::loadCampaign(LPWSTR filepath){ ifstream ccf(filepath, std::ios::in); //ccf.open(filepath); if (!ccf){ return; } string csv; getline(ccf, csv); csv.erase(remove_if(csv.begin(), csv.end(), isspace), csv.end()); //Remove spaces that were there for readability vector<string> levels = CrusadeUtil::split(csv, ';'); for (string level : levels){ level = level.substr(1, level.length() - 2); vector<string> data = CrusadeUtil::split(level, ','); string temp = "../img/Worlds/" + data[0] + ".crwf"; wchar_t* wtemp; CrusadeUtil::s_to_ws(temp, &wtemp); m_filepaths.push_back(wtemp); if (data[1].length() > 0){ m_difficultyMultipliers.push_back((float)stoi(data[1])); } else{ m_difficultyMultipliers.push_back(1); } } } //get all filepaths vector<LPWSTR>* Campaign::getFilePaths(){ return &m_filepaths; } //get a specific filepath LPWSTR Campaign::getFilePath(int index){ return m_filepaths[index]; } vector<float>* Campaign::getDifficultyMultipliers(){ return &m_difficultyMultipliers; } float Campaign::getDifficultyMultiplier(int index){ return m_difficultyMultipliers[index]; } void Campaign::setCurrentLevel(int level){ m_currentLevel = level; } int Campaign::getCurrentLevel(){ return m_currentLevel; } //Returns the path to the next level of the campaign if there is another level. If there isn't another level it returns L"CAMPAIGN FINISHED" LPWSTR Campaign::getNextLevel(){ if (m_currentLevel+1 < (int)m_filepaths.size()){ return getFilePath(++m_currentLevel); } else return L"CAMPAIGN FINISHED"; } wstring Campaign::getName(){ return m_name; } wstring Campaign::getFilename(){ return m_name + L".ccf"; }
24.853659
141
0.68842
[ "vector" ]
1ba0039a7781f0de82fcc2daf0eb2f8912d09488
4,714
hpp
C++
RobWork/src/rwlibs/task/GraspTask.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rwlibs/task/GraspTask.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rwlibs/task/GraspTask.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/* * GraspTask.hpp * * Created on: Aug 15, 2011 * Author: jimali */ #ifndef RWLIBS_TASK_GRASPTASK_HPP_ #define RWLIBS_TASK_GRASPTASK_HPP_ #include "GraspSubTask.hpp" #include "Task.hpp" #include <rw/core/Ptr.hpp> namespace rwlibs { namespace task { /** * @brief A container for describing one or multiple grasping tasks. * It is based on the rwlibs::tasks library. * * Definition of GraspTask xml format * * GraspTask<br> * - p:string:"GripperName" - name of the gripper device * - p:string:"ControllerName" - defaults to GraspController * - p:string:"TCP" - name of the TCP frame */ class GraspTask { public: /// Smart pointer to this type of class. typedef rw::core::Ptr< GraspTask > Ptr; /** * Defines outcome of a single grasp result. * * @deprecated Use GraspResult::TestStatus instead. */ typedef GraspResult::TestStatus TestStatus; public: /** * @brief Default constructor. */ GraspTask () {} /** * @brief Constructs task from CartesianTask. */ GraspTask (rwlibs::task::CartesianTask::Ptr task); /** * @brief Converts GraspTask to CartesianTask. */ rwlibs::task::CartesianTask::Ptr toCartesianTask (); public: std::string getGripperID (); std::string getTCPID (); std::string getGraspControllerID (); void setGripperID (const std::string& id); void setTCPID (const std::string& id); void setGraspControllerID (const std::string& id); void addSubTask (class GraspSubTask& stask) { _subtasks.push_back (stask); } std::vector< class GraspSubTask >& getSubTasks () { return _subtasks; } /** * @brief Filters targets of the task to include only those whose status is included in the * filtering mask. New target list is created for the task, including only targets whose * status matches one of the provided in the includeMask. */ void filterTasks (std::vector< GraspResult::TestStatus >& includeMask); /** * @brief Iterates the grasptask and assemble all targets and the GraspSubTask that * they are associated to. * * @return vector of subtask and target pairs. */ std::vector< std::pair< class GraspSubTask*, class GraspTarget* > > getAllTargets (); /** * @copydoc GraspResult::toString * * @deprecated Use GraspResult::toString() method instead. */ static std::string toString (GraspResult::TestStatus status) { return GraspResult::toString (status); } /** * @brief save as UIBK format * @param task * @param name */ static void saveUIBK (GraspTask::Ptr task, const std::string& name); /** * * @param task * @param name */ static void saveRWTask (GraspTask::Ptr task, const std::string& name); /** * @brief Save a task in RobWork XML format. * @param task [in] the task to write. * @param stream [out] the stream to write to. */ static void saveRWTask (GraspTask::Ptr task, std::ostream& stream); /** * @brief save grasp task in a comma seperated format * @param task * @param name */ static void saveText (GraspTask::Ptr task, const std::string& name); /** * @brief load a GraspTask from file * @param name * @return */ static GraspTask::Ptr load (const std::string& name); /** * @brief load a GraspTask from istream * @param inputStream * @return */ static GraspTask::Ptr load (std::istringstream& inputStream); /** * @brief makes the copy of a task * * Copies over only the gripper ID, tcp ID, and the grasp controller ID. * Targets are NOT copied. */ GraspTask::Ptr clone () { GraspTask::Ptr res = rw::core::ownedPtr (new GraspTask ()); res->_gripperID = _gripperID; res->_tcpID = _tcpID; res->_graspControllerID = _graspControllerID; return res; } private: std::vector< class GraspSubTask > _subtasks; std::string _gripperID; std::string _tcpID; std::string _graspControllerID; }; }} // namespace rwlibs::task #endif /* GRASPTASK_HPP_ */
29.098765
99
0.562792
[ "vector" ]
1ba36e652f4cffb4575c258498afeee151033f88
2,007
cpp
C++
source/Main.cpp
redagito/Raytracer
451702eab28d6d69a122423f0e13aeb504d376a3
[ "MIT" ]
null
null
null
source/Main.cpp
redagito/Raytracer
451702eab28d6d69a122423f0e13aeb504d376a3
[ "MIT" ]
null
null
null
source/Main.cpp
redagito/Raytracer
451702eab28d6d69a122423f0e13aeb504d376a3
[ "MIT" ]
null
null
null
#include <chrono> #include <iostream> #include "RayTracer.h" #include "Scene.h" #include "ViewPlane.h" #include "Sphere.h" void addSphere(Scene& scene, const glm::dvec3& position, double radius, const glm::vec3& color) { auto sphere = std::make_unique<Sphere>(position, radius); sphere->material->color = color; scene.geometry.push_back(std::move(sphere)); } // Scene building function Scene build() { Scene scene; scene.material->color = glm::vec3{0.f, 0.f, 0.f}; // Mid addSphere(scene, {0.0, 0.0, 0.0}, 60.0, {1.f, 0.f, 0.f}); // Left top addSphere(scene, {-100.0, 100.0, 0.0}, 30.0, {0.f, 0.f, 1.f}); // Right bottom addSphere(scene, {50.0, -50.0, 0.0}, 20.0, {0.f, 1.f, 0.f}); // Mid top addSphere(scene, {0.0, 50.0, 0.0}, 30.0, {1.f, 1.f, 0.f}); // Mid front addSphere(scene, {0.0, 0.0, 60.0}, 10.0, {1.f, 0.f, 1.f}); return scene; } Image render(const Scene& scene, const RayTracer& tracer, const ViewPlane& viewPlane) { std::cout << "Start rendering scene" << std::endl; // Scene render with time measurement std::chrono::high_resolution_clock hrc; auto begin = hrc.now(); auto image = tracer.render(scene, viewPlane); auto end = hrc.now(); // Rendering time in milliseconds auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin); std::cout << "End rendering scene" << std::endl; std::cout << "Rendering time: " << diff.count() / 1000.f << " seconds" << std::endl; return image; } int main(int argc, const char** argv) { Scene scene = build(); RayTracer tracer; ViewPlane viewPlane; viewPlane.verticalResolution = 200; viewPlane.horizontalResolution = 200; viewPlane.pixelSize = 1.0; viewPlane.gamma = 1.0; auto image = render(scene, tracer, viewPlane); if (!save(image, "out.png")) { std::cout << "Failed to write image file" << std::endl; return 0; } std::cout << "Image written to file" << std::endl; return 0; }
27.121622
97
0.621325
[ "geometry", "render" ]
1ba63cc92f2b82e7318811074c9db2fddd44b0ab
2,906
cpp
C++
catkin_ws/src/beginner_tutorials/src/track_sequential.cpp
lies98/ROS_chasing_ball
6e1f08ed51a5b5f0c7b0bdebfb1bef2d3fe61949
[ "MIT" ]
null
null
null
catkin_ws/src/beginner_tutorials/src/track_sequential.cpp
lies98/ROS_chasing_ball
6e1f08ed51a5b5f0c7b0bdebfb1bef2d3fe61949
[ "MIT" ]
null
null
null
catkin_ws/src/beginner_tutorials/src/track_sequential.cpp
lies98/ROS_chasing_ball
6e1f08ed51a5b5f0c7b0bdebfb1bef2d3fe61949
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <cv_bridge/cv_bridge.h> #include <sensor_msgs/image_encodings.h> #include <sensor_msgs/Image.h> #include <image_transport/image_transport.h> #include <opencv2/objdetect/objdetect.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> class TrackSequential { public: TrackSequential(ros::NodeHandle nh_); ~TrackSequential(); image_transport::ImageTransport _imageTransport; image_transport::Subscriber image_sub; protected: void imageCB(const sensor_msgs::ImageConstPtr& msg); void ImageProcessing(); void ContourDetection(cv::Mat thresh_in, cv::Mat &output_); private: cv::Mat img_bgr, img1, img2, thresh, diff; int i; }; const std::string win1 = "Live Camera Feed"; const std::string win2 = "Threshold Difference"; TrackSequential::TrackSequential(ros::NodeHandle nh_): _imageTransport(nh_) { image_sub = _imageTransport.subscribe("turtlebot3_burger/camera1/image_raw", 1, &TrackSequential::imageCB, this, image_transport::TransportHints("compressed")); cv::namedWindow(win1, CV_WINDOW_FREERATIO); cv::namedWindow(win2, CV_WINDOW_FREERATIO); i=0; } TrackSequential::~TrackSequential() { cv::destroyWindow(win1); cv::destroyWindow(win2); } void TrackSequential::imageCB(const sensor_msgs::ImageConstPtr& msg) { cv_bridge::CvImagePtr cvPtr; try { cvPtr = cv_bridge::toCvCopy(msg, sensor_msgs::image_encodings::BGR8); } catch (cv_bridge::Exception& e) { ROS_ERROR("cv_bridge exception: %s", e.what()); return; } cvPtr->image.copyTo(img_bgr); cv::cvtColor(cvPtr->image, img1, cv::COLOR_BGR2GRAY); this->ImageProcessing(); img1.copyTo(img2); } void TrackSequential::ImageProcessing() { if(i!=0) { cv::absdiff(img1, img2, diff); cv::threshold(diff, thresh, 20, 255, cv::THRESH_BINARY); cv::morphologyEx(thresh, thresh, 2, cv::getStructuringElement( 2, cv::Size(3, 3))); this->ContourDetection(thresh, img_bgr); cv::imshow(win1, img_bgr); cv::imshow(win2, thresh); } ++i; cv::waitKey(1); } void TrackSequential::ContourDetection(cv::Mat thresh_in, cv::Mat &output_) { cv::Mat temp; cv::Rect objectBoundingRectangle = cv::Rect(0,0,0,0); thresh_in.copyTo(temp); std::vector<std::vector<cv::Point> > contours; std::vector<cv::Vec4i> hierarchy; cv::findContours(temp, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE); if(contours.size()>0) { std::vector<std::vector<cv::Point> > largest_contour; largest_contour.push_back(contours.at(contours.size()-1)); objectBoundingRectangle = cv::boundingRect(largest_contour.at(0)); int x = objectBoundingRectangle.x+objectBoundingRectangle.width/2; int y = objectBoundingRectangle.y+objectBoundingRectangle.height/2; cv::circle(output_,cv::Point(x,y),20,cv::Scalar(0,255,0),2); } } int main(int argc, char** argv) { ros::init(argc, argv, "TrackSequential"); ros::NodeHandle nh; TrackSequential ts(nh); ros::spin(); }
25.716814
161
0.737096
[ "vector" ]
1ba7809ad3a5226782115c9683049b4276618efe
3,701
cpp
C++
src/cup/cup.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/cup/cup.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
src/cup/cup.cpp
mnewhouse/tselements
bd1c6724018e862156948a680bb1bc70dd28bef6
[ "MIT" ]
null
null
null
/* * TS Elements * Copyright 2015-2018 M. Newhouse * Released under the MIT license. */ #include "cup.hpp" #include "cup_settings.hpp" #include <algorithm> namespace ts { namespace cup { Cup::Cup(const CupSettings& cup_settings) : tracks_(cup_settings.tracks), cars_(cup_settings.selected_cars), car_mode_(cup_settings.car_mode), max_player_count_(cup_settings.max_players) { } void Cup::add_track(const resources::TrackReferenceView& track_ref) { tracks_.emplace_back(track_ref); } void Cup::remove_track(const resources::TrackReferenceView& track_ref) { auto end = std::remove_if(tracks_.begin(), tracks_.end(), [track_ref](const resources::TrackReference& entry) { return track_ref.path == entry.path; }); tracks_.erase(end, tracks_.end()); } const std::vector<resources::TrackReference>& Cup::tracks() const { return tracks_; } void Cup::add_car(const resources::CarDefinition& car_desc) { cars_.push_back(car_desc); } void Cup::remove_car(const resources::CarDescriptionRef& car_desc) { auto end = std::remove_if(cars_.begin(), cars_.end(), [car_desc](const resources::CarDefinition& entry) { return entry.car_name == car_desc.name && entry.car_hash == car_desc.hash; }); cars_.erase(end, cars_.end()); } const std::vector<resources::CarDefinition>& Cup::cars() const { return cars_; } void Cup::set_car_mode(CarMode car_mode) { car_mode_ = car_mode; } CarMode Cup::car_mode() const { return car_mode_; } CupState Cup::cup_state() const { return cup_state_; } void Cup::set_cup_state(CupState cup_state) { cup_state_ = cup_state; } std::uint32_t Cup::current_stage() const { return current_stage_; } void Cup::set_current_stage(std::uint32_t stage) { current_stage_ = stage; } void Cup::advance_stage() { ++current_stage_; } void Cup::restart() { current_stage_ = 0; cup_state_ = CupState::Registration; } std::pair<std::uint16_t, RegistrationStatus> Cup::register_client(const PlayerDefinition* players, std::size_t player_count) { if (player_count != 0 && player_count_ + player_count >= max_player_count_) { return std::make_pair(invalid_client_id, RegistrationStatus::TooManyPlayers); } auto it = std::find_if(clients_.begin(), clients_.end(), [](const auto& optional_client) { return optional_client == boost::none; }); if (it == clients_.end()) { return std::make_pair(invalid_client_id, RegistrationStatus::TooManyClients); } it->emplace(); auto& client = **it; client.players.assign(players, players + player_count); player_count_ += player_count; client.id = static_cast<std::uint16_t>(std::distance(clients_.begin(), it)); if (client.id >= clients_end_) clients_end_ = client.id + 1; return std::make_pair(client.id, RegistrationStatus::Success); } void Cup::unregister_client(std::uint16_t client_id) { clients_[client_id] = boost::none; if (clients_end_ - 1 == client_id) { while (clients_end_ != 0 && clients_[client_id--] == boost::none) { --clients_end_; } } } Cup::client_range Cup::clients() const { return client_range(clients_.data(), clients_.data() + clients_end_); } } }
23.724359
85
0.607133
[ "vector" ]
1bb01d446b43dc875855560125b89c45e1afa84a
4,491
cc
C++
dash/test/memory/GlobStaticMemTest.cc
anonymousbitcoin/dash
e549524f25998f9fe2a5ecae240f5ef054a168c0
[ "BSD-3-Clause" ]
null
null
null
dash/test/memory/GlobStaticMemTest.cc
anonymousbitcoin/dash
e549524f25998f9fe2a5ecae240f5ef054a168c0
[ "BSD-3-Clause" ]
null
null
null
dash/test/memory/GlobStaticMemTest.cc
anonymousbitcoin/dash
e549524f25998f9fe2a5ecae240f5ef054a168c0
[ "BSD-3-Clause" ]
2
2019-10-02T23:19:22.000Z
2020-06-27T09:23:31.000Z
#include "GlobStaticMemTest.h" #include <dash/memory/GlobStaticMem.h> TEST_F(GlobStaticMemTest, ConstructorInitializerList) { auto target_local_elements = { 1, 2, 3, 4, 5, 6 }; auto target = dash::GlobStaticMem<int>(target_local_elements); std::vector<int> glob_values; for (dash::team_unit_t u{0}; u < dash::size(); u++) { for (int l = 0; l < target_local_elements.size(); l++) { int val = *(target.at(u,l)); EXPECT_EQ_U(l+1, val); glob_values.push_back(val); } } for (auto val : glob_values) { DASH_LOG_DEBUG_VAR("GlobStaticMemTest.ConstructorInitializerList", val); } int target_element; for (int l = 0; l < target_local_elements.size(); l++) { target.get_value(&target_element, l); EXPECT_EQ_U(l+1, target_element); } } TEST_F(GlobStaticMemTest, GlobalRandomAccess) { auto globmem_local_elements = { 1, 2, 3 }; auto globmem = dash::GlobStaticMem<int>(globmem_local_elements); DASH_LOG_DEBUG_VAR("GlobStaticMemTest", globmem.size()); EXPECT_EQ_U(globmem.size(), 3 * dash::size()); if (dash::myid() == 0) { auto gbegin = globmem.begin(); auto glast = gbegin + (globmem.size() - 1); auto gend = gbegin + globmem.size(); DASH_LOG_DEBUG_VAR("GlobStaticMemTest", gbegin); DASH_LOG_DEBUG_VAR("GlobStaticMemTest", glast); DASH_LOG_DEBUG_VAR("GlobStaticMemTest", gend); // Test distance in global memory over multiple unit spaces: EXPECT_EQ(gend - gbegin, globmem.size()); EXPECT_EQ(glast - gbegin, globmem.size() - 1); // Iterate entire global memory space, including end pointer: for (int g = 0; g <= globmem.size(); ++g) { DASH_LOG_DEBUG_VAR("GlobStaticMemTest", gbegin); // Do not dereference end pointer: if (g < globmem.size()) { int gvalue = *gbegin; EXPECT_EQ((g % 3) + 1, gvalue); EXPECT_EQ(*gbegin, globmem.begin()[g]); } EXPECT_EQ( gbegin, globmem.begin() + g); EXPECT_EQ( (globmem.size() - g), dash::distance(gbegin, gend)); EXPECT_EQ(-(globmem.size() - g), dash::distance(gend, gbegin)); EXPECT_EQ(gend - gbegin, dash::distance(gbegin, gend)); EXPECT_EQ(gbegin - gend, dash::distance(gend, gbegin)); if (g % 2 == 0) { ++gbegin; } else { gbegin++; } } } dash::barrier(); if (dash::myid() == dash::size() - 1) { auto gbegin = globmem.begin(); auto gend = gbegin + globmem.size(); // Reverse iteratation on entire global memory space, starting at // end pointer: for (int g = globmem.size(); g >= 0; --g) { DASH_LOG_DEBUG_VAR("GlobStaticMemTest", gend); // Do not dereference end pointer: if (g < globmem.size()) { int gvalue = *gend; EXPECT_EQ((g % 3) + 1, gvalue); } EXPECT_EQ(gend, globmem.begin() + g); EXPECT_EQ(gend - gbegin, dash::distance(gbegin, gend)); EXPECT_EQ(gbegin - gend, dash::distance(gend, gbegin)); if (g % 2 == 0) { --gend; } else { gend--; } } } } TEST_F(GlobStaticMemTest, LocalBegin) { auto target_local_elements = { 1, 2, 3, 4 }; if(!dash::Team::All().is_leaf()){ SKIP_TEST_MSG("Team is already split"); } auto & sub_team = dash::size() < 4 ? dash::Team::All() : dash::Team::All().split(2); auto target = dash::GlobStaticMem<int>(target_local_elements, sub_team); for (int l = 0; l < target_local_elements.size(); l++) { EXPECT_EQ_U(*(target_local_elements.begin() + l), target.lbegin()[l]); } EXPECT_NE_U(target.lbegin(), nullptr); } TEST_F(GlobStaticMemTest, MoveSemantics){ using memory_t = dash::GlobStaticMem<int>; // move construction { memory_t memory_a(10); *(memory_a.lbegin()) = 5; dash::barrier(); memory_t memory_b(std::move(memory_a)); int value = *(memory_b.lbegin()); ASSERT_EQ_U(value, 5); } dash::barrier(); //move assignment { memory_t memory_a(10); { memory_t memory_b(8); *(memory_a.lbegin()) = 1; *(memory_b.lbegin()) = 2; memory_a = std::move(memory_b); // leave scope of memory_b } ASSERT_EQ_U(*(memory_a.lbegin()), 2); } dash::barrier(); // swap { memory_t memory_a(10); memory_t memory_b(8); *(memory_a.lbegin()) = 1; *(memory_b.lbegin()) = 2; std::swap(memory_a, memory_b); ASSERT_EQ_U(*(memory_a.lbegin()), 2); ASSERT_EQ_U(*(memory_b.lbegin()), 1); } }
28.245283
76
0.60432
[ "vector" ]
1bb3157e9a35f2470fed8f7f99eec06f1f9d2e0b
845
cpp
C++
example/fft_ex03.cpp
BoostGSoC21/math
60051b121de05d7084ae1eb78053a209d06b7860
[ "BSL-1.0" ]
null
null
null
example/fft_ex03.cpp
BoostGSoC21/math
60051b121de05d7084ae1eb78053a209d06b7860
[ "BSL-1.0" ]
30
2021-06-22T12:59:38.000Z
2021-09-02T09:27:49.000Z
example/fft_ex03.cpp
BoostGSoC21/math
60051b121de05d7084ae1eb78053a209d06b7860
[ "BSL-1.0" ]
1
2021-06-07T21:15:02.000Z
2021-06-07T21:15:02.000Z
/* boost::math::fft example 03. FFT plan-like API, default engine */ #include <boost/math/fft/bsl_backend.hpp> #include <iostream> #include <vector> #include <complex> namespace fft = boost::math::fft; template<class T> void print(const std::vector< std::complex<T> >& V) { for(auto i=0UL;i<V.size();++i) std::cout << "V[" << i << "] = " << V[i].real() << ", " << V[i].imag() << '\n'; } int main() { std::vector< std::complex<double> > A{1.0,2.0,3.0,4.0},B(A.size()); // default engine, create plan fft::bsl_dft<std::complex<double>> P(A.size()); // forward transform, out-of-place P.forward(A.cbegin(),A.cend(),B.begin()); print(B); // backward transform, in-place P.backward(B.cbegin(),B.cend(),B.begin()); print(B); return 0; }
19.204545
71
0.544379
[ "vector", "transform" ]
1bb3da7bd6330f2811b4f391005ca259701318cf
3,378
cpp
C++
src/UserInterface/src/Widget/AbstractSimulationVariableWidget.cpp
till213/SkyDolly
75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16
[ "MIT" ]
21
2021-03-01T00:19:41.000Z
2022-02-22T02:57:19.000Z
src/UserInterface/src/Widget/AbstractSimulationVariableWidget.cpp
till213/SkyDolly
75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16
[ "MIT" ]
11
2021-06-20T20:16:56.000Z
2022-03-28T19:03:34.000Z
src/UserInterface/src/Widget/AbstractSimulationVariableWidget.cpp
till213/SkyDolly
75caa54fa9fcbaae04b6605c3c1a68e0cb9a0c16
[ "MIT" ]
3
2021-04-06T19:06:16.000Z
2022-01-20T21:22:39.000Z
/** * Sky Dolly - The Black Sheep for your Flight Recordings * * Copyright (c) Oliver Knoll * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ #include <memory> #include <QWidget> #include "../../../Model/src/Logbook.h" #include "../../../Model/src/Flight.h" #include "../../../SkyConnect/src/SkyConnectManager.h" #include "../../../SkyConnect/src/SkyConnectIntf.h" #include "../../../SkyConnect/src/Connect.h" #include "AbstractSimulationVariableWidget.h" AbstractSimulationVariableWidget ::AbstractSimulationVariableWidget(QWidget *parent) noexcept : QWidget(parent) {} AbstractSimulationVariableWidget::~AbstractSimulationVariableWidget() noexcept {} // PROTECTED void AbstractSimulationVariableWidget::showEvent(QShowEvent *event) noexcept { QWidget::showEvent(event); SkyConnectManager &skyConnectManager = SkyConnectManager::getInstance(); connect(&skyConnectManager, &SkyConnectManager::timestampChanged, this, &AbstractSimulationVariableWidget::updateUi); std::optional<std::reference_wrapper<SkyConnectIntf>> skyConnect = skyConnectManager.getCurrentSkyConnect(); if (skyConnect) { updateUi(skyConnect->get().getCurrentTimestamp(), TimeVariableData::Access::Seek); } Flight &flight = Logbook::getInstance().getCurrentFlight(); connect(&flight, &Flight::userAircraftChanged, this, &AbstractSimulationVariableWidget::updateUiWithCurrentTime); } void AbstractSimulationVariableWidget::hideEvent(QHideEvent *event) noexcept { QWidget::hideEvent(event); SkyConnectManager &skyConnectManager = SkyConnectManager::getInstance(); disconnect(&skyConnectManager, &SkyConnectManager::timestampChanged, this, &AbstractSimulationVariableWidget::updateUi); Flight &flight = Logbook::getInstance().getCurrentFlight(); disconnect(&flight, &Flight::userAircraftChanged, this, &AbstractSimulationVariableWidget::updateUiWithCurrentTime); } // PRIVATE SLOTS void AbstractSimulationVariableWidget::updateUiWithCurrentTime() noexcept { const std::optional<std::reference_wrapper<SkyConnectIntf>> skyConnect = SkyConnectManager::getInstance().getCurrentSkyConnect(); if (skyConnect) { updateUi(skyConnect->get().getCurrentTimestamp(), TimeVariableData::Access::Seek); } }
40.214286
133
0.75222
[ "model" ]
1bba8c1d58a6c2e5e0ab891da61f117f50ffd342
1,503
cpp
C++
CSES/Tree_Diameter.cpp
aldew5/Competitve-Programming
eb0b93a35af3bd5e806aedc44b835830af01d496
[ "MIT" ]
2
2020-05-09T15:54:18.000Z
2021-01-23T22:32:53.000Z
CSES/Tree_Diameter.cpp
aldew5/Competitive-Programming
fc93723fae739d0b06bcf2dbe3b9274584a79a66
[ "MIT" ]
null
null
null
CSES/Tree_Diameter.cpp
aldew5/Competitive-Programming
fc93723fae739d0b06bcf2dbe3b9274584a79a66
[ "MIT" ]
null
null
null
/* ID: alec3 LANG: C++14 PROG: /* Pick an arbitrary node a. DFS from a to a leaf then DFS from the leaf (b) to the corresponding leaf c. The distance between b and c is the diameter. */ #include <bits/stdc++.h> #define check(x) cout<<(#x)<<": "<<x<<" " << endl; #define line cout << "--------------" << endl; #define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define ss second #define ff first #define pb push_back #define lb lower_bound #define ub upper_bound #define ld long double #define all(c) (c).begin(), (c).end() #define FOR(i, a, b) for (int i = a; i < b; i++) #define F0R(i, n) for (int i = 0; i < n; i++) typedef long long ll; typedef unsigned long long ull; int pct(int x) { return __builtin_popcount(x); } using namespace std; void setIO(string name) { freopen((name+".in").c_str(),"r",stdin); freopen((name+".out").c_str(),"w",stdout); ios_base::sync_with_stdio(0); } int n; vector<int> adj[200001]; int leaf = -1; bool visit[200001]; int ans = 0; void dfs(int n, int c){ if (visit[n]) return; visit[n] = true; if (c > ans) leaf = n; ans = max(ans, c); for (auto u : adj[n]) dfs(u, c+1); return; } int main () { cin >> n; int a, b; F0R(i, n-1){ cin >> a >> b; adj[a].pb(b); adj[b].pb(a); } dfs(1, 0); for (int i = 0; i <= n; i++) visit[i] = false; //cout << "LEAF is " << leaf << endl; ans = 0; dfs(leaf, 0); cout << ans << endl; }
17.275862
77
0.55356
[ "vector" ]
1bbf7089233562467e857d70cf72fede1b794181
2,697
cpp
C++
day6/part2.cpp
deltj/advent_of_code_2020
52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1
[ "MIT" ]
null
null
null
day6/part2.cpp
deltj/advent_of_code_2020
52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1
[ "MIT" ]
null
null
null
day6/part2.cpp
deltj/advent_of_code_2020
52d1eeeff6ba0df6bc49679ae9fc73e04a543ca1
[ "MIT" ]
null
null
null
/** * Count customs declaration answers */ #include <cstdlib> #include <fstream> #include <iostream> #include <set> #include <sstream> #include <vector> #include <boost/algorithm/string.hpp> bool everyoneSaysYes(std::vector<std::set<char> > responses, char q) { for(std::vector<std::set<char> >::const_iterator it=responses.begin(); it!=responses.end(); ++it) { if(it->count(q) == 0) { return false; } } return true; } void usage() { std::cout << "day6 <input.txt>" << std::endl; } int main(int argc, char *argv[]) { if(argc != 2) { usage(); return EXIT_FAILURE; } std::ifstream ifs(argv[1], std::ifstream::in); std::string line; int total = 0; std::vector<std::set<char> > groupResponse; while(std::getline(ifs, line)) { std::set<char> singleResponse; // Treat an empty line as a record separator if(line.length() == 0) { int groupCount = 0; if(groupResponse.size() > 0) { // Loop over the first person's responses; any question that // everyone in the group responded 'yes' to will be in this set for(std::set<char>::const_iterator it=groupResponse[0].begin(); it!=groupResponse[0].end(); ++it) { if(everyoneSaysYes(groupResponse, *it)) { groupCount++; } } } groupResponse.clear(); std::cout << "group count: " << groupCount << std::endl; std::cout << "-----------------------" << std::endl; total += groupCount; } else { std::cout << line << std::endl; for(int i=0; i<line.length(); ++i) { singleResponse.insert(line.at(i)); } groupResponse.push_back(singleResponse); } } int groupCount = 0; if(groupResponse.size() > 0) { // Loop over the first person's responses; any question that // everyone in the group responded 'yes' to will be in this set for(std::set<char>::const_iterator it=groupResponse[0].begin(); it!=groupResponse[0].end(); ++it) { if(everyoneSaysYes(groupResponse, *it)) { groupCount++; } } } groupResponse.clear(); std::cout << "group count: " << groupCount << std::endl; std::cout << "-----------------------" << std::endl; total += groupCount; std::cout << "total " << total << std::endl; ifs.close(); }
24.972222
113
0.494994
[ "vector" ]
1bc0d7fe85ddfcb3b24aa2d592879266d47249aa
7,198
cpp
C++
src/native/common/jp_methodoverload.cpp
remram44/jpype
f89974af249f6b38c0698c4c8275f71ac4356b5b
[ "Apache-2.0" ]
1
2017-11-29T11:16:44.000Z
2017-11-29T11:16:44.000Z
src/native/common/jp_methodoverload.cpp
vanschelven/jpype_05
11bbb56e147eed69839711eff545c0fb175b1892
[ "Apache-2.0" ]
null
null
null
src/native/common/jp_methodoverload.cpp
vanschelven/jpype_05
11bbb56e147eed69839711eff545c0fb175b1892
[ "Apache-2.0" ]
2
2019-12-16T09:45:03.000Z
2021-04-15T00:20:24.000Z
/***************************************************************************** Copyright 2004 Steve M�nard Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ #include <jpype.h> JPMethodOverload::JPMethodOverload() { m_Method = NULL; } JPMethodOverload::JPMethodOverload(const JPMethodOverload& o) : m_Class(o.m_Class), m_MethodID(o.m_MethodID), m_ReturnType(o.m_ReturnType), m_Arguments(o.m_Arguments), m_IsStatic(o.m_IsStatic), m_IsFinal(o.m_IsFinal), m_IsConstructor(o.m_IsConstructor) { m_Method = JPEnv::getJava()->NewGlobalRef(o.m_Method); } JPMethodOverload::JPMethodOverload(JPClass* claz, jobject mth) { m_Class = claz; m_Method = JPEnv::getJava()->NewGlobalRef(mth); // static m_IsStatic = JPJni::isMemberStatic(mth); m_IsFinal = JPJni::isMemberStatic(m_Method); // Method ID m_MethodID = JPEnv::getJava()->FromReflectedMethod(mth); m_IsConstructor = JPJni::isConstructor(m_Method); // return type if (! m_IsConstructor) { m_ReturnType = JPJni::getReturnType(mth); } // arguments m_Arguments = JPJni::getParameterTypes(mth, m_IsConstructor); // Add the implicit "this" argument if (! m_IsStatic && ! m_IsConstructor) { m_Arguments.insert(m_Arguments.begin(), 1, claz->getName()); } } JPMethodOverload::~JPMethodOverload() { JPEnv::getJava()->DeleteGlobalRef(m_Method); } string JPMethodOverload::getSignature() { stringstream res; res << "("; for (vector<JPTypeName>::iterator it = m_Arguments.begin(); it != m_Arguments.end(); it++) { res << it->getNativeName(); } res << ")" ; return res.str(); } string JPMethodOverload::getArgumentString() { stringstream res; res << "("; bool first = true; for (vector<JPTypeName>::iterator it = m_Arguments.begin(); it != m_Arguments.end(); it++) { if (! first) { res << ", "; } else { first = false; } res << it->getSimpleName(); } res << ")"; return res.str(); } bool JPMethodOverload::isSameOverload(JPMethodOverload& o) { if (isStatic() != o.isStatic()) { return false; } if (m_Arguments.size() != o.m_Arguments.size()) { return false; } TRACE_IN("JPMethodOverload::isSameOverload"); TRACE2("My sig", getSignature()); TRACE2("It's sig", o.getSignature()); int start = 0; if (! isStatic()) { start = 1; } for (unsigned int i = start; i < m_Arguments.size() && i < o.m_Arguments.size(); i++) { JPTypeName mine = m_Arguments[i]; JPTypeName his = o.m_Arguments[i]; string mineSimple = mine.getSimpleName(); string hisSimple = his.getSimpleName(); if (mineSimple != hisSimple) { return false; } } return true; TRACE_OUT; } EMatchType JPMethodOverload::matches(bool ignoreFirst, vector<HostRef*>& arg) { TRACE_IN("JPMethodOverload::matches"); size_t len = arg.size(); if (len != m_Arguments.size()) { return _none; } EMatchType lastMatch = _exact; for (unsigned int i = 0; i < len; i++) { if (i == 0 && ignoreFirst) { continue; } HostRef* obj = arg[i]; JPType* type = JPTypeManager::getType(m_Arguments[i]); EMatchType match = type->canConvertToJava(obj); if (match < _implicit) { return _none; } if (match < lastMatch) { lastMatch = match; } } return lastMatch; TRACE_OUT; } HostRef* JPMethodOverload::invokeStatic(vector<HostRef*>& arg) { TRACE_IN("JPMethodOverload::invokeStatic"); JPCleaner cleaner; size_t len = arg.size(); JPMallocCleaner<jvalue> v(len); JPMallocCleaner<JPType*> types(len); for (unsigned int i = 0; i < len; i++) { HostRef* obj = arg[i]; types[i] = JPTypeManager::getType(m_Arguments[i]); v[i] = types[i]->convertToJava(obj); if (types[i]->isObjectType()) { cleaner.addLocal(v[i].l); } } jclass claz = m_Class->getClass(); cleaner.addLocal(claz); JPType* retType = JPTypeManager::getType(m_ReturnType); return retType->invokeStatic(claz, m_MethodID, v.borrow()); TRACE_OUT; } HostRef* JPMethodOverload::invokeInstance(vector<HostRef*>& args) { TRACE_IN("JPMethodOverload::invokeInstance"); HostRef* res; { JPCleaner cleaner; // Arg 0 is "this" HostRef* self = args[0]; JPObject* selfObj = JPEnv::getHost()->asObject(self); size_t len = args.size(); JPMallocCleaner<jvalue> v(len-1); for (unsigned int i = 1; i < len; i++) { HostRef* obj = args[i]; JPType* type = JPTypeManager::getType(m_Arguments[i]); v[i-1] = type->convertToJava(obj); if (type->isObjectType()) { cleaner.addLocal(v[i-1].l); } } JPType* retType = JPTypeManager::getType(m_ReturnType); jobject c = selfObj->getObject(); cleaner.addLocal(c); jclass clazz = m_Class->getClass(); cleaner.addLocal(clazz); res = retType->invoke(c, clazz, m_MethodID, v.borrow()); TRACE1("Call finished"); } TRACE1("Call successfull"); return res; TRACE_OUT; } JPObject* JPMethodOverload::invokeConstructor(jclass claz, vector<HostRef*>& arg) { TRACE_IN("JPMethodOverload::invokeConstructor"); size_t len = arg.size(); JPCleaner cleaner; JPMallocCleaner<jvalue> v(len); for (unsigned int i = 0; i < len; i++) { HostRef* obj = arg[i]; // TODO the following can easily be optimized ... or at least cached JPType* t = JPTypeManager::getType(m_Arguments[i]); v[i] = t->convertToJava(obj); if (t->isObjectType()) { cleaner.addLocal(v[i].l); } } jvalue val; val.l = JPEnv::getJava()->NewObjectA(claz, m_MethodID, v.borrow()); cleaner.addLocal(val.l); TRACE1("Object created"); JPTypeName name = JPJni::getName(claz); return new JPObject(name, val.l); TRACE_OUT; } string JPMethodOverload::matchReport(vector<HostRef*>& args) { stringstream res; res << m_ReturnType.getNativeName() << " ("; bool isFirst = true; for (vector<JPTypeName>::iterator it = m_Arguments.begin(); it != m_Arguments.end(); it++) { if (isFirst && ! isStatic()) { isFirst = false; continue; } isFirst = false; res << it->getNativeName(); } res << ") ==> "; EMatchType match = matches(! isStatic(), args); switch(match) { case _none : res << "NONE"; break; case _explicit : res << "EXPLICIT"; break; case _implicit : res << "IMPLICIT"; break; case _exact : res << "EXACT"; break; default : res << "UNKNOWN"; break; } res << endl; return res.str(); }
21.233038
92
0.618227
[ "object", "vector" ]
1bc66fd54f0fc55f7090f3de7bb8f0b41c4c7e1f
6,786
hh
C++
src/mem/coward_addr_mapper.hh
believe7028/gem5
9486ad465cbecd816a8d9500d05fa86c573756dd
[ "BSD-3-Clause" ]
null
null
null
src/mem/coward_addr_mapper.hh
believe7028/gem5
9486ad465cbecd816a8d9500d05fa86c573756dd
[ "BSD-3-Clause" ]
null
null
null
src/mem/coward_addr_mapper.hh
believe7028/gem5
9486ad465cbecd816a8d9500d05fa86c573756dd
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2012 ARM Limited * All rights reserved * * The license below extends only to copyright in the software and shall * not be construed as granting a license to any other intellectual * property including but not limited to intellectual property relating * to a hardware implementation of the functionality of the software * licensed hereunder. You may use the software subject to the license * terms below provided that you ensure that this notice is replicated * unmodified and in its entirety in all distributions of the software, * modified or unmodified, in source code or in binary form. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer; * redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution; * neither the name of the copyright 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 COPYRIGHT * OWNER 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. * * Authors: Andreas Hansson */ #ifndef __MEM_COWARD_ADDR_MAPPER_HH__ #define __MEM_COWARD_ADDR_MAPPER_HH__ #include "mem/mem_object.hh" #include "params/CowardAddrMapper.hh" /** * An address mapper changes the packet addresses in going from the * slave port side of the mapper to the master port side. When the * slave port is queried for the address ranges, it also performs the * necessary range updates. Note that snoop requests that travel from * the master port (i.e. the memory side) to the slave port are * currently not modified. */ class CowardAddrMapper : public MemObject { public: CowardAddrMapper(const CowardAddrMapperParams* params); virtual ~CowardAddrMapper() { } virtual BaseSlavePort& getSlavePort(const std::string& if_name, PortID idx = InvalidPortID); virtual BaseMasterPort& getMasterPort(const std::string& if_name, PortID idx = InvalidPortID); virtual void init(); protected: class CowardAddrMapperSenderState : public Packet::SenderState { public: /** * Construct a new sender state to remember the original address. * * @param _origAddr Address before remapping */ CowardAddrMapperSenderState(Addr _origAddr) : origAddr(_origAddr) { } /** Destructor */ ~CowardAddrMapperSenderState() { } /** The original address the packet was destined for */ Addr origAddr; }; class MapperSlavePort : public SlavePort { public: MapperSlavePort(const std::string& _name, CowardAddrMapper& _mapper) : SlavePort(_name, &_mapper), mapper(_mapper) { } protected: void recvFunctional(PacketPtr pkt) { mapper.recvFunctional(pkt); } Tick recvAtomic(PacketPtr pkt) { return mapper.recvAtomic(pkt); } bool recvTimingReq(PacketPtr pkt) { return mapper.recvTimingReq(pkt); } bool recvTimingSnoopResp(PacketPtr pkt) { return mapper.recvTimingSnoopResp(pkt); } AddrRangeList getAddrRanges() const { return mapper.getAddrRanges(); } void recvRespRetry() { mapper.recvRespRetry(); } private: CowardAddrMapper& mapper; }; /** Instance of slave port, i.e. on the CPU side */ MapperSlavePort slavePort; class MapperMasterPort : public MasterPort { public: MapperMasterPort(const std::string& _name, CowardAddrMapper& _mapper) : MasterPort(_name, &_mapper), mapper(_mapper) { } protected: void recvFunctionalSnoop(PacketPtr pkt) { mapper.recvFunctionalSnoop(pkt); } Tick recvAtomicSnoop(PacketPtr pkt) { return mapper.recvAtomicSnoop(pkt); } bool recvTimingResp(PacketPtr pkt) { return mapper.recvTimingResp(pkt); } void recvTimingSnoopReq(PacketPtr pkt) { mapper.recvTimingSnoopReq(pkt); } void recvRangeChange() { mapper.recvRangeChange(); } bool isSnooping() const { return mapper.isSnooping(); } void recvReqRetry() { mapper.recvReqRetry(); } private: CowardAddrMapper& mapper; }; /** Instance of master port, facing the memory side */ MapperMasterPort masterPort; /** * This contains a list of ranges the should be remapped. It must * be the exact same length as remappedRanges which describes what * manipulation should be done to each range. */ std::vector<AddrRange> originalRanges; /** * This contains a list of ranges that addresses should be * remapped to. See the description for originalRanges above */ std::vector<AddrRange> remappedRanges; bool verbose; void recvFunctional(PacketPtr pkt); void recvFunctionalSnoop(PacketPtr pkt); Tick recvAtomic(PacketPtr pkt); Tick recvAtomicSnoop(PacketPtr pkt); bool recvTimingReq(PacketPtr pkt); bool recvTimingResp(PacketPtr pkt); void recvTimingSnoopReq(PacketPtr pkt); bool recvTimingSnoopResp(PacketPtr pkt); bool isSnooping() const; void recvReqRetry(); void recvRespRetry(); void recvRangeChange(); AddrRangeList getAddrRanges() const; Addr remapAddr(Addr addr) const; }; #endif //__MEM_COWARD_ADDR_MAPPER_HH__
27.697959
77
0.667403
[ "vector" ]
1bc70a5b3217e23d446194c56bc8a0a78125bbb0
27,646
cc
C++
src/tint/resolver/function_validation_test.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
src/tint/resolver/function_validation_test.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
src/tint/resolver/function_validation_test.cc
encounter/dawn-cmake
64a23ce0ede5f232cc209b69d64164ede6810b65
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The Tint Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "src/tint/ast/discard_statement.h" #include "src/tint/ast/return_statement.h" #include "src/tint/ast/stage_attribute.h" #include "src/tint/resolver/resolver.h" #include "src/tint/resolver/resolver_test_helper.h" #include "gmock/gmock.h" using namespace tint::number_suffixes; // NOLINT namespace tint::resolver { namespace { class ResolverFunctionValidationTest : public TestHelper, public testing::Test {}; TEST_F(ResolverFunctionValidationTest, DuplicateParameterName) { // fn func_a(common_name : f32) { } // fn func_b(common_name : f32) { } Func("func_a", {Param("common_name", ty.f32())}, ty.void_(), {}); Func("func_b", {Param("common_name", ty.f32())}, ty.void_(), {}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, ParameterMayShadowGlobal) { // var<private> common_name : f32; // fn func(common_name : f32) { } Global("common_name", ty.f32(), ast::StorageClass::kPrivate); Func("func", {Param("common_name", ty.f32())}, ty.void_(), {}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, LocalConflictsWithParameter) { // fn func(common_name : f32) { // let common_name = 1i; // } Func("func", {Param(Source{{12, 34}}, "common_name", ty.f32())}, ty.void_(), {Decl(Let(Source{{56, 78}}, "common_name", nullptr, Expr(1_i)))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), R"(56:78 error: redeclaration of 'common_name' 12:34 note: 'common_name' previously declared here)"); } TEST_F(ResolverFunctionValidationTest, NestedLocalMayShadowParameter) { // fn func(common_name : f32) { // { // let common_name = 1i; // } // } Func("func", {Param(Source{{12, 34}}, "common_name", ty.f32())}, ty.void_(), {Block(Decl(Let(Source{{56, 78}}, "common_name", nullptr, Expr(1_i))))}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, VoidFunctionEndWithoutReturnStatement_Pass) { // fn func { var a:i32 = 2i; } auto* var = Var("a", ty.i32(), Expr(2_i)); Func(Source{{12, 34}}, "func", ast::VariableList{}, ty.void_(), ast::StatementList{ Decl(var), }); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionUsingSameVariableName_Pass) { // fn func() -> i32 { // var func:i32 = 0i; // return func; // } auto* var = Var("func", ty.i32(), Expr(0_i)); Func("func", ast::VariableList{}, ty.i32(), ast::StatementList{ Decl(var), Return(Source{{12, 34}}, Expr("func")), }, ast::AttributeList{}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionNameSameAsFunctionScopeVariableName_Pass) { // fn a() -> void { var b:i32 = 0i; } // fn b() -> i32 { return 2; } auto* var = Var("b", ty.i32(), Expr(0_i)); Func("a", ast::VariableList{}, ty.void_(), ast::StatementList{ Decl(var), }, ast::AttributeList{}); Func(Source{{12, 34}}, "b", ast::VariableList{}, ty.i32(), ast::StatementList{ Return(2_i), }, ast::AttributeList{}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, UnreachableCode_return) { // fn func() -> { // var a : i32; // return; // a = 2i; //} auto* decl_a = Decl(Var("a", ty.i32())); auto* ret = Return(); auto* assign_a = Assign(Source{{12, 34}}, "a", 2_i); Func("func", ast::VariableList{}, ty.void_(), {decl_a, ret, assign_a}); ASSERT_TRUE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 warning: code is unreachable"); EXPECT_TRUE(Sem().Get(decl_a)->IsReachable()); EXPECT_TRUE(Sem().Get(ret)->IsReachable()); EXPECT_FALSE(Sem().Get(assign_a)->IsReachable()); } TEST_F(ResolverFunctionValidationTest, UnreachableCode_return_InBlocks) { // fn func() -> { // var a : i32; // {{{return;}}} // a = 2i; //} auto* decl_a = Decl(Var("a", ty.i32())); auto* ret = Return(); auto* assign_a = Assign(Source{{12, 34}}, "a", 2_i); Func("func", ast::VariableList{}, ty.void_(), {decl_a, Block(Block(Block(ret))), assign_a}); ASSERT_TRUE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 warning: code is unreachable"); EXPECT_TRUE(Sem().Get(decl_a)->IsReachable()); EXPECT_TRUE(Sem().Get(ret)->IsReachable()); EXPECT_FALSE(Sem().Get(assign_a)->IsReachable()); } TEST_F(ResolverFunctionValidationTest, UnreachableCode_discard) { // fn func() -> { // var a : i32; // discard; // a = 2i; //} auto* decl_a = Decl(Var("a", ty.i32())); auto* discard = Discard(); auto* assign_a = Assign(Source{{12, 34}}, "a", 2_i); Func("func", ast::VariableList{}, ty.void_(), {decl_a, discard, assign_a}); ASSERT_TRUE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 warning: code is unreachable"); EXPECT_TRUE(Sem().Get(decl_a)->IsReachable()); EXPECT_TRUE(Sem().Get(discard)->IsReachable()); EXPECT_FALSE(Sem().Get(assign_a)->IsReachable()); } TEST_F(ResolverFunctionValidationTest, UnreachableCode_discard_InBlocks) { // fn func() -> { // var a : i32; // {{{discard;}}} // a = 2i; //} auto* decl_a = Decl(Var("a", ty.i32())); auto* discard = Discard(); auto* assign_a = Assign(Source{{12, 34}}, "a", 2_i); Func("func", ast::VariableList{}, ty.void_(), {decl_a, Block(Block(Block(discard))), assign_a}); ASSERT_TRUE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 warning: code is unreachable"); EXPECT_TRUE(Sem().Get(decl_a)->IsReachable()); EXPECT_TRUE(Sem().Get(discard)->IsReachable()); EXPECT_FALSE(Sem().Get(assign_a)->IsReachable()); } TEST_F(ResolverFunctionValidationTest, FunctionEndWithoutReturnStatement_Fail) { // fn func() -> int { var a:i32 = 2i; } auto* var = Var("a", ty.i32(), Expr(2_i)); Func(Source{{12, 34}}, "func", ast::VariableList{}, ty.i32(), ast::StatementList{ Decl(var), }, ast::AttributeList{}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: missing return at end of function"); } TEST_F(ResolverFunctionValidationTest, VoidFunctionEndWithoutReturnStatementEmptyBody_Pass) { // fn func {} Func(Source{{12, 34}}, "func", ast::VariableList{}, ty.void_(), ast::StatementList{}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionEndWithoutReturnStatementEmptyBody_Fail) { // fn func() -> int {} Func(Source{{12, 34}}, "func", ast::VariableList{}, ty.i32(), ast::StatementList{}, ast::AttributeList{}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: missing return at end of function"); } TEST_F(ResolverFunctionValidationTest, FunctionTypeMustMatchReturnStatementType_Pass) { // fn func { return; } Func("func", ast::VariableList{}, ty.void_(), ast::StatementList{ Return(), }); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionTypeMustMatchReturnStatementType_fail) { // fn func { return 2i; } Func("func", ast::VariableList{}, ty.void_(), ast::StatementList{ Return(Source{{12, 34}}, Expr(2_i)), }, ast::AttributeList{}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: return statement type must match its function return " "type, returned 'i32', expected 'void'"); } TEST_F(ResolverFunctionValidationTest, FunctionTypeMustMatchReturnStatementType_void_fail) { // fn v { return; } // fn func { return v(); } Func("v", {}, ty.void_(), {Return()}); Func("func", {}, ty.void_(), { Return(Call(Source{{12, 34}}, "v")), }); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: function 'v' does not return a value"); } TEST_F(ResolverFunctionValidationTest, FunctionTypeMustMatchReturnStatementTypeMissing_fail) { // fn func() -> f32 { return; } Func("func", ast::VariableList{}, ty.f32(), ast::StatementList{ Return(Source{{12, 34}}, nullptr), }, ast::AttributeList{}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: return statement type must match its function return " "type, returned 'void', expected 'f32'"); } TEST_F(ResolverFunctionValidationTest, FunctionTypeMustMatchReturnStatementTypeF32_pass) { // fn func() -> f32 { return 2.0; } Func("func", ast::VariableList{}, ty.f32(), ast::StatementList{ Return(Source{{12, 34}}, Expr(2.f)), }, ast::AttributeList{}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionTypeMustMatchReturnStatementTypeF32_fail) { // fn func() -> f32 { return 2i; } Func("func", ast::VariableList{}, ty.f32(), ast::StatementList{ Return(Source{{12, 34}}, Expr(2_i)), }, ast::AttributeList{}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: return statement type must match its function return " "type, returned 'i32', expected 'f32'"); } TEST_F(ResolverFunctionValidationTest, FunctionTypeMustMatchReturnStatementTypeF32Alias_pass) { // type myf32 = f32; // fn func() -> myf32 { return 2.0; } auto* myf32 = Alias("myf32", ty.f32()); Func("func", ast::VariableList{}, ty.Of(myf32), ast::StatementList{ Return(Source{{12, 34}}, Expr(2.f)), }, ast::AttributeList{}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionTypeMustMatchReturnStatementTypeF32Alias_fail) { // type myf32 = f32; // fn func() -> myf32 { return 2u; } auto* myf32 = Alias("myf32", ty.f32()); Func("func", ast::VariableList{}, ty.Of(myf32), ast::StatementList{ Return(Source{{12, 34}}, Expr(2_u)), }, ast::AttributeList{}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: return statement type must match its function return " "type, returned 'u32', expected 'f32'"); } TEST_F(ResolverFunctionValidationTest, CannotCallEntryPoint) { // @stage(compute) @workgroup_size(1) fn entrypoint() {} // fn func() { return entrypoint(); } Func("entrypoint", ast::VariableList{}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(1_i)}); Func("func", ast::VariableList{}, ty.void_(), { CallStmt(Call(Source{{12, 34}}, "entrypoint")), }); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), R"(12:34 error: entry point functions cannot be the target of a function call)"); } TEST_F(ResolverFunctionValidationTest, PipelineStage_MustBeUnique_Fail) { // @stage(fragment) // @stage(vertex) // fn main() { return; } Func(Source{{12, 34}}, "main", ast::VariableList{}, ty.void_(), ast::StatementList{ Return(), }, ast::AttributeList{ Stage(Source{{12, 34}}, ast::PipelineStage::kVertex), Stage(Source{{56, 78}}, ast::PipelineStage::kFragment), }); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), R"(56:78 error: duplicate stage attribute 12:34 note: first attribute declared here)"); } TEST_F(ResolverFunctionValidationTest, NoPipelineEntryPoints) { Func("vtx_func", ast::VariableList{}, ty.void_(), ast::StatementList{ Return(), }, ast::AttributeList{}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionVarInitWithParam) { // fn foo(bar : f32){ // var baz : f32 = bar; // } auto* bar = Param("bar", ty.f32()); auto* baz = Var("baz", ty.f32(), Expr("bar")); Func("foo", ast::VariableList{bar}, ty.void_(), ast::StatementList{Decl(baz)}, ast::AttributeList{}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionConstInitWithParam) { // fn foo(bar : f32){ // let baz : f32 = bar; // } auto* bar = Param("bar", ty.f32()); auto* baz = Let("baz", ty.f32(), Expr("bar")); Func("foo", ast::VariableList{bar}, ty.void_(), ast::StatementList{Decl(baz)}, ast::AttributeList{}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, FunctionParamsConst) { Func("foo", {Param(Sym("arg"), ty.i32())}, ty.void_(), {Assign(Expr(Source{{12, 34}}, "arg"), Expr(1_i)), Return()}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: cannot assign to function parameter\nnote: 'arg' is " "declared here:"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_GoodType_ConstU32) { // let x = 4u; // let x = 8u; // @stage(compute) @workgroup_size(x, y, 16u) // fn main() {} auto* x = GlobalConst("x", ty.u32(), Expr(4_u)); auto* y = GlobalConst("y", ty.u32(), Expr(8_u)); auto* func = Func( "main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr("x"), Expr("y"), Expr(16_u))}); ASSERT_TRUE(r()->Resolve()) << r()->error(); auto* sem_func = Sem().Get(func); auto* sem_x = Sem().Get<sem::GlobalVariable>(x); auto* sem_y = Sem().Get<sem::GlobalVariable>(y); ASSERT_NE(sem_func, nullptr); ASSERT_NE(sem_x, nullptr); ASSERT_NE(sem_y, nullptr); EXPECT_TRUE(sem_func->DirectlyReferencedGlobals().contains(sem_x)); EXPECT_TRUE(sem_func->DirectlyReferencedGlobals().contains(sem_y)); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_GoodType_U32) { // @stage(compute) @workgroup_size(1u, 2u, 3u) // fn main() {} Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Source{{12, 34}}, Expr(1_u), Expr(2_u), Expr(3_u))}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_MismatchTypeU32) { // @stage(compute) @workgroup_size(1u, 2u, 3_i) // fn main() {} Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(1_u), Expr(2_u), Expr(Source{{12, 34}}, 3_i))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size arguments must be of the same type, " "either i32 or u32"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_MismatchTypeI32) { // @stage(compute) @workgroup_size(1_i, 2u, 3_i) // fn main() {} Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(1_i), Expr(Source{{12, 34}}, 2_u), Expr(3_i))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size arguments must be of the same type, " "either i32 or u32"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Const_TypeMismatch) { // let x = 64u; // @stage(compute) @workgroup_size(1i, x) // fn main() {} GlobalConst("x", ty.u32(), Expr(64_u)); Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(1_i), Expr(Source{{12, 34}}, "x"))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size arguments must be of the same type, " "either i32 or u32"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Const_TypeMismatch2) { // let x = 64u; // let y = 32i; // @stage(compute) @workgroup_size(x, y) // fn main() {} GlobalConst("x", ty.u32(), Expr(64_u)); GlobalConst("y", ty.i32(), Expr(32_i)); Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr("x"), Expr(Source{{12, 34}}, "y"))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size arguments must be of the same type, " "either i32 or u32"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Mismatch_ConstU32) { // let x = 4u; // let x = 8u; // @stage(compute) @workgroup_size(x, y, 16i) // fn main() {} GlobalConst("x", ty.u32(), Expr(4_u)); GlobalConst("y", ty.u32(), Expr(8_u)); Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr("x"), Expr("y"), Expr(Source{{12, 34}}, 16_i))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size arguments must be of the same type, " "either i32 or u32"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Literal_BadType) { // @stage(compute) @workgroup_size(64.0) // fn main() {} Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(Source{{12, 34}}, 64.f))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be either literal or " "module-scope constant of type i32 or u32"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Literal_Negative) { // @stage(compute) @workgroup_size(-2i) // fn main() {} Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(Source{{12, 34}}, i32(-2)))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be at least 1"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Literal_Zero) { // @stage(compute) @workgroup_size(0i) // fn main() {} Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(Source{{12, 34}}, 0_i))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be at least 1"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Const_BadType) { // let x = 64.0; // @stage(compute) @workgroup_size(x) // fn main() {} GlobalConst("x", ty.f32(), Expr(64.f)); Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(Source{{12, 34}}, "x"))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be either literal or " "module-scope constant of type i32 or u32"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Const_Negative) { // let x = -2i; // @stage(compute) @workgroup_size(x) // fn main() {} GlobalConst("x", ty.i32(), Expr(i32(-2))); Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(Source{{12, 34}}, "x"))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be at least 1"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Const_Zero) { // let x = 0i; // @stage(compute) @workgroup_size(x) // fn main() {} GlobalConst("x", ty.i32(), Expr(0_i)); Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(Source{{12, 34}}, "x"))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be at least 1"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_Const_NestedZeroValueConstructor) { // let x = i32(i32(i32())); // @stage(compute) @workgroup_size(x) // fn main() {} GlobalConst("x", ty.i32(), Construct(ty.i32(), Construct(ty.i32(), Construct(ty.i32())))); Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(Source{{12, 34}}, "x"))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be at least 1"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_NonConst) { // var<private> x = 64i; // @stage(compute) @workgroup_size(x) // fn main() {} Global("x", ty.i32(), ast::StorageClass::kPrivate, Expr(64_i)); Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Expr(Source{{12, 34}}, "x"))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be either literal or " "module-scope constant of type i32 or u32"); } TEST_F(ResolverFunctionValidationTest, WorkgroupSize_InvalidExpr) { // @stage(compute) @workgroup_size(i32(1)) // fn main() {} Func("main", {}, ty.void_(), {}, {Stage(ast::PipelineStage::kCompute), WorkgroupSize(Construct(Source{{12, 34}}, ty.i32(), 1_i))}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: workgroup_size argument must be either a literal or " "a module-scope constant"); } TEST_F(ResolverFunctionValidationTest, ReturnIsConstructible_NonPlain) { auto* ret_type = ty.pointer(Source{{12, 34}}, ty.i32(), ast::StorageClass::kFunction); Func("f", {}, ret_type, {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: function return type must be a constructible type"); } TEST_F(ResolverFunctionValidationTest, ReturnIsConstructible_AtomicInt) { auto* ret_type = ty.atomic(Source{{12, 34}}, ty.i32()); Func("f", {}, ret_type, {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: function return type must be a constructible type"); } TEST_F(ResolverFunctionValidationTest, ReturnIsConstructible_ArrayOfAtomic) { auto* ret_type = ty.array(Source{{12, 34}}, ty.atomic(ty.i32()), 10_u); Func("f", {}, ret_type, {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: function return type must be a constructible type"); } TEST_F(ResolverFunctionValidationTest, ReturnIsConstructible_StructOfAtomic) { Structure("S", {Member("m", ty.atomic(ty.i32()))}); auto* ret_type = ty.type_name(Source{{12, 34}}, "S"); Func("f", {}, ret_type, {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: function return type must be a constructible type"); } TEST_F(ResolverFunctionValidationTest, ReturnIsConstructible_RuntimeArray) { auto* ret_type = ty.array(Source{{12, 34}}, ty.i32()); Func("f", {}, ret_type, {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: function return type must be a constructible type"); } TEST_F(ResolverFunctionValidationTest, ParameterStoreType_NonAtomicFree) { Structure("S", {Member("m", ty.atomic(ty.i32()))}); auto* ret_type = ty.type_name(Source{{12, 34}}, "S"); auto* bar = Param(Source{{12, 34}}, "bar", ret_type); Func("f", ast::VariableList{bar}, ty.void_(), {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: store type of function parameter must be a " "constructible type"); } TEST_F(ResolverFunctionValidationTest, ParameterSotreType_AtomicFree) { Structure("S", {Member("m", ty.i32())}); auto* ret_type = ty.type_name(Source{{12, 34}}, "S"); auto* bar = Param(Source{{12, 34}}, "bar", ret_type); Func("f", ast::VariableList{bar}, ty.void_(), {}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, ParametersAtLimit) { ast::VariableList params; for (int i = 0; i < 255; i++) { params.emplace_back(Param("param_" + std::to_string(i), ty.i32())); } Func(Source{{12, 34}}, "f", params, ty.void_(), {}); ASSERT_TRUE(r()->Resolve()) << r()->error(); } TEST_F(ResolverFunctionValidationTest, ParametersOverLimit) { ast::VariableList params; for (int i = 0; i < 256; i++) { params.emplace_back(Param("param_" + std::to_string(i), ty.i32())); } Func(Source{{12, 34}}, "f", params, ty.void_(), {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: functions may declare at most 255 parameters"); } TEST_F(ResolverFunctionValidationTest, ParameterVectorNoType) { // fn f(p : vec3) {} Func(Source{{12, 34}}, "f", {Param("p", create<ast::Vector>(Source{{12, 34}}, nullptr, 3))}, ty.void_(), {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: missing vector element type"); } TEST_F(ResolverFunctionValidationTest, ParameterMatrixNoType) { // fn f(p : vec3) {} Func(Source{{12, 34}}, "f", {Param("p", create<ast::Matrix>(Source{{12, 34}}, nullptr, 3, 3))}, ty.void_(), {}); EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: missing matrix element type"); } struct TestParams { ast::StorageClass storage_class; bool should_pass; }; struct TestWithParams : ResolverTestWithParam<TestParams> {}; using ResolverFunctionParameterValidationTest = TestWithParams; TEST_P(ResolverFunctionParameterValidationTest, StorageClass) { auto& param = GetParam(); auto* ptr_type = ty.pointer(Source{{12, 34}}, ty.i32(), param.storage_class); auto* arg = Param(Source{{12, 34}}, "p", ptr_type); Func("f", ast::VariableList{arg}, ty.void_(), {}); if (param.should_pass) { ASSERT_TRUE(r()->Resolve()) << r()->error(); } else { std::stringstream ss; ss << param.storage_class; EXPECT_FALSE(r()->Resolve()); EXPECT_EQ(r()->error(), "12:34 error: function parameter of pointer type cannot be in '" + ss.str() + "' storage class"); } } INSTANTIATE_TEST_SUITE_P(ResolverTest, ResolverFunctionParameterValidationTest, testing::Values(TestParams{ast::StorageClass::kNone, false}, TestParams{ast::StorageClass::kInput, false}, TestParams{ast::StorageClass::kOutput, false}, TestParams{ast::StorageClass::kUniform, false}, TestParams{ast::StorageClass::kWorkgroup, true}, TestParams{ast::StorageClass::kHandle, false}, TestParams{ast::StorageClass::kStorage, false}, TestParams{ast::StorageClass::kPrivate, true}, TestParams{ast::StorageClass::kFunction, true})); } // namespace } // namespace tint::resolver
34.994937
100
0.603451
[ "vector" ]
1bc85bdbd1b3b2f082593df93d51ce872c753f02
2,985
cpp
C++
src/targets/gpu/loop.cpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
72
2018-12-06T18:31:17.000Z
2022-03-30T15:01:02.000Z
src/targets/gpu/loop.cpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
1,006
2018-11-30T16:32:33.000Z
2022-03-31T22:43:39.000Z
src/targets/gpu/loop.cpp
raramakr/AMDMIGraphX
83e7425367f6ce850ec28fe716fe7c23ce34c79f
[ "MIT" ]
36
2019-05-07T10:41:46.000Z
2022-03-28T15:59:56.000Z
#include <migraphx/run_loop.hpp> #include <migraphx/gpu/loop.hpp> #include <migraphx/gpu/context.hpp> #include <migraphx/gpu/device/fill.hpp> #include <unordered_map> namespace migraphx { inline namespace MIGRAPHX_INLINE_NS { namespace gpu { shape hip_loop::compute_shape(std::vector<shape> inputs, std::vector<module_ref> mods) const { auto input_num = (inputs.size() - 2) / 2; inputs.erase(inputs.begin() + input_num, inputs.end()); return op.compute_shape(inputs, std::move(mods)); } struct gpu_loop { int64_t max_iterations = 0; template <class T> void copy(context& ctx, const argument& src, T& dst) const { argument arg_dst{src.get_shape(), &dst}; copy_from_gpu(ctx, src, arg_dst); } template <class T> void copy(context& ctx, T src, const argument& dst) const { argument arg_src{dst.get_shape(), &src}; copy_to_gpu(ctx, arg_src, dst); } void append(const std::vector<argument>&, const std::vector<argument>&, int) const {} void set_zero(context& ctx, const std::vector<argument>& concatenated_outputs, int iter) const { if(iter >= max_iterations) return; auto elem_num = max_iterations - iter; for(const auto& out : concatenated_outputs) { auto s = out.get_shape(); auto size = s.bytes() / max_iterations; auto lens = s.lens(); lens[0] = elem_num; shape ss{s.type(), lens}; assert(ss.bytes() + iter * size <= out.get_shape().bytes()); device::fill(ctx.get_stream().get(), argument(ss, out.data() + iter * size), 0); } } std::unordered_map<std::string, int> get_output_params(const module& m) const { auto get_output_index = [](const std::string& name) { std::string out_prefix = "#output_"; auto loc = name.find(out_prefix); if(loc != std::string::npos) { int index = std::stoi(name.substr(loc + out_prefix.size())); return index; } return -1; }; const auto& param_names = m.get_parameter_names(); std::unordered_map<std::string, int> result; for(const auto& name : param_names) { auto index = get_output_index(name); if(index == -1) continue; result[name] = index; } return result; } }; argument hip_loop::compute(context& ctx, const shape&, const std::vector<argument>& args, const std::vector<module_ref>& mods, const std::function<std::vector<argument>( module_ref&, const std::unordered_map<std::string, argument>&)>& run) const { return run_loop(gpu_loop{op.max_iterations}, ctx, args, mods, run); } } // namespace gpu } // namespace MIGRAPHX_INLINE_NS } // namespace migraphx
30.459184
98
0.579899
[ "shape", "vector" ]
1bc87927f0fb32e92f76592de071cc579b3ef466
1,827
hpp
C++
external/vsomeip/implementation/service_discovery/include/remote_subscription_ack.hpp
lixiaolia/ndk-someip-lib
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
[ "Apache-2.0" ]
3
2021-06-17T14:01:04.000Z
2022-03-18T09:22:44.000Z
external/vsomeip/implementation/service_discovery/include/remote_subscription_ack.hpp
lixiaolia/ndk-someip-lib
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
[ "Apache-2.0" ]
1
2022-03-15T06:21:33.000Z
2022-03-28T06:31:12.000Z
external/vsomeip/implementation/service_discovery/include/remote_subscription_ack.hpp
lixiaolia/ndk-someip-lib
f4088e87f07e3a6bcec402514bb7ebb77ec946ce
[ "Apache-2.0" ]
4
2021-06-17T14:12:18.000Z
2021-12-13T11:53:10.000Z
// Copyright (C) 2018 Bayerische Motoren Werke Aktiengesellschaft (BMW AG) // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. #ifndef VSOMEIP_V3_SD_REMOTE_SUBSCRIPTION_ACK_HPP_ #define VSOMEIP_V3_SD_REMOTE_SUBSCRIPTION_ACK_HPP_ #include <memory> #include <mutex> #include <set> namespace vsomeip_v3 { class remote_subscription; namespace sd { class message_impl; class remote_subscription_ack { public: remote_subscription_ack(const boost::asio::ip::address &_address); // The complete flag signals whether or not all subscribes // of a message have been inserted. bool is_complete() const; void complete(); // The done flag signals whether or not all subscribes // have been processed. bool is_done() const; void done(); std::vector<std::shared_ptr<message_impl> > get_messages() const; std::shared_ptr<message_impl> get_current_message() const; std::shared_ptr<message_impl> add_message(); boost::asio::ip::address get_target_address() const; bool is_pending() const; std::set<std::shared_ptr<remote_subscription> > get_subscriptions() const; void add_subscription( const std::shared_ptr<remote_subscription> &_subscription); bool has_subscription() const; std::unique_lock<std::recursive_mutex> get_lock(); private: std::recursive_mutex mutex_; std::vector<std::shared_ptr<message_impl> > messages_; bool is_complete_; bool is_done_; const boost::asio::ip::address target_address_; std::set<std::shared_ptr<remote_subscription> > subscriptions_; }; } // namespace sd } // namespace vsomeip_v3 #endif // VSOMEIP_V3_SD_REMOTE_SUBSCRIPTION_ACK_HPP_
28.107692
78
0.735085
[ "vector" ]
1bcacc95ebfabe2e5785137e3421424fdf61269c
2,784
cpp
C++
JanuaEngine/tgcviewer-cpp/TgcViewer/Ui/TgcUserVars.cpp
gigc/Janua
cbcc8ad0e9501e1faef5b37a964769970aa3d236
[ "MIT", "Unlicense" ]
98
2015-01-13T16:23:23.000Z
2022-02-14T21:51:07.000Z
JanuaEngine/tgcviewer-cpp/TgcViewer/Ui/TgcUserVars.cpp
gigc/Janua
cbcc8ad0e9501e1faef5b37a964769970aa3d236
[ "MIT", "Unlicense" ]
1
2016-06-30T22:07:54.000Z
2016-06-30T22:07:54.000Z
JanuaEngine/tgcviewer-cpp/TgcViewer/Ui/TgcUserVars.cpp
gigc/Janua
cbcc8ad0e9501e1faef5b37a964769970aa3d236
[ "MIT", "Unlicense" ]
13
2015-08-26T11:19:08.000Z
2021-07-12T03:41:50.000Z
///////////////////////////////////////////////////////////////////////////////// // TgcViewer-cpp // // Author: Matias Leone // ///////////////////////////////////////////////////////////////////////////////// #include "TgcViewer/Ui/TgcUserVars.h" #include "TgcViewer/GuiController.h" //required by forward declaration using namespace TgcViewer; TgcUserVars::TgcUserVars() { this->position = Vector2(5, 200); this->enabled = true; this->enableKey = TgcInput::K_V; this->color = Color::Yellow; } TgcUserVars::TgcUserVars(const TgcUserVars& other) { } TgcUserVars::~TgcUserVars() { } void TgcUserVars::addVar(const string name) { map<string, TgcText2d*>::iterator it = this->uiTexts.find(name); if (it == this->uiTexts.end() ) { TgcText2d* text = new TgcText2d(); text->position = Vector2(position.X, position.Y + TEXT_Y_DISTANCE * this->uiTexts.size()); text->color = color; text->updateValues(); this->uiTexts[name] = text; } } void TgcUserVars::setVar(const string name, const string value) { this->addVar(name); this->uiTexts[name]->text = name + ": " + value; } void TgcUserVars::setVar(const string name, const int value) { TgcUserVars::setVar(name, TgcParserUtils::toString(value)); } void TgcUserVars::setVar(const string name, const int long value) { TgcUserVars::setVar(name, TgcParserUtils::toString(value)); } void TgcUserVars::setVar(const string name, const unsigned int value) { TgcUserVars::setVar(name, TgcParserUtils::toString(value)); } void TgcUserVars::setVar(const string name, const float value) { TgcUserVars::setVar(name, TgcParserUtils::toString(value)); } void TgcUserVars::setVar(const string name, const Vector2& value) { TgcUserVars::setVar(name, TgcParserUtils::toString(value)); } void TgcUserVars::setVar(const string name, const Vector3& value) { TgcUserVars::setVar(name, TgcParserUtils::toString(value)); } void TgcUserVars::setVar(const string name, const Vector4& value) { TgcUserVars::setVar(name, TgcParserUtils::toString(value)); } void TgcUserVars::setVar(const string name, const Color& value) { TgcUserVars::setVar(name, TgcParserUtils::toString(value)); } void TgcUserVars::render() { //Auto show/hide if(GuiController::Instance->input->keyPress(this->enableKey)) { enabled = !enabled; } if(!enabled) return; //Render all for (map<string, TgcText2d*>::iterator it = this->uiTexts.begin(); it != this->uiTexts.end(); ++it) { TgcText2d* text = it->second; text->render(); //GuiController::Instance->drawText(text->text, text->position.X, text->position.Y); } } void TgcUserVars::dispose() { for (map<string, TgcText2d*>::iterator it = this->uiTexts.begin(); it != this->uiTexts.end(); ++it) { TgcText2d* text = it->second; text->dispose(); delete text; } }
22.819672
101
0.667026
[ "render" ]
1bd44186ee36c212c55d623fa1870913e4a4682b
4,265
cpp
C++
GUI.cpp
DomRe/gui
04895189b9a8ccf6ee68010b150b1b227242a8c2
[ "MIT" ]
null
null
null
GUI.cpp
DomRe/gui
04895189b9a8ccf6ee68010b150b1b227242a8c2
[ "MIT" ]
null
null
null
GUI.cpp
DomRe/gui
04895189b9a8ccf6ee68010b150b1b227242a8c2
[ "MIT" ]
null
null
null
/* /// /// GUI.cpp /// galaxy /// /// Refer to LICENSE.txt for more details. /// #include <magic_enum.hpp> #include "galaxy/core/ServiceLocator.hpp" #include "galaxy/graphics/Renderer2D.hpp" #include "galaxy/resource/Shaderbook.hpp" #include "GUI.hpp" namespace galaxy { namespace ui { GUI::GUI() : Serializable {this}, m_state {ConstructionState::DEFAULT}, m_id_counter {0}, m_theme {nullptr}, m_allow_input {true} { } GUI::~GUI() { if (m_state != ConstructionState::DEFAULT) { clear(); } } void GUI::set_theme(Theme* theme) { m_theme = theme; m_state = ConstructionState::THEME_SET; } void GUI::enable_input() noexcept { m_allow_input = true; } void GUI::disable_input() noexcept { m_allow_input = false; } void GUI::on_event(const events::MouseMoved& mme) noexcept { if (m_allow_input) { m_theme->m_event_manager.trigger<events::MouseMoved>(mme.m_x, mme.m_y); } } void GUI::on_event(const events::MousePressed& mpe) noexcept { if (m_allow_input) { m_theme->m_event_manager.trigger<events::MousePressed>(mpe.m_x, mpe.m_y, mpe.m_button); } } void GUI::on_event(const events::MouseReleased& mre) noexcept { if (m_allow_input) { m_theme->m_event_manager.trigger<events::MouseReleased>(mre.m_x, mre.m_y, mre.m_button); } } void GUI::on_event(const events::KeyDown& kde) noexcept { if (m_allow_input) { m_theme->m_event_manager.trigger<events::KeyDown>(kde.m_keycode); } } void GUI::update(const double dt) { std::for_each(m_widgets.begin(), m_widgets.end(), [&](const auto& widget) { widget->update(dt); }); } void GUI::render() { m_theme->m_sb.buffer_data(); RENDERER_2D().buffer_camera(m_theme->m_camera); RENDERER_2D().bind_sb_shader(); RENDERER_2D().draw(&m_theme->m_sb); for (const auto& widget : m_widgets) { widget->render(); } } void GUI::remove(const unsigned int id) { if (id >= m_widgets.size()) { GALAXY_LOG(GALAXY_WARNING, "Attempted to remove widget that does not exist: {0}.", id); } else { // Don't erase because that will mess up ordering. m_widgets[id].reset(); m_widgets[id] = nullptr; m_free.emplace_back(id); } } void GUI::clear() { m_state = ConstructionState::DEFAULT; m_id_counter = 0; m_free.clear(); for (auto& widget : m_widgets) { widget.reset(); } m_widgets.clear(); } nlohmann::json GUI::serialize() { nlohmann::json json = "{}"_json; json["state"] = static_cast<std::string>(magic_enum::enum_name<ConstructionState>(m_state)); json["widgets"] = nlohmann::json::array(); for (const auto& widget : m_widgets) { nlohmann::json widget_json = "{}"_json; widget_json["type"] = static_cast<std::string>(magic_enum::enum_name<Widget::Type>(widget->m_type)); widget_json["data"] = widget->serialize(); json["widgets"].push_back(widget_json); } return json; } void GUI::deserialize(const nlohmann::json& json) { clear(); m_state = magic_enum::enum_cast<ConstructionState>(json.at("state").get<std::string>()).value(); const auto& widgets = json.at("widgets"); for (const auto& widget_obj : widgets) { const auto type = magic_enum::enum_cast<Widget::Type>(widget_obj.at("type").get<std::string>()).value(); switch (type) { case Widget::Type::BUTTON: { auto* widget = create_widget<Button>(); widget->deserialize(widget_obj.at("data")); } break; case Widget::Type::IMAGE: { auto* widget = create_widget<Image>(); widget->deserialize(widget_obj.at("data")); } break; case Widget::Type::LABEL: { auto* widget = create_widget<Label>(); widget->deserialize(widget_obj.at("data")); } break; case Widget::Type::PROGRESSBAR: { auto* widget = create_widget<Progressbar>(); widget->deserialize(widget_obj.at("data")); } break; case Widget::Type::SLIDER: { auto* widget = create_widget<Slider>(); widget->deserialize(widget_obj.at("data")); } break; case Widget::Type::TEXTBOX: { auto* widget = create_widget<Textbox>(); widget->deserialize(widget_obj.at("data")); } break; case Widget::Type::TEXTINPUT: { auto* widget = create_widget<TextInput>(); widget->deserialize(widget_obj.at("data")); } break; case Widget::Type::TOGGLEBUTTON: { auto* widget = create_widget<ToggleButton>(); widget->deserialize(widget_obj.at("data")); } break; default: GALAXY_LOG(GALAXY_ERROR, "Failed to identify widget type: {0}.", json.at("type").get<std::string>()); break; } } } } // namespace ui } // namespace galaxy */
18.871681
118
0.709027
[ "render" ]
1bd4730e3363627f698f91ff109eb30bd618eaf6
6,442
cpp
C++
ShootEditor/src/DependencyViewer.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
5
2016-11-13T08:13:57.000Z
2019-03-31T10:22:38.000Z
ShootEditor/src/DependencyViewer.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
null
null
null
ShootEditor/src/DependencyViewer.cpp
franticsoftware/starports
d723404b20383949874868c251c60cfa06120fde
[ "MIT" ]
1
2016-12-23T11:25:35.000Z
2016-12-23T11:25:35.000Z
/* Amine Rehioui Created: January 31st 2015 */ #include "ShootEditorCommon.h" #include "DependencyViewer.h" #include "IconManager.h" #include "ShootEditor.h" #include "MeshEntity.h" #include "Image.h" #include "EditorUtils.h" #include <wx/splitter.h> namespace shoot { // Define event table BEGIN_EVENT_TABLE(DependencyViewer, wxPanel) EVT_LIST_COL_CLICK(wxID_ANY, OnColumnClick) EVT_LIST_ITEM_SELECTED(wxID_ANY, OnItemSelected) EVT_LIST_ITEM_RIGHT_CLICK(wxID_ANY, OnItemRightClick) EVT_TREE_SEL_CHANGED(ID_DependencyViewer_Tree, OnSelectTreeItem) END_EVENT_TABLE() //! Constructor DependencyViewer::DependencyViewer(wxWindow* pParent) : super(pParent, wxID_ANY, wxDefaultPosition, wxDefaultSize) { auto splitter = new wxSplitterWindow(this); m_pDependencyList = new wxListView(splitter, ID_DependencyViewer_List, wxDefaultPosition); m_pDependencyList->SetImageList(IconManager::Instance()->GetImageList(), wxIMAGE_LIST_SMALL); m_pDependencyTree = new wxTreeCtrl(splitter, ID_DependencyViewer_Tree, wxDefaultPosition, wxDefaultSize, wxTR_DEFAULT_STYLE); m_pDependencyTree->SetImageList(IconManager::Instance()->GetImageList()); splitter->SplitHorizontally(m_pDependencyList, m_pDependencyTree); splitter->SetSashGravity(0.60); // Fill columns wxListItem column; column.SetWidth(135); column.SetText(_T("Dependencies")); m_pDependencyList->InsertColumn(0, column); column.SetText(_T("Template")); column.SetWidth(118); m_pDependencyList->InsertColumn(1, column); wxBoxSizer *pSizer = new wxBoxSizer(wxVERTICAL); pSizer->Add(splitter, wxSizerFlags(1).Expand()); SetSizer(pSizer); // use the sizer for layout pSizer->FitInside(this); } //! Fill void DependencyViewer::Fill(Object* object) { // Fill items m_pDependencyList->DeleteAllItems(); m_pDependencyTree->DeleteAllItems(); wxListItem column; m_pDependencyList->GetColumn(0, column); column.SetText("Dependencies"); m_pDependencyList->SetColumn(0, column); if (!object) return; auto container = ObjectManager::Instance()->GetContainer(object); for (auto reference : container->lReferences) { auto owner = reference->GetOwner(); if (!owner) continue; std::string ownerName = owner->GetName().empty() ? owner->GetClassName() : owner->GetName(); // Type long item = m_pDependencyList->InsertItem(m_pDependencyList->GetItemCount(), ownerName, IconManager::Instance()->GetIconIndex(owner)); m_pDependencyList->SetItemPtrData(item, (size_t)owner); // Template auto path = EditorUtils::GetTemplatePath(owner); m_pDependencyList->SetItem(item, 1, path); } column.SetText(std::string("Dependencies") + " (" + Utils::ToString(container->lReferences.size()) + ")"); m_pDependencyList->SetColumn(0, column); } //! ObjectSort int wxCALLBACK DependencyViewer::ObjectSort(wxIntPtr item1, wxIntPtr item2, wxIntPtr sortData) { Object* pObject1 = (Object*)item1; Object* pObject2 = (Object*)item2; DependencyViewer* viewer = (DependencyViewer*)sortData; int column = viewer->m_ColumnToSort; int result = 0; switch (column) { case 0: { auto name1 = pObject1->GetName().empty() ? pObject1->GetClassName() : pObject1->GetName(); auto name2 = pObject2->GetName().empty() ? pObject2->GetClassName() : pObject2->GetName(); result = name1.compare(name2); } break; case 1: { auto path1 = EditorUtils::GetTemplatePath(pObject1); auto path2 = EditorUtils::GetTemplatePath(pObject2); result = path1.compare(path2); } break; } if (!viewer->m_ColumSortForward[column]) result = -result; return result; } //! FillDependencyTree void DependencyViewer::FillDependencyTree(wxTreeItemId item, Object* object) { auto container = ObjectManager::Instance()->GetContainer(object); for (auto reference : container->lReferences) { auto owner = reference->GetOwner(); if (!owner) continue; auto objectName = EditorUtils::GetObjectName(owner); auto child = m_pDependencyTree->AppendItem(item, objectName, IconManager::Instance()->GetIconIndex(owner), IconManager::Instance()->GetIconIndex(owner), new EditorUtils::ItemData(owner)); FillDependencyTree(child, owner); m_pDependencyTree->Expand(child); } } //! event handlers void DependencyViewer::OnColumnClick(wxListEvent& event) { m_ColumnToSort = event.GetColumn(); m_pDependencyList->SortItems(DependencyViewer::ObjectSort, (long)this); SHOOT_ASSERT(m_ColumnToSort >= 0 && m_ColumnToSort < int(NumColumns), "Invalid Column Index"); m_ColumSortForward[m_ColumnToSort] = !m_ColumSortForward[m_ColumnToSort]; } void DependencyViewer::OnItemSelected(wxListEvent& event) { long item = event.GetItem(); auto object = reinterpret_cast<Object*>(m_pDependencyList->GetItemData(item)); ShootEditor::Instance()->GetObjectInspector()->Fill(object); // fill dependency tree m_pDependencyTree->DeleteAllItems(); auto objectName = EditorUtils::GetObjectName(object); auto treeRoot = m_pDependencyTree->AddRoot(objectName, IconManager::Instance()->GetIconIndex(object), IconManager::Instance()->GetIconIndex(object), new EditorUtils::ItemData(object)); FillDependencyTree(treeRoot, object); m_pDependencyTree->Expand(treeRoot); } void DependencyViewer::OnItemRightClick(wxListEvent& event) { long item = event.GetItem(); auto object = reinterpret_cast<Object*>(m_pDependencyList->GetItemData(item)); wxMenu subMenu; subMenu.Append(ID_DependencyViewer_ViewDependencies, "View Dependencies"); subMenu.Connect(wxEVT_COMMAND_MENU_SELECTED, (wxObjectEventFunction)&DependencyViewer::OnItemMenuClicked, NULL, this); PopupMenu(&subMenu); } void DependencyViewer::OnItemMenuClicked(wxEvent& event) { switch (event.GetId()) { case ID_DependencyViewer_ViewDependencies: { auto selection = m_pDependencyList->GetFocusedItem(); auto object = reinterpret_cast<Object*>(m_pDependencyList->GetItemData(selection)); auto tabControl = ShootEditor::Instance()->GetMainTabControl(); tabControl->SelectObject(object); } break; } } void DependencyViewer::OnSelectTreeItem(wxTreeEvent& event) { wxTreeItemId itemId = event.GetItem(); if (!itemId.IsOk()) return; if (auto data = static_cast<EditorUtils::ItemData*>(m_pDependencyTree->GetItemData(itemId))) { auto object = data->m_pObject; ShootEditor::Instance()->GetObjectInspector()->Fill(object); } } }
30.244131
190
0.742471
[ "object" ]
1bd53c2f46e27b9352f2d9bbbe2edf82dee0263d
2,081
hpp
C++
include/constraint.hpp
EmbersArc/socp_interface
d569ca7315a808e1070d1d01148018f2148ce672
[ "MIT" ]
3
2019-08-24T00:50:42.000Z
2020-03-17T21:35:17.000Z
include/constraint.hpp
EmbersArc/socp_interface
d569ca7315a808e1070d1d01148018f2148ce672
[ "MIT" ]
null
null
null
include/constraint.hpp
EmbersArc/socp_interface
d569ca7315a808e1070d1d01148018f2148ce672
[ "MIT" ]
3
2019-07-22T01:34:50.000Z
2021-06-14T12:45:24.000Z
#pragma once #include "expression.hpp" #include <vector> #include <ostream> namespace op { namespace internal { // represents a constraint like // p_1*x_1 + p_2*x_2 + ... + b == 0 struct EqualityConstraint { explicit EqualityConstraint(const internal::AffineSum &affine); internal::AffineSum affine; friend std::ostream &operator<<(std::ostream &os, const EqualityConstraint &constraint); double evaluate(const std::vector<double> &soln_values) const; }; // represents a constraint like // p_1*x_1 + p_2*x_2 + ... + b >= 0 struct PositiveConstraint { explicit PositiveConstraint(const internal::AffineSum &affine); internal::AffineSum affine; friend std::ostream &operator<<(std::ostream &os, const PositiveConstraint &constraint); double evaluate(const std::vector<double> &soln_values) const; }; // represents a constraint like // norm2([p_1*x_1 + p_2*x_2 + ... + b_1, p_3*x_3 + p_4*x_4 + ... + b_2 ]) // <= p_5*x_5 + p_6*x_6 + ... + b_3 struct SecondOrderConeConstraint { SecondOrderConeConstraint(const internal::Norm2Term &norm2, const internal::AffineSum &affine); internal::Norm2Term norm2; internal::AffineSum affine; friend std::ostream &operator<<(std::ostream &os, const SecondOrderConeConstraint &constraint); double evaluate(const std::vector<double> &soln_values) const; }; } // namespace internal std::vector<internal::EqualityConstraint> operator==(const Affine &affine, const double zero); std::vector<internal::EqualityConstraint> operator==(const Affine &lhs, const Affine &rhs); std::vector<internal::PositiveConstraint> operator>=(const Affine &affine, const double zero); std::vector<internal::PositiveConstraint> operator<=(const double zero, const Affine &affine); std::vector<internal::PositiveConstraint> operator>=(const Affine &lhs, const Affine &rhs); std::vector<internal::PositiveConstraint> operator<=(const Affine &lhs, const Affine &rhs); std::vector<internal::SecondOrderConeConstraint> operator<=(const SOCLhs &socLhs, const Affine &affine); } // namespace op
35.87931
104
0.725613
[ "vector" ]
1bd87a2413953cd73ff52ed8234696da2b700943
2,523
cc
C++
sgw/src/model/DescribeOssBucketInfoRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
sgw/src/model/DescribeOssBucketInfoRequest.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
sgw/src/model/DescribeOssBucketInfoRequest.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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. */ #include <alibabacloud/sgw/model/DescribeOssBucketInfoRequest.h> using AlibabaCloud::Sgw::Model::DescribeOssBucketInfoRequest; DescribeOssBucketInfoRequest::DescribeOssBucketInfoRequest() : RpcServiceRequest("sgw", "2018-05-11", "DescribeOssBucketInfo") { setMethod(HttpRequest::Method::Post); } DescribeOssBucketInfoRequest::~DescribeOssBucketInfoRequest() {} std::string DescribeOssBucketInfoRequest::getBucketEndpoint()const { return bucketEndpoint_; } void DescribeOssBucketInfoRequest::setBucketEndpoint(const std::string& bucketEndpoint) { bucketEndpoint_ = bucketEndpoint; setParameter("BucketEndpoint", bucketEndpoint); } std::string DescribeOssBucketInfoRequest::getType()const { return type_; } void DescribeOssBucketInfoRequest::setType(const std::string& type) { type_ = type; setParameter("Type", type); } std::string DescribeOssBucketInfoRequest::getAccessKeyId()const { return accessKeyId_; } void DescribeOssBucketInfoRequest::setAccessKeyId(const std::string& accessKeyId) { accessKeyId_ = accessKeyId; setParameter("AccessKeyId", accessKeyId); } std::string DescribeOssBucketInfoRequest::getSecurityToken()const { return securityToken_; } void DescribeOssBucketInfoRequest::setSecurityToken(const std::string& securityToken) { securityToken_ = securityToken; setParameter("SecurityToken", securityToken); } std::string DescribeOssBucketInfoRequest::getBucketName()const { return bucketName_; } void DescribeOssBucketInfoRequest::setBucketName(const std::string& bucketName) { bucketName_ = bucketName; setParameter("BucketName", bucketName); } std::string DescribeOssBucketInfoRequest::getGatewayId()const { return gatewayId_; } void DescribeOssBucketInfoRequest::setGatewayId(const std::string& gatewayId) { gatewayId_ = gatewayId; setParameter("GatewayId", gatewayId); }
26.28125
88
0.766548
[ "model" ]
1bdca6d26f9e682046ac5227fd006e48aabe8771
1,459
hpp
C++
src/renderer_clock.hpp
trazfr/alarm
ea511eb0f16945de2005d828f452c76fce9d77e7
[ "MIT" ]
null
null
null
src/renderer_clock.hpp
trazfr/alarm
ea511eb0f16945de2005d828f452c76fce9d77e7
[ "MIT" ]
null
null
null
src/renderer_clock.hpp
trazfr/alarm
ea511eb0f16945de2005d828f452c76fce9d77e7
[ "MIT" ]
null
null
null
#pragma once #include <memory> class Config; /** * @brief Render the analog clock's hands * * The second hand is only displayed if enabled in the config */ class RendererClock { public: struct Impl; /** * Constructor * * @param screenWidth used for the heigth / width ratio to have a round clock * @param screenHeight used for the heigth / width ratio to have a round clock * @param x position on screen of the center of the clock * @param y position on screen of the center of the clock * @param lengthHour length of the hour hand. Max is 1 * @param widthHour width of the hour hand. Max is 1 * @param lengthMin length of the minute hand. Max is 1 * @param widthMin width of the minute hand. Max is 1 * @param lengthSec length of the second hand. Max is 1. Only displayed if enabled in config * @param widthSec width of the second hand. Max is 1. Only displayed if enabled in config */ RendererClock(const Config &config, int screenWidth, int screenHeight, int x, int y, float lengthHour, float widthHour, float lengthMin, float widthMin, float lengthSec, float widthSec); ~RendererClock(); /** * Display the clock hands (call OpenGL to perform the display) */ void draw(int hour, int min, int sec, int millis); private: std::unique_ptr<Impl> pimpl; };
31.042553
96
0.642906
[ "render" ]
1be01b53869a563e07561299812dd3f24a835e40
2,939
hpp
C++
trunk/src/app/srs_app_ingest.hpp
chundonglinlin/srs.win
0e45a27ebf0df35509cac33741d4e3e8454d83fa
[ "MIT" ]
9
2016-02-04T02:09:25.000Z
2019-08-11T15:11:44.000Z
trunk/src/app/srs_app_ingest.hpp
miffa/simple-rtmp-server
e227bd3a0ef948a1c5f9b14eb41f87323338bb6a
[ "MIT" ]
null
null
null
trunk/src/app/srs_app_ingest.hpp
miffa/simple-rtmp-server
e227bd3a0ef948a1c5f9b14eb41f87323338bb6a
[ "MIT" ]
23
2015-12-06T15:18:41.000Z
2021-12-23T13:59:25.000Z
/* The MIT License (MIT) Copyright (c) 2013-2014 winlin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef SRS_APP_INGEST_HPP #define SRS_APP_INGEST_HPP /* #include <srs_app_ingest.hpp> */ #include <srs_core.hpp> #ifdef SRS_AUTO_INGEST #include <vector> #include <srs_app_thread.hpp> #include <srs_app_reload.hpp> class SrsFFMPEG; class SrsConfDirective; class SrsPithyPrint; /** * ingester ffmpeg object. */ class SrsIngesterFFMPEG { public: std::string vhost; std::string id; SrsFFMPEG* ffmpeg; SrsIngesterFFMPEG(SrsFFMPEG* _ffmpeg, std::string _vhost, std::string _id); virtual ~SrsIngesterFFMPEG(); }; /** * ingest file/stream/device, * encode with FFMPEG(optional), * push to SRS(or any RTMP server) over RTMP. */ class SrsIngester : public ISrsThreadHandler, public ISrsReloadHandler { private: std::vector<SrsIngesterFFMPEG*> ingesters; private: SrsThread* pthread; SrsPithyPrint* pithy_print; public: SrsIngester(); virtual ~SrsIngester(); public: virtual int start(); virtual void stop(); // interface ISrsThreadHandler. public: virtual int cycle(); virtual void on_thread_stop(); private: virtual void clear_engines(); virtual int parse(); virtual int parse_ingesters(SrsConfDirective* vhost); virtual int parse_engines(SrsConfDirective* vhost, SrsConfDirective* ingest); virtual int initialize_ffmpeg(SrsFFMPEG* ffmpeg, SrsConfDirective* vhost, SrsConfDirective* ingest, SrsConfDirective* engine); virtual void ingester(); // interface ISrsReloadHandler. public: virtual int on_reload_vhost_removed(std::string vhost); virtual int on_reload_vhost_added(std::string vhost); virtual int on_reload_ingest_removed(std::string vhost, std::string ingest_id); virtual int on_reload_ingest_added(std::string vhost, std::string ingest_id); virtual int on_reload_ingest_updated(std::string vhost, std::string ingest_id); }; #endif #endif
30.298969
130
0.764886
[ "object", "vector" ]
1be17322af2ea1a58c8163af1f64a15096da3e0e
21,983
cpp
C++
renderobjects/UmbralMesh.cpp
Zackmon/SeventhUmbral
25580111b361d2fdc2c15fd2cd150e4c763ca774
[ "BSD-2-Clause" ]
92
2015-01-30T01:57:18.000Z
2022-02-14T00:05:30.000Z
renderobjects/UmbralMesh.cpp
Zackmon/SeventhUmbral
25580111b361d2fdc2c15fd2cd150e4c763ca774
[ "BSD-2-Clause" ]
6
2015-08-18T19:57:17.000Z
2022-01-31T14:48:33.000Z
renderobjects/UmbralMesh.cpp
Zackmon/SeventhUmbral
25580111b361d2fdc2c15fd2cd150e4c763ca774
[ "BSD-2-Clause" ]
44
2015-01-03T13:01:21.000Z
2022-01-31T14:24:40.000Z
#include "UmbralMesh.h" #include "ResourceManager.h" #include "GlobalResources.h" #include "PtrStream.h" #include "StdStream.h" #include "D3DShaderDisassembler.h" #include "UmbralEffectProvider.h" #include "UmbralEffect.h" #include "../dataobjects/HalfFloat.h" #define _USE_GAME_SHADERS #ifdef _USE_GAME_SHADERS #include "string_format.h" #endif static uint16 ByteSwap16(uint16 value) { return (((value & 0xFF00) >> 8) << 0) | (((value & 0x00FF) >> 0) << 8); } static CVector2 ConvertVec2FromHalf(const uint8* rawData) { const uint16* data = reinterpret_cast<const uint16*>(rawData); CVector2 result; result.x = CHalfFloat::ToFloat(ByteSwap16(data[0])); result.y = CHalfFloat::ToFloat(ByteSwap16(data[1])); return result; } static CVector3 ConvertVec3FromUint8(const uint8* rawData) { CVector3 result; result.x = static_cast<float>(rawData[0] / 255.f); result.y = static_cast<float>(rawData[1] / 255.f); result.z = static_cast<float>(rawData[2] / 255.f); return result; } static CVector4 ConvertVec4FromUint8(const uint8* rawData) { CVector4 result; result.x = static_cast<float>(rawData[0] / 255.f); result.y = static_cast<float>(rawData[1] / 255.f); result.z = static_cast<float>(rawData[2] / 255.f); result.w = static_cast<float>(rawData[3] / 255.f); return result; } static CVector3 ConvertVec3FromInt16(const uint8* rawData) { const int16* data = reinterpret_cast<const int16*>(rawData); CVector3 result; result.x = static_cast<float>(static_cast<int16>(ByteSwap16(data[0]))) / 32768.f; result.y = static_cast<float>(static_cast<int16>(ByteSwap16(data[1]))) / 32768.f; result.z = static_cast<float>(static_cast<int16>(ByteSwap16(data[2]))) / 32768.f; return result; } static CVector3 ConvertVec3FromUint16(const uint8* rawData) { const uint16* data = reinterpret_cast<const uint16*>(rawData); CVector3 result; result.x = static_cast<float>(ByteSwap16(data[0])) / 65535.f; result.y = static_cast<float>(ByteSwap16(data[1])) / 65535.f; result.z = static_cast<float>(ByteSwap16(data[2])) / 65535.f; return result; } CUmbralMesh::CUmbralMesh() { } CUmbralMesh::CUmbralMesh(const MeshChunkPtr& meshChunk, const ShaderSectionPtr& shaderSection) : m_meshChunk(meshChunk) , m_shaderSection(shaderSection) { SetupGeometry(); SetupPolyGroups(); SetupEffect(); SetupTextures(); } CUmbralMesh::~CUmbralMesh() { } UmbralMeshPtr CUmbralMesh::CreateInstance() const { //This won't work well if indices weren't rebuilt assert(m_indexRebuildNeeded == false); auto result = std::make_shared<CUmbralMesh>(); //CSceneNode members result->m_worldTransformation = m_worldTransformation; //CMesh members result->m_primitiveType = m_primitiveType; result->m_primitiveCount = m_primitiveCount; result->m_material = m_material; result->m_effectProvider = m_effectProvider; result->m_vertexBuffer = m_vertexBuffer; result->m_boundingSphere = m_boundingSphere; result->m_isPeggedToOrigin = m_isPeggedToOrigin; //CUmbralMesh members result->m_meshChunk = m_meshChunk; result->m_shaderSection = m_shaderSection; result->m_localTexture = m_localTexture; result->m_effect = m_effect; result->m_samplerRegisters = m_samplerRegisters; result->m_activePolyGroups = m_activePolyGroups; result->m_indexRebuildNeeded = m_indexRebuildNeeded; return result; } Palleon::EffectPtr CUmbralMesh::GetEffect() const { return m_effect; } void CUmbralMesh::SetLocalTexture(const ResourceNodePtr& texture) { m_localTexture = texture; SetupTextures(); } void CUmbralMesh::SetActivePolyGroups(uint32 activePolyGroups) { m_activePolyGroups = activePolyGroups; m_indexRebuildNeeded = true; } void CUmbralMesh::Update(float dt) { CMesh::Update(dt); if(m_indexRebuildNeeded) { RebuildIndices(); assert(m_indexRebuildNeeded == false); } } void CUmbralMesh::SetupGeometry() { auto streamChunks = m_meshChunk->SelectNodes<CStreamChunk>(); assert(streamChunks.size() == 2); auto indexStream = streamChunks[0]; auto vertexStream = streamChunks[1]; uint32 vertexCount = vertexStream->GetVertexCount(); auto bufferDesc = GenerateVertexBufferDescriptor(vertexStream, indexStream); auto positionElement = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_POSITION); auto normalElement = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_NORMAL); auto uv1Element = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_UV1); auto uv2Element = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_UV2); auto uv3Element = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_UV3); auto uv4Element = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_UV4); auto colorElement = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_COLOR); auto tangentElement = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_TANGENT); assert(positionElement != nullptr); assert(positionElement->dataFormat == CStreamChunk::ELEMENT_DATA_FORMAT_INT16); assert(!normalElement || normalElement->dataFormat == CStreamChunk::ELEMENT_DATA_FORMAT_BYTE); assert(!colorElement || colorElement->dataFormat == CStreamChunk::ELEMENT_DATA_FORMAT_BYTE); assert(!uv1Element || uv1Element->dataFormat == CStreamChunk::ELEMENT_DATA_FORMAT_HALF); assert(!uv2Element || uv2Element->dataFormat == CStreamChunk::ELEMENT_DATA_FORMAT_HALF); assert(!uv3Element || uv3Element->dataFormat == CStreamChunk::ELEMENT_DATA_FORMAT_HALF); assert(!uv4Element || uv4Element->dataFormat == CStreamChunk::ELEMENT_DATA_FORMAT_HALF); assert(!tangentElement || tangentElement->dataFormat == CStreamChunk::ELEMENT_DATA_FORMAT_BYTE); m_primitiveType = Palleon::PRIMITIVE_TRIANGLE_LIST; m_boundingSphere.radius = sqrt(2.f); //Vertex position range is [-1, 1] m_vertexBuffer = Palleon::CGraphicDevice::GetInstance().CreateVertexBuffer(bufferDesc); const auto& posVertexItem = bufferDesc.GetVertexItem(Palleon::VERTEX_ITEM_ID_POSITION); const auto& nrmVertexItem = bufferDesc.GetVertexItem(Palleon::VERTEX_ITEM_ID_NORMAL); const auto& uv0VertexItem = bufferDesc.GetVertexItem(Palleon::VERTEX_ITEM_ID_UV0); const auto& uv1VertexItem = bufferDesc.GetVertexItem(Palleon::VERTEX_ITEM_ID_UV1); const auto& uv2VertexItem = bufferDesc.GetVertexItem(CUmbralEffect::VERTEX_ITEM_ID_UV2); const auto& uv3VertexItem = bufferDesc.GetVertexItem(CUmbralEffect::VERTEX_ITEM_ID_UV3); const auto& colorVertexItem = bufferDesc.GetVertexItem(Palleon::VERTEX_ITEM_ID_COLOR); const auto& tangentVertexItem = bufferDesc.GetVertexItem(CUmbralEffect::VERTEX_ITEM_ID_TANGENT); const auto& placeholderVertexItem = bufferDesc.GetVertexItem(CUmbralEffect::VERTEX_ITEM_ID_PLACEHOLDER); uint32 placeholderValue = Palleon::CGraphicDevice::ConvertColorToUInt32(CColor(0, 0, 0, 1)); { const uint8* srcVertices = vertexStream->GetData(); uint8* dstVertices = reinterpret_cast<uint8*>(m_vertexBuffer->LockVertices()); for(unsigned int i = 0; i < vertexCount; i++) { auto position = ConvertVec3FromInt16(srcVertices + positionElement->offsetInVertex); *reinterpret_cast<CVector3*>(dstVertices + posVertexItem->offset) = position; if(normalElement) { auto normal = ConvertVec3FromUint8(srcVertices + normalElement->offsetInVertex); *reinterpret_cast<CVector3*>(dstVertices + nrmVertexItem->offset) = normal; } if(uv1Element) { auto uv1 = ConvertVec2FromHalf(srcVertices + uv1Element->offsetInVertex); *reinterpret_cast<CVector2*>(dstVertices + uv0VertexItem->offset) = uv1; } if(uv2Element) { auto uv2 = ConvertVec2FromHalf(srcVertices + uv2Element->offsetInVertex); *reinterpret_cast<CVector2*>(dstVertices + uv1VertexItem->offset) = uv2; } if(uv3Element) { auto uv3 = ConvertVec2FromHalf(srcVertices + uv3Element->offsetInVertex); *reinterpret_cast<CVector2*>(dstVertices + uv2VertexItem->offset) = uv3; } if(uv4Element) { auto uv4 = ConvertVec2FromHalf(srcVertices + uv4Element->offsetInVertex); *reinterpret_cast<CVector2*>(dstVertices + uv3VertexItem->offset) = uv4; } if(colorElement) { *reinterpret_cast<uint8*>(dstVertices + colorVertexItem->offset + 0) = *(srcVertices + colorElement->offsetInVertex + 0); *reinterpret_cast<uint8*>(dstVertices + colorVertexItem->offset + 1) = *(srcVertices + colorElement->offsetInVertex + 1); *reinterpret_cast<uint8*>(dstVertices + colorVertexItem->offset + 2) = *(srcVertices + colorElement->offsetInVertex + 2); *reinterpret_cast<uint8*>(dstVertices + colorVertexItem->offset + 3) = *(srcVertices + colorElement->offsetInVertex + 3); } if(tangentElement) { auto tangent = ConvertVec4FromUint8(srcVertices + tangentElement->offsetInVertex); *reinterpret_cast<CVector4*>(dstVertices + tangentVertexItem->offset) = tangent; } *reinterpret_cast<uint32*>(dstVertices + placeholderVertexItem->offset) = placeholderValue; srcVertices += vertexStream->GetVertexSize(); dstVertices += bufferDesc.GetVertexSize(); } m_vertexBuffer->UnlockVertices(); } } Palleon::VERTEX_BUFFER_DESCRIPTOR CUmbralMesh::GenerateVertexBufferDescriptor(const StreamChunkPtr& vertexStream, const StreamChunkPtr& indexStream) { uint32 currentOffset = 0; unsigned int currentVertexItem = 0; auto positionElement = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_POSITION); auto normalElement = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_NORMAL); auto uv1Element = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_UV1); auto uv2Element = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_UV2); auto uv3Element = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_UV3); auto uv4Element = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_UV4); auto colorElement = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_COLOR); auto tangentElement = vertexStream->FindElement(CStreamChunk::ELEMENT_DATA_TYPE_TANGENT); assert(positionElement != nullptr); Palleon::VERTEX_BUFFER_DESCRIPTOR result; result.vertexCount = vertexStream->GetVertexCount(); result.indexCount = indexStream->GetVertexCount(); if(positionElement) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = Palleon::VERTEX_ITEM_ID_POSITION; vertexItem.offset = currentOffset; vertexItem.size = sizeof(CVector3); currentOffset += vertexItem.size; } if(normalElement) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = Palleon::VERTEX_ITEM_ID_NORMAL; vertexItem.offset = currentOffset; vertexItem.size = sizeof(CVector3); currentOffset += vertexItem.size; } if(uv1Element) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = Palleon::VERTEX_ITEM_ID_UV0; vertexItem.offset = currentOffset; vertexItem.size = sizeof(CVector2); currentOffset += vertexItem.size; } if(uv2Element) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = Palleon::VERTEX_ITEM_ID_UV1; vertexItem.offset = currentOffset; vertexItem.size = sizeof(CVector2); currentOffset += vertexItem.size; } if(uv3Element) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = CUmbralEffect::VERTEX_ITEM_ID_UV2; vertexItem.offset = currentOffset; vertexItem.size = sizeof(CVector2); currentOffset += vertexItem.size; } if(uv4Element) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = CUmbralEffect::VERTEX_ITEM_ID_UV3; vertexItem.offset = currentOffset; vertexItem.size = sizeof(CVector2); currentOffset += vertexItem.size; } if(colorElement) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = Palleon::VERTEX_ITEM_ID_COLOR; vertexItem.offset = currentOffset; vertexItem.size = sizeof(uint32); currentOffset += vertexItem.size; } if(tangentElement) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = CUmbralEffect::VERTEX_ITEM_ID_TANGENT; vertexItem.offset = currentOffset; vertexItem.size = sizeof(CVector4); currentOffset += vertexItem.size; } //Add placeholder element (for missing elements) { auto& vertexItem = result.vertexItems[currentVertexItem++]; vertexItem.id = CUmbralEffect::VERTEX_ITEM_ID_PLACEHOLDER; vertexItem.offset = currentOffset; vertexItem.size = sizeof(uint32); currentOffset += vertexItem.size; } return result; } void CUmbralMesh::SetupPolyGroups() { auto streamChunks = m_meshChunk->SelectNodes<CStreamChunk>(); assert(streamChunks.size() == 2); auto groupChunks = m_meshChunk->SelectNodes<CPgrpChunk>(); auto indexStream = streamChunks[0]; uint32 indexCount = indexStream->GetVertexCount(); assert((indexCount % 3) == 0); uint32 triangleCount = indexCount / 3; std::vector<bool> triangleUsed; triangleUsed.resize(triangleCount, false); assert(m_polyGroups.size() == 0); for(const auto& group : groupChunks) { auto groupName = group->GetName(); assert(groupName.length() >= 2); //There's some poly group names with "Happy" that can be conflicting with //the name pattern we're looking for if(groupName.find("Happy") == 0) continue; auto groupNameSuffix = groupName.substr(groupName.length() - 2, 2); if(groupNameSuffix[0] != '_') continue; unsigned int groupIndex = groupNameSuffix[1] - 'a'; assert(m_polyGroups.find(groupIndex) == std::end(m_polyGroups)); m_polyGroups[groupIndex] = group->GetTriangles(); for(const auto& triangleIndex : group->GetTriangles()) { triangleUsed[triangleIndex] = true; } } assert(m_basePolyGroup.size() == 0); m_basePolyGroup.reserve(triangleCount); for(unsigned int i = 0; i < triangleCount; i++) { if(!triangleUsed[i]) { m_basePolyGroup.push_back(i); } } m_indexRebuildNeeded = true; } void CUmbralMesh::SetupEffect() { #ifdef _USE_GAME_SHADERS FileChunkPtr vertexShaderFile; FileChunkPtr pixelShaderFile; auto fileChunks = m_shaderSection->SelectNodes<CFileChunk>(); for(const auto& fileChunk : fileChunks) { auto fileName = fileChunk->GetName(); if(!vertexShaderFile && fileName.find(".vpo") != std::string::npos) { vertexShaderFile = fileChunk; } if(!pixelShaderFile && fileName.find(".fpo") != std::string::npos) { pixelShaderFile = fileChunk; } } assert(vertexShaderFile && pixelShaderFile); auto makeShaderStreamFromFile = [] (const FileChunkPtr& file) { const auto compiledShader = file->GetCompiledShader(); uint32 compiledShaderLength = file->GetCompiledShaderLength(); return Framework::CPtrStream(compiledShader, compiledShaderLength); }; auto vertexShaderStream = makeShaderStreamFromFile(vertexShaderFile); auto pixelShaderStream = makeShaderStreamFromFile(pixelShaderFile); // CD3DShader vertexShader(Framework::CStdStream("D:\\Projects\\SeventhUmbral\\tools\\WorldEditor\\data\\standard.vso", "rb")); // CD3DShader pixelShader(Framework::CStdStream("D:\\Projects\\SeventhUmbral\\tools\\WorldEditor\\data\\standard.pso", "rb")); auto vertexShader = CD3DShader(vertexShaderStream); auto pixelShader = CD3DShader(pixelShaderStream); #if 0 auto shaderType = pixelShader.GetType(); std::string shaderCode; for(const auto& instruction : pixelShader.GetInstructions()) { auto mnemonic = CD3DShaderDisassembler::GetInstructionMnemonic(shaderType, instruction); auto operands = CD3DShaderDisassembler::GetInstructionOperands(shaderType, instruction); shaderCode += string_format("%s %s\r\n", mnemonic.c_str(), operands.c_str()); } #endif bool hasAlphaTest = false; { auto material = GetMaterial(); auto pramChunk = m_shaderSection->SelectNode<CPramChunk>(); assert(pramChunk); switch(pramChunk->GetRenderMode()) { case 0x809: //Alpha blended mode material->SetAlphaBlendingMode(Palleon::ALPHA_BLENDING_LERP); break; case 0x818: //Default render mode break; case 0xC12: case 0xC1A: //Alpha tested mode (this needs to be done in the shader) hasAlphaTest = true; break; } material->SetCullingMode(Palleon::CULLING_CW); //Copy parameters to effect parameters for(const auto& param : pramChunk->GetParameters()) { Palleon::CEffectParameter effectParam; switch(param.numValues) { case 1: effectParam.SetScalar(param.valueX); break; case 2: effectParam.SetVector2(CVector2(param.valueX, param.valueY)); break; case 3: effectParam.SetVector3(CVector3(param.valueX, param.valueY, param.valueZ)); break; case 4: effectParam.SetVector4(CVector4(param.valueX, param.valueY, param.valueZ, param.valueW)); break; default: assert(0); break; } auto paramName = param.isPixelShaderParam ? ("ps_" + param.name) : ("vs_" + param.name); material->SetEffectParameter(paramName, effectParam); } } const auto& effectProvider = CGlobalResources::GetInstance().GetEffectProvider(); m_effect = std::static_pointer_cast<CUmbralEffectProvider>(effectProvider)->GetEffect(vertexShader, pixelShader, hasAlphaTest); SetEffectProvider(effectProvider); const auto& pixelShaderConstantTable = pixelShader.GetConstantTable(); for(const auto& constant : pixelShaderConstantTable.GetConstants()) { if(constant.info.registerSet != CD3DShaderConstantTable::REGISTER_SET_SAMPLER) continue; m_samplerRegisters.insert(std::make_pair(constant.name, constant.info.registerIndex)); } #endif } void CUmbralMesh::SetupTextures() { auto pramChunk = m_shaderSection->SelectNode<CPramChunk>(); assert(pramChunk); auto localTextureSections = m_localTexture ? m_localTexture->SelectNodes<CTextureSection>() : decltype(m_localTexture->SelectNodes<CTextureSection>())(); auto getTextureForSampler = [&localTextureSections] (const PramChunkPtr& pramChunk, const std::string& samplerName) { Palleon::TexturePtr texture; for(const auto& sampler : pramChunk->GetSamplers()) { if(sampler.name == samplerName) { for(const auto& string : sampler.strings) { texture = CGlobalResources::GetInstance().GetTexture(string); if(texture) break; for(const auto& textureSection : localTextureSections) { const auto& sectionName = textureSection->GetResourceId(); if(string.find(sectionName) != std::string::npos) { auto textureDataInfo = textureSection->SelectNode<CGtexData>(); texture = CGlobalResources::CreateTextureFromGtex(textureDataInfo); break; } } if(texture) break; } } } return texture; }; auto sampler0 = getTextureForSampler(pramChunk, "_sampler_00"); auto sampler1 = getTextureForSampler(pramChunk, "_sampler_01"); auto sampler2 = getTextureForSampler(pramChunk, "_sampler_02"); auto sampler3 = getTextureForSampler(pramChunk, "_sampler_03"); auto sampler4 = getTextureForSampler(pramChunk, "_sampler_04"); auto sampler5 = getTextureForSampler(pramChunk, "_sampler_05"); auto sampler6 = getTextureForSampler(pramChunk, "_sampler_06"); for(unsigned int i = 0; i < Palleon::CMaterial::MAX_TEXTURE_SLOTS; i++) { GetMaterial()->SetTextureAddressModeU(i, Palleon::TEXTURE_ADDRESS_REPEAT); GetMaterial()->SetTextureAddressModeV(i, Palleon::TEXTURE_ADDRESS_REPEAT); } #ifdef _USE_GAME_SHADERS auto setSampler = [&] (const std::string& samplerName, const Palleon::TexturePtr& texture) { if(texture) { auto samplerRegisterIterator = m_samplerRegisters.find(samplerName); if(samplerRegisterIterator != std::end(m_samplerRegisters)) { GetMaterial()->SetTexture(samplerRegisterIterator->second, texture); } } }; setSampler("_sampler_00", sampler0); setSampler("_sampler_01", sampler1); setSampler("_sampler_02", sampler2); setSampler("_sampler_03", sampler3); setSampler("_sampler_04", sampler4); setSampler("_sampler_05", sampler5); setSampler("_sampler_06", sampler6); setSampler("lightDiffuseMap", CGlobalResources::GetInstance().GetDiffuseMapTexture()); setSampler("lightToneMap", CGlobalResources::GetInstance().GetLightToneMapTexture()); setSampler("reflectMap", CGlobalResources::GetInstance().GetSkyTexture()); setSampler("shadowMap0", CGlobalResources::GetInstance().GetProxyShadowTexture()); #else GetMaterial()->SetTexture(0, sampler0); #endif } void CUmbralMesh::RebuildIndices() { auto streamChunks = m_meshChunk->SelectNodes<CStreamChunk>(); assert(streamChunks.size() == 2); auto indexStream = streamChunks[0]; unsigned int primitiveCount = 0; unsigned int triangleCount = indexStream->GetVertexCount() / 3; std::vector<bool> triangleUsed; triangleUsed.resize(triangleCount, false); for(auto polyIndex : m_basePolyGroup) { triangleUsed[polyIndex] = true; } for(const auto& polyGroupPair : m_polyGroups) { uint32 polyGroupIndex = polyGroupPair.first; if((m_activePolyGroups & (1 << polyGroupIndex))) continue; for(auto polyIndex : polyGroupPair.second) { triangleUsed[polyIndex] = true; } } const uint16* srcIndices = reinterpret_cast<const uint16*>(indexStream->GetData()); uint16* dstIndices = m_vertexBuffer->LockIndices(); for(unsigned int i = 0; i < triangleCount; i++) { if(triangleUsed[i]) { for(unsigned int j = 0; j < 3; j++) { (*dstIndices++) = ByteSwap16(srcIndices[(i * 3) + j]); } primitiveCount++; } } m_vertexBuffer->UnlockIndices(); m_primitiveCount = primitiveCount; m_indexRebuildNeeded = false; }
34.402191
155
0.730701
[ "render", "vector" ]
1be697b5618849b06b70c3cf8ba2e28219ff46e8
1,468
cpp
C++
src/C++ STL Examples/algorithms/adjacent_find_example.cpp
Fennec2000GH/Software-Engineering-Interview
c7a182d7f8c44f7cabaf77982099594ce297a48b
[ "MIT" ]
1
2020-03-15T04:09:11.000Z
2020-03-15T04:09:11.000Z
src/C++ STL Examples/algorithms/adjacent_find_example.cpp
Fennec2000GH/Software-Engineering-Interview
c7a182d7f8c44f7cabaf77982099594ce297a48b
[ "MIT" ]
null
null
null
src/C++ STL Examples/algorithms/adjacent_find_example.cpp
Fennec2000GH/Software-Engineering-Interview
c7a182d7f8c44f7cabaf77982099594ce297a48b
[ "MIT" ]
null
null
null
#include <algorithm> #include <iostream> #include <iterator> #include <numeric> #include <vector> using namespace std; //std::adjacent_find /* equality (1) * template <class ForwardIterator> * ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last); */ /* predicate (2) * template <class ForwardIterator, class BinaryPredicate> * ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last, BinaryPredicate pred); */ //predicate function tests for first number less than second number bool pred(unsigned long a, unsigned long b) { return a < b; } int main() { //main vector vector<unsigned long> v(10); iota(v.begin(), v.end(), 0); random_shuffle(v.begin(), v.end()); v[5] = v[4]; // elements at indices 4 and 5 are adjacent and equivalent cout << "v: { "; copy(v.cbegin(), v.cend(), ostream_iterator<unsigned long>(cout, ", ")); cout << "} " << endl; //confirm that chosen elements are selected by std::adjacent_find vector<unsigned long>::const_iterator it1 = adjacent_find(v.cbegin(), v.cend()); cout << "CHECK: the first element appearing twice adjacently in v is " << *it1 << endl; //test vector with std::adjacent_find using a binary predicate vector<unsigned long>::const_iterator it2 = adjacent_find(v.cbegin(), v.cend(), pred); cout << "CHECK: the first element appearing twice adjacently based on binary predicate in v is " << *it2 << endl; return 0; }
35.804878
117
0.69346
[ "vector" ]
1be6e24825ba9c2599a8835b4f2f67ca48d5d44e
15,555
cpp
C++
modules/opengl/shader/shaderobject.cpp
victorca25/inviwo
34b6675f6b791a08e358d24aea4f75d5baadc6da
[ "BSD-2-Clause" ]
null
null
null
modules/opengl/shader/shaderobject.cpp
victorca25/inviwo
34b6675f6b791a08e358d24aea4f75d5baadc6da
[ "BSD-2-Clause" ]
null
null
null
modules/opengl/shader/shaderobject.cpp
victorca25/inviwo
34b6675f6b791a08e358d24aea4f75d5baadc6da
[ "BSD-2-Clause" ]
null
null
null
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2012-2017 Inviwo Foundation * All rights reserved. * * 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. * * 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 OWNER 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 <stdio.h> #include <fstream> #include <string> #include "shaderobject.h" #include <inviwo/core/io/textfilereader.h> #include <inviwo/core/util/filesystem.h> #include <inviwo/core/util/stdextensions.h> #include <modules/opengl/openglexception.h> #include <modules/opengl/shader/shadermanager.h> #include <modules/opengl/shader/shaderutils.h> namespace inviwo { ShaderObject::ShaderObject(ShaderType shaderType, std::shared_ptr<const ShaderResource> resource) : shaderType_{shaderType}, id_{glCreateShader(shaderType)}, resource_{resource} { if (!shaderType_) throw OpenGLException("Invalid shader type", IvwContext); // Help developer to spot errors std::string fileExtension = filesystem::getFileExtension(resource_->key()); if (fileExtension != shaderType_.extension()) { LogWarn("File extension does not match shader type: " << resource_->key()); } } ShaderObject::ShaderObject(std::shared_ptr<const ShaderResource> resource) : ShaderObject(ShaderType::get(filesystem::getFileExtension(resource->key())), resource) {} ShaderObject::ShaderObject(ShaderType shaderType, std::string fileName) : ShaderObject(shaderType, loadResource(fileName)) {} ShaderObject::ShaderObject(std::string fileName) : ShaderObject(ShaderType::get(filesystem::getFileExtension(fileName)), loadResource(fileName)) {} ShaderObject::ShaderObject(GLenum shaderType, std::string fileName) : ShaderObject(ShaderType(shaderType), loadResource(fileName)) {} ShaderObject::ShaderObject(const ShaderObject& rhs) : shaderType_(rhs.shaderType_) , id_(glCreateShader(rhs.shaderType_)) , resource_(rhs.resource_) , outDeclarations_(rhs.outDeclarations_) , shaderDefines_(rhs.shaderDefines_) , shaderExtensions_(rhs.shaderExtensions_) { } ShaderObject& ShaderObject::operator=(const ShaderObject& that) { if (this != &that) { glDeleteShader(id_); shaderType_ = that.shaderType_; id_ = glCreateShader(shaderType_); resource_ = that.resource_; outDeclarations_ = that.outDeclarations_; shaderDefines_ = that.shaderDefines_; shaderExtensions_ = that.shaderExtensions_; } return *this; } ShaderObject::~ShaderObject() { glDeleteShader(id_); } GLuint ShaderObject::getID() const { return id_; } std::string ShaderObject::getFileName() const { return resource_->key(); } std::shared_ptr<const ShaderResource> ShaderObject::getResource() const { return resource_; } const std::vector<std::shared_ptr<const ShaderResource>>& ShaderObject::getResources() const { return includeResources_; } ShaderType ShaderObject::getShaderType() const { return shaderType_; } std::shared_ptr<const ShaderResource> ShaderObject::loadResource(std::string fileName) { return utilgl::findShaderResource(fileName); } void ShaderObject::build() { preprocess(); upload(); compile(); } void ShaderObject::preprocess() { resourceCallbacks_.clear(); lineNumberResolver_.clear(); auto holdOntoResources = includeResources_; // Don't release until we have processed again. includeResources_.clear(); std::ostringstream source; addDefines(source); addOutDeclarations(source); addIncludes(source, resource_); sourceProcessed_ = source.str(); } void ShaderObject::addDefines(std::ostringstream& source) { { std::string globalGLSLHeader = ShaderManager::getPtr()->getGlobalGLSLHeader(); std::string curLine; std::istringstream globalGLSLHeaderStream(globalGLSLHeader); while (std::getline(globalGLSLHeaderStream, curLine)) { lineNumberResolver_.emplace_back("GlobalGLSLSHeader", 0); } source << globalGLSLHeader; } { for (const auto& se : shaderExtensions_) { source << "#extension " << se.first << " : " << (se.second ? "enable" : "disable") << "\n"; lineNumberResolver_.emplace_back("Extension", 0); } } { for (const auto& sd : shaderDefines_) { source << "#define " << sd.first << " " << sd.second << "\n"; lineNumberResolver_.emplace_back("Defines", 0); } } { std::string globalDefines; if (shaderType_ == ShaderType::Vertex) { globalDefines += ShaderManager::getPtr()->getGlobalGLSLVertexDefines(); } else if (shaderType_ == ShaderType::Fragment) { globalDefines += ShaderManager::getPtr()->getGlobalGLSLFragmentDefines(); } std::string curLine; std::istringstream globalGLSLDefinesStream(globalDefines); while (std::getline(globalGLSLDefinesStream, curLine)) { lineNumberResolver_.emplace_back("GlobalGLSLSDefines", 0); } source << globalDefines; } } void ShaderObject::addOutDeclarations(std::ostringstream& source) { for (auto curDeclaration : outDeclarations_) { if (curDeclaration.second > -1) { source << "layout(location = " << curDeclaration.second << ") "; } source << "out vec4 " << curDeclaration.first << ";\n"; lineNumberResolver_.emplace_back("Out Declaration", 0); } } void ShaderObject::addIncludes(std::ostringstream& source, std::shared_ptr<const ShaderResource> resource) { std::ostringstream result; std::string curLine; includeResources_.push_back(resource); resourceCallbacks_.push_back( resource->onChange([this](const ShaderResource* /*res*/) { callbacks_.invoke(this); })); std::istringstream shaderSource(resource->source()); int localLineNumber = 1; bool isInsideBlockComment = false; while (std::getline(shaderSource, curLine)) { size_t curPos = 0; bool hasAddedInclude = false; while (curPos != std::string::npos) { if (isInsideBlockComment) { // If we currently are inside a block comment, we only need to look for where it // ends curPos = curLine.find("*/", curPos); isInsideBlockComment = curPos == std::string::npos; if (!isInsideBlockComment) { curPos += 2; // move curPos to the first character after the comment } } else { auto posInclude = curLine.find("#include", curPos); auto posLineComment = curLine.find("//", curPos); auto posBlockCommentStart = curLine.find("/*", curPos); // If we find two includes on the same line if (hasAddedInclude && posInclude != std::string::npos) { std::ostringstream oss; oss << "Found more than one include on line " << localLineNumber << " in resource " << resource->key(); throw OpenGLException(oss.str(), IvwContext); } // ignore everything after a line-comment "//" (unless it is inside a block comment) if (posLineComment != std::string::npos && posLineComment < posInclude && posLineComment < posBlockCommentStart) { break; } // there is a block comment starting on this line, before a include: update curPos // and continue; // the include should be found in the next iteration if (posBlockCommentStart != std::string::npos && posBlockCommentStart < posInclude) { isInsideBlockComment = true; curPos = posBlockCommentStart; continue; } // an include was found if (posInclude != std::string::npos) { auto pathBegin = curLine.find("\"", posInclude + 1); auto pathEnd = curLine.find("\"", pathBegin + 1); std::string incfile(curLine, pathBegin + 1, pathEnd - pathBegin - 1); auto inc = ShaderManager::getPtr()->getShaderResource(incfile); if (!inc) { throw OpenGLException( "Include file " + incfile + " not found in shader search paths.", IvwContext); } auto it = util::find(includeResources_, inc); if (it == includeResources_.end()) { // Only include files once. addIncludes(source, inc); source << curLine.substr(pathEnd + 1); } hasAddedInclude = true; } // after the include it can still be comments, we need to detect if a block comment // starts // if the next thing is a line comment, we continue to next line if (posLineComment != std::string::npos && posLineComment < posBlockCommentStart) { // there is a line-comment after the include and before any block comment, then // go to next line break; } // set curPos to either npos or the pos of the start of the next block comment curPos = posBlockCommentStart; // will be npos of it has not been found // updated the flag to tell if we are in a block comment or not isInsideBlockComment = posBlockCommentStart != std::string::npos; } } if (!hasAddedInclude) { // include the whole line source << curLine << "\n"; lineNumberResolver_.emplace_back(resource->key(), localLineNumber); } localLineNumber++; } } void ShaderObject::upload() { const char* source = sourceProcessed_.c_str(); glShaderSource(id_, 1, &source, nullptr); LGL_ERROR; } bool ShaderObject::isReady() const { GLint res = GL_FALSE; glGetShaderiv(id_, GL_COMPILE_STATUS, &res); return res == GL_TRUE; } void ShaderObject::compile() { glCompileShader(id_); if (!isReady()) { throw OpenGLException( resource_->key() + " " + utilgl::reformatInfoLog(lineNumberResolver_, utilgl::getShaderInfoLog(id_)), IvwContext); } #ifdef IVW_DEBUG auto log = utilgl::getShaderInfoLog(id_); if (!log.empty()) { util::log(IvwContext, resource_->key() + " " + utilgl::reformatInfoLog(lineNumberResolver_, log), LogLevel::Info, LogAudience::User); } #endif } void ShaderObject::addShaderDefine(std::string name, std::string value) { shaderDefines_[name] = value; } void ShaderObject::removeShaderDefine(std::string name) { shaderDefines_.erase(name); } bool ShaderObject::hasShaderDefine(const std::string& name) const { return shaderDefines_.find(name) != shaderDefines_.end(); } void ShaderObject::clearShaderDefines() { shaderDefines_.clear(); } void ShaderObject::addShaderExtension(std::string extName, bool enabled) { shaderExtensions_[extName] = enabled; } void ShaderObject::removeShaderExtension(std::string extName) { shaderExtensions_.erase(extName); } bool ShaderObject::hasShaderExtension(const std::string& extName) const { return shaderExtensions_.find(extName) != shaderExtensions_.end(); } void ShaderObject::clearShaderExtensions() { shaderExtensions_.clear(); } void ShaderObject::addOutDeclaration(std::string name, int location) { auto it = util::find_if(outDeclarations_, [&](std::pair<std::string, int>& elem) { return elem.first == name; }); if (it != outDeclarations_.end()) { it->second = location; } else { outDeclarations_.push_back({name, location}); } } void ShaderObject::clearOutDeclarations() { outDeclarations_.clear(); } std::pair<std::string, unsigned int> ShaderObject::resolveLine(size_t line) const { if (line<lineNumberResolver_.size()) return lineNumberResolver_[line]; else return {"",0}; } std::string ShaderObject::print(bool showSource, bool preprocess) const { if (preprocess) { if (showSource) { std::string::size_type width = 0; for (auto l : lineNumberResolver_) { std::string file = splitString(l.first, '/').back(); width = std::max(width, file.length()); } size_t i = 0; std::string line; std::stringstream out; std::istringstream in(sourceProcessed_); while (std::getline(in, line)) { std::string file = i < lineNumberResolver_.size() ? splitString(lineNumberResolver_[i].first, '/').back() : ""; unsigned int lineNumber = i < lineNumberResolver_.size() ? lineNumberResolver_[i].second : 0; out << std::left << std::setw(width + 1u) << file << std::right << std::setw(4) << lineNumber << ": " << std::left << line << "\n"; ++i; } return out.str(); } else { return sourceProcessed_; } } else { if (showSource) { size_t lineNumber = 1; std::string line; std::stringstream out; std::istringstream in(resource_->source()); while (std::getline(in, line)) { std::string file = resource_->key(); out << std::left << std::setw(file.length() + 1u) << file << std::right << std::setw(4) << lineNumber << ": " << std::left << line << "\n"; ++lineNumber; } return out.str(); } else { return resource_->source(); } } } } // namespace
38.125
100
0.606365
[ "vector" ]
1bee0a7e41fc0d6e2d76a783503fd41cb10d4d6f
2,285
hpp
C++
include/codegen/include/System/Reflection/CustomAttributeTypedArgument.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/Reflection/CustomAttributeTypedArgument.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/Reflection/CustomAttributeTypedArgument.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:09:43 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.ValueType #include "System/ValueType.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; } // Completed forward declares // Type namespace: System.Reflection namespace System::Reflection { // Autogenerated type: System.Reflection.CustomAttributeTypedArgument struct CustomAttributeTypedArgument : public System::ValueType { public: // private System.Type argumentType // Offset: 0x0 System::Type* argumentType; // private System.Object value // Offset: 0x8 ::Il2CppObject* value; // Creating value type constructor for type: CustomAttributeTypedArgument CustomAttributeTypedArgument(System::Type* argumentType_ = {}, ::Il2CppObject* value_ = {}) : argumentType{argumentType_}, value{value_} {} // public System.Void .ctor(System.Type argumentType, System.Object value) // Offset: 0xA43220 static CustomAttributeTypedArgument* New_ctor(System::Type* argumentType, ::Il2CppObject* value); // public System.Object get_Value() // Offset: 0xA43228 ::Il2CppObject* get_Value(); // public override System.String ToString() // Offset: 0xA43230 // Implemented from: System.ValueType // Base method: System.String ValueType::ToString() ::Il2CppString* ToString(); // public override System.Boolean Equals(System.Object obj) // Offset: 0xA43238 // Implemented from: System.ValueType // Base method: System.Boolean ValueType::Equals(System.Object obj) bool Equals(::Il2CppObject* obj); // public override System.Int32 GetHashCode() // Offset: 0xA43240 // Implemented from: System.ValueType // Base method: System.Int32 ValueType::GetHashCode() int GetHashCode(); }; // System.Reflection.CustomAttributeTypedArgument } DEFINE_IL2CPP_ARG_TYPE(System::Reflection::CustomAttributeTypedArgument, "System.Reflection", "CustomAttributeTypedArgument"); #pragma pack(pop)
40.087719
143
0.708972
[ "object" ]
1bf1abc91f3abb90bb003405a572c0ec9a013702
13,457
cc
C++
dcmdata/apps/dcm2pdf.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
24
2015-07-22T05:07:51.000Z
2019-02-28T04:52:33.000Z
dcmdata/apps/dcm2pdf.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
13
2015-07-23T05:43:02.000Z
2021-07-17T17:14:45.000Z
dcmdata/apps/dcm2pdf.cc
chrisvana/dcmtk_copy
f929ab8590aca5b7a319c95af4fe2ee31be52f46
[ "Apache-2.0" ]
13
2015-07-23T01:07:30.000Z
2021-01-05T09:49:30.000Z
/* * * Copyright (C) 2007-2010, OFFIS e.V. * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation were developed by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmdata * * Author: Marco Eichelberg * * Purpose: Exctract PDF file from DICOM encapsulated PDF storage object * * Last Update: $Author: joergr $ * Update Date: $Date: 2010-10-21 08:32:21 $ * CVS/RCS Revision: $Revision: 1.8 $ * Status: $State: Exp $ * * CVS/RCS Log at end of file * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #define INCLUDE_CSTDLIB #define INCLUDE_CSTDIO #define INCLUDE_CSTRING #include "dcmtk/ofstd/ofstdinc.h" BEGIN_EXTERN_C #ifdef HAVE_FCNTL_H #include <fcntl.h> /* for O_RDONLY */ #endif #ifdef HAVE_SYS_TYPES_H #include <sys/types.h> /* required for sys/stat.h */ #endif #ifdef HAVE_SYS_STAT_H #include <sys/stat.h> /* for stat, fstat */ #endif END_EXTERN_C #include "dcmtk/dcmdata/dctk.h" #include "dcmtk/dcmdata/cmdlnarg.h" #include "dcmtk/ofstd/ofconapp.h" #include "dcmtk/dcmdata/dcuid.h" /* for dcmtk version name */ #include "dcmtk/ofstd/ofstd.h" #include "dcmtk/dcmdata/dcistrmz.h" /* for dcmZlibExpectRFC1950Encoding */ #ifdef WITH_ZLIB #include <zlib.h> /* for zlibVersion() */ #endif #define OFFIS_CONSOLE_APPLICATION "dcm2pdf" static OFLogger dcm2pdfLogger = OFLog::getLogger("dcmtk.apps." OFFIS_CONSOLE_APPLICATION); static char rcsid[] = "$dcmtk: " OFFIS_CONSOLE_APPLICATION " v" OFFIS_DCMTK_VERSION " " OFFIS_DCMTK_RELEASEDATE " $"; #define FILENAME_PLACEHOLDER "#f" static OFString replaceChars(const OFString &srcstr, const OFString &pattern, const OFString &substitute) /* * This function replaces all occurrences of pattern in srcstr with substitute and returns * the result as a new OFString variable. Note that srcstr itself will not be changed. * * Parameters: * srcstr - [in] The source string. * pattern - [in] The pattern string which shall be substituted. * substitute - [in] The substitute for pattern in srcstr. */ { OFString result = srcstr; size_t pos = 0; while (pos != OFString_npos) { pos = result.find(pattern, pos); if (pos != OFString_npos) { result.replace(pos, pattern.size(), substitute); pos += substitute.size(); } } return result; } #define SHORTCOL 3 #define LONGCOL 20 int main(int argc, char *argv[]) { const char *opt_ifname = NULL; const char *opt_ofname = NULL; const char *opt_execString = NULL; E_FileReadMode opt_readMode = ERM_autoDetect; E_TransferSyntax opt_ixfer = EXS_Unknown; OFConsoleApplication app(OFFIS_CONSOLE_APPLICATION, "Extract PDF file from DICOM encapsulated PDF", rcsid); OFCommandLine cmd; cmd.setOptionColumns(LONGCOL, SHORTCOL); cmd.setParamColumn(LONGCOL + SHORTCOL + 4); cmd.addParam("dcmfile-in", "DICOM input filename"); cmd.addParam("pdffile-out", "PDF output filename"); cmd.addGroup("general options:", LONGCOL, SHORTCOL + 2); cmd.addOption("--help", "-h", "print this help text and exit", OFCommandLine::AF_Exclusive); cmd.addOption("--version", "print version information and exit", OFCommandLine::AF_Exclusive); OFLog::addOptions(cmd); cmd.addGroup("input options:"); cmd.addSubGroup("input file format:"); cmd.addOption("--read-file", "+f", "read file format or data set (default)"); cmd.addOption("--read-file-only", "+fo", "read file format only"); cmd.addOption("--read-dataset", "-f", "read data set without file meta information"); cmd.addSubGroup("input transfer syntax:", LONGCOL, SHORTCOL); cmd.addOption("--read-xfer-auto", "-t=", "use TS recognition (default)"); cmd.addOption("--read-xfer-detect", "-td", "ignore TS specified in the file meta header"); cmd.addOption("--read-xfer-little", "-te", "read with explicit VR little endian TS"); cmd.addOption("--read-xfer-big", "-tb", "read with explicit VR big endian TS"); cmd.addOption("--read-xfer-implicit", "-ti", "read with implicit VR little endian TS"); cmd.addSubGroup("parsing of odd-length attributes:"); cmd.addOption("--accept-odd-length", "+ao", "accept odd length attributes (default)"); cmd.addOption("--assume-even-length", "+ae", "assume real length is one byte larger"); cmd.addSubGroup("handling of undefined length UN elements:"); cmd.addOption("--enable-cp246", "+ui", "read undefined len UN as implicit VR (default)"); cmd.addOption("--disable-cp246", "-ui", "read undefined len UN as explicit VR"); cmd.addSubGroup("handling of defined length UN elements:"); cmd.addOption("--retain-un", "-uc", "retain elements as UN (default)"); cmd.addOption("--convert-un", "+uc", "convert to real VR if known"); cmd.addSubGroup("automatic data correction:"); cmd.addOption("--enable-correction", "+dc", "enable automatic data correction (default)"); cmd.addOption("--disable-correction", "-dc", "disable automatic data correction"); #ifdef WITH_ZLIB cmd.addSubGroup("bitstream format of deflated input:"); cmd.addOption("--bitstream-deflated", "+bd", "expect deflated bitstream (default)"); cmd.addOption("--bitstream-zlib", "+bz", "expect deflated zlib bitstream"); #endif cmd.addGroup("execution options:", LONGCOL, SHORTCOL + 2); cmd.addOption("--exec", "-x", 1, "[c]ommand: string", "execute command c after PDF extraction"); /* evaluate command line */ prepareCmdLineArgs(argc, argv, OFFIS_CONSOLE_APPLICATION); if (app.parseCommandLine(cmd, argc, argv, OFCommandLine::PF_ExpandWildcards)) { /* check exclusive options first */ if (cmd.hasExclusiveOption()) { if (cmd.findOption("--version")) { app.printHeader(OFTrue /*print host identifier*/); ofConsole.lockCout() << OFendl << "External libraries used:"; ofConsole.unlockCout(); #ifdef WITH_ZLIB ofConsole.lockCout() << OFendl << "- ZLIB, Version " << zlibVersion() << OFendl; ofConsole.unlockCout(); #else ofConsole.lockCout() << " none" << OFendl; ofConsole.unlockCout(); #endif return 0; } } /* command line parameters and options */ cmd.getParam(1, opt_ifname); cmd.getParam(2, opt_ofname); OFLog::configureFromCommandLine(cmd, app); cmd.beginOptionBlock(); if (cmd.findOption("--read-file")) opt_readMode = ERM_autoDetect; if (cmd.findOption("--read-file-only")) opt_readMode = ERM_fileOnly; if (cmd.findOption("--read-dataset")) opt_readMode = ERM_dataset; cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--read-xfer-auto")) opt_ixfer = EXS_Unknown; if (cmd.findOption("--read-xfer-detect")) dcmAutoDetectDatasetXfer.set(OFTrue); if (cmd.findOption("--read-xfer-little")) { app.checkDependence("--read-xfer-little", "--read-dataset", opt_readMode == ERM_dataset); opt_ixfer = EXS_LittleEndianExplicit; } if (cmd.findOption("--read-xfer-big")) { app.checkDependence("--read-xfer-big", "--read-dataset", opt_readMode == ERM_dataset); opt_ixfer = EXS_BigEndianExplicit; } if (cmd.findOption("--read-xfer-implicit")) { app.checkDependence("--read-xfer-implicit", "--read-dataset", opt_readMode == ERM_dataset); opt_ixfer = EXS_LittleEndianImplicit; } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--accept-odd-length")) { dcmAcceptOddAttributeLength.set(OFTrue); } if (cmd.findOption("--assume-even-length")) { dcmAcceptOddAttributeLength.set(OFFalse); } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--enable-cp246")) { dcmEnableCP246Support.set(OFTrue); } if (cmd.findOption("--disable-cp246")) { dcmEnableCP246Support.set(OFFalse); } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--retain-un")) { dcmEnableUnknownVRConversion.set(OFFalse); } if (cmd.findOption("--convert-un")) { dcmEnableUnknownVRConversion.set(OFTrue); } cmd.endOptionBlock(); cmd.beginOptionBlock(); if (cmd.findOption("--enable-correction")) { dcmEnableAutomaticInputDataCorrection.set(OFTrue); } if (cmd.findOption("--disable-correction")) { dcmEnableAutomaticInputDataCorrection.set(OFFalse); } cmd.endOptionBlock(); #ifdef WITH_ZLIB cmd.beginOptionBlock(); if (cmd.findOption("--bitstream-deflated")) { dcmZlibExpectRFC1950Encoding.set(OFFalse); } if (cmd.findOption("--bitstream-zlib")) { dcmZlibExpectRFC1950Encoding.set(OFTrue); } cmd.endOptionBlock(); #endif if (cmd.findOption("--exec")) app.checkValue(cmd.getValue(opt_execString)); } /* print resource identifier */ OFLOG_DEBUG(dcm2pdfLogger, rcsid << OFendl); /* make sure data dictionary is loaded */ if (!dcmDataDict.isDictionaryLoaded()) { OFLOG_WARN(dcm2pdfLogger, "no data dictionary loaded, check environment variable: " << DCM_DICT_ENVIRONMENT_VARIABLE); } // open inputfile if ((opt_ifname == NULL) || (strlen(opt_ifname) == 0)) { OFLOG_FATAL(dcm2pdfLogger, "invalid filename: <empty string>"); return 1; } DcmFileFormat fileformat; DcmDataset * dataset = fileformat.getDataset(); OFLOG_INFO(dcm2pdfLogger, "open input file " << opt_ifname); OFCondition error = fileformat.loadFile(opt_ifname, opt_ixfer, EGL_noChange, DCM_MaxReadLength, opt_readMode); if (error.bad()) { OFLOG_FATAL(dcm2pdfLogger, error.text() << ": reading file: " << opt_ifname); return 1; } OFString sopClass; error = dataset->findAndGetOFString(DCM_SOPClassUID, sopClass); if (error.bad() || sopClass != UID_EncapsulatedPDFStorage) { OFLOG_FATAL(dcm2pdfLogger, "not an Encapsulated PDF Storage object: " << opt_ifname); return 1; } DcmElement *delem = NULL; error = dataset->findAndGetElement(DCM_EncapsulatedDocument, delem); if (error.bad() || delem == NULL) { OFLOG_FATAL(dcm2pdfLogger, "attribute (0042,0011) Encapsulated Document missing."); return 1; } Uint32 len = delem->getLength(); Uint8 *pdfDocument = NULL; error = delem->getUint8Array(pdfDocument); if (error.bad() || pdfDocument == NULL || len == 0) { OFLOG_FATAL(dcm2pdfLogger, "attribute (0042,0011) Encapsulated Document empty or wrong VR."); return 1; } /* strip pad byte at end of file, if there is one. The PDF format expects * files to end with %%EOF followed by CR/LF. If the last character of the * file is not a CR or LF, we assume it is a pad byte and remove it. */ if (pdfDocument[len-1] != 10 && pdfDocument[len-1] != 13) { --len; } FILE *pdffile = fopen(opt_ofname, "wb"); if (pdffile == NULL) { OFLOG_FATAL(dcm2pdfLogger, "unable to create file " << opt_ofname); return 1; } if (len != fwrite(pdfDocument, 1, len, pdffile)) { OFLOG_FATAL(dcm2pdfLogger, "write error in file " << opt_ofname); fclose(pdffile); return 1; } fclose(pdffile); OFLOG_INFO(dcm2pdfLogger, "conversion successful"); if (opt_execString) { OFString cmdStr = opt_execString; cmdStr = replaceChars(cmdStr, OFString(FILENAME_PLACEHOLDER), opt_ofname); // Execute command and return result return system(cmdStr.c_str()); } return 0; } /* * CVS/RCS Log: * $Log: dcm2pdf.cc,v $ * Revision 1.8 2010-10-21 08:32:21 joergr * Renamed variable to avoid warning reported by gcc with additional flags. * * Revision 1.7 2010-10-14 13:13:30 joergr * Updated copyright header. Added reference to COPYRIGHT file. * * Revision 1.6 2009-11-13 13:20:23 joergr * Fixed minor issues in log output. * * Revision 1.5 2009-11-04 09:58:05 uli * Switched to logging mechanism provided by the "new" oflog module * * Revision 1.4 2008-09-25 14:38:48 joergr * Moved output of resource identifier in order to avoid printing the same * information twice. * * Revision 1.3 2008-09-25 11:19:48 joergr * Added support for printing the expanded command line arguments. * Always output the resource identifier of the command line tool in debug mode. * * Revision 1.2 2007/07/11 10:41:21 joergr * Fixed layout and other minor issues of the usage output (--help). * * Revision 1.1 2007/07/11 09:10:29 meichel * Added new tool dcm2pdf that extracts a PDF document from a DICOM * Encapsulated PDF file, i.e. is the counterpart to pdf2dcm. * * */
33.896725
121
0.636323
[ "object" ]
1bf4da2ac3f95bd86fe13bb24c44b488dd7c6b52
33,343
cpp
C++
playground/src/imageviewer.cpp
UniStuttgart-VISUS/MLBGStippling
2330c8561682a8eb385728764a93b0aa21ff6f36
[ "MIT" ]
null
null
null
playground/src/imageviewer.cpp
UniStuttgart-VISUS/MLBGStippling
2330c8561682a8eb385728764a93b0aa21ff6f36
[ "MIT" ]
1
2022-02-21T08:39:33.000Z
2022-02-24T17:17:15.000Z
playground/src/imageviewer.cpp
UniStuttgart-VISUS/MLBGStippling
2330c8561682a8eb385728764a93b0aa21ff6f36
[ "MIT" ]
null
null
null
#include "imageviewer.h" #include <QOpenGLWidget> #include <QPdfWriter> #include <QSvgGenerator> #include <QtWidgets> uint qHash(QColor key) { return key.rgba(); } uint qHash(std::tuple<QColor, float> key) { return std::get<0>(key).rgba() ^ qHash(std::get<1>(key)); } class CircleStipplesItem : public QGraphicsItem { public: CircleStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float size = stipple.size; auto x = stipple.center.x - size / 2.0f + offset.x(); auto y = stipple.center.y - size / 2.0f + offset.y(); QRectF rect(x, y, size, size); QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_rects.contains(color)) { m_rects[color] = QVector<QRectF>(); } m_rects[color].append(rect); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_rects.cbegin(); iter != m_rects.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto rect : iter.value()) { if (painter->paintEngine()->type() == QPaintEngine::OpenGL || painter->paintEngine()->type() == QPaintEngine::OpenGL2) { // Drawing rounded rects is faster for these engines, but would result in // paths for vector graphics backends. qreal radius = rect.width() / 2.0f; painter->drawRoundedRect(rect, radius, radius); } else { painter->drawEllipse(rect); } } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; QHash<QColor, QVector<QRectF>> m_rects; }; class LineStipplesItem : public QGraphicsItem { public: LineStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float size = stipple.size; QPointF center = QPointF(stipple.center.x + offset.x(), stipple.center.y + offset.y()); QPointF centerOffset = QPointF(cos(stipple.rotation), sin(stipple.rotation)); centerOffset *= size / 2.0f; QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. BatchTuple tuple(color, stipple.shapeParameter); //XXX: this has the potential to generate alot of batches. if (!m_rects.contains(tuple)) { m_rects[tuple] = QVector<std::pair<QPointF, QPointF>>(); } m_rects[tuple].append({ center - centerOffset, center + centerOffset }); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); for (auto iter = m_rects.cbegin(); iter != m_rects.cend(); ++iter) { auto [color, lineWidth] = iter.key(); QPen tempPen = QPen(color, lineWidth, Qt::SolidLine); tempPen.setCapStyle(Qt::FlatCap); painter->setPen(tempPen); for (const auto line : iter.value()) { painter->drawLine(line.first, line.second); } } painter->setPen(pen); painter->setBrush(brush); } protected: QRectF m_boundingRect; using BatchTuple = std::tuple<QColor, float>; QHash<BatchTuple, QVector<std::pair<QPointF, QPointF>>> m_rects; }; class RectangleStipplesItem : public QGraphicsItem { public: RectangleStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float size = stipple.size; QPointF center = QPointF(stipple.center.x, stipple.center.y) + offset; QPointF directionX = QPointF(cos(stipple.rotation), sin(stipple.rotation)) * size / 2.0f * stipple.shapeParameter; QPointF directionY = QPointF(-sin(stipple.rotation), cos(stipple.rotation)) * size / 2.0f; QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_polys.contains(color)) { m_polys[color] = QVector<QVector<QPointF>>(); } m_polys[color].append({ center + directionX + directionY, center - directionX + directionY, center - directionX - directionY, center + directionX - directionY }); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_polys.cbegin(); iter != m_polys.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto poly : iter.value()) { painter->drawPolygon(&poly[0], 4); } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; QHash<QColor, QVector<QVector<QPointF>>> m_polys; }; class RhombusStipplesItem : public QGraphicsItem { public: RhombusStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float size = stipple.size; QPointF center = QPointF(stipple.center.x, stipple.center.y) + offset; QPointF directionX = QPointF(cos(stipple.rotation), sin(stipple.rotation)) * size / 2.0f * stipple.shapeParameter; QPointF directionY = QPointF(-sin(stipple.rotation), cos(stipple.rotation)) * size / 2.0f; QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_polys.contains(color)) { m_polys[color] = QVector<QVector<QPointF>>(); } m_polys[color].append({ center + directionX, center + directionY, center - directionX, center - directionY }); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_polys.cbegin(); iter != m_polys.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto poly : iter.value()) { painter->drawPolygon(&poly[0], 4); } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; QHash<QColor, QVector<QVector<QPointF>>> m_polys; }; class EllipseStipplesItem : public QGraphicsItem { public: struct Ellipse { QPointF center; QPointF size; float angle; }; EllipseStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. QPointF center = QPointF(stipple.center.x, stipple.center.y) + offset; QPointF size = QPointF(stipple.size * stipple.shapeParameter, stipple.size); QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_ellipses.contains(color)) { m_ellipses[color] = QVector<Ellipse>(); } m_ellipses[color].append({ center, size, stipple.rotation }); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_ellipses.cbegin(); iter != m_ellipses.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto Ellipse : iter.value()) { painter->save(); painter->translate(Ellipse.center); painter->rotate(qRadiansToDegrees(Ellipse.angle)); painter->drawEllipse(QRectF(-Ellipse.size / 2.0f, Ellipse.size / 2.0f)); painter->restore(); } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; QHash<QColor, QVector<Ellipse>> m_ellipses; }; class TriangleStipplesItem : public QGraphicsItem { public: TriangleStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float size = stipple.size; QPointF center = QPointF(stipple.center.x, stipple.center.y) + offset; float radius = size / std::sqrt(3); float angles[3] = { 0.0f, M_PI * 4.0f / 6.0f, M_PI * 8.0f / 6.0f }; QVector<QPointF> cornerPoints = QVector<QPointF>(); for (float angle : angles) { cornerPoints.append(center + QPointF(cos(stipple.rotation + angle), sin(stipple.rotation + angle)) * radius); } QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_polys.contains(color)) { m_polys[color] = QVector<QVector<QPointF>>(); } m_polys[color].append(cornerPoints); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_polys.cbegin(); iter != m_polys.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto poly : iter.value()) { painter->drawPolygon(&poly[0], 3); } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; QHash<QColor, QVector<QVector<QPointF>>> m_polys; }; class RoundedLineStipplesItem : public QGraphicsItem { public: RoundedLineStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float size = stipple.size; QPointF center = QPointF(stipple.center.x, stipple.center.y) + offset; QPointF directionX = QPointF(cos(stipple.rotation), sin(stipple.rotation)) * (size - stipple.shapeRadius * stipple.shapeParameter) / 2.0f; QPointF directionY = QPointF(-sin(stipple.rotation), cos(stipple.rotation)) * (1.0f - stipple.shapeRadius) * (stipple.shapeParameter / 2.0f); QVector<QPointF> cornerPoints = { center + directionX + directionY, center - directionX + directionY, center - directionX - directionY, center + directionX - directionY }; QVector<QPointF> polyPoints = QVector<QPointF>(); float segmentRadius = M_PI / ((pointsPerCorner - 1) * 2); for (int cornerIndex = 0; cornerIndex < 4; ++cornerIndex) { for (int segmentIndex = 0; segmentIndex < pointsPerCorner; ++segmentIndex) { QPointF corner = cornerPoints[cornerIndex]; float angle = (cornerIndex * (pointsPerCorner - 1) + segmentIndex) * segmentRadius + stipple.rotation; polyPoints.append(corner + QPointF(cos(angle), sin(angle)) * stipple.shapeRadius * stipple.shapeParameter / 2.0f); } } QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_polys.contains(color)) { m_polys[color] = QVector<QVector<QPointF>>(); } m_polys[color].append(polyPoints); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_polys.cbegin(); iter != m_polys.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto poly : iter.value()) { painter->drawPolygon(&poly[0], pointsPerCorner * 4); } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; int pointsPerCorner = 10; QHash<QColor, QVector<QVector<QPointF>>> m_polys; }; class RoundedRectangleStipplesItem : public QGraphicsItem { public: RoundedRectangleStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float size = stipple.size; QPointF center = QPointF(stipple.center.x, stipple.center.y) + offset; QPointF directionX = QPointF(cos(stipple.rotation), sin(stipple.rotation)) * (size / 2.0f) * (stipple.shapeParameter - stipple.shapeRadius); QPointF directionY = QPointF(-sin(stipple.rotation), cos(stipple.rotation)) * (size / 2.0f) * (1.0f - stipple.shapeRadius); QVector<QPointF> cornerPoints = { center + directionX + directionY, center - directionX + directionY, center - directionX - directionY, center + directionX - directionY }; QVector<QPointF> polyPoints = QVector<QPointF>(); float segmentRadius = M_PI / ((pointsPerCorner - 1) * 2); for (int cornerIndex = 0; cornerIndex < 4; ++cornerIndex) { for (int segmentIndex = 0; segmentIndex < pointsPerCorner; ++segmentIndex) { QPointF corner = cornerPoints[cornerIndex]; float angle = (cornerIndex * (pointsPerCorner - 1) + segmentIndex) * segmentRadius + stipple.rotation; polyPoints.append(corner + QPointF(cos(angle), sin(angle)) * stipple.shapeRadius * size / 2.0f); } } QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_polys.contains(color)) { m_polys[color] = QVector<QVector<QPointF>>(); } m_polys[color].append(polyPoints); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_polys.cbegin(); iter != m_polys.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto poly : iter.value()) { painter->drawPolygon(&poly[0], pointsPerCorner * 4); } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; int pointsPerCorner = 10; QHash<QColor, QVector<QVector<QPointF>>> m_polys; }; class RoundedRhombusStipplesItem : public QGraphicsItem { public: RoundedRhombusStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float size = (1.0f - stipple.shapeRadius) * stipple.size; QPointF center = QPointF(stipple.center.x, stipple.center.y) + offset; QPointF directionX = QPointF(cos(stipple.rotation), sin(stipple.rotation)) * size / 2.0f * stipple.shapeParameter; QPointF directionY = QPointF(-sin(stipple.rotation), cos(stipple.rotation)) * size / 2.0f; QVector<QPointF> cornerPoints = { center + directionX, center + directionY, center - directionX, center - directionY }; QVector<QPointF> polyPoints = QVector<QPointF>(); float angleOffset = atanf(stipple.shapeParameter); //inscribed circle radius = a*b/(sqrt(a*a+b*b)*2), where a = stipple.size and b = stipple.size * stipple.shapeParameter const float inscribed = stipple.shapeRadius * stipple.size * stipple.shapeParameter / (std::sqrt((1.0f + stipple.shapeParameter * stipple.shapeParameter)) * 2.0f); for (int cornerIndex = 0; cornerIndex < 4; ++cornerIndex) { float startAngle = cornerIndex * M_PI / 2.0f - angleOffset; float endAngle = cornerIndex * M_PI / 2.0f + angleOffset; float segmentRadius = (endAngle - startAngle) / (pointsPerCorner - 1); for (int segmentIndex = 0; segmentIndex < pointsPerCorner; ++segmentIndex) { QPointF corner = cornerPoints[cornerIndex]; float angle = startAngle + segmentIndex * segmentRadius + stipple.rotation; polyPoints.append(corner + QPointF(cos(angle), sin(angle)) * inscribed); } angleOffset = M_PI / 2.0f - angleOffset; } QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_polys.contains(color)) { m_polys[color] = QVector<QVector<QPointF>>(); } m_polys[color].append(polyPoints); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_polys.cbegin(); iter != m_polys.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto poly : iter.value()) { painter->drawPolygon(&poly[0], pointsPerCorner * 4); } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; int pointsPerCorner = 10; QHash<QColor, QVector<QVector<QPointF>>> m_polys; }; class RoundedTriangleStipplesItem : public QGraphicsItem { public: RoundedTriangleStipplesItem(const std::vector<Stipple>& stipples, QSizeF targetSize, QPointF offset, QGraphicsItem* parent = nullptr) : QGraphicsItem(parent) , m_boundingRect(QPointF(0, 0), targetSize) { for (const auto& stipple : stipples) { // Transform to view space. float triangle_side = (1.0f - stipple.shapeRadius) * stipple.size; QPointF center = QPointF(stipple.center.x, stipple.center.y) + offset; float radius = triangle_side / std::sqrt(3); float angles[3] = { stipple.rotation, (float)M_PI * 4.0f / 6.0f + stipple.rotation, (float)M_PI * 8.0f / 6.0f + stipple.rotation }; QVector<QPointF> cornerPoints = QVector<QPointF>(); for (float angle : angles) { cornerPoints.append(center + QPointF(cos(angle), sin(angle)) * radius); } QVector<QPointF> polyPoints = QVector<QPointF>(); float segmentRadius = (2.0 * M_PI) / ((pointsPerCorner - 1) * 3); const float r_inscribed = stipple.shapeRadius * stipple.size * std::sqrt(3.0f) / 6.0f; for (int cornerIndex = 0; cornerIndex < 3; ++cornerIndex) { for (int segmentIndex = 0; segmentIndex < pointsPerCorner; ++segmentIndex) { QPointF corner = cornerPoints[cornerIndex]; float angle = angles[(cornerIndex + 1) % 3] + M_PI + segmentIndex * segmentRadius; polyPoints.append(corner + QPointF(cos(angle), sin(angle)) * r_inscribed); } } QColor color(stipple.color.r(), stipple.color.g(), stipple.color.b(), stipple.color.a()); // Store it for rendering. if (!m_polys.contains(color)) { m_polys[color] = QVector<QVector<QPointF>>(); } m_polys[color].append(polyPoints); } } QRectF boundingRect() const override { return m_boundingRect; } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget) override { QPen pen = painter->pen(); QBrush brush = painter->brush(); painter->setPen(Qt::NoPen); for (auto iter = m_polys.cbegin(); iter != m_polys.cend(); ++iter) { painter->setBrush(iter.key()); for (const auto poly : iter.value()) { painter->drawPolygon(&poly[0], pointsPerCorner * 3); } } painter->setPen(painter->pen()); painter->setBrush(brush); } protected: QRectF m_boundingRect; int pointsPerCorner = 10; QHash<QColor, QVector<QVector<QPointF>>> m_polys; }; ImageViewer::ImageViewer(QWidget* parent) : QGraphicsView(parent) , m_canvasColor(QColor(119, 119, 119)) { // OpenGL acceleration. QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setDepthBufferSize(0); format.setSamples(8); QOpenGLWidget* viewport = new QOpenGLWidget(); viewport->setFormat(format); setViewport(viewport); // Rendering-related things. setRenderHint(QPainter::Antialiasing, true); setRenderHint(QPainter::SmoothPixmapTransform, true); setOptimizationFlag(QGraphicsView::DontSavePainterState); setViewportUpdateMode(QGraphicsView::FullViewportUpdate); setCacheMode(QGraphicsView::CacheNone); // Look and feel. setInteractive(false); setDragMode(QGraphicsView::ScrollHandDrag); setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); setBackgroundBrush(palette().brush(QPalette::Dark)); setAlignment(Qt::AlignCenter); setMinimumSize(QSize(480, 640)); setFrameStyle(0); setScene(new QGraphicsScene(this)); } void ImageViewer::clear() { this->scene()->clear(); m_stipplesSplit = 0; m_stipplesTotal = 0; } void ImageViewer::setCanvasArea(const QRectF& rect) { this->scene()->setSceneRect(rect); } QColor ImageViewer::canvasColor() const { return m_canvasColor; } void ImageViewer::setCanvasColor(QColor color) { m_canvasColor = color; this->update(); } void ImageViewer::setHightlightSplits(bool enabled) { m_highlightSplits = enabled; } void ImageViewer::setBackground(const QImage& image, float scale) { QGraphicsPixmapItem* item = this->scene()->addPixmap(QPixmap::fromImage(image)); item->setTransformationMode(Qt::SmoothTransformation); item->setScale(1.0f / scale); item->setZValue(-2.0f); } void ImageViewer::setDensity(int layerIndex, const Map<float>& density, float scale, const QColor& color) { QImage image(density.width, density.height, QImage::Format_ARGB32); for (int y = 0; y < image.height(); ++y) { for (int x = 0; x < image.width(); ++x) { int alpha = std::min(255.0f, std::max(0.0f, density.pixels[y * density.width + x] * 255.0f)); QRgb newPixel = qRgba(color.red(), color.green(), color.blue(), alpha); image.setPixel(x, y, newPixel); } } QGraphicsPixmapItem* item = this->scene()->addPixmap(QPixmap::fromImage(image)); item->setTransformationMode(Qt::SmoothTransformation); item->setScale(scale); item->setZValue(-1.0f); } void ImageViewer::setStipples(int layerIndex, const std::vector<Stipple>& stipples, QSize imageSize, QPointF offset) { m_stipplesSplit += std::count_if(stipples.begin(), stipples.end(), [](const auto& stipple) { return stipple.state == StippleState::New; }); m_stipplesTotal += stipples.size(); std::vector<Stipple> stipplesCopy = stipples; if (m_highlightSplits) { int h, s, v; for (auto& stipple : stipplesCopy) { if (stipple.state == StippleState::New) { QColor(stipple.color.argb).getHsv(&h, &s, &v); s = (s + 80 * (s < 128 ? 1 : -1)); v = (v + 80 * (v < 128 ? 1 : -1)); QColor highlightColor = QColor::fromHsv(h, s, v); stipple.color = Color(highlightColor.red(), highlightColor.green(), highlightColor.blue()); } else if (stipple.state == StippleState::Merged) { stipple.color = Color(255, 0, 255); } } } const auto newStippleItem = [this, imageSize, offset](const std::vector<Stipple>& stipples) -> QGraphicsItem* { switch (stipples[0].shape) { case StippleShape::Circle: return new CircleStipplesItem(stipples, imageSize, offset); case StippleShape::Line: return new LineStipplesItem(stipples, imageSize, offset); case StippleShape::Rectangle: return new RectangleStipplesItem(stipples, imageSize, offset); case StippleShape::Rhombus: return new RhombusStipplesItem(stipples, imageSize, offset); case StippleShape::Ellipse: return new EllipseStipplesItem(stipples, imageSize, offset); case StippleShape::Triangle: return new TriangleStipplesItem(stipples, imageSize, offset); case StippleShape::RoundedLine: return new RoundedLineStipplesItem(stipples, imageSize, offset); case StippleShape::RoundedRectangle: return new RoundedRectangleStipplesItem(stipples, imageSize, offset); case StippleShape::RoundedRhombus: return new RoundedRhombusStipplesItem(stipples, imageSize, offset); case StippleShape::RoundedTriangle: return new RoundedTriangleStipplesItem(stipples, imageSize, offset); default: Q_UNREACHABLE(); } }; if (!stipplesCopy.empty()) { auto item = newStippleItem(stipplesCopy); this->scene()->addItem(item); } } void ImageViewer::save(const QString& path) { if (path.endsWith("svg", Qt::CaseInsensitive)) { this->saveSVG(path); } else if (path.endsWith("pdf", Qt::CaseInsensitive)) { this->savePDF(path); } else { this->savePixmap(path); } } void ImageViewer::drawBackground(QPainter* painter, const QRectF& rect) { QGraphicsView::drawBackground(painter, rect); painter->fillRect(this->sceneRect(), m_canvasColor); } void ImageViewer::wheelEvent(QWheelEvent* event) { QGraphicsView::wheelEvent(event); if (event->angleDelta().y() > 0) { this->scale(1.25, 1.25); } else { this->scale(0.8, 0.8); } } void ImageViewer::savePDF(const QString& path) { QPdfWriter writer(path); writer.setCreator(QApplication::applicationName()); writer.setPageSize(QPageSize(this->scene()->sceneRect().size(), QPageSize::Point)); writer.setPageMargins(QMarginsF()); QPainter painter(&writer); this->scene()->render(&painter); painter.end(); } void ImageViewer::saveSVG(const QString& path) { QSvgGenerator generator; generator.setFileName(path); generator.setSize(QSize(this->scene()->width(), this->scene()->height())); generator.setViewBox(this->scene()->sceneRect()); generator.setDescription(QString("Created by %1").arg(QApplication::applicationName())); QPainter painter(&generator); this->scene()->render(&painter); painter.end(); } void ImageViewer::savePixmap(const QString& path) { QPixmap pixmap = this->toPixmap(1.0f); if (path.endsWith(".jpg")) { //XXX: do this properly QPixmap otherPixmap(pixmap.size()); otherPixmap.fill(m_canvasColor); QPainter painter(&otherPixmap); painter.drawPixmap(0, 0, pixmap); painter.end(); pixmap = otherPixmap; } pixmap.save(path); } QPixmap ImageViewer::toPixmap(float superSamplingFactor) { QRectF sceneRect = QTransform::fromScale(superSamplingFactor, superSamplingFactor) .mapRect(this->scene()->sceneRect()); QPixmap pixmap(sceneRect.size().toSize()); pixmap.fill(Qt::transparent); QPainter painter(&pixmap); painter.setRenderHint(QPainter::Antialiasing, true); painter.setRenderHint(QPainter::SmoothPixmapTransform, true); painter.setClipRect(sceneRect); this->scene()->render(&painter); return std::move(pixmap); } void ImageViewer::contextMenuEvent(QContextMenuEvent* event) { const auto copyPixmap = [this](float superSamplingFactor, bool useAlpha) { return [this, superSamplingFactor, useAlpha](bool checked) { QPixmap pixmap = this->toPixmap(superSamplingFactor); QImage::Format format = useAlpha ? QImage::Format_ARGB32 : QImage::Format_RGB32; QImage image(pixmap.size(), format); if (useAlpha) { image.fill(Qt::transparent); } else { image.fill(m_canvasColor); } QPainter painter(&image); painter.drawPixmap(0, 0, pixmap); // Workaround since clipboard()->setImage() does not work with GIMP, Word, etc. QByteArray byteArray; QBuffer buffer(&byteArray); buffer.open(QIODevice::WriteOnly); image.save(&buffer, "PNG"); buffer.close(); QMimeData* mime = new QMimeData(); mime->setImageData(image); mime->setData("PNG", byteArray); mime->setData("image/png", byteArray); QApplication::clipboard()->setMimeData(mime); }; }; QMenu menu(this); QAction* copyAction100 = menu.addAction("Copy at 100%"); QAction* copyAction200 = menu.addAction("Copy at 200%"); QAction* copyAction400 = menu.addAction("Copy at 400%"); QAction* copyAction100Alpha = menu.addAction("Copy at 100% (transparent)"); QAction* copyAction200Alpha = menu.addAction("Copy at 200% (transparent)"); QAction* copyAction400Alpha = menu.addAction("Copy at 400% (transparent)"); connect(copyAction100, QOverload<bool>::of(&QAction::triggered), copyPixmap(1.0f, false)); connect(copyAction200, QOverload<bool>::of(&QAction::triggered), copyPixmap(2.0f, false)); connect(copyAction400, QOverload<bool>::of(&QAction::triggered), copyPixmap(4.0f, false)); connect(copyAction100Alpha, QOverload<bool>::of(&QAction::triggered), copyPixmap(1.0f, true)); connect(copyAction200Alpha, QOverload<bool>::of(&QAction::triggered), copyPixmap(2.0f, true)); connect(copyAction400Alpha, QOverload<bool>::of(&QAction::triggered), copyPixmap(4.0f, true)); if (m_stipplesTotal > 0) { if (m_stipplesSplit > 1) { menu.addAction(QString("Stipples %L1 (%2 splits)").arg(m_stipplesTotal).arg(m_stipplesSplit))->setEnabled(false); } else { menu.addAction(QString("Stipples %L1").arg(m_stipplesTotal))->setEnabled(false); } } menu.addAction(QString("Position %1 , %2").arg(event->pos().x()).arg(event->pos().y()))->setEnabled(false); menu.exec(event->globalPos()); }
42.638107
183
0.616711
[ "render", "shape", "vector", "transform" ]
1bfd559c98ea4f165e4ed8c22d69247d08016e3e
13,810
cpp
C++
cpp-stl-containers/vector/my-vector.cpp
ElwinCabrera/Standard-Template-Library-Containers-CPP
d6ace1760616cc1abf1e66e38926b9eaa75bcbbd
[ "BSD-3-Clause" ]
null
null
null
cpp-stl-containers/vector/my-vector.cpp
ElwinCabrera/Standard-Template-Library-Containers-CPP
d6ace1760616cc1abf1e66e38926b9eaa75bcbbd
[ "BSD-3-Clause" ]
null
null
null
cpp-stl-containers/vector/my-vector.cpp
ElwinCabrera/Standard-Template-Library-Containers-CPP
d6ace1760616cc1abf1e66e38926b9eaa75bcbbd
[ "BSD-3-Clause" ]
1
2020-05-20T16:04:42.000Z
2020-05-20T16:04:42.000Z
/* Operation Speed CustomVector(); O(1) CustomVector(unsigned int size) O(size) CustomVector(unsigned int size, const T &type) O(size) CustomVector(const CustomVector<T> &v) O(v.size()) CustomVector(CustomVector<T> &&other) O(1) ~CustomVector() O(capacity) begin() O(1) end() O(1) size() O(1) max_size() O(1) capacity() O(1) empty() O(1) reserve(unsigned int cap) O(cap) shrink_to_fit(); O(cap - size) operator[](unsigned int idx) O(1) - Amertized at(unsigned int idx) O(1) - Amertized front() O(1) back() O(1) data() O(1) assign(unsigned int count, const T &value) O(count) push_back(const T &item) O(1) push_front(const T &item) O(size) pop_back() O(1) insert(iterator it, const T &item) O(size - it) erase(iterator pos) O(size - pos) erase(iterator first, iterator last) O(size - first) resize(unsigned int size) O(size) swap(CustomVector<T> &otherV) O(1) clear() O(size) */ #include <stdexcept> #include <iostream> #include <string.h> #include <algorithm> #include <climits> template<class T> class CustomVector{ private: unsigned int currCapacity; unsigned int vectSize; T *buffer; public: typedef T *iterator; CustomVector(); CustomVector(unsigned int size); CustomVector(unsigned int size, const T &type); CustomVector(const CustomVector<T> &v); //Copy Constructor CustomVector(CustomVector<T> &&other) noexcept ; //Move Constructor ~CustomVector(); CustomVector<T>& operator=(const CustomVector<T> &v); CustomVector<T>& operator=(CustomVector<T> &&other); iterator begin(); iterator end(); /*iterator rbegin(); iterator rend(); iterator cbegin() const; iterator cend() const; iterator crbegin() const; iterator crend() const;*/ unsigned int size() const; unsigned int max_size() const; unsigned int capacity() const; bool empty() const; void reserve(unsigned int cap); void shrink_to_fit(); T& operator[](unsigned int idx); T& operator[](unsigned int idx) const; T& at(unsigned int idx); T& at(unsigned int idx) const; T& front() const; T& back() const; T* data() const; void assign(unsigned int count, const T &value); void push_back(const T &item); void push_front(const T &item); void pop_back(); void insert(iterator it, const T &item); void insert(unsigned int pos, const T &item); void erase(iterator pos); void erase(iterator first, iterator last); void resize(unsigned int size); void swap(CustomVector<T> &otherV) noexcept; void clear(); template<class ... Args> void emplace(iterator it,Args&& ... args){ //T newT(std::forward<Args>(args)...)); T *newT = new (it) T(std::forward<Args>(args)...); //push_back(new (*this) T(std::forward<Args>(args)...)); } template<class ... Args> void emplace_back(Args&& ... args){ //T newT(std::forward<Args>(args)...)); if(vectSize == currCapacity){ if(vectSize == 0) reserve(1); else reserve(2 * currCapacity); } T *newT = new (end()) T(std::forward<Args>(args)...); //push_back(new (*this) T(std::forward<Args>(args)...)); ++vectSize; } //void get_allocator }; /** Constructors and Destructors **/ template<typename T> CustomVector<T>::CustomVector(){ //cout << "In Constructor #1"<<"\n"; currCapacity = 0; vectSize = 0; buffer = nullptr; } template<typename T> CustomVector<T>::CustomVector(unsigned int size){ //cout << "In Constructor #2"<<"\n"; buffer = nullptr; this->vectSize = size; reserve(size); } template<typename T> CustomVector<T>::CustomVector(unsigned int size, const T &item){ //cout << "In Constructor #3"<<"\n"; if(this->buffer != nullptr) this->buffer = nullptr; reserve(size); this->vectSize = size; for(unsigned int i = 0; i < size; i++) memcpy(buffer+i, &item, sizeof(item)); } template<typename T> CustomVector<T>::CustomVector( const CustomVector<T> &other){ //cout << "In Copy Constructor #4"<<"\n"; this->buffer = nullptr; reserve(other.size()); vectSize = other.size(); for(unsigned int i = 0; i < other.size(); i++) buffer[i] = other.buffer[i]; } template<typename T> CustomVector<T>::CustomVector(CustomVector<T> &&other) noexcept { //cout << "In Move Constructor #5"<<"\n"; buffer = other->buffer; other->buffer = nullptr; } template<typename T> CustomVector<T>::~CustomVector(){ //cout << "In Custom Vector Destructor "<<"\n"; if(buffer != nullptr) { delete[] buffer; buffer = nullptr; } } template<typename T> CustomVector<T>& CustomVector<T>::operator=(const CustomVector<T> &other){ //cout << "In operator= (...)"<<"\n"; CustomVector<T> tmpCpy(other); tmpCpy.swap(*this); return *this; } template<typename T> CustomVector<T>& CustomVector<T>::operator=(CustomVector<T> &&other){ } /** Iterators **/ template<typename T> typename CustomVector<T>::iterator CustomVector<T>::begin(){ return buffer; } template<typename T> typename CustomVector<T>::iterator CustomVector<T>::end(){ return buffer + size(); } /** Capacity Functions **/ template<typename T> unsigned int CustomVector<T>::size() const { //cout << "In size()"<<"\n"; return vectSize; } template<typename T> unsigned int CustomVector<T>::max_size() const { //cout << "In max_size()"<<"\n"; return UINT_MAX; } template<typename T> bool CustomVector<T>::empty() const { //cout << "In empty()"<<"\n"; return size() == 0; } template<typename T> void CustomVector<T>::reserve(unsigned int cap){ //cout << "In reserve(..)"<<"\n"; T *newArr; try{ newArr = new T[(sizeof(T)* cap)]; } catch (const std::bad_alloc& ba){ std::cerr << "CustomVector reserve(): memory allocation failure: " << ba.what()<<"\n"; } if(buffer != nullptr) { for(unsigned int i =0; i< vectSize; i++ ) newArr[i] = buffer[i]; delete[] buffer; buffer = nullptr; } buffer = newArr; currCapacity = cap; } template<typename T> unsigned int CustomVector<T>::capacity() const { //cout << "In capacity()"<<"\n"; return currCapacity; } template<typename T> void CustomVector<T>::shrink_to_fit(){ //cout << "In shrink_to_fit()"<<"\n"; for(auto it = end(); it< begin() + currCapacity; it++) it->~T(); currCapacity = vectSize; } /** Access **/ template <typename T> T& CustomVector<T>::operator[] (unsigned int idx){ //cout << "In operator[] (...)"<<"\n"; return buffer[idx]; } template <typename T> T& CustomVector<T>::operator[] (unsigned int idx) const{ //cout << "In operator[] (...)"<<"\n"; return buffer[idx]; } template <typename T> T& CustomVector<T>::at(unsigned int idx){ //cout << "In at(...)"<<"\n"; try{ return buffer[idx]; } catch(const std::out_of_range& oor){ std::cerr << "Out of Range error: " << oor.what() << "\n"; } } template <typename T> T& CustomVector<T>::at(unsigned int idx) const{ //cout << "In at(...)"<<"\n"; try{ return buffer[idx]; } catch(const std::out_of_range& oor){ std::cerr << "Out of Range error: " << oor.what() << "\n"; } } template <typename T> T& CustomVector<T>::front() const{ //cout << "In front()"<<"\n"; return buffer[0]; } template <typename T> T& CustomVector<T>::back() const{ //cout << "In back()"<<"\n"; return buffer[vectSize-1]; } template <typename T> T* CustomVector<T>::data() const{ //cout << "In data()"<<"\n"; return buffer; } /** Modifiers **/ template<typename T> void CustomVector<T>::clear(){ //cout << "In clear()"<<"\n"; if(buffer != nullptr) delete[] buffer; buffer = nullptr; vectSize = 0; } template<typename T> void CustomVector<T>::assign(unsigned int count, const T &item){ //cout << "In assign(...)"<<"\n"; resize(count); for(unsigned int i = 0; i < count; i++) this->at(i) = item; } template<typename T> void CustomVector<T>::push_back(const T &item){ //cout << "In push_back(...)"<<"\n"; if(vectSize == currCapacity){ if(currCapacity == 0) reserve(1); else reserve(2 *currCapacity); } buffer[vectSize++] = item; } template<typename T> void CustomVector<T>::push_front(const T &item){ //cout << "In push_front(...)"<<"\n"; if(vectSize == currCapacity){ if(currCapacity == 0) reserve(1); else reserve(2 * currCapacity); } for(unsigned int i = vectSize; i>=1; i--) buffer[i] = buffer[i -1]; buffer[0] = item; ++vectSize; } template<typename T> void CustomVector<T>::pop_back(){ //cout << "In pop_back()"<<"\n"; --vectSize; (end()-1)->~T(); } template<typename T> void CustomVector<T>::insert(CustomVector<T>::iterator it, const T &item){ //cout << "In insert(...)"<<"\n"; *it = item; } template<typename T> void CustomVector<T>::insert(unsigned int pos, const T &item){ //cout << "In insert(...)"<<"\n"; this->buffer[pos] = item; } template<typename T> void CustomVector<T>::erase(CustomVector<T>::iterator it){ //cout << "In erase(...) #1"<<"\n"; if(it == end()-1) { pop_back(); } else{ it->~T(); for(auto i = it; i < end(); i++){ if(i +1 < end()) *i = *(i +1); } --vectSize; } } template<typename T> void CustomVector<T>::erase(CustomVector<T>::iterator first, CustomVector<T>::iterator last){ //cout << "In erase(...) #2"<<"\n"; int count = 0; for(auto it = first; it < last; it++){ ++count; it->~T(); } auto it = first; auto it2 = last; while(it2 < end()){ *it++ = *it2++; it2->~T(); } vectSize = vectSize - count; } template<typename T> void CustomVector<T>::resize(unsigned int size) { //cout << "In resize(...)"<<"\n"; T *newArr = new T[size]; int stopIdx = (size > vectSize) ? vectSize: size; for(unsigned int i = 0; i < stopIdx; i++) newArr[i] = buffer[i]; if(buffer != nullptr) delete[] buffer; buffer = newArr; currCapacity = size; vectSize = size; } template<typename T> void CustomVector<T>::swap(CustomVector<T> &otherV) noexcept{ //cout << "In swap(...)"<<"\n"; using std::swap; unsigned int i = otherV.size(); swap(this->vectSize, i); swap(this->buffer, otherV.buffer); } // template<typename T> // namespace test { // typedef CustomVector<T> vect; // } /*template< class Type, class UnqualifiedType = std::remove_cv_t<Type> > class Iterator { public: using value_type = UnqualifiedType; using pointer = UnqualifiedType*; using reference = UnqualifiedType&; using difference_type = std::ptrdiff_t; using iterator_category = std::random_access_iterator_tag; Iterator(): v(nullptr), i(0) {} Iterator(Vector<Type>* v, int i): v(v), i(i) {} // Default Copy/Move Are Fine. Iterator(Iterator &it) = default; Iterator(Iterator &&it) = default; // Default Destructor fine. ~Iterator() = default; reference operator*() {return (*v)[i];} const reference operator*() const {return (*v)[i];} pointer operator->() {return &((*v)[i]);} const pointer operator->() const {return &((*v)[i]);} reference operator[](int m) {return (*v)[i + m];} const reference operator[](int m) const {return (*v)[i + m];} Iterator& operator++() {++i;return *this;} Iterator& operator--() {--i;return *this;} Iterator operator++(int) {Iterator r(*this);++i;return r;} Iterator operator--(int) {Iterator r(*this);--i;return r;} Iterator& operator+=(int n) {i += n;return *this;} Iterator& operator-=(int n) {i -= n;return *this;} Iterator operator+(int n) const {Iterator r(*this);return r += n;} Iterator operator-(int n) const {Iterator r(*this);return r -= n;} difference_type operator-(Iterator const& r) const {return i - r.i;} // Note: comparing iterator from different containers // is undefined behavior so we don't need to check // if they are the same container. bool operator<(Iterator const& r) const {return i < r.i;} bool operator<=(Iterator const& r) const {return i <= r.i;} bool operator>(Iterator const& r) const {return i > r.i;} bool operator>=(Iterator const& r) const {return i >= r.i;} bool operator!=(const Iterator &r) const {return i != r.i;} bool operator==(const Iterator &r) const {return i == r.i;} private: Vector<Type>* v; int i; };*/
28.592133
94
0.549095
[ "vector" ]
40011cf96ef521b38cd94e20c82f642e5dabfb52
2,284
cpp
C++
aws-cpp-sdk-mediaconvert/source/model/DashIsoPlaybackDeviceCompatibility.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-mediaconvert/source/model/DashIsoPlaybackDeviceCompatibility.cpp
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-mediaconvert/source/model/DashIsoPlaybackDeviceCompatibility.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/mediaconvert/model/DashIsoPlaybackDeviceCompatibility.h> #include <aws/core/utils/HashingUtils.h> #include <aws/core/Globals.h> #include <aws/core/utils/EnumParseOverflowContainer.h> using namespace Aws::Utils; namespace Aws { namespace MediaConvert { namespace Model { namespace DashIsoPlaybackDeviceCompatibilityMapper { static const int CENC_V1_HASH = HashingUtils::HashString("CENC_V1"); static const int UNENCRYPTED_SEI_HASH = HashingUtils::HashString("UNENCRYPTED_SEI"); DashIsoPlaybackDeviceCompatibility GetDashIsoPlaybackDeviceCompatibilityForName(const Aws::String& name) { int hashCode = HashingUtils::HashString(name.c_str()); if (hashCode == CENC_V1_HASH) { return DashIsoPlaybackDeviceCompatibility::CENC_V1; } else if (hashCode == UNENCRYPTED_SEI_HASH) { return DashIsoPlaybackDeviceCompatibility::UNENCRYPTED_SEI; } EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { overflowContainer->StoreOverflow(hashCode, name); return static_cast<DashIsoPlaybackDeviceCompatibility>(hashCode); } return DashIsoPlaybackDeviceCompatibility::NOT_SET; } Aws::String GetNameForDashIsoPlaybackDeviceCompatibility(DashIsoPlaybackDeviceCompatibility enumValue) { switch(enumValue) { case DashIsoPlaybackDeviceCompatibility::CENC_V1: return "CENC_V1"; case DashIsoPlaybackDeviceCompatibility::UNENCRYPTED_SEI: return "UNENCRYPTED_SEI"; default: EnumParseOverflowContainer* overflowContainer = Aws::GetEnumOverflowContainer(); if(overflowContainer) { return overflowContainer->RetrieveOverflow(static_cast<int>(enumValue)); } return {}; } } } // namespace DashIsoPlaybackDeviceCompatibilityMapper } // namespace Model } // namespace MediaConvert } // namespace Aws
32.169014
112
0.66725
[ "model" ]
4002528a1ff37c9be94fdb9d238c64153a43b911
4,300
cpp
C++
mjcore/decomp.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
13
2016-01-20T02:10:52.000Z
2022-03-08T15:51:36.000Z
mjcore/decomp.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
13
2020-09-28T12:57:52.000Z
2022-02-20T19:20:57.000Z
mjcore/decomp.cpp
MihailJP/MiHaJong
b81168ab2696dd29af5c400b84c870a9b8a2f01e
[ "MIT" ]
4
2016-09-19T13:44:10.000Z
2022-02-18T08:13:37.000Z
#include "decomp.h" #include <cassert> #include "lzma/LzmaLib.h" #include "lzma/Sha256.h" #include "logging.h" #include "reader/readrsrc.h" #include "../common/strcode.h" #include "except.h" #ifndef _MSC_VER #include <cstdlib> #endif #include <algorithm> using std::min; /* 面子データ初期化 */ namespace Compressed { void Data::decompress(int FileID_) { #ifdef _WIN32 DWORD size = 0; #else /*_WIN32*/ size_t size = 0; #endif /*_WIN32*/ SizeT size_ = 0; const uint8_t* compressedBuf = nullptr; int result; LoadFileInResource(FileID_, LZMA_STREAM, size, compressedBuf); assert(size > 13); uint8_t* compressedData = new uint8_t[static_cast<std::size_t>(size) + 1]; memcpy(compressedData, compressedBuf, size); compressedData[size] = 0; decompressedSize = *(reinterpret_cast<size_t *>(compressedData+5)); DecompressedData = new uint8_t[decompressedSize]; size_ = size; result = LzmaUncompress(DecompressedData, &decompressedSize, reinterpret_cast<const uint8_t *>(compressedData+13), &size_, reinterpret_cast<const uint8_t *>(compressedData), 5); delete[] compressedData; compressedData = nullptr; if (result != SZ_OK) { CodeConv::tostringstream o; o << _T("LZMAストリームのデコードに失敗しました。ファイルが壊れている虞があります。") << _T("エラーコード: ") << result; Raise(EXCEPTION_MJCORE_DECOMPRESSION_FAILURE, o.str().c_str()); } else { info(_T("LZMAストリームをデコードしました。")); } return; } void Data::calcSHA256() { CSha256 p; Sha256_Init(&p); Sha256_Update(&p, DecompressedData, decompressedSize); Sha256_Final(&p, actualDigest); } std::string Data::bytesToHexString(std::vector<uint8_t> byteStr) { std::string hx = std::string(); for (unsigned int i = 0; i < byteStr.size(); i++) { std::ostringstream o; o.setf(std::ios::right); o.fill('0'); o.width(2); o << std::hex << static_cast<int>(byteStr[i]); hx += o.str(); } return hx; } void Data::verify(LPCTSTR Description_, const uint8_t* const expectedDigest_) { memset(actualDigest, 0, sizeof(actualDigest)); bool mdUnmatch = false; calcSHA256(); for (int i = 0; i < 32; i++) { if (expectedDigest_[i] != actualDigest[i]) mdUnmatch = true; } if (mdUnmatch) { CodeConv::tostringstream o; o << Description_ << _T("のSHA256ハッシュ値が一致しませんでした。") << _T("ファイルが壊れている虞があります。") << std::endl << _T("期待されるハッシュ値: ") << CodeConv::EnsureTStr(bytesToHexString(std::vector<uint8_t>(expectedDigest_, expectedDigest_ + 32))) << std::endl << _T("実際のハッシュ値: ") << CodeConv::EnsureTStr(bytesToHexString(std::vector<uint8_t>(actualDigest, actualDigest + 32))); Raise(EXCEPTION_MJCORE_HASH_MISMATCH, o.str().c_str()); } else { CodeConv::tostringstream o; o << Description_ << _T("のSHA256ハッシュ値の照合に成功しました。"); info(o.str().c_str()); } } Data::Data(LPCTSTR Description_, int FileID_, const uint8_t* const expectedDigest_) { // 初期化 memset(actualDigest, 0, sizeof actualDigest); try { decompress(FileID_); verify(Description_, expectedDigest_); } #ifdef _WIN32 catch (_EXCEPTION_POINTERS* e) { ErrorInfo *errStat = nullptr; switch (e->ExceptionRecord->ExceptionCode) { case EXCEPTION_MJCORE_DECOMPRESSION_FAILURE: errStat = reinterpret_cast<ErrorInfo *>(e->ExceptionRecord->ExceptionInformation[0]); MessageBox(nullptr, CodeConv::EnsureTStr(errStat->msg).c_str(), _T("LZMA decompression error"), MB_OK | MB_ICONERROR | MB_SETFOREGROUND); #ifdef _MSC_VER terminate(); #else abort(); #endif case EXCEPTION_MJCORE_HASH_MISMATCH: errStat = reinterpret_cast<ErrorInfo *>(e->ExceptionRecord->ExceptionInformation[0]); MessageBox(nullptr, CodeConv::EnsureTStr(errStat->msg).c_str(), _T("SHA256 verification error"), MB_OK | MB_ICONERROR | MB_SETFOREGROUND); #ifdef _MSC_VER terminate(); #else abort(); #endif default: throw; } } #else /*_WIN32*/ catch (...) { /* TODO: 未実装箇所 */ throw; } #endif /*_WIN32*/ } Data::~Data() { delete[] DecompressedData; DecompressedData = nullptr; } LPCTSTR Data::Description = nullptr; constexpr uint8_t Data::expectedDigest[32] = {0,}; LPCTSTR file_mentz_dat::Description = _T("面子構成データベース"); constexpr uint8_t file_mentz_dat::expectedDigest[32] = { 0x38, 0x27, 0x3a, 0x13, 0x49, 0x94, 0xd3, 0x77, 0x0e, 0x09, 0x05, 0xd4, 0xf5, 0xf7, 0xbb, 0x30, 0x81, 0x0a, 0x9f, 0x8d, 0xd4, 0x4d, 0xe8, 0x24, 0xbb, 0x66, 0x1f, 0x71, 0x40, 0xcd, 0x2c, 0x0b, }; }
28.666667
118
0.705581
[ "vector" ]
40076726af347cc881fc023143c47efc7a648258
3,077
cpp
C++
src/mbgl/renderer/painters/painter_line.cpp
skwerlzu/mapbox2
41d2496c07e54a8dad70aea4610c7200711983e5
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/renderer/painters/painter_line.cpp
skwerlzu/mapbox2
41d2496c07e54a8dad70aea4610c7200711983e5
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/renderer/painters/painter_line.cpp
skwerlzu/mapbox2
41d2496c07e54a8dad70aea4610c7200711983e5
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
#include <mbgl/renderer/painter.hpp> #include <mbgl/renderer/paint_parameters.hpp> #include <mbgl/renderer/buckets/line_bucket.hpp> #include <mbgl/renderer/render_tile.hpp> #include <mbgl/renderer/layers/render_line_layer.hpp> #include <mbgl/style/layers/line_layer_impl.hpp> #include <mbgl/programs/programs.hpp> #include <mbgl/programs/line_program.hpp> #include <mbgl/sprite/sprite_atlas.hpp> #include <mbgl/geometry/line_atlas.hpp> namespace mbgl { using namespace style; void Painter::renderLine(PaintParameters& parameters, LineBucket& bucket, const RenderLineLayer& layer, const RenderTile& tile) { if (pass == RenderPass::Opaque) { return; } const LinePaintProperties::PossiblyEvaluated& properties = layer.evaluated; auto draw = [&] (auto& program, auto&& uniformValues) { program.draw( context, gl::Triangles(), depthModeForSublayer(0, gl::DepthMode::ReadOnly), stencilModeForClipping(tile.clip), colorModeForRenderPass(), std::move(uniformValues), *bucket.vertexBuffer, *bucket.indexBuffer, bucket.segments, bucket.paintPropertyBinders.at(layer.getID()), properties, state.getZoom() ); }; if (!properties.get<LineDasharray>().from.empty()) { const LinePatternCap cap = bucket.layout.get<LineCap>() == LineCapType::Round ? LinePatternCap::Round : LinePatternCap::Square; LinePatternPos posA = lineAtlas->getDashPosition(properties.get<LineDasharray>().from, cap); LinePatternPos posB = lineAtlas->getDashPosition(properties.get<LineDasharray>().to, cap); lineAtlas->bind(context, 0); draw(parameters.programs.lineSDF, LineSDFProgram::uniformValues( properties, frame.pixelRatio, tile, state, pixelsToGLUnits, posA, posB, layer.dashLineWidth, lineAtlas->getSize().width)); } else if (!properties.get<LinePattern>().from.empty()) { optional<SpriteAtlasElement> posA = spriteAtlas->getPattern(properties.get<LinePattern>().from); optional<SpriteAtlasElement> posB = spriteAtlas->getPattern(properties.get<LinePattern>().to); if (!posA || !posB) return; spriteAtlas->bind(true, context, 0); draw(parameters.programs.linePattern, LinePatternProgram::uniformValues( properties, tile, state, pixelsToGLUnits, spriteAtlas->getPixelSize(), *posA, *posB)); } else { draw(parameters.programs.line, LineProgram::uniformValues( properties, tile, state, pixelsToGLUnits)); } } } // namespace mbgl
33.086022
104
0.58336
[ "geometry" ]
400993949032d2f54ca3588c58d5ca65b841b507
13,359
cpp
C++
src/TRGame/Lighting/LightCalculator/DirectionalLightCalculator.cpp
CXUtk/TRV2
945950012e2385aeb24e80bf5e876703445ba423
[ "Apache-2.0" ]
null
null
null
src/TRGame/Lighting/LightCalculator/DirectionalLightCalculator.cpp
CXUtk/TRV2
945950012e2385aeb24e80bf5e876703445ba423
[ "Apache-2.0" ]
15
2021-09-04T13:02:51.000Z
2021-10-05T05:51:31.000Z
src/TRGame/Lighting/LightCalculator/DirectionalLightCalculator.cpp
CXUtk/TRV2
945950012e2385aeb24e80bf5e876703445ba423
[ "Apache-2.0" ]
null
null
null
#include "DirectionalLightCalculator.h" #include <algorithm> #include <TREngine/Core/Utils/Utils.h> #include <TREngine/Engine.h> #include <TREngine/Core/Render/render.h> #include <TRGame/Worlds/WorldResources.h> #include <TRGame/Worlds/Tile.h> #include <TRGame/Worlds/TileSection.h> static std::vector<Edge> drawSegments; DirectionalLightCalculator::DirectionalLightCalculator(LightCommon* lightCommon) : _lightCommonData(lightCommon) {} DirectionalLightCalculator::~DirectionalLightCalculator() {} void DirectionalLightCalculator::AddLight(const Light & light) { _lights.push_back(light); } void DirectionalLightCalculator::ClearLights() { _lights.clear(); } void DirectionalLightCalculator::Calculate() { _shadowTriangles.clear(); for (auto& light : _lights) { calculateTrianglesForOneLight(light); } } void DirectionalLightCalculator::DrawTriangles(const glm::mat4& worldProjection) { //auto universalRenderer = trv2::Engine::GetInstance()->GetUniversalRenderer(); //int i = 0; //int sz = _shadowTriangles.size(); //for (auto& triangle : _shadowTriangles) //{ // //i++; // //if(i == 1) // universalRenderer->DrawWiredTriangle(triangle.Pos[0], triangle.Pos[1], triangle.Pos[2]); //} ////universalRenderer->SetPolygonMode(trv2::PolygonMode::WIREFRAME); //universalRenderer->Flush(trv2::PrimitiveType::TRIANGLE_LIST, worldProjection); //universalRenderer->SetPolygonMode(trv2::PolygonMode::FILL); //for (auto& segment : drawSegments) //{ // universalRenderer->DrawLine(segment.Start, segment.End, glm::vec4(0, 0, 1, 1), glm::vec4(1, 0, 0, 1)); //} //universalRenderer->Flush(trv2::PrimitiveType::LINE_LIST, worldProjection); } PVertex DirectionalLightCalculator::getVertexPtr(glm::ivec2 pos) { auto p = _vertexPtrMap.find(std::pair<int, int>{ pos.x, pos.y }); if (p != _vertexPtrMap.end()) { return p->second; } int id = _vertices.size(); _vertices.push_back(Vertex(id, pos)); PVertex vertex = &_vertices.back(); _vertexPtrMap[std::pair<int, int>{pos.x, pos.y}] = vertex; return vertex; } void DirectionalLightCalculator::calculateTrianglesForOneLight(const Light& light) { _vertices.clear(); _edges.clear(); _vertexPtrMap.clear(); auto common = _lightCommonData; auto sweepCenter = light.Position; glm::ivec2 lightTile = GameWorld::GetLowerWorldCoord(sweepCenter, 0); std::vector<KeyPointTmp> keypointTmps{}; auto startPos = lightTile - glm::ivec2(light.Radius); auto endPos = lightTile + glm::ivec2(light.Radius + 1); trv2::RectI areaRect(startPos, endPos - startPos); addBorderEdges(areaRect, sweepCenter); // Limit seraching range, generate computing segments for (int y = -light.Radius; y <= light.Radius; y++) { for (int x = -light.Radius; x <= light.Radius; x++) { auto curTilePos = lightTile + glm::ivec2(x, y); if (common->GetCachedTile(curTilePos).Type == 0) continue; auto tileRect = trv2::RectI(curTilePos, glm::ivec2(1)); addTileEdges(tileRect, sweepCenter); } } drawSegments.assign(_edges.begin(), _edges.end()); // Sort keypoints by their polar angle for (auto& vertex : _vertices) { PVertex pV = &vertex; auto pos = pV->GetWorldPos() - sweepCenter; if (pV->ConjunctionInfo.empty()) continue; keypointTmps.push_back(KeyPointTmp{ pV, atan2(pos.y, pos.x) }); } std::sort(keypointTmps.begin(), keypointTmps.end()); SweepStructure structure(_edges.size()); EdgeCmp cmp(structure); GeoPQ PQ(cmp); structure.EdgeSet = &PQ; int startIndex; performFirstScan(keypointTmps, structure, sweepCenter, startIndex); if (_edges.size() > 100) { bool a = cmp(&_edges[34], &_edges[16]); bool b = cmp(&_edges[16], &_edges[34]); if (true); } int sz = keypointTmps.size(); int cnt = 0; for (int i = startIndex; i < sz + 1; i++) { auto& cur = keypointTmps[i % sz]; auto& nxt = keypointTmps[(i + 1) % sz]; auto keypointPosCur = cur.Vertex->GetWorldPos(); auto keypointPosNext = nxt.Vertex->GetWorldPos(); // Batch the points with the same polar angle ++cnt; if (i == sz || std::abs(cross2(keypointPosCur - light.Position, keypointPosNext - light.Position)) > LightCommon::EPS) { performOneScan(keypointTmps, structure, sweepCenter, i - cnt + 1, i); cnt = 0; } } } void DirectionalLightCalculator::addBorderEdges(const trv2::RectI& rect, glm::vec2 sweepCenter) { PVertex BottomLeft = getVertexPtr(rect.BottomLeft()); PVertex TopLeft = getVertexPtr(rect.TopLeft()); PVertex TopRight = getVertexPtr(rect.TopRight()); PVertex BottomRight = getVertexPtr(rect.BottomRight()); // Left addOneSegment(BottomLeft, TopLeft, false, sweepCenter); // Up addOneSegment(TopLeft, TopRight, true, sweepCenter); // Right addOneSegment(TopRight, BottomRight, false, sweepCenter); // Bottom addOneSegment(BottomRight, BottomLeft, true, sweepCenter); } void DirectionalLightCalculator::addTileEdges(const trv2::RectI& rect, glm::vec2 sweepCenter) { PVertex BottomLeft = getVertexPtr(rect.BottomLeft()); PVertex TopLeft = getVertexPtr(rect.TopLeft()); PVertex TopRight = getVertexPtr(rect.TopRight()); PVertex BottomRight = getVertexPtr(rect.BottomRight()); auto tileCoord = rect.BottomLeft(); auto leftBlock = glm::ivec2(tileCoord.x - 1, tileCoord.y); auto upBlock = glm::ivec2(tileCoord.x, tileCoord.y + 1); auto rightBlock = glm::ivec2(tileCoord.x + 1, tileCoord.y); auto downBlock = glm::ivec2(tileCoord.x, tileCoord.y - 1); auto common = _lightCommonData; if (common->IsTileCoordInRange(leftBlock) && common->GetCachedTile(leftBlock).Type == 0) { // Left addOneSegment(BottomLeft, TopLeft, false, sweepCenter); } if (common->IsTileCoordInRange(upBlock) && common->GetCachedTile(upBlock).Type == 0) { // Up addOneSegment(TopLeft, TopRight, true, sweepCenter); } if (common->IsTileCoordInRange(rightBlock) && common->GetCachedTile(rightBlock).Type == 0) { // Right addOneSegment(TopRight, BottomRight, false, sweepCenter); } if (common->IsTileCoordInRange(downBlock) && common->GetCachedTile(downBlock).Type == 0) { // Bottom addOneSegment(BottomRight, BottomLeft, true, sweepCenter); } } void DirectionalLightCalculator::addOneSegment(PVertex A, PVertex B, bool horizontal, glm::vec2 sweepCenter) { auto vA = A->GetWorldPos() - sweepCenter; auto vB = B->GetWorldPos() - sweepCenter; float jud = cross2(vA, vB); // jud >= 0 means vB is on the left of vA, starting point should be A bool s; int id = _edges.size(); float d1 = glm::dot(vA, vA), d2 = glm::dot(vB, vB); if (jud > 0 || (jud == 0 && d1 < d2)) { _edges.push_back(Edge(A, B, id, horizontal)); s = true; } else if(jud < 0 || (jud == 0 && d1 >= d2)) { _edges.push_back(Edge(B, A, id, horizontal)); s = false; } PEdge edge = &_edges.back(); A->ConjunctionInfo.push_back(EndPointInfo{ edge, !s }); B->ConjunctionInfo.push_back(EndPointInfo{ edge, s }); } void DirectionalLightCalculator::performFirstScan(const std::vector<KeyPointTmp>& sweep, SweepStructure& structure, glm::vec2 sweepCenter, int& nxtIndex) { if (!sweep.size()) return; structure.currentRay = { sweepCenter, sweep[0].Vertex->GetWorldPos() - sweepCenter }; int totalEdges = _edges.size(); std::vector<PVertex> startpoints{}; std::map<int, int> testSegments{}; for (int i = 0; i < totalEdges; i++) { auto& edge = _edges[i]; float t; if (edge.IntersectionTest(structure.currentRay, t, true)) { testSegments[edge.Id]++; edge.IntersectionTest(structure.currentRay, t, true); } } // Proceed to next different angle nxtIndex = 0; int sz = sweep.size(); startpoints.push_back(sweep[0].Vertex); while (nxtIndex < sz && std::abs(cross2(sweep[(nxtIndex + 1) % sz].Vertex->GetWorldPos() - sweepCenter, sweep[nxtIndex].Vertex->GetWorldPos() - sweepCenter)) < LightCommon::EPS) { nxtIndex++; startpoints.push_back(sweep[nxtIndex].Vertex); } nxtIndex++; for (auto startpt : startpoints) { for (const auto& conj : startpt->ConjunctionInfo) { if (conj.IsEnd) { testSegments[conj.Edge->Id]--; } else { testSegments[conj.Edge->Id]++; } } } for (auto& pair : testSegments) { if (pair.second < 0) { eraseEdge(structure, &_edges[pair.first], sweepCenter); } } for (auto& pair : testSegments) { if (pair.second > 0) { insertNewEdge(structure, &_edges[pair.first], sweepCenter); } } float minnTime = std::numeric_limits<float>::infinity(); PEdge minnEdge = nullptr; findNearestWall(structure, minnTime, minnEdge); assert(minnEdge != nullptr); structure.lastKeyPosition = structure.currentRay.Eval(minnTime); } void DirectionalLightCalculator::RasterizeLightTriangles() { auto common = _lightCommonData; common->TileRectWorld.ForEach([this, common](glm::ivec2 coord) -> void { glm::vec2 center = glm::vec2(coord * GameWorld::TILE_SIZE + GameWorld::TILE_SIZE / 2); for (const auto& triangle : _shadowTriangles) { bool can = true; for (int i = 0; i < 3; i++) { glm::vec2 dir = triangle.Pos[(i + 1) % 3] - triangle.Pos[i]; if (cross2(dir, center - triangle.Pos[i]) > 0) { can = false; break; } } if (can) { int id = common->GetBlockId(coord - common->TileRectWorld.Position); common->TileColors[0][id] += 2.f; common->TileColors[1][id] += 2.f; common->TileColors[2][id] += 2.f; break; } } }); } void DirectionalLightCalculator::findNearestWall(SweepStructure& structure, float& minnTime, PEdge& minnEdge) { minnTime = std::numeric_limits<float>::infinity(); minnEdge = nullptr; //if (structure.PQ-> > 1) //{ // if (true); // //printf("%d\n", structure.PQ->top()->Id); //} if (!structure.EdgeSet->empty()) { for (auto edge : *structure.EdgeSet) { float t; if (edge->IntersectionTest(structure.currentRay, t)) { if (t < minnTime) { minnTime = t; minnEdge = edge; } } } //auto p = structure.EdgeSet->rbegin(); //auto edge = *p; //bool has = edge->IntersectionTest(structure.currentRay, minnTime); //assert(has); //minnEdge = edge; } if(!minnEdge) { for (auto edge : structure.borderEdges) { float t; if (edge->IntersectionTest(structure.currentRay, t)) { if (t < minnTime) { minnTime = t; minnEdge = edge; } } } } } void DirectionalLightCalculator::performOneScan(const std::vector<KeyPointTmp>& sweep, SweepStructure& structure, glm::vec2 sweepCenter, int start, int end) { int sz = sweep.size(); auto currentVertex = sweep[start % sz].Vertex; structure.currentRay = { sweepCenter, currentVertex->GetWorldPos() - sweepCenter }; float minnTime = std::numeric_limits<float>::infinity(); PEdge minnEdge = nullptr; findNearestWall(structure, minnTime, minnEdge); assert(minnEdge); float oldMinTime = minnTime; int oldMinSeg = minnEdge->Id; std::map<int, int> testSegments{}; for (int j = start; j <= end; j++) { auto vertex = sweep[j % sz].Vertex; for (const auto& conj : vertex->ConjunctionInfo) { if (conj.IsEnd) { testSegments[conj.Edge->Id]--; } else { testSegments[conj.Edge->Id]++; } } } for (auto& pair : testSegments) { if (pair.second < 0) { eraseEdge(structure, &_edges[pair.first], sweepCenter); } } for (auto& pair : testSegments) { if (pair.second > 0) { insertNewEdge(structure, &_edges[pair.first], sweepCenter); } } findNearestWall(structure, minnTime, minnEdge); assert(minnEdge); if (end == sz || oldMinSeg != minnEdge->Id) { auto lastPos = structure.currentRay.Eval(oldMinTime); auto newPos = structure.currentRay.Eval(minnTime); if (_shadowTriangles.size() == 36 - 8) { if (true); } //if (std::abs(cross2(structure.lastKeyPosition - sweepCenter, lastPos - sweepCenter)) > 1.f) //{ _shadowTriangles.push_back(Triangle(structure.lastKeyPosition, sweepCenter, lastPos)); //} structure.lastKeyPosition = newPos; } } void DirectionalLightCalculator::insertNewEdge(SweepStructure& structure, PEdge edge, glm::vec2 sweepCenter) { if (edge->IsBorder()) { structure.borderEdges.push_back(edge); } else { #ifdef _DEBUG { // test if the wrong edge existed in the state for (auto& a : *structure.EdgeSet) { if (a->Id == edge->Id) { assert(false); } } } #endif // DEBUG auto p = structure.EdgeSet->find(edge); assert(p == structure.EdgeSet->end()); //structure.activeEdges[edge->Id] = true; structure.EdgeSet->insert(edge); #ifdef _DEBUG { // test if added the wrong edge bool exist = false; for (auto& a : *structure.EdgeSet) { if (a->Id == edge->Id) { exist = true; } } assert(exist); } #endif // DEBUG } } void DirectionalLightCalculator::eraseEdge(SweepStructure& structure, PEdge edge, glm::vec2 sweepCenter) { if (edge->IsBorder()) { auto p = std::find(structure.borderEdges.begin(), structure.borderEdges.end(), edge); structure.borderEdges.erase(p); } else { //assert(structure.activeEdges[edge->Id]); //structure.activeEdges[edge->Id] = false; auto p = structure.EdgeSet->find(edge); assert(p != structure.EdgeSet->end()); structure.EdgeSet->erase(p); #ifdef _DEBUG // test if deleted the wrong edge for (auto& a : *structure.EdgeSet) { if (a->Id == edge->Id) { assert(false); } } #endif // DEBUG auto p2 = structure.EdgeSet->find(edge); assert(p2 == structure.EdgeSet->end()); } }
25.016854
112
0.679317
[ "render", "vector" ]
400e0c23839a1f1f4a240baf6d5f500d4980a5d6
6,943
hpp
C++
third_party/omr/compiler/optimizer/VirtualGuardCoalescer.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/compiler/optimizer/VirtualGuardCoalescer.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/compiler/optimizer/VirtualGuardCoalescer.hpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2000, 2019 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at http://eclipse.org/legal/epl-2.0 * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception [1] and GNU General Public * License, version 2 with the OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #ifndef VIRTUALGUARDCOALESCER_HPP #define VIRTUALGUARDCOALESCER_HPP #include <stddef.h> #include <stdint.h> #include "compile/Method.hpp" #include "env/TRMemory.hpp" #include "il/Block.hpp" #include "il/Node.hpp" #include "il/Node_inlines.hpp" #include "il/TreeTop.hpp" #include "il/TreeTop_inlines.hpp" #include "infra/BitVector.hpp" #include "infra/List.hpp" #include "optimizer/Optimization.hpp" #include "optimizer/OptimizationManager.hpp" #define MALFORMED_GUARD MAX_SCOUNT class TR_ValueNumberInfo; namespace TR { class CFG; } namespace TR { class Compilation; } namespace TR { class SymbolReference; } struct TR_SymNodePair { TR::SymbolReference *_symRef; TR::Node *_node; }; class TR_VirtualGuardTailSplitter : public TR::Optimization { public: TR_VirtualGuardTailSplitter(TR::OptimizationManager *manager); static TR::Optimization *create(TR::OptimizationManager *manager) { return new (manager->allocator()) TR_VirtualGuardTailSplitter(manager); } virtual int32_t perform(); virtual const char * optDetailString() const throw(); private: class VGInfo { public: TR_ALLOC(TR_Memory::VirtualGuardTailSplitter) VGInfo(TR::Block *branch, TR::Block *call, TR::Block *inlined, TR::Block *merge, VGInfo *parent) : _branch(branch), _call(call), _inlined(inlined), _merge(merge), _referenceCount(0), _valid(true) { if (!parent) _parent = this; else { _parent = parent; parent->addChild(this); } } VGInfo *getRoot() { return _parent == this? this : _parent->getRoot(); } bool stillExists() { return _valid; } void markRemoved(); bool isRoot() { return _parent == this; } bool isLeaf() { return _referenceCount == 0; } bool isNonTrivialRoot() { return _parent == this && _referenceCount != 0; } bool isNonTrivialLeaf() { return _parent != this && _referenceCount == 0; } // a leaf that is not a root void addChild(VGInfo *) { ++_referenceCount; } void removeChild(VGInfo *) { --_referenceCount; } bool isExceptionSafe() { return _call->getExceptionSuccessors().empty(); } TR::Block *getBranchBlock() { return _branch; } TR::Block *getMergeBlock() { return _merge; } TR::Block *getCallBlock() { return _call; } TR::Block *getFirstInlinedBlock() { return _inlined; } VGInfo *getParent() { return _parent; } scount_t getIndex() { return _branch->getLastRealTreeTop()->getNode()->getLocalIndex(); } uint32_t getNumber() { return _branch->getNumber(); } private: VGInfo *_parent; TR::Block *_branch; TR::Block *_call; TR::Block *_inlined; TR::Block *_merge; uint8_t _referenceCount; bool _valid; }; void initializeDataStructures(); void splitLinear(TR::Block *start, TR::Block *end); void remergeGuard(TR_BlockCloner&, VGInfo *); bool isBlockInInlinedCallTreeOf(VGInfo *, TR::Block *block); VGInfo *recognizeVirtualGuard(TR::Block *, VGInfo *parent); VGInfo *getVirtualGuardInfo(TR::Block *); TR::Block *lookAheadAndSplit(VGInfo *info, List<TR::Block> *stack); void transformLinear(TR::Block *first, TR::Block *last); bool isKill(TR::Block *); bool isKill(TR::Node *); TR::Node *getFirstCallNode(TR::Block *block); TR::CFG *_cfg; // Virtual Guard Information Table and Accessor Methods // uint32_t _numGuards; vcount_t _visitCount; VGInfo *getGuard(uint32_t index) { return index == MALFORMED_GUARD ? NULL : _table[index]; } VGInfo *getGuard(TR::Block *branch) { return getGuard(branch->getLastRealTreeTop()->getNode()); } VGInfo *getGuard(TR::Node *branch) { return getGuard(branch->getLocalIndex()); } void putGuard(uint32_t index, VGInfo *info); VGInfo **_table; bool _splitDone; }; class TR_InnerPreexistence : public TR::Optimization { public: TR_InnerPreexistence(TR::OptimizationManager *manager); static TR::Optimization *create(TR::OptimizationManager *manager) { return new (manager->allocator()) TR_InnerPreexistence(manager); } virtual int32_t perform(); virtual const char * optDetailString() const throw(); class GuardInfo { public: TR_ALLOC(TR_Memory::VirtualGuardTailSplitter) GuardInfo(TR::Compilation *, TR::Block *block, GuardInfo *parent, TR_ValueNumberInfo *vnInfo, uint32_t numInlinedSites); TR::Block *getBlock() { return _block; } TR::Node *getGuardNode() { return _block->getLastRealTreeTop()->getNode(); } TR::Node *getCallNode () { return getGuardNode()->getVirtualCallNodeForGuard(); } GuardInfo *getParent() { return _parent; } TR_BitVector *getArgVNs() { return _argVNs; } int32_t getThisVN() { return _thisVN; } void setVisible(uint32_t inner) { _innerSubTree->set(inner); } bool isVisible (uint32_t inner) { return _innerSubTree->isSet(inner); } TR_BitVector *getVisibleGuards() { return _innerSubTree; } void setHasBeenDevirtualized() { _hasBeenDevirtualized = true; } bool getHasBeenDevirtualized() { return _hasBeenDevirtualized; } private: GuardInfo *_parent; TR::Block *_block; uint32_t _thisVN; TR_BitVector *_argVNs; bool _hasBeenDevirtualized; TR_BitVector *_innerSubTree; }; private: int32_t initialize(); void transform(); void devirtualize(GuardInfo *guard); int32_t _numInlinedSites; GuardInfo **_guardTable; TR_ValueNumberInfo *_vnInfo; }; #endif
33.703883
135
0.656489
[ "transform" ]
401a5e73d8638ca2da54df9a18f881f0d8880ff1
109,109
cc
C++
driver/utility.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
driver/utility.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
driver/utility.cc
realnickel/mysql-connector-odbc
cd3aad7a64a2c6bf58c6b04e0a63026bbacc8189
[ "Artistic-1.0-Perl" ]
null
null
null
// Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License, version 2.0, as // published by the Free Software Foundation. // // This program is also distributed with certain software (including // but not limited to OpenSSL) that is licensed under separate terms, // as designated in a particular file or component or in included license // documentation. The authors of MySQL hereby grant you an // additional permission to link the program and your derivative works // with the separately licensed software that they have included with // MySQL. // // Without limiting anything contained in the foregoing, this file, // which is part of <MySQL Product>, is also subject to the // Universal FOSS Exception, version 1.0, a copy of which can be found at // http://oss.oracle.com/licenses/universal-foss-exception. // // 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, version 2.0, for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA /** @file utility.c @brief Utility functions */ #include "driver.h" #include "errmsg.h" #include <ctype.h> #define DATETIME_DIGITS 14 const SQLULEN sql_select_unlimited= (SQLULEN)-1; /** Execute a SQL statement with setting sql_select_limit for each execution as SQL_ATTR_MAX_ROWS applies to all result sets on the statement and not connection. @param[in] dbc The database connection @param[in] query The query to execute @param[in] query_length The length of query to execute @param[in] req_lock The flag if dbc->lock thread lock should be used when executing a query */ SQLRETURN exec_stmt_query(STMT *stmt, const char *query, SQLULEN query_length, my_bool req_lock) { SQLRETURN rc; if(!SQL_SUCCEEDED(rc= set_sql_select_limit(stmt->dbc, stmt->stmt_options.max_rows, req_lock))) { /* if setting sql_select_limit fails, the query will probably fail anyway too */ return rc; } return odbc_stmt(stmt->dbc, query, query_length, req_lock); } /** /** Execute a SQL statement. @param[in] dbc The database connection @param[in] query The query to execute @param[in] req_lock The flag if dbc->lock thread lock should be used when executing a query */ SQLRETURN odbc_stmt(DBC *dbc, const char *query, SQLULEN query_length, my_bool req_lock) { SQLRETURN result= SQL_SUCCESS; if (req_lock) { myodbc_mutex_lock(&dbc->lock); } if (query_length == SQL_NTS) { query_length= strlen(query); } if ( check_if_server_is_alive(dbc) || mysql_real_query(&dbc->mysql, query, query_length) ) { result= set_conn_error(dbc,MYERR_S1000,mysql_error(&dbc->mysql), mysql_errno(&dbc->mysql)); } if (req_lock) { myodbc_mutex_unlock(&dbc->lock); } return result; } /** Link a list of fields to the current statement result. @todo This is a terrible idea. We need to purge this. @param[in] stmt The statement to modify @param[in] fields The fields to attach to the statement @param[in] field_count The number of fields */ void myodbc_link_fields(STMT *stmt, MYSQL_FIELD *fields, uint field_count) { MYSQL_RES *result; myodbc_mutex_lock(&stmt->dbc->lock); result= stmt->result; result->fields= fields; result->field_count= field_count; result->current_field= 0; fix_result_types(stmt); myodbc_mutex_unlock(&stmt->dbc->lock); } /** Fills STMT's lengths array for given row. Makes use of myodbc_link_fields a bit less terrible. @param[in,out] stmt The statement to modify @param[in] fix_rules Describes how to calculate lengths. For each element value N > 0 - length is taken of field #N from original results (counting from 1) N <=0 - constant length (-N) @param[in] row Row for which to fix lengths @param[in] field_count The number of fields */ void fix_row_lengths(STMT *stmt, const long* fix_rules, uint row, uint field_count) { unsigned long* orig_lengths, *row_lengths; uint i; if (stmt->lengths == NULL) return; row_lengths= stmt->lengths + row*field_count; orig_lengths= mysql_fetch_lengths(stmt->result); for (i= 0; i < field_count; ++i) { if (fix_rules[i] > 0) row_lengths[i]= orig_lengths[fix_rules[i] - 1]; else row_lengths[i]= -fix_rules[i]; } } /** Figure out the ODBC result types for each column in the result set. @param[in] stmt The statement with result types to be fixed. */ void fix_result_types(STMT *stmt) { uint i; MYSQL_RES *result= stmt->result; DESCREC *irrec; MYSQL_FIELD *field; int capint32= stmt->dbc->ds->limit_column_size ? 1 : 0; stmt->state= ST_EXECUTED; /* Mark set found */ /* Populate the IRD records */ for (i= 0; i < field_count(stmt); ++i) { irrec= desc_get_rec(stmt->ird, i, TRUE); /* TODO function for this */ field= result->fields + i; irrec->row.field= field; irrec->type= get_sql_data_type(stmt, field, NULL); irrec->concise_type= get_sql_data_type(stmt, field, (char *)irrec->row.type_name); switch (irrec->concise_type) { case SQL_DATE: case SQL_TYPE_DATE: case SQL_TIME: case SQL_TYPE_TIME: case SQL_TIMESTAMP: case SQL_TYPE_TIMESTAMP: irrec->type= SQL_DATETIME; break; default: irrec->type= irrec->concise_type; break; } irrec->datetime_interval_code= get_dticode_from_concise_type(irrec->concise_type); irrec->type_name= (SQLCHAR *) irrec->row.type_name; irrec->length= get_column_size(stmt, field); /* prevent overflowing of result when ADO multiplies the length by sizeof(SQLWCHAR) */ if (capint32 && irrec->length == INT_MAX32 && irrec->concise_type == SQL_WLONGVARCHAR) irrec->length /= sizeof(SQL_WCHAR); irrec->octet_length= get_transfer_octet_length(stmt, field); irrec->display_size= get_display_size(stmt, field); /* According ODBC specs(http://msdn.microsoft.com/en-us/library/ms713558%28v=VS.85%29.aspx) "SQL_DESC_OCTET_LENGTH ... For variable-length character or binary types, this is the maximum length in bytes. This value does not include the null terminator" Thus there is no need to add 1 to octet_length for char types */ irrec->precision= 0; /* Set precision for all non-char/blob types */ switch (irrec->type) { case SQL_BINARY: case SQL_BIT: case SQL_CHAR: case SQL_WCHAR: case SQL_VARBINARY: case SQL_VARCHAR: case SQL_WVARCHAR: case SQL_LONGVARBINARY: case SQL_LONGVARCHAR: case SQL_WLONGVARCHAR: break; default: irrec->precision= (SQLSMALLINT) irrec->length; break; } irrec->scale= myodbc_max(0, get_decimal_digits(stmt, field)); if ((field->flags & NOT_NULL_FLAG) && !(field->type == MYSQL_TYPE_TIMESTAMP) && !(field->flags & AUTO_INCREMENT_FLAG)) irrec->nullable= SQL_NO_NULLS; else irrec->nullable= SQL_NULLABLE; irrec->table_name= (SQLCHAR *)field->table; irrec->name= (SQLCHAR *)field->name; irrec->label= (SQLCHAR *)field->name; if (field->flags & AUTO_INCREMENT_FLAG) irrec->auto_unique_value= SQL_TRUE; else irrec->auto_unique_value= SQL_FALSE; /* We need support from server, when aliasing is there */ irrec->base_column_name= (SQLCHAR *)field->org_name; irrec->base_table_name= (SQLCHAR *)field->org_table; if (field->flags & BINARY_FLAG) /* TODO this doesn't cut it anymore */ irrec->case_sensitive= SQL_TRUE; else irrec->case_sensitive= SQL_FALSE; if (field->db && *field->db) { irrec->catalog_name= (SQLCHAR *)field->db; } else { irrec->catalog_name= (SQLCHAR *)(stmt->dbc->database ? stmt->dbc->database : ""); } irrec->fixed_prec_scale= SQL_FALSE; switch (field->type) { case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_BLOB: case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_STRING: if (field->charsetnr == BINARY_CHARSET_NUMBER) { irrec->literal_prefix= (SQLCHAR *) "0x"; irrec->literal_suffix= (SQLCHAR *) ""; break; } /* FALLTHROUGH */ case MYSQL_TYPE_DATE: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_TIME: case MYSQL_TYPE_YEAR: irrec->literal_prefix= (SQLCHAR *) "'"; irrec->literal_suffix= (SQLCHAR *) "'"; break; default: irrec->literal_prefix= (SQLCHAR *) ""; irrec->literal_suffix= (SQLCHAR *) ""; } switch (field->type) { case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_TINY: case MYSQL_TYPE_DECIMAL: irrec->num_prec_radix= 10; break; /* overwrite irrec->precision set above */ case MYSQL_TYPE_FLOAT: irrec->num_prec_radix= 2; irrec->precision= 23; break; case MYSQL_TYPE_DOUBLE: irrec->num_prec_radix= 2; irrec->precision= 53; break; default: irrec->num_prec_radix= 0; break; } irrec->schema_name= (SQLCHAR *) ""; /* We limit BLOB/TEXT types to SQL_PRED_CHAR due an oversight in ADO causing problems with updatable cursors. */ switch (irrec->concise_type) { case SQL_LONGVARBINARY: case SQL_LONGVARCHAR: case SQL_WLONGVARCHAR: irrec->searchable= SQL_PRED_CHAR; break; default: irrec->searchable= SQL_SEARCHABLE; break; } irrec->unnamed= SQL_NAMED; if (field->flags & UNSIGNED_FLAG) irrec->is_unsigned= SQL_TRUE; else irrec->is_unsigned= SQL_FALSE; if (field->table && *field->table) irrec->updatable= SQL_ATTR_READWRITE_UNKNOWN; else irrec->updatable= SQL_ATTR_READONLY; } stmt->ird->count= result->field_count; } /** Change a string with a length to a NUL-terminated string. @param[in,out] to A buffer to write the string into, which must be at at least length + 1 bytes long. @param[in] from A pointer to the beginning of the source string. @param[in] length The length of the string, or SQL_NTS if it is already NUL-terminated. @return A pointer to a NUL-terminated string. */ char *fix_str(char *to, const char *from, int length) { if ( !from ) return ""; if ( length == SQL_NTS ) return (char *)from; strmake(to,from,length); return to; } /* @type : myodbc internal @purpose : duplicate the string */ char *dupp_str(char *from,int length) { char *to; if ( !from ) return myodbc_strdup("",MYF(MY_WME)); if ( length == SQL_NTS ) length= strlen(from); if ( (to= (char*)myodbc_malloc(length+1,MYF(MY_WME))) ) { memcpy(to,from,length); to[length]= 0; } return to; } /* Copy a field to a byte string. @param[in] stmt Pointer to statement @param[out] result Buffer for result @param[in] result_bytes Size of result buffer (in bytes) @param[out] avail_bytes Pointer to buffer for storing number of bytes available as result @param[in] field Field being stored @param[in] src Source data for result @param[in] src_bytes Length of source data (in bytes) @return Standard ODBC result code */ SQLRETURN copy_binary_result(STMT *stmt, SQLCHAR *result, SQLLEN result_bytes, SQLLEN *avail_bytes, MYSQL_FIELD *field __attribute__((unused)), char *src, unsigned long src_bytes) { SQLRETURN rc= SQL_SUCCESS; ulong copy_bytes; if (!result_bytes) result= 0; /* Don't copy anything! */ /* Apply max length to source data, if one was specified. */ if (stmt->stmt_options.max_length && src_bytes > stmt->stmt_options.max_length) src_bytes= stmt->stmt_options.max_length; /* Initialize the source offset */ if (!stmt->getdata.source) stmt->getdata.source= src; else { src_bytes-= stmt->getdata.source - src; src= stmt->getdata.source; /* If we've already retrieved everything, return SQL_NO_DATA_FOUND */ if (src_bytes == 0) return SQL_NO_DATA_FOUND; } copy_bytes= myodbc_min((unsigned long)result_bytes, src_bytes); if (result && stmt->stmt_options.retrieve_data) memcpy(result, src, copy_bytes); if (avail_bytes && stmt->stmt_options.retrieve_data) *avail_bytes= src_bytes; stmt->getdata.source+= copy_bytes; if (src_bytes > (unsigned long)result_bytes) { set_stmt_error(stmt, "01004", NULL, 0); rc= SQL_SUCCESS_WITH_INFO; } return rc; } /* Copy a field to an ANSI result string. @param[in] stmt Pointer to statement @param[out] result Buffer for result @param[in] result_bytes Size of result buffer (in bytes) @param[out] avail_bytes Pointer to buffer for storing number of bytes available as result @param[in] field Field being stored @param[in] src Source data for result @param[in] src_bytes Length of source data (in bytes) @return Standard ODBC result code */ SQLRETURN copy_ansi_result(STMT *stmt, SQLCHAR *result, SQLLEN result_bytes, SQLLEN *avail_bytes, MYSQL_FIELD *field, char *src, unsigned long src_bytes) { SQLRETURN rc= SQL_SUCCESS; char *src_end; SQLCHAR *result_end; ulong used_bytes= 0, used_chars= 0, error_count= 0; my_bool convert_binary= (field->charsetnr == BINARY_CHARSET_NUMBER ? 1 : 0) && (field->org_table_length == 0 ? 1 : 0) && stmt->dbc->ds->handle_binary_as_char; CHARSET_INFO *to_cs= stmt->dbc->ansi_charset_info, *from_cs= get_charset(field->charsetnr && (!convert_binary) ? field->charsetnr : UTF8_CHARSET_NUMBER, MYF(0)); if (!from_cs) return set_stmt_error(stmt, "07006", "Source character set not " "supported by client", 0); if (!result_bytes) result= 0; /* Don't copy anything! */ /* If we don't have to do any charset conversion, we can just use copy_binary_result() and NUL-terminate the buffer here. */ if (to_cs->number == from_cs->number) { SQLLEN bytes; if (!avail_bytes) avail_bytes= &bytes; if (!result_bytes && !stmt->getdata.source) { *avail_bytes= src_bytes; set_stmt_error(stmt, "01004", NULL, 0); return SQL_SUCCESS_WITH_INFO; } if (result_bytes) --result_bytes; rc= copy_binary_result(stmt, result, result_bytes, avail_bytes, field, src, src_bytes); if (SQL_SUCCEEDED(rc) && result && stmt->stmt_options.retrieve_data) result[myodbc_min(*avail_bytes, result_bytes)]= '\0'; return rc; } result_end= result + result_bytes - 1; /* Handle when result_bytes is 1 -- we have room for the NUL termination, but nothing else. */ if (result == result_end) { if (stmt->stmt_options.retrieve_data) *result= '\0'; result= 0; } /* Apply max length to source data, if one was specified. */ if (stmt->stmt_options.max_length && src_bytes > stmt->stmt_options.max_length) src_bytes= stmt->stmt_options.max_length; src_end= src + src_bytes; /* Initialize the source offset */ if (!stmt->getdata.source) stmt->getdata.source= src; else src= stmt->getdata.source; /* If we've already retrieved everything, return SQL_NO_DATA_FOUND */ if (stmt->getdata.dst_bytes != (ulong)~0L && stmt->getdata.dst_offset >= stmt->getdata.dst_bytes) return SQL_NO_DATA_FOUND; /* If we have leftover bytes from an earlier character conversion, copy as much as we can into place. */ if (stmt->getdata.latest_bytes) { int new_bytes= myodbc_min(stmt->getdata.latest_bytes - stmt->getdata.latest_used, result_end - result); if (stmt->stmt_options.retrieve_data) memcpy(result, stmt->getdata.latest + stmt->getdata.latest_used, new_bytes); if (new_bytes + stmt->getdata.latest_used == stmt->getdata.latest_bytes) stmt->getdata.latest_bytes= 0; result+= new_bytes; if (result == result_end) { if (stmt->stmt_options.retrieve_data) *result= '\0'; result= NULL; } used_bytes+= new_bytes; stmt->getdata.latest_used+= new_bytes; } while (src < src_end) { /* Find the conversion functions. */ auto mb_wc = from_cs->cset->mb_wc; auto wc_mb = to_cs->cset->wc_mb; my_wc_t wc; uchar dummy[7]; /* Longer than any single character in our charsets. */ int to_cnvres; int cnvres= (*mb_wc)(from_cs, &wc, (uchar *)src, (uchar *)src_end); if (cnvres == MY_CS_ILSEQ) { ++error_count; cnvres= 1; wc= '?'; } else if (cnvres < 0 && cnvres > MY_CS_TOOSMALL) { ++error_count; cnvres= abs(cnvres); wc= '?'; } else if (cnvres < 0) return set_stmt_error(stmt, "HY000", "Unknown failure when converting character " "from server character set.", 0); convert_to_out: /* We always convert into a temporary buffer, so we can properly handle characters that are going to get split across requests. */ if (stmt->stmt_options.retrieve_data) { to_cnvres= (*wc_mb)(to_cs, wc, result ? result : dummy, (result ? result_end : dummy + sizeof(dummy))); } else { // If not copying data then pretend all went as planned to_cnvres= 1; } if (to_cnvres > 0) { used_chars+= 1; used_bytes+= to_cnvres; if (result) result+= to_cnvres; src+= cnvres; if (result && result == result_end) { if (stmt->getdata.dst_bytes != (ulong)~0L) { stmt->getdata.source+= cnvres; break; } if (stmt->stmt_options.retrieve_data) *result= '\0'; result= NULL; } else if (!result) continue; stmt->getdata.source+= cnvres; } else if (result && to_cnvres <= MY_CS_TOOSMALL) { /* If we didn't have enough room for the character, we convert into stmt->getdata.latest and copy what we can. The next call to SQLGetData() will then copy what it can to the next buffer. */ stmt->getdata.latest_bytes= (*wc_mb)(to_cs, wc, stmt->getdata.latest, stmt->getdata.latest + sizeof(stmt->getdata.latest)); stmt->getdata.latest_used= myodbc_min(stmt->getdata.latest_bytes, result_end - result); memcpy(result, stmt->getdata.latest, stmt->getdata.latest_used); result+= stmt->getdata.latest_used; if (stmt->stmt_options.retrieve_data) *result= '\0'; result= NULL; used_chars+= 1; used_bytes+= stmt->getdata.latest_bytes; src+= stmt->getdata.latest_bytes; stmt->getdata.source+= stmt->getdata.latest_bytes; } else if (stmt->getdata.latest_bytes == MY_CS_ILUNI && wc != '?') { ++error_count; wc= '?'; goto convert_to_out; } else return set_stmt_error(stmt, "HY000", "Unknown failure when converting character " "to result character set.", 0); } if (result && stmt->stmt_options.retrieve_data) *result= 0; if (result_bytes && stmt->getdata.dst_bytes == (ulong)~0L) { stmt->getdata.dst_bytes= used_bytes; stmt->getdata.dst_offset= 0; } if (avail_bytes && stmt->stmt_options.retrieve_data) { if (stmt->getdata.dst_bytes != (ulong)~0L) *avail_bytes= stmt->getdata.dst_bytes - stmt->getdata.dst_offset; else *avail_bytes= used_bytes; } stmt->getdata.dst_offset+= myodbc_min((ulong)(result_bytes ? result_bytes - 1 : 0), used_bytes); /* Did we truncate the data? */ if (!result_bytes || stmt->getdata.dst_bytes > stmt->getdata.dst_offset) { set_stmt_error(stmt, "01004", NULL, 0); rc= SQL_SUCCESS_WITH_INFO; } /* Did we encounter any character conversion problems? */ if (error_count) { set_stmt_error(stmt, "22018", NULL, 0); rc= SQL_SUCCESS_WITH_INFO; } return rc; } /** Copy a result from the server into a buffer as a SQL_C_WCHAR. @param[in] stmt Pointer to statement @param[out] result Buffer for result @param[in] result_len Size of result buffer (in characters) @param[out] avail_bytes Pointer to buffer for storing amount of data available before this call @param[in] field Field being stored @param[in] src Source data for result @param[in] src_bytes Length of source data (in bytes) @return Standard ODBC result code */ SQLRETURN copy_wchar_result(STMT *stmt, SQLWCHAR *result, SQLINTEGER result_len, SQLLEN *avail_bytes, MYSQL_FIELD *field, char *src, long src_bytes) { SQLRETURN rc= SQL_SUCCESS; char *src_end; SQLWCHAR *result_end; ulong used_chars= 0, error_count= 0; CHARSET_INFO *from_cs= get_charset(field->charsetnr ? field->charsetnr : UTF8_CHARSET_NUMBER, MYF(0)); if (!from_cs) return set_stmt_error(stmt, "07006", "Source character set not " "supported by client", 0); if (!result_len) result= NULL; /* Don't copy anything! */ result_end= result + result_len - 1; if (result == result_end) { *result= 0; result= 0; } /* Apply max length to source data, if one was specified. */ if (stmt->stmt_options.max_length && (ulong)src_bytes > stmt->stmt_options.max_length) src_bytes= stmt->stmt_options.max_length; src_end= src + src_bytes; /* Initialize the source data */ if (!stmt->getdata.source) stmt->getdata.source= src; else src= stmt->getdata.source; /* If we've already retrieved everything, return SQL_NO_DATA_FOUND */ if (stmt->getdata.dst_bytes != (ulong)~0L && stmt->getdata.dst_offset >= stmt->getdata.dst_bytes) return SQL_NO_DATA_FOUND; /* We may have a leftover char from the last call. */ if (stmt->getdata.latest_bytes) { if (stmt->stmt_options.retrieve_data) memcpy(result, stmt->getdata.latest, sizeof(SQLWCHAR)); ++result; if (result == result_end) { if (stmt->stmt_options.retrieve_data) *result= 0; result= NULL; } used_chars+= 1; stmt->getdata.latest_bytes= 0; } while (src < src_end) { /* Find the conversion functions. */ auto mb_wc = from_cs->cset->mb_wc; auto wc_mb = utf8_charset_info->cset->wc_mb; my_wc_t wc; uchar u8[5]; /* Max length of utf-8 string we'll see. */ SQLWCHAR dummy[2]; /* If SQLWCHAR is UTF-16, we may need two chars. */ int to_cnvres; int cnvres= (*mb_wc)(from_cs, &wc, (uchar *)src, (uchar *)src_end); if (cnvres == MY_CS_ILSEQ) { ++error_count; cnvres= 1; wc= '?'; } else if (cnvres < 0 && cnvres > MY_CS_TOOSMALL) { ++error_count; cnvres= abs(cnvres); wc= '?'; } else if (cnvres < 0) return set_stmt_error(stmt, "HY000", "Unknown failure when converting character " "from server character set.", 0); convert_to_out: /* We always convert into a temporary buffer, so we can properly handle characters that are going to get split across requests. */ to_cnvres= (*wc_mb)(utf8_charset_info, wc, u8, u8 + sizeof(u8)); if (to_cnvres > 0) { u8[to_cnvres]= '\0'; src+= cnvres; if (sizeof(SQLWCHAR) == 4) { utf8toutf32(u8, (UTF32 *)(result ? result : dummy)); if (result) ++result; used_chars+= 1; } else { UTF32 u32; UTF16 out[2]; int chars; utf8toutf32(u8, &u32); chars= utf32toutf16(u32, (UTF16 *)out); if (result) { if (stmt->stmt_options.retrieve_data) *result= out[0]; result++; } used_chars+= chars; if (chars > 1 && result && result != result_end) { if (stmt->stmt_options.retrieve_data) *result= out[1]; result++; } else if (chars > 1 && result) { *((SQLWCHAR *)stmt->getdata.latest)= out[1]; stmt->getdata.latest_bytes= 2; stmt->getdata.latest_used= 0; if (stmt->stmt_options.retrieve_data) *result= 0; result= NULL; if (stmt->getdata.dst_bytes != (ulong)~0L) { stmt->getdata.source+= cnvres; break; } } else if (chars > 1) continue; } if (result) stmt->getdata.source+= cnvres; if (result && result == result_end) { if (stmt->stmt_options.retrieve_data) *result= 0; result= NULL; } } else if (stmt->getdata.latest_bytes == MY_CS_ILUNI && wc != '?') { ++error_count; wc= '?'; goto convert_to_out; } else return set_stmt_error(stmt, "HY000", "Unknown failure when converting character " "to result character set.", 0); } if (result && stmt->stmt_options.retrieve_data) *result= 0; if (result_len && stmt->getdata.dst_bytes == (ulong)~0L) { stmt->getdata.dst_bytes= used_chars * sizeof(SQLWCHAR); stmt->getdata.dst_offset= 0; } if (avail_bytes && stmt->stmt_options.retrieve_data) { if (result_len) *avail_bytes= stmt->getdata.dst_bytes - stmt->getdata.dst_offset; else *avail_bytes= used_chars * sizeof(SQLWCHAR); } stmt->getdata.dst_offset+= myodbc_min((ulong)(result_len ? result_len - 1 : 0), used_chars) * sizeof(SQLWCHAR); /* Did we truncate the data? */ if (!result_len || stmt->getdata.dst_bytes > stmt->getdata.dst_offset) { set_stmt_error(stmt, "01004", NULL, 0); rc= SQL_SUCCESS_WITH_INFO; } /* Did we encounter any character conversion problems? */ if (error_count) { set_stmt_error(stmt, "22018", NULL, 0); rc= SQL_SUCCESS_WITH_INFO; } return rc; } /* @type : myodbc internal @purpose : is used when converting a binary string to a SQL_C_CHAR */ SQLRETURN copy_binhex_result(STMT *stmt, SQLCHAR *rgbValue, SQLINTEGER cbValueMax, SQLLEN *pcbValue, MYSQL_FIELD *field __attribute__((unused)), char *src, ulong src_length) { /** @todo padding of BINARY */ char *dst= (char*) rgbValue; ulong length; ulong max_length= stmt->stmt_options.max_length; ulong *offset= &stmt->getdata.src_offset; #if MYSQL_VERSION_ID >= 40100 char NEAR _dig_vec[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; #endif if ( !cbValueMax ) dst= 0; /* Don't copy anything! */ if ( max_length ) /* If limit on char lengths */ { set_if_smaller(cbValueMax,(long) max_length+1); set_if_smaller(src_length,(max_length+1)/2); } if ( *offset == (ulong) ~0L ) *offset= 0; /* First call */ else if ( *offset >= src_length ) return SQL_NO_DATA_FOUND; src+= *offset; src_length-= *offset; length= cbValueMax ? (ulong)(cbValueMax-1)/2 : 0; length= myodbc_min(src_length,length); (*offset)+= length; /* Fix for next call */ if (pcbValue && stmt->stmt_options.retrieve_data) *pcbValue= src_length*2; if ( dst && stmt->stmt_options.retrieve_data ) /* Bind allows null pointers */ { ulong i; for ( i= 0 ; i < length ; ++i ) { *dst++= _dig_vec[(uchar) *src >> 4]; *dst++= _dig_vec[(uchar) *src++ & 15]; } *dst= 0; } if ( (ulong) cbValueMax > length*2 ) return SQL_SUCCESS; set_stmt_error(stmt, "01004", NULL, 0); return SQL_SUCCESS_WITH_INFO; } /** Get the SQL data type and (optionally) type name for a MYSQL_FIELD. @param[in] stmt @param[in] field @param[out] buff @return The SQL data type. */ SQLSMALLINT get_sql_data_type(STMT *stmt, MYSQL_FIELD *field, char *buff) { my_bool field_is_binary= (field->charsetnr == BINARY_CHARSET_NUMBER ? 1 : 0) && ((field->org_table_length > 0 ? 1 : 0) || !stmt->dbc->ds->handle_binary_as_char); switch (field->type) { case MYSQL_TYPE_BIT: if (buff) (void)myodbc_stpmov(buff, "bit"); /* MySQL's BIT type can have more than one bit, in which case we treat it as a BINARY field. */ return (field->length > 1) ? SQL_BINARY : SQL_BIT; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: if (buff) (void)myodbc_stpmov(buff, "decimal"); return SQL_DECIMAL; case MYSQL_TYPE_TINY: /* MYSQL_TYPE_TINY could either be a TINYINT or a single CHAR. */ if (buff) { buff= myodbc_stpmov(buff, (field->flags & NUM_FLAG) ? "tinyint" : "char"); if (field->flags & UNSIGNED_FLAG) (void)myodbc_stpmov(buff, " unsigned"); } return (field->flags & NUM_FLAG) ? SQL_TINYINT : SQL_CHAR; case MYSQL_TYPE_SHORT: if (buff) { buff= myodbc_stpmov(buff, "smallint"); if (field->flags & UNSIGNED_FLAG) (void)myodbc_stpmov(buff, " unsigned"); } return SQL_SMALLINT; case MYSQL_TYPE_INT24: if (buff) { buff= myodbc_stpmov(buff, "mediumint"); if (field->flags & UNSIGNED_FLAG) (void)myodbc_stpmov(buff, " unsigned"); } return SQL_INTEGER; case MYSQL_TYPE_LONG: if (buff) { buff= myodbc_stpmov(buff, "integer"); if (field->flags & UNSIGNED_FLAG) (void)myodbc_stpmov(buff, " unsigned"); } return SQL_INTEGER; case MYSQL_TYPE_LONGLONG: if (buff) { if (stmt->dbc->ds->change_bigint_columns_to_int) buff= myodbc_stpmov(buff, "int"); else buff= myodbc_stpmov(buff, "bigint"); if (field->flags & UNSIGNED_FLAG) (void)myodbc_stpmov(buff, " unsigned"); } if (stmt->dbc->ds->change_bigint_columns_to_int) return SQL_INTEGER; return SQL_BIGINT; case MYSQL_TYPE_FLOAT: if (buff) { buff= myodbc_stpmov(buff, "float"); if (field->flags & UNSIGNED_FLAG) (void)myodbc_stpmov(buff, " unsigned"); } return SQL_REAL; case MYSQL_TYPE_DOUBLE: if (buff) { buff= myodbc_stpmov(buff, "double"); if (field->flags & UNSIGNED_FLAG) (void)myodbc_stpmov(buff, " unsigned"); } return SQL_DOUBLE; case MYSQL_TYPE_NULL: if (buff) (void)myodbc_stpmov(buff, "null"); return SQL_VARCHAR; case MYSQL_TYPE_YEAR: if (buff) (void)myodbc_stpmov(buff, "year"); return SQL_SMALLINT; case MYSQL_TYPE_TIMESTAMP: if (buff) (void)myodbc_stpmov(buff, "timestamp"); if (stmt->dbc->env->odbc_ver == SQL_OV_ODBC3) return SQL_TYPE_TIMESTAMP; return SQL_TIMESTAMP; case MYSQL_TYPE_DATETIME: if (buff) (void)myodbc_stpmov(buff, "datetime"); if (stmt->dbc->env->odbc_ver == SQL_OV_ODBC3) return SQL_TYPE_TIMESTAMP; return SQL_TIMESTAMP; case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_DATE: if (buff) (void)myodbc_stpmov(buff, "date"); if (stmt->dbc->env->odbc_ver == SQL_OV_ODBC3) return SQL_TYPE_DATE; return SQL_DATE; case MYSQL_TYPE_TIME: if (buff) (void)myodbc_stpmov(buff, "time"); if (stmt->dbc->env->odbc_ver == SQL_OV_ODBC3) return SQL_TYPE_TIME; return SQL_TIME; case MYSQL_TYPE_STRING: if (buff) (void)myodbc_stpmov(buff, field_is_binary ? "binary" : "char"); return field_is_binary ? SQL_BINARY : (stmt->dbc->unicode && field->charsetnr != stmt->dbc->ansi_charset_info->number ? SQL_WCHAR : SQL_CHAR); /* MYSQL_TYPE_VARCHAR is never actually sent, this just silences a compiler warning. */ case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_VAR_STRING: if (buff) (void)myodbc_stpmov(buff, field_is_binary ? "varbinary" : "varchar"); return field_is_binary ? SQL_VARBINARY : (stmt->dbc->unicode && field->charsetnr != stmt->dbc->ansi_charset_info->number ? SQL_WVARCHAR : SQL_VARCHAR); case MYSQL_TYPE_TINY_BLOB: if (buff) (void)myodbc_stpmov(buff, field_is_binary ? "tinyblob" : "tinytext"); return field_is_binary ? SQL_LONGVARBINARY : (stmt->dbc->unicode && field->charsetnr != stmt->dbc->ansi_charset_info->number ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR); case MYSQL_TYPE_BLOB: if (buff) { switch(field->length) { case 255: (void)myodbc_stpmov(buff, field_is_binary ? "tinyblob" : "tinytext"); break; case 16777215: (void)myodbc_stpmov(buff, field_is_binary ? "mediumblob" : "mediumtext"); break; case 4294967295UL: (void)myodbc_stpmov(buff, field_is_binary ? "longblob" : "longtext"); break; default: (void)myodbc_stpmov(buff, field_is_binary ? "blob" : "text"); } } return field_is_binary ? SQL_LONGVARBINARY : (stmt->dbc->unicode && field->charsetnr != stmt->dbc->ansi_charset_info->number ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR); case MYSQL_TYPE_MEDIUM_BLOB: if (buff) (void)myodbc_stpmov(buff, field_is_binary ? "mediumblob" : "mediumtext"); return field_is_binary ? SQL_LONGVARBINARY : (stmt->dbc->unicode && field->charsetnr != stmt->dbc->ansi_charset_info->number ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR); case MYSQL_TYPE_LONG_BLOB: if (buff) (void)myodbc_stpmov(buff, field_is_binary ? "longblob" : "longtext"); return field_is_binary ? SQL_LONGVARBINARY : (stmt->dbc->unicode && field->charsetnr != stmt->dbc->ansi_charset_info->number ? SQL_WLONGVARCHAR : SQL_LONGVARCHAR); case MYSQL_TYPE_ENUM: if (buff) (void)myodbc_stpmov(buff, "enum"); return SQL_CHAR; case MYSQL_TYPE_SET: if (buff) (void)myodbc_stpmov(buff, "set"); return SQL_CHAR; case MYSQL_TYPE_GEOMETRY: if (buff) (void)myodbc_stpmov(buff, "geometry"); return SQL_LONGVARBINARY; } if (buff) *buff= '\0'; return SQL_UNKNOWN_TYPE; } void sqlulen_to_str(char *buff, SQLULEN value) { } /** Fill the display size buffer accordingly to size of SQLLEN @param[in,out] buff @param[in] stmt @param[in] field @return void */ SQLLEN fill_display_size_buff(char *buff, STMT *stmt, MYSQL_FIELD *field) { /* See comment for fill_transfer_oct_len_buff()*/ SQLLEN size= get_display_size(stmt, field); sprintf(buff,size == SQL_NO_TOTAL ? "%d" : (sizeof(SQLLEN) == 4 ? "%lu" : "%lld"), size); return size; } /** Fill the transfer octet length buffer accordingly to size of SQLLEN @param[in,out] buff @param[in] stmt @param[in] field @return void */ SQLLEN fill_transfer_oct_len_buff(char *buff, STMT *stmt, MYSQL_FIELD *field) { /* The only possible negative value get_transfer_octet_length can return is SQL_NO_TOTAL But it can return value which is greater that biggest signed integer(%ld). Thus for other values we use %lu. %lld should fit all (currently) possible in mysql values. */ SQLLEN len= get_transfer_octet_length(stmt, field); sprintf(buff, len == SQL_NO_TOTAL ? "%d" : (sizeof(SQLLEN) == 4 ? "%lu" : "%lld"), len ); return len; } /** Fill the column size buffer accordingly to size of SQLULEN @param[in,out] buff @param[in] stmt @param[in] field @return void */ SQLULEN fill_column_size_buff(char *buff, STMT *stmt, MYSQL_FIELD *field) { SQLULEN size= get_column_size(stmt, field); sprintf(buff, (size== SQL_NO_TOTAL ? "%d" : (sizeof(SQLULEN) == 4 ? "%lu" : "%llu")), size); return size; } /** Capping length value if connection option is set */ static SQLLEN cap_length(STMT *stmt, unsigned long real_length) { if (stmt->dbc->ds->limit_column_size != 0 && real_length > INT_MAX32) return INT_MAX32; return real_length; } /** Get the column size (in characters) of a field, as defined at: http://msdn2.microsoft.com/en-us/library/ms711786.aspx @param[in] stmt @param[in] field @return The column size of the field */ SQLULEN get_column_size(STMT *stmt, MYSQL_FIELD *field) { SQLULEN length= field->length; /* Work around a bug in some versions of the server. */ if (field->max_length > field->length) length= field->max_length; length= cap_length(stmt, length); switch (field->type) { case MYSQL_TYPE_TINY: return (field->flags & NUM_FLAG) ? 3 : 1; case MYSQL_TYPE_SHORT: return 5; case MYSQL_TYPE_LONG: return 10; case MYSQL_TYPE_FLOAT: return 7; case MYSQL_TYPE_DOUBLE: return 15; case MYSQL_TYPE_NULL: return 0; case MYSQL_TYPE_LONGLONG: if (stmt->dbc->ds->change_bigint_columns_to_int) return 10; /* same as MYSQL_TYPE_LONG */ else return (field->flags & UNSIGNED_FLAG) ? 20 : 19; case MYSQL_TYPE_INT24: return 8; case MYSQL_TYPE_DATE: return 10; case MYSQL_TYPE_TIME: return 8; case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_NEWDATE: return 19; case MYSQL_TYPE_YEAR: return 4; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: return (length - (!(field->flags & UNSIGNED_FLAG) ? 1: 0) - /* sign? */ (field->decimals ? 1 : 0)); /* decimal point? */ case MYSQL_TYPE_BIT: /* We treat a BIT(n) as a SQL_BIT if n == 1, otherwise we treat it as a SQL_BINARY, so length is (bits + 7) / 8. */ if (length == 1) return 1; return (length + 7) / 8; case MYSQL_TYPE_ENUM: case MYSQL_TYPE_SET: case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_STRING: if (field->charsetnr == BINARY_CHARSET_NUMBER) return length; else { CHARSET_INFO *charset= get_charset(field->charsetnr, MYF(0)); return length / (charset ? charset->mbmaxlen : 1); } case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: case MYSQL_TYPE_GEOMETRY: return length; } return SQL_NO_TOTAL; } /** Get the decimal digits of a field, as defined at: http://msdn2.microsoft.com/en-us/library/ms709314.aspx @param[in] stmt @param[in] field @return The decimal digits, or @c SQL_NO_TOTAL where it makes no sense The function has to return SQLSMALLINT, since it corresponds to SQL_DESC_SCALE or SQL_DESC_PRECISION for some data types. */ SQLSMALLINT get_decimal_digits(STMT *stmt __attribute__((unused)), MYSQL_FIELD *field) { switch (field->type) { case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: return field->decimals; /* All exact numeric types. */ case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: case MYSQL_TYPE_INT24: case MYSQL_TYPE_YEAR: case MYSQL_TYPE_TIME: case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: return 0; /* We treat MYSQL_TYPE_BIT as an exact numeric type only for BIT(1). */ case MYSQL_TYPE_BIT: if (field->length == 1) return 0; default: /* This value is only used in some catalog functions. It's co-erced to zero for all descriptor use. */ return SQL_NO_TOTAL; } } /** Get the transfer octet length of a field, as defined at: http://msdn2.microsoft.com/en-us/library/ms713979.aspx @param[in] stmt @param[in] field @return The transfer octet length */ SQLLEN get_transfer_octet_length(STMT *stmt, MYSQL_FIELD *field) { int capint32= stmt->dbc->ds->limit_column_size ? 1 : 0; SQLLEN length; /* cap at INT_MAX32 due to signed value */ if (field->length > INT_MAX32) length= INT_MAX32; else length= field->length; switch (field->type) { case MYSQL_TYPE_TINY: return 1; case MYSQL_TYPE_SHORT: return 2; case MYSQL_TYPE_INT24: return 3; case MYSQL_TYPE_LONG: return 4; case MYSQL_TYPE_FLOAT: return 4; case MYSQL_TYPE_DOUBLE: return 8; case MYSQL_TYPE_NULL: return 1; case MYSQL_TYPE_LONGLONG: return 20; case MYSQL_TYPE_DATE: return sizeof(SQL_DATE_STRUCT); case MYSQL_TYPE_TIME: return sizeof(SQL_TIME_STRUCT); case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_NEWDATE: return sizeof(SQL_TIMESTAMP_STRUCT); case MYSQL_TYPE_YEAR: return 1; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: return field->length; case MYSQL_TYPE_BIT: /* We treat a BIT(n) as a SQL_BIT if n == 1, otherwise we treat it as a SQL_BINARY, so length is (bits + 7) / 8. field->length has the number of bits. */ return (field->length + 7) / 8; case MYSQL_TYPE_STRING: if (stmt->dbc->ds->pad_char_to_full_length) length= field->max_length; /* FALLTHROUGH */ case MYSQL_TYPE_ENUM: case MYSQL_TYPE_SET: case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: case MYSQL_TYPE_GEOMETRY: if (field->charsetnr != stmt->dbc->ansi_charset_info->number && field->charsetnr != BINARY_CHARSET_NUMBER) length *= stmt->dbc->ansi_charset_info->mbmaxlen; if (capint32 && length > INT_MAX32) length= INT_MAX32; return length; } return SQL_NO_TOTAL; } /** Get the display size of a field, as defined at: http://msdn2.microsoft.com/en-us/library/ms713974.aspx @param[in] stmt @param[in] field @return The display size */ SQLLEN get_display_size(STMT *stmt __attribute__((unused)),MYSQL_FIELD *field) { int capint32= stmt->dbc->ds->limit_column_size ? 1 : 0; CHARSET_INFO *charset= get_charset(field->charsetnr, MYF(0)); unsigned int mbmaxlen= charset ? charset->mbmaxlen : 1; switch (field->type) { case MYSQL_TYPE_TINY: return 3 + (field->flags & UNSIGNED_FLAG ? 1 : 0); case MYSQL_TYPE_SHORT: return 5 + (field->flags & UNSIGNED_FLAG ? 1 : 0); case MYSQL_TYPE_INT24: return 8 + (field->flags & UNSIGNED_FLAG ? 1 : 0); case MYSQL_TYPE_LONG: return 10 + (field->flags & UNSIGNED_FLAG ? 1 : 0); case MYSQL_TYPE_FLOAT: return 14; case MYSQL_TYPE_DOUBLE: return 24; case MYSQL_TYPE_NULL: return 1; case MYSQL_TYPE_LONGLONG: return 20; case MYSQL_TYPE_DATE: return 10; case MYSQL_TYPE_TIME: return 8; case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_NEWDATE: return 19; case MYSQL_TYPE_YEAR: return 4; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: return field->length; case MYSQL_TYPE_BIT: /* We treat a BIT(n) as a SQL_BIT if n == 1, otherwise we treat it as a SQL_BINARY, so display length is (bits + 7) / 8 * 2. field->length has the number of bits. */ if (field->length == 1) return 1; return (field->length + 7) / 8 * 2; case MYSQL_TYPE_ENUM: case MYSQL_TYPE_SET: case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_STRING: case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: case MYSQL_TYPE_BLOB: case MYSQL_TYPE_GEOMETRY: { unsigned long length; if (field->charsetnr == BINARY_CHARSET_NUMBER) length= field->length * 2; else length= field->length / mbmaxlen; if (capint32 && length > INT_MAX32) length= INT_MAX32; return length; } } return SQL_NO_TOTAL; } /* Map the concise type (value or param) to the correct datetime or interval code. See SQLSetDescField()/SQL_DESC_DATETIME_INTERVAL_CODE docs for details. */ SQLSMALLINT get_dticode_from_concise_type(SQLSMALLINT concise_type) { /* figure out SQL_DESC_DATETIME_INTERVAL_CODE from SQL_DESC_CONCISE_TYPE */ switch (concise_type) { case SQL_C_TYPE_DATE: return SQL_CODE_DATE; case SQL_C_TYPE_TIME: return SQL_CODE_TIME; case SQL_C_TIMESTAMP: case SQL_C_TYPE_TIMESTAMP: return SQL_CODE_TIMESTAMP; case SQL_C_INTERVAL_DAY: return SQL_CODE_DAY; case SQL_C_INTERVAL_DAY_TO_HOUR: return SQL_CODE_DAY_TO_HOUR; case SQL_C_INTERVAL_DAY_TO_MINUTE: return SQL_CODE_DAY_TO_MINUTE; case SQL_C_INTERVAL_DAY_TO_SECOND: return SQL_CODE_DAY_TO_SECOND; case SQL_C_INTERVAL_HOUR: return SQL_CODE_HOUR; case SQL_C_INTERVAL_HOUR_TO_MINUTE: return SQL_CODE_HOUR_TO_MINUTE; case SQL_C_INTERVAL_HOUR_TO_SECOND: return SQL_CODE_HOUR_TO_SECOND; case SQL_C_INTERVAL_MINUTE: return SQL_CODE_MINUTE; case SQL_C_INTERVAL_MINUTE_TO_SECOND: return SQL_CODE_MINUTE_TO_SECOND; case SQL_C_INTERVAL_MONTH: return SQL_CODE_MONTH; case SQL_C_INTERVAL_SECOND: return SQL_CODE_SECOND; case SQL_C_INTERVAL_YEAR: return SQL_CODE_YEAR; case SQL_C_INTERVAL_YEAR_TO_MONTH: return SQL_CODE_YEAR_TO_MONTH; default: return 0; } } /* Map the SQL_DESC_DATETIME_INTERVAL_CODE to the SQL_DESC_CONCISE_TYPE for datetime types. Constant returned is valid for both param and value types. */ SQLSMALLINT get_concise_type_from_datetime_code(SQLSMALLINT dticode) { switch (dticode) { case SQL_CODE_DATE: return SQL_C_TYPE_DATE; case SQL_CODE_TIME: return SQL_C_TYPE_DATE; case SQL_CODE_TIMESTAMP: return SQL_C_TYPE_TIMESTAMP; default: return 0; } } /* Map the SQL_DESC_DATETIME_INTERVAL_CODE to the SQL_DESC_CONCISE_TYPE for interval types. Constant returned is valid for both param and value types. */ SQLSMALLINT get_concise_type_from_interval_code(SQLSMALLINT dticode) { switch (dticode) { case SQL_CODE_DAY: return SQL_C_INTERVAL_DAY; case SQL_CODE_DAY_TO_HOUR: return SQL_C_INTERVAL_DAY_TO_HOUR; case SQL_CODE_DAY_TO_MINUTE: return SQL_C_INTERVAL_DAY_TO_MINUTE; case SQL_CODE_DAY_TO_SECOND: return SQL_C_INTERVAL_DAY_TO_SECOND; case SQL_CODE_HOUR: return SQL_C_INTERVAL_HOUR; case SQL_CODE_HOUR_TO_MINUTE: return SQL_C_INTERVAL_HOUR_TO_MINUTE; case SQL_CODE_HOUR_TO_SECOND: return SQL_C_INTERVAL_HOUR_TO_SECOND; case SQL_CODE_MINUTE: return SQL_C_INTERVAL_MINUTE; case SQL_CODE_MINUTE_TO_SECOND: return SQL_C_INTERVAL_MINUTE_TO_SECOND; case SQL_CODE_MONTH: return SQL_C_INTERVAL_MONTH; case SQL_CODE_SECOND: return SQL_C_INTERVAL_SECOND; case SQL_CODE_YEAR: return SQL_C_INTERVAL_YEAR; case SQL_CODE_YEAR_TO_MONTH: return SQL_C_INTERVAL_YEAR_TO_MONTH; default: return 0; } } /* Map the concise type to a (possibly) more general type. */ SQLSMALLINT get_type_from_concise_type(SQLSMALLINT concise_type) { /* set SQL_DESC_TYPE from SQL_DESC_CONCISE_TYPE */ switch (concise_type) { /* datetime data types */ case SQL_C_TYPE_DATE: case SQL_C_TYPE_TIME: case SQL_C_TYPE_TIMESTAMP: return SQL_DATETIME; /* interval data types */ case SQL_C_INTERVAL_YEAR: case SQL_C_INTERVAL_MONTH: case SQL_C_INTERVAL_DAY: case SQL_C_INTERVAL_HOUR: case SQL_C_INTERVAL_MINUTE: case SQL_C_INTERVAL_SECOND: case SQL_C_INTERVAL_YEAR_TO_MONTH: case SQL_C_INTERVAL_DAY_TO_HOUR: case SQL_C_INTERVAL_DAY_TO_MINUTE: case SQL_C_INTERVAL_DAY_TO_SECOND: case SQL_C_INTERVAL_HOUR_TO_MINUTE: case SQL_C_INTERVAL_HOUR_TO_SECOND: case SQL_C_INTERVAL_MINUTE_TO_SECOND: return SQL_INTERVAL; /* else, set same */ default: return concise_type; } } /* @type : myodbc internal @purpose : returns internal type to C type */ int unireg_to_c_datatype(MYSQL_FIELD *field) { switch ( field->type ) { case MYSQL_TYPE_BIT: /* MySQL's BIT type can have more than one bit, in which case we treat it as a BINARY field. */ return (field->length > 1) ? SQL_C_BINARY : SQL_C_BIT; case MYSQL_TYPE_TINY: return SQL_C_TINYINT; case MYSQL_TYPE_YEAR: case MYSQL_TYPE_SHORT: return SQL_C_SHORT; case MYSQL_TYPE_INT24: case MYSQL_TYPE_LONG: return SQL_C_LONG; case MYSQL_TYPE_FLOAT: return SQL_C_FLOAT; case MYSQL_TYPE_DOUBLE: return SQL_C_DOUBLE; case MYSQL_TYPE_TIMESTAMP: case MYSQL_TYPE_DATETIME: return SQL_C_TIMESTAMP; case MYSQL_TYPE_NEWDATE: case MYSQL_TYPE_DATE: return SQL_C_DATE; case MYSQL_TYPE_TIME: return SQL_C_TIME; case MYSQL_TYPE_BLOB: case MYSQL_TYPE_TINY_BLOB: case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: return SQL_C_BINARY; case MYSQL_TYPE_LONGLONG: /* Must be returned as char */ default: return SQL_C_CHAR; } } /* @type : myodbc internal @purpose : returns default C type for a given SQL type */ int default_c_type(int sql_data_type) { switch ( sql_data_type ) { case SQL_CHAR: case SQL_VARCHAR: case SQL_LONGVARCHAR: case SQL_DECIMAL: case SQL_NUMERIC: default: return SQL_C_CHAR; case SQL_BIGINT: return SQL_C_SBIGINT; case SQL_BIT: return SQL_C_BIT; case SQL_TINYINT: return SQL_C_TINYINT; case SQL_SMALLINT: return SQL_C_SHORT; case SQL_INTEGER: return SQL_C_LONG; case SQL_REAL: case SQL_FLOAT: return SQL_C_FLOAT; case SQL_DOUBLE: return SQL_C_DOUBLE; case SQL_BINARY: case SQL_VARBINARY: case SQL_LONGVARBINARY: return SQL_C_BINARY; case SQL_DATE: case SQL_TYPE_DATE: return SQL_C_DATE; case SQL_TIME: case SQL_TYPE_TIME: return SQL_C_TIME; case SQL_TIMESTAMP: case SQL_TYPE_TIMESTAMP: return SQL_C_TIMESTAMP; } } /* @type : myodbc internal @purpose : returns bind length */ ulong bind_length(int sql_data_type,ulong length) { switch ( sql_data_type ) { case SQL_C_BIT: case SQL_C_TINYINT: case SQL_C_STINYINT: case SQL_C_UTINYINT: return 1; case SQL_C_SHORT: case SQL_C_SSHORT: case SQL_C_USHORT: return 2; case SQL_C_LONG: case SQL_C_SLONG: case SQL_C_ULONG: return sizeof(SQLINTEGER); case SQL_C_FLOAT: return sizeof(float); case SQL_C_DOUBLE: return sizeof(double); case SQL_C_DATE: case SQL_C_TYPE_DATE: return sizeof(DATE_STRUCT); case SQL_C_TIME: case SQL_C_TYPE_TIME: return sizeof(TIME_STRUCT); case SQL_C_TIMESTAMP: case SQL_C_TYPE_TIMESTAMP: return sizeof(TIMESTAMP_STRUCT); case SQL_C_SBIGINT: case SQL_C_UBIGINT: return sizeof(longlong); case SQL_C_NUMERIC: return sizeof(SQL_NUMERIC_STRUCT); default: /* For CHAR, VARCHAR, BLOB, DEFAULT...*/ return length; } } /** Get bookmark value from SQL_ATTR_FETCH_BOOKMARK_PTR buffer @param[in] fCType ODBC C type to return data as @param[out] rgbValue Pointer to buffer for returning data */ SQLLEN get_bookmark_value(SQLSMALLINT fCType, SQLPOINTER rgbValue) { switch (fCType) { case SQL_C_CHAR: case SQL_C_BINARY: return atol((const char*) rgbValue); case SQL_C_WCHAR: return sqlwchartoul((SQLWCHAR *)rgbValue, NULL); case SQL_C_TINYINT: case SQL_C_STINYINT: case SQL_C_UTINYINT: case SQL_C_SHORT: case SQL_C_SSHORT: case SQL_C_USHORT: case SQL_C_LONG: case SQL_C_SLONG: case SQL_C_ULONG: case SQL_C_FLOAT: case SQL_C_DOUBLE: case SQL_C_SBIGINT: case SQL_C_UBIGINT: return *((SQLLEN *) rgbValue); } return 0; } /* @type : myodbc internal @purpose : convert a possible string to a timestamp value */ int str_to_ts(SQL_TIMESTAMP_STRUCT *ts, const char *str, int len, int zeroToMin, BOOL dont_use_set_locale) { uint year, length; char buff[DATETIME_DIGITS + 1], *to; const char *end; SQL_TIMESTAMP_STRUCT tmp_timestamp; SQLUINTEGER fraction; if ( !ts ) { ts= (SQL_TIMESTAMP_STRUCT *) &tmp_timestamp; } /* SQL_NTS is (naturally) negative and is caught as well */ if (len < 0) { len= strlen(str); } /* We don't wan to change value in the out parameter directly before we know that string is a good datetime */ end= get_fractional_part(str, len, dont_use_set_locale, &fraction); if (end == NULL || end > str + len) { end= str + len; } for ( to= buff; str < end; ++str ) { if ( isdigit(*str) ) { if (to < buff+sizeof(buff)-1) { *to++= *str; } else { /* We have too many numbers in the string and we not gonna tolerate it */ return SQLTS_BAD_DATE; } } } length= (uint) (to-buff); if ( length == 6 || length == 12 ) /* YYMMDD or YYMMDDHHMMSS */ { memmove(buff+2, buff, length); if ( buff[0] <= '6' ) { buff[0]='2'; buff[1]='0'; } else { buff[0]='1'; buff[1]='9'; } length+= 2; to+= 2; } if (length < DATETIME_DIGITS) { strfill(buff + length, DATETIME_DIGITS - length, '0'); } else { *to= 0; } year= (digit(buff[0])*1000+digit(buff[1])*100+digit(buff[2])*10+digit(buff[3])); if (!strncmp(&buff[4], "00", 2) || !strncmp(&buff[6], "00", 2)) { if (!zeroToMin) /* Don't convert invalid */ return SQLTS_NULL_DATE; /* convert invalid to min allowed */ if (!strncmp(&buff[4], "00", 2)) buff[5]= '1'; if (!strncmp(&buff[6], "00", 2)) buff[7]= '1'; } ts->year= year; ts->month= digit(buff[4])*10+digit(buff[5]); ts->day= digit(buff[6])*10+digit(buff[7]); ts->hour= digit(buff[8])*10+digit(buff[9]); ts->minute= digit(buff[10])*10+digit(buff[11]); ts->second= digit(buff[12])*10+digit(buff[13]); ts->fraction= fraction; return 0; } /* @type : myodbc internal @purpose : convert a possible string to a time value */ my_bool str_to_time_st(SQL_TIME_STRUCT *ts, const char *str) { char buff[24],*to, *tokens[3] = {0, 0, 0}; int num= 0, int_hour=0, int_min= 0, int_sec= 0; SQL_TIME_STRUCT tmp_time; if ( !ts ) ts= (SQL_TIME_STRUCT *) &tmp_time; /* remember the position of the first numeric string */ tokens[0]= buff; for ( to= buff ; *str && to < buff+sizeof(buff)-1 ; ++str ) { if (isdigit(*str)) *to++= *str; else if (num < 2) { /* terminate the string and remember the beginning of the new one only if the time component number is not out of range */ *to++= 0; tokens[++num]= to; } else /* We can leave the loop now */ break; } /* Put the final termination character */ *to= 0; int_hour= tokens[0] ? atoi(tokens[0]) : 0; int_min= tokens[1] ? atoi(tokens[1]) : 0; int_sec= tokens[2] ? atoi(tokens[2]) : 0; /* Convert seconds into minutes if necessary */ if (int_sec > 59) { int_min+= int_sec / 60; int_sec= int_sec % 60; } /* Convert minutes into hours if necessary */ if (int_min > 59) { int_hour+= int_min / 60; int_min= int_min % 60; } ts->hour = (SQLUSMALLINT)(int_hour < 65536 ? int_hour : 65535); ts->minute = (SQLUSMALLINT)int_min; ts->second = (SQLUSMALLINT)int_sec; return 0; } /* @type : myodbc internal @purpose : convert a possible string to a data value. if zeroToMin is specified, YEAR-00-00 dates will be converted to the min valid ODBC date */ my_bool str_to_date(SQL_DATE_STRUCT *rgbValue, const char *str, uint length, int zeroToMin) { uint field_length,year_length,digits,i,date[3]; const char *pos; const char *end= str+length; for ( ; !isdigit(*str) && str != end ; ++str ) ; /* Calculate first number of digits. If length= 4, 8 or >= 14 then year is of format YYYY (YYYY-MM-DD, YYYYMMDD) */ for ( pos= str; pos != end && isdigit(*pos) ; ++pos ) ; digits= (uint) (pos-str); year_length= (digits == 4 || digits == 8 || digits >= 14) ? 4 : 2; field_length= year_length-1; for ( i= 0 ; i < 3 && str != end; ++i ) { uint tmp_value= (uint) (uchar) (*str++ - '0'); while ( str != end && isdigit(str[0]) && field_length-- ) { tmp_value= tmp_value*10 + (uint) (uchar) (*str - '0'); ++str; } date[i]= tmp_value; while ( str != end && !isdigit(*str) ) ++str; field_length= 1; /* Rest fields can only be 2 */ } if (i <= 1 || (i > 1 && !date[1]) || (i > 2 && !date[2])) { if (!zeroToMin) /* Convert? */ return 1; rgbValue->year= date[0]; rgbValue->month= (i > 1 && date[1]) ? date[1] : 1; rgbValue->day= (i > 2 && date[2]) ? date[2] : 1; } else { while ( i < 3 ) date[i++]= 1; rgbValue->year= date[0]; rgbValue->month= date[1]; rgbValue->day= date[2]; } return 0; } /* @type : myodbc internal @purpose : convert a time string to a (ulong) value. At least following formats are recogniced HHMMSS HHMM HH HH.MM.SS {t HH:MM:SS } @return : HHMMSS */ ulong str_to_time_as_long(const char *str, uint length) { uint i,date[3]; const char *end= str+length; if ( length == 0 ) return 0; for ( ; !isdigit(*str) && str != end ; ++str ) --length; for ( i= 0 ; i < 3 && str != end; ++i ) { uint tmp_value= (uint) (uchar) (*str++ - '0'); --length; while ( str != end && isdigit(str[0]) ) { tmp_value= tmp_value*10 + (uint) (uchar) (*str - '0'); ++str; --length; } date[i]= tmp_value; while ( str != end && !isdigit(*str) ) { ++str; --length; } } if ( length && str != end ) return str_to_time_as_long(str, length);/* timestamp format */ if ( date[0] > 10000L || i < 3 ) /* Properly handle HHMMSS format */ return(ulong) date[0]; return(ulong) date[0] * 10000L + (ulong) (date[1]*100L+date[2]); } /* @type : myodbc internal @purpose : if there was a long time since last question, check that the server is up with mysql_ping (to force a reconnect) */ int check_if_server_is_alive( DBC *dbc ) { time_t seconds= (time_t) time( (time_t*)0 ); int result= 0; if ( (ulong)(seconds - dbc->last_query_time) >= CHECK_IF_ALIVE ) { if ( mysql_ping( &dbc->mysql ) ) { /* BUG: 14639 A. The 4.1 doc says when mysql_ping() fails we can get one of the following errors from mysql_errno(); CR_COMMANDS_OUT_OF_SYNC CR_SERVER_GONE_ERROR CR_UNKNOWN_ERROR But if you do a mysql_ping() after bringing down the server you get CR_SERVER_LOST. PAH - 9.MAR.06 */ if ( mysql_errno( &dbc->mysql ) == CR_SERVER_LOST ) result = 1; } } dbc->last_query_time = seconds; return result; } /* @type : myodbc3 internal @purpose : appends quoted string to dynamic string */ my_bool dynstr_append_quoted_name(DYNAMIC_STRING *str, const char *name) { uint tmp= strlen(name); char *pos; if ( dynstr_realloc(str,tmp+3) ) return 1; pos= str->str+str->length; *pos='`'; memcpy(pos+1,name,tmp); pos[tmp+1]='`'; pos[tmp+2]= 0; /* Safety */ str->length+= tmp+2; return 0; } /* @type : myodbc3 internal @purpose : reset the db name to current_database() */ my_bool reget_current_catalog(DBC *dbc) { x_free(dbc->database); dbc->database= NULL; if ( odbc_stmt(dbc, "select database()", SQL_NTS, TRUE) ) { return 1; } else { MYSQL_RES *res; MYSQL_ROW row; if ( (res= mysql_store_result(&dbc->mysql)) && (row= mysql_fetch_row(res)) ) { /* if (cmp_database(row[0], dbc->database)) */ { if ( row[0] ) { dbc->database = myodbc_strdup(row[0], MYF(MY_WME)); } else { dbc->database = NULL; } } } mysql_free_result(res); } return 0; } /* @type : myodbc internal @purpose : compare strings without regarding to case */ int myodbc_strcasecmp(const char *s, const char *t) { if (!s && !t) { return 0; } if (!s || !t) { return 1; } while (toupper((uchar) *s) == toupper((uchar) *t++)) if (!*s++) return 0; return((int) toupper((uchar) s[0]) - (int) toupper((uchar) t[-1])); } /* @type : myodbc internal @purpose : compare strings without regarding to case */ int myodbc_casecmp(const char *s, const char *t, uint len) { if (!s && !t) { return 0; } if (!s || !t) { return (int)len + 1; } while (len-- != 0 && toupper(*s++) == toupper(*t++)) ; return (int)len + 1; } /* @type : myodbc internal @purpose : frees the result and additional allocated buffers for STMT */ void free_internal_result_buffers(STMT *stmt) { free_root(&stmt->alloc_root, MYF(0)); } /* @type : myodbc3 internal @purpose : logs the queries sent to server */ void query_print(FILE *log_file,char *query) { if ( log_file && query ) { /* because of bug 68201 we bring the result of time() call to 64-bits in any case */ long long time_now= time(NULL); fprintf(log_file, "%lld:%s;\n", time_now, query); } } FILE *init_query_log(void) { FILE *query_log; #ifdef _WIN32 char filename[MAX_PATH]; size_t buffsize; getenv_s(&buffsize, filename, sizeof(filename), "TEMP"); if (buffsize) { sprintf(filename + buffsize - 1, "\\%s", DRIVER_QUERY_LOGFILE); } else { sprintf(filename, "c:\\%s", DRIVER_QUERY_LOGFILE); } if ( (query_log= fopen(filename, "a+")) ) #else if ( (query_log= fopen(DRIVER_QUERY_LOGFILE, "a+")) ) #endif { fprintf(query_log,"-- Query logging\n"); fprintf(query_log,"--\n"); fprintf(query_log,"-- Driver name: %s Version: %s\n",DRIVER_NAME, DRIVER_VERSION); #ifdef HAVE_LOCALTIME_R { time_t now= time(NULL); struct tm start; localtime_r(&now,&start); fprintf(query_log,"-- Timestamp: %02d%02d%02d %2d:%02d:%02d\n", start.tm_year % 100, start.tm_mon+1, start.tm_mday, start.tm_hour, start.tm_min, start.tm_sec); } #endif /* HAVE_LOCALTIME_R */ fprintf(query_log,"\n"); } return query_log; } void end_query_log(FILE *query_log) { if ( query_log ) { fclose(query_log); query_log= 0; } } my_bool is_minimum_version(const char *server_version,const char *version) { /* Variables have to be initialized if we don't want to get random values after sscanf */ uint major1= 0, major2= 0, minor1= 0, minor2= 0, build1= 0, build2= 0; sscanf(server_version, "%u.%u.%u", &major1, &minor1, &build1); sscanf(version, "%u.%u.%u", &major2, &minor2, &build2); if ( major1 > major2 || major1 == major2 && (minor1 > minor2 || minor1 == minor2 && build1 >= build2)) { return TRUE; } return FALSE; } /** Escapes a string that may contain wildcard characters (%, _) and other problematic characters (", ', \n, etc). Like mysql_real_escape_string() but also including % and _. Can be used with an identified by passing escape_id. @param[in] mysql Pointer to MYSQL structure @param[out] to Buffer for escaped string @param[in] to_length Length of destination buffer, or 0 for "big enough" @param[in] from The string to escape @param[in] length The length of the string to escape @param[in] escape_id Escaping an identified that will be quoted */ ulong myodbc_escape_string(STMT *stmt, char *to, ulong to_length, const char *from, ulong length, int escape_id) { const char *to_start= to; const char *end, *to_end=to_start + (to_length ? to_length-1 : 2*length); my_bool overflow= FALSE; /*get_charset_by_csname(charset, MYF(MY_CS_PRIMARY), MYF(0));*/ CHARSET_INFO *charset_info= stmt->dbc->cxn_charset_info; my_bool use_mb_flag= use_mb(charset_info); for (end= from + length; from < end; ++from) { char escape= 0; int tmp_length; if (use_mb_flag && (tmp_length= my_ismbchar(charset_info, from, end))) { if (to + tmp_length > to_end) { overflow= TRUE; break; } while (tmp_length--) *to++= *from++; --from; continue; } /* If the next character appears to begin a multi-byte character, we escape that first byte of that apparent multi-byte character. (The character just looks like a multi-byte character -- if it were actually a multi-byte character, it would have been passed through in the test above.) Without this check, we can create a problem by converting an invalid multi-byte character into a valid one. For example, 0xbf27 is not a valid GBK character, but 0xbf5c is. (0x27 = ', 0x5c = \) */ if (use_mb_flag && (tmp_length= my_mbcharlen(charset_info, *from)) > 1) escape= *from; else switch (*from) { case 0: /* Must be escaped for 'mysql' */ escape= '0'; break; case '\n': /* Must be escaped for logs */ escape= 'n'; break; case '\r': escape= 'r'; break; case '\\': case '\'': case '"': /* Better safe than sorry */ case '_': case '%': escape= *from; break; case '\032': /* This gives problems on Win32 */ escape= 'Z'; break; } /* if escaping an id, only handle back-tick */ if (escape_id) { if (*from == '`') escape= *from; else escape= 0; } if (escape) { if (to + 2 > to_end) { overflow= TRUE; break; } *to++= escape != '`' ? '\\' : '`'; *to++= escape; } else { if (to + 1 > to_end) { overflow= TRUE; break; } *to++= *from; } } *to= 0; return overflow ? (ulong)~0 : (ulong) (to - to_start); } /** Scale an int[] representing SQL_C_NUMERIC @param[in] ary Array in little endian form @param[in] s Scale */ static void sqlnum_scale(int *ary, int s) { /* multiply out all pieces */ while (s--) { ary[0] *= 10; ary[1] *= 10; ary[2] *= 10; ary[3] *= 10; ary[4] *= 10; ary[5] *= 10; ary[6] *= 10; ary[7] *= 10; } } /** Unscale an int[] representing SQL_C_NUMERIC. This leaves the last element (0) with the value of the last digit. @param[in] ary Array in little endian form */ static void sqlnum_unscale_le(int *ary) { int i; for (i= 7; i > 0; --i) { ary[i - 1] += (ary[i] % 10) << 16; ary[i] /= 10; } } /** Unscale an int[] representing SQL_C_NUMERIC. This leaves the last element (7) with the value of the last digit. @param[in] ary Array in big endian form */ static void sqlnum_unscale_be(int *ary, int start) { int i; for (i= start; i < 7; ++i) { ary[i + 1] += (ary[i] % 10) << 16; ary[i] /= 10; } } /** Perform the carry to get all elements below 2^16. Should be called right after sqlnum_scale(). @param[in] ary Array in little endian form */ static void sqlnum_carry(int *ary) { int i; /* carry over rest of structure */ for (i= 0; i < 7; ++i) { ary[i+1] += ary[i] >> 16; ary[i] &= 0xffff; } } /** Retrieve a SQL_NUMERIC_STRUCT from a string. The requested scale and precesion are first read from sqlnum, and then updated values are written back at the end. @param[in] numstr String representation of number to convert @param[in] sqlnum Destination struct @param[in] overflow_ptr Whether or not whole-number overflow occurred. This indicates failure, and the result of sqlnum is undefined. */ void sqlnum_from_str(const char *numstr, SQL_NUMERIC_STRUCT *sqlnum, int *overflow_ptr) { /* We use 16 bits of each integer to convert the current segment of the number leaving extra bits to multiply/carry */ int build_up[8], tmp_prec_calc[8]; /* current segment as integer */ unsigned int curnum; /* current segment digits copied for strtoul() */ char curdigs[5]; /* number of digits in current segment */ int usedig; int i; int len; char *decpt= strchr((char*)numstr, '.'); int overflow= 0; SQLSCHAR reqscale= sqlnum->scale; SQLCHAR reqprec= sqlnum->precision; memset(&sqlnum->val, 0, sizeof(sqlnum->val)); memset(build_up, 0, sizeof(build_up)); /* handle sign */ if (!(sqlnum->sign= !(*numstr == '-'))) ++numstr; len= (int) strlen(numstr); sqlnum->precision= len; sqlnum->scale= 0; /* process digits in groups of <=4 */ for (i= 0; i < len; i += usedig) { if (i + 4 < len) usedig= 4; else usedig= len - i; /* if we have the decimal point, ignore it by setting it to the last char (will be ignored by strtoul) */ if (decpt && decpt >= numstr + i && decpt < numstr + i + usedig) { usedig = (int) (decpt - (numstr + i) + 1); sqlnum->scale= len - (i + usedig); --sqlnum->precision; decpt= NULL; } /* terminate prematurely if we can't do anything else */ /*if (overflow && !decpt) break; else */if (overflow) /*continue;*/goto end; /* grab just this piece, and convert to int */ memcpy(curdigs, numstr + i, usedig); curdigs[usedig]= 0; curnum= strtoul(curdigs, NULL, 10); if (curdigs[usedig - 1] == '.') sqlnum_scale(build_up, usedig - 1); else sqlnum_scale(build_up, usedig); /* add the current number */ build_up[0] += curnum; sqlnum_carry(build_up); if (build_up[7] & ~0xffff) overflow= 1; } /* scale up to SQL_DESC_SCALE */ if (reqscale > 0 && reqscale > sqlnum->scale) { while (reqscale > sqlnum->scale) { sqlnum_scale(build_up, 1); sqlnum_carry(build_up); ++sqlnum->scale; } } /* scale back, truncating decimals */ else if (reqscale < sqlnum->scale) { while (reqscale < sqlnum->scale && sqlnum->scale > 0) { sqlnum_unscale_le(build_up); build_up[0] /= 10; --sqlnum->precision; --sqlnum->scale; } } /* scale back whole numbers while there's no significant digits */ if (reqscale < 0) { memcpy(tmp_prec_calc, build_up, sizeof(build_up)); while (reqscale < sqlnum->scale) { sqlnum_unscale_le(tmp_prec_calc); if (tmp_prec_calc[0] % 10) { overflow= 1; goto end; } sqlnum_unscale_le(build_up); tmp_prec_calc[0] /= 10; build_up[0] /= 10; --sqlnum->precision; --sqlnum->scale; } } /* calculate minimum precision */ memcpy(tmp_prec_calc, build_up, sizeof(build_up)); do { sqlnum_unscale_le(tmp_prec_calc); i= tmp_prec_calc[0] % 10; tmp_prec_calc[0] /= 10; if (i == 0) --sqlnum->precision; } while (i == 0 && sqlnum->precision > 0); /* detect precision overflow */ if (sqlnum->precision > reqprec) overflow= 1; else sqlnum->precision= reqprec; /* compress results into SQL_NUMERIC_STRUCT.val */ for (i= 0; i < 8; ++i) { int elem= 2 * i; sqlnum->val[elem]= build_up[i] & 0xff; sqlnum->val[elem+1]= (build_up[i] >> 8) & 0xff; } end: if (overflow_ptr) *overflow_ptr= overflow; } /** Convert a SQL_NUMERIC_STRUCT to a string. Only val and sign are read from the struct. precision and scale will be updated on the struct with the final values used in the conversion. @param[in] sqlnum Source struct @param[in] numstr Buffer to convert into string. Note that you MUST use numbegin to read the result string. This should point to the LAST byte available. (We fill in digits backwards.) @param[in,out] numbegin String pointer that will be set to the start of the result string. @param[in] reqprec Requested precision @param[in] reqscale Requested scale @param[in] truncptr Pointer to set the truncation type encountered. If SQLNUM_TRUNC_WHOLE, this indicates a failure and the contents of numstr are undefined and numbegin will not be written to. */ void sqlnum_to_str(SQL_NUMERIC_STRUCT *sqlnum, SQLCHAR *numstr, SQLCHAR **numbegin, SQLCHAR reqprec, SQLSCHAR reqscale, int *truncptr) { int expanded[8]; int i, j; int max_space= 0; int calcprec= 0; int trunc= 0; /* truncation indicator */ *numstr--= 0; /* it's expected to have enough space (~at least min(39, max(prec, scale+2)) + 3) */ /* expand the packed sqlnum->val so we have space to divide through expansion happens into an array in big-endian form */ for (i= 0; i < 8; ++i) expanded[7 - i]= (sqlnum->val[(2 * i) + 1] << 8) | sqlnum->val[2 * i]; /* max digits = 39 = log_10(2^128)+1 */ for (j= 0; j < 39; ++j) { /* skip empty prefix */ while (!expanded[max_space]) ++max_space; /* if only the last piece has a value, it's the end */ if (max_space >= 7) { i= 7; if (!expanded[7]) { /* special case for zero, we'll end immediately */ if (!*(numstr + 1)) { *numstr--= '0'; calcprec= 1; } break; } } else { /* extract the next digit */ sqlnum_unscale_be(expanded, max_space); } *numstr--= '0' + (expanded[7] % 10); expanded[7] /= 10; ++calcprec; if (j == reqscale - 1) *numstr--= '.'; } sqlnum->scale= reqscale; /* add <- dec pt */ if (calcprec < reqscale) { while (calcprec < reqscale) { *numstr--= '0'; --reqscale; } *numstr--= '.'; *numstr--= '0'; } /* handle fractional truncation */ if (calcprec > reqprec && reqscale > 0) { SQLCHAR *end= numstr + strlen((char *)numstr) - 1; while (calcprec > reqprec && reqscale) { *end--= 0; --calcprec; --reqscale; } if (calcprec > reqprec && reqscale == 0) { trunc= SQLNUM_TRUNC_WHOLE; goto end; } if (*end == '.') { *end--= '\0'; } else { /* move the dec pt-- ??? */ /* char c2, c= numstr[calcprec - reqscale]; numstr[calcprec - reqscale]= '.'; while (reqscale) { c2= numstr[calcprec + 1 - reqscale]; numstr[calcprec + 1 - reqscale]= c; c= c2; --reqscale; } */ } trunc= SQLNUM_TRUNC_FRAC; } /* add zeros for negative scale */ if (reqscale < 0) { int i; reqscale *= -1; for (i= 1; i <= calcprec; ++i) *(numstr + i - reqscale)= *(numstr + i); numstr -= reqscale; memset(numstr + calcprec + 1, '0', reqscale); } sqlnum->precision= calcprec; /* finish up, handle auxilary fix-ups */ if (!sqlnum->sign) { *numstr--= '-'; } ++numstr; *numbegin= numstr; end: if (truncptr) *truncptr= trunc; } /** Adjust a pointer based on bind offset and bind type. @param[in] ptr The base pointer @param[in] bind_offset_ptr The bind offset ptr (can be NULL). (SQL_ATTR_PARAM_BIND_OFFSET_PTR, SQL_ATTR_ROW_BIND_OFFSET_PTR, SQL_DESC_BIND_OFFSET_PTR) @param[in] bind_type The bind type. Should be SQL_BIND_BY_COLUMN (0) or the length of a row for row-wise binding. (SQL_ATTR_PARAM_BIND_TYPE, SQL_ATTR_ROW_BIND_TYPE, SQL_DESC_BIND_TYPE) @param[in] default_size The column size if bind type = SQL_BIND_BY_COLUMN. @param[in] row The row number. @return The base pointer with the offset added. If the base pointer is NULL, NULL is returned. */ void *ptr_offset_adjust(void *ptr, SQLULEN *bind_offset_ptr, SQLINTEGER bind_type, SQLINTEGER default_size, SQLULEN row) { size_t offset= 0; if (bind_offset_ptr) offset= (size_t) *bind_offset_ptr; if (bind_type == SQL_BIND_BY_COLUMN) offset+= default_size * row; else offset+= bind_type * row; return ptr ? ((SQLCHAR *) ptr) + offset : NULL; } /** Sets the value of @@sql_select_limit @param[in] dbc dbc handler @param[in] new_value Value to set @@sql_select_limit. @param[in] req_lock The flag if dbc->lock thread lock should be used when executing a query Returns new_value if operation was successful, -1 otherwise */ SQLRETURN set_sql_select_limit(DBC *dbc, SQLULEN lim_value, my_bool req_lock) { char query[44]; SQLRETURN rc; /* Both 0 and max(SQLULEN) value mean no limit and sql_select_limit to DEFAULT */ if (lim_value == dbc->sql_select_limit || lim_value == sql_select_unlimited && dbc->sql_select_limit == 0) return SQL_SUCCESS; if (lim_value > 0 && lim_value < sql_select_unlimited) sprintf(query, "set @@sql_select_limit=%lu", (unsigned long)lim_value); else { strcpy(query, "set @@sql_select_limit=DEFAULT"); lim_value= 0; } if (SQL_SUCCEEDED(rc= odbc_stmt(dbc, query, SQL_NTS, req_lock))) { dbc->sql_select_limit= lim_value; } return rc; } /** Detects the parameter type. @param[in] proc procedure parameter string @param[in] len param string length @param[out] ptype pointer where to write the param type Returns position in the param string after parameter type */ char *proc_get_param_type(char *proc, int len, SQLSMALLINT *ptype) { while (isspace(*proc) && (len--)) ++proc; if (len >= 6 && !myodbc_casecmp(proc, "INOUT ", 6)) { *ptype= (SQLSMALLINT) SQL_PARAM_INPUT_OUTPUT; return proc + 6; } if (len >= 4 && !myodbc_casecmp(proc, "OUT ", 4)) { *ptype= (SQLSMALLINT) SQL_PARAM_OUTPUT; return proc + 4; } if (len >= 3 && !myodbc_casecmp(proc, "IN ", 3)) { *ptype= (SQLSMALLINT) SQL_PARAM_INPUT; return proc + 3; } *ptype= (SQLSMALLINT)SQL_PARAM_INPUT; return proc; } /** Detects the parameter name @param[in] proc procedure parameter string @param[in] len param string length @param[out] cname pointer where to write the param name Returns position in the param string after parameter name */ char* proc_get_param_name(char *proc, int len, char *cname) { char quote_symbol= '\0'; while (isspace(*proc) && (len--)) ++proc; /* can be '"' if ANSI_QUOTE is enabled */ if (*proc == '`' || *proc == '"') { quote_symbol= *proc; ++proc; } while ((len--) && (quote_symbol != '\0' ? *proc != quote_symbol : !isspace(*proc))) *(cname++)= *(proc++); return quote_symbol ? proc + 1 : proc; } /** Detects the parameter data type @param[in] proc procedure parameter string @param[in] len param string length @param[out] cname pointer where to write the param type name Returns position in the param string after parameter type name */ char* proc_get_param_dbtype(char *proc, int len, char *ptype) { char *trim_str, *start_pos= ptype; while (isspace(*proc) && (len--)) ++proc; while (*proc && (len--) ) *(ptype++)= *(proc++); /* remove the character set definition */ if (trim_str= strstr( myodbc_strlwr(start_pos, 0), " charset ")) { ptype= trim_str; (*ptype)= 0; } /* trim spaces from the end */ ptype-=1; while (isspace(*(ptype))) { *ptype= 0; --ptype; } return proc; } SQLTypeMap SQL_TYPE_MAP_values[TYPE_MAP_SIZE]= { /* SQL_BIT= -7 */ {(SQLCHAR*)"bit", 3, SQL_BIT, MYSQL_TYPE_BIT, 1, 1}, {(SQLCHAR*)"bool", 4, SQL_BIT, MYSQL_TYPE_BIT, 1, 1}, /* SQL_TINY= -6 */ {(SQLCHAR*)"tinyint", 7, SQL_TINYINT, MYSQL_TYPE_TINY, 1, 1}, /* SQL_BIGINT= -5 */ {(SQLCHAR*)"bigint", 6, SQL_BIGINT, MYSQL_TYPE_LONGLONG, 20, 1}, /* SQL_LONGVARBINARY= -4 */ {(SQLCHAR*)"long varbinary", 14, SQL_LONGVARBINARY, MYSQL_TYPE_MEDIUM_BLOB, 16777215, 1}, {(SQLCHAR*)"blob", 4, SQL_LONGVARBINARY, MYSQL_TYPE_BLOB, 65535, 1}, {(SQLCHAR*)"longblob", 8, SQL_LONGVARBINARY, MYSQL_TYPE_LONG_BLOB, 4294967295UL, 1}, {(SQLCHAR*)"tinyblob", 8, SQL_LONGVARBINARY, MYSQL_TYPE_TINY_BLOB, 255, 1}, {(SQLCHAR*)"mediumblob", 10, SQL_LONGVARBINARY, MYSQL_TYPE_MEDIUM_BLOB, 16777215,1 }, /* SQL_VARBINARY= -3 */ {(SQLCHAR*)"varbinary", 9, SQL_VARBINARY, MYSQL_TYPE_VAR_STRING, 0, 1}, /* SQL_BINARY= -2 */ {(SQLCHAR*)"binary", 6, SQL_BINARY, MYSQL_TYPE_STRING, 0, 1}, /* SQL_LONGVARCHAR= -1 */ {(SQLCHAR*)"long varchar", 12, SQL_LONGVARCHAR, MYSQL_TYPE_MEDIUM_BLOB, 16777215, 0}, {(SQLCHAR*)"text", 4, SQL_LONGVARCHAR, MYSQL_TYPE_BLOB, 65535, 0}, {(SQLCHAR*)"mediumtext", 10, SQL_LONGVARCHAR, MYSQL_TYPE_MEDIUM_BLOB, 16777215, 0}, {(SQLCHAR*)"longtext", 8, SQL_LONGVARCHAR, MYSQL_TYPE_LONG_BLOB, 4294967295UL, 0}, {(SQLCHAR*)"tinytext", 8, SQL_LONGVARCHAR, MYSQL_TYPE_TINY_BLOB, 255, 0}, /* SQL_CHAR= 1 */ {(SQLCHAR*)"char", 4, SQL_CHAR, MYSQL_TYPE_STRING, 0, 0}, {(SQLCHAR*)"enum", 4, SQL_CHAR, MYSQL_TYPE_STRING, 0, 0}, {(SQLCHAR*)"set", 3, SQL_CHAR, MYSQL_TYPE_STRING, 0, 0}, /* SQL_NUMERIC= 2 */ {(SQLCHAR*)"numeric", 7, SQL_NUMERIC, MYSQL_TYPE_DECIMAL, 0, 1}, /* SQL_DECIMAL= 3 */ {(SQLCHAR*)"decimal", 7, SQL_DECIMAL, MYSQL_TYPE_DECIMAL, 0, 1}, /* SQL_INTEGER= 4 */ {(SQLCHAR*)"int", 3, SQL_INTEGER, MYSQL_TYPE_LONG, 10, 1}, {(SQLCHAR*)"mediumint", 9, SQL_INTEGER, MYSQL_TYPE_INT24, 8, 1}, /* SQL_SMALLINT= 5 */ {(SQLCHAR*)"smallint", 8, SQL_SMALLINT, MYSQL_TYPE_SHORT, 5, 1}, /* SQL_REAL= 7 */ {(SQLCHAR*)"float", 5, SQL_REAL, MYSQL_TYPE_FLOAT, 7, 1}, /* SQL_DOUBLE= 8 */ {(SQLCHAR*)"double", 6, SQL_DOUBLE, MYSQL_TYPE_DOUBLE, 15, 1}, /* SQL_DATETIME= 9 */ {(SQLCHAR*)"datetime", 8, SQL_TYPE_TIMESTAMP, MYSQL_TYPE_DATETIME, 19, 1}, /* SQL_VARCHAR= 12 */ {(SQLCHAR*)"varchar", 7, SQL_VARCHAR, MYSQL_TYPE_VARCHAR, 0, 0}, /* SQL_TYPE_DATE= 91 */ {(SQLCHAR*)"date", 4, SQL_TYPE_DATE, MYSQL_TYPE_DATE, 10, 1}, /* YEAR - SQL_SMALLINT */ {(SQLCHAR*)"year", 4, SQL_SMALLINT, MYSQL_TYPE_YEAR, 2, 1}, /* SQL_TYPE_TIMESTAMP= 93 */ {(SQLCHAR*)"timestamp", 9, SQL_TYPE_TIMESTAMP, MYSQL_TYPE_TIMESTAMP, 19, 1}, /* SQL_TYPE_TIME= 92 */ {(SQLCHAR*)"time", 4, SQL_TYPE_TIME, MYSQL_TYPE_TIME, 8, 1} }; enum enum_field_types map_sql2mysql_type(SQLSMALLINT sql_type) { int i; for (i= 0; i < TYPE_MAP_SIZE; ++i) { if (SQL_TYPE_MAP_values[i].sql_type == sql_type) { return (enum_field_types)SQL_TYPE_MAP_values[i].mysql_type; } } return MYSQL_TYPE_BLOB; } /** Gets the parameter index in the type map array @param[in] ptype procedure parameter type name @param[in] len param string length Returns position in the param string after parameter type name */ int proc_get_param_sql_type_index(const char *ptype, int len) { int i; for (i= 0; i < TYPE_MAP_SIZE; ++i) { if (len >= SQL_TYPE_MAP_values[i].name_length && (!myodbc_casecmp(ptype, (const char*)SQL_TYPE_MAP_values[i].type_name, SQL_TYPE_MAP_values[i].name_length))) return i; } return 16; /* "char" */ } /** Gets the parameter info array from the map using index @param[in] index index in the param info array Pointer to the structure that contains parameter info */ SQLTypeMap *proc_get_param_map_by_index(int index) { return &SQL_TYPE_MAP_values[index]; } /** Parses parameter size and decimal digits @param[in] ptype parameter type name @param[in] len type string length @param[out] dec pointer where to write decimal digits Returns parsed size */ SQLUINTEGER proc_parse_sizes(SQLCHAR *ptype, int len, SQLSMALLINT *dec) { int parsed= 0; SQLUINTEGER param_size= 0; if (ptype == NULL) { /* That shouldn't happen though */ return 0; } while ((len > 0) && (*ptype!= ')') && (parsed < 2)) { int n_index= 0; char number_to_parse[16]= "\0"; /* skip all non-digit characters */ while (!isdigit(*ptype) && (len-- >= 0) && (*ptype!= ')')) ++ptype; /* add digit characters to the buffer for parsing */ while (isdigit(*ptype) && (len-- >= 0)) { number_to_parse[n_index++]= *ptype; ++ptype; } /* 1st number is column size, 2nd is decimal digits */ if (!parsed) param_size= atoi(number_to_parse); else *dec= (SQLSMALLINT)atoi(number_to_parse); ++parsed; } return param_size; } /** Determines the length of ENUM/SET @param[in] ptype parameter type name @param[in] len type string length @param[in] is_enum flag to treat string as ENUM instead of SET Returns size of ENUM/SET */ SQLUINTEGER proc_parse_enum_set(SQLCHAR *ptype, int len, BOOL is_enum) { SQLUINTEGER total_len= 0, elem_num= 0, max_len= 0, cur_len= 0; char quote_symbol= '\0'; /* theoretically ')' can be inside quotes as part of enum value */ while ((len > 0) && (quote_symbol != '\0' || *ptype!= ')')) { if (*ptype == quote_symbol) { quote_symbol= '\0'; max_len= myodbc_max(cur_len, max_len); } else if (*ptype == '\'' || *ptype == '"') { quote_symbol= *ptype; cur_len= 0; ++elem_num; } else if (quote_symbol) { ++cur_len; ++total_len; } ++ptype; --len; } return is_enum ? max_len : total_len + elem_num - 1; } /** Returns parameter size and decimal digits @param[in] ptype parameter type name @param[in] len type string length @param[in] sql_type_index index in the param info array @param[out] dec pointer where to write decimal digits Returns parameter size */ SQLUINTEGER proc_get_param_size(SQLCHAR *ptype, int len, int sql_type_index, SQLSMALLINT *dec) { SQLUINTEGER param_size= SQL_TYPE_MAP_values[sql_type_index].type_length; SQLCHAR *start_pos= (SQLCHAR*)strchr((const char*)ptype, '('); SQLCHAR *end_pos= (SQLCHAR*)strrchr((const char*)ptype, ')'); /* no decimal digits by default */ *dec= SQL_NO_TOTAL; switch (SQL_TYPE_MAP_values[sql_type_index].mysql_type) { /* these type sizes need to be parsed */ case MYSQL_TYPE_DECIMAL: param_size= proc_parse_sizes(start_pos, end_pos - start_pos, dec); if(!param_size) param_size= 10; /* by default */ break; case MYSQL_TYPE_YEAR: *dec= 0; param_size= proc_parse_sizes(start_pos, end_pos - start_pos, dec); if(!param_size) param_size= 4; /* by default */ break; case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_VAR_STRING: case MYSQL_TYPE_STRING: if (!myodbc_strcasecmp((const char*)(SQL_TYPE_MAP_values[sql_type_index].type_name), "set")) { param_size= proc_parse_enum_set(start_pos, end_pos - start_pos, FALSE); } else if (!myodbc_strcasecmp((const char*)(SQL_TYPE_MAP_values[sql_type_index].type_name), "enum")) { param_size= proc_parse_enum_set(start_pos, end_pos - start_pos, TRUE); } else /* just normal character type */ { param_size= proc_parse_sizes(start_pos, end_pos - start_pos, dec); if (param_size == 0 && SQL_TYPE_MAP_values[sql_type_index].sql_type == SQL_BINARY) param_size= 1; } break; case MYSQL_TYPE_BIT: param_size= proc_parse_sizes(start_pos, end_pos - start_pos, dec); /* fall through*/ case MYSQL_TYPE_DATETIME: case MYSQL_TYPE_TINY: case MYSQL_TYPE_SHORT: case MYSQL_TYPE_INT24: case MYSQL_TYPE_LONG: case MYSQL_TYPE_LONGLONG: *dec= 0; break; } return param_size; } /** Gets parameter columns size @param[in] stmt statement @param[in] sql_type_index index in the param info array @param[in] col_size parameter size @param[in] decimal_digits write decimal digits @param[in] flags field flags Returns parameter octet length */ SQLLEN proc_get_param_col_len(STMT *stmt, int sql_type_index, SQLULEN col_size, SQLSMALLINT decimal_digits, unsigned int flags, char * str_buff) { MYSQL_FIELD temp_fld; temp_fld.length= (unsigned long)col_size + (SQL_TYPE_MAP_values[sql_type_index].mysql_type == MYSQL_TYPE_DECIMAL ? 1 + (flags & UNSIGNED_FLAG ? 0 : 1) : 0); /* add 1for sign, if needed, and 1 for decimal point */ temp_fld.max_length= col_size; temp_fld.decimals= decimal_digits; temp_fld.flags= flags; temp_fld.charsetnr= stmt->dbc->ansi_charset_info->number; temp_fld.type= (enum_field_types)(SQL_TYPE_MAP_values[sql_type_index].mysql_type); if (str_buff != NULL) { return fill_column_size_buff(str_buff, stmt, &temp_fld); } else { return get_column_size( stmt, &temp_fld); } } /** Gets parameter octet length @param[in] stmt statement @param[in] sql_type_index index in the param info array @param[in] col_size parameter size @param[in] decimal_digits write decimal digits @param[in] flags field flags Returns parameter octet length */ SQLLEN proc_get_param_octet_len(STMT *stmt, int sql_type_index, SQLULEN col_size, SQLSMALLINT decimal_digits, unsigned int flags, char * str_buff) { MYSQL_FIELD temp_fld; temp_fld.length= (unsigned long)col_size + (SQL_TYPE_MAP_values[sql_type_index].mysql_type == MYSQL_TYPE_DECIMAL ? 1 + (flags & UNSIGNED_FLAG ? 0 : 1) : 0); /* add 1for sign, if needed, and 1 for decimal point */ temp_fld.max_length= col_size; temp_fld.decimals= decimal_digits; temp_fld.flags= flags; temp_fld.charsetnr= stmt->dbc->ansi_charset_info->number; temp_fld.type= (enum_field_types)(SQL_TYPE_MAP_values[sql_type_index].mysql_type); if (str_buff != NULL) { return fill_transfer_oct_len_buff(str_buff, stmt, &temp_fld); } else { return get_transfer_octet_length(stmt, &temp_fld); } } /** tokenize the string by putting \0 bytes to separate params @param[in] str parameters string @param[out] params_num number of detected parameters Returns pointer to the first param */ char *proc_param_tokenize(char *str, int *params_num) { BOOL bracket_open= 0; char *str_begin= str, quote_symbol='\0'; int len= strlen(str); *params_num= 0; /* if no params at all */ while (len > 0 && isspace(*str)) { ++str; --len; } if (len && *str && *str != ')') *params_num= 1; while (len > 0) { /* Making sure that a bracket is not inside quotes. that's possible for SET or ENUM values */ if (quote_symbol == '\0') { if (!bracket_open && *str == ',') { *str= '\0'; ++(*params_num); } else if (*str == '(') { bracket_open= 1; } else if (*str == ')') { bracket_open= 0; } else if (*str == '"' || *str == '\'') { quote_symbol= *str; } } else if( *str == quote_symbol) { quote_symbol= '\0'; } ++str; --len; } return str_begin; } /** goes to the next token in \0-terminated string sequence @param[in] str parameters string @param[in] str_end end of the sequence Returns pointer to the next token in sequence */ char *proc_param_next_token(char *str, char *str_end) { int end_token= strlen(str); /* return the next string after \0 byte */ if (str + end_token + 1 < str_end) return (char*)(str + end_token + 1); return 0; } /** deletes the list element and moves the pointer forward @param[in] elem item to delete Returns pointer to the next list element */ LIST *list_delete_forward(LIST *elem) { if(elem->prev) elem->prev->next= elem->next; if(elem->next) { elem->next->prev= elem->prev; elem= elem->next; } return elem; } /** Sets row_count in STMT's MYSQL_RES and affected rows property MYSQL object. Primary use is to set number of affected rows for constructed resulsets. Setting mysql.affected_rows is required for SQLRowCount to return correct data for such resultsets. */ void set_row_count(STMT *stmt, my_ulonglong rows) { if (stmt != NULL && stmt->result != NULL) { stmt->result->row_count= rows; stmt->dbc->mysql.affected_rows= rows; } } /** Gets fractional time of a second from datetime or time string. @param[in] value (date)time string @param[in] len length of value buffer @param[in] dont_use_set_locale use dot as decimal part separator @param[out] fraction buffer where to put fractional part in nanoseconds Returns pointer to decimal point in the string */ const char * get_fractional_part(const char * str, int len, BOOL dont_use_set_locale, SQLUINTEGER * fraction) { const char *decptr= NULL, *end; int decpoint_len= 1; if (len < 0) { len= strlen(str); } end= str + len; if (dont_use_set_locale) { decptr= strchr(str, '.'); } else { decpoint_len= decimal_point_length; while (*str && str < end) { if (str[0] == decimal_point[0] && is_prefix(str,decimal_point) ) { decptr= str; break; } ++str; } } /* If decimal point is the last character - we don't have fractional part */ if (decptr && decptr < end - decpoint_len) { char buff[10], *ptr; strfill(buff, sizeof(buff)-1, '0'); str= decptr + decpoint_len; for (ptr= buff; str < end && ptr < buff + sizeof(buff); ++ptr) { /* there actually should not be anything that is not a digit... */ if (isdigit(*str)) { *ptr= *str++; } } buff[9]= 0; *fraction= atoi(buff); } else { *fraction= 0; decptr= NULL; } return decptr; } /* Convert MySQL timestamp to full ANSI timestamp format. */ char * complete_timestamp(const char * value, ulong length, char buff[21]) { char *pos; uint i; if (length == 6 || length == 10 || length == 12) { /* For two-digit year, < 60 is considered after Y2K */ if (value[0] <= '6') { buff[0]= '2'; buff[1]= '0'; } else { buff[0]= '1'; buff[1]= '9'; } } else { buff[0]= value[0]; buff[1]= value[1]; value+= 2; length-= 2; } buff[2]= *value++; buff[3]= *value++; buff[4]= '-'; if (value[0] == '0' && value[1] == '0') { /* Month was 0, which ODBC can't handle. */ return NULL; } pos= buff+5; length&= 30; /* Ensure that length is ok */ for (i= 1, length-= 2; (int)length > 0; length-= 2, ++i) { *pos++= *value++; *pos++= *value++; *pos++= i < 2 ? '-' : (i == 2) ? ' ' : ':'; } for ( ; pos != buff + 20; ++i) { *pos++= '0'; *pos++= '0'; *pos++= i < 2 ? '-' : (i == 2) ? ' ' : ':'; } return buff; } /* HPUX has some problems with long double : http://docs.hp.com/en/B3782-90716/ch02s02.html strtold() has implementations that return struct long_double, 128bit one, which contains four 32bit words. Fix described : -------- union { long_double l_d; long double ld; } u; // convert str to a long_double; store return val in union //(Putting value into union enables converted value to be // accessed as an ANSI C long double) u.l_d = strtold( (const char *)str, (char **)NULL); -------- reinterpret_cast doesn't work :( */ long double myodbc_strtold(const char *nptr, char **endptr) { /* * Experienced odd compilation errors on one of windows build hosts - * cmake reported there is strold function. Since double and long double on windows * are of the same size - we are using strtod on those platforms regardless * to the HAVE_FUNCTION_STRTOLD value */ #ifdef _WIN32 return strtod(nptr, endptr); #else # ifndef HAVE_FUNCTION_STRTOLD return strtod(nptr, endptr); # else # if defined(__hpux) && defined(_LONG_DOUBLE) union { long_double l_d; long double ld; } u; u.l_d = strtold( nptr, endptr); return u.ld; # else return strtold(nptr, endptr); # endif # endif #endif } /* @type : myodbc3 internal @purpose : help function to enlarge buffer if necessary */ char *extend_buffer(NET *net, char *to, ulong length) { ulong need= 0; need= (ulong)(to - (char *)net->buff) + length; if (!to || need > net->max_packet - 10) { if (myodbc_net_realloc(net, need)) { return 0; } to= (char *)net->buff + need - length; } return to; } /* @type : myodbc3 internal @purpose : help function to extend the buffer and copy the data */ char *add_to_buffer(NET *net,char *to,const char *from,ulong length) { if ( !(to= extend_buffer(net,to,length)) ) return 0; memcpy(to,from,length); return to+length; } /* Get the offset and row numbers from a string with LIMIT @param[in] cs charset @param[in] query query @param[in] query_end end of query @param[out] offs_out output buffer for offset @param[out] rows_out output buffer for rows @return the position where LIMIT OFFS, ROWS is ending */ char* get_limit_numbers(CHARSET_INFO* cs, char *query, char * query_end, unsigned long long *offs_out, unsigned int *rows_out) { char digit_buf[30]; int index_pos = 0; // Skip spaces after LIMIT while ((query_end > query) && myodbc_isspace(cs, query, query_end)) ++query; // Collect all numbers for the offset while ((query_end > query) && myodbc_isnum(cs, query, query_end)) { digit_buf[index_pos] = *query; ++index_pos; ++query; } if (!index_pos) { // Something went wrong, the limit numbers are not found return query; } digit_buf[index_pos] = '\0'; *offs_out = (unsigned long long)atoll(digit_buf); // Find the row number for "LIMIT offset, row_number" while ((query_end > query) && !myodbc_isnum(cs, query, query_end)) ++query; if (query == query_end) { // It was "LIMIT row_number" without offset // What we thought was offset is in fact the number of rows *rows_out = (unsigned long)*offs_out; *offs_out = 0; return query; } index_pos = 0; // reset index to use with another number // Collect all numbers for the row number while ((query_end > query) && myodbc_isnum(cs, query, query_end)) { digit_buf[index_pos] = *query; ++index_pos; ++query; } digit_buf[index_pos] = '\0'; *rows_out = (unsigned long)atol(digit_buf); return query; } /* Check if SELECT query requests the row locking @param[in] cs charset @param[in] query query @param[in] query_end query end @param[in] is_share flag to check the share mode otherwise for update @return position of "FOR UPDATE" or "LOCK IN SHARE MODE" inside a query. Otherwise returns NULL. */ const char* check_row_locking(CHARSET_INFO* cs, char * query, char * query_end, BOOL is_share_mode) { const char *before_token= query_end; const char *token= NULL; int i = 0; const char *for_update[2] = { "UPDATE", "FOR" }; const char *lock_in_share_mode[4] = { "MODE", "SHARE", "IN", "LOCK" }; const char **check = for_update; int index_max = 2; if (is_share_mode) { check = lock_in_share_mode; index_max = 4; } for (i = 0; i < index_max; ++i) { token = mystr_get_prev_token(cs, &before_token, query); if (myodbc_casecmp(token, check[i], strlen(check[i]))) return NULL; } return token; } MY_LIMIT_CLAUSE find_position4limit(CHARSET_INFO* cs, char *query, char * query_end) { MY_LIMIT_CLAUSE result={0,0,NULL,NULL}; char *limit_pos = NULL; result.begin= result.end= query_end; assert(query && query_end && query_end >= query); if ((limit_pos = (char*)find_token(cs, query, query_end, "LIMIT"))) { // Found LIMIT in the query result.end = get_limit_numbers(cs, limit_pos + 5, query_end, &result.offset, &result.row_count); // We will start again from the position of LIMIT to simplify the logic result.begin = limit_pos; } else // No LIMIT in SELECT { const char *locking_pos = NULL; if ((locking_pos = check_row_locking(cs, query, query_end, FALSE)) || (locking_pos = check_row_locking(cs, query, query_end, TRUE))) { // FOR UPDATE or LOCK IN SHARE MODE was detected result.begin= result.end = (char*)locking_pos - 1; // With a previous space } else { while(query_end > query && (!*query_end || myodbc_isspace(cs, query_end, result.end))) { --query_end; } if (*query_end==';') { result.begin= result.end= query_end; } } } return result; } BOOL myodbc_isspace(CHARSET_INFO* cs, const char * begin, const char *end) { int ctype; cs->cset->ctype(cs, &ctype, (const uchar*) begin, (const uchar*) end); return ctype & _MY_SPC; } BOOL myodbc_isnum(CHARSET_INFO* cs, const char * begin, const char *end) { int ctype; cs->cset->ctype(cs, &ctype, (const uchar*)begin, (const uchar*)end); return ctype & _MY_NMR; } int got_out_parameters(STMT *stmt) { uint i; DESCREC *iprec; int result= NO_OUT_PARAMETERS; for(i= 0; i < stmt->param_count; ++i) { iprec= desc_get_rec(stmt->ipd, i, '\0'); if (iprec) { if(iprec->parameter_type == SQL_PARAM_INPUT_OUTPUT || iprec->parameter_type == SQL_PARAM_OUTPUT) { result|= GOT_OUT_PARAMETERS; } #ifndef USE_IODBC else if (iprec->parameter_type == SQL_PARAM_INPUT_OUTPUT_STREAM || iprec->parameter_type == SQL_PARAM_OUTPUT_STREAM) { result|= GOT_OUT_STREAM_PARAMETERS; } #endif } } return result; } int get_session_variable(STMT *stmt, const char *var, char *result) { char buff[255+4*NAME_CHAR_LEN], *to; MYSQL_RES *res; MYSQL_ROW row; if (var) { to= myodbc_stpmov(buff, "SHOW SESSION VARIABLES LIKE '"); to= myodbc_stpmov(to, var); to= myodbc_stpmov(to, "'"); *to= '\0'; if (!SQL_SUCCEEDED(odbc_stmt(stmt->dbc, buff, SQL_NTS, TRUE))) { return 0; } res= mysql_store_result(&stmt->dbc->mysql); if (!res) return 0; row= mysql_fetch_row(res); if (row) { strcpy(result, row[1]); mysql_free_result(res); return strlen(result); } mysql_free_result(res); } return 0; } /** Sets the value of @@max_execution_time @param[in] stmt stmt handler @param[in] new_value Value to set @@max_execution_time. Returns new_value if operation was successful, -1 otherwise */ SQLRETURN set_query_timeout(STMT *stmt, SQLULEN new_value) { char query[44]; SQLRETURN rc= SQL_SUCCESS; if (new_value == stmt->stmt_options.query_timeout || !is_minimum_version(stmt->dbc->mysql.server_version, "5.7.8")) { /* Do nothing if setting same timeout or MySQL server older than 5.7.8 */ return SQL_SUCCESS; } if (new_value > 0) { unsigned long long msec_value= (unsigned long long)new_value * 1000; sprintf(query, "set @@max_execution_time=%llu", msec_value); } else { strcpy(query, "set @@max_execution_time=DEFAULT"); new_value= 0; } if (SQL_SUCCEEDED(rc= odbc_stmt(stmt->dbc, query, SQL_NTS, TRUE))) { stmt->stmt_options.query_timeout= new_value; } return rc; } SQLULEN get_query_timeout(STMT *stmt) { SQLULEN query_timeout= SQL_QUERY_TIMEOUT_DEFAULT; /* 0 */ if (is_minimum_version(stmt->dbc->mysql.server_version, "5.7.8")) { /* Be cautious with very long values even if they don't make sense */ char query_timeout_char[32]= {0}; uint length= get_session_variable(stmt, "MAX_EXECUTION_TIME", (char*)query_timeout_char); /* Terminate the string just in case */ query_timeout_char[length]= 0; /* convert */ query_timeout= (SQLULEN)(atol(query_timeout_char) / 1000); } return query_timeout; } const char get_identifier_quote(STMT *stmt) { const char tick= '`', quote= '"', empty= ' '; if (is_minimum_version(stmt->dbc->mysql.server_version, "3.23.06")) { /* The full list of all SQL modes takes over 512 symbols, so we reserve some for the future */ char sql_mode[2048]= " "; /* The token finder skips the leading space and starts with the first non-space value. Thus (sql_mode+1). */ uint length= get_session_variable(stmt, "SQL_MODE", (char*)(sql_mode+1)); const char *end= sql_mode + length; if (find_first_token(stmt->dbc->ansi_charset_info, sql_mode, end, "ANSI_QUOTES")) { return quote; } else { return tick; } } return empty; } /** Realloc the NET packet buffer. */ my_bool myodbc_net_realloc(NET *net, size_t length) { uchar *buff; size_t pkt_length; if (length >= net->max_packet_size) { /* @todo: 1 and 2 codes are identical. */ net->error= 1; net->last_errno= ER_NET_PACKET_TOO_LARGE; return 1; } pkt_length = (length+IO_SIZE-1) & ~(IO_SIZE-1); /* We must allocate some extra bytes for the end 0 and to be able to read big compressed blocks + 1 safety byte since uint3korr() in net_read_packet() may actually read 4 bytes depending on build flags and platform. */ if (!(buff= (uchar*) myodbc_realloc((char*) net->buff, pkt_length + NET_HEADER_SIZE + COMP_HEADER_SIZE + 1, MYF(MY_WME)))) { /* @todo: 1 and 2 codes are identical. */ net->error= 1; net->last_errno= ER_OUT_OF_RESOURCES; /* In the server the error is reported by MY_WME flag. */ return 1; } net->buff=net->write_pos=buff; net->buff_end=buff+(net->max_packet= (ulong) pkt_length); return 0; } /** Free net packet buffer. */ void myodbc_net_end(NET *net) { my_free(net->buff); net->buff=0; }
25.582415
104
0.61544
[ "geometry", "object" ]