hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
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
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c5b039ee0234f54312d283c1d27949f21872e054
3,607
cpp
C++
src/core_math.cpp
thechrisyoon08/NeuralNetworks
b47eb6425341c0d0e8278431aaf8b64143ce921f
[ "MIT" ]
1
2018-12-30T05:11:59.000Z
2018-12-30T05:11:59.000Z
src/core_math.cpp
thechrisyoon08/sANNity
b47eb6425341c0d0e8278431aaf8b64143ce921f
[ "MIT" ]
null
null
null
src/core_math.cpp
thechrisyoon08/sANNity
b47eb6425341c0d0e8278431aaf8b64143ce921f
[ "MIT" ]
null
null
null
#include "../include/core_math.h" #include <cstdlib> #include <iostream> #include <vector> #include <random> #include <math.h> #include <assert.h> namespace tensor{ void Tensor::fill_weights(const std::string initializer){ this->tensor.resize(this->m * this->n); if(initializer== "zero"){ for(size_t entry = 0; entry < this->m * this->n; ++entry){ this->tensor[entry] = 0.0; } } if(initializer == "glorot"){ double variance = 2.0 / (this->m + this->n); std::random_device rd; std::mt19937 e2(rd()); std::uniform_real_distribution<> dist(-std::sqrt(3.0 * variance), std::sqrt(3.0 * variance)); for(size_t entry = 0; entry < this->m * this->n; ++entry){ this->tensor[entry] = dist(e2); } } } void Tensor::fill_weights(const double low, const double high){ this->tensor.resize(this->m * this->n); std::random_device rd; std::mt19937 e2(rd()); std::uniform_real_distribution<> dist(low, high); for(size_t entry = 0; entry < this->m * this->n; ++entry){ this->tensor[entry] = dist(e2); } } void Tensor::T(){ std::vector<double> original = this->tensor; this->tensor.resize(this->n * this->m); for(size_t e = 0; e < this->n * this->m; ++e){ size_t i = e/this->m; size_t j = e%this->m; this->tensor[e] = original[this->n * j + i]; } std::swap(this->m, this->n); this->transposed = !this->transposed; } void copy_tensor(Tensor& A, Tensor& B){ A = B; } void initialize(Tensor& empty_tensor, size_t row, size_t col, std::string initializer){ empty_tensor.m = row; empty_tensor.n = col; empty_tensor.fill_weights(initializer); } void initialize(Tensor& empty_tensor, size_t row, size_t col, double low, double high){ empty_tensor.m = row; empty_tensor.n = col; empty_tensor.fill_weights(low, high); } const Tensor operator+(const Tensor& lhs, const Tensor& rhs){ Tensor ret(lhs.m, lhs.n); for(size_t entry = 0; entry < lhs.m * lhs.n; ++entry){ ret.tensor[entry] = lhs.tensor[entry] + rhs.tensor[entry]; } return ret; } const Tensor operator-(const Tensor& lhs, const Tensor& rhs){ Tensor ret(lhs.m, lhs.n); for(size_t entry = 0; entry < lhs.m * lhs.n; ++entry){ ret.tensor[entry] = lhs.tensor[entry] - rhs.tensor[entry]; } return ret; } const Tensor operator*(const double k, const Tensor& rhs){ Tensor ret(rhs.m, rhs.n); for(size_t entry = 0; entry < rhs.m * rhs.n; ++entry){ ret.tensor[entry] = k * rhs.tensor[entry]; } return ret; } const Tensor operator*(const Tensor& lhs, const Tensor& rhs){ assert(lhs.n == rhs.m); Tensor ret(lhs.m, rhs.n); for(size_t i = 0; i < lhs.m; ++i){ for(size_t j = 0; j < rhs.n; ++j){ for(size_t k = 0; k < lhs.n; ++k){ ret.tensor[j + i * rhs.n] += lhs.tensor[k + i * lhs.n] * rhs.tensor[j + k * rhs.n]; } } } return ret; } /*const Tensor operator=(const Tensor& t){ return t; }*/ std::ostream& operator<<(std::ostream& os, const Tensor& M){ os << "["; for(size_t i = 0; i < M.m; ++i){ if(i != 0){ os << " "; } os << "["; for(size_t j = 0; j < M.n; ++j){ os << M.tensor[j + M.n * i]; if(j == M.n - 1){ os << "]"; }else{ os << ", "; } } if(i == M.m - 1){ os << "]\n "; }else{ os << "\n"; } } } }
26.137681
101
0.535071
thechrisyoon08
c5b3694027671c2a0d6653bc51150967a242c5f9
1,034
cpp
C++
src/arguments/src/ArgumentsException.cpp
xgallom/eset_file_system
3816a8e3ae3c36d5771b900251345d08c76f8a0e
[ "MIT" ]
null
null
null
src/arguments/src/ArgumentsException.cpp
xgallom/eset_file_system
3816a8e3ae3c36d5771b900251345d08c76f8a0e
[ "MIT" ]
null
null
null
src/arguments/src/ArgumentsException.cpp
xgallom/eset_file_system
3816a8e3ae3c36d5771b900251345d08c76f8a0e
[ "MIT" ]
null
null
null
// // Created by xgallom on 4/4/19. // #include "ArgumentsException.h" #include "ArgumentsConfig.h" #include <sstream> namespace Arguments { Exception::Exception(const std::string &a_what) : std::runtime_error(a_what) {} Exception Exception::InvalidArgCount(int argCount) { std::stringstream stream; // count - 1 because argument[0] is the program name stream << "Program expects between " << (MinArgCount - 1) << " and " << (MaxArgCount - 1) << " arguments, " << (argCount - 1) << " provided"; return Exception(stream.str()); } Exception Exception::InvalidKeyLength(const std::string &key) { std::stringstream stream; stream << "Key \"" << key << "\" with length " << key.length() << " is either empty, or too long.\n" << "Maximum allowed key length is " << MaximumKeyLength; return Exception(stream.str()); } Exception Exception::InvalidOption(const std::string &option) { std::stringstream stream; stream << "Invalid option " << option; return Exception(stream.str()); } }
22.478261
109
0.659574
xgallom
c5b8b2e00fb51bbfd63c63fbf4c6369b0eda6d02
764
cpp
C++
editor/ui/windows/sceneview/light.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
editor/ui/windows/sceneview/light.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
editor/ui/windows/sceneview/light.cpp
chokomancarr/chokoengine2
2825f2b95d24689f4731b096c8be39cc9a0f759a
[ "Apache-2.0" ]
null
null
null
#include "chokoeditor.hpp" CE_BEGIN_ED_NAMESPACE void EW_S_Light::Init() { EW_S_DrawCompList::funcs[(int)ComponentType::Light] = &Draw; EW_S_DrawCompList::activeFuncs[(int)ComponentType::Light] = &DrawActive; } void EW_S_Light::Draw(const Component& c, const Mat4x4& p) { } void EW_S_Light::DrawActive(const Component& c, const Mat4x4& p) { const auto& lht = static_cast<Light>(c); const auto& tr = lht->object()->transform(); switch (lht->type()) { case LightType::Point: { break; } case LightType::Spot: { const auto& p1 = tr->worldPosition(); const auto& fw = tr->forward(); UI::W::Line(p1 + fw * lht->radius(), p1 + fw * lht->distance(), Color::white()); break; } case LightType::Directional: { break; } } } CE_END_ED_NAMESPACE
21.222222
82
0.676702
chokomancarr
c5bb650b6b79f65a7f578b14a57e6aa4af27d794
2,350
cpp
C++
CppMisc/SrcOld/002-fibonacci.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
CppMisc/SrcOld/002-fibonacci.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
CppMisc/SrcOld/002-fibonacci.cpp
Ginkgo-Biloba/Cpp-Repo1-VS
231c68a055e6bf69a3f7c224e7c0182b67ce5b67
[ "Apache-2.0" ]
null
null
null
#include <ctime> #include <cstdio> typedef unsigned long long ullong; void timeit(ullong(*func)(ullong), char const* info) { clock_t start = clock(); ullong r, s = 0ull; // n 纯粹为了计时故意调大,反正溢出了结果也肯定一样 ullong n = 0xffffull; unsigned it = 0xffffu; // += 是防止直接赋值循环被优化掉;后面的输出是为了防止优化掉 s for (unsigned u = 0u; u < it; ++u) s += func(n); r = func(n); clock_t stop = clock(); printf("%10s(%llu) = %llu (s = %llu) | clock = %d\n", \ info, n, r, s, (int)(stop - start)); } /* O(N) 64 位无符号也只能算到 93 项 12200160415121876738 */ ullong fibonacci(ullong n) { ullong fkm1 = 1ull, fk = 0ull; // F(-1) = 1, F(0) = 0 for (; n; --n) { ullong fkp1 = fkm1 + fk; fkm1 = fk; fk = fkp1; } return fk; } /** O(log2(N)) 因为掺杂了矩阵乘法,所以常数系数大 * 就代码里来说,16 次乘法和 8 次加法避免不了 * [1 1]^n = [f(n + 1) f(n) ] * [1 0] [f(n) f(n - 1)] */ ullong fibMatrix(ullong n) { ullong A[4] = { 1ull, 1ull, 1ull, 0ull }; // n = 1,底数 ullong B[4] = { 1ull, 0ull, 0ull, 1ull }; // n = 0 for (; n; n >>= 1) { ullong C[4]; if (n & 1ull) // r *= x; { C[0] = B[0] * A[0] + B[1] * A[2]; C[1] = B[0] * A[1] + B[1] * A[3]; C[2] = B[2] * A[0] + B[3] * A[2]; C[3] = B[2] * A[1] + B[3] * A[3]; B[0] = C[0]; B[1] = C[1]; B[2] = C[2]; B[3] = C[3]; } // x *= x,其实最后一个循环可以算这个的 C[0] = A[0] * A[0] + A[1] * A[2]; C[1] = A[0] * A[1] + A[1] * A[3]; C[2] = A[2] * A[0] + A[3] * A[2]; C[3] = A[2] * A[1] + A[3] * A[3]; A[0] = C[0]; A[1] = C[1]; A[2] = C[2]; A[3] = C[3]; } return B[1]; } /** O(log2(N))倍数公式,跟矩阵方法差不多,常数小 * F(2n - 1) = F(n)^2 + F(n - 1)^2 * F(2n) = (F(n - 1) + F(n + 1)) * F(n) = (2F(n - 1) + F(n)) * F(n) */ ullong fibShift(ullong n) { // 找到最左边那个 1 ullong mask = 1ull << (sizeof(ullong) * 8 - 1); while (!(mask & n) && mask) mask >>= 1; // f(k), f(k - 1). k = 0, F(-1) = 1 ullong fkm1 = 1ull, fk = 0ull; for (; mask; mask >>= 1) { ullong f2km1 = fk * fk + fkm1 * fkm1; ullong f2k = (fkm1 + fkm1 + fk) * fk; if (mask & n) { fk = f2k + f2km1; // 2k + 1 fkm1 = f2k; } else { fk = f2k; // 2k fkm1 = f2km1; } } return fk; } int main() { /* 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765... */ timeit(fibonacci, "fibonacci"); timeit(fibMatrix, "fibMatrix"); timeit(fibShift, "fibShift"); for (ullong n = 1ull; n--;) printf("fib(%2llu) = %llu\n", n, fibShift(n)); }
22.169811
78
0.488511
Ginkgo-Biloba
c5bf3d264367627720709b6232fc1980890a8aa5
1,045
cpp
C++
Data Structures/TRIE.cpp
FreeJ99/Algorithms
d8364e1107e702aec0b4055b0d52130e64ddc386
[ "MIT" ]
null
null
null
Data Structures/TRIE.cpp
FreeJ99/Algorithms
d8364e1107e702aec0b4055b0d52130e64ddc386
[ "MIT" ]
null
null
null
Data Structures/TRIE.cpp
FreeJ99/Algorithms
d8364e1107e702aec0b4055b0d52130e64ddc386
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<unordered_map> using namespace std; struct Node{ bool leaf; unordered_map<char, Node*> chd; Node(): leaf(false){} }; void insert(Node* root, string s, int idx){ if(idx == s.size()){ root->leaf = true; } else{ if(root->chd[s[idx]] == NULL) root->chd[s[idx]] = new Node(); insert(root->chd[s[idx]], s, idx+1); } } bool find(Node* root, string s, int idx){ if(idx == s.size()){ return root->leaf; } if(root->chd[s[idx]] == NULL) return false; return find(root->chd[s[idx]], s, idx+1); } int main(){ Node* trie = new Node(); insert(trie, "abc", 0); insert(trie, "abd", 0); insert(trie, "def", 0); insert(trie, "dag", 0); cout<< find(trie, "abc", 0) << endl; cout<< find(trie, "abd", 0) << endl; cout<< find(trie, "def", 0) << endl; cout<< find(trie, "dag", 0) << endl; cout<< find(trie, "abv", 0) << endl; cout<< find(trie, "art", 0) << endl; return 0; }
22.234043
45
0.522488
FreeJ99
c5c035dee395ffffc3b65c7d297f7df0d532c2fd
12,042
hpp
C++
src/mechanics_model.hpp
StopkaKris/ExaConstit
fecf8b5d0d97946e29244360c3bc538c3efb433a
[ "BSD-3-Clause" ]
16
2019-10-11T17:03:20.000Z
2021-11-17T14:09:47.000Z
src/mechanics_model.hpp
Leonidas-Z/ExaConstit
0ab293cb6543b97eabde99e3ab43c1e921258ae4
[ "BSD-3-Clause" ]
41
2020-01-29T04:40:16.000Z
2022-03-11T16:59:31.000Z
src/mechanics_model.hpp
Leonidas-Z/ExaConstit
0ab293cb6543b97eabde99e3ab43c1e921258ae4
[ "BSD-3-Clause" ]
7
2019-10-12T02:00:58.000Z
2022-03-10T04:09:35.000Z
#ifndef MECHANICS_MODEL #define MECHANICS_MODEL #include "mfem.hpp" #include <utility> #include <unordered_map> #include <string> /// free function to compute the beginning step deformation gradient to store /// on a quadrature function void computeDefGrad(mfem::QuadratureFunction *qf, mfem::ParFiniteElementSpace *fes, mfem::Vector &x0); class ExaModel { public: int numProps; int numStateVars; bool init_step = false; protected: double dt, t; // -------------------------------------------------------------------------- // The velocity method requires us to retain both the beggining and end time step // coordinates of the mesh. We need these to be able to compute the correct // incremental deformation gradient (using the beg. time step coords) and the // velocity gradient (uses the end time step coords). mfem::ParGridFunction* beg_coords; mfem::ParGridFunction* end_coords; // --------------------------------------------------------------------------- // STATE VARIABLES and PROPS common to all user defined models // The beginning step stress and the end step (or incrementally upated) stress mfem::QuadratureFunction *stress0; mfem::QuadratureFunction *stress1; // The updated material tangent stiffness matrix, which will need to be // stored after an EvalP call and used in a later AssembleH call mfem::QuadratureFunction *matGrad; // quadrature vector function coefficients for any history variables at the // beginning of the step and end (or incrementally updated) step. mfem::QuadratureFunction *matVars0; mfem::QuadratureFunction *matVars1; // Stores the von Mises / hydrostatic scalar stress measure // we use this array to compute both the hydro and von Mises stress quantities mfem::QuadratureFunction *vonMises; // add vector for material properties, which will be populated based on the // requirements of the user defined model. The properties are expected to be // the same at all quadrature points. That is, the material properties are // constant and not dependent on space mfem::Vector *matProps; bool PA; // Temporary fix just to make sure things work mfem::Vector matGradPA; std::unordered_map<std::string, std::pair<int, int> > qf_mapping; // --------------------------------------------------------------------------- public: ExaModel(mfem::QuadratureFunction *q_stress0, mfem::QuadratureFunction *q_stress1, mfem::QuadratureFunction *q_matGrad, mfem::QuadratureFunction *q_matVars0, mfem::QuadratureFunction *q_matVars1, mfem::ParGridFunction* _beg_coords, mfem::ParGridFunction* _end_coords, mfem::Vector *props, int nProps, int nStateVars, bool _PA) : numProps(nProps), numStateVars(nStateVars), beg_coords(_beg_coords), end_coords(_end_coords), stress0(q_stress0), stress1(q_stress1), matGrad(q_matGrad), matVars0(q_matVars0), matVars1(q_matVars1), matProps(props), PA(_PA) { if (_PA) { int npts = q_matGrad->Size() / q_matGrad->GetVDim(); matGradPA.SetSize(81 * npts, mfem::Device::GetMemoryType()); matGradPA.UseDevice(true); } } virtual ~ExaModel() { } /// This function is used in generating the B matrix commonly seen in the formation of /// the material tangent stiffness matrix in mechanics [B^t][Cstiff][B] virtual void GenerateGradMatrix(const mfem::DenseMatrix& DS, mfem::DenseMatrix& B); /// This function is used in generating the Bbar matrix seen in the formation of /// the material tangent stiffness matrix in mechanics [B^t][Cstiff][B] for /// incompressible materials virtual void GenerateGradBarMatrix(const mfem::DenseMatrix& DS, const mfem::DenseMatrix& eDS, mfem::DenseMatrix& B); /// This function is used in generating the B matrix that's used in the formation /// of the geometric stiffness contribution of the stiffness matrix seen in mechanics /// as [B^t][sigma][B] virtual void GenerateGradGeomMatrix(const mfem::DenseMatrix& DS, mfem::DenseMatrix& Bgeom); /** @brief This function is responsible for running the entire model and will be the * external function that other classes/people can call. * * It will consist of 3 stages/kernels: * 1.) A set-up kernel/stage that computes all of the needed values for the material model * 2.) A kernel that runs the material model (an t = 0 version of this will exist as well) * 3.) A post-processing kernel/stage that does everything after the kernel * e.g. All of the data is put back into the correct format here and re-arranged as needed * By having this function, we only need to ever right one integrator for everything. * It also allows us to run these models on the GPU even if the rest of the assembly operation * can't be there yet. If UMATs are used then these operations won't occur on the GPU. * * We'll need to supply the number of quadrature pts, number of elements, the dimension * of the space we're working with, the number of nodes for an element, the jacobian associated * with the transformation from the reference element to the local element, the quadrature integration wts, * and the velocity field at the elemental level (space_dim * nnodes * nelems). */ virtual void ModelSetup(const int nqpts, const int nelems, const int space_dim, const int nnodes, const mfem::Vector &jacobian, const mfem::Vector &loc_grad, const mfem::Vector &vel) = 0; /// routine to update the beginning step deformation gradient. This must /// be written by a model class extension to update whatever else /// may be required for that particular model virtual void UpdateModelVars() = 0; /// set time on the base model class void SetModelTime(const double time) { t = time; } /// set delta timestep on the base model class void SetModelDt(const double dtime) { dt = dtime; } /// Get delta timestep on the base model class double GetModelDt() { return dt; } /// return a pointer to beginning step stress. This is used for output visualization mfem::QuadratureFunction *GetStress0() { return stress0; } /// return a pointer to beginning step stress. This is used for output visualization mfem::QuadratureFunction *GetStress1() { return stress1; } /// function to set the internal von Mises QuadratureFuntion pointer to some /// outside source void setVonMisesPtr(mfem::QuadratureFunction* vm_ptr) { vonMises = vm_ptr; } /// return a pointer to von Mises stress quadrature function for visualization mfem::QuadratureFunction *GetVonMises() { return vonMises; } /// return a pointer to the matVars0 quadrature function mfem::QuadratureFunction *GetMatVars0() { return matVars0; } /// return a pointer to the matGrad quadrature function mfem::QuadratureFunction *GetMatGrad() { return matGrad; } /// return a pointer to the matProps vector mfem::Vector *GetMatProps() { return matProps; } /// routine to get element stress at ip point. These are the six components of /// the symmetric Cauchy stress where standard Voigt notation is being used void GetElementStress(const int elID, const int ipNum, bool beginStep, double* stress, int numComps); /// set the components of the member function end stress quadrature function with /// the updated stress void SetElementStress(const int elID, const int ipNum, bool beginStep, double* stress, int numComps); /// routine to get the element statevars at ip point. void GetElementStateVars(const int elID, const int ipNum, bool beginStep, double* stateVars, int numComps); /// routine to set the element statevars at ip point void SetElementStateVars(const int elID, const int ipNum, bool beginStep, double* stateVars, int numComps); /// routine to get the material properties data from the decorated mfem vector void GetMatProps(double* props); /// setter for the material properties data on the user defined model object void SetMatProps(double* props, int size); /// routine to set the material Jacobian for this element and integration point. void SetElementMatGrad(const int elID, const int ipNum, double* grad, int numComps); /// routine to get the material Jacobian for this element and integration point void GetElementMatGrad(const int elId, const int ipNum, double* grad, int numComps); /// routine to update beginning step stress with end step values void UpdateStress(); /// routine to update beginning step state variables with end step values void UpdateStateVars(); /// Update the End Coordinates using a simple Forward Euler Integration scheme /// The beggining time step coordinates should be updated outside of the model routines void UpdateEndCoords(const mfem::Vector& vel); /// This method performs a fast approximate polar decomposition for 3x3 matrices /// The deformation gradient or 3x3 matrix of interest to be decomposed is passed /// in as the initial R matrix. The error on the solution can be set by the user. void CalcPolarDecompDefGrad(mfem::DenseMatrix& R, mfem::DenseMatrix& U, mfem::DenseMatrix& V, double err = 1e-12); /// Lagrangian is simply E = 1/2(F^tF - I) void CalcLagrangianStrain(mfem::DenseMatrix& E, const mfem::DenseMatrix &F); /// Eulerian is simply e = 1/2(I - F^(-t)F^(-1)) void CalcEulerianStrain(mfem::DenseMatrix& E, const mfem::DenseMatrix &F); /// Biot strain is simply B = U - I void CalcBiotStrain(mfem::DenseMatrix& E, const mfem::DenseMatrix &F); /// Log strain is equal to e = 1/2 * ln(C) or for UMATs its e = 1/2 * ln(B) void CalcLogStrain(mfem::DenseMatrix& E, const mfem::DenseMatrix &F); /// Converts a unit quaternion over to rotation matrix void Quat2RMat(const mfem::Vector& quat, mfem::DenseMatrix& rmat); /// Converts a rotation matrix over to a unit quaternion void RMat2Quat(const mfem::DenseMatrix& rmat, mfem::Vector& quat); /// Returns a pointer to our 4D material tangent stiffness tensor const double *GetMTanData(){ return matGradPA.Read(); } /// Converts a normal 2D stiffness tensor into it's equivalent 4D stiffness /// tensor void TransformMatGradTo4D(); /// This method sets the end time step stress to the beginning step /// and then returns the internal data pointer of the end time step /// array. double* StressSetup(); /// This methods set the end time step state variable array to the /// beginning time step values and then returns the internal data pointer /// of the end time step array. double* StateVarsSetup(); /// This function calculates the plastic strain rate tensor (D^p) with /// a DpMat that's a full 3x3 matrix rather than a 6-dim vector just so /// we can re-use storage from the deformation gradient tensor. virtual void calcDpMat(mfem::QuadratureFunction &DpMat) const = 0; /// Returns an unordered map that maps a given variable name to its /// its location and length within the state variable variable. const std::unordered_map<std::string, std::pair<int, int> > *GetQFMapping() { return &qf_mapping; } }; #endif
46.674419
122
0.66102
StopkaKris
c5c31a6215118d04f3e7655eadd9e8229e66be39
2,424
cpp
C++
Practice/2018/2018.11.2/Luogu3962.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2018/2018.11.2/Luogu3962.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2018/2018.11.2/Luogu3962.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; #define ll long long #define mem(Arr,x) memset(Arr,x,sizeof(Arr)) #define lson (now<<1) #define rson (lson|1) const int maxN=101000; const int SS=(1<<10)-1; const int inf=2147483647; class SegmentData { public: int lkey,rkey,key; int sum; }; int n; int Seq[maxN]; SegmentData S[maxN<<2]; SegmentData operator + (const SegmentData A,const SegmentData B); void Build(int now,int l,int r); SegmentData Query(int now,int l,int r,int ql,int qr); int main(){ scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d",&Seq[i]),Seq[i]=(Seq[i]-1)%9+1; //for (int i=1;i<=n;i++) cout<<Seq[i]<<" ";cout<<endl; Build(1,1,n); int Q;scanf("%d",&Q); while (Q--){ int l,r;scanf("%d%d",&l,&r); //cout<<"Q:"<<l<<" "<<r<<endl; SegmentData R=Query(1,1,n,l,r); int cnt=0; for (int i=9;(i>=0)&&(cnt<5);i--) if (R.key&(1<<i)){ printf("%d ",i);++cnt; } while (cnt<5) printf("-1 "),++cnt; printf("\n"); } return 0; } SegmentData operator + (const SegmentData A,const SegmentData B){ SegmentData r;r.lkey=A.lkey;r.rkey=B.rkey;r.key=A.key|B.key;r.sum=(A.sum+B.sum-1)%9+1; //cout<<r.key<<endl; for (int i=0;i<=9;i++) if (A.rkey&(1<<i)){ r.key|=((B.lkey<<i)&SS); if (i) r.key|=((((B.lkey>>(9-i))&SS)>>1)<<1); } //cout<<r.lkey<<" "<<A.lkey<<" "<<((A.lkey<<B.sum)&SS)<<" "<<((A.lkey>>(9-B.sum))&SS)<<endl; r.lkey|=((B.lkey<<A.sum)&SS); r.lkey|=((((B.lkey>>(9-A.sum))&SS)>>1)<<1); //cout<<r.lkey<<endl; r.rkey|=((A.rkey<<B.sum)&SS); r.rkey|=((((A.rkey>>(9-B.sum))&SS)>>1)<<1); //cout<<r.key<<endl; r.key|=r.lkey|r.rkey; //cout<<"Merge:["<<A.lkey<<" "<<A.rkey<<" "<<A.key<<" "<<A.sum<<"] ["<<B.lkey<<" "<<B.rkey<<" "<<B.key<<" "<<B.sum<<"] ["<<r.lkey<<" "<<r.rkey<<" "<<r.key<<" "<<r.sum<<"]"<<endl; return r; } void Build(int now,int l,int r){ if (l==r){ S[now].lkey=S[now].rkey=S[now].key=(1<<Seq[l]); S[now].sum=Seq[l];return; } int mid=(l+r)>>1; Build(lson,l,mid);Build(rson,mid+1,r); S[now]=S[lson]+S[rson];return; } SegmentData Query(int now,int l,int r,int ql,int qr){ //cout<<"["<<l<<","<<r<<"]"<<endl; if ((l==ql)&&(r==qr)) return S[now]; int mid=(l+r)>>1; if (qr<=mid) return Query(lson,l,mid,ql,qr); else if (ql>=mid+1) return Query(rson,mid+1,r,ql,qr); else return Query(lson,l,mid,ql,mid)+Query(rson,mid+1,r,mid+1,qr); } /* 10 4 1 9 9 5 5 4 4 7 7 1 4 7 //*/
24.989691
179
0.560644
SYCstudio
c5c5ed2eebcc56d6b9c04051215eb73a824b79ae
762
cpp
C++
dumb_kernel.cpp
rioyokotalab/scala20-artifact
2a438f1fec4f9963d44181578f87c703a5bd4016
[ "BSD-3-Clause" ]
1
2021-06-10T01:11:55.000Z
2021-06-10T01:11:55.000Z
dumb_kernel.cpp
rioyokotalab/scala20-artifact
2a438f1fec4f9963d44181578f87c703a5bd4016
[ "BSD-3-Clause" ]
null
null
null
dumb_kernel.cpp
rioyokotalab/scala20-artifact
2a438f1fec4f9963d44181578f87c703a5bd4016
[ "BSD-3-Clause" ]
null
null
null
#include "utils.hpp" void dumb_kernel(double *GXYb, int mc, int nc, int xc, int yc, int mb, int nb, double * packA_V, double * packB_S, double *packB_U, double *packA_S) { double cmn, exn; for (int mi = 0; mi < B_SIZE; ++mi) { for (int ni = 0; ni < B_SIZE; ++ni) { for (int ki = 0; ki < K_SIZE; ++ki) { for (int xi = 0; xi < B_SIZE; ++xi) { for (int yi = 0; yi < B_SIZE; ++yi) { cmn = packA_V[(mc * block_size + mi) + ki * VEC_SIZE] * packB_U[ki * VEC_SIZE + nb + nc + ni]; exn = packA_S[(mi + mc + mb) * VEC_SIZE + (xc + xi) ] * cmn; GXYb[(xc + xi) * LDA_S + yc + yi] += exn * packB_S[nc + ni * VEC_SIZE + (yc + yi)]; } } } } } }
34.636364
96
0.472441
rioyokotalab
c5c7b40f5fc1e12a15e2b359e6552cfa5cae6088
10,416
cpp
C++
xlib/Drawing.cpp
X547/xlibe
fbab795ad8a86503174ecfcb8603ec868537d069
[ "MIT" ]
1
2022-01-02T16:10:26.000Z
2022-01-02T16:10:26.000Z
xlib/Drawing.cpp
X547/xlibe
fbab795ad8a86503174ecfcb8603ec868537d069
[ "MIT" ]
null
null
null
xlib/Drawing.cpp
X547/xlibe
fbab795ad8a86503174ecfcb8603ec868537d069
[ "MIT" ]
null
null
null
/* * Copyright 2003, Shibukawa Yoshiki. All rights reserved. * Copyright 2003, kazuyakt. All rights reserved. * Copyright 2021, Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT license. */ #include "Drawing.h" #include <interface/Bitmap.h> #include <interface/Polygon.h> #include "Drawables.h" #include "Font.h" #include "GC.h" extern "C" { #include <X11/Xlib.h> #include <X11/Xlibint.h> } #include "Debug.h" static pattern pattern_for(GC gc) { pattern ptn; switch (gc->values.fill_style) { default: case FillSolid: ptn = B_SOLID_HIGH; break; case FillTiled: case FillStippled: // TODO: proper implementation? case FillOpaqueStippled: ptn = B_MIXED_COLORS; break; } return ptn; } extern "C" int XDrawLine(Display *display, Drawable w, GC gc, int x1, int y1, int x2, int y2) { XSegment seg; seg.x1 = x1; seg.y1 = y1; seg.x2 = x2; seg.y2 = y2; return XDrawSegments(display, w, gc, &seg, 1); } extern "C" int XDrawSegments(Display *display, Drawable w, GC gc, XSegment *segments, int ns) { XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); for(int i = 0; i < ns; i++) { BPoint point1(segments[i].x1, segments[i].y1); BPoint point2(segments[i].x2, segments[i].y2); view->StrokeLine(point1, point2, pattern_for(gc)); } view->UnlockLooper(); return 0; } extern "C" int XDrawLines(Display *display, Drawable w, GC gc, XPoint *points, int np, int mode) { int i; short wx, wy; wx = 0; wy = 0; XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); switch( mode ) { case CoordModeOrigin : for( i=0; i<(np-1); i++ ) { BPoint point1(points[i].x, points[i].y); BPoint point2(points[i+1].x, points[i+1].y); view->StrokeLine(point1, point2, pattern_for(gc)); } break; case CoordModePrevious: for( i=0; i<np; i++ ) { if ( i==0 ) { wx = wx + points[i].x; wy = wy + points[i].y; BPoint point1( wx, wy ); BPoint point2( wx, wy ); view->StrokeLine(point1, point2, pattern_for(gc)); } else { BPoint point3( wx, wy ); wx = wx + points[i].x; wy = wy + points[i].y; BPoint point4( wx, wy ); view->StrokeLine(point3, point4, pattern_for(gc)); } } break; } view->UnlockLooper(); return 0; } extern "C" int XDrawRectangle(Display *display, Drawable w, GC gc, int x,int y, unsigned int width, unsigned int height) { XRectangle rect; rect.x = x; rect.y = y; rect.width = width; rect.height = height; return XDrawRectangles(display, w, gc, &rect, 1); } extern "C" int XDrawRectangles(Display *display, Drawable w, GC gc, XRectangle *rect, int n) { XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); for (int i = 0; i < n; i++) { view->StrokeRect(brect_from_xrect(rect[i]), pattern_for(gc)); } view->UnlockLooper(); return 0; } extern "C" int XFillRectangle(Display *display, Drawable win, GC gc, int x, int y, unsigned int w, unsigned int h) { XRectangle rect; rect.x = x; rect.y = y; rect.width = w; rect.height = h; return XFillRectangles(display, win, gc, &rect, 1); } extern "C" int XFillRectangles(Display *display, Drawable w, GC gc, XRectangle *rect, int n) { XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); for (int i = 0; i < n; i++) { view->FillRect(brect_from_xrect(rect[i]), pattern_for(gc)); } view->UnlockLooper(); return 0; } extern "C" int XDrawArc(Display *display, Drawable w, GC gc, int x, int y, unsigned int width,unsigned height, int a1, int a2) { XArc arc; arc.x = x; arc.y = y; arc.width = width; arc.height = height; arc.angle1 = a1; arc.angle2 = a2; return XDrawArcs(display, w, gc, &arc, 1); } extern "C" int XDrawArcs(Display *display, Drawable w, GC gc, XArc *arc, int n) { // FIXME: Take arc_mode into account! XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); for (int i = 0; i < n; i++) { view->StrokeArc(brect_from_xrect(make_xrect(arc[i].x, arc[i].y, arc[i].width, arc[i].height)), ((float)arc[i].angle1) / 64, ((float)arc[i].angle2) / 64, pattern_for(gc)); } view->UnlockLooper(); return 0; } extern "C" int XFillArc(Display *display, Drawable w, GC gc, int x, int y, unsigned int width, unsigned height, int a1, int a2) { XArc arc; arc.x = x; arc.y = y; arc.width = width; arc.height = height; arc.angle1 = a1; arc.angle2 = a2; return XFillArcs(display, w, gc, &arc, 1); } extern "C" int XFillArcs(Display *display, Drawable w, GC gc, XArc *arc, int n) { // FIXME: Take arc_mode into account! XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); for (int i = 0; i < n; i++) { view->FillArc(brect_from_xrect(make_xrect(arc[i].x, arc[i].y, arc[i].width, arc[i].height)), ((float)arc[i].angle1) / 64.0f, ((float)arc[i].angle2) / 64.0f, pattern_for(gc)); } view->UnlockLooper(); return 0; } extern "C" int XFillPolygon(Display *display, Drawable w, GC gc, XPoint *points, int npoints, int shape, int mode) { BPolygon polygon; switch (mode) { case CoordModeOrigin : for(int i = 0; i < npoints; i++) { BPoint point(points[i].x, points[i].y); polygon.AddPoints(&point, 1); } break; case CoordModePrevious: { int wx = 0, wy = 0; for(int i = 0; i < npoints; i++) { wx = wx + points[i].x; wy = wy + points[i].y; BPoint point(wx, wy); polygon.AddPoints(&point, 1); } break; } } XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); view->FillPolygon(&polygon, pattern_for(gc)); view->UnlockLooper(); return 0; } extern "C" int XDrawPoint(Display *display, Drawable w, GC gc, int x, int y) { XPoint point; point.x = x; point.y = y; return XDrawPoints(display, w, gc, &point, 1, CoordModeOrigin); } extern "C" int XDrawPoints(Display *display, Drawable w, GC gc, XPoint* points, int n, int mode) { XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); view->PushState(); view->SetPenSize(1); switch (mode) { case CoordModeOrigin : for (int i = 0; i < n; i++) { BPoint point(points[i].x, points[i].y); view->StrokeLine(point, point, pattern_for(gc)); } break; case CoordModePrevious: { short wx = 0, wy = 0; for (int i = 0; i < n; i++) { wx = wx + points[i].x; wy = wy + points[i].y; BPoint point( wx, wy ); view->StrokeLine(point, point, pattern_for(gc)); } break; } } view->PopState(); view->UnlockLooper(); return 0; } extern "C" int XCopyArea(Display* display, Drawable src, Drawable dest, GC gc, int src_x, int src_y, unsigned int width, unsigned int height, int dest_x, int dest_y) { XDrawable* src_d = Drawables::get(src); XDrawable* dest_d = Drawables::get(dest); if (!src_d || !dest_d) return BadDrawable; const BRect src_rect = brect_from_xrect(make_xrect(src_x, src_y, width, height)); const BRect dest_rect = brect_from_xrect(make_xrect(dest_x, dest_y, width, height)); if (src_d == dest_d) { src_d->view()->LockLooper(); bex_check_gc(src_d, gc); src_d->view()->CopyBits(src_rect, dest_rect); src_d->view()->UnlockLooper(); return Success; } XPixmap* src_pxm = dynamic_cast<XPixmap*>(src_d); if (src_pxm) { src_pxm->sync(); dest_d->view()->LockLooper(); bex_check_gc(dest_d, gc); dest_d->view()->DrawBitmap(src_pxm->offscreen(), src_rect, dest_rect); dest_d->view()->UnlockLooper(); return Success; } // TODO? UNIMPLEMENTED(); return BadValue; } extern "C" int XCopyPlane(Display *display, Drawable src, Drawable dest, GC gc, int src_x, int src_y, unsigned int width, unsigned int height, int dest_x, int dest_y, unsigned long plane) { // TODO: Actually use "plane"! return XCopyArea(display, src, dest, gc, src_x, src_y, width, height, dest_x, dest_y); } extern "C" int XPutImage(Display *display, Drawable d, GC gc, XImage* image, int src_x, int src_y, int dest_x, int dest_y, unsigned int width, unsigned int height) { XDrawable* drawable = Drawables::get(d); if (!drawable) return BadDrawable; BBitmap* bbitmap = (BBitmap*)image->obdata; if (image->data != bbitmap->Bits()) { // We must import the bits before drawing. // TODO: Optimization: Import only the bits we are about to draw! bbitmap->ImportBits(image->data, image->height * image->bytes_per_line, image->bytes_per_line, image->xoffset, bbitmap->ColorSpace()); } BView* view = drawable->view(); view->LockLooper(); bex_check_gc(drawable, gc); view->DrawBitmap(bbitmap, brect_from_xrect(make_xrect(src_x, src_y, width, height)), brect_from_xrect(make_xrect(dest_x, dest_y, width, height))); view->UnlockLooper(); return Success; } extern "C" void Xutf8DrawString(Display *display, Drawable w, XFontSet set, GC gc, int x, int y, const char* str, int len) { // FIXME: Use provided fonts! XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); view->DrawString(str, len, BPoint(x, y)); view->UnlockLooper(); } extern "C" int XDrawString(Display* display, Drawable w, GC gc, int x, int y, const char* str, int len) { Xutf8DrawString(display, w, NULL, gc, x, y, str, len); return 0; } extern "C" void Xutf8DrawImageString(Display *display, Drawable w, XFontSet set, GC gc, int x, int y, const char* str, int len) { Xutf8DrawString(display, w, set, gc, x, y, str, len); } extern "C" int XDrawImageString(Display *display, Drawable w, GC gc, int x, int y, const char* str, int len) { return XDrawString(display, w, gc, x, y, str, len); } extern "C" int XDrawText(Display *display, Drawable w, GC gc, int x, int y, XTextItem* items, int count) { XDrawable* window = Drawables::get(w); BView* view = window->view(); view->LockLooper(); bex_check_gc(window, gc); view->PushState(); for (int i = 0; i < count; i++) { if (items[i].font != None) { BFont font = bfont_from_font(items[i].font); view->SetFont(&font); } view->DrawString(items[i].chars, items[i].nchars, BPoint(x, y)); x += view->StringWidth(items[i].chars, items[i].nchars); x += items[i].delta; } view->PopState(); view->UnlockLooper(); return 0; }
24.223256
106
0.66225
X547
c5c83e5489bc07df68ab6b618831b6c3ad512abc
188
cpp
C++
src/backends/windows/has_last_error.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/windows/has_last_error.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
src/backends/windows/has_last_error.cpp
freundlich/libawl
0d51f388a6b662373058cb51a24ef25ed826fa0f
[ "BSL-1.0" ]
null
null
null
#include <awl/backends/windows/has_last_error.hpp> #include <awl/backends/windows/windows.hpp> bool awl::backends::windows::has_last_error() { return ::GetLastError() != ERROR_SUCCESS; }
37.6
91
0.765957
freundlich
c5ca729a61faf3428f30752fc18548673c8ddfdd
18,824
cc
C++
src/buffers.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
src/buffers.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
src/buffers.cc
klantz81/feature-detection
1ed289711128a30648e198b085534fe9a9610984
[ "MIT" ]
null
null
null
#include "buffers.h" // cFloatBuffer ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// cFloatBuffer::cFloatBuffer() : width(0), height(0), buffer(0) { } cFloatBuffer::cFloatBuffer(int width, int height) : width(width), height(height) { this->buffer = new float[this->width*this->height]; for (int i = 0; i < this->width * this->height; i++) this->buffer[i] = 0.0f; } cFloatBuffer::~cFloatBuffer() { if (this->buffer) delete [] buffer; } cFloatBuffer& cFloatBuffer::operator=(const cFloatBuffer& buffer) { if (this->width != buffer.width || this->height != buffer.height) { this->width = buffer.width; this->height = buffer.height; if (this->buffer) delete [] this->buffer; this->buffer = new float[this->width*this->height]; } for (int i = 0; i < this->width * this->height; i++) this->buffer[i] = buffer.buffer[i]; return *this; } // cDoubleBuffer ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int cDoubleBuffer::save_index = 0; cDoubleBuffer::cDoubleBuffer() : width(0), height(0), buffer(0) { } cDoubleBuffer::cDoubleBuffer(int width, int height) : width(width), height(height) { this->buffer = new double[this->width*this->height]; for (int i = 0; i < this->width * this->height; i++) this->buffer[i] = 0.0; } cDoubleBuffer::cDoubleBuffer(const cDoubleBuffer& buffer) : width(buffer.width), height(buffer.height), buffer(0) { this->buffer = new double[this->width*this->height]; for (int i = 0; i < this->width*this->height; i++) this->buffer[i] = buffer.buffer[i]; } cDoubleBuffer::~cDoubleBuffer() { if (this->buffer) delete [] buffer; } cDoubleBuffer& cDoubleBuffer::operator=(const cDoubleBuffer& buffer) { if (this->width != buffer.width || this->height != buffer.height) { this->width = buffer.width; this->height = buffer.height; if (this->buffer) delete [] this->buffer; this->buffer = new double[this->width*this->height]; } for (int i = 0; i < this->width * this->height; i++) this->buffer[i] = buffer.buffer[i]; return *this; } cFloatBuffer cDoubleBuffer::toFloat(float scale_factor) { cFloatBuffer buf(this->width, this->height); for (int i = 0; i < this->width * this->height; i++) buf.buffer[i] = (float)this->buffer[i] * scale_factor; return buf; } void cDoubleBuffer::save() { cDoubleBuffer::save_index++; std::stringstream s; s << "media_save/buffer" << (save_index < 10 ? "000" : (save_index < 100 ? "00" : (save_index < 1000 ? "0" : ""))) << save_index << ".pgm"; std::fstream of(s.str().c_str(), std::ios_base::out | std::ios_base::trunc); of << "P2" << std::endl; of << this->width << " " << this->height << std::endl; of << "255" << std::endl; for (int j = 0; j < this->height; j++) { for (int i = 0; i < this->width; i++) { int p = (int)(this->buffer[j * this->width + i] * 255.0); p = CLAMP(p, 0, 255); of << p << " "; } of << std::endl; } } void cDoubleBuffer::save(const char* file) { std::fstream of(file, std::ios_base::out | std::ios_base::trunc); of << "P2" << std::endl; of << this->width << " " << this->height << std::endl; of << "255" << std::endl; for (int j = 0; j < this->height; j++) { for (int i = 0; i < this->width; i++) { int p = (int)(this->buffer[j * this->width + i] * 255.0); p = CLAMP(p, 0, 255); of << p << " "; } of << std::endl; } } double cDoubleBuffer::operator[](int index) const { return (index >= 0 && index < this->width * this->height) ? this->buffer[index] : 0.0; } double cDoubleBuffer::at(int index) const { return (index >= 0 && index < this->width * this->height) ? this->buffer[index] : 0.0; } double cDoubleBuffer::at(int x, int y) const { int index = y * this->width + x; return (index >= 0 && index < this->width * this->height) ? this->buffer[index] : 0.0; } double cDoubleBuffer::interpolate(double x, double y) const { x = CLAMP(x, 0.000001, this->width - 1.000001); y = CLAMP(y, 0.000001, this->height - 1.000001); int x0 = (int)x, y0 = (int)y; double s0 = x - x0, s1 = y - y0; double t = this->buffer[(y0 + 0) * this->width + x0 + 0]*(1 - s0)*(1 - s1) + this->buffer[(y0 + 0) * this->width + x0 + 1]*( s0)*(1 - s1) + this->buffer[(y0 + 1) * this->width + x0 + 0]*(1 - s0)*( s1) + this->buffer[(y0 + 1) * this->width + x0 + 1]*( s0)*( s1); return t; } double cDoubleBuffer::sum(int x, int y, const cKernel& kernel) { double sum = 0.0; for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++) for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) sum += this->at(x + i, y + j); return sum; } cDoubleBuffer cDoubleBuffer::operator*(const cDoubleBuffer& buffer) { cDoubleBuffer buf(this->width, this->height); for (int i = 0; i < this->width * this->height; i++) buf.buffer[i] = this->buffer[i] * buffer.buffer[i]; return buf; } cDoubleBuffer cDoubleBuffer::magnitude(const cDoubleBuffer& buffer) { cDoubleBuffer buf(this->width, this->height); for (int i = 0; i < this->width * this->height; i++) buf.buffer[i] = sqrt(pow(this->buffer[i], 2.0) + pow(buffer.buffer[i], 2.0)); return buf; } cDoubleBuffer cDoubleBuffer::sub(int x, int y, const cKernel& kernel) const { cDoubleBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1); int index = 0; for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++) for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) buf.buffer[index++] = this->at(x + i, y + j); return buf; } cDoubleBuffer cDoubleBuffer::subInterpolate(double x, double y, const cKernel& kernel) const { cDoubleBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1); int index = 0; for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++) for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) buf.buffer[index++] = this->interpolate(x + i, y + j); return buf; } cDoubleBuffer cDoubleBuffer::subInterpolate(matrix22 A, vector2 b, const cKernel& kernel) const { cDoubleBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1); int index = 0; for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++) for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) { vector2 x = A * vector2(i, j) + b; buf.buffer[index++] = this->interpolate(x.x, x.y); } return buf; } cDoubleBuffer cDoubleBuffer::downsample() { cDoubleBuffer buf(this->width/2, this->height/2); for (int j = 0; j < this->height / 2; j++) for (int i = 0; i < this->width / 2; i++) buf.buffer[j * this->width / 2 + i] = 0.25 * this->buffer[j * 2 * this->width + i * 2] + 0.125 * ( (j > 0 ? this->buffer[(j - 1) * 2 * this->width + i * 2] : 0.0) + (j < this->height / 2 - 1 ? this->buffer[(j + 1) * 2 * this->width + i * 2] : 0.0) + (i > 0 ? this->buffer[j * 2 * this->width + (i - 1) * 2] : 0.0) + (i < this->width / 2 - 1 ? this->buffer[j * 2 * this->width + (i + 1) * 2] : 0.0) ) + 0.0625 * ( (j > 0 && i > 0 ? this->buffer[(j - 1) * 2 * this->width + (i - 1) * 2] : 0.0) + (j > 0 && i < this->width / 2 - 1 ? this->buffer[(j - 1) * 2 * this->width + (i + 1) * 2] : 0.0) + (j < this->height / 2 - 1 && i > 0 ? this->buffer[(j + 1) * 2 * this->width + (i - 1) * 2] : 0.0) + (j < this->height / 2 - 1 && i < this->width / 2 - 1 ? this->buffer[(j + 1) * 2 * this->width + (i + 1) * 2] : 0.0) ); return buf; } cDoubleBuffer cDoubleBuffer::scharrOperatorX() { cDoubleBuffer Ix(this->width, this->height); for (int j = 0; j < this->height; j++) for (int i = 0; i < this->width; i++) Ix.buffer[j * this->width + i] = (i > 0 ? ( (j > 0 ? this->buffer[(j - 1) * this->width + (i - 1)] * -3.0 : 0.0) + this->buffer[ j * this->width + (i - 1)] * -10.0 + (j < this->height - 1 ? this->buffer[(j + 1) * this->width + (i - 1)] * -3.0 : 0.0) ) : 0.0) + (i < this->width - 1 ? ( (j > 0 ? this->buffer[(j - 1) * this->width + (i + 1)] * 3.0 : 0.0) + this->buffer[ j * this->width + (i + 1)] * 10.0 + (j < this->height - 1 ? this->buffer[(j + 1) * this->width + (i + 1)] * 3.0 : 0.0) ) : 0.0); return Ix; } cDoubleBuffer cDoubleBuffer::scharrOperatorY() { cDoubleBuffer Iy(this->width, this->height); for (int j = 0; j < this->height; j++) for (int i = 0; i < this->width; i++) Iy.buffer[j * this->width + i] = (j > 0 ? ( (i > 0 ? this->buffer[(j - 1) * this->width + (i - 1)] * -3.0 : 0.0) + this->buffer[(j - 1) * this->width + i ] * -10.0 + (i < this->width - 1 ? this->buffer[(j - 1) * this->width + (i + 1)] * -3.0 : 0.0) ) : 0.0) + (j < this->height - 1 ? ( (i > 0 ? this->buffer[(j + 1) * this->width + (i - 1)] * 3.0 : 0.0) + this->buffer[(j + 1) * this->width + i ] * 10.0 + (i < this->width - 1 ? this->buffer[(j + 1) * this->width + (i + 1)] * 3.0 : 0.0) ) : 0.0); return Iy; } cDoubleBuffer cDoubleBuffer::scharrOperator() { cDoubleBuffer Ix = this->scharrOperatorX(); cDoubleBuffer Iy = this->scharrOperatorY(); cDoubleBuffer I(this->width, this->height); for (int i = 0; i < this->width * this->height; i++) I.buffer[i] = sqrt(Ix.buffer[i]*Ix.buffer[i] + Iy.buffer[i]*Iy.buffer[i]); return I; } cDoubleBuffer cDoubleBuffer::gaussianConvolutionX(const cKernel& kernel) { cDoubleBuffer buf(this->width, this->height); for (int j = 0; j < this->height; j++) for (int i = 0; i < this->width; i++) for (int k = -kernel.kernel_radius; k <= kernel.kernel_radius; k++) if (i + k >= 0 && i + k < this->width) buf.buffer[j * this->width + i] += this->buffer[j * this->width + i + k] * kernel.kernel[k + kernel.kernel_radius]; return buf; } cDoubleBuffer cDoubleBuffer::gaussianConvolutionY(const cKernel& kernel) { cDoubleBuffer buf(this->width, this->height); for (int j = 0; j < this->height; j++) for (int i = 0; i < this->width; i++) for (int k = -kernel.kernel_radius; k <= kernel.kernel_radius; k++) if (j + k >= 0 && j + k < this->height) buf.buffer[j * this->width + i] += this->buffer[(j + k) * this->width + i] * kernel.kernel[k + kernel.kernel_radius]; return buf; } cDoubleBuffer cDoubleBuffer::gaussianConvolution(const cKernel& kernel) { return (this->gaussianConvolutionX(kernel)).gaussianConvolutionY(kernel); } cDoubleBuffer cDoubleBuffer::gaussianConvolutionDX(const cKernel& kernel) { cDoubleBuffer buf(this->width, this->height); for (int j = 0; j < this->height; j++) for (int i = 0; i < this->width; i++) for (int k = -kernel.kernel_radius; k <= kernel.kernel_radius; k++) if (i + k >= 0 && i + k < this->width) buf.buffer[j * this->width + i] += this->buffer[j * this->width + i + k] * kernel.kernel_derivative[k + kernel.kernel_radius]; return buf; } cDoubleBuffer cDoubleBuffer::gaussianConvolutionDY(const cKernel& kernel) { cDoubleBuffer buf(this->width, this->height); for (int j = 0; j < this->height; j++) for (int i = 0; i < this->width; i++) for (int k = -kernel.kernel_radius; k <= kernel.kernel_radius; k++) if (j + k >= 0 && j + k < this->height) buf.buffer[j * this->width + i] += this->buffer[(j + k) * this->width + i] * kernel.kernel_derivative[k + kernel.kernel_radius]; return buf; } cDoubleBuffer cDoubleBuffer::gaussianDerivativeX(const cKernel& kernel) { return (this->gaussianConvolutionDX(kernel)).gaussianConvolutionY(kernel); } cDoubleBuffer cDoubleBuffer::gaussianDerivativeY(const cKernel& kernel) { return (this->gaussianConvolutionX(kernel)).gaussianConvolutionDY(kernel); } // cColorBuffer ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// int cColorBuffer::save_index = 0; cColorBuffer::cColorBuffer() : width(0), height(0), bpp(0), buffer(0) { } cColorBuffer::cColorBuffer(int width, int height, int bpp) : width(width), height(height), bpp(bpp) { this->buffer = new unsigned char[this->width*this->height*this->bpp]; for (int i = 0; i < this->width * this->height * this->bpp; i++) this->buffer[i] = 0; } cColorBuffer::cColorBuffer(const char* image) { SDL_Surface *s = IMG_Load(image); this->width = s->w; this->height = s->h; this->bpp = s->format->BitsPerPixel; this->buffer = new unsigned char[width * height * bpp / 8]; memcpy(buffer, s->pixels, width * height * bpp / 8); SDL_FreeSurface(s); } void cColorBuffer::save() { cColorBuffer::save_index++; std::stringstream s; s << "media_save/cbuffer" << (save_index < 10 ? "000" : (save_index < 100 ? "00" : (save_index < 1000 ? "0" : ""))) << save_index << ".ppm"; std::fstream of(s.str().c_str(), std::ios_base::out | std::ios_base::trunc); of << "P3" << std::endl; of << this->width << " " << this->height << std::endl; of << "255" << std::endl; for (int j = 0; j < this->height; j++) { for (int i = 0; i < this->width; i++) { int r = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 0]; r = CLAMP(r, 0, 255); int g = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 1]; g = CLAMP(g, 0, 255); int b = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 2]; b = CLAMP(b, 0, 255); of << r << " " << g << " " << b << " "; } of << std::endl; } } void cColorBuffer::save(const char* file) { std::fstream of(file, std::ios_base::out | std::ios_base::trunc); of << "P3" << std::endl; of << this->width << " " << this->height << std::endl; of << "255" << std::endl; for (int j = 0; j < this->height; j++) { for (int i = 0; i < this->width; i++) { int r = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 0]; r = CLAMP(r, 0, 255); int g = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 1]; g = CLAMP(g, 0, 255); int b = this->buffer[j * this->width * this->bpp/8 + i * this->bpp/8 + 2]; b = CLAMP(b, 0, 255); of << r << " " << g << " " << b << " "; } of << std::endl; } } _rgb cColorBuffer::at(int x, int y) const { int index = y * this->width * this->bpp/8 + x * this->bpp/8; _rgb rgb = {0,0,0}; if (index >= 0 && index < this->width * this->bpp / 8 * this->height - 2) { rgb.r = this->buffer[index + 0]; rgb.g = this->buffer[index + 1]; rgb.b = this->buffer[index + 2]; } return rgb; } _rgb cColorBuffer::interpolate(double x, double y) const { x = CLAMP(x, 0.000001, this->width - 1.000001); y = CLAMP(y, 0.000001, this->height - 1.000001); int x0 = (int)x, y0 = (int)y; double s0 = x - x0, s1 = y - y0; _rgb rgb = {0,0,0}; rgb.r = this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 0]*(1 - s0)*(1 - s1) + this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 0]*( s0)*(1 - s1) + this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 0]*(1 - s0)*( s1) + this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 0]*( s0)*( s1); rgb.g = this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 1]*(1 - s0)*(1 - s1) + this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 1]*( s0)*(1 - s1) + this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 1]*(1 - s0)*( s1) + this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 1]*( s0)*( s1); rgb.b = this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 2]*(1 - s0)*(1 - s1) + this->buffer[(y0 + 0) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 2]*( s0)*(1 - s1) + this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 0) * this->bpp/8 + 2]*(1 - s0)*( s1) + this->buffer[(y0 + 1) * this->width * this->bpp/8 + (x0 + 1) * this->bpp/8 + 2]*( s0)*( s1); return rgb; } cColorBuffer cColorBuffer::sub(int x, int y, const cKernel& kernel) const { cColorBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1, this->bpp); int index = 0; for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++) for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) { _rgb rgb = this->at(x + i, y + j); buf.buffer[index + 0] = rgb.r; buf.buffer[index + 1] = rgb.g; buf.buffer[index + 2] = rgb.b; index += buf.bpp / 8; } return buf; } cColorBuffer cColorBuffer::subInterpolate(double x, double y, const cKernel& kernel) const { cColorBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1, this->bpp); int index = 0; for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++) for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) { _rgb rgb = this->interpolate(x + i, y + j); buf.buffer[index + 0] = rgb.r; buf.buffer[index + 1] = rgb.g; buf.buffer[index + 2] = rgb.b; index += buf.bpp / 8; } return buf; } cColorBuffer cColorBuffer::subInterpolate(matrix22 A, vector2 b, const cKernel& kernel) const { cColorBuffer buf(kernel.kernel_radius * 2 + 1, kernel.kernel_radius * 2 + 1, this->bpp); int index = 0; for (int j = -kernel.kernel_radius; j <= kernel.kernel_radius; j++) for (int i = -kernel.kernel_radius; i <= kernel.kernel_radius; i++) { vector2 x = A * vector2(i, j) + b; _rgb rgb = this->interpolate(x.x, x.y); buf.buffer[index + 0] = rgb.r; buf.buffer[index + 1] = rgb.g; buf.buffer[index + 2] = rgb.b; index += buf.bpp / 8; } return buf; } cColorBuffer::~cColorBuffer() { if (this->buffer) delete [] buffer; } void cColorBuffer::load(const char* image) { SDL_Surface *s = IMG_Load(image); if (this->width != s->w || this->height != s->h || this->bpp != s->format->BitsPerPixel) { this->width = s->w; this->height = s->h; this->bpp = s->format->BitsPerPixel; if (this->buffer) delete [] this->buffer; this->buffer = new unsigned char[this->width*this->height*this->bpp]; } memcpy(this->buffer, s->pixels, this->width * this->height * this->bpp / 8); SDL_FreeSurface(s); } cDoubleBuffer cColorBuffer::grayscale() { cDoubleBuffer buf(this->width, this->height); for (int i = 0; i < this->width * this->height; i++) buf.buffer[i] = (this->buffer[i * this->bpp / 8 + 0] / 255.0 * 0.30 + this->buffer[i * this->bpp / 8 + 1] / 255.0 * 0.59 + this->buffer[i * this->bpp / 8 + 2] / 255.0 * 0.11); return buf; }
41.462555
259
0.562208
klantz81
c5cadfbc305bb5d1e535e8f8fcaa60d267412bdb
2,763
cpp
C++
overhead-detect/src/modules/view/ImageGridWindow.cpp
cn0512/PokeDetective
b2785350010a00391c1349046a78f7e27c3af564
[ "Apache-2.0" ]
null
null
null
overhead-detect/src/modules/view/ImageGridWindow.cpp
cn0512/PokeDetective
b2785350010a00391c1349046a78f7e27c3af564
[ "Apache-2.0" ]
null
null
null
overhead-detect/src/modules/view/ImageGridWindow.cpp
cn0512/PokeDetective
b2785350010a00391c1349046a78f7e27c3af564
[ "Apache-2.0" ]
null
null
null
#ifndef IMAGE_GRID_WINDOW_CPP #define IMAGE_GRID_WINDOW_CPP #include <assert.h> #include <string> #include <opencv2/opencv.hpp> #include "ImageGridCell.cpp" using namespace cv; class ImageGridWindow { private: String title; Size size; bool isVisible; int rows; int cols; vector<ImageGridCell> cells; ImageGridCell& cell(int i, int j) { return cells[i + j * rows]; } public: ImageGridWindow(String title, int rows = 1, int cols = 1) { this->title = title; this->isVisible = false; this->rows = rows; this->cols = cols; this->cells = vector<ImageGridCell>(rows * cols); } ImageGridWindow* setGridCellTitle(int i, int j, String title) { cell(i, j).setTitle(title); return this; } ImageGridWindow* setGridCellImage(int i, int j, Mat image) { cell(i, j).setImage(image); return this; } ImageGridWindow* setSize(int width, int height) { assert(!isVisible); size = Size(width, height); return this; } ImageGridWindow* addTrackbar(string name, int* value, int maxValue) { assert(isVisible); createTrackbar(name, title, value, maxValue); return this; } ImageGridWindow* show() { assert(!isVisible); namedWindow(title, WINDOW_NORMAL); resizeWindow(title, size.width, size.height); isVisible = true; return this; } void draw() { assert(isVisible); Mat image(size.height, size.width, CV_8UC3); Size cellImageSize = Size(size.width / cols, size.height / rows); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { Rect cellROIRect = Rect(j * cellImageSize.width, i * cellImageSize.height, cellImageSize.width, cellImageSize.height); if (cell(i, j).hasImage()) { Mat cellImage; resize(cell(i, j).getImage(), cellImage, cellImageSize); if (cellImage.type() == CV_8UC1) { cvtColor(cellImage, cellImage, CV_GRAY2RGB); } cellImage.copyTo(image(cellROIRect)); } String cellTitle = cell(i, j).getTitle(); Size cellTitleTextSize = getTextSize(cellTitle, FONT_HERSHEY_COMPLEX_SMALL, 1.0, 1, NULL); putText(image, cellTitle, Point(cellROIRect.x + (cellROIRect.width / 2 - cellTitleTextSize.width / 2), cellTitleTextSize.height + 8), FONT_HERSHEY_COMPLEX_SMALL, 0.75, Scalar(0, 0, 255)); } } imshow(title, image); waitKey(1); } }; #endif
26.314286
203
0.564604
cn0512
c5daa273dd4ab20759832968146f7077fee9c58b
439
cc
C++
MWP2_1E.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2021-02-01T11:21:56.000Z
2021-02-01T11:21:56.000Z
MWP2_1E.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
null
null
null
MWP2_1E.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2022-01-28T15:25:45.000Z
2022-01-28T15:25:45.000Z
// C++14 (gcc 8.3) #include <algorithm> #include <iostream> #include <string> #include <vector> int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(nullptr); std::vector<std::string> words; std::string word; while (std::cin >> word) { words.push_back(word); } std::sort(words.begin(), words.end()); for (auto it{words.begin()}; it != words.end(); ++it) { std::cout << *it << "\n"; } return 0; }
19.086957
57
0.594533
hkktr
c5db24648dcb994cc0671d991851bedc79c33fac
232
hpp
C++
src/actor/ActorId.hpp
patrikpihlstrom/nn-c-
8b5df5f2c62a3dbefc9ded4908daffdf989c771b
[ "MIT" ]
null
null
null
src/actor/ActorId.hpp
patrikpihlstrom/nn-c-
8b5df5f2c62a3dbefc9ded4908daffdf989c771b
[ "MIT" ]
null
null
null
src/actor/ActorId.hpp
patrikpihlstrom/nn-c-
8b5df5f2c62a3dbefc9ded4908daffdf989c771b
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> struct ActorId { uint64_t id; bool operator== (const ActorId& compare) const { return id == compare.id; } bool operator< (const ActorId& compare) const { return id < compare.id; } };
11.047619
47
0.659483
patrikpihlstrom
c5dba36aad008efc0858fcd21d747c9d17b5b30e
4,458
hpp
C++
src/klass/layer.hpp
burncode/py-skp
2e022fc7ef54bc77454bd368f3b512ad3cb5b0f2
[ "MIT" ]
1
2021-02-28T16:33:38.000Z
2021-02-28T16:33:38.000Z
src/klass/layer.hpp
burncode/py-skp
2e022fc7ef54bc77454bd368f3b512ad3cb5b0f2
[ "MIT" ]
null
null
null
src/klass/layer.hpp
burncode/py-skp
2e022fc7ef54bc77454bd368f3b512ad3cb5b0f2
[ "MIT" ]
null
null
null
#ifndef SKP_LAYER_HPP #define SKP_LAYER_HPP #include "common.hpp" #include <SketchUpAPI/model/layer.h> #include "entity.hpp" typedef struct { SkpEntity skp_entilty; SULayerRef _su_layer; } SkpLayer; static void SkpLayer_dealloc(SkpLayer* self) { Py_TYPE(self)->tp_free((PyObject*)self); } static SUEntityRef SkpLayer__get_su_entity(void *self) { SkpEntity *ent_self = (SkpEntity*)self; if (!SUIsValid(ent_self->_su_entity)) { ent_self->_su_entity = SULayerToEntity(((SkpLayer*)self)->_su_layer); } return ent_self->_su_entity; } static PyObject * SkpLayer_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { PyObject *py_obj = (PyObject*)SkpEntityType.tp_new(type, args, kwds); SkpLayer *self = (SkpLayer*)py_obj; if (self != NULL) { ((SkpEntity*)self)->get_su_entity = &SkpLayer__get_su_entity; self->_su_layer = SU_INVALID; } return py_obj; } static int SkpLayer_init(SkpLayer *self, PyObject *args, PyObject *kwds) { return 0; } static PyMemberDef SkpLayer_members[] = { {NULL} /* Sentinel */ }; static PyObject* SkpLayer_getname(SkpLayer *self, void *closure) { SKP_GET_STRING_BODY(SULayerGetName, _su_layer, "cannot get name") } static int SkpLayer_setname(SkpLayer *self, PyObject *value, void *closure) { //TODO: Cannot overwrite Layer0 SKP_SET_STRING_BODY(SULayerSetName, _su_layer, "cannot set name") } static PyGetSetDef SkpLayer_getseters[] = { { "name", (getter)SkpLayer_getname, (setter)SkpLayer_setname, "name", NULL}, {NULL} /* Sentinel */ }; static PyMethodDef SkpLayer_methods[] = { {NULL} /* Sentinel */ }; static PyTypeObject SkpLayerType = { PyVarObject_HEAD_INIT(NULL, 0) "skp.Layer", /* tp_name */ sizeof(SkpLayer), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)SkpLayer_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */ "SketchUp Layer", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ SkpLayer_methods, /* tp_methods */ SkpLayer_members, /* tp_members */ SkpLayer_getseters, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)SkpLayer_init, /* tp_init */ 0, /* tp_alloc */ SkpLayer_new, /* tp_new */ }; #endif
40.162162
84
0.401301
burncode
c5e35d17fb6c91295662f366518c972975b69bed
2,389
cpp
C++
google/gcj/2019/1b/a.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
google/gcj/2019/1b/a.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
google/gcj/2019/1b/a.cpp
yu3mars/proconVSCodeGcc
fcf36165bb14fb6f555664355e05dd08d12e426b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; using pii = pair<int, int>; #define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i) #define all(x) (x).begin(), (x).end() #define m0(x) memset(x, 0, sizeof(x)) int dx4[4] = {1, 0, -1, 0}, dy4[4] = {0, 1, 0, -1}; class GoogleCodeJam { public: string case_prefix; void exec() { int p,q; cin>>p>>q; vector<int> x(p),y(p); vector<char> c(p); vector<int> lsN(q+1),lsS(q+1),lsE(q+1),lsW(q+1); for(int i = 0; i < p; i++) { cin>>x[i]>>y[i]>>c[i]; if(c[i]=='N') { lsN[y[i]+1]++; } else if(c[i]=='S') { lsS[y[i]-1]++; } else if(c[i]=='E') { lsE[x[i]+1]++; } else if(c[i]=='W') { lsW[x[i]-1]++; } } for(int i = 0; i < q; i++) { lsN[i+1]+=lsN[i]; lsE[i+1]+=lsE[i]; } for(int i = q - 1; i >= 0; i--) { lsS[i]+=lsS[i+1]; lsW[i]+=lsW[i+1]; } int ansx=0, ansy=0; for(int i = 0; i <= q; i++) { if(lsN[i]+lsS[i]>lsN[ansy]+lsS[ansy]) { ansy=i; } if(lsE[i]+lsW[i]>lsE[ansx]+lsW[ansx]) { ansx=i; } } /* cout<< "lsN"; for(int i = 0; i <= q; i++) { cout<<" "<<lsN[i]; } cout<<endl; cout<< "lsS"; for(int i = 0; i <= q; i++) { cout<<" "<<lsS[i]; } cout<<endl; cout<< "lsE"; for(int i = 0; i <= q; i++) { cout<<" "<<lsE[i]; } cout<<endl; cout<< "lsW"; for(int i = 0; i <= q; i++) { cout<<" "<<lsW[i]; } cout<<endl; */ cout<<ansx<<" "<<ansy<<endl; } GoogleCodeJam() { int T; std::cin >> T; for (int i = 1; i <= T; i++) { case_prefix = "Case #" + std::to_string(i) + ": "; cout << case_prefix; exec(); } } }; int main() { GoogleCodeJam(); return 0; }
20.594828
66
0.321892
yu3mars
c5e3b634fe1e1449283eaaf536e62babbcf04933
3,184
cc
C++
lib/io/disk_manager.cc
DibiBase/dibibase
46020a1052f16d8225a06a5a5b5dd43dd62e5c26
[ "Apache-2.0" ]
1
2021-12-14T12:22:32.000Z
2021-12-14T12:22:32.000Z
lib/io/disk_manager.cc
DibiBase/dibibase
46020a1052f16d8225a06a5a5b5dd43dd62e5c26
[ "Apache-2.0" ]
5
2021-11-16T15:21:11.000Z
2022-03-30T13:01:44.000Z
lib/io/disk_manager.cc
DibiBase/dibibase
46020a1052f16d8225a06a5a5b5dd43dd62e5c26
[ "Apache-2.0" ]
null
null
null
#include "io/disk_manager.hh" #include <cerrno> #include <fcntl.h> #include <memory> #include <string> #include <unistd.h> #include "catalog/record.hh" #include "catalog/schema.hh" #include "db/index_page.hh" #include "mem/summary.hh" #include "util/buffer.hh" #include "util/logger.hh" using namespace dibibase; std::unique_ptr<mem::Summary> io::DiskManager::load_summary(std::string &database_path, std::string &table_name, size_t sstable_id) { int fd = open((database_path + "/" + table_name + "/summary_" + std::to_string(sstable_id) + ".db") .c_str(), O_RDONLY); std::unique_ptr<unsigned char[]> buf = std::unique_ptr<unsigned char[]>(new unsigned char[4096]); int rc = read(fd, buf.get(), 4096); if (rc < 0) util::Logger::make().err("Error reading Summary file: %d", errno); else if (rc != 4096) util::Logger::make().err("Malformed Summary file: File length isn't 4096"); util::Buffer *summary_buffer = new util::MemoryBuffer(std::move(buf), 4096); auto summary = mem::Summary::from(summary_buffer); delete summary_buffer; return summary; } std::unique_ptr<db::IndexPage> io::DiskManager::load_index_page(std::string &database_path, std::string &table_name, size_t sstable_id, uint8_t page_num) { int fd = open((database_path + "/" + table_name + "/index_" + std::to_string(sstable_id) + ".db") .c_str(), O_RDONLY); lseek(fd, page_num * 4096, SEEK_SET); std::unique_ptr<unsigned char[]> buf = std::unique_ptr<unsigned char[]>(new unsigned char[4096]); int rc = read(fd, buf.get(), 4096); if (rc < 0) util::Logger::make().err("Error reading Index file: %d", errno); else if (rc != 4096) util::Logger::make().err( "Malformed Index file: File length isn't a mulitple of 4096"); util::Buffer *index_buffer = new util::MemoryBuffer(std::move(buf), 4096); auto index_page = db::IndexPage::from(index_buffer); delete index_buffer; return index_page; } catalog::Record io::DiskManager::get_record_from_data( std::string &database_path, std::string &table_name, size_t sstable_id, catalog::Schema &schema, off_t offset) { int fd = open((database_path + "/" + table_name + "/data_" + std::to_string(sstable_id) + ".db") .c_str(), O_RDONLY); lseek(fd, offset, SEEK_SET); std::unique_ptr<unsigned char[]> buf = std::unique_ptr<unsigned char[]>(new unsigned char[schema.record_size()]); int rc = read(fd, buf.get(), schema.record_size()); if (rc < 0) util::Logger::make().err("Error reading Data file: %d", errno); else if (rc != static_cast<int>(schema.record_size())) util::Logger::make().err("Malformed Data file: File is truncated"); util::Buffer *record_buffer = new util::MemoryBuffer(std::move(buf), schema.record_size()); auto read_record = catalog::Record::from(record_buffer, schema); auto record = catalog::Record(read_record->values()); delete record_buffer; return record; }
31.524752
80
0.629083
DibiBase
c5e6003b9f5e7d70abdf6fe2e66e6568cfc80184
650
cpp
C++
Semester_2/Lab_14/main.cpp
DenCoder618/SUAI-Labs
4785f5888257a7da79bc7ab681cde670ab3cf586
[ "MIT" ]
1
2021-09-20T23:58:34.000Z
2021-09-20T23:58:34.000Z
Semester_2/Lab_14/main.cpp
DenCoder618/SUAI-Labs
4785f5888257a7da79bc7ab681cde670ab3cf586
[ "MIT" ]
9
2021-09-22T22:47:47.000Z
2021-10-23T00:34:36.000Z
Semester_2/Lab_14/main.cpp
DenCoder618/SUAI-Labs
4785f5888257a7da79bc7ab681cde670ab3cf586
[ "MIT" ]
null
null
null
// Программа должна хранить схему в виде заданной в задании // структуры данных, где хранятся геометрические фигуры. // Каждая фигура характеризуется уникальным идентификатором // (int) id, координатами на экране (x, y), а также своими параметрами // Программа должна уметь работать с фигурами, указанными в задании. // Каждая фигуру должна уметь выводить на экран свои параметры // в текстовом режиме с помощью метода print(). // Возможно, в будущем будут добавлены новые фигуры // Класс FigureList должен быть основан на связном списке. // Связаный список должен быть реализован с помощью двух классов // Node (элемент списка) и List (сам список)
50
70
0.783077
DenCoder618
c5e7778713b803c63fc46728bf635fff4d5826f4
10,667
cpp
C++
Test/test_buffer.cpp
Grandbrain/StdEx
e79c37ea77f67ae44e4cc4db4a9e90965c2fbf97
[ "MIT" ]
null
null
null
Test/test_buffer.cpp
Grandbrain/StdEx
e79c37ea77f67ae44e4cc4db4a9e90965c2fbf97
[ "MIT" ]
null
null
null
Test/test_buffer.cpp
Grandbrain/StdEx
e79c37ea77f67ae44e4cc4db4a9e90965c2fbf97
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <buffer.hpp> // Testing of buffer. TEST_CASE("Testing of buffer") { // Testing of buffer constructors. SECTION("Constructors") { SECTION("Constructor without parameters") { stdex::buffer<int> a; REQUIRE(a.data() == nullptr); REQUIRE(a.empty()); REQUIRE(a.capacity() == 0); } SECTION("Constructor with initializer list") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 5); REQUIRE(a.at(4) == 5); } SECTION("Constructor with capacity") { stdex::buffer<int> a(10); REQUIRE(a.data() != nullptr); REQUIRE(a.empty()); REQUIRE(a.capacity() == 10); } SECTION("Constructor with data array") { int array[] = { 1, 2, 3, 4, 5 }; stdex::buffer<int> a(array, sizeof(array) / sizeof(int)); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 5); REQUIRE(a.at(0) == 1); } SECTION("Constructor with data array and capacity") { int array[] = { 1, 2, 3, 4, 5 }; stdex::buffer<int> a(array, sizeof(array) / sizeof(int), 10); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 10); REQUIRE(a.at(0) == 1); } SECTION("Copy constructor") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b = a; REQUIRE(b.data() != nullptr); REQUIRE(b.size() == 5); REQUIRE(b.capacity() == 5); REQUIRE(b.at(1) == 2); } SECTION("Move constructor") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b = std::move(a); REQUIRE(b.data() != nullptr); REQUIRE(b.size() == 5); REQUIRE(b.capacity() == 5); REQUIRE(b.at(0) == 1); REQUIRE(b.at(1) == 2); REQUIRE(b.at(2) == 3); REQUIRE(b.at(3) == 4); REQUIRE(b.at(4) == 5); } } // Testing of assignment operators. SECTION("Assignment operators") { SECTION("Copy assignment operator") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b { 6, 7, 8, 9, 10 }; b = a; REQUIRE(b.size() == 5); REQUIRE(b.capacity() == 5); REQUIRE(b.at(0) == 1); REQUIRE(b.at(4) == 5); } SECTION("Move assignment operator") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b { 6, 7, 8, 9, 10 }; b = std::move(a); REQUIRE(b.size() == 5); REQUIRE(b.capacity() == 5); REQUIRE(b.at(0) == 1); REQUIRE(b.at(1) == 2); REQUIRE(b.at(2) == 3); REQUIRE(b.at(3) == 4); REQUIRE(b.at(4) == 5); } SECTION("Assignment operator with initializer list") { stdex::buffer<int> a; a = { 1, 2, 3, 4, 5 }; REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 5); REQUIRE(a.at(0) == 1); REQUIRE(a.at(4) == 5); } } // Testing of equality operators. SECTION("Equality checking") { SECTION("Equality operator") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b { 1, 2, 3, 4, 5 }; REQUIRE(a == b); } SECTION("Inequality operator") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b { 6, 7, 8, 9, 10 }; REQUIRE(a != b); } } // Testing of data assignment. SECTION("Data assignment") { SECTION("Assign an initializer list") { stdex::buffer<int> a; a.assign({ 1, 2, 3, 4, 5 }); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 5); REQUIRE(a.at(4) == 5); } SECTION("Assign a capacity") { stdex::buffer<int> a; a.assign(10); REQUIRE(a.data() != nullptr); REQUIRE(a.empty()); REQUIRE(a.capacity() == 10); } SECTION("Assign a data array") { int array[] = { 1, 2, 3, 4, 5 }; stdex::buffer<int> a; a.assign(array, sizeof(array) / sizeof(int)); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 5); REQUIRE(a.at(0) == 1); } SECTION("Assign a data array and capacity") { int array[] = { 1, 2, 3, 4, 5 }; stdex::buffer<int> a; a.assign(array, sizeof(array) / sizeof(int), 10); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 10); REQUIRE(a.at(0) == 1); } SECTION("Assign an existing object") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b; b.assign(a); REQUIRE(b.data() != nullptr); REQUIRE(b.size() == 5); REQUIRE(b.capacity() == 5); REQUIRE(b.at(1) == 2); } SECTION("Assign a temporary object") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b; b.assign(std::move(a)); REQUIRE(b.data() != nullptr); REQUIRE(b.size() == 5); REQUIRE(b.capacity() == 5); REQUIRE(b.at(0) == 1); REQUIRE(b.at(1) == 2); REQUIRE(b.at(2) == 3); REQUIRE(b.at(3) == 4); REQUIRE(b.at(4) == 5); } SECTION("Erase old data") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b { 6, 7, 8, 9, 10 }; b.assign(a); REQUIRE(b.data() != nullptr); REQUIRE(b.size() == 5); REQUIRE(b.capacity() == 5); REQUIRE(b.at(0) == 1); REQUIRE(b[4] == 5); } } // Testing of data appending. SECTION("Data appending") { SECTION("Append an existing object") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b { 6, 7, 8, 9, 10 }; a.append(b); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 10); REQUIRE(a.capacity() == 10); REQUIRE(a.at(0) == 1); REQUIRE(a[9] == 10); } SECTION("Append an initializer list") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; a.append({ 6, 7, 8, 9, 10 }); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 10); REQUIRE(a.capacity() == 10); REQUIRE(a.at(9) == 10); } SECTION("Append a single value") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; a.append(6); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 6); REQUIRE(a.capacity() == 6); REQUIRE(a.at(5) == 6); } SECTION("Append a data array") { int array[] = { 6, 7, 8, 9, 10 }; stdex::buffer<int> a { 1, 2, 3, 4, 5 }; a.append(array, sizeof(array) / sizeof(int)); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 10); REQUIRE(a.capacity() == 10); REQUIRE(a.at(9) == 10); } SECTION("Append a data with reserved capacity") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; a.assign(10); a.append({ 6, 7, 8 }); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 8); REQUIRE(a.capacity() == 10); REQUIRE(a.at(7) == 8); REQUIRE(a[9] == 0); } } // Testing of data insertion. SECTION("Data insertion") { SECTION("Insert a data array") { int array[] = { 6, 7, 8, 9, 10 }; stdex::buffer<int> a { 1, 2, 3, 4, 5 }; a.insert(array, sizeof(array) / sizeof(int), 2); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 10); REQUIRE(a.capacity() == 10); REQUIRE(a.at(0) == 1); REQUIRE(a.at(2) == 6); REQUIRE(a.at(4) == 8); REQUIRE(a.at(6) == 10); REQUIRE(a.at(9) == 5); } } // Testing of range access. SECTION("Range access") { SECTION("Getting the first element") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; REQUIRE(a.first() == 1); REQUIRE((a.first() = 10) == 10); } SECTION("Getting the last element") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; REQUIRE(a.last() == 5); REQUIRE((a.last() = 10) == 10); } SECTION("Iterator loop") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int> b; for (int element : a) b.append(element); REQUIRE(a == b); } } // Testing of data clearing. SECTION("Data clearing") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; a.clear(); REQUIRE(a.data() == nullptr); REQUIRE(a.empty()); REQUIRE(a.capacity() == 0); } // Testing of object swapping. SECTION("Object swapping") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; stdex::buffer<int32_t> b { 6, 7, 8, 9, 10 }; stdex::swap(a, b); REQUIRE(a.at(0) == 6); REQUIRE(a.at(4) == 10); REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 5); REQUIRE(b.at(0) == 1); REQUIRE(b.at(4) == 5); REQUIRE(b.size() == 5); REQUIRE(b.capacity() == 5); } // Testing of shrinking to fit. SECTION("Shrinking to fit") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; a.assign(10); REQUIRE(a.data() != nullptr); REQUIRE(a.size() == 5); REQUIRE(a.capacity() == 10); REQUIRE(a.at(4) == 5); a.shrink_to_fit(); REQUIRE(a.capacity() == 5); } // Testing of data releasing. SECTION("Data releasing") { stdex::buffer<int> a { 1, 2, 3, 4, 5 }; int* data = a.release(); delete[] data; REQUIRE(a.data() == nullptr); REQUIRE(a.empty()); REQUIRE(a.capacity() == 0); } }
31.190058
73
0.431612
Grandbrain
c5ec745eb47bce7dd5d8dec897432173e866d91b
30
cc
C++
deps/gettext/gettext-tools/woe32dll/c++msgfilter.cc
kimpel70/poedit
9114258b6421c530f6516258635e730d8d3f6b26
[ "MIT" ]
3
2021-05-04T17:09:06.000Z
2021-10-04T07:19:26.000Z
deps/gettext/gettext-tools/woe32dll/c++msgfilter.cc
kimpel70/poedit
9114258b6421c530f6516258635e730d8d3f6b26
[ "MIT" ]
null
null
null
deps/gettext/gettext-tools/woe32dll/c++msgfilter.cc
kimpel70/poedit
9114258b6421c530f6516258635e730d8d3f6b26
[ "MIT" ]
null
null
null
#include "../src/msgfilter.c"
15
29
0.666667
kimpel70
c5eef785114172af92a644f2c971a510e55dac8d
131,233
cpp
C++
disabled_modules/visual_script/visual_script_nodes.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
disabled_modules/visual_script/visual_script_nodes.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
disabled_modules/visual_script/visual_script_nodes.cpp
ZopharShinta/SegsEngine
86d52c5b805e05e107594efd3358cabd694365f0
[ "CC-BY-3.0", "Apache-2.0", "MIT" ]
null
null
null
/*************************************************************************/ /* visual_script_nodes.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "visual_script_nodes.h" #include "core/engine.h" #include "core/global_constants.h" #include "core/method_bind.h" #include "core/method_info.h" #include "core/method_ptrcall.h" #include "core/object_tooling.h" #include "core/os/input.h" #include "core/os/os.h" #include "core/project_settings.h" #include "core/string.h" #include "core/string_formatter.h" #include "core/translation_helpers.h" #include "scene/main/node.h" #include "scene/main/scene_tree.h" #include "EASTL/sort.h" IMPL_GDCLASS(VisualScriptFunction) IMPL_GDCLASS(VisualScriptOperator) IMPL_GDCLASS(VisualScriptSelect) IMPL_GDCLASS(VisualScriptVariableGet) IMPL_GDCLASS(VisualScriptVariableSet) IMPL_GDCLASS(VisualScriptConstant) IMPL_GDCLASS(VisualScriptPreload) IMPL_GDCLASS(VisualScriptIndexGet) IMPL_GDCLASS(VisualScriptLists) IMPL_GDCLASS(VisualScriptComposeArray) IMPL_GDCLASS(VisualScriptIndexSet) IMPL_GDCLASS(VisualScriptGlobalConstant) IMPL_GDCLASS(VisualScriptClassConstant) IMPL_GDCLASS(VisualScriptBasicTypeConstant) IMPL_GDCLASS(VisualScriptMathConstant) IMPL_GDCLASS(VisualScriptEngineSingleton) IMPL_GDCLASS(VisualScriptSceneNode) IMPL_GDCLASS(VisualScriptSceneTree) IMPL_GDCLASS(VisualScriptResourcePath) IMPL_GDCLASS(VisualScriptSelf) IMPL_GDCLASS(VisualScriptCustomNode) IMPL_GDCLASS(VisualScriptSubCall) IMPL_GDCLASS(VisualScriptComment) IMPL_GDCLASS(VisualScriptConstructor) IMPL_GDCLASS(VisualScriptLocalVar) IMPL_GDCLASS(VisualScriptLocalVarSet) IMPL_GDCLASS(VisualScriptInputAction) IMPL_GDCLASS(VisualScriptDeconstruct) VARIANT_ENUM_CAST(VisualScriptMathConstant::MathConstant) VARIANT_ENUM_CAST(VisualScriptCustomNode::StartMode); VARIANT_ENUM_CAST(VisualScriptInputAction::Mode) ////////////////////////////////////////// ////////////////FUNCTION////////////////// ////////////////////////////////////////// bool VisualScriptFunction::_set(const StringName &p_name, const Variant &p_value) { if (p_name == "argument_count") { int new_argc = p_value.as<int>(); int argc = arguments.size(); if (argc == new_argc) return true; arguments.resize(new_argc); for (int i = argc; i < new_argc; i++) { arguments[i].name = StringName("arg" + itos(i + 1)); arguments[i].type = VariantType::NIL; } ports_changed_notify(); Object_change_notify(this); return true; } if (StringUtils::begins_with(p_name,"argument/")) { FixedVector<StringView, 3> parts; String::split_ref(parts, p_name, '/'); int idx = StringUtils::to_int(parts[1]) - 1; ERR_FAIL_INDEX_V(idx, arguments.size(), false); StringView what = parts[2]; if (what == StringView("type")) { VariantType new_type = p_value.as<VariantType>(); arguments[idx].type = new_type; ports_changed_notify(); return true; } if (what == StringView("name")) { arguments[idx].name = p_value.as<StringName>(); ports_changed_notify(); return true; } } if (p_name == "stack/stackless") { set_stack_less(p_value.as<bool>()); return true; } if (p_name == "stack/size") { stack_size = p_value.as<int>(); return true; } if (p_name == "rpc/mode") { rpc_mode = p_value.as<MultiplayerAPI_RPCMode>(); return true; } if (p_name == "sequenced/sequenced") { sequenced = p_value.as<bool>(); ports_changed_notify(); return true; } return false; } bool VisualScriptFunction::_get(const StringName &p_name, Variant &r_ret) const { if (p_name == "argument_count") { r_ret = arguments.size(); return true; } if (StringUtils::begins_with(p_name,"argument/")) { FixedVector<StringView, 3> parts; String::split_ref(parts, p_name, '/'); int idx = StringUtils::to_int(parts[1]) - 1; ERR_FAIL_INDEX_V(idx, arguments.size(), false); StringView what = parts[2]; if (what == StringView("type")) { r_ret = arguments[idx].type; return true; } if (what == StringView("name")) { r_ret = arguments[idx].name; return true; } } if (p_name == "stack/stackless") { r_ret = stack_less; return true; } if (p_name == "stack/size") { r_ret = stack_size; return true; } if (p_name == "rpc/mode") { r_ret = (int8_t)rpc_mode; return true; } if (p_name == "sequenced/sequenced") { r_ret = sequenced; return true; } return false; } void VisualScriptFunction::_get_property_list(Vector<PropertyInfo> *p_list) const { p_list->push_back(PropertyInfo(VariantType::INT, "argument_count", PropertyHint::Range, "0,256")); char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX]; fill_with_all_variant_types("Any",argt); for (int i = 0; i < arguments.size(); i++) { p_list->push_back(PropertyInfo(VariantType::INT, StringName("argument/" + itos(i + 1) + "/type"), PropertyHint::Enum, argt)); p_list->push_back(PropertyInfo(VariantType::STRING, StringName("argument/" + itos(i + 1) + "/name"))); } p_list->push_back(PropertyInfo(VariantType::BOOL, "sequenced/sequenced")); if (!stack_less) { p_list->push_back(PropertyInfo(VariantType::INT, "stack/size", PropertyHint::Range, "1,100000")); } p_list->push_back(PropertyInfo(VariantType::BOOL, "stack/stackless")); p_list->push_back(PropertyInfo(VariantType::INT, "rpc/mode", PropertyHint::Enum, "Disabled,Remote,Master,Puppet,Remote Sync,Master Sync,Puppet Sync")); } int VisualScriptFunction::get_output_sequence_port_count() const { return 1; } bool VisualScriptFunction::has_input_sequence_port() const { return false; } int VisualScriptFunction::get_input_value_port_count() const { return 0; } int VisualScriptFunction::get_output_value_port_count() const { return arguments.size(); } StringView VisualScriptFunction::get_output_sequence_port_text(int p_port) const { return nullptr; } PropertyInfo VisualScriptFunction::get_input_value_port_info(int p_idx) const { ERR_FAIL_V(PropertyInfo()); } PropertyInfo VisualScriptFunction::get_output_value_port_info(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, arguments.size(), PropertyInfo()); PropertyInfo out; out.type = arguments[p_idx].type; out.name = arguments[p_idx].name; out.hint = arguments[p_idx].hint; out.hint_string = arguments[p_idx].hint_string; return out; } StringView VisualScriptFunction::get_caption() const { return "Function"; } String VisualScriptFunction::get_text() const { return get_name(); //use name as function name I guess } void VisualScriptFunction::add_argument(VariantType p_type, const StringName &p_name, int p_index, const PropertyHint p_hint, StringView p_hint_string) { Argument arg; arg.name = p_name; arg.type = p_type; arg.hint = p_hint; arg.hint_string = p_hint_string; if (p_index >= 0) arguments.insert_at(p_index, arg); else arguments.push_back(arg); ports_changed_notify(); } void VisualScriptFunction::set_argument_type(int p_argidx, VariantType p_type) { ERR_FAIL_INDEX(p_argidx, arguments.size()); arguments[p_argidx].type = p_type; ports_changed_notify(); } VariantType VisualScriptFunction::get_argument_type(int p_argidx) const { ERR_FAIL_INDEX_V(p_argidx, arguments.size(), VariantType::NIL); return arguments[p_argidx].type; } void VisualScriptFunction::set_argument_name(int p_argidx, const StringName &p_name) { ERR_FAIL_INDEX(p_argidx, arguments.size()); arguments[p_argidx].name = p_name; ports_changed_notify(); } StringName VisualScriptFunction::get_argument_name(int p_argidx) const { ERR_FAIL_INDEX_V(p_argidx, arguments.size(), StringName()); return arguments[p_argidx].name; } void VisualScriptFunction::remove_argument(int p_argidx) { ERR_FAIL_INDEX(p_argidx, arguments.size()); arguments.erase_at(p_argidx); ports_changed_notify(); } int VisualScriptFunction::get_argument_count() const { return arguments.size(); } void VisualScriptFunction::set_rpc_mode(MultiplayerAPI_RPCMode p_mode) { rpc_mode = p_mode; } MultiplayerAPI_RPCMode VisualScriptFunction::get_rpc_mode() const { return rpc_mode; } class VisualScriptNodeInstanceFunction : public VisualScriptNodeInstance { public: VisualScriptFunction *node; VisualScriptInstance *instance; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { int ac = node->get_argument_count(); for (int i = 0; i < ac; i++) { #ifdef DEBUG_ENABLED VariantType expected = node->get_argument_type(i); if (expected != VariantType::NIL) { if (!Variant::can_convert_strict(p_inputs[i]->get_type(), expected)) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_ARGUMENT; r_error.expected = expected; r_error.argument = i; return 0; } } #endif *p_outputs[i] = *p_inputs[i]; } return 0; } }; VisualScriptNodeInstance *VisualScriptFunction::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceFunction *instance = memnew(VisualScriptNodeInstanceFunction); instance->node = this; instance->instance = p_instance; return instance; } VisualScriptFunction::VisualScriptFunction() { stack_size = 256; stack_less = false; sequenced = true; rpc_mode = MultiplayerAPI_RPCMode(0); } void VisualScriptFunction::set_stack_less(bool p_enable) { stack_less = p_enable; Object_change_notify(this); } bool VisualScriptFunction::is_stack_less() const { return stack_less; } void VisualScriptFunction::set_sequenced(bool p_enable) { sequenced = p_enable; } bool VisualScriptFunction::is_sequenced() const { return sequenced; } void VisualScriptFunction::set_stack_size(int p_size) { ERR_FAIL_COND(p_size < 1 || p_size > 100000); stack_size = p_size; } int VisualScriptFunction::get_stack_size() const { return stack_size; } ////////////////////////////////////////// /////////////////LISTS//////////////////// ////////////////////////////////////////// int VisualScriptLists::get_output_sequence_port_count() const { if (sequenced) return 1; return 0; } bool VisualScriptLists::has_input_sequence_port() const { return sequenced; } StringView VisualScriptLists::get_output_sequence_port_text(int p_port) const { return nullptr; } int VisualScriptLists::get_input_value_port_count() const { return inputports.size(); } int VisualScriptLists::get_output_value_port_count() const { return outputports.size(); } PropertyInfo VisualScriptLists::get_input_value_port_info(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, inputports.size(), PropertyInfo()); PropertyInfo pi; pi.name = inputports[p_idx].name; pi.type = inputports[p_idx].type; return pi; } PropertyInfo VisualScriptLists::get_output_value_port_info(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, outputports.size(), PropertyInfo()); PropertyInfo pi; pi.name = outputports[p_idx].name; pi.type = outputports[p_idx].type; return pi; } bool VisualScriptLists::is_input_port_editable() const { return ((flags & INPUT_EDITABLE) == INPUT_EDITABLE); } bool VisualScriptLists::is_input_port_name_editable() const { return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE); } bool VisualScriptLists::is_input_port_type_editable() const { return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE); } bool VisualScriptLists::is_output_port_editable() const { return ((flags & OUTPUT_EDITABLE) == OUTPUT_EDITABLE); } bool VisualScriptLists::is_output_port_name_editable() const { return ((flags & INPUT_NAME_EDITABLE) == INPUT_NAME_EDITABLE); } bool VisualScriptLists::is_output_port_type_editable() const { return ((flags & INPUT_TYPE_EDITABLE) == INPUT_TYPE_EDITABLE); } // for the inspector bool VisualScriptLists::_set(const StringName &p_name, const Variant &p_value) { using namespace StringUtils; if (p_name == "input_count" && is_input_port_editable()) { int new_argc = p_value.as<int>(); int argc = inputports.size(); if (argc == new_argc) return true; inputports.resize(new_argc); for (int i = argc; i < new_argc; i++) { inputports[i].name = StringName("arg" + itos(i + 1)); inputports[i].type = VariantType::NIL; } ports_changed_notify(); Object_change_notify(this); return true; } if (StringUtils::begins_with(p_name,"input/") && is_input_port_editable()) { FixedVector<StringView, 3> parts; String::split_ref(parts, p_name, '/'); int idx = to_int(parts[1]) - 1; ERR_FAIL_INDEX_V(idx, inputports.size(), false); StringView what = parts[2]; if (what == StringView("type")) { VariantType new_type = p_value.as<VariantType>(); inputports[idx].type = new_type; ports_changed_notify(); return true; } if (what == StringView("name")) { inputports[idx].name = p_value.as<StringName>(); ports_changed_notify(); return true; } } if (p_name == "output_count" && is_output_port_editable()) { int new_argc = p_value.as<int>(); int argc = outputports.size(); if (argc == new_argc) return true; outputports.resize(new_argc); for (int i = argc; i < new_argc; i++) { outputports[i].name = StringName("arg" + itos(i + 1)); outputports[i].type = VariantType::NIL; } ports_changed_notify(); Object_change_notify(this); return true; } if (begins_with(p_name,"output/") && is_output_port_editable()) { FixedVector<StringView, 3> parts; String::split_ref(parts, p_name, '/'); int idx = to_int(parts[1]) - 1; ERR_FAIL_INDEX_V(idx, outputports.size(), false); StringView what = parts[2]; if (what == StringView("type")) { VariantType new_type = p_value.as<VariantType>(); outputports[idx].type = new_type; ports_changed_notify(); return true; } if (what == StringView("name")) { outputports[idx].name = p_value.as<StringName>(); ports_changed_notify(); return true; } } if (p_name == "sequenced/sequenced") { sequenced = p_value.as<bool>(); ports_changed_notify(); return true; } return false; } bool VisualScriptLists::_get(const StringName &p_name, Variant &r_ret) const { using namespace StringUtils; if (p_name == "input_count" && is_input_port_editable()) { r_ret = inputports.size(); return true; } if (begins_with(p_name,"input/") && is_input_port_editable()) { FixedVector<StringView, 3> parts; String::split_ref(parts, p_name, '/'); int idx = to_int(parts[1]) - 1; ERR_FAIL_INDEX_V(idx, inputports.size(), false); StringView what = parts[2]; if (what == StringView("type")) { r_ret = inputports[idx].type; return true; } if (what == StringView("name")) { r_ret = inputports[idx].name; return true; } } if (p_name == "output_count" && is_output_port_editable()) { r_ret = outputports.size(); return true; } if (begins_with(p_name,"output/") && is_output_port_editable()) { FixedVector<StringView, 3> parts; String::split_ref(parts, p_name, '/'); int idx = to_int(parts[1]) - 1; ERR_FAIL_INDEX_V(idx, outputports.size(), false); StringView what = parts[2]; if (what == StringView("type")) { r_ret = outputports[idx].type; return true; } if (what == StringView("name")) { r_ret = outputports[idx].name; return true; } } if (p_name == "sequenced/sequenced") { r_ret = sequenced; return true; } return false; } void VisualScriptLists::_get_property_list(Vector<PropertyInfo> *p_list) const { if (is_input_port_editable()) { p_list->push_back(PropertyInfo(VariantType::INT, "input_count", PropertyHint::Range, "0,256")); String argt("Any"); for (int i = 1; i < (int8_t)VariantType::VARIANT_MAX; i++) { argt += String(",") + Variant::get_type_name(VariantType(i)); } for (int i = 0; i < inputports.size(); i++) { p_list->push_back(PropertyInfo(VariantType::INT, StringName("input/" + itos(i + 1) + "/type"), PropertyHint::Enum, StringName(argt))); p_list->push_back(PropertyInfo(VariantType::STRING, StringName("input/" + itos(i + 1) + "/name"))); } } if (is_output_port_editable()) { p_list->push_back(PropertyInfo(VariantType::INT, "output_count", PropertyHint::Range, "0,256")); String argt("Any"); for (int i = 1; i < (int8_t)VariantType::VARIANT_MAX; i++) { argt += String(",") + Variant::get_type_name(VariantType(i)); } for (int i = 0; i < outputports.size(); i++) { p_list->push_back(PropertyInfo(VariantType::INT, StringName("output/" + itos(i + 1) + "/type"), PropertyHint::Enum, StringName(argt))); p_list->push_back(PropertyInfo(VariantType::STRING, StringName("output/" + itos(i + 1) + "/name"))); } } p_list->push_back(PropertyInfo(VariantType::BOOL, "sequenced/sequenced")); } // input data port interaction void VisualScriptLists::add_input_data_port(VariantType p_type, const StringName &p_name, int p_index) { if (!is_input_port_editable()) return; Port inp; inp.name = p_name; inp.type = p_type; if (p_index >= 0) inputports.insert_at(p_index, inp); else inputports.push_back(inp); ports_changed_notify(); Object_change_notify(this); } void VisualScriptLists::set_input_data_port_type(int p_idx, VariantType p_type) { if (!is_input_port_type_editable()) return; ERR_FAIL_INDEX(p_idx, inputports.size()); inputports[p_idx].type = p_type; ports_changed_notify(); Object_change_notify(this); } void VisualScriptLists::set_input_data_port_name(int p_idx, const StringName &p_name) { if (!is_input_port_name_editable()) return; ERR_FAIL_INDEX(p_idx, inputports.size()); inputports[p_idx].name = p_name; ports_changed_notify(); Object_change_notify(this); } void VisualScriptLists::remove_input_data_port(int p_argidx) { if (!is_input_port_editable()) return; ERR_FAIL_INDEX(p_argidx, inputports.size()); inputports.erase_at(p_argidx); ports_changed_notify(); Object_change_notify(this); } // output data port interaction void VisualScriptLists::add_output_data_port(VariantType p_type, const StringName &p_name, int p_index) { if (!is_output_port_editable()) return; Port out; out.name = p_name; out.type = p_type; if (p_index >= 0) outputports.insert_at(p_index, out); else outputports.push_back(out); ports_changed_notify(); Object_change_notify(this); } void VisualScriptLists::set_output_data_port_type(int p_idx, VariantType p_type) { if (!is_output_port_type_editable()) return; ERR_FAIL_INDEX(p_idx, outputports.size()); outputports[p_idx].type = p_type; ports_changed_notify(); Object_change_notify(this); } void VisualScriptLists::set_output_data_port_name(int p_idx, const StringName &p_name) { if (!is_output_port_name_editable()) return; ERR_FAIL_INDEX(p_idx, outputports.size()); outputports[p_idx].name = p_name; ports_changed_notify(); Object_change_notify(this); } void VisualScriptLists::remove_output_data_port(int p_argidx) { if (!is_output_port_editable()) return; ERR_FAIL_INDEX(p_argidx, outputports.size()); outputports.erase_at(p_argidx); ports_changed_notify(); Object_change_notify(this); } // sequences void VisualScriptLists::set_sequenced(bool p_enable) { if (sequenced == p_enable) return; sequenced = p_enable; ports_changed_notify(); } bool VisualScriptLists::is_sequenced() const { return sequenced; } VisualScriptLists::VisualScriptLists() { // initialize sequenced = false; flags = 0; } void VisualScriptLists::_bind_methods() { MethodBinder::bind_method(D_METHOD("add_input_data_port", {"type", "name", "index"}), &VisualScriptLists::add_input_data_port); MethodBinder::bind_method(D_METHOD("set_input_data_port_name", {"index", "name"}), &VisualScriptLists::set_input_data_port_name); MethodBinder::bind_method(D_METHOD("set_input_data_port_type", {"index", "type"}), &VisualScriptLists::set_input_data_port_type); MethodBinder::bind_method(D_METHOD("remove_input_data_port", {"index"}), &VisualScriptLists::remove_input_data_port); MethodBinder::bind_method(D_METHOD("add_output_data_port", {"type", "name", "index"}), &VisualScriptLists::add_output_data_port); MethodBinder::bind_method(D_METHOD("set_output_data_port_name", {"index", "name"}), &VisualScriptLists::set_output_data_port_name); MethodBinder::bind_method(D_METHOD("set_output_data_port_type", {"index", "type"}), &VisualScriptLists::set_output_data_port_type); MethodBinder::bind_method(D_METHOD("remove_output_data_port", {"index"}), &VisualScriptLists::remove_output_data_port); } ////////////////////////////////////////// //////////////COMPOSEARRAY//////////////// ////////////////////////////////////////// int VisualScriptComposeArray::get_output_sequence_port_count() const { if (sequenced) return 1; return 0; } bool VisualScriptComposeArray::has_input_sequence_port() const { return sequenced; } StringView VisualScriptComposeArray::get_output_sequence_port_text(int p_port) const { return nullptr; } int VisualScriptComposeArray::get_input_value_port_count() const { return inputports.size(); } int VisualScriptComposeArray::get_output_value_port_count() const { return 1; } PropertyInfo VisualScriptComposeArray::get_input_value_port_info(int p_idx) const { ERR_FAIL_INDEX_V(p_idx, inputports.size(), PropertyInfo()); PropertyInfo pi; pi.name = inputports[p_idx].name; pi.type = inputports[p_idx].type; return pi; } PropertyInfo VisualScriptComposeArray::get_output_value_port_info(int p_idx) const { PropertyInfo pi; pi.name = "out"; pi.type = VariantType::ARRAY; return pi; } StringView VisualScriptComposeArray::get_caption() const { return "Compose Array"; } String VisualScriptComposeArray::get_text() const { return {}; } class VisualScriptComposeArrayNode : public VisualScriptNodeInstance { public: int input_count = 0; int get_working_memory_size() const override { return 0; } virtual int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (input_count > 0) { Array arr; for (int i = 0; i < input_count; i++) arr.push_back((*p_inputs[i])); Variant va = Variant(arr); *p_outputs[0] = va; } return 0; } }; VisualScriptNodeInstance *VisualScriptComposeArray::instance(VisualScriptInstance *p_instance) { VisualScriptComposeArrayNode *instance = memnew(VisualScriptComposeArrayNode); instance->input_count = inputports.size(); return instance; } VisualScriptComposeArray::VisualScriptComposeArray() { // initialize stuff here sequenced = false; flags = INPUT_EDITABLE; } ////////////////////////////////////////// ////////////////OPERATOR////////////////// ////////////////////////////////////////// int VisualScriptOperator::get_output_sequence_port_count() const { return 0; } bool VisualScriptOperator::has_input_sequence_port() const { return false; } int VisualScriptOperator::get_input_value_port_count() const { return (op == Variant::OP_BIT_NEGATE || op == Variant::OP_NOT || op == Variant::OP_NEGATE || op == Variant::OP_POSITIVE) ? 1 : 2; } int VisualScriptOperator::get_output_value_port_count() const { return 1; } StringView VisualScriptOperator::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptOperator::get_input_value_port_info(int p_idx) const { static const VariantType port_types[Variant::OP_MAX][2] = { { VariantType::NIL, VariantType::NIL }, //OP_EQUAL, { VariantType::NIL, VariantType::NIL }, //OP_NOT_EQUAL, { VariantType::NIL, VariantType::NIL }, //OP_LESS, { VariantType::NIL, VariantType::NIL }, //OP_LESS_EQUAL, { VariantType::NIL, VariantType::NIL }, //OP_GREATER, { VariantType::NIL, VariantType::NIL }, //OP_GREATER_EQUAL, //mathematic { VariantType::NIL, VariantType::NIL }, //OP_ADD, { VariantType::NIL, VariantType::NIL }, //OP_SUBTRACT, { VariantType::NIL, VariantType::NIL }, //OP_MULTIPLY, { VariantType::NIL, VariantType::NIL }, //OP_DIVIDE, { VariantType::NIL, VariantType::NIL }, //OP_NEGATE, { VariantType::NIL, VariantType::NIL }, //OP_POSITIVE, { VariantType::INT, VariantType::INT }, //OP_MODULE, { VariantType::STRING, VariantType::STRING }, //OP_STRING_CONCAT, //bitwise { VariantType::INT, VariantType::INT }, //OP_SHIFT_LEFT, { VariantType::INT, VariantType::INT }, //OP_SHIFT_RIGHT, { VariantType::INT, VariantType::INT }, //OP_BIT_AND, { VariantType::INT, VariantType::INT }, //OP_BIT_OR, { VariantType::INT, VariantType::INT }, //OP_BIT_XOR, { VariantType::INT, VariantType::INT }, //OP_BIT_NEGATE, //logic { VariantType::BOOL, VariantType::BOOL }, //OP_AND, { VariantType::BOOL, VariantType::BOOL }, //OP_OR, { VariantType::BOOL, VariantType::BOOL }, //OP_XOR, { VariantType::BOOL, VariantType::BOOL }, //OP_NOT, //containment { VariantType::NIL, VariantType::NIL } //OP_IN, }; ERR_FAIL_INDEX_V(p_idx, 2, PropertyInfo()); PropertyInfo pinfo; pinfo.name = StringName(p_idx == 0 ? "A" : "B"); pinfo.type = port_types[op][p_idx]; if (pinfo.type == VariantType::NIL) pinfo.type = typed; return pinfo; } PropertyInfo VisualScriptOperator::get_output_value_port_info(int p_idx) const { static const VariantType port_types[Variant::OP_MAX] = { //comparison VariantType::BOOL, //OP_EQUAL, VariantType::BOOL, //OP_NOT_EQUAL, VariantType::BOOL, //OP_LESS, VariantType::BOOL, //OP_LESS_EQUAL, VariantType::BOOL, //OP_GREATER, VariantType::BOOL, //OP_GREATER_EQUAL, //mathematic VariantType::NIL, //OP_ADD, VariantType::NIL, //OP_SUBTRACT, VariantType::NIL, //OP_MULTIPLY, VariantType::NIL, //OP_DIVIDE, VariantType::NIL, //OP_NEGATE, VariantType::NIL, //OP_POSITIVE, VariantType::INT, //OP_MODULE, VariantType::STRING, //OP_STRING_CONCAT, //bitwise VariantType::INT, //OP_SHIFT_LEFT, VariantType::INT, //OP_SHIFT_RIGHT, VariantType::INT, //OP_BIT_AND, VariantType::INT, //OP_BIT_OR, VariantType::INT, //OP_BIT_XOR, VariantType::INT, //OP_BIT_NEGATE, //logic VariantType::BOOL, //OP_AND, VariantType::BOOL, //OP_OR, VariantType::BOOL, //OP_XOR, VariantType::BOOL, //OP_NOT, //containment VariantType::BOOL //OP_IN, }; PropertyInfo pinfo; pinfo.name = ""; pinfo.type = port_types[op]; if (pinfo.type == VariantType::NIL) pinfo.type = typed; return pinfo; } static const char *op_names[] = { //comparison "Are Equal", //OP_EQUAL, "Are Not Equal", //OP_NOT_EQUAL, "Less Than", //OP_LESS, "Less Than or Equal", //OP_LESS_EQUAL, "Greater Than", //OP_GREATER, "Greater Than or Equal", //OP_GREATER_EQUAL, //mathematic "Add", //OP_ADD, "Subtract", //OP_SUBTRACT, "Multiply", //OP_MULTIPLY, "Divide", //OP_DIVIDE, "Negate", //OP_NEGATE, "Positive", //OP_POSITIVE, "Remainder", //OP_MODULE, "Concatenate", //OP_STRING_CONCAT, //bitwise "Bit Shift Left", //OP_SHIFT_LEFT, "Bit Shift Right", //OP_SHIFT_RIGHT, "Bit And", //OP_BIT_AND, "Bit Or", //OP_BIT_OR, "Bit Xor", //OP_BIT_XOR, "Bit Negate", //OP_BIT_NEGATE, //logic "And", //OP_AND, "Or", //OP_OR, "Xor", //OP_XOR, "Not", //OP_NOT, //containment "In", //OP_IN, }; StringView VisualScriptOperator::get_caption() const { static const StringView op_names[] = { //comparison "A = B", //OP_EQUAL, "A ≠B", //OP_NOT_EQUAL, "A < B", //OP_LESS, "A ≤ B", //OP_LESS_EQUAL, "A > B", //OP_GREATER, "A ≥ B", //OP_GREATER_EQUAL, //mathematic "A + B", //OP_ADD, "A - B", //OP_SUBTRACT, "A × B", //OP_MULTIPLY, "A ÷ B", //OP_DIVIDE, "¬ A", //OP_NEGATE, "+ A", //OP_POSITIVE, "A mod B", //OP_MODULE, "A .. B", //OP_STRING_CONCAT, //bitwise "A << B", //OP_SHIFT_LEFT, "A >> B", //OP_SHIFT_RIGHT, "A & B", //OP_BIT_AND, "A | B", //OP_BIT_OR, "A ^ B", //OP_BIT_XOR, "~A", //OP_BIT_NEGATE, //logic "A and B", //OP_AND, "A or B", //OP_OR, "A xor B", //OP_XOR, "not A", //OP_NOT, "A in B", //OP_IN, }; return op_names[op]; } void VisualScriptOperator::set_operator(Variant::Operator p_op) { if (op == p_op) return; op = p_op; ports_changed_notify(); } Variant::Operator VisualScriptOperator::get_operator() const { return op; } void VisualScriptOperator::set_typed(VariantType p_op) { if (typed == p_op) return; typed = p_op; ports_changed_notify(); } VariantType VisualScriptOperator::get_typed() const { return typed; } void VisualScriptOperator::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_operator", {"op"}), &VisualScriptOperator::set_operator); MethodBinder::bind_method(D_METHOD("get_operator"), &VisualScriptOperator::get_operator); MethodBinder::bind_method(D_METHOD("set_typed", {"type"}), &VisualScriptOperator::set_typed); MethodBinder::bind_method(D_METHOD("get_typed"), &VisualScriptOperator::get_typed); String types; for (int i = 0; i < Variant::OP_MAX; i++) { if (i > 0) types += (","); types += (op_names[i]); } char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX]; fill_with_all_variant_types("Any",argt); ADD_PROPERTY(PropertyInfo(VariantType::INT, "operator", PropertyHint::Enum, StringName(types)), "set_operator", "get_operator"); ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_typed", "get_typed"); } class VisualScriptNodeInstanceOperator : public VisualScriptNodeInstance { public: bool unary; Variant::Operator op; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool valid; if (unary) { Variant::evaluate(op, *p_inputs[0], Variant(), *p_outputs[0], valid); } else { Variant::evaluate(op, *p_inputs[0], *p_inputs[1], *p_outputs[0], valid); } if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; if (p_outputs[0]->get_type() == VariantType::STRING) { r_error_str = p_outputs[0]->as<String>(); } else { if (unary) r_error_str = String(op_names[op]) + RTR_utf8(": Invalid argument of type: ") + Variant::get_type_name(p_inputs[0]->get_type()); else r_error_str = String(op_names[op]) + RTR_utf8(": Invalid arguments: ") + "A: " + Variant::get_type_name(p_inputs[0]->get_type()) + " B: " + Variant::get_type_name(p_inputs[1]->get_type()); } } return 0; } }; VisualScriptNodeInstance *VisualScriptOperator::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceOperator *instance = memnew(VisualScriptNodeInstanceOperator); instance->unary = get_input_value_port_count() == 1; instance->op = op; return instance; } VisualScriptOperator::VisualScriptOperator() { op = Variant::OP_ADD; typed = VariantType::NIL; } template <Variant::Operator OP> static Ref<VisualScriptNode> create_op_node(StringView p_name) { Ref<VisualScriptOperator> node(make_ref_counted<VisualScriptOperator>()); node->set_operator(OP); return node; } ////////////////////////////////////////// ////////////////OPERATOR////////////////// ////////////////////////////////////////// int VisualScriptSelect::get_output_sequence_port_count() const { return 0; } bool VisualScriptSelect::has_input_sequence_port() const { return false; } int VisualScriptSelect::get_input_value_port_count() const { return 3; } int VisualScriptSelect::get_output_value_port_count() const { return 1; } StringView VisualScriptSelect::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptSelect::get_input_value_port_info(int p_idx) const { if (p_idx == 0) { return PropertyInfo(VariantType::BOOL, "cond"); } else if (p_idx == 1) { return PropertyInfo(typed, "a"); } else { return PropertyInfo(typed, "b"); } } PropertyInfo VisualScriptSelect::get_output_value_port_info(int p_idx) const { return PropertyInfo(typed, "out"); } StringView VisualScriptSelect::get_caption() const { return "Select"; } String VisualScriptSelect::get_text() const { return "a if cond, else b"; } void VisualScriptSelect::set_typed(VariantType p_op) { if (typed == p_op) return; typed = p_op; ports_changed_notify(); } VariantType VisualScriptSelect::get_typed() const { return typed; } void VisualScriptSelect::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_typed", {"type"}), &VisualScriptSelect::set_typed); MethodBinder::bind_method(D_METHOD("get_typed"), &VisualScriptSelect::get_typed); char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX]; fill_with_all_variant_types("Any",argt); ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_typed", "get_typed"); } class VisualScriptNodeInstanceSelect : public VisualScriptNodeInstance { public: //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool cond = p_inputs[0]->as<bool>(); if (cond) *p_outputs[0] = *p_inputs[1]; else *p_outputs[0] = *p_inputs[2]; return 0; } }; VisualScriptNodeInstance *VisualScriptSelect::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSelect *instance = memnew(VisualScriptNodeInstanceSelect); return instance; } VisualScriptSelect::VisualScriptSelect() { typed = VariantType::NIL; } ////////////////////////////////////////// ////////////////VARIABLE GET////////////////// ////////////////////////////////////////// int VisualScriptVariableGet::get_output_sequence_port_count() const { return 0; } bool VisualScriptVariableGet::has_input_sequence_port() const { return false; } int VisualScriptVariableGet::get_input_value_port_count() const { return 0; } int VisualScriptVariableGet::get_output_value_port_count() const { return 1; } StringView VisualScriptVariableGet::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptVariableGet::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptVariableGet::get_output_value_port_info(int p_idx) const { PropertyInfo pinfo; pinfo.name = "value"; if (get_visual_script() && get_visual_script()->has_variable(variable)) { PropertyInfo vinfo = get_visual_script()->get_variable_info(variable); pinfo.type = vinfo.type; pinfo.hint = vinfo.hint; pinfo.hint_string = vinfo.hint_string; } return pinfo; } StringView VisualScriptVariableGet::get_caption() const { thread_local char buf[512]; buf[0]=0; strncat(buf,"Get ",511); strncat(buf,variable.asCString(),511); return buf; } void VisualScriptVariableGet::set_variable(StringName p_variable) { if (variable == p_variable) return; variable = p_variable; ports_changed_notify(); } StringName VisualScriptVariableGet::get_variable() const { return variable; } void VisualScriptVariableGet::_validate_property(PropertyInfo &property) const { if (property.name == "var_name" && get_visual_script()) { Ref<VisualScript> vs = get_visual_script(); Vector<StringName> vars; vs->get_variable_list(&vars); String vhint; for (int i=0,fin=vars.size(); i<fin; ++i) { if (!vhint.empty()) vhint += (","); vhint += vars[i].asCString(); } property.hint = PropertyHint::Enum; property.hint_string = vhint; } } void VisualScriptVariableGet::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_variable", {"name"}), &VisualScriptVariableGet::set_variable); MethodBinder::bind_method(D_METHOD("get_variable"), &VisualScriptVariableGet::get_variable); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "var_name"), "set_variable", "get_variable"); } class VisualScriptNodeInstanceVariableGet : public VisualScriptNodeInstance { public: VisualScriptVariableGet *node; VisualScriptInstance *instance; StringName variable; int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!instance->get_variable(variable, p_outputs[0])) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR_utf8("VariableGet not found in script: ") + "'" + String(variable) + "'"; return 0; } return 0; } }; VisualScriptNodeInstance *VisualScriptVariableGet::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceVariableGet *instance = memnew(VisualScriptNodeInstanceVariableGet); instance->node = this; instance->instance = p_instance; instance->variable = variable; return instance; } VisualScriptVariableGet::VisualScriptVariableGet() { } ////////////////////////////////////////// ////////////////VARIABLE SET////////////////// ////////////////////////////////////////// int VisualScriptVariableSet::get_output_sequence_port_count() const { return 1; } bool VisualScriptVariableSet::has_input_sequence_port() const { return true; } int VisualScriptVariableSet::get_input_value_port_count() const { return 1; } int VisualScriptVariableSet::get_output_value_port_count() const { return 0; } StringView VisualScriptVariableSet::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptVariableSet::get_input_value_port_info(int p_idx) const { PropertyInfo pinfo; pinfo.name = "set"; if (get_visual_script() && get_visual_script()->has_variable(variable)) { PropertyInfo vinfo = get_visual_script()->get_variable_info(variable); pinfo.type = vinfo.type; pinfo.hint = vinfo.hint; pinfo.hint_string = vinfo.hint_string; } return pinfo; } PropertyInfo VisualScriptVariableSet::get_output_value_port_info(int p_idx) const { return PropertyInfo(); } StringView VisualScriptVariableSet::get_caption() const { thread_local char buf[512]; buf[0]=0; strncat(buf,"Set ",511); strncat(buf,variable.asCString(),511); return buf; } void VisualScriptVariableSet::set_variable(StringName p_variable) { if (variable == p_variable) return; variable = p_variable; ports_changed_notify(); } StringName VisualScriptVariableSet::get_variable() const { return variable; } void VisualScriptVariableSet::_validate_property(PropertyInfo &property) const { if (property.name == "var_name" && get_visual_script()) { Ref<VisualScript> vs = get_visual_script(); Vector<StringName> vars; vs->get_variable_list(&vars); String vhint; for (int i=0,fin=vars.size(); i<fin; ++i) { if (!vhint.empty()) vhint += (","); vhint += vars[i].asCString(); } property.hint = PropertyHint::Enum; property.hint_string = vhint; } } void VisualScriptVariableSet::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_variable", {"name"}), &VisualScriptVariableSet::set_variable); MethodBinder::bind_method(D_METHOD("get_variable"), &VisualScriptVariableSet::get_variable); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "var_name"), "set_variable", "get_variable"); } class VisualScriptNodeInstanceVariableSet : public VisualScriptNodeInstance { public: VisualScriptVariableSet *node; VisualScriptInstance *instance; StringName variable; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!instance->set_variable(variable, *p_inputs[0])) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = RTR_utf8("VariableSet not found in script: ") + "'" + variable + "'"; } return 0; } }; VisualScriptNodeInstance *VisualScriptVariableSet::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceVariableSet *instance = memnew(VisualScriptNodeInstanceVariableSet); instance->node = this; instance->instance = p_instance; instance->variable = variable; return instance; } VisualScriptVariableSet::VisualScriptVariableSet() { } ////////////////////////////////////////// ////////////////CONSTANT////////////////// ////////////////////////////////////////// int VisualScriptConstant::get_output_sequence_port_count() const { return 0; } bool VisualScriptConstant::has_input_sequence_port() const { return false; } int VisualScriptConstant::get_input_value_port_count() const { return 0; } int VisualScriptConstant::get_output_value_port_count() const { return 1; } StringView VisualScriptConstant::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptConstant::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptConstant::get_output_value_port_info(int p_idx) const { PropertyInfo pinfo; pinfo.name = value.as<StringName>(); pinfo.type = type; return pinfo; } StringView VisualScriptConstant::get_caption() const { return ("Constant"); } void VisualScriptConstant::set_constant_type(VariantType p_type) { if (type == p_type) return; type = p_type; Callable::CallError ce; value = Variant::construct(type, nullptr, 0, ce); ports_changed_notify(); Object_change_notify(this); } VariantType VisualScriptConstant::get_constant_type() const { return type; } void VisualScriptConstant::set_constant_value(Variant p_value) { if (value == p_value) return; value = p_value; ports_changed_notify(); } Variant VisualScriptConstant::get_constant_value() const { return value; } void VisualScriptConstant::_validate_property(PropertyInfo &property) const { if (property.name == "value") { property.type = type; if (type == VariantType::NIL) property.usage = 0; //do not save if nil } } void VisualScriptConstant::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_constant_type", {"type"}), &VisualScriptConstant::set_constant_type); MethodBinder::bind_method(D_METHOD("get_constant_type"), &VisualScriptConstant::get_constant_type); MethodBinder::bind_method(D_METHOD("set_constant_value", {"value"}), &VisualScriptConstant::set_constant_value); MethodBinder::bind_method(D_METHOD("get_constant_value"), &VisualScriptConstant::get_constant_value); char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX]; fill_with_all_variant_types("Null",argt); ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_constant_type", "get_constant_type"); ADD_PROPERTY(PropertyInfo(VariantType::NIL, "value", PropertyHint::None, "", PROPERTY_USAGE_NIL_IS_VARIANT | PROPERTY_USAGE_DEFAULT), "set_constant_value", "get_constant_value"); } class VisualScriptNodeInstanceConstant : public VisualScriptNodeInstance { public: Variant constant; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = constant; return 0; } }; VisualScriptNodeInstance *VisualScriptConstant::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceConstant *instance = memnew(VisualScriptNodeInstanceConstant); instance->constant = value; return instance; } VisualScriptConstant::VisualScriptConstant() { type = VariantType::NIL; } ////////////////////////////////////////// ////////////////PRELOAD////////////////// ////////////////////////////////////////// int VisualScriptPreload::get_output_sequence_port_count() const { return 0; } bool VisualScriptPreload::has_input_sequence_port() const { return false; } int VisualScriptPreload::get_input_value_port_count() const { return 0; } int VisualScriptPreload::get_output_value_port_count() const { return 1; } StringView VisualScriptPreload::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptPreload::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptPreload::get_output_value_port_info(int p_idx) const { PropertyInfo pinfo; pinfo.type = VariantType::OBJECT; if (preload) { pinfo.hint = PropertyHint::ResourceType; pinfo.hint_string = preload->get_class(); if (PathUtils::is_resource_file(preload->get_path())) { pinfo.name = StringName(preload->get_path()); } else if (!preload->get_name().empty()) { pinfo.name = StringName(preload->get_name()); } else { pinfo.name = StringName(preload->get_class()); } } else { pinfo.name = "<empty>"; } return pinfo; } StringView VisualScriptPreload::get_caption() const { return ("Preload"); } void VisualScriptPreload::set_preload(const Ref<Resource> &p_preload) { if (preload == p_preload) return; preload = p_preload; ports_changed_notify(); } Ref<Resource> VisualScriptPreload::get_preload() const { return preload; } void VisualScriptPreload::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_preload", {"resource"}), &VisualScriptPreload::set_preload); MethodBinder::bind_method(D_METHOD("get_preload"), &VisualScriptPreload::get_preload); ADD_PROPERTY(PropertyInfo(VariantType::OBJECT, "resource", PropertyHint::ResourceType, "Resource"), "set_preload", "get_preload"); } class VisualScriptNodeInstancePreload : public VisualScriptNodeInstance { public: Ref<Resource> preload; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = preload; return 0; } }; VisualScriptNodeInstance *VisualScriptPreload::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstancePreload *instance = memnew(VisualScriptNodeInstancePreload); instance->preload = preload; return instance; } VisualScriptPreload::VisualScriptPreload() { } ////////////////////////////////////////// ////////////////INDEX//////////////////// ////////////////////////////////////////// int VisualScriptIndexGet::get_output_sequence_port_count() const { return 0; } bool VisualScriptIndexGet::has_input_sequence_port() const { return false; } int VisualScriptIndexGet::get_input_value_port_count() const { return 2; } int VisualScriptIndexGet::get_output_value_port_count() const { return 1; } StringView VisualScriptIndexGet::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptIndexGet::get_input_value_port_info(int p_idx) const { if (p_idx == 0) { return PropertyInfo(VariantType::NIL, "base"); } else { return PropertyInfo(VariantType::NIL, "index"); } } PropertyInfo VisualScriptIndexGet::get_output_value_port_info(int p_idx) const { return PropertyInfo(); } StringView VisualScriptIndexGet::get_caption() const { return ("Get Index"); } class VisualScriptNodeInstanceIndexGet : public VisualScriptNodeInstance { public: //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool valid; *p_outputs[0] = p_inputs[0]->get(*p_inputs[1], &valid); if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Invalid get: " + p_inputs[0]->get_construct_string(); } return 0; } }; VisualScriptNodeInstance *VisualScriptIndexGet::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceIndexGet *instance = memnew(VisualScriptNodeInstanceIndexGet); return instance; } VisualScriptIndexGet::VisualScriptIndexGet() { } ////////////////////////////////////////// ////////////////INDEXSET////////////////// ////////////////////////////////////////// int VisualScriptIndexSet::get_output_sequence_port_count() const { return 1; } bool VisualScriptIndexSet::has_input_sequence_port() const { return true; } int VisualScriptIndexSet::get_input_value_port_count() const { return 3; } int VisualScriptIndexSet::get_output_value_port_count() const { return 0; } StringView VisualScriptIndexSet::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptIndexSet::get_input_value_port_info(int p_idx) const { if (p_idx == 0) { return PropertyInfo(VariantType::NIL, "base"); } else if (p_idx == 1) { return PropertyInfo(VariantType::NIL, "index"); } else { return PropertyInfo(VariantType::NIL, "value"); } } PropertyInfo VisualScriptIndexSet::get_output_value_port_info(int p_idx) const { return PropertyInfo(); } StringView VisualScriptIndexSet::get_caption() const { return ("Set Index"); } class VisualScriptNodeInstanceIndexSet : public VisualScriptNodeInstance { public: //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { bool valid; *p_outputs[0] = *p_inputs[0]; p_outputs[0]->set(*p_inputs[1], *p_inputs[2], &valid); if (!valid) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Invalid set: " + p_inputs[1]->get_construct_string(); } return 0; } }; VisualScriptNodeInstance *VisualScriptIndexSet::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceIndexSet *instance = memnew(VisualScriptNodeInstanceIndexSet); return instance; } VisualScriptIndexSet::VisualScriptIndexSet() { } ////////////////////////////////////////// ////////////////GLOBALCONSTANT/////////// ////////////////////////////////////////// int VisualScriptGlobalConstant::get_output_sequence_port_count() const { return 0; } bool VisualScriptGlobalConstant::has_input_sequence_port() const { return false; } int VisualScriptGlobalConstant::get_input_value_port_count() const { return 0; } int VisualScriptGlobalConstant::get_output_value_port_count() const { return 1; } StringView VisualScriptGlobalConstant::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptGlobalConstant::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptGlobalConstant::get_output_value_port_info(int p_idx) const { return PropertyInfo(VariantType::INT, StringName(GlobalConstants::get_global_constant_name(index))); } StringView VisualScriptGlobalConstant::get_caption() const { return ("Global Constant"); } void VisualScriptGlobalConstant::set_global_constant(int p_which) { index = p_which; Object_change_notify(this); ports_changed_notify(); } int VisualScriptGlobalConstant::get_global_constant() { return index; } class VisualScriptNodeInstanceGlobalConstant : public VisualScriptNodeInstance { public: int index; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = GlobalConstants::get_global_constant_value(index); return 0; } }; VisualScriptNodeInstance *VisualScriptGlobalConstant::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceGlobalConstant *instance = memnew(VisualScriptNodeInstanceGlobalConstant); instance->index = index; return instance; } void VisualScriptGlobalConstant::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_global_constant", {"index"}), &VisualScriptGlobalConstant::set_global_constant); MethodBinder::bind_method(D_METHOD("get_global_constant"), &VisualScriptGlobalConstant::get_global_constant); String cc; for (int i = 0; i < GlobalConstants::get_global_constant_count(); i++) { if (i > 0) cc += ","; cc += String(GlobalConstants::get_global_constant_name(i)); } ADD_PROPERTY(PropertyInfo(VariantType::INT, "constant", PropertyHint::Enum, StringName(cc)), "set_global_constant", "get_global_constant"); } VisualScriptGlobalConstant::VisualScriptGlobalConstant() { index = 0; } ////////////////////////////////////////// ////////////////CLASSCONSTANT/////////// ////////////////////////////////////////// int VisualScriptClassConstant::get_output_sequence_port_count() const { return 0; } bool VisualScriptClassConstant::has_input_sequence_port() const { return false; } int VisualScriptClassConstant::get_input_value_port_count() const { return 0; } int VisualScriptClassConstant::get_output_value_port_count() const { return 1; } StringView VisualScriptClassConstant::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptClassConstant::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptClassConstant::get_output_value_port_info(int p_idx) const { return PropertyInfo(VariantType::INT, StringName(String(base_type) + "." + name)); } StringView VisualScriptClassConstant::get_caption() const { return ("Class Constant"); } void VisualScriptClassConstant::set_class_constant(const StringName &p_which) { name = p_which; Object_change_notify(this); ports_changed_notify(); } StringName VisualScriptClassConstant::get_class_constant() { return name; } void VisualScriptClassConstant::set_base_type(const StringName &p_which) { base_type = p_which; List<String> constants; ClassDB::get_integer_constant_list(base_type, &constants, true); if (constants.size() > 0) { bool found_name = false; for (const String &E : constants) { if (E == name) { found_name = true; break; } } if (!found_name) { name = StringName(constants.front()); } } else { name = ""; } Object_change_notify(this); ports_changed_notify(); } StringName VisualScriptClassConstant::get_base_type() { return base_type; } class VisualScriptNodeInstanceClassConstant : public VisualScriptNodeInstance { public: int value; bool valid; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!valid) { r_error_str = "Invalid constant name, pick a valid class constant."; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; } *p_outputs[0] = value; return 0; } }; VisualScriptNodeInstance *VisualScriptClassConstant::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceClassConstant *instance = memnew(VisualScriptNodeInstanceClassConstant); instance->value = ClassDB::get_integer_constant(base_type, name, &instance->valid); return instance; } void VisualScriptClassConstant::_validate_property(PropertyInfo &property) const { if (property.name == "constant") { List<String> constants; ClassDB::get_integer_constant_list(base_type, &constants, true); property.hint_string = ""; for(const String & E : constants) { if (!property.hint_string.empty()) { property.hint_string += ","; } property.hint_string += E; } } } void VisualScriptClassConstant::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_class_constant", {"name"}), &VisualScriptClassConstant::set_class_constant); MethodBinder::bind_method(D_METHOD("get_class_constant"), &VisualScriptClassConstant::get_class_constant); MethodBinder::bind_method(D_METHOD("set_base_type", {"name"}), &VisualScriptClassConstant::set_base_type); MethodBinder::bind_method(D_METHOD("get_base_type"), &VisualScriptClassConstant::get_base_type); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "base_type", PropertyHint::TypeString, "Object"), "set_base_type", "get_base_type"); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "constant", PropertyHint::Enum, ""), "set_class_constant", "get_class_constant"); } VisualScriptClassConstant::VisualScriptClassConstant() { base_type = "Object"; } ////////////////////////////////////////// ////////////////BASICTYPECONSTANT/////////// ////////////////////////////////////////// int VisualScriptBasicTypeConstant::get_output_sequence_port_count() const { return 0; } bool VisualScriptBasicTypeConstant::has_input_sequence_port() const { return false; } int VisualScriptBasicTypeConstant::get_input_value_port_count() const { return 0; } int VisualScriptBasicTypeConstant::get_output_value_port_count() const { return 1; } StringView VisualScriptBasicTypeConstant::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptBasicTypeConstant::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptBasicTypeConstant::get_output_value_port_info(int p_idx) const { return PropertyInfo(type, "value"); } StringView VisualScriptBasicTypeConstant::get_caption() const { return "Basic Constant"; } String VisualScriptBasicTypeConstant::get_text() const { if (name.empty()) { return Variant::get_type_name(type); } else { return String(Variant::get_type_name(type)) + "." + name; } } void VisualScriptBasicTypeConstant::set_basic_type_constant(const StringName &p_which) { name = p_which; Object_change_notify(this); ports_changed_notify(); } StringName VisualScriptBasicTypeConstant::get_basic_type_constant() const { return name; } void VisualScriptBasicTypeConstant::set_basic_type(VariantType p_which) { type = p_which; Vector<StringName> constants; Variant::get_constants_for_type(type, &constants); if (constants.size() > 0) { bool found_name = false; for (const StringName &E : constants) { if (name == StringView(E)) { found_name = true; break; } } if (!found_name) { name = constants[0]; } } else { name = ""; } Object_change_notify(this); ports_changed_notify(); } VariantType VisualScriptBasicTypeConstant::get_basic_type() const { return type; } class VisualScriptNodeInstanceBasicTypeConstant : public VisualScriptNodeInstance { public: Variant value; bool valid; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!valid) { r_error_str = "Invalid constant name, pick a valid basic type constant."; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; } *p_outputs[0] = value; return 0; } }; VisualScriptNodeInstance *VisualScriptBasicTypeConstant::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceBasicTypeConstant *instance = memnew(VisualScriptNodeInstanceBasicTypeConstant); instance->value = Variant::get_constant_value(type, name, &instance->valid); return instance; } void VisualScriptBasicTypeConstant::_validate_property(PropertyInfo &property) const { if (property.name == "constant") { Vector<StringName> constants; Variant::get_constants_for_type(type, &constants); if (constants.empty()) { property.usage = 0; return; } property.hint_string = ""; for (const StringName &E : constants) { if (!property.hint_string.empty()) { property.hint_string += (","); } property.hint_string += E; } } } void VisualScriptBasicTypeConstant::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_basic_type", {"name"}), &VisualScriptBasicTypeConstant::set_basic_type); MethodBinder::bind_method(D_METHOD("get_basic_type"), &VisualScriptBasicTypeConstant::get_basic_type); MethodBinder::bind_method(D_METHOD("set_basic_type_constant", {"name"}), &VisualScriptBasicTypeConstant::set_basic_type_constant); MethodBinder::bind_method(D_METHOD("get_basic_type_constant"), &VisualScriptBasicTypeConstant::get_basic_type_constant); char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX]; fill_with_all_variant_types("Null",argt); ADD_PROPERTY(PropertyInfo(VariantType::INT, "basic_type", PropertyHint::Enum, argt), "set_basic_type", "get_basic_type"); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "constant", PropertyHint::Enum, ""), "set_basic_type_constant", "get_basic_type_constant"); } VisualScriptBasicTypeConstant::VisualScriptBasicTypeConstant() { type = VariantType::NIL; } ////////////////////////////////////////// ////////////////MATHCONSTANT/////////// ////////////////////////////////////////// const char *VisualScriptMathConstant::const_name[MATH_CONSTANT_MAX] = { "One", "PI", "PI/2", "TAU", "E", "Sqrt2", "INF", "NAN" }; double VisualScriptMathConstant::const_value[MATH_CONSTANT_MAX] = { 1.0, Math_PI, Math_PI * 0.5, Math_TAU, 2.71828182845904523536, Math::sqrt(2.0), Math_INF, Math_NAN }; int VisualScriptMathConstant::get_output_sequence_port_count() const { return 0; } bool VisualScriptMathConstant::has_input_sequence_port() const { return false; } int VisualScriptMathConstant::get_input_value_port_count() const { return 0; } int VisualScriptMathConstant::get_output_value_port_count() const { return 1; } StringView VisualScriptMathConstant::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptMathConstant::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptMathConstant::get_output_value_port_info(int p_idx) const { return PropertyInfo(VariantType::FLOAT, StaticCString(const_name[constant],true)); } StringView VisualScriptMathConstant::get_caption() const { return ("Math Constant"); } void VisualScriptMathConstant::set_math_constant(MathConstant p_which) { constant = p_which; Object_change_notify(this); ports_changed_notify(); } VisualScriptMathConstant::MathConstant VisualScriptMathConstant::get_math_constant() { return constant; } class VisualScriptNodeInstanceMathConstant : public VisualScriptNodeInstance { public: float value; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = value; return 0; } }; VisualScriptNodeInstance *VisualScriptMathConstant::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceMathConstant *instance = memnew(VisualScriptNodeInstanceMathConstant); instance->value = const_value[constant]; return instance; } void VisualScriptMathConstant::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_math_constant", {"which"}), &VisualScriptMathConstant::set_math_constant); MethodBinder::bind_method(D_METHOD("get_math_constant"), &VisualScriptMathConstant::get_math_constant); String cc; for (int i = 0; i < MATH_CONSTANT_MAX; i++) { if (i > 0) cc += (","); cc += (const_name[i]); } ADD_PROPERTY(PropertyInfo(VariantType::INT, "constant", PropertyHint::Enum, StringName(cc)), "set_math_constant", "get_math_constant"); BIND_ENUM_CONSTANT(MATH_CONSTANT_ONE) BIND_ENUM_CONSTANT(MATH_CONSTANT_PI) BIND_ENUM_CONSTANT(MATH_CONSTANT_HALF_PI) BIND_ENUM_CONSTANT(MATH_CONSTANT_TAU) BIND_ENUM_CONSTANT(MATH_CONSTANT_E) BIND_ENUM_CONSTANT(MATH_CONSTANT_SQRT2) BIND_ENUM_CONSTANT(MATH_CONSTANT_INF) BIND_ENUM_CONSTANT(MATH_CONSTANT_NAN) BIND_ENUM_CONSTANT(MATH_CONSTANT_MAX) } VisualScriptMathConstant::VisualScriptMathConstant() { constant = MATH_CONSTANT_ONE; } ////////////////////////////////////////// ////////////////ENGINESINGLETON/////////// ////////////////////////////////////////// int VisualScriptEngineSingleton::get_output_sequence_port_count() const { return 0; } bool VisualScriptEngineSingleton::has_input_sequence_port() const { return false; } int VisualScriptEngineSingleton::get_input_value_port_count() const { return 0; } int VisualScriptEngineSingleton::get_output_value_port_count() const { return 1; } StringView VisualScriptEngineSingleton::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptEngineSingleton::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptEngineSingleton::get_output_value_port_info(int p_idx) const { return PropertyInfo(VariantType::OBJECT, singleton); } StringView VisualScriptEngineSingleton::get_caption() const { return ("Get Engine Singleton"); } void VisualScriptEngineSingleton::set_singleton(const StringName &p_string) { singleton = p_string; Object_change_notify(this); ports_changed_notify(); } StringName VisualScriptEngineSingleton::get_singleton() { return singleton; } class VisualScriptNodeInstanceEngineSingleton : public VisualScriptNodeInstance { public: Object *singleton; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = Variant(singleton); return 0; } }; VisualScriptNodeInstance *VisualScriptEngineSingleton::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceEngineSingleton *instance = memnew(VisualScriptNodeInstanceEngineSingleton); instance->singleton = Engine::get_singleton()->get_named_singleton(singleton); return instance; } VisualScriptEngineSingleton::TypeGuess VisualScriptEngineSingleton::guess_output_type(TypeGuess *p_inputs, int p_output) const { Object *obj = Engine::get_singleton()->get_named_singleton(singleton); TypeGuess tg; tg.type = VariantType::OBJECT; if (obj) { tg.gdclass = obj->get_class_name(); tg.script = refFromRefPtr<Script>(obj->get_script()); } return tg; } void VisualScriptEngineSingleton::_validate_property(PropertyInfo &property) const { String cc; const Vector<Engine::Singleton> &singletons = Engine::get_singleton()->get_singletons(); for (const Engine::Singleton &E : singletons) { if (E.name == "VS" || E.name == "PS" || E.name == "PS2D" || E.name == "AS" || E.name == "TS" || E.name == "SS" || E.name == "SS2D") continue; //skip these, too simple named if (!cc.empty()) cc += ","; cc += E.name; } property.hint = PropertyHint::Enum; property.hint_string = cc; } void VisualScriptEngineSingleton::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_singleton", {"name"}), &VisualScriptEngineSingleton::set_singleton); MethodBinder::bind_method(D_METHOD("get_singleton"), &VisualScriptEngineSingleton::get_singleton); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "constant"), "set_singleton", "get_singleton"); } VisualScriptEngineSingleton::VisualScriptEngineSingleton() { singleton = StringName(); } ////////////////////////////////////////// ////////////////GETNODE/////////// ////////////////////////////////////////// int VisualScriptSceneNode::get_output_sequence_port_count() const { return 0; } bool VisualScriptSceneNode::has_input_sequence_port() const { return false; } int VisualScriptSceneNode::get_input_value_port_count() const { return 0; } int VisualScriptSceneNode::get_output_value_port_count() const { return 1; } StringView VisualScriptSceneNode::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptSceneNode::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptSceneNode::get_output_value_port_info(int p_idx) const { return PropertyInfo(VariantType::OBJECT, StringName((String)path.simplified())); } StringView VisualScriptSceneNode::get_caption() const { return ("Get Scene Node"); } void VisualScriptSceneNode::set_node_path(const NodePath &p_path) { path = p_path; Object_change_notify(this); ports_changed_notify(); } NodePath VisualScriptSceneNode::get_node_path() { return path; } class VisualScriptNodeInstanceSceneNode : public VisualScriptNodeInstance { public: VisualScriptSceneNode *node; VisualScriptInstance *instance; NodePath path; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Node *node = object_cast<Node>(instance->get_owner_ptr()); if (!node) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Base object is not a Node!"; return 0; } Node *another = node->get_node(path); if (!another) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Path does not lead Node!"; return 0; } *p_outputs[0] = Variant(another); return 0; } }; VisualScriptNodeInstance *VisualScriptSceneNode::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSceneNode *instance = memnew(VisualScriptNodeInstanceSceneNode); instance->node = this; instance->instance = p_instance; instance->path = path; return instance; } VisualScriptSceneNode::TypeGuess VisualScriptSceneNode::guess_output_type(TypeGuess *p_inputs, int p_output) const { VisualScriptSceneNode::TypeGuess tg; tg.type = VariantType::OBJECT; tg.gdclass = "Node"; #ifdef TOOLS_ENABLED Ref<Script> script = get_visual_script(); if (not script) return tg; MainLoop *main_loop = OS::get_singleton()->get_main_loop(); SceneTree *scene_tree = object_cast<SceneTree>(main_loop); if (!scene_tree) return tg; Node *edited_scene = scene_tree->get_edited_scene_root(); if (!edited_scene) return tg; Node *script_node = _find_script_node(edited_scene, edited_scene, script); if (!script_node) return tg; Node *another = script_node->get_node(path); if (another) { tg.gdclass = another->get_class_name(); tg.script = refFromRefPtr<Script>(another->get_script()); } #endif return tg; } void VisualScriptSceneNode::_validate_property(PropertyInfo &property) const { #ifdef TOOLS_ENABLED if (property.name == "node_path") { Ref<Script> script = get_visual_script(); if (not script) return; MainLoop *main_loop = OS::get_singleton()->get_main_loop(); SceneTree *scene_tree = object_cast<SceneTree>(main_loop); if (!scene_tree) return; Node *edited_scene = scene_tree->get_edited_scene_root(); if (!edited_scene) return; Node *script_node = _find_script_node(edited_scene, edited_scene, script); if (!script_node) return; property.hint_string = (String)script_node->get_path(); } #endif } void VisualScriptSceneNode::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_node_path", {"path"}), &VisualScriptSceneNode::set_node_path); MethodBinder::bind_method(D_METHOD("get_node_path"), &VisualScriptSceneNode::get_node_path); ADD_PROPERTY(PropertyInfo(VariantType::NODE_PATH, "node_path", PropertyHint::NodePathToEditedNode), "set_node_path", "get_node_path"); } VisualScriptSceneNode::VisualScriptSceneNode() { path = NodePath("."); } ////////////////////////////////////////// ////////////////SceneTree/////////// ////////////////////////////////////////// int VisualScriptSceneTree::get_output_sequence_port_count() const { return 0; } bool VisualScriptSceneTree::has_input_sequence_port() const { return false; } int VisualScriptSceneTree::get_input_value_port_count() const { return 0; } int VisualScriptSceneTree::get_output_value_port_count() const { return 1; } StringView VisualScriptSceneTree::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptSceneTree::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptSceneTree::get_output_value_port_info(int p_idx) const { return PropertyInfo(VariantType::OBJECT, "Scene Tree", PropertyHint::TypeString, "SceneTree"); } StringView VisualScriptSceneTree::get_caption() const { return "Get Scene Tree"; } class VisualScriptNodeInstanceSceneTree : public VisualScriptNodeInstance { public: VisualScriptSceneTree *node; VisualScriptInstance *instance; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Node *node = object_cast<Node>(instance->get_owner_ptr()); if (!node) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Base object is not a Node!"; return 0; } SceneTree *tree = node->get_tree(); if (!tree) { r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; r_error_str = "Attempt to get SceneTree while node is not in the active tree."; return 0; } *p_outputs[0] = Variant(tree); return 0; } }; VisualScriptNodeInstance *VisualScriptSceneTree::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSceneTree *instance = memnew(VisualScriptNodeInstanceSceneTree); instance->node = this; instance->instance = p_instance; return instance; } VisualScriptSceneTree::TypeGuess VisualScriptSceneTree::guess_output_type(TypeGuess *p_inputs, int p_output) const { TypeGuess tg; tg.type = VariantType::OBJECT; tg.gdclass = "SceneTree"; return tg; } void VisualScriptSceneTree::_validate_property(PropertyInfo &property) const { } void VisualScriptSceneTree::_bind_methods() { } VisualScriptSceneTree::VisualScriptSceneTree() { } ////////////////////////////////////////// ////////////////RESPATH/////////// ////////////////////////////////////////// int VisualScriptResourcePath::get_output_sequence_port_count() const { return 0; } bool VisualScriptResourcePath::has_input_sequence_port() const { return false; } int VisualScriptResourcePath::get_input_value_port_count() const { return 0; } int VisualScriptResourcePath::get_output_value_port_count() const { return 1; } StringView VisualScriptResourcePath::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptResourcePath::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptResourcePath::get_output_value_port_info(int p_idx) const { return PropertyInfo(VariantType::STRING, StringName(path)); } StringView VisualScriptResourcePath::get_caption() const { return ("Resource Path"); } void VisualScriptResourcePath::set_resource_path(StringView p_path) { path = p_path; Object_change_notify(this); ports_changed_notify(); } const String & VisualScriptResourcePath::get_resource_path() { return path; } class VisualScriptNodeInstanceResourcePath : public VisualScriptNodeInstance { public: String path; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = path; return 0; } }; VisualScriptNodeInstance *VisualScriptResourcePath::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceResourcePath *instance = memnew(VisualScriptNodeInstanceResourcePath); instance->path = path; return instance; } void VisualScriptResourcePath::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_resource_path", {"path"}), &VisualScriptResourcePath::set_resource_path); MethodBinder::bind_method(D_METHOD("get_resource_path"), &VisualScriptResourcePath::get_resource_path); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "path", PropertyHint::File), "set_resource_path", "get_resource_path"); } VisualScriptResourcePath::VisualScriptResourcePath() { path = ""; } ////////////////////////////////////////// ////////////////SELF/////////// ////////////////////////////////////////// int VisualScriptSelf::get_output_sequence_port_count() const { return 0; } bool VisualScriptSelf::has_input_sequence_port() const { return false; } int VisualScriptSelf::get_input_value_port_count() const { return 0; } int VisualScriptSelf::get_output_value_port_count() const { return 1; } StringView VisualScriptSelf::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptSelf::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptSelf::get_output_value_port_info(int p_idx) const { StringName type_name; if (get_visual_script()) type_name = get_visual_script()->get_instance_base_type(); else type_name = "instance"; return PropertyInfo(VariantType::OBJECT, type_name); } StringView VisualScriptSelf::get_caption() const { return ("Get Self"); } class VisualScriptNodeInstanceSelf : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = Variant(instance->get_owner_ptr()); return 0; } }; VisualScriptNodeInstance *VisualScriptSelf::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSelf *instance = memnew(VisualScriptNodeInstanceSelf); instance->instance = p_instance; return instance; } VisualScriptSelf::TypeGuess VisualScriptSelf::guess_output_type(TypeGuess *p_inputs, int p_output) const { VisualScriptSceneNode::TypeGuess tg; tg.type = VariantType::OBJECT; tg.gdclass = "Object"; Ref<Script> script = get_visual_script(); if (not script) return tg; tg.gdclass = script->get_instance_base_type(); tg.script = script; return tg; } void VisualScriptSelf::_bind_methods() { } VisualScriptSelf::VisualScriptSelf() { } ////////////////////////////////////////// ////////////////CUSTOM (SCRIPTED)/////////// ////////////////////////////////////////// int VisualScriptCustomNode::get_output_sequence_port_count() const { if (get_script_instance() && get_script_instance()->has_method("_get_output_sequence_port_count")) { return get_script_instance()->call("_get_output_sequence_port_count").as<int>(); } return 0; } bool VisualScriptCustomNode::has_input_sequence_port() const { if (get_script_instance() && get_script_instance()->has_method("_has_input_sequence_port")) { return get_script_instance()->call("_has_input_sequence_port").as<bool>(); } return false; } int VisualScriptCustomNode::get_input_value_port_count() const { if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_count")) { return get_script_instance()->call("_get_input_value_port_count").as<int>(); } return 0; } int VisualScriptCustomNode::get_output_value_port_count() const { if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_count")) { return get_script_instance()->call("_get_output_value_port_count").as<int>(); } return 0; } StringView VisualScriptCustomNode::get_output_sequence_port_text(int p_port) const { if (get_script_instance() && get_script_instance()->has_method("_get_output_sequence_port_text")) { static String val; val = get_script_instance()->call("_get_output_sequence_port_text", p_port).as<String>(); return val; } return StringView(); } PropertyInfo VisualScriptCustomNode::get_input_value_port_info(int p_idx) const { PropertyInfo info; if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_type")) { info.type = get_script_instance()->call("_get_input_value_port_type", p_idx).as<VariantType>(); } if (get_script_instance() && get_script_instance()->has_method("_get_input_value_port_name")) { info.name = get_script_instance()->call("_get_input_value_port_name", p_idx).as<StringName>(); } return info; } PropertyInfo VisualScriptCustomNode::get_output_value_port_info(int p_idx) const { PropertyInfo info; if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_type")) { info.type = get_script_instance()->call("_get_output_value_port_type", p_idx).as<VariantType>(); } if (get_script_instance() && get_script_instance()->has_method("_get_output_value_port_name")) { info.name = get_script_instance()->call("_get_output_value_port_name", p_idx).as<StringName>(); } return info; } StringView VisualScriptCustomNode::get_caption() const { thread_local char buf[512]; if (get_script_instance() && get_script_instance()->has_method("_get_caption")) { buf[0]=0; strncat(buf,get_script_instance()->call("_get_caption").as<String>().c_str(),511); return buf; } return "CustomNode"; } String VisualScriptCustomNode::get_text() const { if (get_script_instance() && get_script_instance()->has_method("_get_text")) { return get_script_instance()->call("_get_text").as<String>(); } return String(); } const char *VisualScriptCustomNode::get_category() const { if (get_script_instance() && get_script_instance()->has_method("_get_category")) { static char buf[256]; strncpy(buf,get_script_instance()->call("_get_category").as<String>().c_str(),255); return buf; } return "Custom"; } class VisualScriptNodeInstanceCustomNode : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; VisualScriptCustomNode *node; int in_count; int out_count; int work_mem_size; int get_working_memory_size() const override { return work_mem_size; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (node->get_script_instance()) { #ifdef DEBUG_ENABLED if (!node->get_script_instance()->has_method(VisualScriptLanguage::singleton->_step)) { r_error_str = RTR_utf8("Custom node has no _step() method, can't process graph."); r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; return 0; } #endif Array in_values; Array out_values; Array work_mem; in_values.resize(in_count); for (int i = 0; i < in_count; i++) { in_values[i] = *p_inputs[i]; } out_values.resize(out_count); work_mem.resize(work_mem_size); for (int i = 0; i < work_mem_size; i++) { work_mem[i] = p_working_mem[i]; } int ret_out; Variant ret = node->get_script_instance()->call(VisualScriptLanguage::singleton->_step, in_values, out_values, p_start_mode, work_mem); if (ret.get_type() == VariantType::STRING) { r_error_str = ret.as<String>(); r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; return 0; } else if (ret.is_num()) { ret_out = ret.as<int>(); } else { r_error_str = RTR_utf8("Invalid return value from _step(), must be integer (seq out), or string (error)."); r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; return 0; } for (int i = 0; i < out_count; i++) { if (i < out_values.size()) { *p_outputs[i] = out_values[i]; } } for (int i = 0; i < work_mem_size; i++) { if (i < work_mem.size()) { p_working_mem[i] = work_mem[i]; } } return ret_out; } return 0; } }; VisualScriptNodeInstance *VisualScriptCustomNode::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceCustomNode *instance = memnew(VisualScriptNodeInstanceCustomNode); instance->instance = p_instance; instance->node = this; instance->in_count = get_input_value_port_count(); instance->out_count = get_output_value_port_count(); if (get_script_instance() && get_script_instance()->has_method("_get_working_memory_size")) { instance->work_mem_size = get_script_instance()->call("_get_working_memory_size").as<int>(); } else { instance->work_mem_size = 0; } return instance; } void VisualScriptCustomNode::_script_changed() { call_deferred("ports_changed_notify"); } void VisualScriptCustomNode::_bind_methods() { BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_output_sequence_port_count")); BIND_VMETHOD(MethodInfo(VariantType::BOOL, "_has_input_sequence_port")); BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_output_sequence_port_text", PropertyInfo(VariantType::INT, "idx"))); BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_input_value_port_count")); BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_output_value_port_count")); BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_input_value_port_type", PropertyInfo(VariantType::INT, "idx"))); BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_input_value_port_name", PropertyInfo(VariantType::INT, "idx"))); BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_output_value_port_type", PropertyInfo(VariantType::INT, "idx"))); BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_output_value_port_name", PropertyInfo(VariantType::INT, "idx"))); BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_caption")); BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_text")); BIND_VMETHOD(MethodInfo(VariantType::STRING, "_get_category")); BIND_VMETHOD(MethodInfo(VariantType::INT, "_get_working_memory_size")); MethodInfo stepmi(VariantType::NIL, "_step", PropertyInfo(VariantType::ARRAY, "inputs"), PropertyInfo(VariantType::ARRAY, "outputs"), PropertyInfo(VariantType::INT, "start_mode"), PropertyInfo(VariantType::ARRAY, "working_mem")); stepmi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; BIND_VMETHOD(stepmi); MethodBinder::bind_method(D_METHOD("_script_changed"), &VisualScriptCustomNode::_script_changed); BIND_ENUM_CONSTANT(START_MODE_BEGIN_SEQUENCE) BIND_ENUM_CONSTANT(START_MODE_CONTINUE_SEQUENCE) BIND_ENUM_CONSTANT(START_MODE_RESUME_YIELD) BIND_CONSTANT(STEP_PUSH_STACK_BIT) BIND_CONSTANT(STEP_GO_BACK_BIT) BIND_CONSTANT(STEP_NO_ADVANCE_BIT) BIND_CONSTANT(STEP_EXIT_FUNCTION_BIT) BIND_CONSTANT(STEP_YIELD_BIT) } VisualScriptCustomNode::VisualScriptCustomNode() { connect("script_changed", this, "_script_changed"); } ////////////////////////////////////////// ////////////////SUBCALL/////////// ////////////////////////////////////////// int VisualScriptSubCall::get_output_sequence_port_count() const { return 1; } bool VisualScriptSubCall::has_input_sequence_port() const { return true; } int VisualScriptSubCall::get_input_value_port_count() const { Ref<Script> script = refFromRefPtr<Script>(get_script()); if (script && script->has_method(VisualScriptLanguage::singleton->_subcall)) { MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall); return mi.arguments.size(); } return 0; } int VisualScriptSubCall::get_output_value_port_count() const { return 1; } StringView VisualScriptSubCall::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptSubCall::get_input_value_port_info(int p_idx) const { Ref<Script> script = refFromRefPtr<Script>(get_script()); if (script && script->has_method(VisualScriptLanguage::singleton->_subcall)) { MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall); return mi.arguments[p_idx]; } return PropertyInfo(); } PropertyInfo VisualScriptSubCall::get_output_value_port_info(int p_idx) const { Ref<Script> script = refFromRefPtr<Script>(get_script()); if (script && script->has_method(VisualScriptLanguage::singleton->_subcall)) { MethodInfo mi = script->get_method_info(VisualScriptLanguage::singleton->_subcall); return mi.return_val; } return PropertyInfo(); } StringView VisualScriptSubCall::get_caption() const { return "SubCall"; } String VisualScriptSubCall::get_text() const { Ref<Script> script = refFromRefPtr<Script>(get_script()); if (script) { if (!script->get_name().empty()) return script->get_name(); if (PathUtils::is_resource_file(script->get_path())) return String(PathUtils::get_file(script->get_path())); return String(script->get_class()); } return String(); } const char *VisualScriptSubCall::get_category() const { return "custom"; } class VisualScriptNodeInstanceSubCall : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; VisualScriptSubCall *subcall; int input_args; bool valid; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { if (!valid) { r_error_str = "Node requires a script with a _subcall(<args>) method to work."; r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; return 0; } *p_outputs[0] = subcall->call(VisualScriptLanguage::singleton->_subcall, p_inputs, input_args, r_error); return 0; } }; VisualScriptNodeInstance *VisualScriptSubCall::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceSubCall *instance = memnew(VisualScriptNodeInstanceSubCall); instance->instance = p_instance; Ref<Script> script = refFromRefPtr<Script>(get_script()); if (script && script->has_method(VisualScriptLanguage::singleton->_subcall)) { instance->valid = true; instance->input_args = get_input_value_port_count(); } else { instance->valid = false; } return instance; } void VisualScriptSubCall::_bind_methods() { MethodInfo scmi(VariantType::NIL, "_subcall", PropertyInfo(VariantType::NIL, "arguments")); scmi.return_val.usage |= PROPERTY_USAGE_NIL_IS_VARIANT; BIND_VMETHOD(scmi); } VisualScriptSubCall::VisualScriptSubCall() { } ////////////////////////////////////////// ////////////////Comment/////////// ////////////////////////////////////////// int VisualScriptComment::get_output_sequence_port_count() const { return 0; } bool VisualScriptComment::has_input_sequence_port() const { return false; } int VisualScriptComment::get_input_value_port_count() const { return 0; } int VisualScriptComment::get_output_value_port_count() const { return 0; } StringView VisualScriptComment::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptComment::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptComment::get_output_value_port_info(int p_idx) const { return PropertyInfo(); } StringView VisualScriptComment::get_caption() const { return title; } String VisualScriptComment::get_text() const { return description; } void VisualScriptComment::set_title(const String &p_title) { if (title == p_title) return; title = p_title; ports_changed_notify(); } const String & VisualScriptComment::get_title() const { return title; } void VisualScriptComment::set_description(const String &p_description) { if (description == p_description) return; description = p_description; ports_changed_notify(); } const String& VisualScriptComment::get_description() const { return description; } void VisualScriptComment::set_size(const Size2 &p_size) { if (size == p_size) return; size = p_size; ports_changed_notify(); } Size2 VisualScriptComment::get_size() const { return size; } const char *VisualScriptComment::get_category() const { return "data"; } class VisualScriptNodeInstanceComment : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { return 0; } }; VisualScriptNodeInstance *VisualScriptComment::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceComment *instance = memnew(VisualScriptNodeInstanceComment); instance->instance = p_instance; return instance; } void VisualScriptComment::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_title", {"title"}), &VisualScriptComment::set_title); MethodBinder::bind_method(D_METHOD("get_title"), &VisualScriptComment::get_title); MethodBinder::bind_method(D_METHOD("set_description", {"description"}), &VisualScriptComment::set_description); MethodBinder::bind_method(D_METHOD("get_description"), &VisualScriptComment::get_description); MethodBinder::bind_method(D_METHOD("set_size", {"size"}), &VisualScriptComment::set_size); MethodBinder::bind_method(D_METHOD("get_size"), &VisualScriptComment::get_size); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "title"), "set_title", "get_title"); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "description", PropertyHint::MultilineText), "set_description", "get_description"); ADD_PROPERTY(PropertyInfo(VariantType::VECTOR2, "size"), "set_size", "get_size"); } VisualScriptComment::VisualScriptComment() { title = "Comment"; size = Size2(150, 150); } ////////////////////////////////////////// ////////////////Constructor/////////// ////////////////////////////////////////// int VisualScriptConstructor::get_output_sequence_port_count() const { return 0; } bool VisualScriptConstructor::has_input_sequence_port() const { return false; } int VisualScriptConstructor::get_input_value_port_count() const { return constructor.arguments.size(); } int VisualScriptConstructor::get_output_value_port_count() const { return 1; } StringView VisualScriptConstructor::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptConstructor::get_input_value_port_info(int p_idx) const { return constructor.arguments[p_idx]; } PropertyInfo VisualScriptConstructor::get_output_value_port_info(int p_idx) const { return PropertyInfo(type, "value"); } StringView VisualScriptConstructor::get_caption() const { thread_local char buf[512]; buf[0]=0; strncat(buf,"Construct ",511); strncat(buf,Variant::get_type_name(type),511); return buf; } const char *VisualScriptConstructor::get_category() const { return "functions"; } void VisualScriptConstructor::set_constructor_type(VariantType p_type) { if (type == p_type) return; type = p_type; ports_changed_notify(); } VariantType VisualScriptConstructor::get_constructor_type() const { return type; } void VisualScriptConstructor::set_constructor(const Dictionary &p_info) { constructor = MethodInfo::from_dict(p_info); ports_changed_notify(); } Dictionary VisualScriptConstructor::get_constructor() const { return constructor; } class VisualScriptNodeInstanceConstructor : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; VariantType type; int argcount; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Callable::CallError ce; *p_outputs[0] = Variant::construct(type, p_inputs, argcount, ce); if (ce.error != Callable::CallError::CALL_OK) { r_error_str = "Invalid arguments for constructor"; } return 0; } }; VisualScriptNodeInstance *VisualScriptConstructor::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceConstructor *instance = memnew(VisualScriptNodeInstanceConstructor); instance->instance = p_instance; instance->type = type; instance->argcount = constructor.arguments.size(); return instance; } void VisualScriptConstructor::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_constructor_type", {"type"}), &VisualScriptConstructor::set_constructor_type); MethodBinder::bind_method(D_METHOD("get_constructor_type"), &VisualScriptConstructor::get_constructor_type); MethodBinder::bind_method(D_METHOD("set_constructor", {"constructor"}), &VisualScriptConstructor::set_constructor); MethodBinder::bind_method(D_METHOD("get_constructor"), &VisualScriptConstructor::get_constructor); ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::None, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_constructor_type", "get_constructor_type"); ADD_PROPERTY(PropertyInfo(VariantType::DICTIONARY, "constructor", PropertyHint::None, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "set_constructor", "get_constructor"); } VisualScriptConstructor::VisualScriptConstructor() { type = VariantType::NIL; } static Map<String, Pair<VariantType, MethodInfo> > constructor_map; static Ref<VisualScriptNode> create_constructor_node(StringView p_name) { auto constructor_iter = constructor_map.find_as(p_name); ERR_FAIL_COND_V(constructor_iter==constructor_map.end(), Ref<VisualScriptNode>()); Ref<VisualScriptConstructor> vsc(make_ref_counted<VisualScriptConstructor>()); vsc->set_constructor_type(constructor_iter->second.first); vsc->set_constructor(constructor_iter->second.second); return vsc; } ////////////////////////////////////////// ////////////////LocalVar/////////// ////////////////////////////////////////// int VisualScriptLocalVar::get_output_sequence_port_count() const { return 0; } bool VisualScriptLocalVar::has_input_sequence_port() const { return false; } int VisualScriptLocalVar::get_input_value_port_count() const { return 0; } int VisualScriptLocalVar::get_output_value_port_count() const { return 1; } StringView VisualScriptLocalVar::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptLocalVar::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptLocalVar::get_output_value_port_info(int p_idx) const { return PropertyInfo(type, name); } StringView VisualScriptLocalVar::get_caption() const { return "Get Local Var"; } const char *VisualScriptLocalVar::get_category() const { return "data"; } void VisualScriptLocalVar::set_var_name(const StringName &p_name) { if (name == p_name) return; name = p_name; ports_changed_notify(); } StringName VisualScriptLocalVar::get_var_name() const { return name; } void VisualScriptLocalVar::set_var_type(VariantType p_type) { type = p_type; ports_changed_notify(); } VariantType VisualScriptLocalVar::get_var_type() const { return type; } class VisualScriptNodeInstanceLocalVar : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; StringName name; int get_working_memory_size() const override { return 1; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_outputs[0] = *p_working_mem; return 0; } }; VisualScriptNodeInstance *VisualScriptLocalVar::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceLocalVar *instance = memnew(VisualScriptNodeInstanceLocalVar); instance->instance = p_instance; instance->name = name; return instance; } void VisualScriptLocalVar::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_var_name", {"name"}), &VisualScriptLocalVar::set_var_name); MethodBinder::bind_method(D_METHOD("get_var_name"), &VisualScriptLocalVar::get_var_name); MethodBinder::bind_method(D_METHOD("set_var_type", {"type"}), &VisualScriptLocalVar::set_var_type); MethodBinder::bind_method(D_METHOD("get_var_type"), &VisualScriptLocalVar::get_var_type); char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX]; fill_with_all_variant_types("Any",argt); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "var_name"), "set_var_name", "get_var_name"); ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_var_type", "get_var_type"); } VisualScriptLocalVar::VisualScriptLocalVar() { name = "new_local"; type = VariantType::NIL; } ////////////////////////////////////////// ////////////////LocalVar/////////// ////////////////////////////////////////// int VisualScriptLocalVarSet::get_output_sequence_port_count() const { return 1; } bool VisualScriptLocalVarSet::has_input_sequence_port() const { return true; } int VisualScriptLocalVarSet::get_input_value_port_count() const { return 1; } int VisualScriptLocalVarSet::get_output_value_port_count() const { return 1; } StringView VisualScriptLocalVarSet::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptLocalVarSet::get_input_value_port_info(int p_idx) const { return PropertyInfo(type, "set"); } PropertyInfo VisualScriptLocalVarSet::get_output_value_port_info(int p_idx) const { return PropertyInfo(type, "get"); } StringView VisualScriptLocalVarSet::get_caption() const { return "Set Local Var"; } String VisualScriptLocalVarSet::get_text() const { return name.asCString(); } const char *VisualScriptLocalVarSet::get_category() const { return "data"; } void VisualScriptLocalVarSet::set_var_name(const StringName &p_name) { if (name == p_name) return; name = p_name; ports_changed_notify(); } StringName VisualScriptLocalVarSet::get_var_name() const { return name; } void VisualScriptLocalVarSet::set_var_type(VariantType p_type) { type = p_type; ports_changed_notify(); } VariantType VisualScriptLocalVarSet::get_var_type() const { return type; } class VisualScriptNodeInstanceLocalVarSet : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; StringName name; int get_working_memory_size() const override { return 1; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { *p_working_mem = *p_inputs[0]; *p_outputs[0] = *p_working_mem; return 0; } }; VisualScriptNodeInstance *VisualScriptLocalVarSet::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceLocalVarSet *instance = memnew(VisualScriptNodeInstanceLocalVarSet); instance->instance = p_instance; instance->name = name; return instance; } void VisualScriptLocalVarSet::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_var_name", {"name"}), &VisualScriptLocalVarSet::set_var_name); MethodBinder::bind_method(D_METHOD("get_var_name"), &VisualScriptLocalVarSet::get_var_name); MethodBinder::bind_method(D_METHOD("set_var_type", {"type"}), &VisualScriptLocalVarSet::set_var_type); MethodBinder::bind_method(D_METHOD("get_var_type"), &VisualScriptLocalVarSet::get_var_type); char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX]; fill_with_all_variant_types("Any",argt); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "var_name"), "set_var_name", "get_var_name"); ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_var_type", "get_var_type"); } VisualScriptLocalVarSet::VisualScriptLocalVarSet() { name = "new_local"; type = VariantType::NIL; } ////////////////////////////////////////// ////////////////LocalVar/////////// ////////////////////////////////////////// int VisualScriptInputAction::get_output_sequence_port_count() const { return 0; } bool VisualScriptInputAction::has_input_sequence_port() const { return false; } int VisualScriptInputAction::get_input_value_port_count() const { return 0; } int VisualScriptInputAction::get_output_value_port_count() const { return 1; } StringView VisualScriptInputAction::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptInputAction::get_input_value_port_info(int p_idx) const { return PropertyInfo(); } PropertyInfo VisualScriptInputAction::get_output_value_port_info(int p_idx) const { const char *mstr=nullptr; switch (mode) { case MODE_PRESSED: { mstr = "pressed"; } break; case MODE_RELEASED: { mstr = "not pressed"; } break; case MODE_JUST_PRESSED: { mstr = "just pressed"; } break; case MODE_JUST_RELEASED: { mstr = "just released"; } break; } return PropertyInfo(VariantType::BOOL, StaticCString(mstr,true)); } StringView VisualScriptInputAction::get_caption() const { thread_local char buf[512]; buf[0]=0; strncat(buf,"Action ",511); strncat(buf,name.asCString(),511); return buf; } const char *VisualScriptInputAction::get_category() const { return "data"; } void VisualScriptInputAction::set_action_name(const StringName &p_name) { if (name == p_name) return; name = p_name; ports_changed_notify(); } StringName VisualScriptInputAction::get_action_name() const { return name; } void VisualScriptInputAction::set_action_mode(Mode p_mode) { if (mode == p_mode) return; mode = p_mode; ports_changed_notify(); } VisualScriptInputAction::Mode VisualScriptInputAction::get_action_mode() const { return mode; } class VisualScriptNodeInstanceInputAction : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; StringName action; VisualScriptInputAction::Mode mode; int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { switch (mode) { case VisualScriptInputAction::MODE_PRESSED: { *p_outputs[0] = Input::get_singleton()->is_action_pressed(action); } break; case VisualScriptInputAction::MODE_RELEASED: { *p_outputs[0] = !Input::get_singleton()->is_action_pressed(action); } break; case VisualScriptInputAction::MODE_JUST_PRESSED: { *p_outputs[0] = Input::get_singleton()->is_action_just_pressed(action); } break; case VisualScriptInputAction::MODE_JUST_RELEASED: { *p_outputs[0] = Input::get_singleton()->is_action_just_released(action); } break; } return 0; } }; VisualScriptNodeInstance *VisualScriptInputAction::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceInputAction *instance = memnew(VisualScriptNodeInstanceInputAction); instance->instance = p_instance; instance->action = name; instance->mode = mode; return instance; } void VisualScriptInputAction::_validate_property(PropertyInfo &property) const { if (property.name != StringView("action")) return; property.hint = PropertyHint::Enum; Vector<PropertyInfo> pinfo; ProjectSettings::get_singleton()->get_property_list(&pinfo); FixedVector<String,32,true> al; for(const PropertyInfo &pi : pinfo) { if (!StringUtils::begins_with(pi.name,"input/")) continue; String name(StringUtils::substr(pi.name,StringUtils::find(pi.name,"/") + 1)); al.push_back(name); } eastl::sort(al.begin(),al.end()); property.hint_string = String::joined(al,","); } void VisualScriptInputAction::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_action_name", {"name"}), &VisualScriptInputAction::set_action_name); MethodBinder::bind_method(D_METHOD("get_action_name"), &VisualScriptInputAction::get_action_name); MethodBinder::bind_method(D_METHOD("set_action_mode", {"mode"}), &VisualScriptInputAction::set_action_mode); MethodBinder::bind_method(D_METHOD("get_action_mode"), &VisualScriptInputAction::get_action_mode); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "action"), "set_action_name", "get_action_name"); ADD_PROPERTY(PropertyInfo(VariantType::INT, "mode", PropertyHint::Enum, "Pressed,Released,JustPressed,JustReleased"), "set_action_mode", "get_action_mode"); BIND_ENUM_CONSTANT(MODE_PRESSED) BIND_ENUM_CONSTANT(MODE_RELEASED) BIND_ENUM_CONSTANT(MODE_JUST_PRESSED) BIND_ENUM_CONSTANT(MODE_JUST_RELEASED) } VisualScriptInputAction::VisualScriptInputAction() { name = ""; mode = MODE_PRESSED; } ////////////////////////////////////////// ////////////////Constructor/////////// ////////////////////////////////////////// int VisualScriptDeconstruct::get_output_sequence_port_count() const { return 0; } bool VisualScriptDeconstruct::has_input_sequence_port() const { return false; } int VisualScriptDeconstruct::get_input_value_port_count() const { return 1; } int VisualScriptDeconstruct::get_output_value_port_count() const { return elements.size(); } StringView VisualScriptDeconstruct::get_output_sequence_port_text(int p_port) const { return StringView(); } PropertyInfo VisualScriptDeconstruct::get_input_value_port_info(int p_idx) const { return PropertyInfo(type, "value"); } PropertyInfo VisualScriptDeconstruct::get_output_value_port_info(int p_idx) const { return PropertyInfo(elements[p_idx].type, elements[p_idx].name); } StringView VisualScriptDeconstruct::get_caption() const { thread_local char buf[512]="Deconstruct "; strncat(buf,Variant::get_type_name(type),256); return buf; } const char *VisualScriptDeconstruct::get_category() const { return "functions"; } void VisualScriptDeconstruct::_update_elements() { elements.clear(); Variant v; Callable::CallError ce; v = Variant::construct(type, nullptr, 0, ce); Vector<PropertyInfo> pinfo; v.get_property_list(&pinfo); for(const PropertyInfo & E : pinfo) { Element e; e.name = E.name; e.type = E.type; elements.push_back(e); } } void VisualScriptDeconstruct::set_deconstruct_type(VariantType p_type) { if (type == p_type) return; type = p_type; _update_elements(); ports_changed_notify(); Object_change_notify(this); //to make input appear/disappear } VariantType VisualScriptDeconstruct::get_deconstruct_type() const { return type; } void VisualScriptDeconstruct::_set_elem_cache(const Array &p_elements) { ERR_FAIL_COND(p_elements.size() % 2 == 1); elements.resize(p_elements.size() / 2); for (int i = 0; i < elements.size(); i++) { elements[i].name = p_elements[i * 2 + 0].as<StringName>(); elements[i].type = p_elements[i * 2 + 1].as<VariantType>(); } } Array VisualScriptDeconstruct::_get_elem_cache() const { Array ret; for (int i = 0; i < elements.size(); i++) { ret.push_back(elements[i].name); ret.push_back(elements[i].type); } return ret; } class VisualScriptNodeInstanceDeconstruct : public VisualScriptNodeInstance { public: VisualScriptInstance *instance; Vector<StringName> outputs; //virtual int get_working_memory_size() const { return 0; } int step(const Variant **p_inputs, Variant **p_outputs, StartMode p_start_mode, Variant *p_working_mem, Callable::CallError &r_error, String &r_error_str) override { Variant in = *p_inputs[0]; for (int i = 0; i < outputs.size(); i++) { bool valid; *p_outputs[i] = in.get(outputs[i], &valid); if (!valid) { r_error_str = "Can't obtain element '" + String(outputs[i]) + "' from " + Variant::get_type_name(in.get_type()); r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD; return 0; } } return 0; } }; VisualScriptNodeInstance *VisualScriptDeconstruct::instance(VisualScriptInstance *p_instance) { VisualScriptNodeInstanceDeconstruct *instance = memnew(VisualScriptNodeInstanceDeconstruct); instance->instance = p_instance; instance->outputs.resize(elements.size()); for (int i = 0; i < elements.size(); i++) { instance->outputs[i] = elements[i].name; } return instance; } void VisualScriptDeconstruct::_validate_property(PropertyInfo & /*property*/) const { } void VisualScriptDeconstruct::_bind_methods() { MethodBinder::bind_method(D_METHOD("set_deconstruct_type", {"type"}), &VisualScriptDeconstruct::set_deconstruct_type); MethodBinder::bind_method(D_METHOD("get_deconstruct_type"), &VisualScriptDeconstruct::get_deconstruct_type); MethodBinder::bind_method(D_METHOD("_set_elem_cache", {"_cache"}), &VisualScriptDeconstruct::_set_elem_cache); MethodBinder::bind_method(D_METHOD("_get_elem_cache"), &VisualScriptDeconstruct::_get_elem_cache); char argt[7+(longest_variant_type_name+1)*(int)VariantType::VARIANT_MAX]; fill_with_all_variant_types("Any",argt); ADD_PROPERTY(PropertyInfo(VariantType::INT, "type", PropertyHint::Enum, argt), "set_deconstruct_type", "get_deconstruct_type"); ADD_PROPERTY(PropertyInfo(VariantType::ARRAY, "elem_cache", PropertyHint::None, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL), "_set_elem_cache", "_get_elem_cache"); } VisualScriptDeconstruct::VisualScriptDeconstruct() { type = VariantType::NIL; } template <VariantType T> static Ref<VisualScriptNode> create_node_deconst_typed(StringView /*p_name*/) { Ref<VisualScriptDeconstruct> node(make_ref_counted<VisualScriptDeconstruct>()); node->set_deconstruct_type(T); return node; } void register_visual_script_nodes() { VisualScriptLanguage::singleton->add_register_func("data/set_variable", create_node_generic<VisualScriptVariableSet>); VisualScriptLanguage::singleton->add_register_func("data/get_variable", create_node_generic<VisualScriptVariableGet>); VisualScriptLanguage::singleton->add_register_func("data/engine_singleton", create_node_generic<VisualScriptEngineSingleton>); VisualScriptLanguage::singleton->add_register_func("data/scene_node", create_node_generic<VisualScriptSceneNode>); VisualScriptLanguage::singleton->add_register_func("data/scene_tree", create_node_generic<VisualScriptSceneTree>); VisualScriptLanguage::singleton->add_register_func("data/resource_path", create_node_generic<VisualScriptResourcePath>); VisualScriptLanguage::singleton->add_register_func("data/self", create_node_generic<VisualScriptSelf>); VisualScriptLanguage::singleton->add_register_func("data/comment", create_node_generic<VisualScriptComment>); VisualScriptLanguage::singleton->add_register_func("data/get_local_variable", create_node_generic<VisualScriptLocalVar>); VisualScriptLanguage::singleton->add_register_func("data/set_local_variable", create_node_generic<VisualScriptLocalVarSet>); VisualScriptLanguage::singleton->add_register_func("data/preload", create_node_generic<VisualScriptPreload>); VisualScriptLanguage::singleton->add_register_func("data/action", create_node_generic<VisualScriptInputAction>); VisualScriptLanguage::singleton->add_register_func("constants/constant", create_node_generic<VisualScriptConstant>); VisualScriptLanguage::singleton->add_register_func("constants/math_constant", create_node_generic<VisualScriptMathConstant>); VisualScriptLanguage::singleton->add_register_func("constants/class_constant", create_node_generic<VisualScriptClassConstant>); VisualScriptLanguage::singleton->add_register_func("constants/global_constant", create_node_generic<VisualScriptGlobalConstant>); VisualScriptLanguage::singleton->add_register_func("constants/basic_type_constant", create_node_generic<VisualScriptBasicTypeConstant>); VisualScriptLanguage::singleton->add_register_func("custom/custom_node", create_node_generic<VisualScriptCustomNode>); VisualScriptLanguage::singleton->add_register_func("custom/sub_call", create_node_generic<VisualScriptSubCall>); VisualScriptLanguage::singleton->add_register_func("index/get_index", create_node_generic<VisualScriptIndexGet>); VisualScriptLanguage::singleton->add_register_func("index/set_index", create_node_generic<VisualScriptIndexSet>); VisualScriptLanguage::singleton->add_register_func("operators/compare/equal", create_op_node<Variant::OP_EQUAL>); VisualScriptLanguage::singleton->add_register_func("operators/compare/not_equal", create_op_node<Variant::OP_NOT_EQUAL>); VisualScriptLanguage::singleton->add_register_func("operators/compare/less", create_op_node<Variant::OP_LESS>); VisualScriptLanguage::singleton->add_register_func("operators/compare/less_equal", create_op_node<Variant::OP_LESS_EQUAL>); VisualScriptLanguage::singleton->add_register_func("operators/compare/greater", create_op_node<Variant::OP_GREATER>); VisualScriptLanguage::singleton->add_register_func("operators/compare/greater_equal", create_op_node<Variant::OP_GREATER_EQUAL>); //mathematic VisualScriptLanguage::singleton->add_register_func("operators/math/add", create_op_node<Variant::OP_ADD>); VisualScriptLanguage::singleton->add_register_func("operators/math/subtract", create_op_node<Variant::OP_SUBTRACT>); VisualScriptLanguage::singleton->add_register_func("operators/math/multiply", create_op_node<Variant::OP_MULTIPLY>); VisualScriptLanguage::singleton->add_register_func("operators/math/divide", create_op_node<Variant::OP_DIVIDE>); VisualScriptLanguage::singleton->add_register_func("operators/math/negate", create_op_node<Variant::OP_NEGATE>); VisualScriptLanguage::singleton->add_register_func("operators/math/positive", create_op_node<Variant::OP_POSITIVE>); VisualScriptLanguage::singleton->add_register_func("operators/math/remainder", create_op_node<Variant::OP_MODULE>); VisualScriptLanguage::singleton->add_register_func("operators/math/string_concat", create_op_node<Variant::OP_STRING_CONCAT>); //bitwise VisualScriptLanguage::singleton->add_register_func("operators/bitwise/shift_left", create_op_node<Variant::OP_SHIFT_LEFT>); VisualScriptLanguage::singleton->add_register_func("operators/bitwise/shift_right", create_op_node<Variant::OP_SHIFT_RIGHT>); VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_and", create_op_node<Variant::OP_BIT_AND>); VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_or", create_op_node<Variant::OP_BIT_OR>); VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_xor", create_op_node<Variant::OP_BIT_XOR>); VisualScriptLanguage::singleton->add_register_func("operators/bitwise/bit_negate", create_op_node<Variant::OP_BIT_NEGATE>); //logic VisualScriptLanguage::singleton->add_register_func("operators/logic/and", create_op_node<Variant::OP_AND>); VisualScriptLanguage::singleton->add_register_func("operators/logic/or", create_op_node<Variant::OP_OR>); VisualScriptLanguage::singleton->add_register_func("operators/logic/xor", create_op_node<Variant::OP_XOR>); VisualScriptLanguage::singleton->add_register_func("operators/logic/not", create_op_node<Variant::OP_NOT>); VisualScriptLanguage::singleton->add_register_func("operators/logic/in", create_op_node<Variant::OP_IN>); VisualScriptLanguage::singleton->add_register_func("operators/logic/select", create_node_generic<VisualScriptSelect>); String deconstruct_prefix("functions/deconstruct/"); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::VECTOR2), create_node_deconst_typed<VariantType::VECTOR2>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::VECTOR3), create_node_deconst_typed<VariantType::VECTOR3>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::COLOR), create_node_deconst_typed<VariantType::COLOR>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::RECT2), create_node_deconst_typed<VariantType::RECT2>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::TRANSFORM2D), create_node_deconst_typed<VariantType::TRANSFORM2D>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::PLANE), create_node_deconst_typed<VariantType::PLANE>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::QUAT), create_node_deconst_typed<VariantType::QUAT>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::AABB), create_node_deconst_typed<VariantType::AABB>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::BASIS), create_node_deconst_typed<VariantType::BASIS>); VisualScriptLanguage::singleton->add_register_func(deconstruct_prefix + Variant::get_type_name(VariantType::TRANSFORM), create_node_deconst_typed<VariantType::TRANSFORM>); VisualScriptLanguage::singleton->add_register_func("functions/compose_array", create_node_generic<VisualScriptComposeArray>); for (int i = 1; i < (int)VariantType::VARIANT_MAX; i++) { Vector<MethodInfo> constructors; Variant::get_constructor_list(VariantType(i), &constructors); for (const MethodInfo &E : constructors) { if (!E.arguments.empty()) { String name = FormatVE("functions/constructors/%s(",Variant::get_type_name(VariantType(i))); for (size_t j = 0; j < E.arguments.size(); j++) { if (j > 0) { name += ", "; } if (E.arguments.size() == 1) { name += Variant::get_type_name(E.arguments[j].type); } else { name += E.arguments[j].name.asCString(); } } name += ")"; VisualScriptLanguage::singleton->add_register_func(name, create_constructor_node); Pair<VariantType, MethodInfo> pair; pair.first = VariantType(i); pair.second = E; constructor_map[name] = pair; } } } } void unregister_visual_script_nodes() { constructor_map.clear(); }
30.791412
209
0.686116
ZopharShinta
c5f9411338a09e257face1d14db19a463987269b
3,679
cpp
C++
errors/errorhandler.cpp
buelowp/aquarium
6d379469fbfe2a8c12631bc5571c76d3c0d9d84a
[ "MIT" ]
3
2017-05-04T08:14:46.000Z
2020-04-21T12:17:08.000Z
errors/errorhandler.cpp
buelowp/aquarium
6d379469fbfe2a8c12631bc5571c76d3c0d9d84a
[ "MIT" ]
12
2019-08-17T20:49:35.000Z
2020-04-22T00:46:17.000Z
errors/errorhandler.cpp
buelowp/aquarium
6d379469fbfe2a8c12631bc5571c76d3c0d9d84a
[ "MIT" ]
null
null
null
/* * Copyright (c) 2020 <copyright holder> <email> * * 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 "errorhandler.h" /** * \fn ErrorHandler::ErrorHandler() * * Set m_handle to 100 because we want to reserve some values * for static assignment, these would be known errors */ ErrorHandler::ErrorHandler() { m_storedErrors = 0; m_handle = 100; } ErrorHandler::~ErrorHandler() { } unsigned int ErrorHandler::critical(std::string msg, mqtt::async_client *client, int timeout, int handle) { if (handle > 0) m_handle = handle; else m_handle++; Critical err(m_handle, msg, client, timeout); err.activate(); digitalWrite(Configuration::instance()->m_greenLed, 0); m_criticals[m_handle] = err; m_storedErrors++; return m_handle; } unsigned int ErrorHandler::fatal(std::string msg, mqtt::async_client *client, int handle) { if (handle > 0) m_handle = handle; else m_handle++; Fatal err(m_handle, msg, client); err.activate(); digitalWrite(Configuration::instance()->m_greenLed, 0); m_fatals[m_handle] = err; m_storedErrors++; return m_handle; } unsigned int ErrorHandler::warning(std::string msg, mqtt::async_client *client, int timeout, int handle) { if (handle > 0) m_handle = handle; else m_handle++; Warning err(m_handle, msg, client, timeout); err.activate(); digitalWrite(Configuration::instance()->m_greenLed, 0); m_warnings[m_handle] = err; m_storedErrors++; return m_handle; } void ErrorHandler::clearCritical(unsigned int handle) { auto search = m_criticals.find(handle); if (search != m_criticals.end()) { Critical err = search->second; err.cancel(); m_criticals.erase(search); m_storedErrors--; } if (m_criticals.size() == 0) { if (m_warnings.size()) { auto it = m_warnings.begin(); Warning err = it->second; err.activate(); } } else { auto it = m_criticals.begin(); Critical err = it->second; err.activate(); } if (m_storedErrors == 0) { digitalWrite(Configuration::instance()->m_greenLed, 1); } } void ErrorHandler::clearWarning(unsigned int handle) { auto search = m_warnings.find(handle); if (search != m_warnings.end()) { Warning err = search->second; err.cancel(); m_warnings.erase(search); m_storedErrors--; } if (m_storedErrors == 0) { digitalWrite(Configuration::instance()->m_greenLed, 1); } }
27.251852
105
0.654797
buelowp
c5f99647d63a209ee39e8ffd30f8ef6eaf2acb46
1,177
cpp
C++
learncpp_com/6-arr_string_pointer_references/142-array_loops/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
learncpp_com/6-arr_string_pointer_references/142-array_loops/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
learncpp_com/6-arr_string_pointer_references/142-array_loops/main.cpp
mitsiu-carreno/cpp_tutorial
71f9083884ae6aa23774c044c3d08be273b6bb8e
[ "MIT" ]
null
null
null
#include <iostream> int main() { int testScore[] ={88, 75, 98, 80, 93}; // Get the average score without loops double noLoopTotalScore = testScore[0] + testScore[1] + testScore[2] + testScore[3] + testScore[4]; double noLoopAverageScore = noLoopTotalScore / (sizeof(testScore) / sizeof(testScore[0])); std::cout << "The average score is: " << noLoopAverageScore << "\n"; // Get the average score WITH loops int totalElements = sizeof(testScore) / sizeof(testScore[0]); double sumScores = 0; int bestScore = 0; for(int count = 0; count < totalElements; ++count) { sumScores += testScore[count]; if(testScore[count] > bestScore) { bestScore = testScore[count]; } } std::cout << "The average score (with loops) is: " << sumScores / totalElements << "\n"; std::cout << "And the best score was: " << bestScore << "\n\n"; std::cout << "Loops are typically used with arrays to do one of three things:\n"; std::cout << "1) Calculate a value (e.g. average, total)\n"; std::cout << "2) Search of a value (e.g. highest, lowest)\n"; std::cout << "3) Reorganize the array (e.g. ascending, descending)\n"; return 0; }
31.810811
101
0.638063
mitsiu-carreno
68019d9f9622a364965e0e7bf99327e5a7522a96
21,223
cpp
C++
src/game/client/tf2/c_env_meteor.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/client/tf2/c_env_meteor.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/client/tf2/c_env_meteor.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "cbase.h" #include "C_Env_Meteor.h" #include "fx_explosion.h" #include "tempentity.h" #include "c_tracer.h" //============================================================================= // // Meteor Factory Functions // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_MeteorFactory::CreateMeteor( int nID, int iType, const Vector &vecPosition, const Vector &vecDirection, float flSpeed, float flStartTime, float flDamageRadius, const Vector &vecTriggerMins, const Vector &vecTriggerMaxs ) { C_EnvMeteor::Create( nID, iType, vecPosition, vecDirection, flSpeed, flStartTime, flDamageRadius, vecTriggerMins, vecTriggerMaxs ); } //============================================================================= // // Meteor Spawner Functions // void RecvProxy_MeteorTargetPositions( const CRecvProxyData *pData, void *pStruct, void *pOut ) { CEnvMeteorSpawnerShared *pSpawner = ( CEnvMeteorSpawnerShared* )pStruct; pSpawner->m_aTargets[pData->m_iElement].m_vecPosition.x = pData->m_Value.m_Vector[0]; pSpawner->m_aTargets[pData->m_iElement].m_vecPosition.y = pData->m_Value.m_Vector[1]; pSpawner->m_aTargets[pData->m_iElement].m_vecPosition.z = pData->m_Value.m_Vector[2]; } void RecvProxy_MeteorTargetRadii( const CRecvProxyData *pData, void *pStruct, void *pOut ) { CEnvMeteorSpawnerShared *pSpawner = ( CEnvMeteorSpawnerShared* )pStruct; pSpawner->m_aTargets[pData->m_iElement].m_flRadius = pData->m_Value.m_Float; } void RecvProxyArrayLength_MeteorTargets( void *pStruct, int objectID, int currentArrayLength ) { CEnvMeteorSpawnerShared *pSpawner = ( CEnvMeteorSpawnerShared* )pStruct; if ( pSpawner->m_aTargets.Count() < currentArrayLength ) { pSpawner->m_aTargets.SetSize( currentArrayLength ); } } BEGIN_RECV_TABLE_NOBASE( CEnvMeteorSpawnerShared, DT_EnvMeteorSpawnerShared ) // Setup (read from) Worldcraft. RecvPropInt ( RECVINFO( m_iMeteorType ) ), RecvPropInt ( RECVINFO( m_bSkybox ) ), RecvPropFloat ( RECVINFO( m_flMinSpawnTime ) ), RecvPropFloat ( RECVINFO( m_flMaxSpawnTime ) ), RecvPropInt ( RECVINFO( m_nMinSpawnCount ) ), RecvPropInt ( RECVINFO( m_nMaxSpawnCount ) ), RecvPropFloat ( RECVINFO( m_flMinSpeed ) ), RecvPropFloat ( RECVINFO( m_flMaxSpeed ) ), // Setup through Init. RecvPropFloat ( RECVINFO( m_flStartTime ) ), RecvPropInt ( RECVINFO( m_nRandomSeed ) ), RecvPropVector ( RECVINFO( m_vecMinBounds ) ), RecvPropVector ( RECVINFO( m_vecMaxBounds ) ), RecvPropVector ( RECVINFO( m_vecTriggerMins ) ), RecvPropVector ( RECVINFO( m_vecTriggerMaxs ) ), // Target List RecvPropArray2( RecvProxyArrayLength_MeteorTargets, RecvPropVector( "meteortargetposition_array_element", 0, 0, 0, RecvProxy_MeteorTargetPositions ), 16, 0, "meteortargetposition_array" ), RecvPropArray2( RecvProxyArrayLength_MeteorTargets, RecvPropFloat( "meteortargetradius_array_element", 0, 0, 0, RecvProxy_MeteorTargetRadii ), 16, 0, "meteortargetradius_array" ) END_RECV_TABLE() // This table encodes the CBaseEntity data. IMPLEMENT_CLIENTCLASS_DT( C_EnvMeteorSpawner, DT_EnvMeteorSpawner, CEnvMeteorSpawner ) RecvPropDataTable ( RECVINFO_DT( m_SpawnerShared ), 0, &REFERENCE_RECV_TABLE( DT_EnvMeteorSpawnerShared ) ), RecvPropInt ( RECVINFO( m_fDisabled ) ), END_RECV_TABLE() //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C_EnvMeteorSpawner::C_EnvMeteorSpawner() { } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorSpawner::OnDataChanged( DataUpdateType_t updateType ) { // Initialize the client side spawner. m_SpawnerShared.Init( &m_Factory, m_SpawnerShared.m_nRandomSeed, m_SpawnerShared.m_flStartTime, m_SpawnerShared.m_vecMinBounds, m_SpawnerShared.m_vecMaxBounds, m_SpawnerShared.m_vecTriggerMins, m_SpawnerShared.m_vecTriggerMaxs ); // Set the next think to be the next spawn interval. if ( !m_fDisabled ) { SetNextClientThink( m_SpawnerShared.m_flNextSpawnTime ); } } #if 0 // Will probably be used later!! //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorSpawner::ReceiveMessage( int classID, bf_read &msg ) { if ( classID != GetClientClass()->m_ClassID ) { // message is for subclass BaseClass::ReceiveMessage( classID, msg ); return; } m_SpawnerShared.m_flStartTime = msg.ReadLong(); m_SpawnerShared.m_flNextSpawnTime = msg.ReadLong(); SetNextClientThink( m_SpawnerShared.m_flNextSpawnTime ); } #endif //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorSpawner::ClientThink( void ) { SetNextClientThink( m_SpawnerShared.MeteorThink( gpGlobals->curtime ) ); } //============================================================================= // // Meteor Tail Functions // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C_EnvMeteorHead::C_EnvMeteorHead() { m_vecPos.Init(); m_vecPrevPos.Init(); m_flParticleScale = 1.0f; m_pSmokeEmitter = NULL; m_flSmokeSpawnInterval = 0.0f; m_hSmokeMaterial = INVALID_MATERIAL_HANDLE; m_flSmokeLifetime = 2.5f; m_bEmitSmoke = true; m_hFlareMaterial = INVALID_MATERIAL_HANDLE; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C_EnvMeteorHead::~C_EnvMeteorHead() { Destroy(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorHead::Start( const Vector &vecOrigin, const Vector &vecDirection ) { // Emitters. m_pSmokeEmitter = CSimpleEmitter::Create( "MeteorTrail" ); // m_pFireEmitter = CSimpleEmitter::Create( "MeteorFire" ); if ( !m_pSmokeEmitter /*|| !m_pFireEmitter*/ ) return; // Smoke m_pSmokeEmitter->SetSortOrigin( vecOrigin ); m_hSmokeMaterial = m_pSmokeEmitter->GetPMaterial( "particle/SmokeStack" ); Assert( m_hSmokeMaterial != INVALID_MATERIAL_HANDLE ); // Fire // m_pFireEmitter->SetSortOrigin( vecOrigin ); // m_hFireMaterial = m_pFireEmitter->GetPMaterial( "particle/particle_fire" ); // Assert( m_hFireMaterial != INVALID_MATERIAL_HANDLE ); // Flare // m_hFlareMaterial = m_ParticleEffect.FindOrAddMaterial( "effects/redflare" ); VectorCopy( vecDirection, m_vecDirection ); VectorCopy( vecOrigin, m_vecPos ); m_bInitThink = true; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorHead::Destroy( void ) { m_pSmokeEmitter = NULL; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorHead::MeteorHeadThink( const Vector &vecOrigin, float flTime ) { if ( m_bInitThink ) { VectorCopy( vecOrigin, m_vecPrevPos ); m_bInitThink = false; } // Update the position of the emitters. VectorCopy( vecOrigin, m_vecPos ); // Update Smoke if ( m_pSmokeEmitter.IsValid() && m_bEmitSmoke ) { m_pSmokeEmitter->SetSortOrigin( m_vecPos ); // Get distance covered Vector vecDelta; VectorSubtract( m_vecPos, m_vecPrevPos, vecDelta ); float flLength = vecDelta.Length(); int nParticleCount = flLength / 35.0f; if ( nParticleCount < 1 ) { nParticleCount = 1; } flLength /= nParticleCount; Vector vecPos; for( int iParticle = 0; iParticle < nParticleCount; ++iParticle ) { vecPos = m_vecPrevPos + ( m_vecDirection * ( flLength * iParticle ) ); // Add some noise to the position. Vector vecPosOffset; vecPosOffset.Random( -m_flSmokeSpawnRadius, m_flSmokeSpawnRadius ); VectorAdd( vecPosOffset, vecPos, vecPosOffset ); SimpleParticle *pParticle = ( SimpleParticle* )m_pSmokeEmitter->AddParticle( sizeof( SimpleParticle ), m_hSmokeMaterial, vecPosOffset ); if ( pParticle ) { pParticle->m_flLifetime = 0.0f; pParticle->m_flDieTime = m_flSmokeLifetime; // Add just a little movement. pParticle->m_vecVelocity.Random( -5.0f, 5.0f ); pParticle->m_uchColor[0] = 255.0f; pParticle->m_uchColor[1] = 255.0f; pParticle->m_uchColor[2] = 255.0f; pParticle->m_uchStartSize = 70 * m_flParticleScale; pParticle->m_uchEndSize = 25 * m_flParticleScale; float flAlpha = random->RandomFloat( 0.5f, 1.0f ); pParticle->m_uchStartAlpha = flAlpha * 255; pParticle->m_uchEndAlpha = 0; pParticle->m_flRoll = random->RandomInt( 0, 360 ); pParticle->m_flRollDelta = random->RandomFloat( -1.0f, 1.0f ); } } } // Update Fire // if ( m_pFireEmitter && m_bEmitFire ) // { // } // Flare // Save off position. VectorCopy( m_vecPos, m_vecPrevPos ); } //============================================================================= // // Meteor Tail Functions // //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C_EnvMeteorTail::C_EnvMeteorTail() { m_TailMaterialHandle = INVALID_MATERIAL_HANDLE; m_pParticleMgr = NULL; m_pParticle = NULL; m_flFadeTime = 0.5f; m_flWidth = 3.0f; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C_EnvMeteorTail::~C_EnvMeteorTail() { Destroy(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorTail::Start( const Vector &vecOrigin, const Vector &vecDirection, float flSpeed ) { // Set the particle manager. m_pParticleMgr = ParticleMgr(); m_pParticleMgr->AddEffect( &m_ParticleEffect, this ); m_TailMaterialHandle = m_ParticleEffect.FindOrAddMaterial( "particle/guidedplasmaprojectile" ); m_pParticle = m_ParticleEffect.AddParticle( sizeof( StandardParticle_t ), m_TailMaterialHandle ); if ( m_pParticle ) { m_pParticle->m_Pos = vecOrigin; } VectorCopy( vecDirection, m_vecDirection ); m_flSpeed = flSpeed; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorTail::Destroy( void ) { if ( m_pParticleMgr ) { m_pParticleMgr->RemoveEffect( &m_ParticleEffect ); m_pParticleMgr = NULL; } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteorTail::DrawFragment( ParticleDraw* pDraw, const Vector &vecStart, const Vector &vecDelta, const Vector4D &vecStartColor, const Vector4D &vecEndColor, float flStartV, float flEndV ) { if( !pDraw->GetMeshBuilder() ) return; // Clip the fragment. Vector vecVerts[4]; if ( !Tracer_ComputeVerts( vecStart, vecDelta, m_flWidth, vecVerts ) ) return; // NOTE: Gotta get the winding right so it's not backface culled // (we need to turn of backface culling for these bad boys) CMeshBuilder* pMeshBuilder = pDraw->GetMeshBuilder(); pMeshBuilder->Position3f( vecVerts[0].x, vecVerts[0].y, vecVerts[0].z ); pMeshBuilder->TexCoord2f( 0, 0.0f, flStartV ); pMeshBuilder->Color4fv( vecStartColor.Base() ); pMeshBuilder->AdvanceVertex(); pMeshBuilder->Position3f( vecVerts[1].x, vecVerts[1].y, vecVerts[1].z ); pMeshBuilder->TexCoord2f( 0, 1.0f, flStartV ); pMeshBuilder->Color4fv( vecStartColor.Base() ); pMeshBuilder->AdvanceVertex(); pMeshBuilder->Position3f( vecVerts[3].x, vecVerts[3].y, vecVerts[3].z ); pMeshBuilder->TexCoord2f( 0, 1.0f, flEndV ); pMeshBuilder->Color4fv( vecEndColor.Base() ); pMeshBuilder->AdvanceVertex(); pMeshBuilder->Position3f( vecVerts[2].x, vecVerts[2].y, vecVerts[2].z ); pMeshBuilder->TexCoord2f( 0, 0.0f, flEndV ); pMeshBuilder->Color4fv( vecEndColor.Base() ); pMeshBuilder->AdvanceVertex(); } void C_EnvMeteorTail::SimulateParticles( CParticleSimulateIterator *pIterator ) { Particle *pParticle = (Particle*)pIterator->GetFirst(); while ( pParticle ) { // Update the particle position. pParticle->m_Pos = GetLocalOrigin(); pParticle = (Particle*)pIterator->GetNext(); } } void C_EnvMeteorTail::RenderParticles( CParticleRenderIterator *pIterator ) { const Particle *pParticle = (const Particle *)pIterator->GetFirst(); while ( pParticle ) { // Now draw the tail fragments... Vector4D vecStartColor( 1.0f, 1.0f, 1.0f, 1.0f ); Vector4D vecEndColor( 1.0f, 1.0f, 1.0f, 0.0f ); Vector vecDelta, vecStartPos, vecEndPos; // Calculate the tail. Vector vecTailEnd; vecTailEnd = GetLocalOrigin() + ( m_vecDirection * -m_flSpeed ); // Transform particles into camera space. TransformParticle( m_pParticleMgr->GetModelView(), GetLocalOrigin(), vecStartPos ); TransformParticle( m_pParticleMgr->GetModelView(), vecTailEnd, vecEndPos ); float sortKey = vecStartPos.z; // Draw the tail fragment. VectorSubtract( vecStartPos, vecEndPos, vecDelta ); DrawFragment( pIterator->GetParticleDraw(), vecEndPos, vecDelta, vecEndColor, vecStartColor, 1.0f - vecEndColor[3], 1.0f - vecStartColor[3] ); pParticle = (const Particle *)pIterator->GetNext( sortKey ); } } //============================================================================= // // Meteor Functions // static g_MeteorCounter = 0; //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C_EnvMeteor::C_EnvMeteor() { } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C_EnvMeteor::~C_EnvMeteor() { } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteor::ClientThink( void ) { // Get the current time. float flTime = gpGlobals->curtime; // Update the meteor. if ( m_Meteor.IsInSkybox( flTime ) ) { if ( m_Meteor.m_nLocation == METEOR_LOCATION_WORLD ) { WorldToSkyboxThink( flTime ); } else { SkyboxThink( flTime ); } } else { if ( m_Meteor.m_nLocation == METEOR_LOCATION_SKYBOX ) { SkyboxToWorldThink( flTime ); } else { WorldThink( flTime ); } } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteor::SkyboxThink( float flTime ) { float flDeltaTime = flTime - m_Meteor.m_flStartTime; if ( flDeltaTime > METEOR_MAX_LIFETIME ) { Destroy( this ); return; } // Check to see if the object is passive or not - act accordingly! if ( !m_Meteor.IsPassive( flTime ) ) { // Update meteor position. Vector origin; m_Meteor.GetPositionAtTime( flTime, origin ); SetLocalOrigin( origin ); // Update the position of the tail effect. m_TailEffect.SetLocalOrigin( GetLocalOrigin() ); m_HeadEffect.MeteorHeadThink( GetLocalOrigin(), flTime ); } // Add the entity to the active list - update! AddEntity(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteor::WorldToSkyboxThink( float flTime ) { // Move the meteor from the world into the skybox. m_Meteor.ConvertFromWorldToSkybox(); // Destroy the head effect. Recreate it. m_HeadEffect.Destroy(); m_HeadEffect.Start( m_Meteor.m_vecStartPosition, m_vecTravelDir ); m_HeadEffect.SetSmokeEmission( true ); m_HeadEffect.SetParticleScale( 1.0f / 16.0f ); m_HeadEffect.m_bInitThink = true; // Update to world model. SetModel( "models/props/common/meteorites/meteor05.mdl" ); // Update the meteor position (move into the skybox!) SetLocalOrigin( m_Meteor.m_vecStartPosition ); // Update (think). SkyboxThink( flTime ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteor::SkyboxToWorldThink( float flTime ) { // Move the meteor from the skybox into the world. m_Meteor.ConvertFromSkyboxToWorld(); // Destroy the head effect. Recreate it. m_HeadEffect.Destroy(); m_HeadEffect.Start( m_Meteor.m_vecStartPosition, m_vecTravelDir ); m_HeadEffect.SetSmokeEmission( true ); m_HeadEffect.SetParticleScale( 1.0f ); m_HeadEffect.m_bInitThink = true; // Update to world model. SetModel( "models/props/common/meteorites/meteor04.mdl" ); SetLocalOrigin( m_Meteor.m_vecStartPosition ); // Update (think). WorldThink( flTime ); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteor::WorldThink( float flTime ) { // Update meteor position. Vector vecEndPosition; m_Meteor.GetPositionAtTime( flTime, vecEndPosition ); // m_Meteor must return the end position in world space for the trace to work. Assert( GetMoveParent() == NULL ); // Msg( "Client: Time = %lf, Position: %4.2f %4.2f %4.2f\n", flTime, vecEndPosition.x, vecEndPosition.y, vecEndPosition.z ); // Check to see if we struck the world. If so, cause an explosion. trace_t trace; Vector vecMin, vecMax; GetRenderBounds( vecMin, vecMax ); // NOTE: This code works only if we aren't in hierarchy!!! Assert( !GetMoveParent() ); CTraceFilterWorldOnly traceFilter; UTIL_TraceHull( GetAbsOrigin(), vecEndPosition, vecMin, vecMax, MASK_SOLID_BRUSHONLY, &traceFilter, &trace ); // Collision. if ( ( trace.fraction < 1.0f ) && !( trace.surface.flags & SURF_SKY ) ) { // Move up to the end. Vector vecEnd = GetAbsOrigin() + ( ( vecEndPosition - GetAbsOrigin() ) * trace.fraction ); // Create an explosion effect! BaseExplosionEffect().Create( vecEnd, 10, 32, TE_EXPLFLAG_NONE ); // Debugging Info!!!! // debugoverlay->AddBoxOverlay( vecEnd, Vector( -10, -10, -10 ), Vector( 10, 10, 10 ), QAngle( 0.0f, 0.0f, 0.0f ), 255, 0, 0, 0, 100 ); Destroy( this ); return; } else { // Move to the end. SetLocalOrigin( vecEndPosition ); } m_TailEffect.SetLocalOrigin( GetLocalOrigin() ); m_HeadEffect.MeteorHeadThink( GetLocalOrigin(), flTime ); // Add the entity to the active list - update! AddEntity(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- C_EnvMeteor *C_EnvMeteor::Create( int nID, int iMeteorType, const Vector &vecOrigin, const Vector &vecDirection, float flSpeed, float flStartTime, float flDamageRadius, const Vector &vecTriggerMins, const Vector &vecTriggerMaxs ) { C_EnvMeteor *pMeteor = new C_EnvMeteor; if ( pMeteor ) { pMeteor->m_Meteor.Init( nID, flStartTime, METEOR_PASSIVE_TIME, vecOrigin, vecDirection, flSpeed, flDamageRadius, vecTriggerMins, vecTriggerMaxs ); // Initialize the meteor. pMeteor->InitializeAsClientEntity( "models/props/common/meteorites/meteor05.mdl", RENDER_GROUP_OPAQUE_ENTITY ); // Handle forward simulation. if ( ( pMeteor->m_Meteor.m_flStartTime + METEOR_MAX_LIFETIME ) < gpGlobals->curtime ) { Destroy( pMeteor ); } // Meteor Head and Tail pMeteor->SetTravelDirection( vecDirection ); pMeteor->m_HeadEffect.SetSmokeEmission( true ); pMeteor->m_HeadEffect.Start( vecOrigin, vecDirection ); pMeteor->m_HeadEffect.SetParticleScale( 1.0f / 16.0f ); pMeteor->m_TailEffect.Start( vecOrigin, vecDirection, flSpeed ); pMeteor->SetNextClientThink( CLIENT_THINK_ALWAYS ); } return pMeteor; } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- void C_EnvMeteor::Destroy( C_EnvMeteor *pMeteor ) { Assert( pMeteor->GetClientHandle() != INVALID_CLIENTENTITY_HANDLE ); ClientThinkList()->AddToDeleteList( pMeteor->GetClientHandle() ); }
32.550613
136
0.569429
cstom4994
68042b93b117990dfebcf29a5579fbdd97c0e06b
224
hpp
C++
graphics/shaders/Type.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
graphics/shaders/Type.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
graphics/shaders/Type.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#ifndef ___INANITY_SHADERS_TYPE_HPP___ #define ___INANITY_SHADERS_TYPE_HPP___ #include "shaders.hpp" BEGIN_INANITY_SHADERS /// Базовый класс типов данных для шейдеров. class Type { public: }; END_INANITY_SHADERS #endif
13.176471
44
0.816964
quyse
680662dc4b4e7bab5d390e481ae866021c4f9eae
2,465
cpp
C++
src/OpenGL/entrypoints/GL3.0/gl_get_booleani_v.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
114
2018-08-05T16:26:53.000Z
2021-12-30T07:28:35.000Z
src/OpenGL/entrypoints/GL3.0/gl_get_booleani_v.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
5
2018-08-18T21:16:58.000Z
2018-11-22T21:50:48.000Z
src/OpenGL/entrypoints/GL3.0/gl_get_booleani_v.cpp
kbiElude/VKGL
fffabf412723a3612ba1c5bfeafe1da38062bd18
[ "MIT" ]
6
2018-08-05T22:32:28.000Z
2021-10-04T15:39:53.000Z
/* VKGL (c) 2018 Dominik Witczak * * This code is licensed under MIT license (see LICENSE.txt for details) */ #include "OpenGL/entrypoints/GL3.0/gl_get_booleani_v.h" #include "OpenGL/context.h" #include "OpenGL/globals.h" #include "OpenGL/utils_enum.h" static bool validate(OpenGL::Context* in_context_ptr, const GLenum& in_target, const GLuint& in_index, GLboolean* out_data_ptr) { bool result = false; // .. result = true; return result; } void VKGL_APIENTRY OpenGL::vkglGetBooleani_v(GLenum target, GLuint index, GLboolean* data) { const auto dispatch_table_ptr = OpenGL::g_dispatch_table_ptr; VKGL_TRACE("glGetBooleani_v(target=[%s] index=[%u] data=[%p])", OpenGL::Utils::get_raw_string_for_gl_enum(target), index, data); dispatch_table_ptr->pGLGetBooleani_v(dispatch_table_ptr->bound_context_ptr, target, index, data); } static void vkglGetBooleani_v_execute(OpenGL::Context* in_context_ptr, const GLenum& in_target, const GLuint& in_index, GLboolean* out_data_ptr) { const OpenGL::ContextProperty target_vkgl = OpenGL::Utils::get_context_property_for_gl_enum(in_target); in_context_ptr->get_parameter_indexed(target_vkgl, OpenGL::GetSetArgumentType::Boolean, in_index, out_data_ptr); } void OpenGL::vkglGetBooleani_v_with_validation(OpenGL::Context* in_context_ptr, const GLenum& in_target, const GLuint& in_index, GLboolean* out_data_ptr) { if (validate(in_context_ptr, in_target, in_index, out_data_ptr) ) { vkglGetBooleani_v_execute(in_context_ptr, in_target, in_index, out_data_ptr); } }
35.724638
107
0.486815
kbiElude
6810d2e317cbd7d391bd49bdb16675f913db7b8b
1,833
hpp
C++
Engine/src/Render/Primitive.hpp
MilkyStorm3/SplashyEngine
2c321395da04b524938390c74a45340d7c3c1e2a
[ "MIT" ]
null
null
null
Engine/src/Render/Primitive.hpp
MilkyStorm3/SplashyEngine
2c321395da04b524938390c74a45340d7c3c1e2a
[ "MIT" ]
null
null
null
Engine/src/Render/Primitive.hpp
MilkyStorm3/SplashyEngine
2c321395da04b524938390c74a45340d7c3c1e2a
[ "MIT" ]
null
null
null
#pragma once #include "Graphics/Buffer.hpp" #include "Render/Transform.hpp" #include "Graphics/Texture.hpp" namespace ant { struct Vertex { glm::vec4 position; glm::vec4 color; glm::vec2 textureCoordinate; float textureId = 0; static VertexBufferLayout layout; operator float *(); #define INT_VERTEX_LAYOUT_DECL VertexBufferLayout Vertex::layout = {AttributeType::vec4f, AttributeType::vec4f, AttributeType::vec2f, AttributeType::vec1f}; }; class OldQuad : public TransformComponent { public: OldQuad(); ~OldQuad() {} friend class Renderer2D; friend class Renderer2DQueue; void SetColor(const glm::vec4 &color); void SetTexture(Ref<Texture> texture); Ref<Texture> GetTexture() const { return m_texture; } inline const glm::vec4 &GetColor() const { return m_color; } inline void SetSubTexture(Ref<SubTexture> tex) { SetSubTexture(*tex); } void SetSubTexture(const SubTexture &tex); private: void SetTexId(uint32_t id); glm::vec4 m_color = {1.f, 1.f, 1.f, 1.f}; Ref<Texture> m_texture; std::array<Vertex, 4> m_vertices; std::array<uint32_t, 6> m_indices; }; class Quad { public: friend class Renderer2D; friend class Renderer2DQueue; Quad(const glm::vec4 &color = {1.f, 1.f, 1.f, 1.f}); ~Quad() {} inline const glm::vec4 &GetColor() const { return m_color; } inline glm::vec4 &GetColorRef() { return m_color; } void SetColor(const glm::vec4 &color); void UpdateColor(); private: glm::vec4 m_color; std::array<Vertex, 4> m_vertices; static const std::array<uint32_t, 6> s_indices; }; }
26.955882
164
0.604474
MilkyStorm3
681626199cecf9f91bc68e243da86c518fc934f5
315
cpp
C++
lib/geometry/distance_between_two_points.cpp
mdstoy/atcoder-cpp
5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7
[ "Unlicense" ]
null
null
null
lib/geometry/distance_between_two_points.cpp
mdstoy/atcoder-cpp
5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7
[ "Unlicense" ]
null
null
null
lib/geometry/distance_between_two_points.cpp
mdstoy/atcoder-cpp
5dfe4db5558dfa1faaf10f19c1a99fee1b4104e7
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // verifing: https://atcoder.jp/contests/math-and-algorithm/submissions/30698630 // *** CAUTION *** : Return value is square. double distance_between_two_points(double x1, double y1, double x2, double y2) { return (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); }
31.5
80
0.669841
mdstoy
681846559edf0e4b5d0f15a30d826a03e68a29a6
313
cpp
C++
Contest 1005/D.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
Contest 1005/D.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
Contest 1005/D.cpp
PC-DOS/SEUCPP-OJ-KEYS
073f97fb29a659abd25554330382f0a7149c2511
[ "MIT" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main(){ int a,b,c,n; n = 0; for (c = 1; c <= 100; ++c){ for (a = 1; a <= c; ++a){ b = sqrt(c*c - a*a); if (a <= b && ((a*a + b*b) == (c*c))) ++n; } } cout << n; //system("pause > nul"); }
20.866667
54
0.373802
PC-DOS
681af677f93b2046ecf12a3ced4e35528cef662f
17,280
cpp
C++
src/bpftrace.cpp
ajor/bpftrace
691e1264b526b9179a610c3ae706e439efd132d3
[ "Apache-2.0" ]
278
2016-12-28T00:51:17.000Z
2022-02-09T10:32:31.000Z
src/bpftrace.cpp
brendangregg/bpftrace
4cc2e864a9bbbcb97a508bfc5a3db1cd0b5d7f95
[ "Apache-2.0" ]
48
2017-07-10T20:17:55.000Z
2020-01-20T23:41:51.000Z
src/bpftrace.cpp
ajor/bpftrace
691e1264b526b9179a610c3ae706e439efd132d3
[ "Apache-2.0" ]
19
2017-07-28T05:49:00.000Z
2022-02-22T22:05:37.000Z
#include <assert.h> #include <fstream> #include <iomanip> #include <iostream> #include <regex> #include <sstream> #include <sys/epoll.h> #include "bcc_syms.h" #include "perf_reader.h" #include "bpforc.h" #include "bpftrace.h" #include "attached_probe.h" #include "triggers.h" namespace bpftrace { int BPFtrace::add_probe(ast::Probe &p) { for (auto attach_point : *p.attach_points) { if (attach_point->provider == "BEGIN") { Probe probe; probe.path = "/proc/self/exe"; probe.attach_point = "BEGIN_trigger"; probe.type = probetype(attach_point->provider); probe.prog_name = p.name(); probe.name = p.name(); special_probes_.push_back(probe); continue; } else if (attach_point->provider == "END") { Probe probe; probe.path = "/proc/self/exe"; probe.attach_point = "END_trigger"; probe.type = probetype(attach_point->provider); probe.prog_name = p.name(); probe.name = p.name(); special_probes_.push_back(probe); continue; } std::vector<std::string> attach_funcs; if (attach_point->func.find("*") != std::string::npos || attach_point->func.find("[") != std::string::npos && attach_point->func.find("]") != std::string::npos) { std::string file_name; switch (probetype(attach_point->provider)) { case ProbeType::kprobe: case ProbeType::kretprobe: file_name = "/sys/kernel/debug/tracing/available_filter_functions"; break; case ProbeType::tracepoint: file_name = "/sys/kernel/debug/tracing/available_events"; break; default: std::cerr << "Wildcard matches aren't available on probe type '" << attach_point->provider << "'" << std::endl; return 1; } auto matches = find_wildcard_matches(attach_point->target, attach_point->func, file_name); attach_funcs.insert(attach_funcs.end(), matches.begin(), matches.end()); } else { attach_funcs.push_back(attach_point->func); } for (auto func : attach_funcs) { Probe probe; probe.path = attach_point->target; probe.attach_point = func; probe.type = probetype(attach_point->provider); probe.prog_name = p.name(); probe.name = attach_point->name(func); probe.freq = attach_point->freq; probes_.push_back(probe); } } return 0; } std::set<std::string> BPFtrace::find_wildcard_matches(const std::string &prefix, const std::string &func, const std::string &file_name) { // Turn glob into a regex auto regex_str = "(" + std::regex_replace(func, std::regex("\\*"), "[^\\s]*") + ")"; if (prefix != "") regex_str = prefix + ":" + regex_str; regex_str = "^" + regex_str; std::regex func_regex(regex_str); std::smatch match; std::ifstream file(file_name); if (file.fail()) { std::cerr << strerror(errno) << ": " << file_name << std::endl; return std::set<std::string>(); } std::string line; std::set<std::string> matches; while (std::getline(file, line)) { if (std::regex_search(line, match, func_regex)) { assert(match.size() == 2); matches.insert(match[1]); } } return matches; } int BPFtrace::num_probes() const { return special_probes_.size() + probes_.size(); } void perf_event_printer(void *cb_cookie, void *data, int size) { auto bpftrace = static_cast<BPFtrace*>(cb_cookie); auto printf_id = *static_cast<uint64_t*>(data); auto arg_data = static_cast<uint8_t*>(data) + sizeof(uint64_t); auto fmt = std::get<0>(bpftrace->printf_args_[printf_id]).c_str(); auto args = std::get<1>(bpftrace->printf_args_[printf_id]); std::vector<uint64_t> arg_values; std::vector<std::unique_ptr<char>> resolved_symbols; for (auto arg : args) { switch (arg.type) { case Type::integer: arg_values.push_back(*(uint64_t*)arg_data); break; case Type::string: arg_values.push_back((uint64_t)arg_data); break; case Type::sym: resolved_symbols.emplace_back(strdup( bpftrace->resolve_sym(*(uint64_t*)arg_data).c_str())); arg_values.push_back((uint64_t)resolved_symbols.back().get()); break; case Type::usym: resolved_symbols.emplace_back(strdup( bpftrace->resolve_usym(*(uint64_t*)arg_data).c_str())); arg_values.push_back((uint64_t)resolved_symbols.back().get()); break; default: abort(); } arg_data += arg.size; } switch (args.size()) { case 0: printf(fmt); break; case 1: printf(fmt, arg_values.at(0)); break; case 2: printf(fmt, arg_values.at(0), arg_values.at(1)); break; case 3: printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2)); break; case 4: printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2), arg_values.at(3)); break; case 5: printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2), arg_values.at(3), arg_values.at(4)); break; case 6: printf(fmt, arg_values.at(0), arg_values.at(1), arg_values.at(2), arg_values.at(3), arg_values.at(4), arg_values.at(5)); break; default: abort(); } } void perf_event_lost(void *cb_cookie, uint64_t lost) { printf("Lost %lu events\n", lost); } std::unique_ptr<AttachedProbe> BPFtrace::attach_probe(Probe &probe, const BpfOrc &bpforc) { auto func = bpforc.sections_.find("s_" + probe.prog_name); if (func == bpforc.sections_.end()) { std::cerr << "Code not generated for probe: " << probe.name << std::endl; return nullptr; } try { return std::make_unique<AttachedProbe>(probe, func->second); } catch (std::runtime_error e) { std::cerr << e.what() << std::endl; } return nullptr; } int BPFtrace::run(std::unique_ptr<BpfOrc> bpforc) { for (Probe &probe : special_probes_) { auto attached_probe = attach_probe(probe, *bpforc.get()); if (attached_probe == nullptr) return -1; special_attached_probes_.push_back(std::move(attached_probe)); } int epollfd = setup_perf_events(); if (epollfd < 0) return epollfd; BEGIN_trigger(); for (Probe &probe : probes_) { auto attached_probe = attach_probe(probe, *bpforc.get()); if (attached_probe == nullptr) return -1; attached_probes_.push_back(std::move(attached_probe)); } poll_perf_events(epollfd); attached_probes_.clear(); END_trigger(); poll_perf_events(epollfd, 100); special_attached_probes_.clear(); return 0; } int BPFtrace::setup_perf_events() { int epollfd = epoll_create1(EPOLL_CLOEXEC); if (epollfd == -1) { std::cerr << "Failed to create epollfd" << std::endl; return -1; } std::vector<int> cpus = ebpf::get_online_cpus(); online_cpus_ = cpus.size(); for (int cpu : cpus) { int page_cnt = 8; void *reader = bpf_open_perf_buffer(&perf_event_printer, &perf_event_lost, this, -1, cpu, page_cnt); if (reader == nullptr) { std::cerr << "Failed to open perf buffer" << std::endl; return -1; } struct epoll_event ev = {}; ev.events = EPOLLIN; ev.data.ptr = reader; int reader_fd = perf_reader_fd((perf_reader*)reader); bpf_update_elem(perf_event_map_->mapfd_, &cpu, &reader_fd, 0); if (epoll_ctl(epollfd, EPOLL_CTL_ADD, reader_fd, &ev) == -1) { std::cerr << "Failed to add perf reader to epoll" << std::endl; return -1; } } return epollfd; } void BPFtrace::poll_perf_events(int epollfd, int timeout) { auto events = std::vector<struct epoll_event>(online_cpus_); while (true) { int ready = epoll_wait(epollfd, events.data(), online_cpus_, timeout); if (ready <= 0) { return; } for (int i=0; i<ready; i++) { perf_reader_event_read((perf_reader*)events[i].data.ptr); } } return; } int BPFtrace::print_maps() { for(auto &mapmap : maps_) { IMap &map = *mapmap.second.get(); int err; if (map.type_.type == Type::quantize) err = print_map_quantize(map); else err = print_map(map); if (err) return err; } return 0; } int BPFtrace::print_map(IMap &map) { std::vector<uint8_t> old_key; try { old_key = find_empty_key(map, map.key_.size()); } catch (std::runtime_error &e) { std::cerr << "Error getting key for map '" << map.name_ << "': " << e.what() << std::endl; return -2; } auto key(old_key); std::vector<std::pair<std::vector<uint8_t>, std::vector<uint8_t>>> values_by_key; while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0) { int value_size = map.type_.size; if (map.type_.type == Type::count) value_size *= ncpus_; auto value = std::vector<uint8_t>(value_size); int err = bpf_lookup_elem(map.mapfd_, key.data(), value.data()); if (err) { std::cerr << "Error looking up elem: " << err << std::endl; return -1; } values_by_key.push_back({key, value}); old_key = key; } if (map.type_.type == Type::count) { std::sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b) { return reduce_value(a.second, ncpus_) < reduce_value(b.second, ncpus_); }); } else { sort_by_key(map.key_.args_, values_by_key); }; for (auto &pair : values_by_key) { auto key = pair.first; auto value = pair.second; std::cout << map.name_ << map.key_.argument_value_list(*this, key) << ": "; if (map.type_.type == Type::stack) std::cout << get_stack(*(uint32_t*)value.data(), false, 8); else if (map.type_.type == Type::ustack) std::cout << get_stack(*(uint32_t*)value.data(), true, 8); else if (map.type_.type == Type::sym) std::cout << resolve_sym(*(uintptr_t*)value.data()); else if (map.type_.type == Type::usym) std::cout << resolve_usym(*(uintptr_t*)value.data()); else if (map.type_.type == Type::string) std::cout << value.data() << std::endl; else if (map.type_.type == Type::count) std::cout << reduce_value(value, ncpus_) << std::endl; else std::cout << *(int64_t*)value.data() << std::endl; } std::cout << std::endl; return 0; } int BPFtrace::print_map_quantize(IMap &map) { // A quantize-map adds an extra 8 bytes onto the end of its key for storing // the bucket number. // e.g. A map defined as: @x[1, 2] = @quantize(3); // would actually be stored with the key: [1, 2, 3] std::vector<uint8_t> old_key; try { old_key = find_empty_key(map, map.key_.size() + 8); } catch (std::runtime_error &e) { std::cerr << "Error getting key for map '" << map.name_ << "': " << e.what() << std::endl; return -2; } auto key(old_key); std::map<std::vector<uint8_t>, std::vector<uint64_t>> values_by_key; while (bpf_get_next_key(map.mapfd_, old_key.data(), key.data()) == 0) { auto key_prefix = std::vector<uint8_t>(map.key_.size()); int bucket = key.at(map.key_.size()); for (size_t i=0; i<map.key_.size(); i++) key_prefix.at(i) = key.at(i); int value_size = map.type_.size * ncpus_; auto value = std::vector<uint8_t>(value_size); int err = bpf_lookup_elem(map.mapfd_, key.data(), value.data()); if (err) { std::cerr << "Error looking up elem: " << err << std::endl; return -1; } if (values_by_key.find(key_prefix) == values_by_key.end()) { // New key - create a list of buckets for it values_by_key[key_prefix] = std::vector<uint64_t>(65); } values_by_key[key_prefix].at(bucket) = reduce_value(value, ncpus_); old_key = key; } // Sort based on sum of counts in all buckets std::vector<std::pair<std::vector<uint8_t>, uint64_t>> total_counts_by_key; for (auto &map_elem : values_by_key) { int sum = 0; for (size_t i=0; i<map_elem.second.size(); i++) { sum += map_elem.second.at(i); } total_counts_by_key.push_back({map_elem.first, sum}); } std::sort(total_counts_by_key.begin(), total_counts_by_key.end(), [&](auto &a, auto &b) { return a.second < b.second; }); for (auto &key_count : total_counts_by_key) { auto &key = key_count.first; auto &value = values_by_key[key]; std::cout << map.name_ << map.key_.argument_value_list(*this, key) << ": " << std::endl; print_quantize(value); std::cout << std::endl; } return 0; } int BPFtrace::print_quantize(const std::vector<uint64_t> &values) const { int max_index = -1; int max_value = 0; for (size_t i = 0; i < values.size(); i++) { int v = values.at(i); if (v != 0) max_index = i; if (v > max_value) max_value = v; } if (max_index == -1) return 0; for (int i = 0; i <= max_index; i++) { std::ostringstream header; if (i == 0) { header << "[0, 1]"; } else { header << "[" << quantize_index_label(i); header << ", " << quantize_index_label(i+1) << ")"; } int max_width = 52; int bar_width = values.at(i)/(float)max_value*max_width; std::string bar(bar_width, '@'); std::cout << std::setw(16) << std::left << header.str() << std::setw(8) << std::right << values.at(i) << " |" << std::setw(max_width) << std::left << bar << "|" << std::endl; } return 0; } std::string BPFtrace::quantize_index_label(int power) { char suffix = '\0'; if (power >= 40) { suffix = 'T'; power -= 40; } else if (power >= 30) { suffix = 'G'; power -= 30; } else if (power >= 20) { suffix = 'M'; power -= 20; } else if (power >= 10) { suffix = 'k'; power -= 10; } std::ostringstream label; label << (1<<power); if (suffix) label << suffix; return label.str(); } uint64_t BPFtrace::reduce_value(const std::vector<uint8_t> &value, int ncpus) { uint64_t sum = 0; for (int i=0; i<ncpus; i++) { sum += *(uint64_t*)(value.data() + i*sizeof(uint64_t*)); } return sum; } std::vector<uint8_t> BPFtrace::find_empty_key(IMap &map, size_t size) const { if (size == 0) size = 8; auto key = std::vector<uint8_t>(size); int value_size = map.type_.size; if (map.type_.type == Type::count || map.type_.type == Type::quantize) value_size *= ncpus_; auto value = std::vector<uint8_t>(value_size); if (bpf_lookup_elem(map.mapfd_, key.data(), value.data())) return key; for (auto &elem : key) elem = 0xff; if (bpf_lookup_elem(map.mapfd_, key.data(), value.data())) return key; for (auto &elem : key) elem = 0x55; if (bpf_lookup_elem(map.mapfd_, key.data(), value.data())) return key; throw std::runtime_error("Could not find empty key"); } std::string BPFtrace::get_stack(uint32_t stackid, bool ustack, int indent) { auto stack_trace = std::vector<uint64_t>(MAX_STACK_SIZE); int err = bpf_lookup_elem(stackid_map_->mapfd_, &stackid, stack_trace.data()); if (err) { std::cerr << "Error looking up stack id " << stackid << ": " << err << std::endl; return ""; } std::ostringstream stack; std::string padding(indent, ' '); stack << "\n"; for (auto &addr : stack_trace) { if (addr == 0) break; if (!ustack) stack << padding << resolve_sym(addr, true) << std::endl; else stack << padding << resolve_usym(addr) << std::endl; } return stack.str(); } std::string BPFtrace::resolve_sym(uintptr_t addr, bool show_offset) { struct bcc_symbol sym; std::ostringstream symbol; if (ksyms_.resolve_addr(addr, &sym)) { symbol << sym.name; if (show_offset) symbol << "+" << sym.offset; } else { symbol << (void*)addr; } return symbol.str(); } std::string BPFtrace::resolve_usym(uintptr_t addr) const { // TODO std::ostringstream symbol; symbol << (void*)addr; return symbol.str(); } void BPFtrace::sort_by_key(std::vector<SizedType> key_args, std::vector<std::pair<std::vector<uint8_t>, std::vector<uint8_t>>> &values_by_key) { int arg_offset = 0; for (auto arg : key_args) { arg_offset += arg.size; } // Sort the key arguments in reverse order so the results are sorted by // the first argument first, then the second, etc. for (size_t i=key_args.size(); i-- > 0; ) { auto arg = key_args.at(i); arg_offset -= arg.size; if (arg.type == Type::integer) { if (arg.size == 8) { std::stable_sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b) { return *(uint64_t*)(a.first.data() + arg_offset) < *(uint64_t*)(b.first.data() + arg_offset); }); } else abort(); } else if (arg.type == Type::string) { std::stable_sort(values_by_key.begin(), values_by_key.end(), [&](auto &a, auto &b) { return strncmp((char*)(a.first.data() + arg_offset), (char*)(b.first.data() + arg_offset), STRING_SIZE) < 0; }); } // Other types don't get sorted } } } // namespace bpftrace
25.300146
135
0.599653
ajor
681da69852f2e04e8ec972ea255dc83edc65a06a
1,632
cc
C++
ETI06F3.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2021-02-01T11:21:56.000Z
2021-02-01T11:21:56.000Z
ETI06F3.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
null
null
null
ETI06F3.cc
hkktr/POLSKI-SPOJ
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
[ "Unlicense" ]
1
2022-01-28T15:25:45.000Z
2022-01-28T15:25:45.000Z
// C++14 (gcc 8.3) #include <algorithm> #include <iostream> #include <vector> class Graph { public: Graph(int vertices) : vertices_{vertices} { adjacency_list_.resize(vertices_); } void AddEdge(int a, int b) { adjacency_list_[a].push_back(b); } std::vector<int> ConnectedComponents() { std::vector<char> visited(vertices_, false); std::vector<int> connected_components; for (int v{0}; v < vertices_; ++v) { if (!visited[v]) { int count{0}; ConnectedComponentsUtility(v, visited, count); if (count > 0) connected_components.push_back(count); } } return connected_components; } private: int vertices_; std::vector<std::vector<int>> adjacency_list_; void ConnectedComponentsUtility(int v, std::vector<char>& visited, int& count) { visited[v] = true; ++count; for (int u : adjacency_list_[v]) { if (!visited[u]) { ConnectedComponentsUtility(u, visited, count); } } } }; int main() { int n; std::cin >> n; Graph graph(n); for (int i{0}; i < n; ++i) { for (int j{0}; j < n; ++j) { bool acquaintance; std::cin >> acquaintance; if (acquaintance) graph.AddEdge(i, j); } } std::vector<int> connected_components{graph.ConnectedComponents()}; if (connected_components.size() != 3) { std::cout << "NIE\n"; } else { std::sort(connected_components.begin(), connected_components.end()); std::cout << "TAK"; for (int count : connected_components) { std::cout << " " << count; } std::cout << "\n"; } return 0; }
22.356164
72
0.58701
hkktr
68217ed14129fd41ec911faa7874ca14d18ae343
995
hpp
C++
src/Luddite/Utilities/YamlParsers.hpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
1
2021-06-03T05:46:46.000Z
2021-06-03T05:46:46.000Z
src/Luddite/Utilities/YamlParsers.hpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
null
null
null
src/Luddite/Utilities/YamlParsers.hpp
Aquaticholic/Luddite-Engine
66584fa31ee75b0cdebabe88cdfa2431d0e0ac2f
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Luddite/Core/pch.hpp" #include "Luddite/Graphics/Color.hpp" void operator >>(const YAML::Node& node, float& f); void operator >>(const YAML::Node& node, int32_t& i); void operator >>(const YAML::Node& node, uint32_t& u); void operator >>(const YAML::Node& node, glm::vec2& v); void operator >>(const YAML::Node& node, glm::vec3& v); void operator >>(const YAML::Node& node, glm::vec4& v); void operator >>(const YAML::Node& node, glm::ivec2& v); void operator >>(const YAML::Node& node, glm::ivec3& v); void operator >>(const YAML::Node& node, glm::ivec4& v); void operator >>(const YAML::Node& node, glm::uvec2& v); void operator >>(const YAML::Node& node, glm::uvec3& v); void operator >>(const YAML::Node& node, glm::uvec4& v); void operator >>(const YAML::Node& node, glm::mat3& m); void operator >>(const YAML::Node& node, glm::mat4& m); void operator >>(const YAML::Node& node, Luddite::ColorRGB& c); void operator >>(const YAML::Node& node, Luddite::ColorRGBA& c);
49.75
64
0.681407
Aquaticholic
6822d1a77aa7f6e4f374c36b11d3bd13fa35b860
4,484
cpp
C++
src/QtFuzzy/nFuzzyVariable.cpp
Vladimir-Lin/QtFuzzy
185869384f3ce9d3a801080b675bae8ed6c5fb12
[ "MIT" ]
null
null
null
src/QtFuzzy/nFuzzyVariable.cpp
Vladimir-Lin/QtFuzzy
185869384f3ce9d3a801080b675bae8ed6c5fb12
[ "MIT" ]
null
null
null
src/QtFuzzy/nFuzzyVariable.cpp
Vladimir-Lin/QtFuzzy
185869384f3ce9d3a801080b675bae8ed6c5fb12
[ "MIT" ]
null
null
null
#include <qtfuzzy.h> N::Fuzzy::Variable:: Variable ( const QString & name , double minimum , double maximum ) : Object ( 0 , None ) , _name ( name ) , _minimum ( minimum ) , _maximum ( maximum ) , Name ( "" ) { } N::Fuzzy::Variable::Variable(const Variable & copy) { uuid = copy.uuid ; type = copy.type ; Name = copy.Name ; nFullLoop ( i , copy.numberOfTerms() ) { addTerm ( copy.getTerm(i)->copy() ) ; } ; } N::Fuzzy::Variable::~Variable(void) { nFullLoop ( i , _terms . size () ) { delete _terms.at(i) ; } ; } void N::Fuzzy::Variable::setName(const QString & n) { _name = n ; } QString N::Fuzzy::Variable::getName(void) const { return _name ; } void N::Fuzzy::Variable::setRange(double minimum,double maximum) { _minimum = minimum ; _maximum = maximum ; } void N::Fuzzy::Variable::setMinimum(double minimum) { _minimum = minimum ; } double N::Fuzzy::Variable::getMinimum(void) const { return _minimum ; } void N::Fuzzy::Variable::setMaximum(double maximum) { _maximum = maximum ; } double N::Fuzzy::Variable::getMaximum(void) const { return _maximum ; } QString N::Fuzzy::Variable::fuzzify(double x) const { QString R ; QString M ; QStringList L ; nFullLoop ( i , _terms.size() ) { M = Operation :: str ( _terms . at(i)->membership(x) ) ; R = QString("%1 / %2").arg(M).arg(_terms.at(i)->Name ) ; L << R ; } ; R = "" ; if (L.count()>0) R = L . join (" + ") ; return R ; } N::Fuzzy::Term * N::Fuzzy::Variable::highestMembership(double x,double * yhighest) const { Term * result = NULL ; double ymax = 0 ; nFullLoop ( i , _terms.size() ) { double y = _terms.at(i)->membership(x) ; if ( Operation :: isGt ( y , ymax ) ) { ymax = y ; result = _terms.at(i) ; } ; } ; if (yhighest) (*yhighest) = ymax ; return result ; } QString N::Fuzzy::Variable::toString(void) const { QString R ; QStringList L ; nFullLoop ( i , _terms.size() ) { L << _terms.at(i)->toString() ; } ; R = QString( "%1 [ %2 ]" ) .arg ( getName() ) .arg ( L.join(", ") ) ; return R ; } void N::Fuzzy::Variable::sort(void) { SortByCoG criterion ; criterion.minimum = _minimum ; criterion.maximum = _maximum ; std::sort(_terms.begin(),_terms.end(),criterion) ; } void N::Fuzzy::Variable::addTerm(Term * term) { _terms . push_back ( term ) ; } void N::Fuzzy::Variable::insertTerm(Term * term,int index) { _terms . insert ( index , term ) ; } N::Fuzzy::Term * N::Fuzzy::Variable::getTerm(int index) const { return _terms . at ( index ) ; } N::Fuzzy::Term * N::Fuzzy::Variable::getTerm(const QString & name) const { nFullLoop ( i , _terms.size() ) { if (_terms.at(i)->is(name)) { return _terms.at(i) ; } ; } ; return NULL ; } bool N::Fuzzy::Variable::hasTerm(const QString & name) const { return NotNull( getTerm(name) ) ; } N::Fuzzy::Term * N::Fuzzy::Variable::removeTerm(int index) { Term * result ; result = _terms.at(index) ; _terms . remove (index) ; return result ; } int N::Fuzzy::Variable::numberOfTerms(void) const { return _terms.size() ; } const QVector<N::Fuzzy::Term *> & N::Fuzzy::Variable::terms(void) const { return _terms ; }
27.012048
88
0.432649
Vladimir-Lin
68280ca358bc4ed9c6da4e3744c99967dd88af84
3,065
cpp
C++
test/CpuOperations/BCHGTest.cpp
PaulTrampert/GenieSys
637e7f764bc7faac8d0b5afcf22646e200562f6a
[ "MIT" ]
null
null
null
test/CpuOperations/BCHGTest.cpp
PaulTrampert/GenieSys
637e7f764bc7faac8d0b5afcf22646e200562f6a
[ "MIT" ]
82
2020-12-17T04:03:10.000Z
2022-03-24T17:54:28.000Z
test/CpuOperations/BCHGTest.cpp
PaulTrampert/GenieSys
637e7f764bc7faac8d0b5afcf22646e200562f6a
[ "MIT" ]
null
null
null
// // Created by paul.trampert on 4/4/2021. // #include <gtest/gtest.h> #include <GenieSys/CpuOperations/BCHG.h> #include <GenieSys/Bus.h> struct BCHGTest : testing::Test { GenieSys::M68kCpu* cpu; GenieSys::Bus bus; GenieSys::BCHG* subject; BCHGTest() { cpu = bus.getCpu(); subject = new GenieSys::BCHG(cpu, &bus); } ~BCHGTest() override { delete subject; } }; TEST_F(BCHGTest, SpecificityIsTen) { ASSERT_EQ(10, subject->getSpecificity()); } TEST_F(BCHGTest, DisassembleImmediate) { cpu->setPc(20); bus.writeWord(20, 0x0003); ASSERT_EQ("BCHG $03,D7", subject->disassemble(0b0000100000000111)); } TEST_F(BCHGTest, DisassembleDataRegister) { ASSERT_EQ("BCHG D2,D7", subject->disassemble(0b0000010100000111)); } TEST_F(BCHGTest, ImmModeSetsZeroFlag_WhenSpecifiedBitIsZero) { cpu->setDataRegister(0, (uint32_t)0x00000000); cpu->setCcrFlags(GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW); cpu->setPc(20); bus.writeWord(20, 0x0003); uint8_t cycles = subject->execute(0b0000100000000000); ASSERT_EQ(12, cycles); ASSERT_EQ((GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW | GenieSys::CCR_ZERO), cpu->getCcrFlags()); ASSERT_EQ(8, cpu->getDataRegister(0)); } TEST_F(BCHGTest, ImmModeDoesNotSetZeroFlag_WhenSpecifiedBitIsNotZero) { cpu->setDataRegister(0, (uint32_t)0b00000000000000000000000000001000); cpu->setCcrFlags(GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW); cpu->setPc(20); bus.writeWord(20, 0x0003); uint8_t cycles = subject->execute(0b0000100000000000); ASSERT_EQ(12, cycles); ASSERT_EQ((GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW), cpu->getCcrFlags()); ASSERT_EQ(0, cpu->getDataRegister(0)); } TEST_F(BCHGTest, RegModeSetsZeroFlag_WhenSpecifiedBitIsZero) { cpu->setDataRegister(0, (uint32_t)0x00000000); cpu->setCcrFlags(GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW); cpu->setDataRegister(2, (uint32_t)35); uint8_t cycles = subject->execute(0b0000010100000000); ASSERT_EQ(8, cycles); ASSERT_EQ((GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW | GenieSys::CCR_ZERO), cpu->getCcrFlags()); ASSERT_EQ(8, cpu->getDataRegister(0)); } TEST_F(BCHGTest, RegModeDoesNotSetZeroFlag_WhenSpecifiedBitIsNotZero) { cpu->setDataRegister(0, (uint32_t)0b00000000000000000000000000001000); cpu->setCcrFlags(GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW); cpu->setDataRegister(2, (uint32_t)35); uint8_t cycles = subject->execute(0b0000010100000000); ASSERT_EQ(8, cycles); ASSERT_EQ((GenieSys::CCR_CARRY | GenieSys::CCR_EXTEND | GenieSys::CCR_NEGATIVE | GenieSys::CCR_OVERFLOW), cpu->getCcrFlags()); ASSERT_EQ(0, cpu->getDataRegister(0)); }
34.055556
151
0.72398
PaulTrampert
68292e8a8ea099595f63a41b270e1210d757bda9
2,210
cpp
C++
omp1.cpp
jrengdahl/bmomp
3c00f0e599c127504e47a0b35fdb8dbd85f9ebc4
[ "BSD-3-Clause" ]
null
null
null
omp1.cpp
jrengdahl/bmomp
3c00f0e599c127504e47a0b35fdb8dbd85f9ebc4
[ "BSD-3-Clause" ]
null
null
null
omp1.cpp
jrengdahl/bmomp
3c00f0e599c127504e47a0b35fdb8dbd85f9ebc4
[ "BSD-3-Clause" ]
null
null
null
// A test program for experiments with OpenMP. // omp1.cpp tests // "#pragma omp parallel for" #include <stdint.h> #include <stdio.h> #include "exports.hpp" #include "thread.hpp" #include "threadFIFO.hpp" #include "libgomp.hpp" #include "omp.h" // The DeferFIFO used by yield, for rudimentary time-slicing. // Note that the only form of "time-slicing" occurs when a thread // voluntarily calls "yield" to temporarily give up the CPU // to other threads. threadFIFO<DEFER_FIFO_DEPTH> DeferFIFO; // forward declaration of the test thread // We want the test thread to be later in the proram so that "start" is at the beginning of the binary, // so we can say "go 24000000" and not have to look up the entry point in the map. void test(); // the stack for the test thread char stack[2048]; // this is the entry point // we want it to be located at the beginning of the binary extern "C" int start(int argc, char *const argv[]) { app_startup(argv); // init the u-boot API Thread::init(); // init the bare metal threading system libgomp_init(); // init OpenMP Thread::spawn(test, stack); // spawn the test thread // The background loop. // Loop until the test thread terminates. // Note that this code will only spin if // -- all threads have yielded or suspended, or // -- the test thread has terminated. while(!Thread::done(stack)) // while the test thread is stil running { undefer(); // keep trying to wake threads } printf("test complete\n"); return (0); } #define LIMIT 32 void test() { unsigned array[LIMIT]; printf("hello, world!\n"); #pragma omp parallel for num_threads(LIMIT) for(int i=0; i<LIMIT; i++) { array[i] = omp_get_thread_num(); // fill an array with the number of the thread that procsed each element of the array } for(int i=0; i<LIMIT; i++) { printf("%u ", array[i]); // print the array } printf("\n"); }
27.625
141
0.589593
jrengdahl
6829bd8c63bcfd90ba5752091106328991fa11b0
404
hpp
C++
hw3/tmpl/src-cpp/include/AST/UnaryOperator.hpp
idoleat/P-Language-Compiler-CourseProject
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
7
2020-09-10T16:54:49.000Z
2022-03-15T12:39:23.000Z
hw3/tmpl/src-cpp/include/AST/UnaryOperator.hpp
idoleat/simple-P-compiler
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
null
null
null
hw3/tmpl/src-cpp/include/AST/UnaryOperator.hpp
idoleat/simple-P-compiler
57db735b349a0a3a30d78b927953e2d44b7c7d53
[ "MIT" ]
null
null
null
#ifndef __AST_UNARY_OPERATOR_NODE_H #define __AST_UNARY_OPERATOR_NODE_H #include "AST/expression.hpp" class UnaryOperatorNode : public ExpressionNode { public: UnaryOperatorNode(const uint32_t line, const uint32_t col /* TODO: operator, expression */); ~UnaryOperatorNode() = default; void print() override; private: // TODO: operator, expression }; #endif
21.263158
61
0.70297
idoleat
682aeb16d6533e5bff7e1bbd3aa5831f4aa8dd4d
1,290
cpp
C++
math/kth_root_mod/gen/safe_prime.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
290
2019-06-06T22:20:36.000Z
2022-03-27T12:45:04.000Z
math/kth_root_mod/gen/safe_prime.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
536
2019-06-06T18:25:36.000Z
2022-03-29T11:46:36.000Z
math/kth_root_mod/gen/safe_prime.cpp
tko919/library-checker-problems
007a3ef79d1a1824e68545ab326d1523d9c05262
[ "Apache-2.0" ]
82
2019-06-06T18:17:55.000Z
2022-03-21T07:40:31.000Z
#include "random.h" #include <iostream> #include <vector> #include <cassert> #include "../params.h" using namespace std; using ll = long long; vector<ll> enum_prime(ll l, ll r) { vector<int> is_prime(r - l + 1, true); for (ll i = 2; i * i <= r; i++) { for (ll j = max(2 * i, (l + i - 1) / i * i); j <= r; j += i) { assert(l <= j && j <= r); is_prime[j - l] = false; } } vector<ll> res; for (ll i = l; i <= r; i++) { if (2 <= i && is_prime[i - l]) res.push_back(i); } return res; } bool is_prime(ll a) { for (ll div = 2; div*div <= a; ++div) { if (a % div == 0) return false; } return true; } // Suppose a is prime. bool is_safeprime(ll a) { return a>=3 && is_prime((a-1)/2); } int main(int, char* argv[]) { long long seed = atoll(argv[1]); auto gen = Random(seed); ll up = gen.uniform((ll)9e8, P_MAX); vector<ll> primes = enum_prime(up - (ll)5e6, up); int t = T_MAX; printf("%d\n", t); for (int i = 0; i < t; i++) { ll p = 0; while (!is_safeprime(p)) p = primes[gen.uniform<ll>(0LL, primes.size() - 1)]; ll y = gen.uniform(0LL, p - 1); ll k = gen.uniform(0LL, p - 1); printf("%lld %lld %lld\n", k, y, p); } return 0; }
23.454545
85
0.494574
tko919
682eba30c768c3fd3dcaaef271ea4e7c5c664ea1
871
hpp
C++
include/daqi/utilities/file_utilities.hpp
hl4/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
166
2019-04-15T03:19:31.000Z
2022-03-26T05:41:12.000Z
include/daqi/utilities/file_utilities.hpp
YangKefan/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
9
2019-07-18T06:09:59.000Z
2021-01-27T04:19:04.000Z
include/daqi/utilities/file_utilities.hpp
YangKefan/da4qi4
9dfb8902427d40b392977b4fd706048ce3ee8828
[ "Apache-2.0" ]
43
2019-07-03T05:41:57.000Z
2022-02-24T14:16:09.000Z
#ifndef DAQI_FILE_UTILITIES_HPP #define DAQI_FILE_UTILITIES_HPP #include <string> #include "daqi/def/boost_def.hpp" namespace da4qi4 { namespace Utilities { bool SaveDataToFile(std::string const& data, std::string const& filename_with_path, std::string& err); bool SaveDataToFile(std::string const& data, fs::path const& filename_with_path, std::string& err); bool IsFileExists(fs::path const& fullpath); bool IsFileExists(std::string const& fullpath); enum class FileOverwriteOptions { ignore_success, ignore_fail, overwrite }; std::pair<bool, std::string /*msg*/> CopyFile(fs::path const& src, fs::path const& dst, FileOverwriteOptions overwrite); std::pair<bool, std::string /*msg*/> MoveFile(fs::path const& src, fs::path const& dst, FileOverwriteOptions overwrite); } //namesapce Utilities } //namespace da4qi4 #endif // DAQI_FILE_UTILITIES_HPP
24.885714
102
0.75775
hl4
682fc5812863d852f26231283fd91b4c75e0515f
613
cpp
C++
leetcode/Algorithms/reverse-vowels-of-a-string.cpp
Doarakko/competitive-programming
5ae78c501664af08a3f16c81dbd54c68310adec8
[ "MIT" ]
1
2017-07-11T16:47:29.000Z
2017-07-11T16:47:29.000Z
leetcode/Algorithms/reverse-vowels-of-a-string.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
1
2021-02-07T09:10:26.000Z
2021-02-07T09:10:26.000Z
leetcode/Algorithms/reverse-vowels-of-a-string.cpp
Doarakko/Competitive-Programming
10642a4bd7266c828dd2fc6e311284e86bdf2968
[ "MIT" ]
null
null
null
class Solution { public: string reverseVowels(string s) { vector<int> v; for (int i = 0; i < s.length(); i++) { switch (s[i]) { case 'a': case 'i': case 'u': case 'e': case 'o': case 'A': case 'I': case 'U': case 'E': case 'O': v.push_back(i); } } for (int i = 0; i < (int)(v.size() / 2); i++) { swap(s[v[i]], s[v[v.size() - 1 - i]]); } return s; } };
19.15625
53
0.298532
Doarakko
682fce5ba95dadeb2a1ba215388d6142c832646d
583
hpp
C++
Include/SA/Input/Base/Axis/Bindings/InputAxisRange.hpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
1
2022-01-20T23:17:18.000Z
2022-01-20T23:17:18.000Z
Include/SA/Input/Base/Axis/Bindings/InputAxisRange.hpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
null
null
null
Include/SA/Input/Base/Axis/Bindings/InputAxisRange.hpp
SapphireSuite/Engine
f29821853aec6118508f31d3e063e83e603f52dd
[ "MIT" ]
null
null
null
// Copyright (c) 2021 Sapphire's Suite. All Rights Reserved. #pragma once #ifndef SAPPHIRE_INPUT_INPUT_AXIS_RANGE_GUARD #define SAPPHIRE_INPUT_INPUT_AXIS_RANGE_GUARD #include <SA/Input/Base/Bindings/InputRangeBase.hpp> #include <SA/Input/Base/Axis/Bindings/InputAxisBinding.hpp> namespace Sa { class InputAxisRange : public InputRangeBase<InputAxisBinding> { public: float minThreshold = 0.0f; float maxThreshold = 1.0f; float scale = 1.0f; using InputRangeBase<InputAxisBinding>::InputRangeBase; bool Execute(float _value) override final; }; } #endif // GUARD
20.821429
63
0.7753
SapphireSuite
6830046466209c71aafc249d502ff69efbc46f64
373
cpp
C++
Math/168. Excel Sheet Column Title.cpp
YuPeize/LeetCode-
b01d00f28e1eedcb04aee9eca984685bd9d52791
[ "MIT" ]
2
2019-10-28T06:40:09.000Z
2022-03-09T10:50:06.000Z
Math/168. Excel Sheet Column Title.cpp
sumiya-NJU/LeetCode
8e6065e160da3db423a51aaf3ae53b2023068d05
[ "MIT" ]
null
null
null
Math/168. Excel Sheet Column Title.cpp
sumiya-NJU/LeetCode
8e6065e160da3db423a51aaf3ae53b2023068d05
[ "MIT" ]
1
2018-12-09T13:46:06.000Z
2018-12-09T13:46:06.000Z
/* author: ypz */ class Solution { public: string convertToTitle(int n) { string ans; while(n != 0) { char temp; if(n%26 == 0) { temp = 'Z'; n -= 1; } else temp = 'A' + n%26 - 1; ans = temp + ans; n = n / 26; } return ans; } };
16.954545
39
0.335121
YuPeize
6834eaa61ab72647f1f8a23f2265d6a14a8ae59a
2,459
cpp
C++
luogu/p1042.cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
luogu/p1042.cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
luogu/p1042.cpp
ajidow/Answers_of_OJ
70e0c02d9367c3a154b83a277edbf158f32484a3
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> using namespace std; char c; // int hua,sb; // int huawin,sbwin; int tmphua,tmpsb; int cnt = 0; int get[100000]; int main(int argc, char const *argv[]) { // cout << "11:0" << endl; while(1) { c = getchar(); if (c == 'E') { cout << tmphua << ":" << tmpsb << endl; break; }else if (c == 'W'){ // hua++; tmphua++; cnt++; get[cnt] = 1; }else{ // sb++; tmpsb++; cnt++; get[cnt] = -1; } if (tmphua >= 11 && tmphua - tmpsb >= 2) { cout << tmphua << ":" << tmpsb << endl; tmphua = 0; tmpsb = 0; }else if (tmpsb >= 11 && tmpsb - tmphua >= 2) { cout << tmphua << ":" << tmpsb << endl; tmphua = 0; tmpsb = 0; } } cout << endl; tmphua = 0; tmpsb = 0; // cout << "21:0" << endl; for (int i = 1;i <= cnt; ++i) { if (get[i] == 1){ tmphua++; }else{ tmpsb++; } if (tmphua >= 21 && tmphua - tmpsb >= 2) { cout << tmphua << ":" << tmpsb << endl; tmpsb = 0; tmphua = 0; }else if (tmpsb >= 21 && tmpsb - tmphua >= 2) { cout << tmphua << ":" << tmpsb << endl; tmpsb = 0; tmphua = 0; } } cout << tmphua << ":" << tmpsb; return 0; } // #include<iostream> // using namespace std; // char ch; // bool g[1000000];//记录比分,true表示华华胜,false表示输; // int a,tmpsb,cnt;//a,tmpsb存储比分; // int main() // { // while(1) // { // ch=getchar();//一个字符一个字符读入; // if(ch=='E') // { // cout<<a<<":"<<tmpsb<<endl;//输出当前比分; // break; // } // if(ch=='W') // { // a++;cnt++;g[cnt]=true;//存到数组中,以便算21分制时再模拟一次; // } // if(ch=='L') // { // tmpsb++;cnt++; // } // if(a>=11&&a-tmpsb>=2) // { // cout<<a<<":"<<tmpsb<<endl; // a=0;tmpsb=0; // } // if(tmpsb>=11&&tmpsb-a>=2) // { // cout<<a<<":"<<tmpsb<<endl; // a=0;tmpsb=0; // } // } // a=0;tmpsb=0;cout<<endl;//归零; // for(int i=1;i<=cnt;i++)//过程与之前类似; // { // if(g[i]) a++; // else tmpsb++; // if(a>=21&&a-tmpsb>=2) // { // cout<<a<<":"<<tmpsb<<endl; // a=0;tmpsb=0; // } // if(tmpsb>=21&&tmpsb-a>=2) // { // cout<<a<<":"<<tmpsb<<endl; // a=0;tmpsb=0; // } // } // cout<<a<<":"<<tmpsb<<endl;//输出最后一局比分; // return 0; // }
19.362205
60
0.395283
ajidow
6835e1f3603467bf8ff17f87fc84f97f267c2969
1,997
cpp
C++
SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramWidget.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
1
2022-03-29T18:51:49.000Z
2022-03-29T18:51:49.000Z
SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramWidget.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
SerialPrograms/Source/NintendoSwitch/Framework/NintendoSwitch_SingleSwitchProgramWidget.cpp
Gin890/Arduino-Source
9047ff584010d8ddc3558068874f16fb3c7bb46d
[ "MIT" ]
null
null
null
/* Single Switch Program Template * * From: https://github.com/PokemonAutomation/Arduino-Source * */ #include "CommonFramework/Tools/BlackBorderCheck.h" #include "NintendoSwitch_SingleSwitchProgramWidget.h" #include <iostream> using std::cout; using std::endl; namespace PokemonAutomation{ namespace NintendoSwitch{ SingleSwitchProgramWidget::~SingleSwitchProgramWidget(){ RunnableSwitchProgramWidget::request_program_stop(); join_program_thread(); } SingleSwitchProgramWidget* SingleSwitchProgramWidget::make( QWidget& parent, SingleSwitchProgramInstance& instance, PanelHolder& holder ){ SingleSwitchProgramWidget* widget = new SingleSwitchProgramWidget(parent, instance, holder); widget->construct(); return widget; } void SingleSwitchProgramWidget::run_switch_program(const ProgramInfo& info){ SingleSwitchProgramInstance& instance = static_cast<SingleSwitchProgramInstance&>(m_instance); CancellableHolder<CancellableScope> scope; SingleSwitchProgramEnvironment env( info, scope, m_logger, m_current_stats.get(), m_historical_stats.get(), system().logger(), sanitize_botbase(system().botbase()), system().camera(), system().overlay(), system().audio() ); connect( &env, &ProgramEnvironment::set_status, this, &SingleSwitchProgramWidget::status_update ); { std::lock_guard<std::mutex> lg(m_lock); m_scope = &scope; } try{ start_program_video_check(env.console, instance.descriptor().feedback()); BotBaseContext context(scope, env.console.botbase()); instance.program(env, context); std::lock_guard<std::mutex> lg(m_lock); m_scope = nullptr; }catch (...){ env.update_stats(); std::lock_guard<std::mutex> lg(m_lock); m_scope = nullptr; throw; } } } }
26.626667
99
0.657987
Gin890
68383cad3387296c9c36cca5935b428b4f51c87f
9,038
cpp
C++
Grbl_Esp32/src/Spindles/YL620Spindle.cpp
ghjklzx/ESP32-E-support
03e081d3f6df613ff1f215ba311bec3fb7baa8ed
[ "MIT" ]
49
2021-12-15T12:57:20.000Z
2022-02-07T12:22:10.000Z
Firmware/Grbl_Esp32-main/Grbl_Esp32/src/Spindles/YL620Spindle.cpp
pspadale/Onyx-Stepper-Motherboard
e94e6cc2e40869f6ee395a3f6e52c81307373971
[ "MIT" ]
null
null
null
Firmware/Grbl_Esp32-main/Grbl_Esp32/src/Spindles/YL620Spindle.cpp
pspadale/Onyx-Stepper-Motherboard
e94e6cc2e40869f6ee395a3f6e52c81307373971
[ "MIT" ]
10
2021-12-15T12:57:24.000Z
2022-01-17T22:47:33.000Z
#include "YL620Spindle.h" /* YL620Spindle.cpp This is for a Yalang YL620/YL620-A VFD based spindle to be controlled via RS485 Modbus RTU. Part of Grbl_ESP32 2021 - Marco Wagner Grbl is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Grbl is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with Grbl. If not, see <http://www.gnu.org/licenses/>. WARNING!!!! VFDs are very dangerous. They have high voltages and are very powerful Remove power before changing bits. ============================================================================================================= Configuration required for the YL620 Parameter number Description Value ------------------------------------------------------------------------------- P00.00 Main frequency 400.00Hz (match to your spindle) P00.01 Command source 3 P03.00 RS485 Baud rate 3 (9600) P03.01 RS485 address 1 P03.02 RS485 protocol 2 P03.08 Frequency given lower limit 100.0Hz (match to your spindle cooling-type) =============================================================================================================== RS485 communication is standard Modbus RTU Therefore, the following operation codes are relevant: 0x03: read single holding register 0x06: write single holding register Holding register address Description --------------------------------------------------------------------------- 0x0000 main frequency 0x0308 frequency given lower limit 0x2000 command register (further information below) 0x2001 Modbus485 frequency command (x0.1Hz => 2500 = 250.0Hz) 0x200A Target frequency 0x200B Output frequency 0x200C Output current Command register at holding address 0x2000 -------------------------------------------------------------------------- bit 1:0 b00: No function b01: shutdown command b10: start command b11: Jog command bit 3:2 reserved bit 5:4 b00: No function b01: Forward command b10: Reverse command b11: change direction bit 7:6 b00: No function b01: reset an error flag b10: reset all error flags b11: reserved */ namespace Spindles { YL620::YL620() : VFD() {} void YL620::direction_command(SpindleState mode, ModbusCommand& data) { // NOTE: data length is excluding the CRC16 checksum. data.tx_length = 6; data.rx_length = 6; // data.msg[0] is omitted (modbus address is filled in later) data.msg[1] = 0x06; // 06: write output register data.msg[2] = 0x20; // 0x2000: command register address data.msg[3] = 0x00; data.msg[4] = 0x00; // High-Byte of command always 0x00 switch (mode) { case SpindleState::Cw: data.msg[5] = 0x12; // Start in forward direction break; case SpindleState::Ccw: data.msg[5] = 0x22; // Start in reverse direction break; default: // SpindleState::Disable data.msg[5] = 0x01; // Disable spindle break; } } void YL620::set_speed_command(uint32_t rpm, ModbusCommand& data) { // NOTE: data length is excluding the CRC16 checksum. data.tx_length = 6; data.rx_length = 6; // We have to know the max RPM before we can set the current RPM: auto max_rpm = this->_max_rpm; auto max_frequency = this->_maxFrequency; uint16_t freqFromRPM = (uint16_t(rpm) * uint16_t(max_frequency)) / uint16_t(max_rpm); #ifdef VFD_DEBUG_MODE grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "For %d RPM the output frequency is set to %d Hz*10", int(rpm), int(freqFromRPM)); #endif data.msg[1] = 0x06; data.msg[2] = 0x20; data.msg[3] = 0x01; data.msg[4] = uint8_t(freqFromRPM >> 8); data.msg[5] = uint8_t(freqFromRPM & 0xFF); } VFD::response_parser YL620::initialization_sequence(int index, ModbusCommand& data) { if (index == -1) { // NOTE: data length is excluding the CRC16 checksum. data.tx_length = 6; data.rx_length = 5; data.msg[1] = 0x03; data.msg[2] = 0x03; data.msg[3] = 0x08; data.msg[4] = 0x00; data.msg[5] = 0x01; // Recv: 01 03 02 03 E8 xx xx // -- -- = 1000 return [](const uint8_t* response, Spindles::VFD* vfd) -> bool { auto yl620 = static_cast<YL620*>(vfd); yl620->_minFrequency = (uint16_t(response[3]) << 8) | uint16_t(response[4]); #ifdef VFD_DEBUG_MODE grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "YL620 allows minimum frequency of %d Hz", int(yl620->_minFrequency)); #endif return true; }; } else if (index == -2) { // NOTE: data length is excluding the CRC16 checksum. data.tx_length = 6; data.rx_length = 5; data.msg[1] = 0x03; data.msg[2] = 0x00; data.msg[3] = 0x00; data.msg[4] = 0x00; data.msg[5] = 0x01; // Recv: 01 03 02 0F A0 xx xx // -- -- = 4000 return [](const uint8_t* response, Spindles::VFD* vfd) -> bool { auto yl620 = static_cast<YL620*>(vfd); yl620->_maxFrequency = (uint16_t(response[3]) << 8) | uint16_t(response[4]); vfd->_min_rpm = uint32_t(yl620->_minFrequency) * uint32_t(vfd->_max_rpm) / uint32_t(yl620->_maxFrequency); // 1000 * 24000 / 4000 = 6000 RPM. #ifdef VFD_DEBUG_MODE grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "YL620 allows maximum frequency of %d Hz", int(yl620->_maxFrequency)); grbl_msg_sendf(CLIENT_SERIAL, MsgLevel::Info, "Configured maxRPM of %d RPM results in minRPM of %d RPM", int(vfd->_max_rpm), int(vfd->_min_rpm)); #endif return true; }; } else { return nullptr; } } VFD::response_parser YL620::get_current_rpm(ModbusCommand& data) { // NOTE: data length is excluding the CRC16 checksum. data.tx_length = 6; data.rx_length = 5; // Send: 01 03 200B 0001 data.msg[1] = 0x03; data.msg[2] = 0x20; data.msg[3] = 0x0B; data.msg[4] = 0x00; data.msg[5] = 0x01; // Recv: 01 03 02 05 DC xx xx // ---- = 1500 return [](const uint8_t* response, Spindles::VFD* vfd) -> bool { uint16_t freq = (uint16_t(response[3]) << 8) | uint16_t(response[4]); auto yl620 = static_cast<YL620*>(vfd); uint16_t rpm = freq * uint16_t(vfd->_max_rpm) / uint16_t(yl620->_maxFrequency); // Set current RPM value? Somewhere? vfd->_sync_rpm = rpm; return true; }; } VFD::response_parser YL620::get_current_direction(ModbusCommand& data) { // NOTE: data length is excluding the CRC16 checksum. data.tx_length = 6; data.rx_length = 5; // Send: 01 03 20 00 00 01 data.msg[1] = 0x03; data.msg[2] = 0x20; data.msg[3] = 0x00; data.msg[4] = 0x00; data.msg[5] = 0x01; // Receive: 01 03 02 00 0A xx xx // ----- status is in 00 0A bit 5:4 // TODO: What are we going to do with this? Update sys.spindle_speed? Update vfd state? return [](const uint8_t* response, Spindles::VFD* vfd) -> bool { return true; }; } }
38.7897
136
0.501881
ghjklzx
683ba4119670f9dbd36d441fbe7e90e150be3690
5,495
cpp
C++
crystal/foundation/http/Crypto.cpp
crystal-dataop/crystal
128e1dcde1ef68cabadab9b16d45f5199f0afe5c
[ "Apache-2.0" ]
2
2020-10-02T03:31:50.000Z
2020-12-31T09:41:48.000Z
crystal/foundation/http/Crypto.cpp
crystal-dataop/crystal
128e1dcde1ef68cabadab9b16d45f5199f0afe5c
[ "Apache-2.0" ]
null
null
null
crystal/foundation/http/Crypto.cpp
crystal-dataop/crystal
128e1dcde1ef68cabadab9b16d45f5199f0afe5c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2020 Yeolar */ #include "crystal/foundation/http/Crypto.h" #include <iomanip> #include <vector> #include <openssl/evp.h> #include <openssl/md5.h> #include <openssl/sha.h> namespace crystal { std::string Crypto::to_hex_string(const std::string& input) { std::stringstream hex_stream; hex_stream << std::hex << std::internal << std::setfill('0'); for (auto& byte : input) { hex_stream << std::setw(2) << static_cast<int>(static_cast<unsigned char>(byte)); } return hex_stream.str(); } std::string Crypto::md5(const std::string& input, size_t iterations) { std::string hash; hash.resize(128 / 8); MD5(reinterpret_cast<const unsigned char*>(&input[0]), input.size(), reinterpret_cast<unsigned char*>(&hash[0])); for (size_t c = 1; c < iterations; ++c) { MD5(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(), reinterpret_cast<unsigned char*>(&hash[0])); } return hash; } std::string Crypto::md5(std::istream& stream, size_t iterations) { MD5_CTX context; MD5_Init(&context); std::streamsize read_length; std::vector<char> buffer(buffer_size); while ((read_length = stream.read(&buffer[0], buffer_size).gcount()) > 0) { MD5_Update(&context, buffer.data(), static_cast<size_t>(read_length)); } std::string hash; hash.resize(128 / 8); MD5_Final(reinterpret_cast<unsigned char*>(&hash[0]), &context); for (size_t c = 1; c < iterations; ++c) { MD5(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(), reinterpret_cast<unsigned char*>(&hash[0])); } return hash; } std::string Crypto::sha1(const std::string& input, size_t iterations) { std::string hash; hash.resize(160 / 8); SHA1(reinterpret_cast<const unsigned char*>(&input[0]), input.size(), reinterpret_cast<unsigned char*>(&hash[0])); for (size_t c = 1; c < iterations; ++c) { SHA1(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(), reinterpret_cast<unsigned char*>(&hash[0])); } return hash; } std::string Crypto::sha1(std::istream& stream, size_t iterations) { SHA_CTX context; SHA1_Init(&context); std::streamsize read_length; std::vector<char> buffer(buffer_size); while ((read_length = stream.read(&buffer[0], buffer_size).gcount()) > 0) { SHA1_Update(&context, buffer.data(), static_cast<size_t>(read_length)); } std::string hash; hash.resize(160 / 8); SHA1_Final(reinterpret_cast<unsigned char*>(&hash[0]), &context); for (size_t c = 1; c < iterations; ++c) { SHA1(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(), reinterpret_cast<unsigned char*>(&hash[0])); } return hash; } std::string Crypto::sha256(const std::string& input, size_t iterations) { std::string hash; hash.resize(256 / 8); SHA256(reinterpret_cast<const unsigned char*>(&input[0]), input.size(), reinterpret_cast<unsigned char*>(&hash[0])); for (size_t c = 1; c < iterations; ++c) { SHA256(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(), reinterpret_cast<unsigned char*>(&hash[0])); } return hash; } std::string Crypto::sha256(std::istream& stream, size_t iterations) { SHA256_CTX context; SHA256_Init(&context); std::streamsize read_length; std::vector<char> buffer(buffer_size); while ((read_length = stream.read(&buffer[0], buffer_size).gcount()) > 0) { SHA256_Update(&context, buffer.data(), static_cast<size_t>(read_length)); } std::string hash; hash.resize(256 / 8); SHA256_Final(reinterpret_cast<unsigned char*>(&hash[0]), &context); for (size_t c = 1; c < iterations; ++c) { SHA256(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(), reinterpret_cast<unsigned char*>(&hash[0])); } return hash; } std::string Crypto::sha512(const std::string& input, size_t iterations) { std::string hash; hash.resize(512 / 8); SHA512(reinterpret_cast<const unsigned char*>(&input[0]), input.size(), reinterpret_cast<unsigned char*>(&hash[0])); for (size_t c = 1; c < iterations; ++c) { SHA512(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(), reinterpret_cast<unsigned char*>(&hash[0])); } return hash; } std::string Crypto::sha512(std::istream& stream, size_t iterations) { SHA512_CTX context; SHA512_Init(&context); std::streamsize read_length; std::vector<char> buffer(buffer_size); while ((read_length = stream.read(&buffer[0], buffer_size).gcount()) > 0) { SHA512_Update(&context, buffer.data(), static_cast<size_t>(read_length)); } std::string hash; hash.resize(512 / 8); SHA512_Final(reinterpret_cast<unsigned char*>(&hash[0]), &context); for (size_t c = 1; c < iterations; ++c) { SHA512(reinterpret_cast<const unsigned char*>(&hash[0]), hash.size(), reinterpret_cast<unsigned char*>(&hash[0])); } return hash; } std::string Crypto::pbkdf2(const std::string& password, const std::string& salt, int iterations, int key_size) { std::string key; key.resize(static_cast<size_t>(key_size)); PKCS5_PBKDF2_HMAC_SHA1(password.c_str(), password.size(), reinterpret_cast<const unsigned char*>(salt.c_str()), salt.size(), iterations, key_size, reinterpret_cast<unsigned char*>(&key[0])); return key; } } // namespace crystal
33.919753
78
0.647134
crystal-dataop
683f82e4ea5d0c5966b1ad32dd95cfea784541a8
25,099
cpp
C++
octomap/src/testing/test_set_tree_values.cpp
BadgerTechnologies/octomap
cf470ad72aaf7783b6eeef82331f52146557fc09
[ "BSD-3-Clause" ]
null
null
null
octomap/src/testing/test_set_tree_values.cpp
BadgerTechnologies/octomap
cf470ad72aaf7783b6eeef82331f52146557fc09
[ "BSD-3-Clause" ]
null
null
null
octomap/src/testing/test_set_tree_values.cpp
BadgerTechnologies/octomap
cf470ad72aaf7783b6eeef82331f52146557fc09
[ "BSD-3-Clause" ]
null
null
null
#include <memory> #include <octomap/octomap.h> #include "testing.h" using namespace std; using namespace octomap; using namespace octomath; int main(int /*argc*/, char** /*argv*/) { double res = 0.01; OcTree value_tree(res); OcTree value_tree2(res); OcTree bounds_tree(res); OcTree tree(res); OcTree expected_tree(res); OcTree* null_tree = nullptr; shared_ptr<OcTree> treep; OcTreeNode* node; const key_type center_key = tree.coordToKey(0.0); std::cout << "\nSetting Tree Values from Other Trees\n===============================\n"; // First, test using empty trees tree.setTreeValues(null_tree, false, false); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(null_tree, true, false); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(null_tree, true, true); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, true); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, true, true); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree, true); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree, true, true); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); // Add a node to the value tree but use an empty bounds tree value_tree.setNodeValue(OcTreeKey(), 1.0); tree.setTreeValues(&value_tree, &bounds_tree); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree, true); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree, true, true); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); // Test the case of an empty tree being set to the universe (pruned node at top). tree.clear(); value_tree.clear(); value_tree.setNodeValueAtDepth(OcTreeKey(), 0, value_tree.getClampingThresMaxLog()); EXPECT_EQ(tree.size(), 0); tree.setTreeValues(&value_tree); EXPECT_EQ(tree.size(), 1); tree.clear(); value_tree.clear(); // Now, test with one leaf in our tree point3d singlePt(-0.05, -0.02, 1.0); OcTreeKey singleKey, nextKey; tree.coordToKeyChecked(singlePt, singleKey); tree.updateNode(singleKey, true); tree.setTreeValues(&value_tree); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, true); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, false, true); EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.updateNode(singleKey, true); // Since the bounds tree is empty, no change should happen tree.setTreeValues(&value_tree, &bounds_tree, true, true); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); bounds_tree.updateNode(singleKey, true); tree.setTreeValues(&value_tree, &bounds_tree, false, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree, true, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree, false, true); // Bounds tree has our key, our tree should be empty now EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); // Set the bounds tree to everything. bounds_tree.setNodeValueAtDepth(OcTreeKey(), 0, bounds_tree.getClampingThresMax()); EXPECT_EQ(bounds_tree.size(), 1); tree.clear(); tree.updateNode(singleKey, true); tree.setTreeValues(&value_tree, &bounds_tree, false, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree, true, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); tree.setTreeValues(&value_tree, &bounds_tree, false, true); // Bounds tree has our key, our tree should be empty now EXPECT_EQ(tree.size(), 0); EXPECT_EQ(tree.size(), tree.calcNumNodes()); // Now put a single node in the value tree value_tree.setNodeValue(singleKey, -1.0); tree.setNodeValue(singleKey, 1.0); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(1.0, node->getLogOdds()); tree.setTreeValues(&value_tree, true, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(1.0, node->getLogOdds()); tree.setTreeValues(&value_tree, false, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(-1.0, node->getLogOdds()); tree.setNodeValue(singleKey, 1.0); tree.setTreeValues(&value_tree, false, true); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(-1.0, node->getLogOdds()); // Now try the same node in the bounds tree. bounds_tree.clear(); bounds_tree.setNodeValue(singleKey, 1.0); tree.setNodeValue(singleKey, 1.0); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(1.0, node->getLogOdds()); tree.setTreeValues(&value_tree, &bounds_tree, true, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(1.0, node->getLogOdds()); tree.setTreeValues(&value_tree, &bounds_tree, false, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(-1.0, node->getLogOdds()); tree.setNodeValue(singleKey, 1.0); tree.setTreeValues(&value_tree, &bounds_tree, false, true); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(-1.0, node->getLogOdds()); // Set the bounds tree to everything. bounds_tree.setNodeValueAtDepth(OcTreeKey(), 0, bounds_tree.getClampingThresMax()); EXPECT_EQ(bounds_tree.size(), 1); tree.setNodeValue(singleKey, 1.0); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(1.0, node->getLogOdds()); tree.setTreeValues(&value_tree, &bounds_tree, true, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(1.0, node->getLogOdds()); tree.setTreeValues(&value_tree, &bounds_tree, false, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(-1.0, node->getLogOdds()); tree.setNodeValue(singleKey, 1.0); tree.setTreeValues(&value_tree, &bounds_tree, false, true); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); EXPECT_EQ(tree.size(), tree.calcNumNodes()); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(-1.0, node->getLogOdds()); // Test having a pruned inner node for a value tree when using maximum. tree.setNodeValue(singleKey, 1.0); value_tree.setNodeValueAtDepth(singleKey, value_tree.getTreeDepth() - 1, -1.0); EXPECT_EQ(value_tree.size(), value_tree.getTreeDepth()); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); tree.setTreeValues(&value_tree, &bounds_tree, true, false); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 8); node = tree.search(singleKey); EXPECT_TRUE(node); EXPECT_EQ(1.0, node->getLogOdds()); nextKey = singleKey; nextKey[1] += 1; node = tree.search(nextKey); EXPECT_TRUE(node); EXPECT_EQ(-1.0, node->getLogOdds()); // Test having a pruned inner node in our tree, a sub-node in the value // tree while using delete first. tree.clear(); value_tree.clear(); bounds_tree.clear(); tree.setNodeValueAtDepth(singleKey, tree.getTreeDepth() - 1, 1.0); value_tree.setNodeValueAtDepth(singleKey, value_tree.getTreeDepth(), 1.0); bounds_tree.setNodeValueAtDepth(singleKey, bounds_tree.getTreeDepth() - 1, 1.0); EXPECT_EQ(tree.size(), tree.getTreeDepth()); EXPECT_EQ(value_tree.size(), value_tree.getTreeDepth() + 1); EXPECT_EQ(bounds_tree.size(), bounds_tree.getTreeDepth()); tree.setTreeValues(&value_tree, &bounds_tree, false, true); EXPECT_EQ(tree.size(), tree.getTreeDepth() + 1); // Test no value tree with a non-overlapping bounds tree with delete first set. tree.clear(); bounds_tree.clear(); nextKey[1] += 2; tree.setNodeValue(singleKey, 1.0); bounds_tree.setNodeValue(nextKey, 1.0); EXPECT_EQ(tree.getTreeDepth() + 1, tree.size()); EXPECT_EQ(bounds_tree.getTreeDepth() + 1, bounds_tree.size()); treep.reset(new OcTree(tree)); treep->setTreeValues(null_tree, &bounds_tree, false, true); EXPECT_EQ(tree.getTreeDepth() + 1, tree.size()); EXPECT_TRUE(tree == *treep); // Test delete first with an empty value tree, a complex bounds tree and // value tree with the value tree completely inside (result should be // empty). tree.clear(); bounds_tree.clear(); for(int i=-10; i<=10; ++i) { for(int j=-10; j<=10; ++j) { for(int k=-10; k<=10; ++k) { OcTreeKey key(center_key+i, center_key+j, center_key+k); bounds_tree.setNodeValue(key, 1.0); } } } for(int i=-7; i<=9; ++i) { for(int j=-5; j<=3; ++j) { for(int k=-2; k<=8; ++k) { OcTreeKey key(center_key+i, center_key+j, center_key+k); tree.setNodeValue(key, 1.0); } } } tree.setTreeValues(null_tree, &bounds_tree, false, true); EXPECT_EQ(0, tree.size()); // Now, make more complex merging scenarios. tree.clear(); value_tree.clear(); bounds_tree.setNodeValueAtDepth(OcTreeKey(), 0, bounds_tree.getClampingThresMax()); for(int i=0; i<4; ++i) { for(int j=0; j<4; ++j) { for(int k=0; k<4; ++k) { float value1 = -1.0; float value2 = 1.0; if (i >= 1 && i <= 2 && j >= 1 && j <= 2 && k >= 1 && k <= 2) { value1 = 1.0; value2 = -1.0; } OcTreeKey key(center_key+i, center_key+j, center_key+k); tree.setNodeValue(key, value1); value_tree.setNodeValue(key, value2); } } } OcTreeKey search_key(center_key+2, center_key+2, center_key+2); EXPECT_EQ(4*4*4 + 4*4*4/8 + tree.getTreeDepth() - 1, tree.size()); EXPECT_EQ(4*4*4 + 4*4*4/8 + value_tree.getTreeDepth() - 1, value_tree.size()); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &bounds_tree, true, false); EXPECT_EQ(tree.getTreeDepth() - 1, treep->size()); EXPECT_EQ(treep->size(), treep->calcNumNodes()); node = treep->search(search_key); EXPECT_EQ(1.0, node->getLogOdds()); expected_tree.clear(); expected_tree.setNodeValueAtDepth(OcTreeKey(center_key+2, center_key+2, center_key+2), tree.getTreeDepth() - 2, 1.0); EXPECT_TRUE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &bounds_tree, false, false); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(value_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &bounds_tree, false, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(value_tree == *treep); // Now try with bounds limited. expected_tree.clear(); treep.reset(new OcTree(tree)); expected_tree.swapContent(*treep); expected_tree.setNodeValueAtDepth(OcTreeKey(center_key+1, center_key+1, center_key+1), tree.getTreeDepth() - 1, 1.0); bounds_tree.clear(); bounds_tree.setNodeValueAtDepth(OcTreeKey(center_key+1, center_key+1, center_key+1), tree.getTreeDepth() - 1, 1.0); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &bounds_tree, true, false); EXPECT_EQ(4*4*4 - 8 + 4*4*4/8 + tree.getTreeDepth() - 1, treep->size()); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(expected_tree == *treep); expected_tree.setNodeValue(OcTreeKey(center_key+1, center_key+1, center_key+1), -1.0); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &bounds_tree, false, false); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &bounds_tree, false, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(expected_tree == *treep); tree.clear(); value_tree.clear(); value_tree2.clear(); bounds_tree.clear(); for(int i=-4; i<4; ++i) { for(int j=-4; j<4; ++j) { for(int k=-4; k<4; ++k) { float value1 = -200.0; float value2 = -200.0; float value3 = -200.0; if (i >= -4 && i <= -3 && j >= -4 && j <= -3 && k >= -4 && k <= -3) { value1 = -1.0; } else if( i >= -4 && i < 0 && j >= -4 && j < 0 && k >= -4 && k < 0) { value1 = 1.0; } else if(i == 0 && j == 0 && k == 0) { value1 = 1.0; } else if(i == 2 && j == 2 && k == 2) { value1 = 1.0; } else if (i >= 2 && i <= 3 && j >= 2 && j <= 3 && k >= 2 && k <= 3) { value1 = -1.0; } if( i >= -4 && i < 0 && j >= -4 && j < 0 && k >= -4 && k < 0) { value2 = 1.0; } else if( i >= 1 && i < 4 && j >= 1 && j < 4 && k >= 1 && k < 4) { value2 = -1.0; } if(i == -2 && j == -2 && k == -2) { value3 = -1.0; } else if(i == 0 && j == 0 && k == 0) { value3 = -1.0; } else if(i == 1 && j == 1 && k == 1) { value3 = 1.0; } else if (i >= 2 && i <= 3 && j >= 2 && j <= 3 && k >= 2 && k <= 3) { value3 = 1.0; } OcTreeKey key(center_key+i, center_key+j, center_key+k); if (value1 > -100.0) { tree.setNodeValue(key, value1); } if (value2 > -100.0) { value_tree.setNodeValue(key, value2); } if (value3 > -100.0) { value_tree2.setNodeValue(key, value3); } } } } bounds_tree.setNodeValueAtDepth(OcTreeKey(center_key-2, center_key-2, center_key-2), bounds_tree.getTreeDepth() - 2, 1.0); bounds_tree.setNodeValueAtDepth(OcTreeKey(center_key+3, center_key+3, center_key+3), bounds_tree.getTreeDepth() - 1, 1.0); treep.reset(new OcTree(tree)); EXPECT_EQ((1 + 8) + 7 + 2 * tree.getTreeDepth(), treep->size()); EXPECT_EQ(4*3+2*3+1 + 5 + 2 * tree.getTreeDepth(), value_tree.size()); EXPECT_EQ(2 + 1 + 2 * tree.getTreeDepth(), value_tree2.size()); treep->setTreeValues(&value_tree, &bounds_tree, true, false); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, &bounds_tree, true, false); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_EQ(2 * tree.getTreeDepth(), treep->size()); expected_tree.clear(); expected_tree.setNodeValueAtDepth(OcTreeKey(center_key-2, center_key-2, center_key-2), expected_tree.getTreeDepth() - 2, 1.0); expected_tree.setNodeValue(OcTreeKey(center_key, center_key, center_key), 1.0); expected_tree.setNodeValueAtDepth(OcTreeKey(center_key+3, center_key+3, center_key+3), expected_tree.getTreeDepth() - 1, 1.0); EXPECT_TRUE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, true, false); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, true, false); EXPECT_EQ(treep->size(), treep->calcNumNodes()); for(int i=1; i<4; ++i) { for(int j=1; j<4; ++j) { for(int k=1; k<4; ++k) { float v=-200.0; if (i==1 && j==1 && k==1) { v=1.0; } else if (i==1 || j==1 || k==1) { v=-1.0; } if (v > -100.0) { expected_tree.setNodeValue(OcTreeKey(center_key+i, center_key+j, center_key+k), v); } } } } EXPECT_TRUE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); expected_tree.swapContent(*treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree2, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2); EXPECT_EQ(treep->size(), treep->calcNumNodes()); expected_tree.swapContent(*treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree2); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &bounds_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, &bounds_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); expected_tree.swapContent(*treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree2, &bounds_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree, &bounds_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, &bounds_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &value_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, &value_tree2); EXPECT_EQ(treep->size(), treep->calcNumNodes()); expected_tree.swapContent(*treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree2, &value_tree2); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree, &value_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, &value_tree2); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &value_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, &value_tree2); EXPECT_EQ(treep->size(), treep->calcNumNodes()); expected_tree.swapContent(*treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree2, &value_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree, &value_tree2); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->setTreeValues(&value_tree2, &value_tree); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_FALSE(expected_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, false, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(value_tree == *treep); treep->setTreeValues(&value_tree2, false, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_TRUE(value_tree2 == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree, &bounds_tree, false, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_FALSE(value_tree == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(&value_tree2, &bounds_tree, false, true); EXPECT_EQ(treep->size(), treep->calcNumNodes()); EXPECT_FALSE(value_tree2 == *treep); treep.reset(new OcTree(tree)); treep->setTreeValues(null_tree, &tree, false, true); EXPECT_EQ(treep->size(), 0); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep.reset(new OcTree(tree)); treep->setTreeValues(&tree, false, false, [](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int) {node->setLogOdds(1.0);}); EXPECT_EQ(treep->size(), 2 * treep->getTreeDepth()); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->clear(); float max_log = tree.getClampingThresMaxLog(); // Ugly, but in C++11 you can't capture in a lambda and use it as a function pointer. // Instead, use bind to send the value to set to the lambda treep->setTreeValues(&tree, false, false, std::bind([](OcTree::NodeType* node, float value){node->setLogOdds(value);}, std::placeholders::_2, max_log)); EXPECT_EQ(treep->size(), 2 * treep->getTreeDepth()); EXPECT_EQ(treep->size(), treep->calcNumNodes()); treep->clear(); treep->setTreeValues(&tree, false, false, [](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int) {node->setLogOdds(1.0);}); treep->setTreeValues(&value_tree, false, false, [](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int) {node->setLogOdds(1.0);}); treep->setTreeValues(&value_tree2, false, false, [](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int) {node->setLogOdds(1.0);}); EXPECT_EQ(treep->size(), 25 + 2 * treep->getTreeDepth()); EXPECT_EQ(treep->size(), treep->calcNumNodes()); tree.clear(); value_tree.clear(); value_tree2.clear(); for(int i=0; i<16; ++i) { for(int j=0; j<16; ++j) { for(int k=0; k<16; ++k) { float value1 = -200.0; float value2 = -200.0; float value3 = -200.0; if(i<2 || k>13 ) { value1 = -1.0; } else if(i<5 || j>3) { value2 = .5; } else { value3 = 1.0; } OcTreeKey key(center_key+i, center_key+j, center_key+k); if (value1 > -100.0) { tree.setNodeValue(key, value1); } if (value2 > -100.0) { value_tree.setNodeValue(key, value2); } if (value3 > -100.0) { value_tree2.setNodeValue(key, value3); } } } } treep->clear(); treep->setTreeValues(&tree, false, false, [](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int) {node->setLogOdds(1.0);}); treep->setTreeValues(&value_tree, false, false, [](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int) {node->setLogOdds(1.0);}); treep->setTreeValues(&value_tree2, false, false, [](const OcTree::NodeType*, OcTree::NodeType* node, bool, const OcTreeKey&, unsigned int) {node->setLogOdds(1.0);}); EXPECT_EQ(treep->size(), treep->getTreeDepth() - 3); EXPECT_EQ(treep->size(), treep->calcNumNodes()); std::cerr << "Test successful.\n"; return 0; }
40.287319
130
0.61616
BadgerTechnologies
683f877debdbab79a8362817d237a71245f32022
546
cpp
C++
c++/10611.cpp
AkashChandrakar/UVA
b90535c998ecdffe0f30e56fec89411f456b16a5
[ "Apache-2.0" ]
2
2016-10-23T14:35:13.000Z
2018-09-16T05:38:47.000Z
c++/10611.cpp
AkashChandrakar/UVA
b90535c998ecdffe0f30e56fec89411f456b16a5
[ "Apache-2.0" ]
null
null
null
c++/10611.cpp
AkashChandrakar/UVA
b90535c998ecdffe0f30e56fec89411f456b16a5
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int arr[50001]; int main() { int n, q, x, y, h; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &arr[i]); scanf("%d", &q); for (int i = 0; i < q; i++) { scanf("%d", &h); x = lower_bound(arr, arr + n, h) - arr; if (arr[x] >= h && x > 0) { printf("%d ", arr[x - 1]); } else if(arr[n-1] < h) printf("%d ", arr[n - 1]); else printf("X "); y = upper_bound(arr, arr + n, h) - arr; if (y != n) printf("%d\n", arr[y]); else printf("X\n"); } return 0; }
17.612903
41
0.456044
AkashChandrakar
9697f68859d4396524f960cc99eaf724a97aa2d6
1,588
cc
C++
src/pineapple/app.cc
tomocy/pineapple
bc9c901a521616c4f47d079c6945359eac947ca2
[ "MIT" ]
null
null
null
src/pineapple/app.cc
tomocy/pineapple
bc9c901a521616c4f47d079c6945359eac947ca2
[ "MIT" ]
null
null
null
src/pineapple/app.cc
tomocy/pineapple
bc9c901a521616c4f47d079c6945359eac947ca2
[ "MIT" ]
null
null
null
#include "src/pineapple/app.h" #include <iostream> #include <map> #include <string> #include <vector> #include "external/flags/src/flags/flags.h" #include "src/pineapple/command.h" #include "src/pineapple/context.h" #include "src/pineapple/exceptions.h" namespace pineapple { App::App(const std::string& name) : Command(name) {} App::App(const std::string& name, const std::string& description) : Command(name, description, nullptr) {} App::App(const std::string& name, const action_t& action) : Command(name, action) {} App::App(const std::string& name, const std::string& description, const Command::action_t& action) : Command(name, description, action) {} void App::Run(int n, const char** args) { Run(std::vector<std::string>(args, args + n)); } void App::Run(const std::vector<std::string>& args) { if (args.size() < 1) { throw Exception( "insufficient arguments: one argument is required at least"); } auto trimmed = std::vector<std::string>(std::begin(args) + 1, std::end(args)); try { flags.Parse(trimmed); } catch (const flags::Exception& e) { throw Exception(e.What()); } auto ctx = Context(flags); if (ctx.Args().size() >= 1 && DoHaveCommand(ctx.Args().at(0))) { RunCommand(std::move(ctx)); return; } if (ctx.Args().empty() || action != nullptr) { DoAction(ctx); return; } throw Exception("argument\"" + ctx.Args().at(0) + "\" is not handled at all: action or command named \"" + ctx.Args().at(0) + "\" is needed"); } } // namespace pineapple
26.466667
80
0.630353
tomocy
9698ff51d7f20ca0b8a25b150ddb419aaa7e01c8
2,860
cpp
C++
crogine/src/network/NetPeer.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
41
2017-08-29T12:14:36.000Z
2022-02-04T23:49:48.000Z
crogine/src/network/NetPeer.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
11
2017-09-02T15:32:45.000Z
2021-12-27T13:34:56.000Z
crogine/src/network/NetPeer.cpp
fallahn/crogine
f6cf3ade1f4e5de610d52e562bf43e852344bca0
[ "FTL", "Zlib" ]
5
2020-01-25T17:51:45.000Z
2022-03-01T05:20:30.000Z
/*----------------------------------------------------------------------- Matt Marchant 2017 - 2020 http://trederia.blogspot.com crogine - Zlib license. 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. -----------------------------------------------------------------------*/ #include "../detail/enet/enet/enet.h" #include <crogine/network/NetData.hpp> using namespace cro; std::string NetPeer::getAddress() const { CRO_ASSERT(m_peer, "Not a valid peer"); auto bytes = m_peer->address.host; std::string ret = std::to_string(bytes & 0x000000FF); ret += "." + std::to_string((bytes & 0x0000FF00) >> 8); ret += "." + std::to_string((bytes & 0x00FF0000) >> 16); ret += "." + std::to_string((bytes & 0xFF000000) >> 24); return ret; } std::uint16_t NetPeer::getPort() const { CRO_ASSERT(m_peer, "Not a valid peer"); return m_peer->address.port; } std::uint32_t NetPeer::getID() const { CRO_ASSERT(m_peer, "Not a valid peer"); return m_peer->connectID; } std::uint32_t NetPeer::getRoundTripTime()const { CRO_ASSERT(m_peer, "Not a valid peer"); return m_peer->roundTripTime; } NetPeer::State NetPeer::getState() const { if (!m_peer) { return State::Disconnected; } switch (m_peer->state) { case ENET_PEER_STATE_ACKNOWLEDGING_CONNECT: return State::AcknowledingConnect; case ENET_PEER_STATE_ACKNOWLEDGING_DISCONNECT: return State::AcknowledingDisconnect; case ENET_PEER_STATE_CONNECTED: return State::Connected; case ENET_PEER_STATE_CONNECTING: return State::Connecting; case ENET_PEER_STATE_CONNECTION_PENDING: return State::PendingConnect; case ENET_PEER_STATE_CONNECTION_SUCCEEDED: return State::Succeeded; case ENET_PEER_STATE_DISCONNECTED: return State::Disconnected; case ENET_PEER_STATE_DISCONNECTING: return State::Disconnecting; case ENET_PEER_STATE_DISCONNECT_LATER: return State::DisconnectLater; case ENET_PEER_STATE_ZOMBIE: return State::Zombie; } return State::Zombie; }
28.316832
73
0.683217
fallahn
969e5fbeb80508aa303a4023e918e6af5a213024
955
cpp
C++
Cpp/CpTemplate.cpp
aminPial/Competitive-Programming-Library
c77373bf9f0dd212369a383ec3165d345f2a0cc7
[ "MIT" ]
4
2020-03-21T04:32:09.000Z
2021-07-14T13:49:00.000Z
Cpp/CpTemplate.cpp
aminPial/Competitive-Programming-Library
c77373bf9f0dd212369a383ec3165d345f2a0cc7
[ "MIT" ]
null
null
null
Cpp/CpTemplate.cpp
aminPial/Competitive-Programming-Library
c77373bf9f0dd212369a383ec3165d345f2a0cc7
[ "MIT" ]
1
2020-12-11T06:06:06.000Z
2020-12-11T06:06:06.000Z
#pragma GCC optimize("O3","unroll-loops","omit-frame-pointer","inline","fast-math","no-stack-protector") //Optimization flags #pragma GCC target("sse,sse2,sse3,ssse3,popcnt,abm,mmx,tune=native") // #include <x86intrin.h> //AVX/SSE Extensions /* 만든 사람 <xrssa> */ /* 불타오르네, 불타오르네, 불타오르네 */ #include <bits/stdc++.h> using namespace std; #define f(i,n) for(int i=0;i<n;i++) #define fab(i,a,b) for(int i=a;i<b;i++) #define fa(elem, arr) for(auto &elem:arr) #define gcd(x,y) __gcd(x,y) #define lcm(x,y) (x/gcd(x,y))*y #define mod 1000000007 #define all(a) a.begin(),a.end() #define INF 1e9+5 // # define INF 0x3f3f3f3f #define EPS 1e-6 void solve(){ } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); solve(); // 여러 테스트 사례 사용 // int t;scanf("%d",&t);while(t--) solve(); // int t;scanf("%d",&t);fab(i,1,t+1) printf("Case #%d: %d",i,solve()) ; return 0; }
27.285714
125
0.584293
aminPial
96a0e1fecb2c7f6e7286af9704399ff11e621035
6,614
hpp
C++
Simple++/Graphic/Texture.hpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
Simple++/Graphic/Texture.hpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
Simple++/Graphic/Texture.hpp
Oriode/Simpleplusplus
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
[ "Apache-2.0" ]
null
null
null
namespace Graphic { template<typename T> Texture<T>::Texture( typename Format format ) { this -> datas.push( new ImageT<T>( format ) ); } template<typename T> Graphic::Texture<T>::Texture( const Math::Vec2<Size> & size, typename Format format ) { this -> datas.push( new ImageT<T>( size, format ) ); } template<typename T> Texture<T>::Texture( const Texture<T> & image ) { for ( auto it = image.datas.getBegin(); it != image.datas.getEnd(); it++ ) this -> datas.push( new ImageT<T>( **it ) ); } template<typename T> Texture<T>::Texture( const T * dataBuffer, const Math::Vec2<Size> & size, typename LoadingFormat loadingFormat, bool invertY ) { this -> datas.push( new ImageT<T>( dataBuffer, size, loadingFormat, invertY ) ); } template<typename T> Graphic::Texture<T>::Texture( const ImageT<T> & image ) { this -> datas.push( new ImageT<T>( image ) ); } template<typename T> Texture<T>::Texture( ctor ) { } template<typename T> Texture<T>::Texture( Texture<T> && image ) : datas( Utility::toRValue( image.datas ) ) { image.datas.clear(); //clear the others datas to ensure no double delete } template<typename T> Texture<T>::~Texture() { _unload(); } template<typename T> void Graphic::Texture<T>::setPixel( typename Vector<ImageT<T>>::Size i, unsigned int x, unsigned int y, const T * p ) { this -> datas[i] -> getDatas()[this -> size.x * y + x] = p; } template<typename T> const T * Texture<T>::getPixel( typename Vector<ImageT<T>>::Size i, unsigned int x, unsigned int y ) const { return this -> datas[i] -> getDatas()[this -> size.x * y + x]; } template<typename T> void Texture<T>::generateMipmaps() { if ( this -> datas.getSize() > 1 ) { for ( auto it = this -> datas.getBegin() + 1; it != this -> datas.getEnd(); it++ ) { delete * it; } this -> datas.resize( 1 ); } Vector<ImageT<T>>::Size i = 0; auto newMipmap = this -> datas[i] -> createMipmap(); while ( newMipmap ) { this -> datas.push( newMipmap ); i++; newMipmap = this -> datas[i] -> createMipmap(); } } template<typename T> bool Texture<T>::write( std::fstream * fileStream ) const { Vector<ImageT<T> *>::Size nbMipmaps = this -> datas.getSize(); if ( !IO::write( fileStream, &nbMipmaps ) ) return false; for ( auto it = this -> datas.getBegin(); it != this -> datas.getEnd(); it++ ) { if ( !IO::write( fileStream, *it ) ) return false; } return true; } template<typename T> bool Texture<T>::read( std::fstream * fileStream ) { _unload(); return _read( fileStream ); } template<typename T> void Texture<T>::_unload() { while ( this -> datas.getSize() ) delete this -> datas.pop(); } template<typename T> bool Texture<T>::_read( std::fstream * fileStream ) { Vector<ImageT<T> *>::Size nbDatas; if ( !IO::read( fileStream, &nbDatas ) ) return false; // Clamp the number of datas with a big number just in case of file corruption. nbDatas = Math::min<Vector<ImageT<T> *>::Size>( nbDatas, 100 ); for ( Vector<ImageT<T> * >::Size i = 0; i < nbDatas; i++ ) { ImageT<T> * newImage = new ImageT<T>(); if ( newImage -> read( fileStream ) ) { this -> datas.push( newImage ); } else { delete newImage; _unload(); return false; } } return true; } template<typename T> void Texture<T>::setDatas( const T * data, const Math::Vec2<Size> & size, typename LoadingFormat loadingFormat /*= LoadingFormat::RGB*/, bool invertY /*= false*/ ) { _unload(); this -> datas.push( new ImageT<T>( data, size, loadingFormat, invertY ) ); } template<typename T> void Graphic::Texture<T>::setDatas( const ImageT<T> & image ) { _unload(); this -> datas.push( new ImageT<T>( image ) ); } template<typename T> Texture<T> & Texture<T>::operator=( Texture<T> && image ) { for ( auto it = this -> datas.getBegin(); it != this -> datas.getEnd(); it++ ) delete ( *it ); this -> datas = Utility::toRValue( image.datas ); image.datas.clear(); //clear the others datas to ensure no double delete return *this; } template<typename T> Texture<T> & Texture<T>::operator=( const Texture<T> & image ) { for ( auto it = this -> datas.getBegin(); it != this -> datas.getEnd(); it++ ) delete ( *it ); this -> datas.clear(); for ( auto it = image.datas.getBegin(); it != image.datas.getEnd(); it++ ) this -> datas.push( new Image( **it ) ); return *this; } template<typename T> T * Texture<T>::getDatas( typename Vector<ImageT<T>>::Size i ) { return this -> datas[i] -> getDatas(); } template<typename T> const T * Texture<T>::getDatas( typename Vector<ImageT<T>>::Size i ) const { return this -> datas[i] -> getDatas(); } template<typename T> unsigned int Texture<T>::getHeight( typename Vector<ImageT<T>>::Size i ) const { return this -> datas[i] -> getSize().y; } template<typename T> unsigned int Texture<T>::getWidth( typename Vector<ImageT<T>>::Size i ) const { return this -> datas[i] -> getSize().x; } template<typename T> const Math::Vec2<Size> & Texture<T>::getSize( typename Vector<ImageT<T>>::Size i ) const { return this -> datas[i] -> getSize(); } template<typename T> void Texture<T>::clear( const Math::Vec2<Size> & size ) { Format format = getFormat(); _unload(); this -> datas.push( new Image( size, format ) ); } template<typename T> void Texture<T>::clear( const Math::Vec2<Size> & size, typename Format format ) { _unload(); this -> datas.push( new Image( size, format ) ); } template<typename T> typename Format Texture<T>::getFormat() const { return this -> datas[0] -> getFormat(); } template<typename T> ImageT<T> & Texture<T>::getMipmap( typename Vector<ImageT<T>>::Size i ) { return *this -> datas[i]; } template<typename T> const ImageT<T> & Texture<T>::getMipmap( typename Vector<ImageT<T>>::Size i ) const { return *this -> datas[i]; } template<typename T> ImageT<T> & Graphic::Texture<T>::operator[]( typename Vector<ImageT<T>>::Size i ) { return *this -> datas[i]; } template<typename T> const ImageT<T> & Graphic::Texture<T>::operator[]( typename Vector<ImageT<T>>::Size i ) const { return *this -> datas[i]; } template<typename T> typename Vector<ImageT<T> * >::Size Texture<T>::getNbMipmaps() const { return this -> datas.getSize(); } template<typename T> typename Vector<ImageT<T> * > & Graphic::Texture<T>::getMipmapVector() { return this -> datas; } template<typename T> const typename Vector<ImageT<T> * > & Graphic::Texture<T>::getMipmapVector() const { return this -> datas; } }
25.05303
166
0.63033
Oriode
96aa0c6d5cbc789bf926bffea3256127799d74b4
2,237
cpp
C++
DOS_Boat_Source/EnemySpace.cpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
DOS_Boat_Source/EnemySpace.cpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
DOS_Boat_Source/EnemySpace.cpp
michaelslewis/DOS_Boat
1c25f352d75555fa81bbd0f99c89aaed43739646
[ "MIT" ]
null
null
null
/**************************************************************************** * Author: Michael S. Lewis * * Date: 6/3/2016 * * Description: EnemySpace.cpp is the EnemySpace class function * * implementation file (for Final Project "DOS Boat"). * * An EnemySpace inflicts damage to the SS Damage, and deducts * * a specific number of Strength Points, varying by space. * *****************************************************************************/ #include "EnemySpace.hpp" #include "Babbage.hpp" #include <iostream> #include <cstdlib> #include <string> /**************************************************************************** * EnemySpace::EnemySpace() * * Default constructor for the EnemySpace derived class. * *****************************************************************************/ EnemySpace::EnemySpace() : Ocean() { // Empty function. } /**************************************************************************** * EnemySpace::EnemySpace(string, string, int) * * Overloaded constructor for the EnemySpace derived class. * *****************************************************************************/ EnemySpace::EnemySpace(std::string nameSpace, std::string spaceHeading, std::string spaceType, int damageSpace) : Ocean(nameSpace, spaceHeading, spaceType) { this->damage = damageSpace; } /**************************************************************************** * EnemySpace::playSpace(Babbage*, bool) * * Displays current space, description, inflicts damage, offers a hint, * * displays commands for headings, and prompts for next move. * *****************************************************************************/ void EnemySpace::playSpace(Babbage* babbage, bool displayHint) { std::cout << "You are " << this->name << "." << std::endl; std::cout << this->description << std::endl; babbage->damage(this->damage); if (!babbage->aliveStatus()) { return; } if (displayHint) { babbage->getSpace()->displayHint(); } std::cout << "You can go " << this->headings << "." << std::endl; this->nextSpace(babbage); }
38.568966
78
0.453286
michaelslewis
96ad39b2a5385f3be8906cdd2fd7048b6aeda733
3,703
cpp
C++
lib/regi/sim_metrics_2d/xregImgSimMetric2DGradNCCOCL.cpp
rg2/xreg
c06440d7995f8a441420e311bb7b6524452843d3
[ "MIT" ]
30
2020-09-29T18:36:13.000Z
2022-03-28T09:25:13.000Z
lib/regi/sim_metrics_2d/xregImgSimMetric2DGradNCCOCL.cpp
gaocong13/Orthopedic-Robot-Navigation
bf36f7de116c1c99b86c9ba50f111c3796336af0
[ "MIT" ]
3
2020-10-09T01:21:27.000Z
2020-12-10T15:39:44.000Z
lib/regi/sim_metrics_2d/xregImgSimMetric2DGradNCCOCL.cpp
rg2/xreg
c06440d7995f8a441420e311bb7b6524452843d3
[ "MIT" ]
8
2021-05-25T05:14:48.000Z
2022-02-26T12:29:50.000Z
/* * MIT License * * Copyright (c) 2020 Robert Grupp * * 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 "xregImgSimMetric2DGradNCCOCL.h" xreg::ImgSimMetric2DGradNCCOCL::ImgSimMetric2DGradNCCOCL() : grad_x_sim_(this->ctx_, this->queue_), grad_y_sim_(this->ctx_, this->queue_) { } xreg::ImgSimMetric2DGradNCCOCL::ImgSimMetric2DGradNCCOCL( const boost::compute::device& dev) : ImgSimMetric2DGradImgOCL(dev), grad_x_sim_(this->ctx_, this->queue_), grad_y_sim_(this->ctx_, this->queue_) { } xreg::ImgSimMetric2DGradNCCOCL::ImgSimMetric2DGradNCCOCL( const boost::compute::context& ctx, const boost::compute::command_queue& queue) : ImgSimMetric2DGradImgOCL(ctx, queue), grad_x_sim_(this->ctx_, this->queue_), grad_y_sim_(this->ctx_, this->queue_) { } void xreg::ImgSimMetric2DGradNCCOCL::allocate_resources() { ImgSimMetric2DGradImgOCL::allocate_resources(); // masks are set to grad_x_sim_ and grad_y_sim_ via the parent call to allocate resources, which // will make the initial call to process_updated_mask() and in turn call process_mask() grad_x_sim_.set_num_moving_images(this->num_mov_imgs_); grad_x_sim_.set_fixed_image(this->fixed_img_); // still needs to be set for metadata grad_x_sim_.set_fixed_image_dev(fixed_grad_x_dev_buf_); grad_x_sim_.set_mov_imgs_ocl_buf(mov_grad_x_dev_buf_.get()); grad_x_sim_.set_setup_vienna_cl_ctx(false); grad_x_sim_.set_vienna_cl_ctx_idx(this->vienna_cl_ctx_idx()); grad_x_sim_.allocate_resources(); grad_y_sim_.set_num_moving_images(this->num_mov_imgs_); grad_y_sim_.set_fixed_image(this->fixed_img_); // still needs to be set for metadata grad_y_sim_.set_fixed_image_dev(fixed_grad_y_dev_buf_); grad_y_sim_.set_mov_imgs_ocl_buf(mov_grad_y_dev_buf_.get()); grad_y_sim_.set_setup_vienna_cl_ctx(false); grad_y_sim_.set_vienna_cl_ctx_idx(this->vienna_cl_ctx_idx()); grad_y_sim_.allocate_resources(); this->sim_vals_.assign(this->num_mov_imgs_, 0); } void xreg::ImgSimMetric2DGradNCCOCL::process_mask() { ImgSimMetric2DGradImgOCL::process_mask(); grad_x_sim_.set_mask(this->mask_); grad_y_sim_.set_mask(this->mask_); } void xreg::ImgSimMetric2DGradNCCOCL::compute() { this->pre_compute(); compute_sobel_grads(); // perform the NCC calculations on each direction grad_x_sim_.set_num_moving_images(this->num_mov_imgs_); grad_y_sim_.set_num_moving_images(this->num_mov_imgs_); grad_x_sim_.compute(); grad_y_sim_.compute(); for (size_type mov_idx = 0; mov_idx < this->num_mov_imgs_; ++mov_idx) { this->sim_vals_[mov_idx] = 0.5 * (grad_x_sim_.sim_val(mov_idx) + grad_y_sim_.sim_val(mov_idx)); } }
37.40404
99
0.766946
rg2
96bba7b9ab561f38e4598dc669f60b9304497550
1,609
cpp
C++
Libraries/RobsJuceModules/jura_framework/gui/misc/jura_DescribedComponent.cpp
elanhickler/RS-MET
c04cbe660ea426ddf659dfda3eb9cba890de5468
[ "FTL" ]
null
null
null
Libraries/RobsJuceModules/jura_framework/gui/misc/jura_DescribedComponent.cpp
elanhickler/RS-MET
c04cbe660ea426ddf659dfda3eb9cba890de5468
[ "FTL" ]
null
null
null
Libraries/RobsJuceModules/jura_framework/gui/misc/jura_DescribedComponent.cpp
elanhickler/RS-MET
c04cbe660ea426ddf659dfda3eb9cba890de5468
[ "FTL" ]
1
2017-10-15T07:25:41.000Z
2017-10-15T07:25:41.000Z
// construction/destruction: DescribedItem::DescribedItem(const String& newDescription) { description = newDescription; descriptionField = NULL; } DescribedItem::~DescribedItem() { } // setup: void DescribedItem::setDescription(const String &newDescription) { description = newDescription; if( descriptionField != NULL ) descriptionField->setText(description); } void DescribedItem::setDescriptionField(RTextField *newDescriptionField) { if( descriptionField != NULL ) descriptionField->setText(String()); // clear the old field descriptionField = newDescriptionField; } // inquiry: String DescribedItem::getDescription() const { return description; } RTextField* DescribedItem::getDescriptionField() const { return descriptionField; } //================================================================================================= void DescribedComponent::mouseEnter(const juce::MouseEvent &e) { if( descriptionField != NULL ) descriptionField->setText(description); } void DescribedComponent::mouseExit(const MouseEvent &e) { if( descriptionField != NULL ) descriptionField->setText(String()); } void DescribedComponent::repaintOnMessageThread() { if(MessageManager::getInstance()->isThisTheMessageThread()) repaint(); else { /* * Passing a safe ptr to avoid accidentally calling this while the editor is being * destroyed during an automation move. */ Component::SafePointer<DescribedComponent> ptr = { this }; MessageManager::callAsync([=] {if (ptr) ptr.getComponent()->repaint(); }); } }
22.985714
99
0.675575
elanhickler
96bc18f49667ca4c8c31f5167020e62a49ba064a
939
cpp
C++
Nacro/SDK/FN_ActiveModifierItemHUD_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_ActiveModifierItemHUD_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_ActiveModifierItemHUD_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ActiveModifierItemHUD.ActiveModifierItemHUD_C.AssignIcon // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // struct FSlateBrush inIconSlateBrush (Parm) void UActiveModifierItemHUD_C::AssignIcon(const struct FSlateBrush& inIconSlateBrush) { static auto fn = UObject::FindObject<UFunction>("Function ActiveModifierItemHUD.ActiveModifierItemHUD_C.AssignIcon"); UActiveModifierItemHUD_C_AssignIcon_Params params; params.inIconSlateBrush = inIconSlateBrush; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
23.475
118
0.630458
Milxnor
96beef18081b7735ce5c4d9cf42b4db3184df2e3
553
cpp
C++
atcoder/Educational DP Contest/C.cpp
ApocalypseMac/CP
b2db9aa5392a362dc0d979411788267ed9a5ff1d
[ "MIT" ]
null
null
null
atcoder/Educational DP Contest/C.cpp
ApocalypseMac/CP
b2db9aa5392a362dc0d979411788267ed9a5ff1d
[ "MIT" ]
null
null
null
atcoder/Educational DP Contest/C.cpp
ApocalypseMac/CP
b2db9aa5392a362dc0d979411788267ed9a5ff1d
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> const int maxn = 100005; int N, h[maxn][3], dp[maxn][3]; int main(){ std::cin >> N; memset(dp, 0, sizeof(dp)); for (int i = 1; i <= N; i++) std::cin >> h[i][0] >> h[i][1] >> h[i][2]; for (int i = 1; i <= N; i++){ dp[i][0] = h[i][0] + std::max(dp[i-1][1], dp[i-1][2]); dp[i][1] = h[i][1] + std::max(dp[i-1][0], dp[i-1][2]); dp[i][2] = h[i][2] + std::max(dp[i-1][0], dp[i-1][1]); } std::cout << *std::max_element(std::begin(dp[N]), std::end(dp[N])); return 0; }
34.5625
71
0.426763
ApocalypseMac
96bf34023f5eda6a9b69bfbc5b8ca83db5ea852b
1,089
cpp
C++
Algorithms on Graphs/week1_decomposition1/1_reachability/reachability.cpp
18Pranjul/Data-Structures-and-Algorithms-Specialization-Coursera
1d2f3a4ee390f0297de29de84205ef5f2a40f31d
[ "MIT" ]
null
null
null
Algorithms on Graphs/week1_decomposition1/1_reachability/reachability.cpp
18Pranjul/Data-Structures-and-Algorithms-Specialization-Coursera
1d2f3a4ee390f0297de29de84205ef5f2a40f31d
[ "MIT" ]
null
null
null
Algorithms on Graphs/week1_decomposition1/1_reachability/reachability.cpp
18Pranjul/Data-Structures-and-Algorithms-Specialization-Coursera
1d2f3a4ee390f0297de29de84205ef5f2a40f31d
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> #include <math.h> #include <cstring> #include <string> #include <stack> #include <queue> #include <deque> #include <map> #include <set> #include <utility> #include <iomanip> #include <climits> using namespace std; #define ll long long #define MOD 1000000007 #define MAX 1000000000000000000 #define ln "\n" #define pb push_back #define pll pair<ll,ll> #define mp make_pair #define f first #define s second #define Test ll t;cin>>t; while(t--) #define fast_io ios_base::sync_with_stdio(false);cin.tie(NULL); ll root(ll a[],ll x) { while(a[x]!=x) { a[x]=a[a[x]]; x=a[x]; } return x; } void Union(ll a[],ll x,ll y) { ll rx=root(a,x),ry=root(a,y); if(rx<ry) a[ry]=rx; else a[rx]=ry; } int main() { fast_io; ll n,m; cin>>n>>m; ll a[n+5],i; for(i=1;i<=n;i++) a[i]=i; for(i=0;i<m;i++) { ll x,y; cin>>x>>y; Union(a,x,y); } ll x,y; cin>>x>>y; if(root(a,x)==root(a,y)) cout<<"1"; else cout<<"0"; return 0; }
17.852459
64
0.56933
18Pranjul
96c360efe5ceec388a286236c77b3ed67a4b1eeb
478
cpp
C++
smart_ptr_test.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
1
2019-03-21T04:06:13.000Z
2019-03-21T04:06:13.000Z
smart_ptr_test.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
null
null
null
smart_ptr_test.cpp
hnqiu/cpp-test
ec3eafd3126be8468ba4f2d6a26c5863659aa8e3
[ "MIT" ]
null
null
null
/* Copyright (C) 2019 hnqiu. All rights reserved. * Licensed under the MIT License. See LICENSE for details. */ #include <iostream> #include <memory> #include <vector> #include "class_test.h" int smart_ptr_test() { std::shared_ptr<Agent> agt = std::make_shared<Agent>(1); std::vector<decltype(agt)> agents; agents.push_back(agt); auto first_elem = agents.begin(); std::cout << "agent's id is " << (*first_elem)->get_id() << std::endl; return 0; }
22.761905
74
0.658996
hnqiu
96c85c75575dc9b33ecabf72f8e2b8f699068fd8
1,629
cpp
C++
Arrays/DesignStackIncrementOps.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
1
2021-01-31T03:43:59.000Z
2021-01-31T03:43:59.000Z
Arrays/DesignStackIncrementOps.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
null
null
null
Arrays/DesignStackIncrementOps.cpp
karan2808/Cpp
595f536e33505c5fd079b709d6370bf888043fb3
[ "MIT" ]
1
2021-01-25T14:27:08.000Z
2021-01-25T14:27:08.000Z
#include <iostream> using namespace std; class CustomStack_Array { int *stkArr; int stkSize; // keep a track of number of elements or top position int stkTop; public: // constructor CustomStack_Array(int maxSize) { stkArr = new int[maxSize]; stkTop = 0; stkSize = maxSize; } // destructor ~CustomStack_Array() { delete stkArr; } // push an element to the stack void push(int x) { if (stkTop < stkSize) { stkArr[stkTop++] = x; } } // pop an element from the top of the stack and return it, if empty return -1 int pop() { if (stkTop) { // 0 based indexing return stkArr[--stkTop]; } return -1; } // increment the bottom k elements of the stack by val void increment(int k, int val) { for (int i = 0; i < stkTop && i < k; i++) { stkArr[i] += val; } } void printElements() { for (int i = 0; i < stkTop; i++) { cout << stkArr[i] << " "; } cout << endl; } }; int main() { CustomStack_Array csa(10); csa.push(6); csa.push(66); csa.push(7); csa.push(5); csa.push(99); csa.push(8); csa.push(4); cout << "Elements in the stack are: "; csa.printElements(); int x = csa.pop(); x = csa.pop(); x = csa.pop(); x = csa.pop(); cout << "Top element of stack is: " << csa.pop() << endl; cout << "Elements in the stack are: "; csa.printElements(); return 0; }
19.626506
81
0.493554
karan2808
96ccf681f5512d65eee912482db5800a9f1ff0c3
13,223
cpp
C++
Code/Sumo_RTOS/FREERTOS_SHELL/Source/lib/serial/rs232int.cpp
ryanforsberg/me507
5a9fd25e2062fec3c9d0cb141d360ad67709488b
[ "MIT" ]
null
null
null
Code/Sumo_RTOS/FREERTOS_SHELL/Source/lib/serial/rs232int.cpp
ryanforsberg/me507
5a9fd25e2062fec3c9d0cb141d360ad67709488b
[ "MIT" ]
null
null
null
Code/Sumo_RTOS/FREERTOS_SHELL/Source/lib/serial/rs232int.cpp
ryanforsberg/me507
5a9fd25e2062fec3c9d0cb141d360ad67709488b
[ "MIT" ]
null
null
null
//************************************************************************************* /** \file rs232int.cpp * This file contains a class which allows the use of a serial port on an AVR * microcontroller. This version of the class uses the serial port receiver * interrupt and a buffer to allow characters to be received in the background. * The port is used in "text mode"; that is, the information which is sent and * received is expected to be plain ASCII text, and the set of overloaded left-shift * operators "<<" in emstream.* can be used to easily send all sorts of data * to the serial port in a manner similar to iostreams (like "cout") in regular C++. * * Revised: * \li 09-14-2017 CTR Adapted from JRR code for AVR to be compatibile with xmega series * * License: * This file is copyright 2012 by JR Ridgely and released under the Lesser GNU * Public License, version 2. It intended for educational use only, but its use * is not limited thereto. */ /* 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 CONSEQUEN- * TIAL 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 <stdint.h> #include <stdlib.h> #include <avr/io.h> #include "rs232int.h" uint8_t* rcvC0_buffer = NULL; uint8_t* rcvC1_buffer = NULL; uint8_t* rcvD0_buffer = NULL; uint8_t* rcvD1_buffer = NULL; uint8_t* rcvE0_buffer = NULL; uint8_t* rcvE1_buffer = NULL; uint8_t* rcvF0_buffer = NULL; /// This index is used to write into serial character receiver buffer 0. uint16_t rcvC0_read_index; uint16_t rcvC1_read_index; uint16_t rcvD0_read_index; uint16_t rcvD1_read_index; uint16_t rcvE0_read_index; uint16_t rcvE1_read_index; uint16_t rcvF0_read_index; /// This index is used to read from serial character receiver buffer 0. uint16_t rcvC0_write_index; uint16_t rcvC1_write_index; uint16_t rcvD0_write_index; uint16_t rcvD1_write_index; uint16_t rcvE0_write_index; uint16_t rcvE1_write_index; uint16_t rcvF0_write_index; //------------------------------------------------------------------------------------- /** This method sets up the AVR UART for communications. It calls the emstream * constructor, which prepares to convert numbers to text strings, and the base232 * constructor, which does the work of setting up the serial port. Note that the user * program must call sei() somewhere to enable global interrupts so that this driver * will work. It is not called in this constructor because it's common to construct * many drivers which use interrupts, including this one, and then enable interrupts * globally using sei() after all the constructors have been called. * @param baud_rate The desired baud rate for serial communications. Default is 9600 * @param p_usart A pointer to the desired USART c-struct. The default is USARTC0. On an * XMGEGA choices are C0, C1, D0, D1, E0, E1, F0 */ rs232::rs232 (uint16_t baud_rate, USART_t* p_usart) : emstream (), base232 (baud_rate, p_usart) { if(p_usart == &USARTC0) { p_rcv_buffer = &rcvC0_buffer; p_rcv_read_index = &rcvC0_read_index; p_rcv_write_index = &rcvC0_write_index; } #ifdef USARTC1 else if(p_usart == &USARTC1) { p_rcv_buffer = &rcvC1_buffer; p_rcv_read_index = &rcvC1_read_index; p_rcv_write_index = &rcvC1_write_index; } #endif #ifdef USARTD0 else if(p_usart == &USARTD0) { p_rcv_buffer = &rcvD0_buffer; p_rcv_read_index = &rcvD0_read_index; p_rcv_write_index = &rcvD0_write_index; } #endif #ifdef USARTD1 else if(p_usart == &USARTD1) { p_rcv_buffer = &rcvD1_buffer; p_rcv_read_index = &rcvD1_read_index; p_rcv_write_index = &rcvD1_write_index; } #endif #ifdef USARTE0 else if(p_usart == &USARTE0) { p_rcv_buffer = &rcvE0_buffer; p_rcv_read_index = &rcvE0_read_index; p_rcv_write_index = &rcvE0_write_index; } #endif #ifdef USARTE1 else if(p_usart == &USARTE1) { p_rcv_buffer = &rcvE1_buffer; p_rcv_read_index = &rcvE1_read_index; p_rcv_write_index = &rcvE1_write_index; } #endif #ifdef USARTF0 else if(p_usart == &USARTF0) { p_rcv_buffer = &rcvF0_buffer; p_rcv_read_index = &rcvF0_read_index; p_rcv_write_index = &rcvF0_write_index; } #endif else { } *p_rcv_buffer = new uint8_t[RSINT_BUF_SIZE]; *p_rcv_read_index = 0; *p_rcv_write_index = 0; } //------------------------------------------------------------------------------------- /** This method sends one character to the serial port. It waits until the port is * ready, so it can hold up the system for a while. It times out if it waits too * long to send the character; you can check the return value to see if the character * was successfully sent, or just cross your fingers and ignore the return value. * Note 1: It's possible that at slower baud rates and/or higher processor speeds, * this routine might time out even when the port is working fine. A solution would * be to change the count variable to an integer and use a larger starting number. * Note 2: Fixed! The count is now an integer and it works at lower baud rates. * @param chout The character to be sent out * @return True if everything was OK and false if there was a timeout */ bool rs232::putchar (char chout) { // Now wait for the serial port transmitter buffer to be empty for (uint16_t count = 0; ((*p_USR & mask_UDRE) == 0); count++) { if (count > UART_TX_TOUT) return (false); } // Clear the TXCn bit so it can be used to check if the serial port is busy. This // check needs to be done prior to putting the processor into sleep mode. Oddly, // the TXCn bit is cleared by writing a one to its bit location *p_USR |= mask_TXC; // The CTS line is 0 and the transmitter buffer is empty, so send the character *p_UDR = chout; return (true); } //------------------------------------------------------------------------------------- /** This method gets one character from the serial port, if one is there. If not, it * waits until there is a character available. This can sometimes take a long time * (even forever), so use this function carefully. One should almost always use * check_for_char() to ensure that there's data available first. * @return The character which was found in the serial port receive buffer */ int16_t rs232::getchar (void) { uint8_t recv_char; // Character read from the queue // Wait until there's a character in the receiver queue while (*p_rcv_read_index == *p_rcv_write_index); recv_char = (*p_rcv_buffer)[*p_rcv_read_index]; if (++(*p_rcv_read_index) >= RSINT_BUF_SIZE) *p_rcv_read_index = 0; return (recv_char); } //------------------------------------------------------------------------------------- /** This method checks if there is a character in the serial port's receiver queue. * The queue will have been filled if a character came in through the serial port and * caused an interrupt. * @return True for character available, false for no character available */ bool rs232::check_for_char (void) { return (*p_rcv_read_index != *p_rcv_write_index); } //------------------------------------------------------------------------------------- /** This method sends the ASCII code to clear a display screen. It is called when the * format modifier 'clrscr' is inserted in a line of "<<" stuff. */ void rs232::clear_screen (void) { putchar (CLRSCR_STYLE); } //------------------------------------------------------------------------------------- /** \cond NOT_ENABLED (This ISR is not to be documented by Doxygen) * This interrupt service routine runs whenever a character has been received by the * first serial port (number 0). It saves that character into the receiver buffer. */ #ifdef USARTC0_RXC_vect ISR (USARTC0_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvC0_buffer[rcvC0_write_index] = USARTC0.DATA; // Increment the write pointer if (++rcvC0_write_index >= RSINT_BUF_SIZE) rcvC0_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvC0_write_index == rcvC0_read_index) if (++rcvC0_read_index >= RSINT_BUF_SIZE) rcvC0_read_index = 0; } #endif #ifdef USARTC1_RXC_vect ISR (USARTC1_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvC1_buffer[rcvC1_write_index] = USARTC1.DATA; // Increment the write pointer if (++rcvC1_write_index >= RSINT_BUF_SIZE) rcvC1_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvC1_write_index == rcvC1_read_index) if (++rcvC1_read_index >= RSINT_BUF_SIZE) rcvC1_read_index = 0; } #endif #ifdef USARTD0_RXC_vect ISR (USARTD0_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvD0_buffer[rcvD0_write_index] = USARTD0.DATA; // Increment the write pointer if (++rcvD0_write_index >= RSINT_BUF_SIZE) rcvD0_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvD0_write_index == rcvD0_read_index) if (++rcvD0_read_index >= RSINT_BUF_SIZE) rcvD0_read_index = 0; } #endif #ifdef USARTD1_RXC_vect ISR (USARTD1_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvD1_buffer[rcvD1_write_index] = USARTD1.DATA; // Increment the write pointer if (++rcvD1_write_index >= RSINT_BUF_SIZE) rcvD1_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvD1_write_index == rcvD1_read_index) if (++rcvD1_read_index >= RSINT_BUF_SIZE) rcvD1_read_index = 0; } #endif #ifdef USARTE0_RXC_vect ISR (USARTE0_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvE0_buffer[rcvE0_write_index] = USARTE0.DATA; // Increment the write pointer if (++rcvE0_write_index >= RSINT_BUF_SIZE) rcvE0_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvE0_write_index == rcvE0_read_index) if (++rcvE0_read_index >= RSINT_BUF_SIZE) rcvE0_read_index = 0; } #endif #ifdef USARTE1_RXC_vect ISR (USARTE1_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvE1_buffer[rcvE1_write_index] = USARTE1.DATA; // Increment the write pointer if (++rcvE1_write_index >= RSINT_BUF_SIZE) rcvE1_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvE1_write_index == rcvE1_read_index) if (++rcvE1_read_index >= RSINT_BUF_SIZE) rcvE1_read_index = 0; } #endif #ifdef USARTF0_RXC_vect ISR (USARTF0_RXC_vect) { // When this ISR is triggered, there's a character waiting in the USART data reg- // ister, and the write index indexes the place where that character should go rcvF0_buffer[rcvF0_write_index] = USARTF0.DATA; // Increment the write pointer if (++rcvF0_write_index >= RSINT_BUF_SIZE) rcvF0_write_index = 0; // If the write pointer is now equal to the read pointer, that means we've just // overwritten the oldest data. Increment the read pointer so that it doesn't seem // as if the buffer is empty if (rcvF0_write_index == rcvF0_read_index) if (++rcvF0_read_index >= RSINT_BUF_SIZE) rcvF0_read_index = 0; } #endif
35.641509
90
0.703547
ryanforsberg
96cddc003fed9b2b7e4054d6b2ba569b08966190
1,618
cpp
C++
call_thunk.cpp
znone/call_thunk
f4b16151f15a27bbc5ac939ee9053ebc4bf71790
[ "Apache-2.0" ]
23
2018-08-15T13:25:23.000Z
2022-02-24T15:17:28.000Z
call_thunk.cpp
znone/call_thunk
f4b16151f15a27bbc5ac939ee9053ebc4bf71790
[ "Apache-2.0" ]
3
2020-03-07T04:07:08.000Z
2022-01-05T08:10:40.000Z
call_thunk.cpp
znone/call_thunk
f4b16151f15a27bbc5ac939ee9053ebc4bf71790
[ "Apache-2.0" ]
6
2019-08-07T13:47:50.000Z
2021-08-01T08:13:06.000Z
#include "call_thunk.h" #ifdef _WIN32 #include <windows.h> #else #include <sys/mman.h> #ifndef offsetof #define offsetof(s,m) ((size_t)&reinterpret_cast<char const volatile&>((((s*)0)->m))) #endif //offsetof #ifndef _countof #define _countof(_Array) (sizeof(_Array) / sizeof(_Array[0])) #endif //_countof #endif //_WIN32 #include <string.h> #include <assert.h> #include <memory> namespace call_thunk { #pragma pack(push, 1) #if defined(_M_IX86) || defined(__i386__) #include "thunk_code_x86.cpp" #elif defined(_M_X64) || defined(__x86_64__) #include "thunk_code_x64.cpp" #endif void base_thunk::init_code(call_declare caller, call_declare callee, size_t argc, const argument_info* arginfos) throw(bad_call) { _thunk_size = thunk_code::calc_size(caller, callee, argc, arginfos); #if defined(_WIN32) _code = (char*)VirtualAlloc(NULL, _thunk_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE); #else _code = (char*)mmap(NULL, _thunk_size, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); #endif //_WIN32 _thunk = reinterpret_cast<thunk_code*>(_code); _code += sizeof(thunk_code); new(_thunk) thunk_code(caller, callee, argc, arginfos); } void base_thunk::destroy_code() { if (_thunk) { #if defined(_WIN32) VirtualFree(_thunk, 0, MEM_RELEASE); #else munmap(_thunk, _thunk_size); #endif //_WIN32 _thunk = NULL; _code = NULL; _thunk_size = 0; } } void base_thunk::flush_cache() { #ifdef _WIN32 FlushInstructionCache(GetCurrentProcess(), _thunk, _thunk_size); #else #endif //_WIN32 } void base_thunk::bind_impl(void* object, void* proc) { _thunk->bind(object, proc); } }
21.012987
128
0.729913
znone
96d3c5189455bae96243c9cfdbd58238cbdb2b53
4,997
cpp
C++
app/perfclient.cpp
HarryKBD/raperf
0a2d3876dd5923722bffa3dce5f7ee1e83253b00
[ "BSD-3-Clause" ]
null
null
null
app/perfclient.cpp
HarryKBD/raperf
0a2d3876dd5923722bffa3dce5f7ee1e83253b00
[ "BSD-3-Clause" ]
null
null
null
app/perfclient.cpp
HarryKBD/raperf
0a2d3876dd5923722bffa3dce5f7ee1e83253b00
[ "BSD-3-Clause" ]
null
null
null
#include <unistd.h> #include <cstdlib> #include <cstring> #include <netdb.h> #include <iostream> #include <udt.h> #include "cc.h" #include "test_util.h" #include <sys/time.h> using namespace std; //#define SEND_BUF_SIZE 50000 #define SEND_BUF_SIZE 8000 int64_t SEND_FILE_SIZE = 1024*1024*1024; //5GB void * monitor(void *); char send_buf[SEND_BUF_SIZE] = {0x03, }; int main(int argc, char * argv[]) { if ((4 != argc) || (0 == atoi(argv[2]))) { cout << "usage: appclient server_ip server_port filename" << endl; return 0; } // Automatically start up and clean up UDT module. UDTUpDown _udt_; struct addrinfo hints, *local, *peer; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_flags = AI_PASSIVE; hints.ai_family = AF_INET; hints.ai_socktype = SOCK_STREAM; //hints.ai_socktype = SOCK_DGRAM; if (0 != getaddrinfo(NULL, "9000", &hints, &local)) { cout << "incorrect network address.\n" << endl; return 0; } UDTSOCKET client = UDT::socket(local->ai_family, local->ai_socktype, local->ai_protocol); // UDT Options //UDT::setsockopt(client, 0, UDT_CC, new CCCFactory<CUDPBlast>, sizeof(CCCFactory<CUDPBlast>)); //UDT::setsockopt(client, 0, UDT_MSS, new int(9000), sizeof(int)); UDT::setsockopt(client, 0, UDT_SNDBUF, new int(10000000), sizeof(int)); //UDT::setsockopt(client, 0, UDP_SNDBUF, new int(10000000), sizeof(int)); //UDT::setsockopt(client, 0, UDT_MAXBW, new int64_t(12500000), sizeof(int)); // Windows UDP issue // For better performance, modify HKLM\System\CurrentControlSet\Services\Afd\Parameters\FastSendDatagramThreshold // for rendezvous connection, enable the code below /* UDT::setsockopt(client, 0, UDT_RENDEZVOUS, new bool(true), sizeof(bool)); if (UDT::ERROR == UDT::bind(client, local->ai_addr, local->ai_addrlen)) { cout << "bind: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } */ freeaddrinfo(local); if (0 != getaddrinfo(argv[1], argv[2], &hints, &peer)) { cout << "incorrect server/peer address. " << argv[1] << ":" << argv[2] << endl; return 0; } // connect to the server, implict bind if (UDT::ERROR == UDT::connect(client, peer->ai_addr, peer->ai_addrlen)) { cout << "connect: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } freeaddrinfo(peer); // send name information of the requested file int len = strlen(argv[3]); if (UDT::ERROR == UDT::send(client, (char*)&len, sizeof(int), 0)) { cout << "send: " << UDT::getlasterror().getErrorMessage() << endl; return -1; } if (UDT::ERROR == UDT::send(client, argv[3], len, 0)) { cout << "send: " << UDT::getlasterror().getErrorMessage() << endl; return -1; } int64_t send_size = SEND_FILE_SIZE*20; // send file size information if (UDT::ERROR == UDT::send(client, (char*)&send_size, sizeof(int64_t), 0)) { cout << "send: " << UDT::getlasterror().getErrorMessage() << endl; return 0; } cout << "sending file: " << argv[3] << " size: " << send_size << endl; pthread_create(new pthread_t, NULL, monitor, &client); int64_t total_sent = 0; int ss; struct timeval tv_start, tv_end; gettimeofday(&tv_start, NULL); while(total_sent < send_size) { int ssize = 0; int frag = 0; while (ssize < SEND_BUF_SIZE) { if (UDT::ERROR == (ss = UDT::send(client, send_buf + ssize, SEND_BUF_SIZE - ssize, 0))) { cout << "send:" << UDT::getlasterror().getErrorMessage() << endl; break; } //cout << ss << endl; frag++; ssize += ss; } //cout << "frag " << frag << endl; if (ssize < SEND_BUF_SIZE) break; total_sent += ssize; } gettimeofday(&tv_end, NULL); time_t taken = tv_end.tv_sec - tv_start.tv_sec; cout << "sending file done. saved file name : " << argv[3] << " total sent: " << total_sent << "( " << total_sent/(double)taken/1000000.0 << " MB/s) expected: " << SEND_FILE_SIZE << endl; UDT::close(client); return 0; } void * monitor(void * s) { UDTSOCKET u = *(UDTSOCKET *)s; UDT::TRACEINFO perf; cout << "SendRate(Mb/s)\tRTT(ms)\tCWnd\tPktSndPeriod(us)\tRecvACK\tRecvNAK" << endl; while (true) { sleep(1); if (UDT::ERROR == UDT::perfmon(u, &perf)) { cout << "perfmon: " << UDT::getlasterror().getErrorMessage() << endl; break; } cout << perf.mbpsSendRate << "\t\t" << perf.msRTT << "\t" << perf.pktCongestionWindow << "\t" << perf.usPktSndPeriod << "\t\t\t" << perf.pktRecvACK << "\t" << perf.pktRecvNAK << endl; } return NULL; }
27.010811
191
0.571743
HarryKBD
96d59dc54e46397f6fafa6dcadce847d7560dbc0
2,665
cpp
C++
fon9/FileRevRead_UT.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
21
2019-01-29T14:41:46.000Z
2022-03-11T00:22:56.000Z
fon9/FileRevRead_UT.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
null
null
null
fon9/FileRevRead_UT.cpp
fonwin/Plan
3bfa9407ab04a26293ba8d23c2208bbececb430e
[ "Apache-2.0" ]
9
2019-01-27T14:19:33.000Z
2022-03-11T06:18:24.000Z
/// \file fon9/FileRevRead_UT.cpp /// \author fonwinz@gmail.com #include "fon9/FileRevRead.hpp" #include "fon9/RevPrint.hpp" //--------------------------------------------------------------------------// bool OpenFile(const char* info, fon9::File& fd, const char* fname, fon9::FileMode fm) { printf("%s %s\n", info, fname); auto res = fd.Open(fname, fm); if (res) return true; puts(fon9::RevPrintTo<std::string>("Open error: ", res).c_str()); return false; } //--------------------------------------------------------------------------// int main(int argc, char** args) { #if defined(_MSC_VER) && defined(_DEBUG) _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); //_CrtSetBreakAlloc(176); #endif if(argc < 3) { printf("Reverse InputFile lines to OutputFile.\n" "Usage: InputFile OutputFile\n"); return 3; } fon9::File fdin; if (!OpenFile("Input file: ", fdin, args[1], fon9::FileMode::Read)) return 3; fon9_MSC_WARN_DISABLE_NO_PUSH(4820 4355); struct RevReader : public fon9::RevReadSearcher<fon9::FileRevReadBuffer<1024*4>, fon9::FileRevSearch> { fon9_NON_COPY_NON_MOVE(RevReader); // using base = fon9::RevReadSearcher<fon9::FileRevReadBuffer<1024 * 4>, fon9::FileRevSearch>; RevReader() = default; unsigned long LineCount_{0}; fon9::File FdOut_; virtual fon9::LoopControl OnFileBlock(size_t rdsz) override { if (this->RevSearchBlock(this->GetBlockPos(), '\n', rdsz) == fon9::LoopControl::Break) return fon9::LoopControl::Break; if (this->GetBlockPos() == 0 && this->LastRemainSize_ > 0) this->AppendLine(this->BlockBuffer_, this->LastRemainSize_); return fon9::LoopControl::Continue; } virtual fon9::LoopControl OnFoundChar(char* pbeg, char* pend) override { ++pbeg; // *pbeg=='\n'; => 應放在行尾. if (pbeg == pend && this->LineCount_ == 0) ++this->LineCount_; else this->AppendLine(pbeg, static_cast<size_t>(pend - pbeg)); return fon9::LoopControl::Continue; } void AppendLine(char* pbeg, size_t lnsz) { this->FdOut_.Append(pbeg, lnsz); this->FdOut_.Append("\n", 1); ++this->LineCount_; } }; RevReader reader; if (!OpenFile("Output file: ", reader.FdOut_, args[2], fon9::FileMode::Append | fon9::FileMode::CreatePath | fon9::FileMode::Trunc)) return 3; auto res = reader.Start(fdin); printf("Line count: %lu\n", reader.LineCount_); if (!res) puts(fon9::RevPrintTo<std::string>("Error: ", res).c_str()); return 0; }
37.535211
135
0.586867
fonwin
96d5be95ce9e37030eb3c39a32acfe308746443f
2,668
cpp
C++
src/renderer.cpp
kacejot/ray-tracer-se
8543826db12bda41e99bf37a6beef7a4acd79cff
[ "MIT" ]
null
null
null
src/renderer.cpp
kacejot/ray-tracer-se
8543826db12bda41e99bf37a6beef7a4acd79cff
[ "MIT" ]
null
null
null
src/renderer.cpp
kacejot/ray-tracer-se
8543826db12bda41e99bf37a6beef7a4acd79cff
[ "MIT" ]
null
null
null
#include <algorithm> #include <future> #include <thread> #include "renderer.h" #include "utils.h" #include "vec3.h" #include "ray.h" std::vector<vec3*> divide_vector_to_chunks(std::vector<vec3>& vector, size_t chunk_size) { std::vector<vec3*> result{}; size_t current_chunk = 0; for (; current_chunk < vector.size(); current_chunk += chunk_size) { result.push_back(vector.data() + current_chunk); } return result; } void write_fraction_color(std::ostream &out, vec3 vec) { vec *= 255.0f; // Write the translated [0,255] value of each color component. out << static_cast<int>(std::clamp(vec.r, 0.0, 255.0)) << ' ' << static_cast<int>(std::clamp(vec.g, 0.0, 255.0)) << ' ' << static_cast<int>(std::clamp(vec.b, 0.0, 255.0)) << '\n'; } void p3_renderer::render(){ auto threads = static_cast<size_t>(std::thread::hardware_concurrency()); auto rows_per_thread = image_height / threads + 1; out << "P3\n" << image_width << " " << image_height << "\n255\n"; std::vector<std::future<std::vector<vec3>>> futures; for (size_t i = 0; i < threads; ++i) { auto end_heigth = std::clamp((threads - i) * rows_per_thread, size_t{0}, image_height); auto start_height = std::clamp(end_heigth - rows_per_thread, size_t{0}, image_height); futures.push_back(std::async(std::launch::async, &p3_renderer::render_parallel, this, start_height, end_heigth)); } for (auto&& future : futures) { future.wait(); } for (auto&& future : futures) { for (auto&& color : future.get()) { write_fraction_color(out, color); } } std::cout << "\nDone.\n"; } std::vector<vec3> p3_renderer::render_parallel(size_t start_height, size_t end_heigth) { std::vector<vec3> result; for (int j = static_cast<int>(end_heigth) - 1; j >= static_cast<int>(start_height); --j) { // some dirty code here if (start_height == 0) { std::cout << std::endl << "Row's to render: " << j << ' ' << std::flush; } for (int i = 0; i < static_cast<int>(image_width); ++i) { vec3 color{}; for (int s = 0; s < samples_per_pixel; ++s) { auto u = (i + random_double()) / image_width; auto v = (j + random_double()) / image_height; ray r = cam.cast_ray(u, v); color += ray_color(r, world, max_depth); } color /= static_cast<double>(samples_per_pixel); gamma_correct(color, 0.5); result.push_back(color); } } return result; }
31.388235
121
0.574588
kacejot
96d71c62e8c5eb74a046150c71861d615e84d54c
3,137
hpp
C++
Source/Common/Delegate.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/Common/Delegate.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
Source/Common/Delegate.hpp
gunstarpl/Perim-Game-07-2015
58efdee1857f5cccad909d5c2a76f2d6871657e6
[ "Unlicense", "MIT" ]
null
null
null
#pragma once #include "Precompiled.hpp" // // Delegate // Implementation based on: http://molecularmusings.wordpress.com/2011/09/19/generic-type-safe-delegates-and-events-in-c/ // Be careful not to invoke a delagate to a method of an instance that no longer exists. // // Binding and invoking a function: // bool Function(const char* c, int i) { /*...*/ } // Delegate<bool(const char*, int)> delegate; // delegate.Bind<&Function>(); // delegate.Invoke("hello", 5); // // Binding and invoking a functor: // auto Object = [](const char* c, int i) { /*...*/ }; // Delegate<bool(const char*, int)> delegate; // delegate.Bind(&Object); // delegate.Invoke("hello", 5); // // Binding and invoking a method: // bool Class::Function(const char* c, int i) { /*...*/ } // Class instance; // Delegate<bool(const char*, int)> delegate; // delegate.Bind<Class, &Class::Function>(&instance); // delegate.Invoke("hello", 5); // template<typename Type> class Delegate; template<typename ReturnType, typename... Arguments> class Delegate<ReturnType(Arguments...)> { private: // Type declarations. typedef void* InstancePtr; typedef ReturnType (*FunctionPtr)(InstancePtr, Arguments...); // Compile time invocation stubs. template<ReturnType (*Function)(Arguments...)> static ReturnType FunctionStub(InstancePtr instance, Arguments... arguments) { return (Function)(std::forward<Arguments>(arguments)...); } template<class InstanceType> static ReturnType FunctorStub(InstancePtr instance, Arguments... arguments) { return (*static_cast<InstanceType*>(instance))(std::forward<Arguments>(arguments)...); } template<class InstanceType, ReturnType (InstanceType::*Function)(Arguments...)> static ReturnType MethodStub(InstancePtr instance, Arguments... arguments) { return (static_cast<InstanceType*>(instance)->*Function)(std::forward<Arguments>(arguments)...); } public: Delegate() : m_instance(nullptr), m_function(nullptr) { } void Cleanup() { m_instance = nullptr; m_function = nullptr; } // Binds a static function. template<ReturnType (*Function)(Arguments...)> void Bind() { m_instance = nullptr; m_function = &FunctionStub<Function>; } // Binds a functor object. template<class InstanceType> void Bind(InstanceType* instance) { m_instance = instance; m_function = &FunctorStub<InstanceType>; } // Binds an instance method. template<class InstanceType, ReturnType (InstanceType::*Function)(Arguments...)> void Bind(InstanceType* instance) { m_instance = instance; m_function = &MethodStub<InstanceType, Function>; } // Invokes the delegate. ReturnType Invoke(Arguments... arguments) { if(m_function == nullptr) return ReturnType(); return m_function(m_instance, std::forward<Arguments>(arguments)...); } private: InstancePtr m_instance; FunctionPtr m_function; };
28.518182
122
0.64329
gunstarpl
96d85fed9c2efee4fbd53b3c8b07ef38e8e6abb6
3,365
cpp
C++
Demo App/Demos/BlackHoleDemo.cpp
aderussell/ARPhysics
2669db7cd9e31918d8573e5a6bde654b443b0961
[ "MIT" ]
null
null
null
Demo App/Demos/BlackHoleDemo.cpp
aderussell/ARPhysics
2669db7cd9e31918d8573e5a6bde654b443b0961
[ "MIT" ]
null
null
null
Demo App/Demos/BlackHoleDemo.cpp
aderussell/ARPhysics
2669db7cd9e31918d8573e5a6bde654b443b0961
[ "MIT" ]
null
null
null
// // BlackHoleDemo.cpp // Drawing // // Created by Adrian Russell on 16/12/2013. // Copyright (c) 2013 Adrian Russell. All rights reserved. // #include "BlackHoleDemo.h" //#include "TestingIndexing.h" #define NUMBER_OF_PARTICLES 90 #define COLLISION_LEVEL 1 // TODO: add ball bounce demo, roll down hill then fall off and bounce on floor BlackHoleDemo::BlackHoleDemo() { BruteForceIndexing *bruteForce = new BruteForceIndexing(); World *world = new World(320, 240, bruteForce); this->world = world; bruteForce->release(); _particles = new Array(); _blackHoles = new Array(); //_blackHole = new CircleBody(6.0, Vector2(150.0, 130.0), 5.0); //world->addBody(_blackHole); GravityToPointForceGenerator *gravityGenerator = new GravityToPointForceGenerator(30.0, Vector2(150.0, 130.0)); world->addForceGenerator(gravityGenerator); _blackHoles->addObject(gravityGenerator); gravityGenerator->release(); //gravityGenerator = new GravityToPointForceGenerator(10.0, Vector2(140.0, 130.0)); //world->addForceGenerator(gravityGenerator); //_blackHoles->addObject(gravityGenerator); for (unsigned int i = 0; i < NUMBER_OF_PARTICLES; i++) { CircleBody *particle = new CircleBody(1, Vector2(10.0, 2.0 + 3 * i), 1.0); particle->setGroups(COLLISION_LEVEL); world->addBody(particle); _particles->addObject(particle); particle->release(); } } BlackHoleDemo::~BlackHoleDemo() { this->world->release(); _particles->release(); _blackHoles->release(); } void BlackHoleDemo::mouseEvent(int button, int state, int x, int y) { if (button == 0 && state == 0) { GravityToPointForceGenerator *gravityGenerator = (GravityToPointForceGenerator *)_blackHoles->objectAtIndex(0); gravityGenerator->setPoint(Vector2(x, y)); } else if (button == 2 && state == 0) { GravityToPointForceGenerator *gravityGenerator = new GravityToPointForceGenerator(30.0, Vector2(x, y)); world->addForceGenerator(gravityGenerator); _blackHoles->addObject(gravityGenerator); gravityGenerator->release(); } // create a new circle // or delete a circle } void BlackHoleDemo::mouseMoved(int x, int y) { } void BlackHoleDemo::keyPressed(unsigned char key, int x, int y) { if (key == '1') { for (unsigned int i = 0; i < _particles->count(); i++) { CircleBody *particle = (CircleBody *)_particles->objectAtIndex(i); if (particle->collisionGroups() == COLLISION_LEVEL) { particle->setGroups(0); } else { particle->setGroups(COLLISION_LEVEL); } } } } void BlackHoleDemo::draw() { for (unsigned int i = 0; i < _blackHoles->count(); i++) { GravityToPointForceGenerator *gravityGenerator = (GravityToPointForceGenerator *)_blackHoles->objectAtIndex(i); drawCircle(gravityGenerator->position(), gravityGenerator->force() / 5.0, 0.0, kBlackColor, kNoColor); } for (unsigned int i = 0; i < _particles->count(); i++) { CircleBody *particle = (CircleBody *)_particles->objectAtIndex(i); drawCircle(particle->position(), particle->radius(), particle->rotation(), kWhiteColor, kWhiteColor); } }
29.008621
119
0.645468
aderussell
96dbe09ef61a26a313e8873b00859c7873396fe1
55,122
cpp
C++
qws/src/gui/QProgressDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
42
2015-02-16T19:29:16.000Z
2021-07-25T11:09:03.000Z
qws/src/gui/QProgressDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
1
2017-11-23T12:49:25.000Z
2017-11-23T12:49:25.000Z
qws/src/gui/QProgressDialog.cpp
keera-studios/hsQt
8aa71a585cbec40005354d0ee43bce9794a55a9a
[ "BSD-2-Clause" ]
5
2015-10-15T21:25:30.000Z
2017-11-22T13:18:24.000Z
///////////////////////////////////////////////////////////////////////////// // // File : QProgressDialog.cpp // Copyright : (c) David Harley 2010 // Project : qtHaskell // Version : 1.1.4 // Modified : 2010-09-02 17:02:01 // // Warning : this file is machine generated - do not modify. // ///////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <wchar.h> #include <qtc_wrp_core.h> #include <qtc_wrp_gui.h> #include <qtc_subclass.h> #include <gui/QProgressDialog_DhClass.h> extern "C" { QTCEXPORT(void*,qtc_QProgressDialog)() { DhQProgressDialog*tr = new DhQProgressDialog(); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog1)(void* x1) { QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); DhQProgressDialog*tr = new DhQProgressDialog((QWidget*)tx1); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog2)(void* x1, long x2) { QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); DhQProgressDialog*tr = new DhQProgressDialog((QWidget*)tx1, (Qt::WindowFlags)x2); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog3)(wchar_t* x1, wchar_t* x2, int x3, int x4) { DhQProgressDialog*tr = new DhQProgressDialog(from_method(x1), from_method(x2), (int)x3, (int)x4); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog4)(wchar_t* x1, wchar_t* x2, int x3, int x4, void* x5) { QObject*tx5 = *((QPointer<QObject>*)x5); if ((tx5!=NULL)&&((QObject *)tx5)->property(QTC_PROP).isValid()) tx5 = ((QObject*)(((qtc_DynamicQObject*)tx5)->parent())); DhQProgressDialog*tr = new DhQProgressDialog(from_method(x1), from_method(x2), (int)x3, (int)x4, (QWidget*)tx5); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(void*,qtc_QProgressDialog5)(wchar_t* x1, wchar_t* x2, int x3, int x4, void* x5, long x6) { QObject*tx5 = *((QPointer<QObject>*)x5); if ((tx5!=NULL)&&((QObject *)tx5)->property(QTC_PROP).isValid()) tx5 = ((QObject*)(((qtc_DynamicQObject*)tx5)->parent())); DhQProgressDialog*tr = new DhQProgressDialog(from_method(x1), from_method(x2), (int)x3, (int)x4, (QWidget*)tx5, (Qt::WindowFlags)x6); tr->setProperty(QTC_DHPROP, true); QPointer<DhQProgressDialog> * ttr = new QPointer<DhQProgressDialog>(tr); return (void*) ttr; } QTCEXPORT(int,qtc_QProgressDialog_autoClose)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->autoClose(); } QTCEXPORT(int,qtc_QProgressDialog_autoReset)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->autoReset(); } QTCEXPORT(void,qtc_QProgressDialog_cancel)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->cancel(); } QTCEXPORT(void,qtc_QProgressDialog_changeEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhchangeEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_changeEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhchangeEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_closeEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhcloseEvent((QCloseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_closeEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhcloseEvent((QCloseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_forceShow)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhforceShow(); } QTCEXPORT(void*,qtc_QProgressDialog_labelText)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QString * tq = new QString(((QProgressDialog*)tx0)->labelText()); return (void*)(tq); } QTCEXPORT(int,qtc_QProgressDialog_maximum)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->maximum(); } QTCEXPORT(int,qtc_QProgressDialog_minimum)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->minimum(); } QTCEXPORT(int,qtc_QProgressDialog_minimumDuration)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->minimumDuration(); } QTCEXPORT(void,qtc_QProgressDialog_reset)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->reset(); } QTCEXPORT(void,qtc_QProgressDialog_resizeEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhresizeEvent((QResizeEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_resizeEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhresizeEvent((QResizeEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_setAutoClose)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setAutoClose((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_setAutoReset)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setAutoReset((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_setBar)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QProgressDialog*)tx0)->setBar((QProgressBar*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_setCancelButton)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QProgressDialog*)tx0)->setCancelButton((QPushButton*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_setCancelButtonText)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setCancelButtonText(from_method(x1)); } QTCEXPORT(void,qtc_QProgressDialog_setLabel)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QProgressDialog*)tx0)->setLabel((QLabel*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_setLabelText)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setLabelText(from_method(x1)); } QTCEXPORT(void,qtc_QProgressDialog_setMaximum)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setMaximum((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_setMinimum)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setMinimum((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_setMinimumDuration)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setMinimumDuration((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_setRange)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setRange((int)x1, (int)x2); } QTCEXPORT(void,qtc_QProgressDialog_setValue)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setValue((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_showEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhshowEvent((QShowEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_showEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhshowEvent((QShowEvent*)x1); } QTCEXPORT(void*,qtc_QProgressDialog_sizeHint)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize * tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = new QSize(((DhQProgressDialog*)tx0)->DhsizeHint()); } else { tc = new QSize(((QProgressDialog*)tx0)->sizeHint()); } return (void*)(tc); } QTCEXPORT(void*,qtc_QProgressDialog_sizeHint_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize * tc = new QSize(((DhQProgressDialog*)tx0)->DvhsizeHint()); return (void*)(tc); } QTCEXPORT(void,qtc_QProgressDialog_sizeHint_qth)(void* x0, int* _ret_w, int* _ret_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = ((DhQProgressDialog*)tx0)->DhsizeHint(); } else { tc = ((QProgressDialog*)tx0)->sizeHint(); } *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(void,qtc_QProgressDialog_sizeHint_qth_h)(void* x0, int* _ret_w, int* _ret_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tc = ((DhQProgressDialog*)tx0)->DvhsizeHint(); *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(int,qtc_QProgressDialog_value)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->value(); } QTCEXPORT(int,qtc_QProgressDialog_wasCanceled)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int) ((QProgressDialog*)tx0)->wasCanceled(); } QTCEXPORT(void,qtc_QProgressDialog_finalizer)(void* x0) { delete ((QPointer<QProgressDialog>*)x0); } QTCEXPORT(void*,qtc_QProgressDialog_getFinalizer)() { return (void*)(&qtc_QProgressDialog_finalizer); } QTCEXPORT(void,qtc_QProgressDialog_delete)(void* x0) { QObject* tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&(((QObject*)tx0)->property(QTC_PROP).isValid())) { qtc_DynamicQObject* ttx0 = (qtc_DynamicQObject*)tx0; tx0 = ((QObject*)(tx0->parent())); ttx0->freeDynamicSlots(); delete ttx0; } if ((tx0!=NULL)&&(((QObject*)tx0)->property(QTC_DHPROP).isValid())) { ((DhQProgressDialog*)tx0)->freeDynamicHandlers(); delete((DhQProgressDialog*)tx0); } else { delete((QProgressDialog*)tx0); } } QTCEXPORT(void,qtc_QProgressDialog_deleteLater)(void* x0) { QObject* tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&(((QObject*)tx0)->property(QTC_PROP).isValid())) { qtc_DynamicQObject* ttx0 = (qtc_DynamicQObject*)tx0; tx0 = ((QObject*)(tx0->parent())); ttx0->freeDynamicSlots(); ttx0->deleteLater(); } if ((tx0!=NULL)&&(((QObject*)tx0)->property(QTC_DHPROP).isValid())) { ((DhQProgressDialog*)tx0)->freeDynamicHandlers(); ((DhQProgressDialog*)tx0)->deleteLater(); } else { ((QProgressDialog*)tx0)->deleteLater(); } } QTCEXPORT(void,qtc_QProgressDialog_accept)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { ((DhQProgressDialog*)tx0)->Dhaccept(); } else { ((QDialog*)tx0)->accept(); } } QTCEXPORT(void,qtc_QProgressDialog_accept_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dvhaccept(); } QTCEXPORT(void,qtc_QProgressDialog_adjustPosition)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((DhQProgressDialog*)tx0)->DhadjustPosition((QWidget*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_contextMenuEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhcontextMenuEvent((QContextMenuEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_contextMenuEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhcontextMenuEvent((QContextMenuEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_done)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { ((DhQProgressDialog*)tx0)->Dhdone((int)x1); } else { ((QDialog*)tx0)->done((int)x1); } } QTCEXPORT(void,qtc_QProgressDialog_done_h)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dvhdone((int)x1); } QTCEXPORT(int,qtc_QProgressDialog_event)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->Dhevent((QEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_event_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->Dvhevent((QEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_eventFilter)(void* x0, void* x1, void* x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); return (int)((DhQProgressDialog*)tx0)->DheventFilter((QObject*)tx1, (QEvent*)x2); } QTCEXPORT(void,qtc_QProgressDialog_keyPressEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhkeyPressEvent((QKeyEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_keyPressEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhkeyPressEvent((QKeyEvent*)x1); } QTCEXPORT(void*,qtc_QProgressDialog_minimumSizeHint)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize * tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = new QSize(((DhQProgressDialog*)tx0)->DhminimumSizeHint()); } else { tc = new QSize(((QDialog*)tx0)->minimumSizeHint()); } return (void*)(tc); } QTCEXPORT(void*,qtc_QProgressDialog_minimumSizeHint_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize * tc = new QSize(((DhQProgressDialog*)tx0)->DvhminimumSizeHint()); return (void*)(tc); } QTCEXPORT(void,qtc_QProgressDialog_minimumSizeHint_qth)(void* x0, int* _ret_w, int* _ret_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = ((DhQProgressDialog*)tx0)->DhminimumSizeHint(); } else { tc = ((QDialog*)tx0)->minimumSizeHint(); } *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(void,qtc_QProgressDialog_minimumSizeHint_qth_h)(void* x0, int* _ret_w, int* _ret_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tc = ((DhQProgressDialog*)tx0)->DvhminimumSizeHint(); *_ret_w = tc.width(); *_ret_h = tc.height(); return; } QTCEXPORT(void,qtc_QProgressDialog_reject)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { ((DhQProgressDialog*)tx0)->Dhreject(); } else { ((QDialog*)tx0)->reject(); } } QTCEXPORT(void,qtc_QProgressDialog_reject_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dvhreject(); } QTCEXPORT(void,qtc_QProgressDialog_setVisible)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { ((DhQProgressDialog*)tx0)->DhsetVisible((bool)x1); } else { ((QDialog*)tx0)->setVisible((bool)x1); } } QTCEXPORT(void,qtc_QProgressDialog_setVisible_h)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhsetVisible((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_actionEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhactionEvent((QActionEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_actionEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhactionEvent((QActionEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_addAction)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QObject*tx1 = *((QPointer<QObject>*)x1); if ((tx1!=NULL)&&((QObject *)tx1)->property(QTC_PROP).isValid()) tx1 = ((QObject*)(((qtc_DynamicQObject*)tx1)->parent())); ((QProgressDialog*)tx0)->addAction((QAction*)tx1); } QTCEXPORT(void,qtc_QProgressDialog_create)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhcreate(); } QTCEXPORT(void,qtc_QProgressDialog_create1)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhcreate((WId)x1); } QTCEXPORT(void,qtc_QProgressDialog_create2)(void* x0, void* x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhcreate((WId)x1, (bool)x2); } QTCEXPORT(void,qtc_QProgressDialog_create3)(void* x0, void* x1, int x2, int x3) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhcreate((WId)x1, (bool)x2, (bool)x3); } QTCEXPORT(void,qtc_QProgressDialog_destroy)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhdestroy(); } QTCEXPORT(void,qtc_QProgressDialog_destroy1)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhdestroy((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_destroy2)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->Dhdestroy((bool)x1, (bool)x2); } QTCEXPORT(int,qtc_QProgressDialog_devType)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { return (int)((DhQProgressDialog*)tx0)->DhdevType(); } else { return (int)((QWidget*)tx0)->devType(); } } QTCEXPORT(int,qtc_QProgressDialog_devType_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DvhdevType(); } QTCEXPORT(void,qtc_QProgressDialog_dragEnterEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhdragEnterEvent((QDragEnterEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragEnterEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhdragEnterEvent((QDragEnterEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragLeaveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhdragLeaveEvent((QDragLeaveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragLeaveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhdragLeaveEvent((QDragLeaveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragMoveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhdragMoveEvent((QDragMoveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dragMoveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhdragMoveEvent((QDragMoveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dropEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhdropEvent((QDropEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_dropEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhdropEvent((QDropEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_enabledChange)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhenabledChange((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_enterEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhenterEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_enterEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhenterEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_focusInEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhfocusInEvent((QFocusEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_focusInEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhfocusInEvent((QFocusEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_focusNextChild)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DhfocusNextChild(); } QTCEXPORT(int,qtc_QProgressDialog_focusNextPrevChild)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DhfocusNextPrevChild((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_focusOutEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhfocusOutEvent((QFocusEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_focusOutEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhfocusOutEvent((QFocusEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_focusPreviousChild)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DhfocusPreviousChild(); } QTCEXPORT(void,qtc_QProgressDialog_fontChange)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhfontChange((const QFont&)(*(QFont*)x1)); } QTCEXPORT(int,qtc_QProgressDialog_heightForWidth)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { return (int)((DhQProgressDialog*)tx0)->DhheightForWidth((int)x1); } else { return (int)((QWidget*)tx0)->heightForWidth((int)x1); } } QTCEXPORT(int,qtc_QProgressDialog_heightForWidth_h)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->DvhheightForWidth((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_hideEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhhideEvent((QHideEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_hideEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhhideEvent((QHideEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_inputMethodEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhinputMethodEvent((QInputMethodEvent*)x1); } QTCEXPORT(void*,qtc_QProgressDialog_inputMethodQuery)(void* x0, long x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QVariant * tc; if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { tc = new QVariant(((DhQProgressDialog*)tx0)->DhinputMethodQuery((Qt::InputMethodQuery)x1)); } else { tc = new QVariant(((QWidget*)tx0)->inputMethodQuery((Qt::InputMethodQuery)x1)); } return (void*)(tc); } QTCEXPORT(void*,qtc_QProgressDialog_inputMethodQuery_h)(void* x0, long x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QVariant * tc = new QVariant(((DhQProgressDialog*)tx0)->DvhinputMethodQuery((int)x1)); return (void*)(tc); } QTCEXPORT(void,qtc_QProgressDialog_keyReleaseEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhkeyReleaseEvent((QKeyEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_keyReleaseEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhkeyReleaseEvent((QKeyEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_languageChange)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhlanguageChange(); } QTCEXPORT(void,qtc_QProgressDialog_leaveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhleaveEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_leaveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhleaveEvent((QEvent*)x1); } QTCEXPORT(int,qtc_QProgressDialog_metric)(void* x0, long x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (int)((DhQProgressDialog*)tx0)->Dhmetric((int)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseDoubleClickEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmouseDoubleClickEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseDoubleClickEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmouseDoubleClickEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseMoveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmouseMoveEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseMoveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmouseMoveEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mousePressEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmousePressEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mousePressEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmousePressEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseReleaseEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmouseReleaseEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_mouseReleaseEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmouseReleaseEvent((QMouseEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_move)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->move((const QPoint&)(*(QPoint*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_move_qth)(void* x0, int x1_x, int x1_y) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QPoint tx1(x1_x, x1_y); ((QProgressDialog*)tx0)->move(tx1); } QTCEXPORT(void,qtc_QProgressDialog_move1)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->move((int)x1, (int)x2); } QTCEXPORT(void,qtc_QProgressDialog_moveEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhmoveEvent((QMoveEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_moveEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhmoveEvent((QMoveEvent*)x1); } QTCEXPORT(void*,qtc_QProgressDialog_paintEngine)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_DHPROP).isValid()) { return (void*)((DhQProgressDialog*)tx0)->DhpaintEngine(); } else { return (void*)((QWidget*)tx0)->paintEngine(); } } QTCEXPORT(void*,qtc_QProgressDialog_paintEngine_h)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); return (void*)((DhQProgressDialog*)tx0)->DvhpaintEngine(); } QTCEXPORT(void,qtc_QProgressDialog_paintEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhpaintEvent((QPaintEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_paintEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhpaintEvent((QPaintEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_paletteChange)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhpaletteChange((const QPalette&)(*(QPalette*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_repaint)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->repaint(); } QTCEXPORT(void,qtc_QProgressDialog_repaint1)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->repaint((const QRegion&)(*(QRegion*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_repaint2)(void* x0, int x1, int x2, int x3, int x4) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->repaint((int)x1, (int)x2, (int)x3, (int)x4); } QTCEXPORT(void,qtc_QProgressDialog_resetInputContext)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhresetInputContext(); } QTCEXPORT(void,qtc_QProgressDialog_resize)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->resize((const QSize&)(*(QSize*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_resize_qth)(void* x0, int x1_w, int x1_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QSize tx1(x1_w, x1_h); ((QProgressDialog*)tx0)->resize(tx1); } QTCEXPORT(void,qtc_QProgressDialog_resize1)(void* x0, int x1, int x2) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->resize((int)x1, (int)x2); } QTCEXPORT(void,qtc_QProgressDialog_setGeometry)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setGeometry((const QRect&)(*(QRect*)x1)); } QTCEXPORT(void,qtc_QProgressDialog_setGeometry_qth)(void* x0, int x1_x, int x1_y, int x1_w, int x1_h) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QRect tx1(x1_x, x1_y, x1_w, x1_h); ((QProgressDialog*)tx0)->setGeometry(tx1); } QTCEXPORT(void,qtc_QProgressDialog_setGeometry1)(void* x0, int x1, int x2, int x3, int x4) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setGeometry((int)x1, (int)x2, (int)x3, (int)x4); } QTCEXPORT(void,qtc_QProgressDialog_setMouseTracking)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((QProgressDialog*)tx0)->setMouseTracking((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_tabletEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhtabletEvent((QTabletEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_tabletEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhtabletEvent((QTabletEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_updateMicroFocus)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhupdateMicroFocus(); } QTCEXPORT(void,qtc_QProgressDialog_wheelEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhwheelEvent((QWheelEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_wheelEvent_h)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DvhwheelEvent((QWheelEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_windowActivationChange)(void* x0, int x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhwindowActivationChange((bool)x1); } QTCEXPORT(void,qtc_QProgressDialog_childEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhchildEvent((QChildEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_connectNotify)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QString tx1(from_method(x1)); QByteArray txa1(tx1.toAscii()); ((DhQProgressDialog*)tx0)->DhconnectNotify(txa1.data()); } QTCEXPORT(void,qtc_QProgressDialog_customEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhcustomEvent((QEvent*)x1); } QTCEXPORT(void,qtc_QProgressDialog_disconnectNotify)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QString tx1(from_method(x1)); QByteArray txa1(tx1.toAscii()); ((DhQProgressDialog*)tx0)->DhdisconnectNotify(txa1.data()); } QTCEXPORT(int,qtc_QProgressDialog_receivers)(void* x0, wchar_t* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); QString tx1(from_method(x1)); QByteArray txa1(tx1.toAscii()); return (int)((DhQProgressDialog*)tx0)->Dhreceivers(txa1.data()); } QTCEXPORT(void*,qtc_QProgressDialog_sender)(void* x0) { QObject*tx0 = *((QPointer<QObject>*)x0); QObject * tc = (QObject*)(((DhQProgressDialog*)tx0)->Dhsender()); QPointer<QObject> * ttc = new QPointer<QObject>(tc); return (void*)(ttc); } QTCEXPORT(void,qtc_QProgressDialog_timerEvent)(void* x0, void* x1) { QObject*tx0 = *((QPointer<QObject>*)x0); if ((tx0!=NULL)&&((QObject *)tx0)->property(QTC_PROP).isValid()) tx0 = ((QObject*)(((qtc_DynamicQObject*)tx0)->parent())); ((DhQProgressDialog*)tx0)->DhtimerEvent((QTimerEvent*)x1); } QTCEXPORT(void, qtc_QProgressDialog_userMethod)(void * evt_obj, int evt_typ) { QObject * te = *((QPointer<QObject>*)evt_obj); if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); ((DhQProgressDialog*)te)->userDefined(evt_typ); } QTCEXPORT(void*, qtc_QProgressDialog_userMethodVariant)(void * evt_obj, int evt_typ, void * xv) { QObject * te = *((QPointer<QObject>*)evt_obj); if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); return (void*)(((DhQProgressDialog*)te)->userDefinedVariant(evt_typ, (QVariant*)xv)); } QTCEXPORT(int, qtc_QProgressDialog_setUserMethod)(void * evt_obj, int evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { QObject * te = *((QPointer<QObject>*)evt_obj); QObject * tr = te; if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); QPointer<QObject> * ttr = new QPointer<QObject>(tr); return (int) ((DhQProgressDialog*)te)->setDynamicQHandlerud(0, (void*)ttr, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setUserMethodVariant)(void * evt_obj, int evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { QObject * te = *((QPointer<QObject>*)evt_obj); QObject * tr = te; if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); QPointer<QObject> * ttr = new QPointer<QObject>(tr); return (int) ((DhQProgressDialog*)te)->setDynamicQHandlerud(1, (void*)ttr, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_unSetUserMethod)(void * evt_obj, int udm_typ, int evt_typ) { QObject * te = *((QPointer<QObject>*)evt_obj); if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); return (int) ((DhQProgressDialog*)te)->unSetDynamicQHandlerud(udm_typ, evt_typ); } QTCEXPORT(int, qtc_QProgressDialog_setHandler)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { QObject * te = *((QPointer<QObject>*)evt_obj); QObject * tr = te; if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); QString tq_evt(from_method((wchar_t *)evt_typ)); QByteArray tqba_evt(tq_evt.toAscii()); QPointer<QObject> * ttr = new QPointer<QObject>(tr); return (int) ((DhQProgressDialog*)te)->setDynamicQHandler((void*)ttr, tqba_evt.data(), rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_unSetHandler)(void * evt_obj, wchar_t * evt_typ) { QObject * te = *((QPointer<QObject>*)evt_obj); if (((QObject *)te)->property(QTC_PROP).isValid()) te = (((qtc_DynamicQObject *)te)->parent()); QString tq_evt(from_method((wchar_t *)evt_typ)); QByteArray tqba_evt(tq_evt.toAscii()); return (int) ((DhQProgressDialog*)te)->unSetDynamicQHandler(tqba_evt.data()); } QTCEXPORT(int, qtc_QProgressDialog_setHandler1)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler2)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler3)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler4)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler5)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler6)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler7)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler8)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler9)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } QTCEXPORT(int, qtc_QProgressDialog_setHandler10)(void * evt_obj, wchar_t * evt_typ, void * rf_ptr, void * st_ptr, void * df_ptr) { return (int) qtc_QProgressDialog_setHandler(evt_obj, evt_typ, rf_ptr, st_ptr, df_ptr); } }
48.267951
135
0.67971
keera-studios
96e926f31d8751147f189670acb00d398d85fe05
3,743
inl
C++
libgpos/include/gpos/common/CSyncList.inl
bhuvnesh2703/gpos
bce4ed761ef35e2852691a86b8099d820844a3e8
[ "ECL-2.0", "Apache-2.0" ]
28
2016-01-29T08:27:42.000Z
2021-03-11T01:42:33.000Z
libgpos/include/gpos/common/CSyncList.inl
bhuvnesh2703/gpos
bce4ed761ef35e2852691a86b8099d820844a3e8
[ "ECL-2.0", "Apache-2.0" ]
22
2016-02-01T16:31:50.000Z
2017-07-13T13:25:53.000Z
libgpos/include/gpos/common/CSyncList.inl
bhuvnesh2703/gpos
bce4ed761ef35e2852691a86b8099d820844a3e8
[ "ECL-2.0", "Apache-2.0" ]
23
2016-01-28T03:19:24.000Z
2021-05-28T07:32:51.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2011 EMC Corp. // // @filename: // CSyncList.inl // // @doc: // Implementation of template-based synchronized stack class with // minimum synchronization overhead; it provides a minimal set of // thread-safe operations through atomic primitives (lock-free); // // It requires that the elements are only inserted once, as their address // is used for identification; if elements are concurrently deleted, // iteration through the list is not thread safe; // // In order to be useful for system programming the class must be // allocation-less, i.e. manage elements without additional allocation, // to work in exception or OOM situations; //--------------------------------------------------------------------------- #include "gpos/sync/atomic.h" namespace gpos { //--------------------------------------------------------------------------- // @function: // CSyncList<T>::~CSyncList // // @doc: // Dtor; // //--------------------------------------------------------------------------- template<class T> CSyncList<T>::~CSyncList() {} //--------------------------------------------------------------------------- // @function: // CSyncList<T>::Push // // @doc: // Insert element at the head of the list; // //--------------------------------------------------------------------------- template<class T> void CSyncList<T>::Push ( T *pt ) { GPOS_ASSERT(NULL != pt); GPOS_ASSERT(m_list.PtFirst() != pt); ULONG ulAttempts = 0; SLink &linkElem = m_list.Link(pt); #ifdef GPOS_DEBUG void *pvHeadNext = linkElem.m_pvNext; #endif // GPOS_DEBUG GPOS_ASSERT(NULL == linkElem.m_pvNext); // keep spinning until passed element becomes the head while (true) { T *ptHead = m_list.PtFirst(); GPOS_ASSERT(pt != ptHead && "Element is already inserted"); GPOS_ASSERT(pvHeadNext == linkElem.m_pvNext && "Element is concurrently accessed"); // set current head as next element linkElem.m_pvNext = ptHead; #ifdef GPOS_DEBUG pvHeadNext = linkElem.m_pvNext; #endif // GPOS_DEBUG // attempt to set element as head if (FCompareSwap<T>((volatile T**) &m_list.m_ptHead, ptHead, pt)) { break; } CheckBackOff(ulAttempts); } } //--------------------------------------------------------------------------- // @function: // CSyncList<T>::Pop // // @doc: // Remove element from the head of the list; // //--------------------------------------------------------------------------- template<class T> T * CSyncList<T>::Pop() { ULONG ulAttempts = 0; T *ptHeadOld = NULL; // keep spinning until the head is removed while (true) { // get current head ptHeadOld = m_list.PtFirst(); if (NULL == ptHeadOld) { break; } // second element becomes the new head SLink &linkElem = m_list.Link(ptHeadOld); T *ptHeadNew = static_cast<T*>(linkElem.m_pvNext); // attempt to set new head if (FCompareSwap<T>((volatile T**) &m_list.m_ptHead, ptHeadOld, ptHeadNew)) { // reset link linkElem.m_pvNext = NULL; break; } CheckBackOff(ulAttempts); } return ptHeadOld; } //--------------------------------------------------------------------------- // @function: // CSyncList<T>::CheckBackOff // // @doc: // Back-off after too many attempts; // //--------------------------------------------------------------------------- template<class T> void CSyncList<T>::CheckBackOff ( ULONG &ulAttempts ) const { if (++ulAttempts == GPOS_SPIN_ATTEMPTS) { // back-off clib::USleep(GPOS_SPIN_BACKOFF); ulAttempts = 0; GPOS_CHECK_ABORT; } } } // EOF
22.413174
86
0.517499
bhuvnesh2703
96f36a536c81d16403e31c0e0626bcdedbbc42f9
70,589
cpp
C++
SOMTRANSIT/MAXTRANSIT/samples/objects/particles/sflectrs/monoflector.cpp
SOM-Firmwide/SOMTRANSIT
a83879c3b60bd24c45bcf4c01fcd11632e799973
[ "MIT" ]
null
null
null
SOMTRANSIT/MAXTRANSIT/samples/objects/particles/sflectrs/monoflector.cpp
SOM-Firmwide/SOMTRANSIT
a83879c3b60bd24c45bcf4c01fcd11632e799973
[ "MIT" ]
null
null
null
SOMTRANSIT/MAXTRANSIT/samples/objects/particles/sflectrs/monoflector.cpp
SOM-Firmwide/SOMTRANSIT
a83879c3b60bd24c45bcf4c01fcd11632e799973
[ "MIT" ]
null
null
null
#include "MonoflectDialog.h" #include "sflectr.h" #include "MouseCursors.h" #define PLANAR 0 #define SPHERE 1 #define MESH 2 #define MONODEF_CUSTNAME_CHUNK 0x0100 static TriObject *IsUseable(Object *pobj,TimeValue t) { if (pobj->SuperClassID()==GEOMOBJECT_CLASS_ID) { if (pobj->IsSubClassOf(triObjectClassID)) return (TriObject*)pobj; else { if (pobj->CanConvertToType(triObjectClassID)) return (TriObject*)pobj->ConvertToType(t,triObjectClassID); } } return NULL; } //--- ClassDescriptor and class vars --------------------------------- class BasicFlectorModClassDesc:public ClassDesc { public: int IsPublic() {return 0;} void * Create(BOOL loading = FALSE) { return new BasicFlectorMod();} const TCHAR * ClassName() {return GetString(IDS_EP_BASICDEFLECTORMOD);} SClass_ID SuperClassID() {return WSM_CLASS_ID; } Class_ID ClassID() {return BASICFLECTORMOD_CLASSID;} const TCHAR* Category() {return _T("");} }; static BasicFlectorModClassDesc BasicFlectorModDesc; ClassDesc* GetBasicFlectorModDesc() {return &BasicFlectorModDesc;} IObjParam* BasicFlectorObj::ip = NULL; class FlectorPickOperand : public PickModeCallback, public PickNodeCallback { public: BasicFlectorObj *po; FlectorPickOperand() {po=NULL;} BOOL HitTest(IObjParam *ip,HWND hWnd,ViewExp *vpt,IPoint2 m,int flags); BOOL Pick(IObjParam *ip,ViewExp *vpt); void EnterMode(IObjParam *ip); void ExitMode(IObjParam *ip); BOOL RightClick(IObjParam *ip, ViewExp * /*vpt*/) { return TRUE; } BOOL Filter(INode *node); PickNodeCallback *GetFilter() {return this;} }; class CreateFlectorPickNode : public RestoreObj { public: BasicFlectorObj *obj; INode *oldn; CreateFlectorPickNode(BasicFlectorObj *o, INode *n) { obj = o; oldn=n; } void Restore(int isUndo) { INode* cptr=obj->st->pblock2->GetINode(PB_MESHNODE); TSTR custname; if (cptr) { custname = TSTR(cptr->GetName()); } else { custname=_T(""); } obj->st->ShowName(); } void Redo() { int type; obj->pblock2->GetValue(PB_TYPE,0,type,FOREVER); if ((type==2)&&(obj->st->pmap[pbType_subani])) obj->st->ShowName(oldn); } TSTR Description() {return GetString(IDS_AP_FPICK);} }; #define CID_CREATEBasicFlectorMODE CID_USER +23 FlectorPickOperand BasicFlectorObj::pickCB; IParamMap2Ptr BasicFlectorObj::pmap[numpblocks]={NULL,NULL}; class CreateBasicFlectorProc : public MouseCallBack,ReferenceMaker { private: IObjParam *ip; void Init(IObjParam *i) {ip=i;} CreateMouseCallBack *createCB; INode *CloudNode; BasicFlectorObj *BasicFlectorObject; int attachedToNode; IObjCreate *createInterface; ClassDesc *cDesc; Matrix3 mat; // the nodes TM relative to the CP Point3 p0,p1; IPoint2 sp0, sp1; BOOL square; int ignoreSelectionChange; int lastPutCount; void CreateNewObject(); virtual void GetClassName(MSTR& s) { s = _M("CreateBasicFlectorProc"); } // from Animatable int NumRefs() { return 1; } RefTargetHandle GetReference(int i) { return (RefTargetHandle)CloudNode; } void SetReference(int i, RefTargetHandle rtarg) { CloudNode = (INode *)rtarg; } // StdNotifyRefChanged calls this, which can change the partID to new value // If it doesnt depend on the particular message& partID, it should return // REF_DONTCARE BOOL SupportAutoGrid(){return TRUE;} RefResult NotifyRefChanged(const Interval& changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message, BOOL propagate); public: void Begin( IObjCreate *ioc, ClassDesc *desc ); void End(); void SetIgnore(BOOL sw) { ignoreSelectionChange = sw; } CreateBasicFlectorProc() { ignoreSelectionChange = FALSE; } int createmethod(ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat); int proc( HWND hwnd, int msg, int point, int flag, IPoint2 m ); }; class CreateBasicFlectorMode : public CommandMode { public: CreateBasicFlectorProc proc; IObjParam *ip; BasicFlectorObj *obj; void Begin( IObjCreate *ioc, ClassDesc *desc ) { proc.Begin( ioc, desc ); } void End() { proc.End(); } void JumpStart(IObjParam *i,BasicFlectorObj*o); int Class() {return CREATE_COMMAND;} int ID() { return CID_CREATEBasicFlectorMODE; } MouseCallBack *MouseProc(int *numPoints) {*numPoints = 10000; return &proc;} ChangeForegroundCallback *ChangeFGProc() {return CHANGE_FG_SELECTED;} BOOL ChangeFG( CommandMode *oldMode ) { return (oldMode->ChangeFGProc() != CHANGE_FG_SELECTED); } void EnterMode() { GetCOREInterface()->PushPrompt(GetString(IDS_AP_CREATEMODE)); SetCursor(UI::MouseCursors::LoadMouseCursor(UI::MouseCursors::Crosshair)); } void ExitMode() {GetCOREInterface()->PopPrompt();SetCursor(LoadCursor(NULL, IDC_ARROW));} }; static CreateBasicFlectorMode theCreateBasicFlectorMode; IParamMap2Ptr BasicFlectorType::pmap[numpblocks]={NULL,NULL}; MonoFlectorParamPtr BasicFlectorType::theParam[numpblocks]={NULL,NULL}; class BasicFlectorTypeObjDlgProc : public BasicFlectorDlgProc { public: HWND hw; int dtype; ParamID which; IParamBlock2* pblk; BasicFlectorTypeObjDlgProc(BasicFlectorObj* sso_in) { sso = sso_in; st = NULL; dtype = pbType_subani; which = PB_TYPE; } void Update(TimeValue t); INT_PTR DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); }; class BasicFlectorComplexDlgProc : public BasicFlectorDlgProc { public: HWND hw; int dtype; ParamID which; IParamBlock2* pblk; BasicFlectorComplexDlgProc(BasicFlectorObj* sso_in) { sso = sso_in; st = NULL; dtype = pbComplex_subani; which = PB_COMPLEX; } void Update(TimeValue t); INT_PTR DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); }; // this classdesc2 for the object class BasicFlectorObjClassDesc:public ClassDesc2 { public: int IsPublic() { return TRUE; } void * Create( BOOL loading ) { return new BasicFlectorObj(); } const TCHAR * ClassName() { return GetString(IDS_AP_MONONAME); } SClass_ID SuperClassID() { return WSM_OBJECT_CLASS_ID; } Class_ID ClassID() { return BASICFLECTOR_CLASSID; } const TCHAR* Category() { return GetString(IDS_EP_SW_DEFLECTORS); } int BeginCreate(Interface *i); int EndCreate(Interface *i); // Hardwired name, used by MAX Script as unique identifier const TCHAR* InternalName() { return _T("BasicFlectorObj"); } HINSTANCE HInstance() { return hInstance; } }; static BasicFlectorObjClassDesc BasicFlectorOCD; ClassDesc* GetBasicFlectorObjDesc() {return &BasicFlectorOCD;} BOOL BasicFlectorObj::creating = FALSE; void BasicFlectorTypeObjDlgProc::Update(TimeValue t) { sdlgs = GetDlgItem(hw, IDC_FLECTTYPELIST); SetUpList(sdlgs,hw,sso->st->GetNameList(dtype)); int oldval; pblk->GetValue(which,0,oldval,FOREVER); SendMessage(sdlgs, CB_SETCURSEL, oldval, 0); } //each one of these takes input from a listbox and creates/destroys the subrollups INT_PTR BasicFlectorTypeObjDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { int id = LOWORD(wParam); pblk=sso->pblock2; hw=hWnd; switch (msg) { case WM_INITDIALOG: Update(t); break; case WM_DESTROY: if (sso->st->theParam[dtype]) { sso->st->theParam[dtype]->DeleteThis(); sso->st->theParam[dtype]=NULL; } break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_FLECTTYPELIST: int curSel = SendMessage(sdlgs, CB_GETCURSEL, 0, 0); if (curSel<0) return TRUE; int oldval; pblk->GetValue(which,0,oldval,FOREVER); if (oldval!=curSel) { pblk->SetValue(which,0,curSel); sso->st->CreateMonoFlectorParamDlg(GetCOREInterface(),curSel,dtype,sso->st->pmap[dtype]->GetHWnd()); } return TRUE; } break; } return FALSE; } void BasicFlectorComplexDlgProc::Update(TimeValue t) { sdlgs = GetDlgItem(hw, IDC_FLECTCOMPLEXITYLIST); SetUpList(sdlgs,hw,sso->st->GetNameList(dtype)); int oldval;pblk->GetValue(which,0,oldval,FOREVER); SendMessage(sdlgs, CB_SETCURSEL, oldval, 0); } INT_PTR BasicFlectorComplexDlgProc::DlgProc(TimeValue t, IParamMap2 *map, HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { int id = LOWORD(wParam); pblk=sso->pbComplex;hw=hWnd; switch (msg) { case WM_INITDIALOG: Update(t); break; case WM_DESTROY: if (sso->st->theParam[dtype]) { sso->st->theParam[dtype]->DeleteThis();sso->st->theParam[dtype]=NULL; } break; case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_FLECTCOMPLEXITYLIST: int curSel = SendMessage(sdlgs, CB_GETCURSEL, 0, 0); if (curSel<0) return TRUE; int oldval; pblk->GetValue(which,0,oldval,FOREVER); if (oldval!=curSel) { pblk->SetValue(which,0,curSel); sso->st->CreateMonoFlectorParamDlg(GetCOREInterface(),curSel,dtype,sso->st->pmap[dtype]->GetHWnd()); } return TRUE; } break; } return FALSE; } static BOOL IsGEOM(Object *obj) { if (obj!=NULL) { if (obj->SuperClassID()==GEOMOBJECT_CLASS_ID) { if (obj->IsSubClassOf(triObjectClassID)) return TRUE; else { if (obj->CanConvertToType(triObjectClassID)) return TRUE; } } } return FALSE; } BOOL FlectorPickOperand::Filter(INode *node) { if ((node)&&(!node->IsGroupHead())) { ObjectState os = node->GetObjectRef()->Eval(po->ip->GetTime()); if (os.obj->IsParticleSystem() || os.obj->SuperClassID()!=GEOMOBJECT_CLASS_ID) { node = NULL; return FALSE; } node->BeginDependencyTest(); po->NotifyDependents(FOREVER,0,REFMSG_TEST_DEPENDENCY); if(node->EndDependencyTest()) { node = NULL; return FALSE; } } return node ? TRUE : FALSE; } BOOL FlectorPickOperand::HitTest( IObjParam *ip,HWND hWnd,ViewExp *vpt,IPoint2 m,int flags) { if ( ! vpt || ! vpt->IsAlive() || ! hWnd) { // why are we here DbgAssert(!_T("Invalid viewport!")); return FALSE; } INode *node = ip->PickNode(hWnd,m,this); if ((node)&&(!node->IsGroupHead())) { ObjectState os = node->GetObjectRef()->Eval(ip->GetTime()); if ((os.obj->SuperClassID()!=GEOMOBJECT_CLASS_ID)||(!IsGEOM(os.obj))) { node = NULL; return FALSE; } } return node ? TRUE : FALSE; } BOOL FlectorPickOperand::Pick(IObjParam *ip,ViewExp *vpt) { if ( ! vpt || ! vpt->IsAlive() ) { // why are we here DbgAssert(!_T("Invalid viewport!")); return FALSE; } BOOL groupflag=0; INode *node = vpt->GetClosestHit(); assert(node); INodeTab nodes; if (node->IsGroupMember()) { groupflag=1; while (node->IsGroupMember()) node=node->GetParentNode(); } int subtree=0; if (groupflag) MakeGroupNodeList(node,&nodes,subtree,ip->GetTime()); else{ nodes.SetCount(1);nodes[0]=node;} ip->FlashNodes(&nodes); theHold.Begin(); theHold.Put(new CreateFlectorPickNode(po,node)); po->st->pblock2->SetValue(PB_MESHNODE,ip->GetTime(),node); theHold.Accept(GetString(IDS_AP_FPICK)); po->st->ShowName(node); if (po->creating) { theCreateBasicFlectorMode.JumpStart(ip,po); ip->SetCommandMode(&theCreateBasicFlectorMode); ip->RedrawViews(ip->GetTime()); return FALSE; } else { return TRUE; } } void FlectorPickOperand::EnterMode(IObjParam *ip) { ICustButton *iBut; iBut=GetICustButton(GetDlgItem(po->st->hParams,IDC_EP_PICKBUTTON)); if (iBut) iBut->SetCheck(TRUE); ReleaseICustButton(iBut); GetCOREInterface()->PushPrompt(GetString(IDS_AP_PICKMODE)); } void FlectorPickOperand::ExitMode(IObjParam *ip) { ICustButton *iBut; iBut=GetICustButton(GetDlgItem(po->st->hParams,IDC_EP_PICKBUTTON)); if (iBut) iBut->SetCheck(FALSE); ReleaseICustButton(iBut); GetCOREInterface()->PopPrompt(); } //pb2s for each static dialog static ParamBlockDesc2 BasicFlectorPB ( pbType_subani, _T("BasicFlectorParams"), 0, &BasicFlectorOCD, P_AUTO_CONSTRUCT + P_AUTO_UI, pbType_subani, //rollout IDD_MF_0100_FLECTTYPESELECT, IDS_DLG_FTYPE, 0, 0, NULL, // params PB_TYPE, _T("FlectorType"), TYPE_INT, 0, IDS_FLECTORTYPETBLE, p_end, //watje ref to hold the collision engine monoflect_colliderp, _T("colliderplane"), TYPE_REFTARG, 0, IDS_FLECTORTYPETBLE, p_end, monoflect_colliders, _T("collidersphere"), TYPE_REFTARG, 0, IDS_FLECTORTYPETBLE, p_end, monoflect_colliderm, _T("collidermesh"), TYPE_REFTARG, 0, IDS_FLECTORTYPETBLE, p_end, p_end ); static ParamBlockDesc2 BasicFComplexPB ( pbComplex_subani, _T("FlectorComplexityParams"), 0, &BasicFlectorOCD, P_AUTO_CONSTRUCT + P_AUTO_UI, pbComplex_subani, //rollout IDD_MF_0200_FLECTCOMPLEXITYSELECT, IDS_DLG_FCOMPLEX, 0, 0, NULL, // params PB_COMPLEX, _T("FlectorComplex"), TYPE_INT, 0, IDS_FLECTORCOMPTBLE, p_end, p_end ); RefResult CreateBasicFlectorProc::NotifyRefChanged( const Interval& changeInt, RefTargetHandle hTarget, PartID& partID, RefMessage message, BOOL propagate) { switch (message) { case REFMSG_TARGET_SELECTIONCHANGE: if ( ignoreSelectionChange ) { break; } if ( BasicFlectorObject && CloudNode==hTarget ) { // this will set camNode== NULL; theHold.Suspend(); DeleteReference(0); theHold.Resume(); goto endEdit; } // fall through case REFMSG_TARGET_DELETED: if (BasicFlectorObject && CloudNode==hTarget ) { endEdit: if (createInterface->GetCommandMode()->ID() == CID_STDPICK) { if (BasicFlectorObject->creating) { theCreateBasicFlectorMode.JumpStart(BasicFlectorObject->ip,BasicFlectorObject); createInterface->SetCommandMode(&theCreateBasicFlectorMode); } else {createInterface->SetStdCommandMode(CID_OBJMOVE);} } BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); BasicFlectorObject->EndEditParams( (IObjParam*)createInterface, 0, NULL); BasicFlectorObject = NULL; CloudNode = NULL; CreateNewObject(); attachedToNode = FALSE; } else if (CloudNode==hTarget ) CloudNode = NULL; break; } return REF_SUCCEED; } void AddMesh(BasicFlectorObj *obj, TriObject *triOb, Matrix3 tm, BOOL nottop) { int lastv = obj->nv, lastf = obj->nf; obj->nv += triOb->GetMesh().getNumVerts(); obj->nf += triOb->GetMesh().getNumFaces(); if (!nottop) obj->dmesh->DeepCopy(&triOb->GetMesh(),PART_GEOM|PART_TOPO); else { obj->dmesh->setNumFaces(obj->nf,obj->dmesh->getNumFaces()); obj->dmesh->setNumVerts(obj->nv,obj->dmesh->getNumVerts()); tm = tm*obj->invtm; for (int vc=0;vc<triOb->GetMesh().getNumFaces();vc++) { obj->dmesh->faces[lastf]=triOb->GetMesh().faces[vc]; for (int vs=0;vs<3;vs++) obj->dmesh->faces[lastf].v[vs]+=lastv; lastf++; } } for (int vc=0;vc<triOb->GetMesh().getNumVerts();vc++) { if (nottop) obj->dmesh->verts[lastv]=triOb->GetMesh().verts[vc]*tm; else obj->dmesh->verts[lastv]=triOb->GetMesh().verts[vc]; lastv++; } } void CreateBasicFlectorProc::Begin( IObjCreate *ioc, ClassDesc *desc ) { ip=(IObjParam*)ioc; createInterface = ioc; cDesc = desc; attachedToNode = FALSE; createCB = NULL; CloudNode = NULL; BasicFlectorObject = NULL; CreateNewObject(); } void CreateBasicFlectorProc::CreateNewObject() { SuspendSetKeyMode(); createInterface->GetMacroRecorder()->BeginCreate(cDesc); BasicFlectorObject = (BasicFlectorObj*)cDesc->Create(); lastPutCount = theHold.GetGlobalPutCount(); // Start the edit params process if ( BasicFlectorObject ) { BasicFlectorObject->BeginEditParams( (IObjParam*)createInterface, BEGIN_EDIT_CREATE, NULL ); BasicFlectorObject->SetAFlag(A_OBJ_CREATING); BasicFlectorObject->SetAFlag(A_OBJ_LONG_CREATE); } ResumeSetKeyMode(); } //LACamCreationManager::~LACamCreationManager void CreateBasicFlectorProc::End() { if ( BasicFlectorObject ) { BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); BasicFlectorObject->EndEditParams( (IObjParam*)createInterface, END_EDIT_REMOVEUI, NULL); if ( !attachedToNode ) { // RB 4-9-96: Normally the hold isn't holding when this // happens, but it can be in certain situations (like a track view paste) // Things get confused if it ends up with undo... theHold.Suspend(); BasicFlectorObject->DeleteAllRefsFromMe(); BasicFlectorObject->DeleteAllRefsToMe(); theHold.Resume(); BasicFlectorObject->DeleteThis(); BasicFlectorObject = NULL; createInterface->GetMacroRecorder()->Cancel(); if (theHold.GetGlobalPutCount()!=lastPutCount) GetSystemSetting(SYSSET_CLEAR_UNDO); } else if ( CloudNode ) { theHold.Suspend(); DeleteReference(0); // sets cloudNode = NULL theHold.Resume(); } } } void CreateBasicFlectorMode::JumpStart(IObjParam *i,BasicFlectorObj *o) { ip = i; obj = o; obj->BeginEditParams(i,BEGIN_EDIT_CREATE,NULL); } int BasicFlectorObjClassDesc::BeginCreate(Interface *i) { SuspendSetKeyMode(); IObjCreate *iob = i->GetIObjCreate(); theCreateBasicFlectorMode.Begin(iob,this); iob->PushCommandMode(&theCreateBasicFlectorMode); return TRUE; } int BasicFlectorObjClassDesc::EndCreate(Interface *i) { ResumeSetKeyMode(); theCreateBasicFlectorMode.End(); i->RemoveMode(&theCreateBasicFlectorMode); macroRec->EmitScript(); // 10/00 return TRUE; } int CreateBasicFlectorProc::proc(HWND hwnd,int msg,int point,int flag, IPoint2 m ) { int res=TRUE; ViewExp& vpx = createInterface->GetViewExp(hwnd); assert( vpx.IsAlive() ); DWORD snapdim = SNAP_IN_3D; switch ( msg ) { case MOUSE_POINT: switch ( point ) { case 0: { assert( BasicFlectorObject ); vpx.CommitImplicitGrid(m, flag ); if ( createInterface->SetActiveViewport(hwnd) ) { return FALSE; } if (createInterface->IsCPEdgeOnInView()) { res = FALSE; goto done; } if ( attachedToNode ) { // send this one on its way BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); BasicFlectorObject->EndEditParams( (IObjParam*)createInterface, 0, NULL); createInterface->GetMacroRecorder()->EmitScript(); // Get rid of the reference. if (CloudNode) { theHold.Suspend(); DeleteReference(0); theHold.Resume(); } // new object CreateNewObject(); // creates BasicFlectorObject } theHold.Begin(); // begin hold for undo mat.IdentityMatrix(); // link it up INode *l_CloudNode = createInterface->CreateObjectNode( BasicFlectorObject); attachedToNode = TRUE; BasicFlectorObject->ClearAFlag(A_OBJ_CREATING); assert( l_CloudNode ); createCB = NULL; createInterface->SelectNode( l_CloudNode ); // Reference the new node so we'll get notifications. theHold.Suspend(); ReplaceReference( 0, l_CloudNode); theHold.Resume(); mat.SetTrans(vpx.SnapPoint(m,m,NULL,snapdim)); macroRec->Disable(); // 10/00 createInterface->SetNodeTMRelConstPlane(CloudNode, mat); macroRec->Enable(); } default: res = createmethod(vpx.ToPointer(),msg,point,flag,m,mat); createInterface->SetNodeTMRelConstPlane(CloudNode, mat); if (res==CREATE_ABORT) goto abort; if (res==CREATE_STOP) { BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); theHold.Accept(GetString(IDS_EP_CREATE)); } createInterface->RedrawViews(createInterface->GetTime()); //DS break; } break; case MOUSE_MOVE: res = createmethod(vpx.ToPointer(),msg,point,flag,m,mat); macroRec->Disable(); // 10/2/00 createInterface->SetNodeTMRelConstPlane(CloudNode, mat); macroRec->Enable(); if (res==CREATE_ABORT) goto abort; if (res==CREATE_STOP) { BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); theHold.Accept(GetString(IDS_EP_CREATE)); // TH } createInterface->RedrawViews(createInterface->GetTime(),REDRAW_INTERACTIVE); //DS // macroRec->SetProperty(BasicFlectorObject, _T("target"), // JBW 4/23/99 // mr_create, Class_ID(TARGET_CLASS_ID, 0), GEOMOBJECT_CLASS_ID, 1, _T("transform"), mr_matrix3, &mat); break; case MOUSE_FREEMOVE: SetCursor(UI::MouseCursors::LoadMouseCursor(UI::MouseCursors::Crosshair)); res = createmethod(vpx.ToPointer(),msg,point,flag,m,mat); vpx.TrackImplicitGrid(m); break; case MOUSE_PROPCLICK: createInterface->SetStdCommandMode(CID_OBJMOVE); break; case MOUSE_ABORT: abort: assert( BasicFlectorObject ); BasicFlectorObject->ClearAFlag(A_OBJ_LONG_CREATE); BasicFlectorObject->EndEditParams( (IObjParam*)createInterface,0,NULL); theHold.Cancel(); // deletes both the Cloudera and target. if (theHold.GetGlobalPutCount()!=lastPutCount) GetSystemSetting(SYSSET_CLEAR_UNDO); BasicFlectorObject=NULL; createInterface->RedrawViews(createInterface->GetTime()); CreateNewObject(); attachedToNode = FALSE; res = FALSE; } done: if ((res == CREATE_STOP)||(res==CREATE_ABORT)) vpx.ReleaseImplicitGrid(); return res; } void BasicFlectorDlgProc::SetUpList(HWND cwnd,HWND hWnd,dlglist ilist) { SendMessage(cwnd,CB_RESETCONTENT,0,0); for (int i=0; i<ilist.cnt; i++) { SendMessage(cwnd,CB_ADDSTRING,0,(LPARAM)(TCHAR*)GetString(ilist.namelst[i])); } } BasicFlectorObj::BasicFlectorObj() { gf = NULL; mf = NULL; pbComplex = NULL; st = NULL; BasicFlectorOCD.MakeAutoParamBlocks(this); assert(pblock2); assert(pbComplex); ReplaceReference(monoflecdlg,new MonoFlector(this)); int tpf=GetTicksPerFrame(); int timeoff=100*tpf; ffdata.FlectForce = Zero; ffdata.ApplyAt = Zero; ffdata.Num = 0; dmesh=NULL; vnorms=NULL; fnorms=NULL; srand(lastrnd=12345); t=99999; custnode=NULL; custname=_T(" "); nv=0;nf=0; ctime=99999; pblock2->SetValue(PB_TYPE,0,0); macroRec->Disable(); //watje create a new ref to our collision engine CollisionPlane *colp = (CollisionPlane*)CreateInstance(REF_MAKER_CLASS_ID, PLANAR_COLLISION_ID); if (colp) { pblock2->SetValue(monoflect_colliderp,0,(ReferenceTarget*)colp); } CollisionSphere *cols = (CollisionSphere*)CreateInstance(REF_MAKER_CLASS_ID, SPHERICAL_COLLISION_ID); if (cols) { pblock2->SetValue(monoflect_colliders,0,(ReferenceTarget*)cols); } CollisionMesh *colm = (CollisionMesh*)CreateInstance(REF_MAKER_CLASS_ID, MESH_COLLISION_ID); if (colm) { pblock2->SetValue(monoflect_colliderm,0,(ReferenceTarget*)colm); } macroRec->Enable(); } BasicFlectorObj::~BasicFlectorObj() { DeleteAllRefsFromMe(); if (gf) delete gf; if (mf) delete mf; if (vnorms) delete[] vnorms; if (fnorms) delete[] fnorms; if (dmesh) delete dmesh; DbgAssert(NULL == pblock2); } void BasicFlectorObj::MapKeys(TimeMap *map,DWORD flags) { Animatable::MapKeys(map,flags); TimeValue TempTime; float ftemp,tpf=GetTicksPerFrame(); pbComplex->GetValue(PB_TIMEON,0,ftemp,FOREVER); TempTime=ftemp*tpf; TempTime = map->map(TempTime); pbComplex->SetValue(PB_TIMEON,0,((float)ftemp)/tpf); pbComplex->GetValue(PB_TIMEOFF,0,ftemp,FOREVER); TempTime=ftemp*tpf; TempTime = map->map(TempTime); pbComplex->SetValue(PB_TIMEOFF,0,((float)ftemp)/tpf); } Modifier *BasicFlectorObj::CreateWSMMod(INode *node) { return new BasicFlectorMod(node,this); } void BasicFlectorObj::IntoPickMode() { if (ip->GetCommandMode()->ID() == CID_STDPICK) { if (creating) { theCreateBasicFlectorMode.JumpStart(ip,this); ip->SetCommandMode(&theCreateBasicFlectorMode); } else {ip->SetStdCommandMode(CID_OBJMOVE);} } else { pickCB.po = this; ip->SetPickMode(&pickCB); } } Object *BasicFlectorField::GetSWObject() { return obj; } BOOL BasicFlectorField::CheckCollision(TimeValue t,Point3 &inp,Point3 &vel,float dt,int index,float *ct, BOOL UpdatePastCollide) { if (obj == NULL) return FALSE; //667105 watje xrefs can change the base object type through proxies which will cause this to be null or the user can copy a new object type over ours BOOL donewithparticle = FALSE; float K=(float)GetMasterScale(UNITS_CENTIMETERS); float stepsize = dt; Point3 InVel, SaveVel = vel; int typeofdeflector; obj->pblock2->GetValue(PB_TYPE,t,typeofdeflector,FOREVER); int enableAdvanced, enableDynamics; obj->pbComplex->GetValue(PB_COMPLEX,t,enableAdvanced,FOREVER); enableDynamics = (enableAdvanced>1?1:0); enableAdvanced = (enableAdvanced>0?1:0); switch(typeofdeflector) { case PLANAR: // PLANAR COLLISION CODE BLOCK BEGINS HERE { ReferenceTarget *rt; obj->pblock2->GetValue(monoflect_colliderp,t,rt,obj->tmValid); colp = (CollisionPlane *) rt; if (!((obj->mValid.InInterval(t))&&(obj->tmValid.InInterval(t)))) { obj->tmValid = FOREVER; obj->st->pblock2->GetValue(PB_WIDTH,t,width,obj->tmValid); obj->st->pblock2->GetValue(PB_LENGTH,t,height,obj->tmValid); obj->st->pblock2->GetValue(PB_QUALITY,t,quality,obj->tmValid); if (colp) { colp->SetWidth(t,width); colp->SetHeight(t,height); colp->SetQuality(t,quality); colp->SetNode(t,node); } if (colp) colp->PreFrame(t,(TimeValue) dt); obj->st->pbComplex->GetValue(PB_BOUNCE,t,bounce,obj->tmValid); obj->st->pbComplex->GetValue(PB_BVAR,t,bvar,obj->tmValid); obj->st->pbComplex->GetValue(PB_CHAOS,t,chaos,obj->tmValid); obj->st->pbComplex->GetValue(PB_INHERVEL,t,vinher,obj->tmValid); obj->st->pbComplex->GetValue(PB_FRICTION,t,friction,obj->tmValid); // vinher *= 0.01f; // bvar *= 0.01f; // chaos *= 0.01f; // friction *= 0.01f; obj->st->pbComplex->GetValue(PB_DISTORTION,t,refvol,obj->tmValid); // refvol *= 0.01f; obj->st->pbComplex->GetValue(PB_DISTORTIONVAR,t,refvar,FOREVER); // refvar *= 0.01f; obj->st->pbComplex->GetValue(PB_PASSVEL,t,decel,FOREVER); obj->st->pbComplex->GetValue(PB_PASSVELVAR,t,decelvar,FOREVER); // decelvar *= 0.01f; width *= 0.5f; height *= 0.5f; Interval tmpValid = FOREVER; } if ((curtime!=t)&&(enableDynamics)) { totalforce = Zero; applyat = Zero; totalnumber = 0; curtime = t; } float fstartt,fendt; TimeValue startt,endt; obj->st->pbComplex->GetValue(PB_TIMEON,t,fstartt,FOREVER); obj->st->pbComplex->GetValue(PB_TIMEOFF,t,fendt,FOREVER); startt=fstartt*GetTicksPerFrame();endt=fendt*GetTicksPerFrame(); if ((t<startt)||(t>endt)) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } if (!colp) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } else { srand(obj->lastrnd); float reflects; obj->st->pbComplex->GetValue(PB_REFLECTS,t,reflects,FOREVER); // reflects *= 0.01f; if (RND01()<reflects) { donewithparticle = TRUE; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colp->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float rvariation = 1.0f; float rchaos = 1.0f; if (bvar != 0.0f) { rvariation =1.0f-( bvar * randomFloat[index%500]); } if (chaos != 0.0f) { rchaos =1.0f-( chaos * randomFloat[index%500]); } vel = bnorm*(bounce*rvariation) + frict*(1.0f-(friction*rchaos)) + (inheritedVel * vinher); inp = hitpoint; if (UpdatePastCollide) { inp += vel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } vel += (inheritedVel * vinher); InVel = vel; applyat = hitpoint; } // particle was not reflected and not tested for refraction! float refracts; obj->st->pbComplex->GetValue(PB_REFRACTS,t,refracts,FOREVER); // refracts *= 0.01f; if ((RND01()<refracts)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colp->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float dirapproach,theta = 0.0f; Point3 ZVec = bnorm; dirapproach = (DotProd(InVel,ZVec)<0.0f?1.0f:-1.0f); Point3 MZVec = -bnorm; InVel *= decel*(1.0f-decelvar*RND01()); float maxref,refangle,maxvarref; refangle = 0.0f; if (!FloatEQ0(refvol)) { if (dirapproach>0.0f) theta = (float)acos(DotProd(Normalize(-InVel),ZVec)); else theta = (float)acos(DotProd(Normalize(-InVel),MZVec)); if ((refvol>0.0f)==(dirapproach>0.0f)) maxref = -theta; else maxref = HalfPI-theta; refangle = maxref*(float)fabs(refvol); float frefangle = (float)fabs(refangle); if ((refvol>0.0f)==(dirapproach>0.0f)) maxvarref = HalfPI-theta-frefangle; else maxvarref = theta-frefangle; refangle += maxvarref*RND11()*refvar; Point3 c,d; if (theta<0.01f) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); d = Point3(xtmp,ytmp,ztmp); c = Normalize(InVel^d); } else { if (dirapproach>0.0f) c = Normalize(ZVec^(-InVel)); else c = Normalize(MZVec^(-InVel)); } RotateOnePoint(InVel,&Zero.x,&c.x,refangle); } float maxdiff,diffuse,diffvar,diffangle; obj->st->pbComplex->GetValue(PB_DIFFUSION,t,diffuse,FOREVER); // diffuse *= 0.01f; obj->st->pbComplex->GetValue(PB_DIFFUSIONVAR,t,diffvar,FOREVER); // diffvar *= 0.01f; maxdiff = HalfPI-theta-refangle; if (!FloatEQ0(diffuse)) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); Point3 d = Point3(xtmp,ytmp,ztmp); Point3 c = Normalize(InVel^d); diffangle = 0.5f*maxdiff*diffuse*(1.0f+RND11()*diffvar); RotateOnePoint(InVel,&Zero.x,&c.x,diffangle); } if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } // particle was neither reflected nor refracted nor tested for either! float spawnonly; obj->st->pbComplex->GetValue(PB_COLAFFECTS,t,spawnonly,FOREVER); // spawnonly *= 0.01f; if ((RND01()<spawnonly)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colp->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float passvel,passvelvar; obj->st->pbComplex->GetValue(PB_COLPASSVEL,t,passvel,FOREVER); obj->st->pbComplex->GetValue(PB_COLPASSVELVAR,t,passvelvar,FOREVER); // passvelvar *= 0.01f; InVel *= passvel*(1.0f+passvelvar*RND11()); float holddt = dt; dt -= at; if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } } } // PLANAR COLLISION CODE BLOCK ENDS HERE break; case SPHERE: // SPHERE COLLISION CODE BLOCK BEGINS HERE { ReferenceTarget *rt; obj->pblock2->GetValue(monoflect_colliders,t,rt,obj->tmValid); cols = (CollisionSphere *) rt; if (!((obj->mValid.InInterval(t))&&(obj->tmValid.InInterval(t)))) { obj->tmValid = FOREVER; obj->st->pblock2->GetValue(PB_WIDTH,t,width,obj->tmValid); if (cols) { cols->SetRadius(t,width); cols->SetNode(t,node); cols->PreFrame(t,(TimeValue) dt); } obj->st->pbComplex->GetValue(PB_BOUNCE,t,bounce,obj->tmValid); obj->st->pbComplex->GetValue(PB_BVAR,t,bvar,obj->tmValid); obj->st->pbComplex->GetValue(PB_CHAOS,t,chaos,obj->tmValid); obj->st->pbComplex->GetValue(PB_INHERVEL,t,vinher,obj->tmValid); obj->st->pbComplex->GetValue(PB_FRICTION,t,friction,obj->tmValid); // vinher *= 0.01f; // bvar *= 0.01f; // chaos *= 0.01f; // friction *= 0.01f; obj->st->pbComplex->GetValue(PB_DISTORTION,t,refvol,obj->tmValid); // refvol *= 0.01f; obj->st->pbComplex->GetValue(PB_DISTORTIONVAR,t,refvar,FOREVER); // refvar *= 0.01f; obj->st->pbComplex->GetValue(PB_PASSVEL,t,decel,FOREVER); obj->st->pbComplex->GetValue(PB_PASSVELVAR,t,decelvar,FOREVER); // decelvar *= 0.01f; Interval tmpValid = FOREVER; } if ((curtime!=t)&&(enableDynamics)) { totalforce = Zero; applyat = Zero; totalnumber = 0; curtime = t; } float fstartt,fendt; TimeValue startt,endt; obj->st->pbComplex->GetValue(PB_TIMEON,t,fstartt,FOREVER); obj->st->pbComplex->GetValue(PB_TIMEOFF,t,fendt,FOREVER); startt=fstartt*GetTicksPerFrame();endt=fendt*GetTicksPerFrame(); if ((t<startt)||(t>endt)) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } if (!cols) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } else { srand(obj->lastrnd); float reflects; obj->st->pbComplex->GetValue(PB_REFLECTS,t,reflects,FOREVER); // reflects *= 0.01f; if (RND01()<reflects) { donewithparticle = TRUE; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = cols->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float rvariation = 1.0f; float rchaos = 1.0f; if (bvar != 0.0f) { rvariation =1.0f-( bvar * randomFloat[index%500]); } if (chaos != 0.0f) { rchaos =1.0f-( chaos * randomFloat[index%500]); } vel = bnorm*(bounce*rvariation) + frict*(1.0f-(friction*rchaos)) + (inheritedVel * vinher); inp = hitpoint; if (UpdatePastCollide) { inp += vel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } vel += (inheritedVel * vinher); InVel = vel; applyat = hitpoint; } // particle was not reflected and not tested for refraction! float refracts; obj->st->pbComplex->GetValue(PB_REFRACTS,t,refracts,FOREVER); // refracts *= 0.01f; if ((RND01()<refracts)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = cols->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float q1 = DotProd(-InVel,bnorm); float theta = (float)acos(q1); if (theta>=HalfPI) theta -= PI; InVel *= decel*(1.0f-decelvar*RND01()); float maxref,refangle,maxvarref; refangle = 0.0f; if (!FloatEQ0(refvol)) { if (refvol>0.0f) maxref = -theta; else maxref = HalfPI-theta; refangle = maxref*(float)fabs(refvol); float frefangle = (float)fabs(refangle); if (refvol>0.0f) maxvarref = HalfPI-theta-frefangle; else maxvarref = theta-frefangle; refangle += maxvarref*RND11()*refvar; Point3 c,d; if (theta<0.01f) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); d = Point3(xtmp,ytmp,ztmp); c = Normalize(InVel^d); } else c = Normalize(bnorm^(-InVel)); RotateOnePoint(InVel,&Zero.x,&c.x,refangle); } float maxdiff,diffuse,diffvar,diffangle; obj->st->pbComplex->GetValue(PB_DIFFUSION,t,diffuse,FOREVER); // diffuse *= 0.01f; obj->st->pbComplex->GetValue(PB_DIFFUSIONVAR,t,diffvar,FOREVER); // diffvar *= 0.01f; maxdiff = HalfPI-theta-refangle; if (!FloatEQ0(diffuse)) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); Point3 d = Point3(xtmp,ytmp,ztmp); Point3 c = Normalize(InVel^d); diffangle = 0.5f*maxdiff*diffuse*(1.0f+RND11()*diffvar); RotateOnePoint(InVel,&Zero.x,&c.x,diffangle); } if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } // particle was neither reflected nor refracted nor tested for either! float spawnonly; obj->st->pbComplex->GetValue(PB_COLAFFECTS,t,spawnonly,FOREVER); // spawnonly *= 0.01f; if ((RND01()<spawnonly)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = cols->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float passvel,passvelvar; obj->st->pbComplex->GetValue(PB_COLPASSVEL,t,passvel,FOREVER); obj->st->pbComplex->GetValue(PB_COLPASSVELVAR,t,passvelvar,FOREVER); // passvelvar *= 0.01f; InVel *= passvel*(1.0f+passvelvar*RND11()); float holddt = dt; dt -= at; if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } } } // SPHERE COLLISION CODE BLOCK ENDS HERE break; case MESH: // MESH COLLISION CODE BLOCK BEGINS HERE { if (badmesh) { obj->ReturnThreeStateValue = DONTCARE; return(0); } Point3 iw; ReferenceTarget *rt; obj->pblock2->GetValue(monoflect_colliderm,t,rt,obj->tmValid); colm = (CollisionMesh *) rt; if (!((obj->mValid.InInterval(t))&&(obj->tmValid.InInterval(t)))) { obj->tmValid = FOREVER; if (colm) colm->SetNode(t,obj->custnode); if (colm) colm->PreFrame(t,(TimeValue) dt); obj->tm = obj->custnode->GetObjectTM(t,&obj->tmValid); obj->tmNoTrans = obj->tm; obj->tmNoTrans.NoTrans(); obj->invtm = Inverse(obj->tm); obj->invtmNoTrans = Inverse(obj->tmNoTrans); obj->st->pbComplex->GetValue(PB_BOUNCE,t,bounce,obj->tmValid); obj->st->pbComplex->GetValue(PB_BVAR,t,bvar,obj->tmValid); obj->st->pbComplex->GetValue(PB_CHAOS,t,chaos,obj->tmValid); obj->st->pbComplex->GetValue(PB_INHERVEL,t,vinher,obj->tmValid); obj->st->pbComplex->GetValue(PB_FRICTION,t,friction,obj->tmValid); obj->st->pbComplex->GetValue(PB_DISTORTION,t,refvol,obj->tmValid); obj->st->pbComplex->GetValue(PB_DISTORTIONVAR,t,refvar,obj->tmValid); obj->st->pbComplex->GetValue(PB_PASSVEL,t,decel,obj->tmValid); obj->st->pbComplex->GetValue(PB_PASSVELVAR,t,decelvar,obj->tmValid); // vinher *= 0.01f; // bvar *= 0.01f; // chaos *= 0.01f; // friction *= 0.01f; if (obj->dmesh) delete obj->dmesh; obj->dmesh = new Mesh; obj->dmesh->setNumFaces(0); if (obj->vnorms) { delete[] obj->vnorms; obj->vnorms=NULL; } if (obj->fnorms) { delete[] obj->fnorms; obj->fnorms=NULL; } obj->nv = (obj->nf=0); Interval tmpValid=FOREVER; obj->ptm = obj->custnode->GetObjectTM(t+(TimeValue)dt,&tmpValid); obj->dvel = (Zero*obj->ptm-Zero*obj->tm)/dt; Object *pobj; pobj = obj->custnode->EvalWorldState(t).obj; obj->mValid = pobj->ObjectValidity(t); TriObject *triOb=NULL; badmesh = TRUE; if ((triOb=IsUseable(pobj,t))!=NULL) AddMesh(obj,triOb,obj->tm,FALSE); if (obj->custnode->IsGroupHead()) { for (int ch=0;ch<obj->custnode->NumberOfChildren();ch++) { INode *cnode=obj->custnode->GetChildNode(ch); if (cnode->IsGroupMember()) { pobj = cnode->EvalWorldState(t).obj; if ((triOb=IsUseable(pobj,t))!=NULL) { Matrix3 tm=cnode->GetObjectTM(t,&obj->tmValid); obj->mValid=obj->mValid & pobj->ObjectValidity(t); AddMesh(obj,triOb,tm,TRUE); } } } } if (obj->nf>0) { obj->vnorms=new MaxSDK::VertexNormal[obj->nv]; obj->fnorms=new Point3[obj->nf]; GetVFLst(obj->dmesh,obj->vnorms,obj->fnorms); badmesh=FALSE; } if ((triOb)&&(triOb!=pobj)) triOb->DeleteThis(); } if (badmesh) { obj->ReturnThreeStateValue = DONTCARE; return 0; } if ((curtime!=t)&&(enableDynamics)) { totalforce = Zero; applyat = Zero; totalnumber = 0; curtime = t; } float fstartt,fendt; TimeValue startt,endt; obj->st->pbComplex->GetValue(PB_TIMEON,t,fstartt,FOREVER); obj->st->pbComplex->GetValue(PB_TIMEOFF,t,fendt,FOREVER); startt=fstartt*GetTicksPerFrame();endt=fendt*GetTicksPerFrame(); if ((t<startt)||(t>endt)) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } if (!colm) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = DONTCARE; return FALSE; } else { srand(obj->lastrnd); float TempDP; float reflects; obj->st->pbComplex->GetValue(PB_REFLECTS,t,reflects,FOREVER); // reflects *= 0.01f; if (RND01()<reflects) { donewithparticle = TRUE; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colm->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float holddt = dt; dt -= at; float rvariation = 1.0f; float rchaos = 1.0f; if (bvar != 0.0f) { rvariation = 1.0f - (bvar * randomFloat[index%500]); } if (chaos != 0.0f) { rchaos = 1.0f - (chaos * randomFloat[index%500]); } vel = bnorm*(bounce*rvariation) + frict*(1.0f-(friction*rchaos)) ; inp = hitpoint; if (UpdatePastCollide) { inp += vel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } vel += (inheritedVel * vinher); InVel = vel; applyat = hitpoint; } // particle was not reflected and not tested for refraction! float refracts; obj->st->pbComplex->GetValue(PB_REFRACTS,t,refracts,FOREVER); // refracts *= 0.01f; if ((RND01()<refracts)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colm->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } Point3 c2,c1; Point3 Vdirbase = Normalize(InVel); float q1 = DotProd(-Vdirbase,bnorm); float theta=(float)acos(q1); if (theta>=HalfPI) theta-=PI; c1 = Normalize((-InVel)^bnorm); c2=Normalize(bnorm^c1); Point3 Drag = friction*c2*DotProd(c2,-InVel); InVel *= decel*(1.0f-decelvar*RND01()); // rotate velocity vector float maxref,refangle,maxvarref; refangle = 0.0f; if (!FloatEQ0(refvol)) { if (refvol>0.0f) maxref = -theta; else maxref = HalfPI-theta; refangle = maxref*(float)fabs(refvol); float frefangle = (float)fabs(refangle); if (refvol>0.0f) maxvarref = HalfPI-theta-frefangle; else maxvarref = theta-frefangle; refangle += maxvarref*RND11()*refvar; Point3 c,d; if (theta<0.01f) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); d = Point3(xtmp,ytmp,ztmp); c = Normalize(InVel^d); } else { c = Normalize(bnorm^(-InVel)); } RotateOnePoint(InVel,&Zero.x,&c.x,refangle); TempDP = DotProd(InVel,bnorm); if (TempDP>0.0f) InVel = InVel - TempDP*bnorm; } float maxdiff,diffuse,diffvar,diffangle; obj->st->pbComplex->GetValue(PB_DIFFUSION,t,diffuse,FOREVER); // diffuse *= 0.01f; obj->st->pbComplex->GetValue(PB_DIFFUSIONVAR,t,diffvar,FOREVER); // diffvar *= 0.01f; maxdiff = HalfPI-theta-refangle; if (!FloatEQ0(diffuse)) { // Martell 4/14/01: Fix for order of ops bug. float ztmp=RND11(); float ytmp=RND11(); float xtmp=RND11(); Point3 d = Point3(xtmp,ytmp,ztmp); Point3 c = Normalize(InVel^d); diffangle = 0.5f*maxdiff*diffuse*(1.0f+RND11()*diffvar); RotateOnePoint(InVel,&Zero.x,&c.x,diffangle); TempDP = DotProd(InVel,bnorm); if (TempDP>0.0f) InVel = InVel - TempDP*bnorm; } float holddt = dt; dt -= at; inp = hitpoint; if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } // particle was neither reflected nor refracted nor tested for either! float spawnonly; obj->st->pbComplex->GetValue(PB_COLAFFECTS,t,spawnonly,FOREVER); // spawnonly *= 0.01f; if ((RND01()<spawnonly)&&(!donewithparticle)&&(enableAdvanced)) { donewithparticle = TRUE; InVel = vel; Point3 hitpoint,bnorm,frict,inheritedVel; float at; BOOL hit = colm->CheckCollision(t,inp,vel,dt,at,hitpoint,bnorm,frict,inheritedVel); if (!hit) { obj->lastrnd=rand(); obj->ReturnThreeStateValue = 0; return FALSE; } float passvel,passvelvar; obj->st->pbComplex->GetValue(PB_COLPASSVEL,t,passvel,FOREVER); obj->st->pbComplex->GetValue(PB_COLPASSVELVAR,t,passvelvar,FOREVER); // passvelvar *= 0.01f; InVel *= passvel*(1.0f+passvelvar*RND11()); float holddt = dt; dt -= at; inp = hitpoint; if (UpdatePastCollide) { inp += InVel * dt; //uses up the rest of the time with the new velocity if (ct) (*ct) = holddt; } else { if (ct) (*ct) = at; } InVel += (inheritedVel * vinher); vel = InVel; applyat = hitpoint; } } } // MESH COLLISION CODE BLOCK ENDS HERE break; } if (donewithparticle) { if (enableDynamics) { float mass = 0.001f; if (t==obj->ctime) { totalnumber += 1; totalforce += (SaveVel-InVel)*K*mass/stepsize; obj->ffdata.FlectForce += totalforce; obj->ffdata.ApplyAt = applyat; obj->ffdata.Num = totalnumber; } } obj->ReturnThreeStateValue = 1; obj->lastrnd = rand(); return TRUE; } else { obj->ReturnThreeStateValue = DONTCARE; obj->lastrnd=rand(); return FALSE; } } void BasicFlectorObj::InvalidateUI() { BasicFlectorPB.InvalidateUI(pblock2->LastNotifyParamID()); BasicFComplexPB.InvalidateUI(pbComplex->LastNotifyParamID()); } void BasicFlectorObj::BeginEditParams( IObjParam *ip, ULONG flags,Animatable *prev ) { this->ip = ip; if (flags & BEGIN_EDIT_CREATE) { creating = TRUE; } else { creating = FALSE; } SimpleWSMObject2::BeginEditParams(ip,flags,prev); if (!pmap[pbType_subani]) { pmap[pbType_subani] = CreateCPParamMap2(pblock2,ip,hInstance,MAKEINTRESOURCE(IDD_MF_0100_FLECTTYPESELECT),GetString(IDS_DLG_FTYPE),0); } pmap[pbType_subani]->SetUserDlgProc(new BasicFlectorTypeObjDlgProc(this)); pmap[pbType_subani]->SetParamBlock(GetParamBlockByID(pbType_subani)); int oldval; pblock2->GetValue(PB_TYPE,pbType_subani,oldval,FOREVER); if (!st->theParam[pbType_subani]) st->CreateMonoFlectorParamDlg(ip,oldval,pbType_subani); else st->pmap[pbType_subani]->SetParamBlock(st->GetParamBlockByID(pbType_subani)); if (!pmap[pbComplex_subani]) { pmap[pbComplex_subani] = CreateCPParamMap2(pbComplex,ip,hInstance,MAKEINTRESOURCE(IDD_MF_0200_FLECTCOMPLEXITYSELECT),GetString(IDS_DLG_FCOMPLEX),0); } pmap[pbComplex_subani]->SetUserDlgProc(new BasicFlectorComplexDlgProc(this)); pmap[pbComplex_subani]->SetParamBlock(GetParamBlockByID(pbComplex_subani)); pbComplex->GetValue(PB_COMPLEX,pbComplex_subani,oldval,FOREVER); if (!st->theParam[pbComplex_subani]) st->CreateMonoFlectorParamDlg(ip,oldval,pbComplex_subani); else st->pmap[pbComplex_subani]->SetParamBlock(st->GetParamBlockByID(pbComplex_subani)); } void Reinit(IParamMap2Ptr *pm,TimeValue t) { ParamBlockDesc2* pbd = (*pm)->GetDesc(); if (!(pbd->flags & P_CLASS_PARAMS)) for (int i = 0; i < pbd->count; i++) { ParamDef& pd = pbd->paramdefs[i]; if (!(pd.flags & P_RESET_DEFAULT)) switch (pd.type) { case TYPE_ANGLE: case TYPE_PCNT_FRAC: case TYPE_WORLD: case TYPE_COLOR_CHANNEL: case TYPE_FLOAT: pd.cur_def.f = (*pm)->GetParamBlock()->GetFloat(pd.ID, t); pd.flags |= P_HAS_CUR_DEFAULT; break; case TYPE_BOOL: case TYPE_TIMEVALUE: case TYPE_RADIOBTN_INDEX: case TYPE_INT: pd.cur_def.i = (*pm)->GetParamBlock()->GetInt(pd.ID, t); pd.flags |= P_HAS_CUR_DEFAULT; break; case TYPE_HSV: case TYPE_RGBA: case TYPE_POINT3: { if (pd.cur_def.p != NULL) delete pd.cur_def.p; pd.cur_def.p = new Point3((*pm)->GetParamBlock()->GetPoint3(pd.ID, t)); pd.flags |= P_HAS_CUR_DEFAULT; break; } case TYPE_STRING: { const TCHAR* s = (*pm)->GetParamBlock()->GetStr(pd.ID, t); if (s != NULL) { pd.cur_def.ReplaceString(s); pd.flags |= P_HAS_CUR_DEFAULT; } break; } case TYPE_FILENAME: { const TCHAR* s = (*pm)->GetParamBlock()->GetStr(pd.ID, t); if (s != NULL) { if (pd.cur_def.s != NULL) { MaxSDK::AssetManagement::IAssetManager::GetInstance()->ReleaseReference(pd.cur_def.s); } pd.cur_def.ReplaceString(s); if (s) MaxSDK::AssetManagement::IAssetManager::GetInstance()->AddReference(s); pd.flags |= P_HAS_CUR_DEFAULT; } break; } } } } void BasicFlectorObj::EndEditParams( IObjParam *ip, ULONG flags,Animatable *next ) { SimpleWSMObject2::EndEditParams(ip,flags,next); ip->ClearPickMode(); this->ip = NULL; if (flags & END_EDIT_REMOVEUI ) { if (pmap[pbType_subani]) { DestroyCPParamMap2(pmap[pbType_subani]); pmap[pbType_subani]=NULL; } if (pmap[pbComplex_subani]) { DestroyCPParamMap2(pmap[pbComplex_subani]); pmap[pbComplex_subani]=NULL; } } else { if (pmap[pbType_subani]) pmap[pbType_subani]->SetUserDlgProc(nullptr); if (pmap[pbComplex_subani]) pmap[pbComplex_subani]->SetUserDlgProc(nullptr); } creating=FALSE; } IOResult BasicFlectorObj::Save(ISave *isave) { isave->BeginChunk(MONODEF_CUSTNAME_CHUNK); isave->WriteWString(custname); isave->EndChunk(); return IO_OK; } class BasicFlectorObjLoad : public PostLoadCallback { public: BasicFlectorObj *n; BasicFlectorObjLoad(BasicFlectorObj *ns) {n = ns;} void proc(ILoad *iload) { ReferenceTarget *rt; Interval iv; n->pblock2->GetValue(monoflect_colliderp,0,rt,iv); if (rt == NULL) { CollisionPlane *colp = (CollisionPlane*)CreateInstance(REF_MAKER_CLASS_ID, PLANAR_COLLISION_ID); if (colp) n->pblock2->SetValue(monoflect_colliderp,0,(ReferenceTarget*)colp); } n->pblock2->GetValue(monoflect_colliders,0,rt,iv); if (rt == NULL) { CollisionSphere *cols = (CollisionSphere*)CreateInstance(REF_MAKER_CLASS_ID, SPHERICAL_COLLISION_ID); if (cols) n->pblock2->SetValue(monoflect_colliders,0,(ReferenceTarget*)cols); } n->pblock2->GetValue(monoflect_colliderm,0,rt,iv); if (rt == NULL) { CollisionMesh *colm = (CollisionMesh*)CreateInstance(REF_MAKER_CLASS_ID, MESH_COLLISION_ID); if (colm) n->pblock2->SetValue(monoflect_colliderm,0,(ReferenceTarget*)colm); } delete this; } }; IOResult BasicFlectorObj::Load(ILoad *iload) { IOResult res = IO_OK; // Default names custname = _T(" "); while (IO_OK==(res=iload->OpenChunk())) { switch (iload->CurChunkID()) { case MONODEF_CUSTNAME_CHUNK: { TCHAR *buf; res=iload->ReadWStringChunk(&buf); custname = TSTR(buf); break; } } iload->CloseChunk(); if (res!=IO_OK) return res; } iload->RegisterPostLoadCallback(new BasicFlectorObjLoad(this)); return IO_OK; } FlectForces BasicFlectorObj::ForceData(TimeValue t) { float ft1,ft2; pbComplex->GetValue(PB_TIMEON,t,ft1,FOREVER); pbComplex->GetValue(PB_TIMEOFF,t,ft2,FOREVER); ffdata.t1=ft1*GetTicksPerFrame();ffdata.t2=ft2*GetTicksPerFrame(); return ffdata; } RefTargetHandle BasicFlectorObj::Clone(RemapDir& remap) { BasicFlectorObj* newob = new BasicFlectorObj(); if (pblock2) newob->ReplaceReference(pbType_subani, remap.CloneRef(pblock2)); if (pbComplex) newob->ReplaceReference(pbComplex_subani, remap.CloneRef(pbComplex)); if (st) newob->ReplaceReference(monoflecdlg, remap.CloneRef(st)); // if (custnode) // newob->ReplaceReference(CUSTNODE,custnode); newob->custname=custname; newob->dmesh=NULL; newob->vnorms=NULL; newob->fnorms=NULL; newob->ivalid.SetEmpty(); BaseClone(this, newob, remap); return(newob); } BOOL BasicFlectorObj::OKtoDisplay(TimeValue t) { float size; st->pblock2->GetValue(PB_WIDTH,t,size,FOREVER); if (size==0.0f) return FALSE; else return TRUE; } /*int BasicFlectorObj::IntersectRay(TimeValue t, Ray& ray, float& at, Point3& norm) { // pass to SimpleObject to do this return SimpleWSMObject2::IntersectRay(t, ray, at, norm); }*/ int BasicFlectorObj::CanConvertToType(Class_ID obtype) { return FALSE; } int CreateBasicFlectorProc::createmethod( ViewExp *vpt,int msg, int point, int flags, IPoint2 m, Matrix3& mat) { if ( ! vpt || ! vpt->IsAlive() ) { // why are we here DbgAssert(!_T("Invalid viewport!")); return FALSE; } Point3 p1, center; DWORD snapdim = SNAP_IN_3D; if (msg == MOUSE_FREEMOVE) { vpt->SnapPreview(m, m, NULL, snapdim); } if (msg==MOUSE_POINT||msg==MOUSE_MOVE) { switch(point) { // point one - where we measure from case 0: GetCOREInterface()->SetHideByCategoryFlags( GetCOREInterface()->GetHideByCategoryFlags() & ~(HIDE_OBJECTS|HIDE_PARTICLES)); sp0 = m; p0 = vpt->SnapPoint(m, m, NULL, snapdim); BasicFlectorObject->st->pblock2->SetValue(PB_WIDTH,0,0.01f); BasicFlectorObject->st->pblock2->SetValue(PB_LENGTH,0,0.01f); p1 = p0 + Point3(.01,.01,.01); mat.SetTrans(float(.5)*(p0+p1)); BasicFlectorObject->st->pmap[pbType_subani]->Invalidate(); break; // point two - where we measure to in worldspace case 1: sp1 = m; p1 = vpt->SnapPoint(m, m, NULL, snapdim); p1.z = p0.z +(float).01; // if(flags&MOUSE_CTRL) // { mat.SetTrans(p0); // } // else mat.SetTrans(float(.5)*(p0+p1)); Point3 d = p1-p0; float len; if (fabs(d.x) > fabs(d.y)) len = d.x; else len = d.y; d.x = d.y = 2.0f * len; BasicFlectorObject->st->pblock2->SetValue(PB_WIDTH,0,(float)fabs(p1.x-p0.x)); BasicFlectorObject->st->pblock2->SetValue(PB_LENGTH,0,(float)fabs(p1.y-p0.y)); BasicFlectorObject->st->pmap[pbType_subani]->Invalidate(); if (msg==MOUSE_POINT) { if (Length(sp1-sp0)<3 || Length(d)<0.1f) return CREATE_ABORT; else { return CREATE_STOP; } } break; } } else { if (msg == MOUSE_ABORT) return CREATE_ABORT; } return TRUE; } BOOL BasicFlectorObj::SupportsDynamics() { int supportsdynamics; pbComplex->GetValue(PB_COMPLEX,0,supportsdynamics,ivalid); return (supportsdynamics>1); } void BasicFlectorObj::BuildMesh(TimeValue t) { int typeofdeflector; pblock2->GetValue(PB_TYPE,0,typeofdeflector,ivalid); float sz0,sz1; ivalid = FOREVER; st->pblock2->GetValue(PB_WIDTH,t,sz0,ivalid); sz0 *= 0.5f; st->pblock2->GetValue(PB_LENGTH,t,sz1,ivalid); sz1 *= 0.5f; switch(typeofdeflector) { case PLANAR: { float w, h; float w2,h2,h3,h4; ivalid = FOREVER; w = sz0; w2=w*0.5f; h = sz1; h2=h*0.5f; h3=h2*0.15f; h4=h2*0.25f; mesh.setNumVerts(19); mesh.setNumFaces(11); mesh.setVert(0, Point3(-w,-h, 0.0f)); mesh.setVert(1, Point3( w,-h, 0.0f)); mesh.setVert(2, Point3( w, h, 0.0f)); mesh.setVert(3, Point3(-w, h, 0.0f)); mesh.setVert( 4, Point3(0.0f,0.0f,0.0f)); mesh.setVert( 5, Point3(0.0f, h2, h2)); mesh.setVert( 6, Point3(0.0f, -h2, h2)); mesh.setVert( 7, Point3(0.0f, h2+h3, h2)); mesh.setVert( 8, Point3(0.0f, h2, h2+h3)); mesh.setVert( 9, Point3(0.0f, -h2, h2-h3)); mesh.setVert(10, Point3(0.0f, -h2+h3, h2)); mesh.setVert(11, Point3(0.0f, h4, 0.0f)); mesh.setVert(12, Point3(0.0f, h4, -h2)); mesh.setVert(13, Point3(0.0f, h4+h3, -h2)); mesh.setVert(14, Point3(0.0f, 0.0f, -h2-h3-h3)); mesh.setVert(15, Point3(0.0f,-h4-h3, -h2)); mesh.setVert(16, Point3(0.0f,-h4, -h2)); mesh.setVert(17, Point3(0.0f,-h4, 0.0f)); mesh.setVert(18, Point3(0.0f,0.0f,-h4)); mesh.faces[0].setEdgeVisFlags(1,1,0); mesh.faces[0].setSmGroup(1); mesh.faces[0].setVerts(0,1,2); mesh.faces[1].setEdgeVisFlags(1,1,0); mesh.faces[1].setSmGroup(1); mesh.faces[1].setVerts(2,3,0); mesh.faces[2].setEdgeVisFlags(1,0,1); mesh.faces[2].setSmGroup(1); mesh.faces[2].setVerts(4,6,5); mesh.faces[3].setEdgeVisFlags(1,0,1); mesh.faces[3].setSmGroup(1); mesh.faces[3].setVerts(6,9,10); mesh.faces[4].setEdgeVisFlags(1,0,1); mesh.faces[4].setSmGroup(1); mesh.faces[4].setVerts(5,8,7); mesh.faces[5].setEdgeVisFlags(1,0,1); mesh.faces[5].setSmGroup(1); mesh.faces[5].setVerts(11,12,18); mesh.faces[6].setEdgeVisFlags(0,0,0); mesh.faces[6].setSmGroup(1); mesh.faces[6].setVerts(12,16,18); mesh.faces[7].setEdgeVisFlags(1,1,0); mesh.faces[7].setSmGroup(1); mesh.faces[7].setVerts(16,17,18); mesh.faces[8].setEdgeVisFlags(1,1,0); mesh.faces[8].setSmGroup(1); mesh.faces[8].setVerts(12,13,14); mesh.faces[9].setEdgeVisFlags(0,0,0); mesh.faces[9].setSmGroup(1); mesh.faces[9].setVerts(12,14,16); mesh.faces[10].setEdgeVisFlags(1,1,0); mesh.faces[10].setSmGroup(1); mesh.faces[10].setVerts(14,15,16); mesh.InvalidateGeomCache(); return; } case SPHERE: { float r,r2,r3,r4,u; #define NUM_SEGS 24 r = 2.0f * sz0; r2=0.5f*r; r3=0.15f*r2; r4=0.25f*r2; mesh.setNumVerts(3*NUM_SEGS+16); mesh.setNumFaces(3*NUM_SEGS+9); for (int i=0; i<NUM_SEGS; i++) { u=float(i)/float(NUM_SEGS) * TWOPI; mesh.setVert(i, Point3((float)cos(u) * r, (float)sin(u) * r, 0.0f)); } for (int i=0; i<NUM_SEGS; i++) { u=float(i)/float(NUM_SEGS) * TWOPI; mesh.setVert(i+NUM_SEGS, Point3(0.0f, (float)cos(u) * r, (float)sin(u) * r)); } for (int i=0; i<NUM_SEGS; i++) { u=float(i)/float(NUM_SEGS) * TWOPI; mesh.setVert(i+2*NUM_SEGS, Point3((float)cos(u) * r, 0.0f, (float)sin(u) * r)); } mesh.setVert(72, Point3(0.0f,0.0f,0.0f)); mesh.setVert(73, Point3(0.0f,0.0f, r )); mesh.setVert(74, Point3(0.0f, r2 ,r+r2)); mesh.setVert(75, Point3(0.0f,-r2 ,r+r2)); mesh.setVert(76, Point3(0.0f, r2+r3,r+r2)); mesh.setVert(77, Point3(0.0f, r2,r+r2+r3)); mesh.setVert(78, Point3(0.0f,-r2,r+r2-r3)); mesh.setVert(79, Point3(0.0f,-r2+r3,r+r2)); mesh.setVert(80, Point3(0.0f, r4 ,-r )); mesh.setVert(81, Point3(0.0f, r4 ,-r-r2)); mesh.setVert(82, Point3(0.0f, r4+r3,-r-r2)); mesh.setVert(83, Point3(0.0f,0.0f ,-r-r2-r3-r3)); mesh.setVert(84, Point3(0.0f,-r4-r3,-r-r2)); mesh.setVert(85, Point3(0.0f,-r4 ,-r-r2)); mesh.setVert(86, Point3(0.0f,-r4 ,-r)); mesh.setVert(87, Point3(0.0f,0.0f ,-r-r4)); for (int i=0; i<3*NUM_SEGS; i++) { int i1 = i+1; if (i1%NUM_SEGS==0) i1 -= NUM_SEGS; mesh.faces[i].setEdgeVisFlags(1,0,0); mesh.faces[i].setSmGroup(1); mesh.faces[i].setVerts(i,i1,3*NUM_SEGS); } mesh.faces[72].setEdgeVisFlags(1,0,1); mesh.faces[72].setSmGroup(1); mesh.faces[72].setVerts(73,75,74); mesh.faces[73].setEdgeVisFlags(1,0,1); mesh.faces[73].setSmGroup(1); mesh.faces[73].setVerts(75,78,79); mesh.faces[74].setEdgeVisFlags(1,0,1); mesh.faces[74].setSmGroup(1); mesh.faces[74].setVerts(74,77,76); mesh.faces[75].setEdgeVisFlags(1,0,1); mesh.faces[75].setSmGroup(1); mesh.faces[75].setVerts(80,81,87); mesh.faces[76].setEdgeVisFlags(0,0,0); mesh.faces[76].setSmGroup(1); mesh.faces[76].setVerts(81,85,87); mesh.faces[77].setEdgeVisFlags(1,1,0); mesh.faces[77].setSmGroup(1); mesh.faces[77].setVerts(85,86,87); mesh.faces[78].setEdgeVisFlags(1,1,0); mesh.faces[78].setSmGroup(1); mesh.faces[78].setVerts(81,82,83); mesh.faces[79].setEdgeVisFlags(0,0,0); mesh.faces[79].setSmGroup(1); mesh.faces[79].setVerts(81,83,85); mesh.faces[80].setEdgeVisFlags(1,1,0); mesh.faces[80].setSmGroup(1); mesh.faces[80].setVerts(83,84,85); mesh.InvalidateGeomCache(); return; } case MESH: { int shouldIhide; st->pblock2->GetValue(PB_HIDEICON,0,shouldIhide,ivalid); if (shouldIhide) { mesh.setNumVerts(0); mesh.setNumFaces(0); mesh.InvalidateGeomCache(); return; } else { float l,h2,h3,h4; l = sz0; h2=l*0.5f; h3=h2*0.15f; h4=h2*0.25f; mesh.setNumVerts(23); mesh.setNumFaces(21); mesh.setVert(0,Point3( l, l, l)); mesh.setVert(1,Point3( l, l,-l)); mesh.setVert(2,Point3( l,-l, l)); mesh.setVert(3,Point3( l,-l,-l)); mesh.setVert(4,Point3(-l, l, l)); mesh.setVert(5,Point3(-l, l,-l)); mesh.setVert(6,Point3(-l,-l, l)); mesh.setVert(7,Point3(-l,-l,-l)); mesh.setVert( 8, Point3(0.0f,0.0f,l)); mesh.setVert( 9, Point3(0.0f, h2,l+h2)); mesh.setVert(10, Point3(0.0f, -h2,l+h2)); mesh.setVert(11, Point3(0.0f, h2+h3,l+h2)); mesh.setVert(12, Point3(0.0f, h2,l+h2+h3)); mesh.setVert(13, Point3(0.0f, -h2,l+h2-h3)); mesh.setVert(14, Point3(0.0f, -h2+h3,l+h2)); mesh.setVert(15, Point3(0.0f, h4, -l)); mesh.setVert(16, Point3(0.0f, h4, -h2-l)); mesh.setVert(17, Point3(0.0f, h4+h3, -h2-l)); mesh.setVert(18, Point3(0.0f, 0.0f, -h2-h3-h3-l)); mesh.setVert(19, Point3(0.0f,-h4-h3, -h2-l)); mesh.setVert(20, Point3(0.0f,-h4, -h2-l)); mesh.setVert(21, Point3(0.0f,-h4, -l)); mesh.setVert(22, Point3(0.0f,0.0f,-h4-l)); mesh.faces[0].setVerts(1,0,2); mesh.faces[0].setEdgeVisFlags(1,1,0); mesh.faces[0].setSmGroup(0); mesh.faces[1].setVerts(2,3,1); mesh.faces[1].setEdgeVisFlags(1,1,0); mesh.faces[1].setSmGroup(0); mesh.faces[2].setVerts(2,0,4); mesh.faces[2].setEdgeVisFlags(1,1,0); mesh.faces[2].setSmGroup(1); mesh.faces[3].setVerts(4,6,2); mesh.faces[3].setEdgeVisFlags(1,1,0); mesh.faces[3].setSmGroup(1); mesh.faces[4].setVerts(3,2,6); mesh.faces[4].setEdgeVisFlags(1,1,0); mesh.faces[4].setSmGroup(2); mesh.faces[5].setVerts(6,7,3); mesh.faces[5].setEdgeVisFlags(1,1,0); mesh.faces[5].setSmGroup(2); mesh.faces[6].setVerts(7,6,4); mesh.faces[6].setEdgeVisFlags(1,1,0); mesh.faces[6].setSmGroup(3); mesh.faces[7].setVerts(4,5,7); mesh.faces[7].setEdgeVisFlags(1,1,0); mesh.faces[7].setSmGroup(3); mesh.faces[8].setVerts(4,0,1); mesh.faces[8].setEdgeVisFlags(1,1,0); mesh.faces[8].setSmGroup(4); mesh.faces[9].setVerts(1,5,4); mesh.faces[9].setEdgeVisFlags(1,1,0); mesh.faces[9].setSmGroup(4); mesh.faces[10].setVerts(1,3,7); mesh.faces[10].setEdgeVisFlags(1,1,0); mesh.faces[10].setSmGroup(5); mesh.faces[11].setVerts(7,5,1); mesh.faces[11].setEdgeVisFlags(1,1,0); mesh.faces[11].setSmGroup(5); mesh.faces[12].setEdgeVisFlags(1,0,1); mesh.faces[12].setSmGroup(1); mesh.faces[12].setVerts(8,10,9); mesh.faces[13].setEdgeVisFlags(1,0,1); mesh.faces[13].setSmGroup(1); mesh.faces[13].setVerts(10,13,14); mesh.faces[14].setEdgeVisFlags(1,0,1); mesh.faces[14].setSmGroup(1); mesh.faces[14].setVerts(9,12,11); mesh.faces[15].setEdgeVisFlags(1,0,1); mesh.faces[15].setSmGroup(1); mesh.faces[15].setVerts(15,16,22); mesh.faces[16].setEdgeVisFlags(0,0,0); mesh.faces[16].setSmGroup(1); mesh.faces[16].setVerts(16,20,22); mesh.faces[17].setEdgeVisFlags(1,1,0); mesh.faces[17].setSmGroup(1); mesh.faces[17].setVerts(20,21,22); mesh.faces[18].setEdgeVisFlags(1,1,0); mesh.faces[18].setSmGroup(1); mesh.faces[18].setVerts(16,17,18); mesh.faces[19].setEdgeVisFlags(0,0,0); mesh.faces[19].setSmGroup(1); mesh.faces[19].setVerts(16,18,20); mesh.faces[20].setEdgeVisFlags(1,1,0); mesh.faces[20].setSmGroup(1); mesh.faces[20].setVerts(18,19,20); mesh.InvalidateGeomCache(); return; } } } } BOOL BasicFlectorObj::HasUVW() { BOOL genUVs = FALSE; // pblock2->GetValue(particlepodobj_genuv, 0, genUVs, FOREVER); return genUVs; } void BasicFlectorObj::SetGenUVW(BOOL sw) { if (sw==HasUVW()) return; // pblock2->SetValue(particlepodobj_genuv, 0, sw); } Animatable* BasicFlectorObj::SubAnim(int i) { switch(i) { // paramblock2s case pbType_subani: return pblock2; case pbComplex_subani: return pbComplex; case monoflecdlg: return st; default: return 0; } } void BasicFlectorObj::SetReference(int i, RefTargetHandle rtarg) { switch(i) { case pbType_subani: SimpleWSMObject2::SetReference(i, rtarg); break; case pbComplex_subani: pbComplex=(IParamBlock2*)rtarg; break; case monoflecdlg: st=(MonoFlector*)rtarg; break; } } RefTargetHandle BasicFlectorObj::GetReference(int i) { switch(i) { // paramblock2s case pbType_subani: return SimpleWSMObject2::GetReference(i); case pbComplex_subani: return pbComplex; case monoflecdlg: return st; default: return 0; } } TSTR BasicFlectorObj::SubAnimName(int i) { switch(i) { case pbType_subani: return GetString(IDS_DLG_FTYPE); case pbComplex_subani: return GetString(IDS_DLG_FCOMPLEX); case monoflecdlg: return GetString(IDS_DLG_MONOF); default: return _T(""); } } IParamBlock2* BasicFlectorObj::GetParamBlock(int i) { switch(i) { case pbType_subani: return pblock2; case pbComplex_subani: return pbComplex; default: return NULL; } } IParamBlock2* BasicFlectorObj::GetParamBlockByID(BlockID id) { if(pblock2->ID() == id) return pblock2; else if(pbComplex->ID() == id) return pbComplex; else return NULL; } RefResult BasicFlectorObj::NotifyRefChanged(const Interval& changeInt,RefTargetHandle hTarget, PartID& partID, RefMessage message, BOOL propagate ) { // switch (message) // { default: SimpleWSMObject2::NotifyRefChanged(changeInt,hTarget,partID,message,propagate); // } return REF_SUCCEED; } BasicFlectorMod::BasicFlectorMod(INode *node,BasicFlectorObj *obj) { ReplaceReference(SIMPWSMMOD_NODEREF,node); } Interval BasicFlectorMod::GetValidity(TimeValue t) { if (obRef && nodeRef) { Interval valid = FOREVER; Matrix3 tm; BasicFlectorObj *obj = (BasicFlectorObj*)GetWSMObject(t); tm = nodeRef->GetObjectTM(t,&valid); float TempT; obj->st->pbComplex->GetValue(PB_TIMEON,t,TempT,valid); obj->st->pbComplex->GetValue(PB_TIMEOFF,t,TempT,valid); float f; obj->st->pbComplex->GetValue(PB_REFLECTS,t,f,valid); obj->st->pbComplex->GetValue(PB_BOUNCE,t,f,valid); obj->st->pbComplex->GetValue(PB_BVAR,t,f,valid); obj->st->pbComplex->GetValue(PB_CHAOS,t,f,valid); obj->st->pbComplex->GetValue(PB_FRICTION,t,f,valid); obj->st->pbComplex->GetValue(PB_INHERVEL,t,f,valid); obj->st->pbComplex->GetValue(PB_REFRACTS,t,f,valid); obj->st->pbComplex->GetValue(PB_PASSVEL,t,f,valid); obj->st->pbComplex->GetValue(PB_PASSVELVAR,t,f,valid); obj->st->pbComplex->GetValue(PB_DISTORTION,t,f,valid); obj->st->pbComplex->GetValue(PB_DISTORTIONVAR,t,f,valid); obj->st->pbComplex->GetValue(PB_DIFFUSION,t,f,valid); obj->st->pbComplex->GetValue(PB_DIFFUSIONVAR,t,f,valid); obj->st->pbComplex->GetValue(PB_COLAFFECTS,t,f,valid); obj->st->pbComplex->GetValue(PB_COLPASSVEL,t,f,valid); obj->st->pbComplex->GetValue(PB_COLPASSVELVAR,t,f,valid); obj->st->pblock2->GetValue(PB_WIDTH,t,f,valid); obj->st->pblock2->GetValue(PB_LENGTH,t,f,valid); return valid; } else { return FOREVER; } } class BasicFlectorDeformer : public Deformer { public: Point3 Map(int i, Point3 p) {return p;} }; static BasicFlectorDeformer BasicFlectordeformer; Deformer& BasicFlectorMod::GetDeformer( TimeValue t,ModContext &mc,Matrix3& mat,Matrix3& invmat) { return BasicFlectordeformer; } RefTargetHandle BasicFlectorMod::Clone(RemapDir& remap) { BasicFlectorMod *newob = new BasicFlectorMod(nodeRef,(BasicFlectorObj*)obRef); newob->SimpleWSMModClone(this, remap); BaseClone(this, newob, remap); return newob; } void BasicFlectorMod::ModifyObject(TimeValue t, ModContext &mc, ObjectState *os, INode *node) { ParticleObject *obj = GetParticleInterface(os->obj); if (obj) { deflect.obj = (BasicFlectorObj*)GetWSMObject(t); deflect.node = nodeRef; if (deflect.obj) { deflect.obj->custnode = deflect.obj->st->pblock2->GetINode(PB_MESHNODE); deflect.obj->tmValid.SetEmpty(); deflect.obj->mValid.SetEmpty(); deflect.badmesh = (deflect.obj->custnode==NULL); if (t<=deflect.obj->t) deflect.obj->lastrnd = 12345; deflect.obj->t=t; deflect.obj->dvel = Zero; deflect.totalforce = Zero; deflect.applyat = Zero; deflect.totalnumber = 0; TimeValue tmpt = GetCOREInterface()->GetTime(); if (deflect.obj->ctime != tmpt) { deflect.obj->ctime = tmpt; deflect.obj->ffdata.FlectForce = deflect.totalforce; deflect.obj->ffdata.ApplyAt = deflect.applyat; deflect.obj->ffdata.Num = deflect.totalnumber; } obj->ApplyCollisionObject(&deflect); } } } CollisionObject *BasicFlectorObj::GetCollisionObject(INode *node) { BasicFlectorField *gf = new BasicFlectorField; gf->obj = this; gf->node = node; gf->obj->tmValid.SetEmpty(); return gf; } /* // Bayboro 9/18/01 void* BasicFlectorObj::GetInterface(ULONG id) { switch (id) { case I_NEWPARTTEST: return (ITestInterface*)this; } return Object::GetInterface(id); } */ // Bayboro 9/18/01 void BasicFlectorObj::SetUpModifier(TimeValue t,INode *node) { custnode = st->pblock2->GetINode(PB_MESHNODE); mf->deflect.obj = (BasicFlectorObj*)(mf->GetWSMObject(t)); mf->deflect.node = mf->nodeRef; // mf->deflect.obj->tmValid.SetEmpty(); // mf->deflect.obj->mValid.SetEmpty(); tmValid.SetEmpty(); mValid.SetEmpty(); mf->deflect.badmesh = (custnode==NULL); // if (t <= mf->deflect.obj->t) // mf->deflect.obj->lastrnd = 12345; mf->deflect.obj->t = t; mf->deflect.obj->dvel = Zero; mf->deflect.totalforce = Zero; mf->deflect.applyat = Zero; mf->deflect.totalnumber = 0; TimeValue tmpt = GetCOREInterface()->GetTime(); if (mf->deflect.obj->ctime != tmpt) { mf->deflect.obj->ctime = tmpt; mf->deflect.obj->ffdata.FlectForce = mf->deflect.totalforce; mf->deflect.obj->ffdata.ApplyAt = mf->deflect.applyat; mf->deflect.obj->ffdata.Num = mf->deflect.totalnumber; } } /* // Bayboro 9/18/01 int BasicFlectorObj::NPTestInterface(TimeValue t,BOOL UpdatePastCollide,ParticleData *part,float dt,INode *node,int index) { ReturnThreeStateValue = DONTCARE; if (!mf) mf = (BasicFlectorMod *)CreateWSMMod(node); SetUpModifier(t,node); float ct = 0; UpdatePastCollide = TRUE; mf->deflect.CheckCollision(t,part->position,part->velocity,dt,index,&ct,UpdatePastCollide); return (ReturnThreeStateValue); } */ // Bayboro 9/18/01
26.962949
183
0.674638
SOM-Firmwide
96f88728b851258c268edfef31d14199305c1a94
114
hpp
C++
src/events/event_data_main_menu.hpp
sfod/quoridor
a82b045fcf26ada34b802895f097c955103fbc14
[ "MIT" ]
null
null
null
src/events/event_data_main_menu.hpp
sfod/quoridor
a82b045fcf26ada34b802895f097c955103fbc14
[ "MIT" ]
31
2015-03-24T10:07:37.000Z
2016-04-20T15:11:18.000Z
src/events/event_data_main_menu.hpp
sfod/quoridor
a82b045fcf26ada34b802895f097c955103fbc14
[ "MIT" ]
null
null
null
#pragma once #include "event_data.hpp" class EventData_MainMenu : public EventDataCRTP<EventData_MainMenu> { };
16.285714
69
0.789474
sfod
96fce3f353f8351594637a8bee987e5bd6d13d02
2,628
cpp
C++
WholesomeEngine/WholesomeEngine/ModuleRender.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
WholesomeEngine/WholesomeEngine/ModuleRender.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
WholesomeEngine/WholesomeEngine/ModuleRender.cpp
HeladodePistacho/WholesomeEngine
e85b512f749d2f506cf5eb5603d2791e3221ccd5
[ "MIT" ]
null
null
null
#include "ModuleRender.h" #include "VulkanLogicalDevice.h" #include <SDL2/SDL_vulkan.h> ModuleRender::ModuleRender() : Module(), vulkan_logic_device(std::make_unique<VulkanLogicalDevice>()) { DEBUG::LOG("CREATING MODULE RENDER", nullptr); } ModuleRender::~ModuleRender() { } ENGINE_STATUS ModuleRender::Init() { ENGINE_STATUS ret = ENGINE_STATUS::SUCCESS; VkResult result = VkResult::VK_SUCCESS; //Create Vulkan Instance if (event_recieved.has_value()) { if (result = vulkan_instance.CreateInstance(event_recieved.value().sdl_window); result == VK_ERROR_INCOMPATIBLE_DRIVER) { DEBUG::LOG("[ERROR] Creating Vulkan Instance Failure: COMPATIBLE DRIVER NOT FOUND", nullptr); ret = ENGINE_STATUS::FAIL; } else if (result != VkResult::VK_SUCCESS) { //Vicente ftw DEBUG::LOG("[ERROR] Creating Vulkan Instance Failure: unknown error", nullptr); ret = ENGINE_STATUS::FAIL; } } DEBUG::LOG("[SUCCESS] Creating Vulkan Instance Success", nullptr); //Optional event will have value if we have recieved the Surface creation event if (event_recieved.has_value()) { //Create Vulkan Surface Instance if (SDL_Vulkan_CreateSurface(const_cast<SDL_Window*>(event_recieved.value().sdl_window), vulkan_instance.GetInstance(), &vulkan_surface) != SDL_TRUE) { DEBUG::LOG("[ERROR] VULKAN SURFACE CREATION FAILURE: %", SDL_GetError()); } else DEBUG::LOG("[SUCCESS] SDL_Vulkan_CreateSurface successfully", nullptr); } //Init Physical Devices if (result = vulkan_instance.GetPhysicalDevices(); result != VK_SUCCESS) { DEBUG::LOG("[ERROR] Getting Physical Device Failure", nullptr); ret = ENGINE_STATUS::FAIL; } //Select physiscal Device if (result = vulkan_instance.SelectPhysicalDevice(vulkan_surface); result != VK_SUCCESS) { DEBUG::LOG("[ERROR] Selecting Physical Device Failure", nullptr); ret = ENGINE_STATUS::FAIL; } //Create Logical Device if (result = vulkan_logic_device->InitDevice(vulkan_instance); result != VK_SUCCESS) { DEBUG::LOG("[ERROR] Creating Logical Device Failure", nullptr); ret = ENGINE_STATUS::FAIL; } return ret; } ENGINE_STATUS ModuleRender::CleanUp() { DEBUG::LOG("...Cleaning Render...", nullptr); //Destroy Surface vkDestroySurfaceKHR(vulkan_instance.GetInstance(), vulkan_surface, nullptr); //Destroy device vulkan_logic_device->DestroyDevice(); //Destroy instance vulkan_instance.DestroyInstance(); return ENGINE_STATUS::SUCCESS; } void ModuleRender::OnEventRecieved(const WEWindowCreation& event_recieved) { //As I'm not gonna use the info of this event right now I store it this->event_recieved = event_recieved; }
27.663158
151
0.741248
HeladodePistacho
8c014f51a2cab44ee6711e258b41c8dcac4991fb
8,596
hpp
C++
src/control/modules/motion-control/PidMotionController.hpp
CollinAvidano/robocup-firmware
847900af9a4a4b3aef4b9aab494b75723b3e10a4
[ "Apache-2.0" ]
null
null
null
src/control/modules/motion-control/PidMotionController.hpp
CollinAvidano/robocup-firmware
847900af9a4a4b3aef4b9aab494b75723b3e10a4
[ "Apache-2.0" ]
null
null
null
src/control/modules/motion-control/PidMotionController.hpp
CollinAvidano/robocup-firmware
847900af9a4a4b3aef4b9aab494b75723b3e10a4
[ "Apache-2.0" ]
null
null
null
#pragma once #include <array> #include <rc-fshare/pid.hpp> #include <rc-fshare/robot_model.hpp> #include "FPGA.hpp" #include "MPU6050.h" #include "RobotDevices.hpp" /** * Robot controller that runs a PID loop on each of the four wheels. */ class PidMotionController { public: PidMotionController() : imu(shared_i2c, MPU6050_DEFAULT_ADDRESS), ax_offset(0), ay_offset(0), az_offset(0), gx_offset(0), gy_offset(0), gz_offset(0), ax(0), ay(0), az(0), gx(0), gy(0), gz(0), rotation(0), target_rotation(0), angular_vel(0), angle_hold(false) { setPidValues(1.0, 0, 0, 50, 0); rotation_pid.kp = 15; rotation_pid.ki = 0; rotation_pid.kd = 300; rotation_pid.setWindup(40); rotation_pid.derivAlpha = 0.0f; // 1 is all old, 0 is all new } // can't init gyro in constructor because i2c not fully up? void startGyro(int16_t ax, int16_t ay, int16_t az, int16_t gx, int16_t gy, int16_t gz) { imu.initialize(); // Thread::wait(100); imu.setFullScaleGyroRange(MPU6050_GYRO_FS_1000); imu.setFullScaleAccelRange(MPU6050_ACCEL_FS_8); imu.setXAccelOffset(ax); imu.setYAccelOffset(ay); imu.setZAccelOffset(az); imu.setXGyroOffset(gx); imu.setYGyroOffset(gy); imu.setZGyroOffset(gz); } void setPidValues(float p, float i, float d, unsigned int windup, float derivAlpha) { for (Pid& ctl : _controllers) { ctl.kp = p; ctl.ki = i; ctl.kd = d; ctl.setWindup(windup); ctl.derivAlpha = derivAlpha; } } void updatePValues(float p) { for (Pid& ctl : _controllers) { ctl.kp = p; } } void updateIValues(float i) { for (Pid& ctl : _controllers) { ctl.ki = i; } } void updateDValues(float d) { for (Pid& ctl : _controllers) { ctl.kd = d; } } void setTargetVel(Eigen::Vector3f target) { _targetVel = target; } /** * Return the duty cycle values for the motors to drive at the target * velocity. * * @param encoderDeltas Encoder deltas for the four drive motors * @param dt Time in ms since the last calll to run() * * @return Duty cycle values for each of the 4 motors */ std::array<int16_t, 4> run(const std::array<int16_t, 4>& encoderDeltas, float dt, Eigen::Vector4d* errors = nullptr, Eigen::Vector4d* wheelVelsOut = nullptr, Eigen::Vector4d* targetWheelVelsOut = nullptr) { // update control targets // in the future, we can get the rotation angle soccer wants and // directly command that // as our target, or integrate the rotational velocities given to us to // create the target. // For now though, we only do an angle hold when soccer is not // commanding rotational velocities // (this should help with strafing quickly) // target_rotation += _targetVel[2] * dt; // get sensor data imu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz); // convert sensor readings to mathematically valid values Eigen::Vector4d wheelVels; wheelVels << encoderDeltas[0], encoderDeltas[1], encoderDeltas[2], encoderDeltas[3]; wheelVels *= 2.0 * M_PI / ENC_TICKS_PER_TURN / dt; auto bot_vel = RobotModel::get().WheelToBot * wheelVels; // we have two redundent sensor measurements for rotation // 32.8 comes from data sheet, units are LSB / (deg/s) float ang_vel_gyro = (gz / 32.8f) * M_PI / 180.0f; float ang_vel_enc = bot_vel[2]; // printf("%f\r\n", ang_vel_enc); // std::printf("%f %f\r\n", ang_vel_gyro, ang_vel_enc); // perform sensor fusion // the higher this is, the more gyro measurements are used instead of // encoders float sensor_fuse_ratio = 1; float ang_vel_update = ang_vel_gyro * sensor_fuse_ratio + ang_vel_enc * (1 - sensor_fuse_ratio); // perform state update based on fused value, passed through a low // passed filter // so far noise on the gyro seems pretty minimal, that's why this filter // is off float alpha = 1.0; // 0->1 (higher means less filtering) angular_vel = (alpha * ang_vel_update + (1 - alpha) * angular_vel); // current rotation estimate rotation += angular_vel * dt; // printf("%f\r\n", rotation * 180.0f / M_PI); // velocity we are actually basing control off of, not the latest // command auto target_vel_act = _targetVel; // std::printf("%f\r\n", rot_error); const auto epsilon = 0.0001f; // soccer tells us to "halt" by sending 0 vel commands, we want to // freeze the // rotational controller too so bots dont' react when getting handled bool soccer_stop = (std::abs(target_vel_act[0]) < epsilon) && (std::abs(target_vel_act[1]) < epsilon); if (!soccer_stop && std::abs(target_vel_act[2]) < epsilon) { if (!angle_hold) { target_rotation = rotation; angle_hold = true; } // get the smallest difference between two angles float rot_error = target_rotation - rotation; while (rot_error < -M_PI) rot_error += 2 * M_PI; while (rot_error > M_PI) rot_error -= 2 * M_PI; target_vel_act[2] = rotation_pid.run(rot_error); } else { // let target_vel_act be exactly what soccer commanded angle_hold = false; } // conversion to commanded wheel velocities Eigen::Vector4d targetWheelVels = RobotModel::get().BotToWheel * target_vel_act.cast<double>(); if (targetWheelVelsOut) { *targetWheelVelsOut = targetWheelVels; } Eigen::Vector4d wheelVelErr = targetWheelVels - wheelVels; if (errors) { *errors = wheelVelErr; } if (wheelVelsOut) { *wheelVelsOut = wheelVels; } // Calculated by checking for slippage at max accel, and decreasing // appropriately // Binary search works really well in this case // Caution: This is dependent on the PID values so increasing the // agressiveness of that will change this double max_error = 3.134765625; double scale = 1; for (int i = 0; i < 4; i++) { if (abs(wheelVelErr[i]) > max_error) { scale = max(scale, abs(wheelVelErr[i]) / max_error); } } wheelVelErr /= scale; targetWheelVels = wheelVels + wheelVelErr; std::array<int16_t, 4> dutyCycles; for (int i = 0; i < 4; i++) { float dc = targetWheelVels[i] * RobotModel::get().DutyCycleMultiplier + copysign(4, targetWheelVels[i]); dc += _controllers[i].run(wheelVelErr[i]); if (std::abs(dc) > FPGA::MAX_DUTY_CYCLE) { // Limit to max duty cycle dc = copysign(FPGA::MAX_DUTY_CYCLE, dc); // Conditional integration indicating open loop control _controllers[i].set_saturated(true); } else { _controllers[i].set_saturated(false); } dutyCycles[i] = static_cast<int16_t>(dc); } return dutyCycles; } // 2048 ticks per turn. Theres is a 3:1 gear ratio between the motor and the // wheel. static const uint16_t ENC_TICKS_PER_TURN = 2048 * 3; private: /// controllers for each wheel std::array<Pid, 4> _controllers{}; Pid rotation_pid; Eigen::Vector3f _targetVel{}; MPU6050 imu; int ax_offset, ay_offset, az_offset, gx_offset, gy_offset, gz_offset; int16_t ax, ay, az, gx, gy, gz; float rotation; // state estimate for rotation // We want to preserve the interface of soccer commanding rotational // velocities // for now, so that requires us to have a separate estimate of soccer's // desired rotation float target_rotation; float angular_vel; bool angle_hold; };
32.315789
80
0.57201
CollinAvidano
8c04536827b6cd7253ac2c9620a3e66ef580ce61
743
cpp
C++
modules/engine/src/Render/Shape/Cuboid.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
1
2016-11-12T02:43:29.000Z
2016-11-12T02:43:29.000Z
modules/engine/src/Render/Shape/Cuboid.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
modules/engine/src/Render/Shape/Cuboid.cpp
litty-studios/randar
95daae57b1ec7d87194cdbcf6e3946b4ed9fc79b
[ "MIT" ]
null
null
null
#include <randar/Render/Shape.hpp> randar::Geometry randar::cuboid( float width, float height, float depth, const randar::Palette& palette) { randar::Geometry geo; Vertex vert; float rw = width / 2.0f; float rh = height / 2.0f; float rd = depth / 2.0f; // Front faces. vert.color = palette.color(); vert.position.set(-rw, -rh, -rd); geo.append(vert); vert.position.set(rw, rh, -rd); geo.append(vert); vert.position.set(-rw, rh, -rd); geo.append(vert); vert.position.set(-rw, -rh, -rd); geo.append(vert); vert.position.set(rw, -rh, -rd); geo.append(vert); vert.position.set(rw, rh, -rd); geo.append(vert); // Back faces. return geo; }
19.051282
37
0.585464
litty-studios
8c076bb1dcc30a6ef07be1b58b7d4608d8839627
26,180
cpp
C++
TommyGun/Plugins/Common/ZXPlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
34
2017-05-08T18:39:13.000Z
2022-02-13T05:05:33.000Z
TommyGun/Plugins/Common/ZXPlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
null
null
null
TommyGun/Plugins/Common/ZXPlugin.cpp
tonyt73/TommyGun
2c2ffae3dcd5dc25fd64d68a9f4cc96d99a1cd36
[ "BSD-3-Clause" ]
6
2017-05-27T01:14:20.000Z
2020-01-20T14:54:30.000Z
/*--------------------------------------------------------------------------- (c) 2004 Scorpio Software 19 Wittama Drive Glenmore Park Sydney NSW 2745 Australia ----------------------------------------------------------------------------- $Workfile:: $ $Revision:: $ $Date:: $ $Author:: $ ---------------------------------------------------------------------------*/ //--------------------------------------------------------------------------- #ifdef BUILDING_CORE #include "core_pch.h" #else #include "pch.h" #endif #pragma hdrstop //--------------------------------------------------------------------------- using namespace Scorpio; using namespace Plugin; using namespace Logging; //--------------------------------------------------------------------------- const int g_iNotFound = -1; //--------------------------------------------------------------------------- __fastcall ZXPlugin::ZXPlugin(const String& sFilename, ZXPluginManager* PluginManager) : m_PluginManager(PluginManager) , m_iLoadOrder(-1) , m_sFileName(sFilename) , m_sDescription("") , m_sComments("") , m_sProductVersion("Unknown") , m_sFileVersion("Unknown") , m_sInternalName("Unknown") , m_sVendor("Unknown") , m_sParentSignature("") , m_bLoaded(false) , m_bDoNotLoad(false) , m_bUnloading(false) , m_bInitialized(false) , m_bExceptionCaught(false) , m_hInstance(NULL) , m_hParentInstance(NULL) , m_NotifyFunc(NULL) , m_ReleaseFunc(NULL) , m_ModuleAddress(0) , m_dwModuleSize(0) , m_dwVersion(0) , m_dwFlags(0) , m_dwInterface(0) , m_Icon(NULL) { } //--------------------------------------------------------------------------- __fastcall ZXPlugin::~ZXPlugin() { // unload the plugin if it hasn't already been done if (true == m_bLoaded) { Unload(); } // reset some member variables just in case m_ModuleAddress = NULL; m_bInitialized = false; m_bUnloading = false; m_bLoaded = false; m_sFileName = ""; } //--------------------------------------------------------------------------- // Load /** * Loads a plugin into memory and initializes it if required * @param GetModuleInformation the pointer to the GetModuleInformation function in PSAPI.dll * @return S_OK if loaded successful, else E_FAIL if failed to load * @author Tony Thompson * @date Last Modified 30 October 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::Load(GetModuleInformationPtr GetModuleInformation) { HRESULT hResult = E_FAIL; bool bFreeLibrary = false; // try to load the DLL String DllPath = ExtractFilePath(Application->ExeName) + String("Plugins\\") + m_sFileName; HINSTANCE hInstance = NULL; ZX_LOG_INFO(lfPlugin, "Loading Plugin: " + DllPath); DWORD dwStartTime = timeGetTime(); try { hInstance = LoadLibrary(DllPath.c_str()); // get the details of the module if (NULL != hInstance) { MODULEINFO ModuleInfo; ModuleInfo.lpBaseOfDll = hInstance; ModuleInfo.SizeOfImage = 0; ModuleInfo.EntryPoint = 0; DWORD SizeOfModuleInfo = sizeof(ModuleInfo); HANDLE hProcess = GetCurrentProcess(); if (true == SAFE_CODE_PTR(GetModuleInformation) && GetModuleInformation(hProcess, hInstance, &ModuleInfo, SizeOfModuleInfo)) { m_dwModuleSize = ModuleInfo.SizeOfImage; } else { m_dwModuleSize = 0; } m_ModuleAddress = hInstance; } else { DWORD dwErrorCode = GetLastError(); ZXMessageBox MessageBox; MessageBox.ShowWindowsErrorMessage("LoadLibrary Failed: " + DllPath, dwErrorCode, __FILE__, __FUNC__, __LINE__); ZX_LOG_ERROR(lfPlugin, "LoadLibrary Error: " + IntToStr(dwErrorCode)); } } catch(...) { ZX_LOG_EXCEPTION(lfException, m_sFileName + "caused an exception while try to load the DLL"); hInstance = NULL; } if (NULL != hInstance) { m_hInstance = hInstance; // Get Plugin file version details hResult = GetPluginVersionInfo(); if (S_OK == hResult) { // We have version info in the file, so check the // interface version and initialise functions from the loaded DLL if ((m_sParentSignature == "" && S_OK == CheckInterfaceRequirements()) || (m_sParentSignature != "" && S_OK == CheckPluginSignature(m_sParentSignature))) { InitialisePtr InitialiseFunc = NULL; InitialiseFunc = reinterpret_cast<InitialisePtr>(GetProcAddress(hInstance, "Initialise")); // Do we have a valid initialise function to call? if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(InitialiseFunc))) { // NOTE: It is not important that we check the LastError value if the GetProcAddresses fail. This maybe because // the dll we are trying to load is not a valid plugin, there maybe other programs out there that use the same // extension we do. Thus we can only assume a valid plugin, if all functions are satisfied. m_NotifyFunc = reinterpret_cast<NotifyPtr> (GetProcAddress(hInstance, "Notify")); m_ReleaseFunc = reinterpret_cast<ReleasePtr>(GetProcAddress(hInstance, "Release")); // Are all the functions required, present? if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(m_NotifyFunc )) && FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(m_ReleaseFunc))) { // yes, the DLL is valid. m_bLoaded = true; hResult = S_OK; // does the plugin have a flags function? FlagsPtr FlagsFunc = reinterpret_cast<FlagsPtr> (GetProcAddress(hInstance, "Flags")); DWORD Flags = 0L; if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(FlagsFunc))) { if (S_FALSE == FlagsFunc(Flags)) { Flags = 0L; } if (FLAG_IsNotUnloadable == (Flags & FLAG_IsNotUnloadable)) { // must always load this plugin m_bDoNotLoad = false; } } m_dwFlags = Flags; // Does the user want us to load the plugin, or do we have to load it because it has to be loaded if (false == m_bDoNotLoad) { bool bExceptionCaught = false; try { m_bLoaded = false; hResult = S_FALSE; // initialize the loaded DLL if (S_OK != InitialiseFunc(this)) { // failed to initialize do not load next time ZX_LOG_ERROR(lfPlugin, "Failed to Initialize Plugin: " + m_sFileName); m_bExceptionCaught = true; m_bDoNotLoad = true; bFreeLibrary = true; } else { m_bLoaded = true; hResult = S_OK; // set the default icon for the plugin if the plugin hasn't already done so in initialize #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->AddPluginIcon(m_hInstance, NULL, m_sDescription); } #endif ZX_LOG_INFO(lfPlugin, "Initialized Plugin: " + m_sFileName); m_bInitialized = true; } } catch(...) { bExceptionCaught = true; ZX_LOG_EXCEPTION(lfException, m_sFileName + " caused an exception during Initialization") } if (true == bExceptionCaught) { // plugin caused an exception during initialization, so unload it m_bExceptionCaught = true; m_bDoNotLoad = true; bFreeLibrary = true; hResult = S_FALSE; } } else { ZX_LOG_WARNING(lfPlugin, "Instructed not to load Plugin: " + m_sFileName); m_bLoaded = true; bFreeLibrary = false; } } else { ZX_LOG_WARNING(lfPlugin, "The File " + m_sFileName + " may not be a TommyGun Plugin"); } } else { ZX_LOG_WARNING(lfPlugin, "The File " + m_sFileName + " may not be a TommyGun Plugin"); } } else { ZX_LOG_ERROR(lfPlugin, "The File " + m_sFileName + " is incompatible with this version of the Framework"); // report that we tried to load a plugin but its interface requirements where incorrect! String Msg = "Failed to Load Plugin: " + m_sFileName; #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->ShowGeneralMessage(Msg, "Incompatible Interface Requirements", __FILE__, __FUNC__, __LINE__); } #endif m_bLoaded = true; Unload(); m_bDoNotLoad = true; bFreeLibrary = false; hResult = S_FALSE; } } else { ZX_LOG_ERROR(lfPlugin, "Plugin " + m_sFileName + " has no Version Info and its interface requirements cannot be validated"); } if (S_FALSE == hResult || true == bFreeLibrary) { ZX_LOG_INFO(lfPlugin, "Unloading " + m_sFileName + " due to error while Loading and Initializing") m_ReleaseFunc = NULL; m_NotifyFunc = NULL; Unload(); } } else { // we failed to load a suspected plugin. ZX_LOG_ERROR(lfPlugin, "LoadLibrary FAILED on the file " + m_sFileName); } DWORD dwEndTime = timeGetTime(); ZX_LOG_INFO(lfPlugin, "Loading took " + IntToStr(dwEndTime - dwStartTime) + "ms for " + m_sFileName); return hResult; } //--------------------------------------------------------------------------- // Unload /** * Unloads a plugin its resources and the dll * @param GetModuleInformation the pointer to the GetModuleInformation function in PSAPI.dll * @return S_OK if loaded successful, else E_FAIL if failed to load * @author Tony Thompson * @date Last Modified 30 October 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::Unload(bool bFreeOptions) { RL_HRESULT(E_FAIL); // clear the events m_Events.clear(); if (true == m_bLoaded) { DWORD dwStartTime = timeGetTime(); try { ZX_LOG_WARNING(lfPlugin, "Unloading Plugin " + m_sFileName); m_bUnloading = true; // release the plugin resources if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(m_ReleaseFunc)) && true == m_bInitialized) { try { m_ReleaseFunc(); } catch(...) { ZX_LOG_EXCEPTION(lfException, m_sFileName + " caused an exception during Release()") ZX_LOG_ERROR(lfPlugin, "Unable to Release Plugin: " + m_sFileName + " due to an exception"); m_bExceptionCaught = true; m_ReleaseFunc = NULL; } } else { ZX_LOG_ERROR(lfPlugin, "No Release function or Plugin is not initialized [" + m_sFileName + "]"); } } __finally { // free the DLL if (NULL != m_hInstance) { #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->Free(m_hInstance, bFreeOptions); } #endif if (FALSE == FreeLibrary(m_hInstance)) { // failed to free the DLL ZX_LOG_ERROR(lfPlugin, "Failed to Unload the DLL of the Plugin: " + m_sFileName); } else { ZX_LOG_INFO(lfPlugin, "Successfully Unloaded the DLL of the Plugin: " + m_sFileName); hResult = S_OK; } m_hInstance = NULL; m_bLoaded = false; } } DWORD dwEndTime = timeGetTime(); ZX_LOG_INFO(lfPlugin, "Unloading took " + IntToStr(dwEndTime - dwStartTime) + "ms for " + m_sFileName); } return hResult; } //--------------------------------------------------------------------------- // GetPluginVersionInfo /** * Gets the File Version information for the plugin file * @param PluginIt The plugin iterator * @return HRESULT S_OK information retrieved, else failed * @author Tony Thompson * @date Created 12 March 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::GetPluginVersionInfo(void) { HRESULT hResult = E_FAIL; // get the detals of the plugin String DllPath = ExtractFilePath(Application->ExeName) + "Plugins\\" + m_sFileName; KFileInfo* FileInfo = NULL; try { FileInfo = new KFileInfo(NULL); } catch(EOutOfMemory&) { ZX_LOG_EXCEPTION(lfException, "Failed to create the FileInfo object") FileInfo = NULL; } if (true == SAFE_PTR(FileInfo)) { FileInfo->FileName = DllPath; if (true == FileInfo->FileInfoValid) { m_sDescription = FileInfo->FileDescription; m_sComments = FileInfo->Comments; m_sVendor = FileInfo->CompanyName; m_sFileVersion = FileInfo->FileVersion; m_sProductVersion = FileInfo->ProductVersion; m_sInternalName = FileInfo->InternalName; hResult = S_OK; } SAFE_DELETE(FileInfo); } return hResult; } //--------------------------------------------------------------------------- // CheckInterfaceRequirements /** * Checks the Plugin Interface Requirements can be met by Core.dll * @param PluginIt The plugin iterator * @return HRESULT S_OK Requirements can be met * @author Tony Thompson * @date Created 12 March 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::CheckInterfaceRequirements(void) { HRESULT hResult = E_FAIL; // convert the product version string to a major and minor number int iDotPos = m_sProductVersion.Pos('.'); ZX_LOG_INFO(lfPlugin, m_sFileName + ", Version: " + m_sProductVersion); if (0 != iDotPos) { AnsiString sMajor = m_sProductVersion.SubString(1, iDotPos - 1); String sProductVersion = m_sProductVersion.SubString(iDotPos + 1, m_sProductVersion.Length()); iDotPos = sProductVersion.Pos('.'); if (0 != iDotPos) { AnsiString sMinor = sProductVersion.SubString(1, iDotPos - 1); int iMajor = 0; int iMinor = 0; iMajor = StrToInt(sMajor); iMinor = StrToInt(sMinor); WORD iVersion = (iMajor << 8) | iMinor; // check the requirements of the plugin against the cores functionality if (g_dwCoreInterfaceVersion >= iVersion && iVersion >= g_dwCompatibleBaseVersion) { hResult = S_OK; } } } return hResult; } //--------------------------------------------------------------------------- // ReadLoadOrder /** * Reads a plugin loading information from the registry * @param NextAvailableLoadOrder the next available load order id to use * @author Tony Thompson * @date Created 22 September 2003 */ //--------------------------------------------------------------------------- void __fastcall ZXPlugin::ReadLoadOrder(unsigned int& NextAvailableLoadOrder) { // assume the plugin has no load order defined int iLoadOrder = g_iNotFound; // reset the plugin flags to zero m_dwFlags = 0L; // try to read a load order from the registry #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager) && true == m_PluginManager->GuiManager->Registry()->Read("Plugins", m_sFileName, iLoadOrder)) { // plugin is known, and an order has been given bool bDoNotLoad; m_iLoadOrder = iLoadOrder; // does it have a DoNotLoad entry if (true == m_PluginManager->GuiManager->Registry()->Read("Plugins", "DNL_" + m_sFileName, bDoNotLoad)) { // yes, assign the DNL value m_bDoNotLoad = bDoNotLoad; if (true == bDoNotLoad) ZX_LOG_INFO(lfPlugin, m_sFileName + " is set NOT to load") } else { // DNL is false by default m_bDoNotLoad = false; } } else { // this is a new plugin, make it welcome and give it a load order m_iLoadOrder = NextAvailableLoadOrder; m_bDoNotLoad = false; ++NextAvailableLoadOrder; } #endif } //--------------------------------------------------------------------------- // AddToOptions /** * Adds a plugin to the options dialog * @param iNewLoadOrder the new load order of the plugin * @author Tony Thompson * @date Created 22 September 2003 */ //--------------------------------------------------------------------------- void __fastcall ZXPlugin::AddToOptions(int iNewLoadOrder) { m_iLoadOrder = iNewLoadOrder; #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->Registry()->Write("Plugins", m_sFileName, (int)m_iLoadOrder); m_PluginManager->GuiManager->Registry()->Write("Plugins", "DNL_" + m_sFileName, m_bDoNotLoad); m_PluginManager->GuiManager->OptionsPluginsAdd(m_hInstance, m_sDescription, m_sFileName, m_sVendor, m_sProductVersion, m_sFileVersion, (FLAG_IsNotUnloadable != (m_dwFlags & FLAG_IsNotUnloadable)), m_bDoNotLoad, FLAG_IsNotVisibleInOptionsPage == (m_dwFlags & FLAG_IsNotVisibleInOptionsPage), m_dwFlags & FLAG_PluginLoadPriorityMask, m_iLoadOrder, m_Icon ); } #endif } //--------------------------------------------------------------------------- bool __fastcall ZXPlugin::InterestedInEvent(TZX_EVENT Event) { return std::find(m_Events.begin(), m_Events.end(), Event) != m_Events.end(); } //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::NotifyEvent(TZX_EVENT Event, LPDATA lpData, DWORD Param, DWORD Arg) { RL_HRESULT(S_FALSE); if (true == InterestedInEvent(Event)) { try { if (true == SAFE_CODE_PTR(m_NotifyFunc)) { hResult = m_NotifyFunc(Event, lpData, Param, Arg); } else { ZX_LOG_ERROR(lfPlugin, m_sFileName + " has an invalid NotifyFunc pointer") } } catch(...) { // plugin caused an exception m_bExceptionCaught = true; ZX_LOG_EXCEPTION(lfException, m_sFileName + " caused an exception while processing NotifyEvent with message 0x" + IntToHex(Event, 8)) // unload the plugin due to exception Unload(); #ifdef USE_GUI_MANAGER if (true == SAFE_PTR(m_PluginManager->GuiManager)) { m_PluginManager->GuiManager->ShowMessage(mbtError, "Plugin has caused an Exception", "A plugin has exploded in a heap and crashed", "Plugin: " + m_sDescription + "\n\nThis plugin has caused a fault and as such has been booted out of the TommyGun environment for being a naughty little plugin.\n\nPlease send the exception.log and plugin.log files to KiwiWare.", "OK", "", "" ); } #endif } } return hResult; } //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::RegisterEvent(TZX_EVENT Event) { RL_HRESULT(E_FAIL); // find the event (or lack of it) if (m_Events.end() == std::find(m_Events.begin(), m_Events.end(), Event)) { // register the event m_Events.push_back(Event); hResult = S_OK; } else { // event already registered hResult = S_FALSE; } return hResult; } //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::UnRegisterEvent(TZX_EVENT Event) { RL_HRESULT(E_FAIL); ZXEventsIterator EventsIt = std::find(m_Events.begin(), m_Events.end(), Event); if (m_Events.end() != EventsIt) { // unregister the event m_Events.erase(EventsIt); hResult = S_OK; } else { // event already unregistered hResult = S_FALSE; } return hResult; } //--------------------------------------------------------------------------- bool __fastcall ZXPlugin::OwnsMemory(void *Address) { DWORD dwAddress = (DWORD)Address; DWORD dwModule = (DWORD)m_ModuleAddress; return (dwModule <= dwAddress && dwAddress <= dwModule + m_dwModuleSize); } //--------------------------------------------------------------------------- // CheckPluginSignature /** * Checks the Plugin Interface Requirements can be met by Core.dll * @param PluginIt The plugin iterator * @return HRESULT S_OK Requirements can be met * @author Tony Thompson * @date Created 12 March 2001 */ //--------------------------------------------------------------------------- HRESULT __fastcall ZXPlugin::CheckPluginSignature(String sRequiredSignature) { HRESULT hResult = E_FAIL; String sSignature = ""; SignaturePtr SignatureFunc = reinterpret_cast<SignaturePtr>(GetProcAddress(Handle, "Signature")); if (FALSE == IsBadCodePtr(reinterpret_cast<StdCallPtr>(SignatureFunc))) { if (S_OK != SignatureFunc(sSignature)) { sSignature = ""; } if (sRequiredSignature == sSignature) { hResult = S_OK; } } m_sParentSignature = sSignature; // convert the product version string to a major and minor number /*int iDotPos = m_sProductVersion.Pos('.'); ZX_LOG_INFO(lfPlugin, m_sFileName + ", Version: " + m_sProductVersion); if (0 != iDotPos) { AnsiString sMajor = m_sProductVersion.SubString(1, iDotPos - 1); String sProductVersion = m_sProductVersion.SubString(iDotPos + 1, m_sProductVersion.Length()); iDotPos = sProductVersion.Pos('.'); if (0 != iDotPos) { AnsiString sMinor = sProductVersion.SubString(1, iDotPos - 1); int iMajor = 0; int iMinor = 0; iMajor = StrToInt(sMajor); iMinor = StrToInt(sMinor); WORD iVersion = (iMajor << 8) | iMinor; // check the requirements of the plugin against the cores functionality if (g_dwCoreInterfaceVersion >= iVersion && iVersion >= g_dwCompatibleBaseVersion) { hResult = S_OK; } } }*/ return hResult; } //---------------------------------------------------------------------------
40.463679
270
0.48793
tonyt73
8c0f4a16c4ad021c7425668ee79e817ec0537b17
4,186
hpp
C++
TBDAnnotation/src/Model/CustomPermutation.hpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
1
2021-06-13T10:49:43.000Z
2021-06-13T10:49:43.000Z
TBDAnnotation/src/Model/CustomPermutation.hpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
null
null
null
TBDAnnotation/src/Model/CustomPermutation.hpp
marcorighini/tbdannotation
f22d395fce5c6c1007177623b0a0c60f7fcb9d4f
[ "Apache-2.0" ]
null
null
null
/* * CustomPermutation.hpp * * Created on: 16/mag/2013 * Author: alessandro */ #ifndef CUSTOMPERMUTATION_HPP_ #define CUSTOMPERMUTATION_HPP_ #include <vector> #include <algorithm> #include <numeric> namespace cp { /* * Custom next combination generator */ template<typename T> class NextCombinationGenerator { std::vector<std::vector<T> > combinations; unsigned int m; template<typename Iterator> bool next_combination(const Iterator first, Iterator k, const Iterator last) { if ((first == last) || (first == k) || (last == k)) return false; Iterator itr1 = first; Iterator itr2 = last; ++itr1; if (last == itr1) return false; itr1 = last; --itr1; itr1 = k; --itr2; while (first != itr1) { if (*--itr1 < *itr2) { Iterator j = k; while (!(*itr1 < *j)) ++j; std::iter_swap(itr1, j); ++itr1; ++j; itr2 = k; std::rotate(itr1, j, last); while (last != j) { ++j; ++itr2; } std::rotate(k, itr2, last); return true; } } std::rotate(first, k, last); return false; } /* * Extract a subvector given a set of indexes */ template<typename R> std::vector<R> getValuesFromIndexesVector(const std::vector<R>& originals, const std::vector<unsigned int>& indexes) { std::vector<R> values(indexes.size()); for (unsigned int i = 0; i < indexes.size(); i++) { values[i] = originals[indexes[i]]; } return values; } public: typedef typename std::vector<std::vector<T> >::iterator iterator; typedef typename std::vector<std::vector<T> >::const_iterator const_iterator; NextCombinationGenerator(const std::vector<T>& _elements, unsigned int _m) : m(_m) { std::vector<unsigned int> elementsIndexes(_elements.size()); std::iota(std::begin(elementsIndexes), std::end(elementsIndexes), 0); do { std::vector<unsigned int> mIndexes(elementsIndexes.begin(), elementsIndexes.begin() + m); combinations.push_back(getValuesFromIndexesVector(_elements, mIndexes)); } while (next_combination(elementsIndexes.begin(), elementsIndexes.begin() + m, elementsIndexes.end())); } iterator begin() { return combinations.begin(); } const_iterator begin() const { return combinations.begin(); } iterator end() { return combinations.end(); } const_iterator end() const { return combinations.end(); } unsigned int size() const { return combinations.size(); } }; /* * Custom next cyclic permutation generator */ template<typename T> class NextCyclicPermutationGenerator { std::vector<std::vector<T> > cyclicPermutations; template<typename Iterator, typename R> static bool next_cyclic_permutation(const Iterator first, const Iterator last, const R terminationValue) { Iterator itr1 = first; Iterator itr2 = last; std::rotate(itr1, itr2 - 1, itr2); if (*itr1 == terminationValue) return false; return true; } /* * Extract a subvector given a set of indexes */ template<typename R> std::vector<R> getValuesFromIndexesVector(const std::vector<R>& originals, const std::vector<unsigned int>& indexes) { std::vector<R> values(indexes.size()); for (unsigned int i = 0; i < indexes.size(); i++) { values[i] = originals[indexes[i]]; } return values; } public: typedef typename std::vector<std::vector<T> >::iterator iterator; typedef typename std::vector<std::vector<T> >::const_iterator const_iterator; NextCyclicPermutationGenerator(const std::vector<T>& _elements) { std::vector<unsigned int> cyclicIndexes(_elements.size()); std::iota(std::begin(cyclicIndexes), std::end(cyclicIndexes), 0); unsigned int firstIndex = cyclicIndexes[0]; do { cyclicPermutations.push_back(getValuesFromIndexesVector(_elements, cyclicIndexes)); } while (next_cyclic_permutation(cyclicIndexes.begin(), cyclicIndexes.end(), firstIndex)); } iterator begin() { return cyclicPermutations.begin(); } const_iterator begin() const { return cyclicPermutations.begin(); } iterator end() { return cyclicPermutations.end(); } const_iterator end() const { return cyclicPermutations.end(); } unsigned int size() const { return cyclicPermutations.size(); } }; } #endif /* CUSTOMPERMUTATION_HPP_ */
23.649718
119
0.685141
marcorighini
8c110ee1d74b8c5c653df52a16a392ac74ba6d7c
3,697
cpp
C++
x_track/Application/X-Track.cpp
liushiwei/lv_port_linux_frame_buffer
17b822a68f8390df1e3b2c09319899c9c61dd72d
[ "MIT" ]
null
null
null
x_track/Application/X-Track.cpp
liushiwei/lv_port_linux_frame_buffer
17b822a68f8390df1e3b2c09319899c9c61dd72d
[ "MIT" ]
null
null
null
x_track/Application/X-Track.cpp
liushiwei/lv_port_linux_frame_buffer
17b822a68f8390df1e3b2c09319899c9c61dd72d
[ "MIT" ]
null
null
null
/* * PROJECT: LVGL ported to Linux * FILE: X-Track.cpp * PURPOSE: Implementation for LVGL ported to Linux * * LICENSE: The MIT License * * DEVELOPER: AlgoIdeas */ #include "App.h" #include "Common/HAL/HAL.h" #include <stdio.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/time.h> #include <time.h> #include "lvgl/lvgl.h" #include "lvgl/examples/lv_examples.h" #include "lv_drivers/display/fbdev.h" #include "lv_fs_if/lv_fs_if.h" #include "lv_drivers/display/fbdev.h" static bool g_keyboard_pressed = false; static int g_keyboard_value = 0; // uint32_t custom_tick_get(void) // { // static uint32_t basic_ms = 0; // uint32_t ms = 0; // struct timespec monotonic_time; // memset(&monotonic_time, 0, sizeof(struct timespec)); // if (basic_ms == 0) // { // clock_gettime(CLOCK_MONOTONIC, &monotonic_time); // basic_ms = monotonic_time.tv_sec * 1000 + monotonic_time.tv_nsec/1000000; // } // clock_gettime(CLOCK_MONOTONIC, &monotonic_time); // ms = monotonic_time.tv_sec * 1000 + monotonic_time.tv_nsec/1000000; // return (ms - basic_ms); // } static void lv_keyboard_driver_read_callback( lv_indev_drv_t* indev_drv, lv_indev_data_t* data) { data->state = (lv_indev_state_t)( g_keyboard_pressed ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL); data->key = g_keyboard_value; } static void lv_lencoder_driver_read_callback( lv_indev_drv_t* indev_drv, lv_indev_data_t* data) { static bool lastState; data->enc_diff = HAL::Encoder_GetDiff(); bool isPush = HAL::Encoder_GetIsPush(); data->state = isPush ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL; if (isPush != lastState) { HAL::Buzz_Tone(isPush ? 500 : 700, 20); lastState = isPush; } } static void lv_display_init(void) { /*Linux frame buffer device init*/ fbdev_init(); /*Initialize a descriptor for the buffer*/ static lv_disp_draw_buf_t draw_buf; lv_disp_draw_buf_init(&draw_buf, (lv_color_t*)malloc(DISP_HOR_RES * DISP_VER_RES * sizeof(lv_color_t)), (lv_color_t*)malloc(DISP_HOR_RES * DISP_VER_RES * sizeof(lv_color_t)), DISP_HOR_RES * DISP_VER_RES * sizeof(lv_color_t)); /*Initialize and register a display driver*/ static lv_disp_drv_t disp_drv; lv_disp_drv_init(&disp_drv); disp_drv.hor_res = DISP_HOR_RES; disp_drv.ver_res = DISP_VER_RES; disp_drv.flush_cb = fbdev_flush; disp_drv.draw_buf = &draw_buf; lv_disp_drv_register(&disp_drv); static lv_indev_drv_t kb_drv; lv_indev_drv_init(&kb_drv); kb_drv.type = LV_INDEV_TYPE_KEYPAD; kb_drv.read_cb = lv_keyboard_driver_read_callback; lv_indev_drv_register(&kb_drv); static lv_indev_drv_t enc_drv; lv_indev_drv_init(&enc_drv); enc_drv.type = LV_INDEV_TYPE_ENCODER; enc_drv.read_cb = lv_lencoder_driver_read_callback; lv_indev_drv_register(&enc_drv); } static int lv_usleep(unsigned int usec) { int ret; struct timespec requst; struct timespec remain; remain.tv_sec = usec / 1000000; remain.tv_nsec = (usec % 1000000) * 1000; do { requst = remain; ret = nanosleep(&requst, &remain); } while (-1 == ret && errno == EINTR); return ret; } // int main() // { // lv_init(); // lv_fs_if_init(); // HAL::HAL_Init(); // /* Display init */ // lv_display_init(); // App_Init(); // while (1) // { // lv_task_handler(); // HAL::HAL_Update(); // lv_usleep(5 * 1000); // lv_tick_inc(5000); // } // App_Uninit(); // return 0; // }
24.163399
84
0.660536
liushiwei
8c15797d0b5214691dd3a7baf2b83c5bab34cf0e
854
cpp
C++
snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocumentFragment.OwnerDocument Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-03-12T19:26:36.000Z
2022-01-10T21:45:33.000Z
snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocumentFragment.OwnerDocument Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_Data/Classic WebData XmlDocumentFragment.OwnerDocument Example/CPP/source.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <Snippet1> #using <System.Xml.dll> using namespace System; using namespace System::IO; using namespace System::Xml; int main() { // Create the XmlDocument. XmlDocument^ doc = gcnew XmlDocument; doc->LoadXml( "<items/>" ); // Create a document fragment. XmlDocumentFragment^ docFrag = doc->CreateDocumentFragment(); // Display the owner document of the document fragment. Console::WriteLine( docFrag->OwnerDocument->OuterXml ); // Add nodes to the document fragment. Notice that the // new element is created using the owner document of // the document fragment. XmlElement^ elem = doc->CreateElement( "item" ); elem->InnerText = "widget"; docFrag->AppendChild( elem ); Console::WriteLine( "Display the document fragment..." ); Console::WriteLine( docFrag->OuterXml ); } // </Snippet1>
25.878788
64
0.68267
BohdanMosiyuk
22c5954e42da3d4b70d11c6e28f6facac8537e77
874
cpp
C++
modules/task_2/yashin_k_topology_star/topology_star.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
1
2021-12-09T17:20:25.000Z
2021-12-09T17:20:25.000Z
modules/task_2/yashin_k_topology_star/topology_star.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/yashin_k_topology_star/topology_star.cpp
Stepakrap/pp_2021_autumn
716803a14183172337d51712fb28fe8e86891a3d
[ "BSD-3-Clause" ]
3
2022-02-23T14:20:50.000Z
2022-03-30T09:00:02.000Z
// Copyright 2021 Yashin Kirill #include <mpi.h> #include <algorithm> #include <random> #include "../../../modules/task_2/yashin_k_topology_star/topology_star.h" int getRand(int min, int max) { if (min == max) { return max; } else { std::mt19937 gen; std::uniform_int_distribution<> distr{min, max}; return distr(gen); } } MPI_Comm Star(int ProcNum) { MPI_Comm starcomm; int* index = new int[ProcNum]; int* edges = new int[2 * ProcNum - 2]; index[0] = ProcNum - 1; for (int i = 1; i < ProcNum; i++) { index[i] = index[i - 1] + 1; } for (int i = 0; i < 2 * ProcNum - 2; i++) { if (i < ProcNum - 1) { edges[i] = i + 1; } else { edges[i] = 0; } } MPI_Graph_create(MPI_COMM_WORLD, ProcNum, index, edges, 1, &starcomm); return starcomm; }
21.317073
74
0.543478
Stepakrap
22c6082b118ca58824432a9561c72c53a5c49d74
10,452
cpp
C++
lib/libstereo/src/stereo_sgmp.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
4
2020-12-28T15:29:15.000Z
2021-06-27T12:37:15.000Z
lib/libstereo/src/stereo_sgmp.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
null
null
null
lib/libstereo/src/stereo_sgmp.cpp
knicos/voltu
70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01
[ "MIT" ]
2
2021-01-13T05:28:39.000Z
2021-05-04T03:37:11.000Z
#include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include "stereo.hpp" #include "matching_cost.hpp" #include "stereo_common.hpp" #include "dsi.hpp" #include "cost_aggregation.hpp" #ifdef __GNUG__ #include <chrono> #include <iostream> /* static std::chrono::time_point<std::chrono::system_clock> start; static void timer_set() { start = std::chrono::high_resolution_clock::now(); } static void timer_print(const std::string &msg, const bool reset=true) { auto stop = std::chrono::high_resolution_clock::now(); char buf[24]; snprintf(buf, sizeof(buf), "%5i ms ", (int) std::chrono::duration_cast<std::chrono::milliseconds>(stop-start).count()); std::cout << buf << msg << "\n" << std::flush; if (reset) { timer_set(); } } */ static void timer_set() {} static void timer_print(const std::string &msg, const bool reset=true) {} #else static void timer_set() {} static void timer_print(const std::string &msg, const bool reset=true) {} #endif using cv::Mat; using cv::Size; static int ct_windows_w = 9; static int ct_windows_h = 7; struct StereoCensusSgmP::Impl { DisparitySpaceImage<unsigned short> dsi; CensusMatchingCost cost; Mat cost_min; Mat cost_min_paths; Mat uncertainty; Mat confidence; Mat disparity_r; Mat prior_disparity; Mat l; Mat r; Mat prior; Mat search; Impl(int width, int height, int min_disp, int max_disp) : dsi(width, height, min_disp, max_disp, ct_windows_w*ct_windows_h), cost(width, height, min_disp, max_disp, ct_windows_w, ct_windows_h), cost_min(height, width, CV_16UC1), cost_min_paths(height, width, CV_16UC1), uncertainty(height, width, CV_16UC1), confidence(height, width, CV_32FC1), disparity_r(height, width, CV_32FC1), prior_disparity(height, width, CV_32FC1) {} void cvtColor(const cv::Mat &iml, const cv::Mat &imr) { switch (iml.channels()) { case 4: cv::cvtColor(iml, l, cv::COLOR_BGRA2GRAY); break; case 3: cv::cvtColor(iml, l, cv::COLOR_BGR2GRAY); break; case 1: l = iml; break; default: throw std::exception(); } switch (imr.channels()) { case 4: cv::cvtColor(imr, r, cv::COLOR_BGRA2GRAY); break; case 3: cv::cvtColor(imr, r, cv::COLOR_BGR2GRAY); break; case 1: r = imr; break; default: throw std::exception(); } } }; static void compute_P2(const cv::Mat &prior, cv::Mat &P2) { } // prior CV32_FC1 // out CV8_UC2 // // TODO: range could be in depth units to get more meningful bounds static void compute_search_range(const cv::Mat &prior, cv::Mat &out, int dmin, int dmax, int range) { out.create(prior.size(), CV_8UC2); out.setTo(0); for (int y = 0; y < out.rows; y++) { for (int x = 0; x < out.cols; x ++) { int d = round(prior.at<float>(y,x)); auto &v = out.at<cv::Vec2b>(y,x); if ((d != 0) && (d >= dmin) && (d <= dmax)) { v[0] = std::max(dmin, d-range); v[1] = std::min(dmax, d+range); } else { v[0] = dmin; v[1] = dmax; } } } } /** * Compute 2D offset image. SGM sweeping direction set with dx and dy. * * Scharstein, D., Taniai, T., & Sinha, S. N. (2018). Semi-global stereo * matching with surface orientation priors. Proceedings - 2017 International * Conference on 3D Vision, 3DV 2017. https://doi.org/10.1109/3DV.2017.00033 */ static void compute_offset_image(const cv::Mat &prior, cv::Mat &out, const int dx, const int dy) { if (prior.empty()) { return; } out.create(prior.size(), CV_16SC1); out.setTo(0); int y_start; int y_stop; int x_start; int x_stop; if (dy < 0) { y_start = -dy; y_stop = prior.rows; } else { y_start = 0; y_stop = prior.rows - dy; } if (dx < 0) { x_start = -dx; x_stop = prior.cols; } else { x_start = 0; x_stop = prior.cols - dx; } for (int y = y_start; y < y_stop; y++) { const float *ptr_prior = prior.ptr<float>(y); const float *ptr_prior_r = prior.ptr<float>(y+dy); short *ptr_out = out.ptr<short>(y); for (int x = x_start; x < x_stop; x++) { // TODO types (assumes signed ptr_out and floating point ptr_prior) if (ptr_prior[x] != 0.0 && ptr_prior_r[x+dx] != 0.0) { ptr_out[x] = round(ptr_prior[x] - ptr_prior_r[x+dx]); } } } } struct AggregationParameters { Mat &prior; // Mat &search; // search range for each pixel CV_8UC2 Mat &min_cost; const StereoCensusSgmP::Parameters &params; }; inline int get_jump(const int y, const int x, const int d, const int dy, const int dx, const cv::Mat &prior) { if (prior.empty()) { return 0; } else if (dx == 1 && dy == 0) { return prior.at<short>(y, x); } else if (dx == -1 && dy == 0) { if (x == prior.cols - 1) { return 0; } return -prior.at<short>(y, x+1); } else if (dx == 0 && dy == 1) { return prior.at<short>(y, x); } else if (dx == 0 && dy == -1) { if (y == prior.rows - 1) { return 0; } return -prior.at<short>(y+1, x); } else if (dx == 1 && dy == 1) { return prior.at<short>(y, x); } else if (dx == -1 && dy == -1) { if (y == prior.rows - 1 || x == prior.cols - 1) { return 0; } return -prior.at<short>(y+1, x+1); } else if (dx == 1 && dy == -1) { return prior.at<short>(y, x); } else if (dx == -1 && dy == 1) { if (y == prior.rows - 1 || x == 0) { return 0; } return -prior.at<short>(y+1, x-1); } } template<typename T=unsigned short> inline void aggregate( AggregationData<CensusMatchingCost, DisparitySpaceImage<T>, T> &data, AggregationParameters &params) { auto &previous_cost_min = data.previous_cost_min; auto &previous = data.previous; auto &updates = data.updates; auto &out = data.out; const auto &in = data.in; const auto &x = data.x; const auto &y = data.y; const auto &i = data.i; const T P1 = params.params.P1; const T P2 = params.params.P2; T cost_min = in.cost_max; //int d_start = params.search.at<cv::Vec2b>(y,x)[0]; //int d_stop = params.search.at<cv::Vec2b>(y,x)[1]; int d_start = in.disp_min; int d_stop = in.disp_max; for (int d = d_start; d <= d_stop; d++) { const int j = get_jump(y, x, d, data.dy, data.dx, params.prior); const int d_j = std::max(std::min(d+j, previous.disp_max), previous.disp_min); const T L_min = std::min<T>(previous(0,i,d_j), std::min<T>(T(previous_cost_min + P2), std::min<T>(T(previous(0,i,std::min(d_j+1, previous.disp_max)) + P1), T(previous(0,i,std::max(d_j-1, previous.disp_min)) + P1)) ) ); T C = in(y,x,d); T cost_update = L_min + C - previous_cost_min; // stop if close to overflow if (cost_update > (std::numeric_limits<T>::max() - T(in.cost_max))) { throw std::exception(); } updates(0,i,d) = cost_update; cost_min = cost_update * (cost_update < cost_min) + cost_min * (cost_update >= cost_min); } /*const T update_skipped = params.params.P3; for (int d = out.disp_min; d < d_start; d++) { previous(0,i,d) = update_skipped; out(y,x,d) += update_skipped; }*/ for (int d = d_start; d <= d_stop; d++) { previous(0,i,d) = updates(0,i,d); out(y,x,d) += updates(0,i,d); } /*for (int d = d_stop+1; d <= out.disp_max; d++) { previous(0,i,d) = update_skipped; out(y,x,d) += update_skipped; }*/ params.min_cost.at<T>(y, x) = cost_min; previous_cost_min = cost_min; } StereoCensusSgmP::StereoCensusSgmP() : impl_(nullptr) { impl_ = new Impl(0, 0, 0, 0); } void StereoCensusSgmP::setPrior(const cv::Mat &prior) { prior.copyTo(impl_->prior_disparity); } void StereoCensusSgmP::compute(const cv::Mat &l, const cv::Mat &r, cv::Mat disparity) { impl_->dsi.clear(); impl_->uncertainty.setTo(0); if (l.rows != impl_->dsi.height || r.cols != impl_->dsi.width) { Mat prior = impl_->prior_disparity; delete impl_; impl_ = nullptr; impl_ = new Impl(l.cols, l.rows, params.d_min, params.d_max); if (prior.size() == l.size()) { impl_->prior_disparity = prior; } } impl_->cvtColor(l, r); timer_set(); // CT impl_->cost.setLeft(impl_->l); impl_->cost.setRight(impl_->r); if (params.debug) { timer_print("census transform"); } // cost aggregation AggregationParameters aggr_params = {impl_->prior, impl_->search, impl_->cost_min_paths, params}; compute_search_range(impl_->prior_disparity, impl_->search, params.d_min, params.d_max, params.range); if (params.paths & AggregationDirections::HORIZONTAL) { compute_offset_image(impl_->prior_disparity, impl_->prior, 1, 0); aggregate_horizontal_all<unsigned short>( aggregate<unsigned short>, impl_->cost, impl_->dsi, aggr_params); if (params.debug) { timer_print("horizontal aggregation"); } } if (params.paths & AggregationDirections::VERTICAL) { compute_offset_image(impl_->prior_disparity, impl_->prior, 0, 1); aggregate_vertical_all<unsigned short>( aggregate<unsigned short>, impl_->cost, impl_->dsi, aggr_params); if (params.debug) { timer_print("vertical aggregation"); } } if (params.paths & AggregationDirections::DIAGONAL1) { compute_offset_image(impl_->prior_disparity, impl_->prior, 1, 1); aggregate_diagonal_upper_all<unsigned short>( aggregate<unsigned short>, impl_->cost, impl_->dsi, aggr_params); if (params.debug) { timer_print("upper diagonal aggregation"); } } if (params.paths & AggregationDirections::DIAGONAL2) { compute_offset_image(impl_->prior_disparity, impl_->prior, 1, -1); aggregate_diagonal_lower_all<unsigned short>( aggregate<unsigned short>, impl_->cost, impl_->dsi, aggr_params); if (params.debug) { timer_print("lower diagonal aggregation"); } } if (!(params.paths & AggregationDirections::ALL)) { throw std::exception(); } // wta + consistency wta(impl_->dsi, disparity, impl_->cost_min, params.subpixel); wta_diagonal(impl_->disparity_r, impl_->dsi); consistency_check(disparity, impl_->disparity_r); // confidence estimate // Drory, A., Haubold, C., Avidan, S., & Hamprecht, F. A. (2014). // Semi-global matching: A principled derivation in terms of // message passing. Lecture Notes in Computer Science (Including Subseries // Lecture Notes in Artificial Intelligence and Lecture Notes in //Bioinformatics). https://doi.org/10.1007/978-3-319-11752-2_4 impl_->uncertainty = impl_->cost_min - impl_->cost_min_paths; // instead of difference, use ratio cv::divide(impl_->cost_min, impl_->cost_min_paths, impl_->confidence, CV_32FC1); // confidence threshold disparity.setTo(0.0f, impl_->uncertainty > params.uniqueness); cv::medianBlur(disparity, disparity, 3); } StereoCensusSgmP::~StereoCensusSgmP() { if (impl_) { delete impl_; impl_ = nullptr; } }
26.460759
110
0.658821
knicos
22d62a307f51a45b8905990dacdfc65973ff971f
6,313
cpp
C++
engine/source/kernel/storage/pack/storage_pack.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
engine/source/kernel/storage/pack/storage_pack.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
engine/source/kernel/storage/pack/storage_pack.cpp
skarab/coffee-master
6c3ff71b7f15735e41c9859b6db981b94414c783
[ "MIT" ]
null
null
null
#include "kernel/storage/pack/storage_pack.h" #include "kernel/core/core.h" #include "kernel/storage/logical/storage_system.h" namespace coffee { namespace storage { //-CONSTRUCTORS-------------------------------------------------------------------------------// Pack::Pack() : _FileAccess(NULL), _ItIsOpen(false) { } //--------------------------------------------------------------------------------------------// Pack::~Pack() { if (_FileAccess!=NULL) COFFEE_Delete(_FileAccess); } //-ACCESSORS----------------------------------------------------------------------------------// bool Pack::IsOpen() const { return _ItIsOpen; } //-QUERIES------------------------------------------------------------------------------------// uint32 Pack::FindFile(const Path& file_path) const { for (uint32 file_index=0 ; file_index<_FileArray.GetSize() ; ++file_index) { if (_FileArray[file_index]->GetPath()==file_path) return file_index; } return NONE; } //-OPERATIONS---------------------------------------------------------------------------------// bool Pack::Open(const Path& path, const MODE& mode) { if (_ItIsOpen) return true; COFFEE_Assert(_FileAccess==NULL, core::ERROR_CODE_Unexpected, "Unexpected error"); if (mode==MODE_Output && !System::Get().HasPath(path)) System::Get().SetFileData(path, Data(), true); _FileAccess = System::Get().GetFileAccess(path); if (_FileAccess==NULL) return false; _Mode = mode; if (mode==MODE_Output) { if (!System::Get().HasPath(path)) System::Get().SetFileData(path, Data(), true); if (!_FileAccess->Open(MODE_Input)) return false; _ReadFileList(); _FileAccess->Close(); if (!_FileAccess->Open(MODE_Output)) return false; } else { if (!_FileAccess->Open(MODE_Input)) return false; _ReadFileList(); } _ItIsOpen = true; return true; } //--------------------------------------------------------------------------------------------// void Pack::Close() { if (_ItIsOpen) { if (_Mode==MODE_Output) _WriteFileList(); _ItIsOpen = false; _FileAccess->Close(); COFFEE_Delete(_FileAccess); _FileAccess = NULL; _FileArray.Erase(); } } //--------------------------------------------------------------------------------------------// void Pack::AddFile(const Path& file_path, Stream& data_stream) { COFFEE_Assert(_Mode==MODE_Output, core::ERROR_CODE_IncorrectUsage, "Failed to write pack"); uint32 file_index = FindFile(file_path); PackFile* file; if (file_index!=NONE) { file = _FileArray[file_index]; } else { file = COFFEE_New(PackFile); _FileArray.AddItem(file); } file->SetPath(file_path); file->SetStream(&data_stream); } //--------------------------------------------------------------------------------------------// void Pack::RemoveFile(const Path& file_path) { COFFEE_Assert(_Mode==MODE_Output, core::ERROR_CODE_IncorrectUsage, "Failed to write pack"); uint32 file_index = FindFile(file_path); if (file_index!=NONE) _FileArray.Remove(file_index); } //--------------------------------------------------------------------------------------------// bool Pack::GetFile(const Path& file_path, Stream& data_stream) { COFFEE_Assert(_Mode==MODE_Input, core::ERROR_CODE_IncorrectUsage, "Failed to read pack"); uint32 file_index = FindFile(file_path); if (file_index!=NONE) { PackFile* file = _FileArray[file_index]; _FileAccess->SetOffset(file->GetOffset()); if (!data_stream.HasData()) data_stream.SetData(COFFEE_New(Data)); data_stream.GetData().Resize(file->GetSize()); _FileAccess->Read(data_stream.GetData().GetBuffer(), file->GetSize()); return true; } return false; } //-OPERATIONS---------------------------------------------------------------------------------// void Pack::_ReadFileList() { while (_FileAccess->GetOffset()<_FileAccess->GetSize()) { PackFile* file; basic::String path; ulong size; _FileAccess->ReadString(path); _FileAccess->Read((char*) &size, sizeof(ulong)); file = COFFEE_New(PackFile); file->SetPath(path); file->SetOffset(_FileAccess->GetOffset()); file->SetSize(size); if (_Mode==MODE_Output) { Stream* data_stream = COFFEE_New(Stream); data_stream->SetData(COFFEE_New(Data)); data_stream->GetData().Resize(file->GetSize()); _FileAccess->Read(data_stream->GetData().GetBuffer(), file->GetSize()); file->SetStream(data_stream); } else { _FileAccess->SetOffset(file->GetOffset() + size); } _FileArray.AddItem(file); } _FileAccess->SetOffset(0); } //--------------------------------------------------------------------------------------------// void Pack::_WriteFileList() { COFFEE_Assert(_Mode==MODE_Output, core::ERROR_CODE_IncorrectUsage, "Failed to write pack"); for (uint32 file_index=0 ; file_index<_FileArray.GetSize() ; ++file_index) { PackFile* file = _FileArray[file_index]; basic::String path = file->GetPath(); ulong size = file->GetStream().GetSize(); _FileAccess->WriteString(path); _FileAccess->Write((char *) &size, sizeof(ulong)); _FileAccess->Write(file->GetStream().GetData().GetBuffer(), size); } } } }
30.795122
100
0.456994
skarab
22e9d3b20d72b678ea7e97fcb5e007aa1610185d
256
cpp
C++
c++/day14/16.cpp
msoild/sword-to-offer
6c15c78ad773da0b66cb76c9e01292851aca45c5
[ "MIT" ]
null
null
null
c++/day14/16.cpp
msoild/sword-to-offer
6c15c78ad773da0b66cb76c9e01292851aca45c5
[ "MIT" ]
null
null
null
c++/day14/16.cpp
msoild/sword-to-offer
6c15c78ad773da0b66cb76c9e01292851aca45c5
[ "MIT" ]
null
null
null
class Solution { public: //notite size string replaceSpaces(string &str) { string retStr; for(auto&x : str) { if(x == ' ') retStr += "%20"; else retStr += x; } return retStr; } };
19.692308
41
0.445313
msoild
22f8b342aba95d8164beb293b3881536556a0fda
2,251
cpp
C++
day3/2.cpp
gian21391/advent_of_code-2021
2aa55a96e73cf7bb5ad152677e2136ca4eca1552
[ "MIT" ]
null
null
null
day3/2.cpp
gian21391/advent_of_code-2021
2aa55a96e73cf7bb5ad152677e2136ca4eca1552
[ "MIT" ]
null
null
null
day3/2.cpp
gian21391/advent_of_code-2021
2aa55a96e73cf7bb5ad152677e2136ca4eca1552
[ "MIT" ]
null
null
null
// // Created by Gianluca on 03/12/2021. // SPDX-License-Identifier: MIT // #include <utility/enumerate.hpp> #include <fstream> #include <cassert> #include <vector> #include <iostream> struct bit_values { int zeros = 0; int ones = 0; }; int main() { auto file = std::ifstream("../day3/input"); assert(file.is_open()); std::vector<bit_values> common_bits; std::vector<std::string> values; bool first_iteration = true; for(std::string line; std::getline(file, line);) { values.emplace_back(line); if (first_iteration) { common_bits.resize(line.size()); first_iteration = false; } for (auto [i, item] : enumerate(line)) { if (item == '0') common_bits[i].zeros++; else common_bits[i].ones++; } } std::vector<std::string> oxygen_values(values); std::vector<bit_values> oxygen_common_bits(common_bits); int i = 0; int remove_bit = -1; while (oxygen_values.size() > 1) { if (oxygen_common_bits[i].zeros > oxygen_common_bits[i].ones) remove_bit = 0; else remove_bit = 1; std::erase_if(oxygen_values, [&](auto value){ return (value[i] - '0') == remove_bit; }); oxygen_common_bits.clear(); oxygen_common_bits.resize(common_bits.size()); for (const auto& line : oxygen_values) { for (auto [j, item]: enumerate(line)) { if (item == '0') oxygen_common_bits[j].zeros++; else oxygen_common_bits[j].ones++; } } i++; } std::vector<std::string> co2_values(values); std::vector<bit_values> co2_common_bits(common_bits); i = 0; remove_bit = -1; while (co2_values.size() > 1) { if (co2_common_bits[i].zeros <= co2_common_bits[i].ones) remove_bit = 0; else remove_bit = 1; std::erase_if(co2_values, [&](auto value){ return (value[i] - '0') == remove_bit;}); co2_common_bits.clear(); co2_common_bits.resize(common_bits.size()); for (const auto& line : co2_values) { for (auto [j, item]: enumerate(line)) { if (item == '0') co2_common_bits[j].zeros++; else co2_common_bits[j].ones++; } } i++; } int oxygen = std::stoi(oxygen_values[0], nullptr, 2); int co2 = std::stoi(co2_values[0], nullptr, 2); std::cout << oxygen * co2 << std::endl; return 0; }
26.797619
92
0.625944
gian21391
22f92505909979895d6ff6045bbe2e6634e2477a
2,313
cpp
C++
thirdparty/threadpool/util.cpp
lynex/nnfusion
6332697c71b6614ca6f04c0dac8614636882630d
[ "MIT" ]
639
2020-09-05T10:00:59.000Z
2022-03-30T08:42:39.000Z
thirdparty/threadpool/util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
252
2020-09-09T05:35:36.000Z
2022-03-29T04:58:41.000Z
thirdparty/threadpool/util.cpp
QPC-database/nnfusion
99ada47c50f355ca278001f11bc752d1c7abcee2
[ "MIT" ]
104
2020-09-05T10:01:08.000Z
2022-03-23T10:59:13.000Z
#define NOMINMAX #include "util.h" #include "hwloc.h" #include <algorithm> namespace concurrency { static hwloc_topology_t hwloc_topology_handle; bool HaveHWLocTopology() { // One time initialization static bool init = []() { if (hwloc_topology_init(&hwloc_topology_handle)) { //LOG(ERROR) << "Call to hwloc_topology_init() failed"; return false; } if (hwloc_topology_load(hwloc_topology_handle)) { //LOG(ERROR) << "Call to hwloc_topology_load() failed"; return false; } return true; }(); return init; } // Return the first hwloc object of the given type whose os_index // matches 'index'. hwloc_obj_t GetHWLocTypeIndex(hwloc_obj_type_t tp, int index) { hwloc_obj_t obj = nullptr; if (index >= 0) { while ((obj = hwloc_get_next_obj_by_type(hwloc_topology_handle, tp, obj)) != nullptr) { if (obj->os_index == index) break; } } return obj; } bool NUMAEnabled() { return (NUMANumNodes() > 1); } int NUMANumNodes() { if (HaveHWLocTopology()) { int num_numanodes = hwloc_get_nbobjs_by_type(hwloc_topology_handle, HWLOC_OBJ_NUMANODE); return std::max(1, num_numanodes); } else { return 1; } } void NUMASetThreadNodeAffinity(int node) { // Find the corresponding NUMA node topology object. hwloc_obj_t obj = GetHWLocTypeIndex(HWLOC_OBJ_NUMANODE, node); if (obj) { hwloc_set_cpubind(hwloc_topology_handle, obj->cpuset, HWLOC_CPUBIND_THREAD | HWLOC_CPUBIND_STRICT); } else { //LOG(ERROR) << "Could not find hwloc NUMA node " << node; } } int NUMAGetThreadNodeAffinity() { int node_index = kNUMANoAffinity; if (HaveHWLocTopology()) { hwloc_cpuset_t thread_cpuset = hwloc_bitmap_alloc(); hwloc_get_cpubind(hwloc_topology_handle, thread_cpuset, HWLOC_CPUBIND_THREAD); hwloc_obj_t obj = nullptr; // Return the first NUMA node whose cpuset is a (non-proper) superset of // that of the current thread. while ((obj = hwloc_get_next_obj_by_type( hwloc_topology_handle, HWLOC_OBJ_NUMANODE, obj)) != nullptr) { if (hwloc_bitmap_isincluded(thread_cpuset, obj->cpuset)) { node_index = obj->os_index; break; } } hwloc_bitmap_free(thread_cpuset); } return node_index; } }
28.207317
80
0.675746
lynex
22f9a3ef4f2362a80ba6c70ed0535f554d603db7
987
cc
C++
src/leetcode/leetcode226_invert_binary_tree.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
src/leetcode/leetcode226_invert_binary_tree.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
src/leetcode/leetcode226_invert_binary_tree.cc
zhaozigu/algs-multi-langs
65ef5fc6df6236064a5c81e5bb7e99c4bae044a7
[ "CNRI-Python" ]
null
null
null
// https://leetcode-cn.com/problems/Invert-Binary-Tree/ #include <algorithm> using namespace std; #include "treenode.hpp" class Solution { public: TreeNode *invertTree(TreeNode *root) { if (root == nullptr) { return nullptr; } TreeNode *right_tree = root->right; root->right = invertTree(root->left); root->left = invertTree(right_tree); return root; } }; #include "gtest/gtest.h" TEST(leetcode226, sampleInputByProblem) { Solution solution; HeapTree in_nodes = {TNode(4), TNode(2), TNode(7), TNode(1), TNode(3), TNode(6), TNode(9)}; HeapTree expect_nodes = { TNode(4), TNode(7), TNode(2), TNode(9), TNode(6), TNode(3), TNode(9)}; ASSERT_EQ(7, solution.invertTree(BuildTree(in_nodes))->left->val); ASSERT_EQ(2, solution.invertTree(BuildTree(in_nodes))->right->val); ASSERT_EQ(6, solution.invertTree(BuildTree(in_nodes))->left->right->val); ASSERT_EQ(3, solution.invertTree(BuildTree(in_nodes))->right->left->val); }
25.973684
93
0.676798
zhaozigu
fe083697651f5529af34a59b39b2229678d9ad23
1,479
cpp
C++
Conta/src/conta.cpp
Italo1994/LAB03
6a0137690174c15f64cf54df9c4ceec7f05c2c19
[ "MIT" ]
null
null
null
Conta/src/conta.cpp
Italo1994/LAB03
6a0137690174c15f64cf54df9c4ceec7f05c2c19
[ "MIT" ]
null
null
null
Conta/src/conta.cpp
Italo1994/LAB03
6a0137690174c15f64cf54df9c4ceec7f05c2c19
[ "MIT" ]
null
null
null
#include <string> #include "conta.h" using std::string; Conta::Conta(string m_agencia, int m_numero, double m_saldo, string m_status, double m_limite, double m_limiteDisponivel, int m_movimentacao, int m_numMovimentacoes) : agencia(m_agencia), numero(m_numero), saldo(m_saldo), status(m_status), limite(m_limite), limiteDisponivel(m_limiteDisponivel), movimentacoes(m_movimentacao), numMovimentacao(m_numMovimentacoes) { } Conta::Conta(){ } Conta::~Conta(){ } void Conta::setAgencia(string m_agencia){ agencia = m_agencia; } void Conta::setNumero(int m_numero){ numero = m_numero; } void Conta::setSaldo(double m_saldo){ saldo = m_saldo; } void Conta::setStatus(string m_status){ status = m_status; } void Conta::setLimite(double m_limite){ limite = m_limite; } void Conta::setMovimentacoes(int m_movimentacoes){ movimentacoes = m_movimentacoes; } void Conta::setNumMovimentacoes(int m_numMov){ numMovimentacao = m_numMov; } void Conta::setId(int m_idConta){ idConta = m_idConta; } string Conta::getAgencia(){ return agencia; } int Conta::getNumero(){ return numero; } double Conta::getSaldo(){ return saldo; } string Conta::getStatus(){ return status; } double Conta::getLimite(){ return limite; } int Conta::getMovimentacoes(){ return movimentacoes; } int Conta::getId(){ return idConta; } int Conta::getNumMovimentacoes(){ return numMovimentacao; } int Conta::totalContas = 0;
17.4
198
0.716024
Italo1994
fe0911dcb842e5ffe140d34cc914a5fbd5fc8d6b
1,295
cc
C++
file_position.cc
codedumper1/mysql-ripple
bb9e3656519597c97d2c67ace918022c9b669d58
[ "Apache-2.0" ]
358
2019-01-25T22:47:12.000Z
2022-03-25T09:35:03.000Z
file_position.cc
codedumper1/mysql-ripple
bb9e3656519597c97d2c67ace918022c9b669d58
[ "Apache-2.0" ]
30
2019-01-29T22:13:30.000Z
2022-01-07T01:50:33.000Z
file_position.cc
codedumper1/mysql-ripple
bb9e3656519597c97d2c67ace918022c9b669d58
[ "Apache-2.0" ]
44
2019-01-28T06:34:45.000Z
2022-01-15T09:36:58.000Z
// Copyright 2018 The Ripple 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 "file_position.h" #include "absl/strings/numbers.h" namespace mysql_ripple { bool FilePosition::Parse(absl::string_view sv) { if (sv.size() <= 1) { return false; } if (sv.front() == '\'' && sv.back() == '\'') { sv = sv.substr(1, sv.size() - 2); } else { if (sv.front() == '\'' || sv.back() == '\'') { return false; } } auto pos = sv.find(':'); if (pos == 0 || pos == absl::string_view::npos) { return false; } filename = std::string(sv.substr(0, pos)); return absl::SimpleAtoi(sv.substr(pos + 1), &offset); } std::string FilePosition::ToString() const { return filename + ":" + std::to_string(offset); } } // namespace mysql_ripple
26.979167
75
0.648649
codedumper1
fe09186af8bdb23aa48d1b950473fe8d7e26f176
230
cpp
C++
SculptEngine/CppLib/src/Collisions/Ray.cpp
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
2
2019-12-14T02:06:52.000Z
2022-01-12T19:25:03.000Z
SculptEngine/CppLib/src/Collisions/Ray.cpp
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
1
2020-02-08T07:34:49.000Z
2020-02-08T07:34:49.000Z
SculptEngine/CppLib/src/Collisions/Ray.cpp
ErwanLeGoffic/Tectrid
81eb17410339c683905c0f7f16dc4f1dd6b6ddeb
[ "MIT" ]
1
2019-01-27T22:32:49.000Z
2019-01-27T22:32:49.000Z
#include "Ray.h" #ifdef __EMSCRIPTEN__ #include <emscripten/bind.h> using namespace emscripten; EMSCRIPTEN_BINDINGS(Ray) { class_<Ray>("Ray") .constructor<Vector3 const&, Vector3 const&, float>(); } #endif // __EMSCRIPTEN__
17.692308
56
0.734783
ErwanLeGoffic
fe0af7278502ff2500ff9a70862a33d3c134cb55
2,177
hpp
C++
Lab2/Lab2/CircularQueue.hpp
erickque/mte-140
d6d48a72b51c8223fa95655be132fe5b18bd8e7d
[ "BSD-4-Clause-UC" ]
null
null
null
Lab2/Lab2/CircularQueue.hpp
erickque/mte-140
d6d48a72b51c8223fa95655be132fe5b18bd8e7d
[ "BSD-4-Clause-UC" ]
null
null
null
Lab2/Lab2/CircularQueue.hpp
erickque/mte-140
d6d48a72b51c8223fa95655be132fe5b18bd8e7d
[ "BSD-4-Clause-UC" ]
null
null
null
// CircularQueue implements a queue using an array as a circular track. #ifndef CIRCULAR_QUEUE_HPP #define CIRCULAR_QUEUE_HPP class CircularQueue { friend class CircularQueueTest; public: // Can be seen outside as CircularQueue::QueueItem typedef int QueueItem; // Used as an indicator of empty queue. static const QueueItem EMPTY_QUEUE; // Default constructor used to initialise the circular queue class. // Default capacity is 16. CircularQueue(); CircularQueue(unsigned int capacity); // Destructor. ~CircularQueue(); // Takes as an argument a QueueItem value. If the queue is not full, it // inserts the value at the rear of the queue (after the last item), and // returns true. It returns false if the process fails. bool enqueue(QueueItem value); // Returns the value at the front of the queue. If the queue is not empty, // the front item is removed from it. If the queue was empty before the // dequeue, the EMPTY_QUEUE constant is returned. QueueItem dequeue(); // Returns the value at the front of the queue without removing it from the // queue. If the queue was empty before the peek, the EMPTY_QUEUE constant is // returned. QueueItem peek() const; // Returns true if the queue is empty and false otherwise. bool empty() const; // Returns true if the queue is full and false otherwise. bool full() const; // Returns the number of items in the queue. int size() const; // Rrints the queue items sequentially ordered from the front to the rear of // the queue. void print() const; private: // Override copy constructor and assignment operator in private so we can't // use them. CircularQueue(const CircularQueue& other) {} //CircularQueue operator=(const CircularQueue& other) {} private: // As the capacity is fixed, you may as well use an array here. QueueItem *items_; // Indices for keeping track of the circular array int head_, tail_; int capacity_; int size_; }; #endif
31.550725
82
0.663757
erickque
fe107a95debad2e1e40da444af800d98800874c2
524
cpp
C++
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheModule.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
null
null
null
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheModule.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
null
null
null
Plugins/GeometryCache/Source/GeometryCache/Private/GeometryCacheModule.cpp
greenrainstudios/AlembicUtilities
3970988065aef6861898a5185495e784a0c43ecb
[ "MIT" ]
1
2021-01-22T09:11:51.000Z
2021-01-22T09:11:51.000Z
// Copyright Epic Games, Inc. All Rights Reserved. #include "GeometryCacheModule.h" #if WITH_EDITOR #include "GeometryCacheEdModule.h" #endif // WITH_EDITOR #include "CodecV1.h" IMPLEMENT_MODULE(FGeometryCacheModule, GeometryCache) void FGeometryCacheModule::StartupModule() { #if WITH_EDITOR FGeometryCacheEdModule& Module = FModuleManager::LoadModuleChecked<FGeometryCacheEdModule>(TEXT("GeometryCacheEd")); #endif FCodecV1Decoder::InitLUT(); } void FGeometryCacheModule::ShutdownModule() { }
22.782609
118
0.767176
greenrainstudios
fe1773f4e57c483aeb5dd5e7c9771ca215ff0e08
4,298
cpp
C++
expressions/aggregation/AggregationHandleMax.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
82
2016-04-18T03:59:06.000Z
2019-02-04T11:46:08.000Z
expressions/aggregation/AggregationHandleMax.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
265
2016-04-19T17:52:43.000Z
2018-10-11T17:55:08.000Z
expressions/aggregation/AggregationHandleMax.cpp
Hacker0912/quickstep-datalog
1de22e7ab787b5efa619861a167a097ff6a4f549
[ "Apache-2.0" ]
68
2016-04-18T05:00:34.000Z
2018-10-30T12:41:02.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "expressions/aggregation/AggregationHandleMax.hpp" #include <cstddef> #include <cstdint> #include <memory> #include <vector> #include "catalog/CatalogTypedefs.hpp" #include "expressions/aggregation/AggregationID.hpp" #include "storage/ValueAccessorMultiplexer.hpp" #include "types/Type.hpp" #include "types/TypedValue.hpp" #include "types/operations/comparisons/Comparison.hpp" #include "types/operations/comparisons/ComparisonFactory.hpp" #include "types/operations/comparisons/ComparisonID.hpp" #include "glog/logging.h" namespace quickstep { class ColumnVector; AggregationHandleMax::AggregationHandleMax(const Type &type) : AggregationConcreteHandle(AggregationID::kMax), type_(type) { fast_comparator_.reset( ComparisonFactory::GetComparison(ComparisonID::kGreater) .makeUncheckedComparatorForTypes(type, type.getNonNullableVersion())); } AggregationState* AggregationHandleMax::accumulateValueAccessor( const std::vector<MultiSourceAttributeId> &argument_ids, const ValueAccessorMultiplexer &accessor_mux) const { DCHECK_EQ(1u, argument_ids.size()) << "Got wrong number of attributes for MAX: " << argument_ids.size(); const ValueAccessorSource argument_source = argument_ids.front().source; const attribute_id argument_id = argument_ids.front().attr_id; DCHECK(argument_source != ValueAccessorSource::kInvalid); DCHECK_NE(argument_id, kInvalidAttributeID); return new AggregationStateMax(fast_comparator_->accumulateValueAccessor( type_.getNullableVersion().makeNullValue(), accessor_mux.getValueAccessorBySource(argument_source), argument_id)); } void AggregationHandleMax::mergeStates(const AggregationState &source, AggregationState *destination) const { const AggregationStateMax &max_source = static_cast<const AggregationStateMax &>(source); AggregationStateMax *max_destination = static_cast<AggregationStateMax *>(destination); if (!max_source.max_.isNull()) { compareAndUpdate(max_destination, max_source.max_); } } void AggregationHandleMax::mergeStates(const std::uint8_t *source, std::uint8_t *destination) const { const TypedValue *src_max_ptr = reinterpret_cast<const TypedValue *>(source); TypedValue *dst_max_ptr = reinterpret_cast<TypedValue *>(destination); if (!(src_max_ptr->isNull())) { compareAndUpdate(dst_max_ptr, *src_max_ptr); } } ColumnVector* AggregationHandleMax::finalizeHashTable( const AggregationStateHashTableBase &hash_table, const std::size_t index, std::vector<std::vector<TypedValue>> *group_by_keys) const { return finalizeHashTableHelper<AggregationHandleMax>( type_, hash_table, index, group_by_keys); } AggregationState* AggregationHandleMax::aggregateOnDistinctifyHashTableForSingle( const AggregationStateHashTableBase &distinctify_hash_table) const { return aggregateOnDistinctifyHashTableForSingleUnaryHelper< AggregationHandleMax, AggregationStateMax>( distinctify_hash_table); } void AggregationHandleMax::aggregateOnDistinctifyHashTableForGroupBy( const AggregationStateHashTableBase &distinctify_hash_table, const std::size_t index, AggregationStateHashTableBase *aggregation_hash_table) const { aggregateOnDistinctifyHashTableForGroupByUnaryHelper<AggregationHandleMax>( distinctify_hash_table, index, aggregation_hash_table); } } // namespace quickstep
38.035398
81
0.769195
Hacker0912
fe2243b3722b197b9f5544425a57ac2fb289dfc5
14,942
cpp
C++
Rendering/Renderer.cpp
CakeWithSteak/fpf
e3a48478215a5b8623f0df76f730534b545ae9c3
[ "MIT" ]
null
null
null
Rendering/Renderer.cpp
CakeWithSteak/fpf
e3a48478215a5b8623f0df76f730534b545ae9c3
[ "MIT" ]
null
null
null
Rendering/Renderer.cpp
CakeWithSteak/fpf
e3a48478215a5b8623f0df76f730534b545ae9c3
[ "MIT" ]
null
null
null
#include "glad/glad.h" #include "Renderer.h" #include <vector> #include <stdexcept> #include <cuda_runtime.h> #include <cuda_gl_interop.h> #include <driver_types.h> #include <algorithm> #include "../Computation/safeCall.h" #include "utils.h" #include "../Computation/shared_types.h" float data[] = { //XY position and UV coordinates -1, 1, 0, 0, //top left -1, -1, 0, 1, //bottom left 1, 1, 1, 0, //top right 1, 1, 1, 0, //top right -1, -1, 0, 1, //bottom left 1, -1, 1, 1, //bottom right }; void Renderer::init(std::string_view cudaCode) { glGenFramebuffers(1, &framebuffer); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); unsigned int VAOs[2]; glGenVertexArrays(2, VAOs); mainVAO = VAOs[0]; overlayVAO = VAOs[1]; unsigned int VBOs[2]; glGenBuffers(2, VBOs); unsigned int mainVBO = VBOs[0]; overlayLineVBO = VBOs[1]; //Init overlay structures glBindVertexArray(overlayVAO); glBindBuffer(GL_ARRAY_BUFFER, overlayLineVBO); glBufferData(GL_ARRAY_BUFFER, 2 * std::max(MAX_PATH_STEPS, SHAPE_TRANS_DEFAULT_POINTS) * sizeof(double), nullptr, GL_DYNAMIC_DRAW); //Line vertices glVertexAttribLPointer(0, 2, GL_DOUBLE, sizeof(double) * 2, nullptr); glEnableVertexAttribArray(0); //Init main structures glBindVertexArray(mainVAO); glBindBuffer(GL_ARRAY_BUFFER, mainVBO); glBufferData(GL_ARRAY_BUFFER, sizeof(data), data, GL_STATIC_DRAW); //Position glVertexAttribPointer(0, 2, GL_FLOAT, false, sizeof(float) * 4, nullptr); glEnableVertexAttribArray(0); //UV glVertexAttribPointer(1, 2, GL_FLOAT, false, sizeof(float) * 4, (void*)(sizeof(float) * 2)); glEnableVertexAttribArray(1); glLineWidth(2); glPointSize(4); initTextures(); initShaders(); initCuda(); initKernels(cudaCode); } void Renderer::initTextures(bool setupProxy) { unsigned int textures[2]; glGenTextures(setupProxy ? 2 : 1, textures); distTexture = textures[0]; if(setupProxy) { proxyTexture = textures[1]; //Init proxy texture glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, proxyTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, proxyTexture, 0); } //Init dist texture glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, distTexture); //Allocates one-channel float32 texture glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, width, height); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } void Renderer::initShaders() { mainShader.use(); mainShader.setUniform("distances", 0); mainShader.setUniform("maxHue", mode.maxHue); minimumUniform = mainShader.getUniformLocation("minDist"); maximumUniform = mainShader.getUniformLocation("maxDist"); if(mode.staticMinMax.has_value()) { mainShader.setUniform(minimumUniform, mode.staticMinMax->first); mainShader.setUniform(maximumUniform, mode.staticMinMax->second); } overlayShader.use(); viewCenterUniform = overlayShader.getUniformLocation("viewportCenter"); viewBreadthUniform = overlayShader.getUniformLocation("viewportBreadth"); proxyShader.use(); proxyShader.setUniform("tex", 1); } void Renderer::initCuda(bool registerPathRes) { CUDA_SAFE(cudaSetDevice(0)); numBlocks = ceilDivide(width * height, 1024); CUDA_SAFE(cudaMallocManaged(&cudaBuffer, 2 * numBlocks * sizeof(float))); //Buffer for min/max fpdist values CUDA_SAFE(cudaGraphicsGLRegisterImage(&cudaSurfaceRes, distTexture, GL_TEXTURE_2D, cudaGraphicsRegisterFlagsSurfaceLoadStore)); cudaSurfaceDesc.resType = cudaResourceTypeArray; if(mode.isAttractor) { size_t numAttractors = static_cast<int>(width * ATTRACTOR_RESOLUTION_MULT) * static_cast<int>(height * ATTRACTOR_RESOLUTION_MULT); CUDA_SAFE(cudaMalloc(&attractorsDeviceBuffer, numAttractors * sizeof(HostFloatComplex))); attractorsHostBuffer = std::make_unique<HostFloatComplex[]>(numAttractors); } if(registerPathRes) { CUDA_SAFE(cudaMallocManaged(&cudaPathLengthPtr, sizeof(int))); CUDA_SAFE(cudaGraphicsGLRegisterBuffer(&overlayBufferRes, overlayLineVBO, cudaGraphicsRegisterFlagsWriteDiscard)); } } Renderer::~Renderer() { CUDA_SAFE(cudaGraphicsUnregisterResource(cudaSurfaceRes)); CUDA_SAFE(cudaGraphicsUnregisterResource(overlayBufferRes)); CUDA_SAFE(cudaFree(cudaBuffer)); CUDA_SAFE(cudaFree(cudaPathLengthPtr)); CUDA_SAFE(cudaFree(attractorsDeviceBuffer)); } void Renderer::render(int maxIters, double metricArg, const std::complex<double>& p, float colorCutoff) { pm.enter(PERF_RENDER); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); auto [start, end] = viewport.getCorners(); size_t numAttractors = (mode.isAttractor) ? findAttractors(maxIters, metricArg, p) : 0; CUDA_SAFE(cudaGraphicsMapResources(1, &cudaSurfaceRes)); auto surface = createSurface(); pm.enter(PERF_KERNEL); if(doublePrec) launch_kernel_double(kernel, start.real(), end.real(), start.imag(), end.imag(), maxIters, cudaBuffer, surface, width, height, p.real(), p.imag(), mode.prepMetricArg(metricArg), attractorsDeviceBuffer, numAttractors); else launch_kernel_float(kernel, start.real(), end.real(), start.imag(), end.imag(), maxIters, cudaBuffer, surface, width, height, p.real(), p.imag(), mode.prepMetricArg(metricArg), attractorsDeviceBuffer, numAttractors); CUDA_SAFE(cudaDeviceSynchronize()); pm.exit(PERF_KERNEL); CUDA_SAFE(cudaDestroySurfaceObject(surface)); CUDA_SAFE(cudaGraphicsUnmapResources(1, &cudaSurfaceRes)); mainShader.use(); if(!mode.staticMinMax.has_value()) { auto [min, max] = (mode.isAttractor) ? std::make_pair(0.0f, static_cast<float>(numAttractors)) : interleavedMinmax(cudaBuffer, 2 * numBlocks); mainShader.setUniform(minimumUniform, min); mainShader.setUniform(maximumUniform, std::min(max, colorCutoff)); std::cout << "Min: " << min << " max: " << max << "\n"; } glBindVertexArray(mainVAO); glDrawArrays(GL_TRIANGLES, 0, 6); if(isOverlayActive()) { refreshOverlayIfNeeded(p, metricArg); pm.enter(PERF_OVERLAY_RENDER); glBindVertexArray(overlayVAO); overlayShader.use(); overlayShader.setUniform(viewCenterUniform, viewport.getCenter().real(), viewport.getCenter().imag()); overlayShader.setUniform(viewBreadthUniform, viewport.getBreadth()); glDrawArrays(GL_POINTS, 0, getOverlayLength()); if(connectOverlayPoints) glDrawArrays(GL_LINE_STRIP, 0, getOverlayLength()); pm.exit(PERF_OVERLAY_RENDER); } pm.exit(PERF_RENDER); } void Renderer::paint() { glBindFramebuffer(GL_FRAMEBUFFER, 0); glBindVertexArray(mainVAO); proxyShader.use(); glDrawArrays(GL_TRIANGLES, 0, 6); } cudaSurfaceObject_t Renderer::createSurface() { CUDA_SAFE(cudaGraphicsSubResourceGetMappedArray(&cudaSurfaceDesc.res.array.array, cudaSurfaceRes, 0, 0)); cudaSurfaceObject_t surface; CUDA_SAFE(cudaCreateSurfaceObject(&surface, &cudaSurfaceDesc)); return surface; } void Renderer::initKernels(std::string_view cudaCode) { auto funcs = compiler.Compile(cudaCode, "runtime.cu", {"kernel", "genFixedPointPath", "transformShape", "findAttractors"}, mode, doublePrec); kernel = funcs[0]; pathKernel = funcs[1]; shapeTransformKernel = funcs[2]; findAttractorsKernel = funcs[3]; } std::string Renderer::getPerformanceReport() { return pm.generateReports(); } void Renderer::resize(int newWidth, int newHeight) { width = newWidth; height = newHeight; CUDA_SAFE(cudaFree(cudaBuffer)); CUDA_SAFE(cudaFree(attractorsDeviceBuffer)); CUDA_SAFE(cudaGraphicsUnregisterResource(cudaSurfaceRes)); glBindTexture(GL_TEXTURE_2D, 0); glDeleteTextures(1, &distTexture); glActiveTexture(GL_TEXTURE1); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, newWidth, newHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, nullptr); initTextures(false); initCuda(false); } int Renderer::generatePath(const std::complex<double>& z, double metricArg, const std::complex<double>& p) { pm.enter(PERF_OVERLAY_GEN); lastP = p; double tolerance = (mode.argIsTolerance) ? metricArg : DEFAULT_PATH_TOLERANCE; lastTolerance = tolerance; pathStart = z; void* bufferPtr; CUDA_SAFE(cudaGraphicsMapResources(1, &overlayBufferRes)); CUDA_SAFE(cudaGraphicsResourceGetMappedPointer(&bufferPtr, nullptr, overlayBufferRes)); if(doublePrec) { launch_kernel_generic(pathKernel, 1, 1, z.real(), z.imag(), MAX_PATH_STEPS, tolerance * tolerance, bufferPtr, cudaPathLengthPtr, p.real(), p.imag()); } else { std::complex<float> fz(z), fp(p); launch_kernel_generic(pathKernel, 1, 1, fz.real(), fz.imag(), MAX_PATH_STEPS, static_cast<float>(tolerance * tolerance), bufferPtr, cudaPathLengthPtr, fp.real(), fp.imag()); } CUDA_SAFE(cudaDeviceSynchronize()); CUDA_SAFE(cudaGraphicsUnmapResources(1, &overlayBufferRes)); pathEnabled = true; pm.exit(PERF_OVERLAY_GEN); return *cudaPathLengthPtr; } void Renderer::refreshOverlayIfNeeded(const std::complex<double>& p, double metricArg) { double tolerance = (mode.argIsTolerance) ? metricArg : DEFAULT_PATH_TOLERANCE; if(std::abs(lastP - p) > PATH_PARAM_UPDATE_THRESHOLD || (std::abs(lastTolerance - tolerance) > PATH_TOL_UPDATE_THRESHOLD && pathEnabled)) { lastP = p; lastTolerance = tolerance; if(pathEnabled) generatePath(pathStart, tolerance, p); else if(shapeTransEnabled) generateShapeTransformImpl(p); } } void Renderer::hideOverlay() { pathEnabled = false; shapeTransEnabled = false; } std::vector<unsigned char> Renderer::exportImageData() { pm.enter(PERF_FRAME_EXPORT_TIME); glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); glReadBuffer(GL_COLOR_ATTACHMENT0); glPixelStorei(GL_PACK_ALIGNMENT, 1); long size = width * height * 3; std::vector<unsigned char> data(size); glReadnPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, size, data.data()); pm.exit(PERF_FRAME_EXPORT_TIME); return data; } void Renderer::generateShapeTransform(ShapeProps shape, int iteration, const std::complex<double>& p, int numShapePoints) { shapeTransProps = shape; shapeTransIteration = iteration; shapeTransEnabled = true; //Make sure we don't overflow the overlay VBO if(numShapePoints > SHAPE_TRANS_DEFAULT_POINTS) { std::cerr << "ERROR: Number of shape transform points can't exceed " << SHAPE_TRANS_DEFAULT_POINTS << "." << std::endl; numShapePoints = SHAPE_TRANS_DEFAULT_POINTS; } shapeTransNumPoints = (numShapePoints == -1) ? SHAPE_TRANS_DEFAULT_POINTS : numShapePoints; generateShapeTransformImpl(p); } void Renderer::setShapeTransformIteration(int iteration, const std::complex<double>& p, bool disableIncremental) { auto lastIterations = shapeTransIteration; shapeTransIteration = iteration; if(!disableIncremental) generateShapeTransformImpl(p, lastIterations); else generateShapeTransformImpl(p); } void Renderer::generateShapeTransformImpl(const std::complex<double>& p, int lastIterations) { pm.enter(PERF_LINE_TRANS_GEN); constexpr int BLOCK_SIZE = 1024; lastP = p; int itersToDo; bool incremental = false; if(lastIterations == -1 || shapeTransIteration < lastIterations || mode.capturing) { itersToDo = shapeTransIteration; } else { itersToDo = shapeTransIteration - lastIterations; incremental = true; } void* bufferPtr; CUDA_SAFE(cudaGraphicsMapResources(1, &overlayBufferRes)); CUDA_SAFE(cudaGraphicsResourceGetMappedPointer(&bufferPtr, nullptr, overlayBufferRes)); if(doublePrec) { launch_kernel_generic(shapeTransformKernel, shapeTransNumPoints, BLOCK_SIZE, *shapeTransProps, p.real(), p.imag(), shapeTransNumPoints, itersToDo, incremental, bufferPtr); } else { std::complex<float> fp(p); launch_kernel_generic(shapeTransformKernel, shapeTransNumPoints, BLOCK_SIZE, *shapeTransProps, fp.real(), fp.imag(), shapeTransNumPoints, itersToDo, incremental, bufferPtr); } CUDA_SAFE(cudaDeviceSynchronize()); CUDA_SAFE(cudaGraphicsUnmapResources(1, &overlayBufferRes)); pm.exit(PERF_LINE_TRANS_GEN); } int Renderer::getOverlayLength() { if(pathEnabled) return *cudaPathLengthPtr; else if(shapeTransEnabled) return shapeTransNumPoints; else throw std::runtime_error("getOverlayLength called without overlay active"); } void Renderer::togglePointConnections() { connectOverlayPoints = !connectOverlayPoints; } size_t Renderer::findAttractors(int maxIters, double metricArg, const std::complex<double>& p) { constexpr int BLOCK_SIZE = 256; pm.enter(PERF_ATTRACTOR); int aWidth = width * ATTRACTOR_RESOLUTION_MULT; int aHeight = height * ATTRACTOR_RESOLUTION_MULT; size_t bufSize = aWidth * aHeight; auto [start, end] = viewport.getCorners(); auto tolerance = (mode.argIsTolerance) ? metricArg : 0.05f; if(doublePrec) { launch_kernel_generic(findAttractorsKernel, bufSize, BLOCK_SIZE, start.real(), end.real(), start.imag(), end.imag(), maxIters, p.real(), p.imag(), tolerance * tolerance, aWidth, aHeight, attractorsDeviceBuffer, ATTRACTOR_MATCH_TOL); } else { std::complex<float> fstart(start), fend(end), fp(p); float ftol = tolerance, F_ATTRACTOR_MATCH_TOL = ATTRACTOR_MATCH_TOL; launch_kernel_generic(findAttractorsKernel, bufSize, BLOCK_SIZE, fstart.real(), fend.real(), fstart.imag(), fend.imag(), maxIters, fp.real(), fp.imag(), ftol * ftol, aWidth, aHeight, attractorsDeviceBuffer, F_ATTRACTOR_MATCH_TOL); } CUDA_SAFE(cudaDeviceSynchronize()); CUDA_SAFE(cudaMemcpy(attractorsHostBuffer.get(), attractorsDeviceBuffer, bufSize * sizeof(HostFloatComplex), cudaMemcpyDeviceToHost)); auto res = deduplicateWithTol(attractorsHostBuffer.get(), aWidth * aHeight, ATTRACTOR_MATCH_TOL, MAX_ATTRACTORS); CUDA_SAFE(cudaMemcpy(attractorsDeviceBuffer, attractorsHostBuffer.get(), res * sizeof(HostFloatComplex), cudaMemcpyHostToDevice)); std::cout << "Attractors: " << res; if(res == MAX_ATTRACTORS) std::cout << " (max)"; std::cout << std::endl; pm.exit(PERF_ATTRACTOR); return res; }
37.923858
240
0.715433
CakeWithSteak
fe2616d15d918ea2abc95cd86f753a5351b1eb7a
5,200
cpp
C++
example/offscreen.cpp
UsiTarek/vkfw
ed25b204146ce4013597706ccce3e72f49ae3462
[ "Apache-2.0" ]
33
2021-01-20T17:10:26.000Z
2022-03-27T03:32:21.000Z
example/offscreen.cpp
UsiTarek/vkfw
ed25b204146ce4013597706ccce3e72f49ae3462
[ "Apache-2.0" ]
1
2022-03-25T22:55:27.000Z
2022-03-26T06:55:29.000Z
example/offscreen.cpp
UsiTarek/vkfw
ed25b204146ce4013597706ccce3e72f49ae3462
[ "Apache-2.0" ]
5
2021-06-29T03:30:06.000Z
2022-03-25T22:57:02.000Z
//======================================================================== // Offscreen rendering example // Copyright (c) Camilla Löwy <elmindreda@glfw.org> // // 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. // //======================================================================== // // Conversion to vkfw (and C++): John Cvelth <cvelth.mail@gmail.com> #include <glad/glad.h> #define VKFW_NO_INCLUDE_VULKAN_HPP #include <vkfw/vkfw.hpp> #if USE_NATIVE_OSMESA #define GLFW_EXPOSE_NATIVE_OSMESA #include <GLFW/glfw3native.h> #endif #include "linmath.h" #include <stdlib.h> #include <stdio.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> static const struct { float x, y; float r, g, b; } vertices[3] = { { -0.6f, -0.4f, 1.f, 0.f, 0.f }, { 0.6f, -0.4f, 0.f, 1.f, 0.f }, { 0.f, 0.6f, 0.f, 0.f, 1.f } }; static const char *vertex_shader_text = "#version 110\n" "uniform mat4 MVP;\n" "attribute vec3 vCol;\n" "attribute vec2 vPos;\n" "varying vec3 color;\n" "void main()\n" "{\n" " gl_Position = MVP * vec4(vPos, 0.0, 1.0);\n" " color = vCol;\n" "}\n"; static const char *fragment_shader_text = "#version 110\n" "varying vec3 color;\n" "void main()\n" "{\n" " gl_FragColor = vec4(color, 1.0);\n" "}\n"; static void error_callback(int error, const char *description) { fprintf(stderr, "Error #%d: %s\n", error, description); } int main(void) { try { vkfw::setErrorCallback(error_callback); vkfw::InitHints init_hints; init_hints.cocoaMenubar = false; auto instance = vkfw::initUnique(init_hints); vkfw::WindowHints hints; hints.clientAPI = vkfw::ClientAPI::eOpenGL; hints.contextVersionMajor = 2u; hints.contextVersionMinor = 0u; hints.visible = false; auto window = vkfw::createWindowUnique(640, 480, "Simple example", hints); window->makeContextCurrent(); gladLoadGLLoader((GLADloadproc) &vkfw::getProcAddress); // NOTE: OpenGL error checks have been omitted for brevity GLuint vertex_buffer, vertex_shader, fragment_shader, program; glGenBuffers(1, &vertex_buffer); glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL); glCompileShader(vertex_shader); fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL); glCompileShader(fragment_shader); program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); GLint mvp_location, vpos_location, vcol_location; mvp_location = glGetUniformLocation(program, "MVP"); vpos_location = glGetAttribLocation(program, "vPos"); vcol_location = glGetAttribLocation(program, "vCol"); glEnableVertexAttribArray(vpos_location); glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void *) 0); glEnableVertexAttribArray(vcol_location); glVertexAttribPointer(vcol_location, 3, GL_FLOAT, GL_FALSE, sizeof(vertices[0]), (void *) (sizeof(float) * 2)); auto size = window->getFramebufferSize(); int width = static_cast<int>(std::get<0>(size)), height = static_cast<int>(std::get<1>(size)); float ratio = (float) width / (float) height; glViewport(0, 0, (GLsizei) width, (GLsizei) height); glClear(GL_COLOR_BUFFER_BIT); mat4x4 mvp; mat4x4_ortho(mvp, -ratio, ratio, -1.f, 1.f, 1.f, -1.f); glUseProgram(program); glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat *) mvp); glDrawArrays(GL_TRIANGLES, 0, 3); glFinish(); #if USE_NATIVE_OSMESA char *buffer; glfwGetOSMesaColorBuffer(window, &width, &height, NULL, (void **) &buffer); #else char *buffer = static_cast<char *>(calloc(4, width * height)); glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buffer); #endif // Write image Y-flipped because OpenGL stbi_write_png("offscreen.png", width, height, 4, buffer + (width * 4 * (height - 1)), -width * 4); #if USE_NATIVE_OSMESA // Here is where there's nothing #else free(buffer); #endif } catch (std::system_error &err) { char error_message[] = "An error has occured: "; strcat(error_message, err.what()); fprintf(stderr, error_message); return -1; } }
29.885057
77
0.693846
UsiTarek
fe2838a58a50c1f33922597e95e8dbd43e86961e
2,850
cpp
C++
day2/placement/data/data_maker/6/std.cpp
DiamondJack/CTSC2018
a3a6ed27d61915ce08bcce4160970a9aeea39a0c
[ "Apache-2.0" ]
2
2019-03-22T11:13:53.000Z
2020-08-28T03:05:02.000Z
day2/placement/data/data_maker/6/std.cpp
DiamondJack/CTSC2018
a3a6ed27d61915ce08bcce4160970a9aeea39a0c
[ "Apache-2.0" ]
null
null
null
day2/placement/data/data_maker/6/std.cpp
DiamondJack/CTSC2018
a3a6ed27d61915ce08bcce4160970a9aeea39a0c
[ "Apache-2.0" ]
null
null
null
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; const int maxn=2010; int n,m,k,en; int t[maxn][maxn],r[maxn][maxn],in[maxn]; int res[maxn]; bool use[maxn][maxn]; char args[100][100]; char djm[1000]; int ans=0x3f3f3f3f; struct edge { int e,f; edge *next,*op; }*v[maxn],ed[maxn*maxn]; void add_edge(int s,int e) { en++; ed[en].next=v[s];v[s]=ed+en;v[s]->e=e; } int judge() { sprintf(djm,"..\\simulator.exe %s %s",args[1],args[2]); system(djm); FILE *f=fopen("res.txt","r"); int v; fscanf(f,"%d",&v); fclose(f); return v; } //start from here void init() { FILE *f = fopen(args[1],"r"); fscanf(f,"%d%d%d%*d",&n,&m,&k); for (int a=1;a<=m;a++) { int s,e; fscanf(f,"%d%d",&s,&e); add_edge(s,e); use[s][e]=true; in[e]++; } for (int a=1;a<=n;a++) for (int b=1;b<=k;b++) fscanf(f,"%d",&t[a][b]); for (int a=1;a<=k;a++) for (int b=1;b<=k;b++) fscanf(f,"%d",&r[a][b]); fclose(f); } int depth[maxn],q[maxn]; void add_edge(int s,int e,int f) { en++; ed[en].next=v[s];v[s]=ed+en;v[s]->e=e;v[s]->f=f; en++; ed[en].next=v[e];v[e]=ed+en;v[e]->e=s;v[e]->f=0; v[s]->op=v[e];v[e]->op=v[s]; } bool bfs() { memset(depth,0,sizeof(depth)); int front=1,tail=1; q[1]=0; depth[0]=1; for (;front<=tail;) { int now=q[front++]; for (edge *e=v[now];e;e=e->next) if (e->f && !depth[e->e]) { depth[e->e]=depth[now]+1; q[++tail]=e->e; } } return depth[n<<1|1]!=0; } int dfs(int now,int flow) { if (now==(n<<1|1)) return flow; int rest=flow; for (edge *e=v[now];e && rest;e=e->next) if (e->f && depth[e->e]==depth[now]+1) { int cur_flow=dfs(e->e,min(e->f,rest)); rest-=cur_flow; e->f-=cur_flow; e->op->f+=cur_flow; } return flow-rest; } int dinic() { int ans=0; while (bfs()) ans+=dfs(0,0x3f3f3f3f); return ans; } void work() { en=0; memset(v,0,sizeof(v)); for (int a=1;a<=n;a++) { add_edge(0,a,t[a][1]); add_edge(a,a+n,0x3f3f3f3f); add_edge(a+n,n<<1|1,t[a][2]); } for (int a=1;a<=n;a++) for (int b=1;b<=n;b++) if (use[a][b]) { add_edge(a,b+n,r[2][1]); add_edge(b,a+n,r[1][2]); } int ans=dinic(); for (edge *e=v[0];e;e=e->next) if (!e->f) res[e->e]=1; else res[e->e]=2; for (edge *e=v[n<<1|1];e;e=e->next) if (!e->op->f) { if (res[e->e-n]==1) printf("%d gg\n",e->e-n); } else { if (res[e->e-n]==2) printf("%d gg\n",e->e-n); } FILE *f=fopen(args[2],"w"); for (int a=1;a<=n;a++) fprintf(f,"%d%c",res[a],a==n?'\n':' '); fclose(f); int v=judge(); if (v!=ans) { printf("%d sb\n",ans); } } void output() { FILE *f=fopen(args[2],"w"); for (int a=1;a<=n;a++) fprintf(f,"%d%c",res[a],a==n?'\n':' '); fclose(f); } int main(int argc,char *argss[]) { for (int a=0;a<argc;a++) sprintf(args[a],"%s",argss[a]); init(); work(); output(); return 0; }
15.405405
56
0.521754
DiamondJack
fe2a8e7b53edce67e0b7e90a6ec41f4a104a6f01
1,866
cpp
C++
classes/input/pointer.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
24
2017-08-22T15:55:34.000Z
2022-03-06T11:41:31.000Z
classes/input/pointer.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
6
2018-07-21T12:17:55.000Z
2021-08-12T11:27:27.000Z
classes/input/pointer.cpp
Patriccollu/smooth
8673d4702c55b1008bbcabddf7907da0e50505e4
[ "Artistic-2.0" ]
9
2017-09-13T02:32:18.000Z
2022-03-06T11:41:32.000Z
/* The smooth Class Library * Copyright (C) 1998-2013 Robert Kausch <robert.kausch@gmx.net> * * This library is free software; you can redistribute it and/or * modify it under the terms of "The Artistic License, Version 2.0". * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include <smooth/input/pointer.h> #include <smooth/input/backends/pointerbackend.h> #include <smooth/init.h> S::Int addPointerInitTmp = S::AddInitFunction(&S::Input::Pointer::Initialize); S::Int addPointerFreeTmp = S::AddFreeFunction(&S::Input::Pointer::Free); S::Input::PointerBackend *S::Input::Pointer::backend = NIL; const S::GUI::Window *S::Input::Pointer::pointerWindow = NIL; S::GUI::Point S::Input::Pointer::mousePosition = S::GUI::Point(); S::Input::Pointer::Pointer() { } S::Input::Pointer::Pointer(const Pointer &) { } S::Int S::Input::Pointer::Initialize() { backend = PointerBackend::CreateBackendInstance(); return Success(); } S::Int S::Input::Pointer::Free() { delete backend; return Success(); } S::Bool S::Input::Pointer::SetCursor(const GUI::Window *window, CursorType mouseCursor) { return backend->SetCursor(window, mouseCursor); } const S::GUI::Point &S::Input::Pointer::GetPosition() { return mousePosition; } const S::GUI::Window *S::Input::Pointer::GetPointerWindow() { return pointerWindow; } S::Void S::Input::Pointer::UpdatePosition(const GUI::Window *window, Int x, Int y) { pointerWindow = window; mousePosition.x = x; mousePosition.y = y; /* FixMe: The -2 offsets seem to be necessary on * all X11 systems. However, I somehow feel * this can't be the right way to do it. */ #ifndef __WIN32__ mousePosition.x -= 2; mousePosition.y -= 2; #endif }
24.552632
87
0.706324
Patriccollu
fe2d3154917901af60089b6e1e1fe7d232382fd4
17,861
cpp
C++
src/universe/vehicle/plumbing/VehiclePlumbing.cpp
TheOpenSpaceProgram/new-ospgl
646ee5229ce4c35856aae0d41b514c86c33791a2
[ "MIT" ]
22
2019-11-15T22:07:17.000Z
2022-01-13T16:40:01.000Z
src/universe/vehicle/plumbing/VehiclePlumbing.cpp
TheOpenSpaceProgram/new-ospgl
646ee5229ce4c35856aae0d41b514c86c33791a2
[ "MIT" ]
25
2020-03-03T00:54:21.000Z
2021-12-30T16:24:22.000Z
src/universe/vehicle/plumbing/VehiclePlumbing.cpp
TheOpenSpaceProgram/new-ospgl
646ee5229ce4c35856aae0d41b514c86c33791a2
[ "MIT" ]
3
2020-03-04T00:36:13.000Z
2020-06-01T20:53:51.000Z
#include "VehiclePlumbing.h" #include "../Vehicle.h" // A reasonable multiplier to prevent extreme flow velocities // I don't know enough fluid mechanics as to determine a reasonable value // so it's arbitrary, chosen to approximate real life rocket values #define FLOW_MULTIPLIER 0.0002 void VehiclePlumbing::update_pipes(float dt, Vehicle* in_veh) { assign_flows(dt); sanify_flow(dt); simulate_flow(dt); } void VehiclePlumbing::assign_flows(float dt) { for(const PipeJunction& jnc : junctions) { junction_flow_rate(jnc, dt); } for(Pipe& p : pipes) { if(p.junction != nullptr) continue; // TODO: Obtain density by averaging or something float sqrt_density = 1.0f; float pa = p.ma->plumbing.get_pressure(p.port_a); float pb = p.mb->plumbing.get_pressure(p.port_b); float sign = pa > pb ? -1.0f : 1.0f; float constant = p.surface * sqrt(2.0f) / sqrt_density; p.flow = sign * constant * sqrt(glm::abs(pb - pa)) * FLOW_MULTIPLIER; } } void VehiclePlumbing::sanify_flow(float dt) { for(PipeJunction& jnc : junctions) { // Liquid volume, gases always fit as they are compressible! float total_accepted_volume = 0.0f; float total_given_volume = 0.0f; StoredFluids f_total = StoredFluids(); // Find how much will be given for(Pipe* p : jnc.pipes) { if(p->flow < 0.0f) continue; // This pipe gives to the junction, find how much would it give StoredFluids f = p->mb->plumbing.out_flow(p->port_b, p->flow * dt, false); float vol = f.get_total_liquid_volume(); if(vol == 0.0f && f.get_total_gas_mass() != 0.0f && f.get_total_liquid_mass() == 0.0f) { // We are draining gases, no need to change flow } else if(vol < p->flow * dt) { // This pipe cannot supply enough, flow is clamped p->flow = vol; } total_given_volume += vol; f_total.modify(f); } // Find how much will be taken for(const Pipe* p : jnc.pipes) { if(p->flow > 0.0f) continue; // This pipe takes from the junction, find how much would it take // We don't care about gases here as they can be taken in infinite ammounts StoredFluids in = f_total.modify(f_total.multiply(-p->flow * dt)); StoredFluids not_taken = p->mb->plumbing.in_flow(p->port_b, in, false); total_accepted_volume += -dt * p->flow - not_taken.get_total_liquid_volume(); } if(total_accepted_volume < total_given_volume) { // Sanify flow, the giving pipes must give less. This is done // in a uniform manner, by multiplying flow of every pipe float factor = total_accepted_volume / total_given_volume; for(Pipe* p : jnc.pipes) { if(p->flow < 0.0f) p->flow *= factor; } } } for(Pipe& p : pipes) { if(p.junction != nullptr) continue; } } // Very similar to sanify but does the actual flow and handles gases void VehiclePlumbing::simulate_flow(float dt) { for(PipeJunction& jnc : junctions) { StoredFluids f_total = StoredFluids(); // Take from pipes for(const Pipe* p : jnc.pipes) { if(p->flow < 0.0f) continue; StoredFluids f = p->mb->plumbing.out_flow(p->port_b, p->flow * dt, true); f_total.modify(f); } for(const Pipe* p : jnc.pipes) { if(p->flow > 0.0f) continue; StoredFluids in = f_total.modify(f_total.multiply(-p->flow * dt)); StoredFluids not_taken = p->mb->plumbing.in_flow(p->port_b, in, true); // TODO: Handle gases? logger->check(not_taken.get_total_liquid_mass() < 0.001f, "Fluids were not conserved!"); } } for(Pipe& p : pipes) { } } void VehiclePlumbing::junction_flow_rate(const PipeJunction& junction, float dt) { size_t jsize = junction.pipes.size(); // We impose the condition that sum(flow) = 0, and // as flow = ct * sqrt(deltaP), we can solve // 0 = sqrt(Pj - Pa) + sqrt(Pj - Pb) ... // Receiving tanks are added as -sqrt(Pa - Pj) as Pj > Pa // This setup divides our function into at max n parts, // with edges that we can determine: They are simply the // pressures sorted from high to low. // Sorted from highest pressure to lowest, safe to keep short-lived pointer std::vector<std::pair<Pipe*, float>> pipe_pressure; pipe_pressure.reserve(jsize); for(auto& pipe : junction.pipes) { float pr = pipe->mb->plumbing.get_pressure(pipe->port_b); pipe_pressure.emplace_back(pipe, pr); } std::sort(pipe_pressure.begin(), pipe_pressure.end(), [](const std::pair<Pipe*, float>& a, const std::pair<Pipe*, float>& b) { return a.second > b.second; }); // TODO: Obtain density by averaging or something float sqrt_density = 1.0f; auto evaluate = [pipe_pressure, jsize, sqrt_density](float x, size_t section, bool diff = false) -> std::pair<float, float> { // These later on will be read from the pipe float sum = 0.0f; float diff_sum = 0.0f; for(size_t i = 0; i < jsize; i++) { float sign = i > (jsize - 2 - section) ? -1.0f : 1.0f; float dP = (pipe_pressure[i].second - x); float constant = pipe_pressure[i].first->surface * sqrt(2.0f) / sqrt_density; float radical = sqrt(glm::abs(dP)); if(diff) { diff_sum -= constant / (2.0f * radical); } sum += sign * constant * radical; } return std::make_pair(sum, diff_sum); }; size_t solution_section = 0; float x = 0.0f, fx; for(size_t i = 0; i < jsize - 1; i++) { float lP = pipe_pressure[i].second; float rP = pipe_pressure[i + 1].second; float left = evaluate(lP, i).first; float right = evaluate(rP, i).first; if(left * right < 0.0f) { solution_section = i; x = (lP + rP) / 2.0f; break; } } // Find an approximation of the solution, we use the Newton Rhapson method as // it's well behaved in this kind of function and converges VERY fast // TODO: Check if the closed form solution is faster AND // TODO: if simply running the method on the whole piece-wise function // TODO: converges (fast) too! for(size_t it = 0; it < 2; it++) { auto pair = evaluate(x, solution_section, true); fx = pair.first; float dfx = pair.second; // if the derivative is small, we are near constant and can early quit if(glm::abs(dfx) < 0.0001) { break; } x = x - fx / dfx; } // fx is very close to the pressure at the junction now for(size_t i = 0; i < jsize; i++) { float sign = i > (jsize - 2 - solution_section) ? -1.0f : 1.0f; float constant = pipe_pressure[i].first->surface * sqrt(2.0f) / sqrt_density; pipe_pressure[i].first->flow = sign * constant * sqrt(glm::abs(pipe_pressure[i].second - x)) * FLOW_MULTIPLIER; } } VehiclePlumbing::VehiclePlumbing(Vehicle *in_vehicle) { veh = in_vehicle; pipe_id = 0; junction_id = 0; } std::vector<PlumbingElement> VehiclePlumbing::grid_aabb_check(glm::vec2 start, glm::vec2 end, const std::vector<PlumbingElement>& ignore, bool expand) { std::vector<PlumbingElement> out; for(const Part* p : veh->parts) { for (const auto &pair : p->machines) { bool ignored = false; for(PlumbingElement m : ignore) { if(m == pair.second) { ignored = true; break; } } if(pair.second->plumbing.has_lua_plumbing() && !ignored) { glm::ivec2 min = pair.second->plumbing.editor_position; glm::ivec2 max = min + pair.second->plumbing.get_editor_size(expand); if (min.x < end.x && max.x > start.x && min.y < end.y && max.y > start.y) { out.emplace_back(pair.second); } } } } // It's easier for junctions, note that we return pointers too for(PipeJunction& jnc : junctions) { bool ignored = false; for(PlumbingElement m : ignore) { if(m == &jnc) { ignored = true; break; } } glm::ivec2 min = jnc.pos; glm::ivec2 max = min + jnc.get_size(expand); if (min.x < end.x && max.x > start.x && min.y < end.y && max.y > start.y && !ignored) { out.emplace_back(&jnc); } } return out; } glm::ivec4 VehiclePlumbing::get_plumbing_bounds() { glm::ivec2 amin = glm::ivec2(INT_MAX, INT_MAX); glm::ivec2 amax = glm::ivec2(INT_MIN, INT_MIN); bool any = false; for(const Part* p : veh->parts) { for (const auto &pair : p->machines) { if (pair.second->plumbing.has_lua_plumbing()) { glm::ivec2 min = pair.second->plumbing.editor_position; glm::ivec2 max = min + pair.second->plumbing.get_editor_size(true); amin = glm::min(amin, min); amax = glm::max(amax, max); any = true; } } } if(any) { return glm::ivec4(amin.x, amin.y, amax.x - amin.x, amax.y - amin.y); } else { return glm::ivec4(0, 0, 0, 0); } } glm::ivec2 VehiclePlumbing::find_free_space(glm::ivec2 size) { // We first do a binary search in the currently used space // If that cannot be found, return outside of used space, to the // bottom as rockets are usually vertical glm::ivec4 bounds = get_plumbing_bounds(); return glm::ivec2(bounds.x, bounds.y + bounds.w); } glm::ivec2 VehiclePlumbing::get_plumbing_size_of(Part* p) { // min is always (0, 0) as that's the forced origin of the plumbing start positions glm::ivec2 max = glm::ivec2(INT_MIN, INT_MIN); bool found_any = false; for(const auto& pair : p->machines) { MachinePlumbing& pb = pair.second->plumbing; if(pb.has_lua_plumbing()) { found_any = true; max = glm::max(max, pb.editor_position + pb.get_editor_size()); } } if(found_any) { return max; } else { return glm::ivec2(0, 0); } } std::vector<PlumbingElement> VehiclePlumbing::get_all_elements() { std::vector<PlumbingElement> out; // Machines for(const Part* p : veh->parts) { for (const auto &pair : p->machines) { if (pair.second->plumbing.has_lua_plumbing()) { out.emplace_back(pair.second); } } } // Junctions for(PipeJunction& jnc : junctions) { out.emplace_back(&jnc); } return out; } Pipe* VehiclePlumbing::create_pipe() { size_t id = ++pipe_id; Pipe p = Pipe(); p.id = id; pipes.push_back(p); // Rebuild the junctions as pointers may change in the vector rebuild_pipe_pointers(); return &pipes[pipes.size() - 1]; } PipeJunction* VehiclePlumbing::create_pipe_junction() { size_t id = ++junction_id; PipeJunction j = PipeJunction(); j.id = id; junctions.push_back(j); // Rebuild junctions in pipes as they may have changed pointer rebuild_junction_pointers(); return &junctions[junctions.size() - 1]; } Pipe* VehiclePlumbing::get_pipe(size_t id) { for(Pipe& p : pipes) { if(p.id == id) { return &p; } } logger->fatal("Couldn't find pipe with id = {}", id); return nullptr; } PipeJunction* VehiclePlumbing::get_junction(size_t id) { for(PipeJunction& p : junctions) { if(p.id == id) { return &p; } } logger->fatal("Couldn't find pipe junction with id = {}", id); return nullptr; } void VehiclePlumbing::remove_pipe(size_t id) { bool found = false; for(size_t i = 0; i < pipes.size(); i++) { if(pipes[i].id == id) { pipes.erase(pipes.begin() + i); found = true; break; } } logger->check(found, "Couldn't find pipe with id= {} to remove", id); rebuild_pipe_pointers(); } void VehiclePlumbing::remove_junction(size_t id) { bool found = false; for(size_t i = 0; i < junctions.size(); i++) { if(junctions[i].id == id) { junctions.erase(junctions.begin() + i); found = true; break; } } logger->check(found, "Couldn't find junction with id= {} to remove", id); rebuild_junction_pointers(); } void VehiclePlumbing::rebuild_junction_pointers() { for(Pipe& p : pipes) { if(p.junction_id != 0) { PipeJunction* found = nullptr; for(PipeJunction& fj : junctions) { if(fj.id == p.junction_id) { found = &fj; break; } } logger->check(found != nullptr, "Couldn't find pipe junction with id = {}", p.junction_id); p.junction = found; } } } void VehiclePlumbing::rebuild_pipe_pointers() { for(PipeJunction& jnc : junctions) { if(jnc.pipes.size() == 0) { // This is the case during vehicle loading jnc.pipes.resize(jnc.pipes_id.size()); } for(size_t i = 0; i < jnc.pipes_id.size(); i++) { jnc.pipes[i] = get_pipe(jnc.pipes_id[i]); } } } glm::ivec2 PipeJunction::get_size(bool extend, bool rotate) const { size_t num_subs; if(get_port_number() <= 4) { num_subs = 1; } else { num_subs = ((get_port_number() - 5) / 2) + 2; } glm::ivec2 base = glm::ivec2(num_subs, 1); if(extend) { base += glm::ivec2(1, 1); } if(rotate && (rotation == 1 || rotation == 3)) { std::swap(base.x, base.y); } return base; } void PipeJunction::add_pipe(Pipe* p) { // Try to find a vacant slot for(size_t i = 0; i < pipes.size(); i++) { if(pipes[i] == nullptr && pipes_id[i] == 0xDEADBEEF) { pipes[i] = p; pipes_id[i] = p->id; return; } } // Otherwise add new pipe pipes.push_back(p); pipes_id.push_back(p->id); } glm::vec2 PipeJunction::get_port_position(const Pipe *p) { // Port positions are a.lways in the same order, same as rendering float f = 1.0f; size_t port_count = get_port_number(); int i = -1; for(size_t j = 0; j < pipes.size(); j++) { if(pipes[j] == p) { i = (int)j; } } logger->check(i != -1, "Couldn't find pipe with id = {}", p->id); glm::vec2 offset; if(port_count <= 4 || (i <= 3)) { if(i == 0) { offset = glm::vec2(0.0f, -1.0f); } else if(i == 1) { offset = glm::vec2(-1.0f, 0.0f); } else if(i == 2) { offset = glm::vec2(0.0f, 1.0f); } else if(i == 3) { offset = glm::vec2(1.0f, 0.0f); } } else { // Algorithmic procedure for ports to the right } // Rotation offset += glm::vec2(0.5f); glm::ivec2 size = get_size(false, false); if(rotation == 1) { std::swap(offset.x, offset.y); offset.x = size.x - offset.x; } else if(rotation == 2) { offset.x = (float)size.x - offset.x; offset.y = (float)size.y - offset.y; } else if(rotation == 3) { std::swap(offset.x, offset.y); offset.y = (float)size.y - offset.y; } return offset * f + (glm::vec2)pos; } // This works even for vacant pipes! size_t PipeJunction::get_port_id(const Pipe* p) { int fid = -1; for(size_t i = 0; i < pipes.size(); i++) { if(pipes[i] == p) { fid = (int)i; break; } } logger->check(fid != -1, "Could not find pipe for port id"); return (size_t)fid; } PlumbingElement::PlumbingElement(PipeJunction *junction) { as_junction = junction; type = JUNCTION; } PlumbingElement::PlumbingElement() { as_machine = nullptr; type = EMPTY; } PlumbingElement::PlumbingElement(Machine *machine) { as_machine = machine; type = MACHINE; } // This operator== functions may unnecesarly check type as afterall // there wont' be a machine and a pipe with the same memory index! bool PlumbingElement::operator==(const Machine* m) const { return type == MACHINE && as_machine == m; } bool PlumbingElement::operator==(const PipeJunction* jnc) const { return type == JUNCTION && as_junction == jnc; } // TODO: This one is specially stupid bool PlumbingElement::operator==(const PlumbingElement& j) const { if(type == MACHINE) { return as_machine == j.as_machine && j.type == MACHINE; } else if(type == JUNCTION) { return as_junction == j.as_junction && j.type == JUNCTION; } return false; } glm::ivec2 PlumbingElement::get_size(bool expand, bool rotate) { logger->check(type != EMPTY, "Tried to call get_size on an empty PlumbingElement"); if(type == MACHINE) { return as_machine->plumbing.get_editor_size(expand, rotate); } else if(type == JUNCTION) { return as_junction->get_size(expand, rotate); } return glm::ivec2(0, 0); } glm::ivec2 PlumbingElement::get_pos() { logger->check(type != EMPTY, "Tried to call get_pos on an empty PlumbingElement"); if(type == MACHINE) { return as_machine->plumbing.editor_position; } else if(type == JUNCTION) { return as_junction->pos; } return glm::ivec2(0, 0); } void PlumbingElement::set_pos(glm::ivec2 pos) { logger->check(type != EMPTY, "Tried to call set_pos on an empty PlumbingElement"); if(type == MACHINE) { as_machine->plumbing.editor_position = pos; } else if(type == JUNCTION) { as_junction->pos = pos; } } int PlumbingElement::get_rotation() { logger->check(type != EMPTY, "Tried to call get_rotation on an empty PlumbingElement"); if(type == MACHINE) { return as_machine->plumbing.editor_rotation; } else if(type == JUNCTION) { return as_junction->rotation; } return 0; } void PlumbingElement::set_rotation(int value) { logger->check(type != EMPTY, "Tried to call set_rotation on an empty PlumbingElement"); if(type == MACHINE) { as_machine->plumbing.editor_rotation = value; } else if(type == JUNCTION) { as_junction->rotation = value; } } std::vector<std::pair<FluidPort, glm::vec2>> PlumbingElement::get_ports() { logger->check(type != EMPTY, "Tried to call get_ports on an empty PlumbingElement"); std::vector<std::pair<FluidPort, glm::vec2>> out; if(type == MACHINE) { for(const FluidPort& p : as_machine->plumbing.fluid_ports) { glm::vec2 pos = as_machine->plumbing.get_port_position(p.id); out.emplace_back(p, pos); } } else if(type == JUNCTION) { for(const Pipe* p : as_junction->pipes) { glm::vec2 pos = as_junction->get_port_position(p); FluidPort port = FluidPort(); port.id = "__junction"; port.numer_id = as_junction->get_port_id(p); port.gui_name = "Junction Port"; port.marker = ""; out.emplace_back(port, pos); } } return out; } void Pipe::invert() { logger->check(junction == nullptr, "Cannot invert a pipe that goes to a junction as it must always be the end"); std::swap(ma, mb); std::swap(port_a, port_b); std::reverse(waypoints.begin(), waypoints.end()); } void Pipe::connect_junction(PipeJunction *jnc) { junction = jnc; junction_id = jnc->id; ma = nullptr; port_a = ""; jnc->add_pipe(this); } Pipe::Pipe() { id = 0; ma = nullptr; mb = nullptr; junction = nullptr; junction_id = 0; port_a = ""; port_b = ""; surface = 1.0f; flow = 0.0f; }
21.339307
125
0.649516
TheOpenSpaceProgram
fe3125c25dd4ac57df2898f8d0bf16aefc42bcfb
502
hpp
C++
owl/scene/light.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
owl/scene/light.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
owl/scene/light.hpp
soerenkoenig/owl
ab10054514a7a5b12a6b81665b3b264cfe37b0f3
[ "MIT" ]
null
null
null
// // .___. // {o,o} // ./)_) // owl --"-"--- // // Copyright © 2018 Sören König. All rights reserved. // #pragma once #include <chrono> namespace owl { namespace scene { enum class light_type { ambient, directional, spot, point }; template<typename Scalar, typename Color> class light { public: light_type type; Scalar intensity; Scalar temperature; Color color; }; } }
12.55
54
0.5
soerenkoenig
fe33d099e9167369f55f319dc61a9bd1e9d9adf7
1,498
hpp
C++
SDK/ARKSurvivalEvolved_Buff_Radiation_Sickness_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Buff_Radiation_Sickness_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Buff_Radiation_Sickness_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_Radiation_Sickness_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Buff_Radiation_Sickness.Buff_Radiation_Sickness_C // 0x000C (0x096C - 0x0960) class ABuff_Radiation_Sickness_C : public ABuff_Base_OnlyRelevantToOwner_C { public: float BuffTimeDecreaseRate; // 0x0960(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float InitialMaxStamina; // 0x0964(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float InitialMaxWeight; // 0x0968(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Buff_Radiation_Sickness.Buff_Radiation_Sickness_C"); return ptr; } void BuffTickClient(float* DeltaTime); void UserConstructionScript(); void ExecuteUbergraph_Buff_Radiation_Sickness(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
34.045455
208
0.59012
2bite
fe3abe9f69d4ccbbdf68b5b27e766cafa3958e47
1,937
cpp
C++
tests/LpmSphereVoronoiMeshUnitTests.cpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
tests/LpmSphereVoronoiMeshUnitTests.cpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
18
2021-06-27T17:59:03.000Z
2022-02-22T03:41:27.000Z
tests/LpmSphereVoronoiMeshUnitTests.cpp
pbosler/lpmKokkos
c8b4a8478c08957ce70a6fbd7da00481c53414b9
[ "BSD-3-Clause" ]
null
null
null
#include "LpmConfig.h" #include "LpmDefs.hpp" #include "Kokkos_Core.hpp" #include "LpmMeshSeed.hpp" #include "LpmSphereVoronoiPrimitives.hpp" #include "LpmSphereVoronoiMesh.hpp" #include "LpmVtkIO.hpp" #include <iostream> #include <iomanip> #include <string> #include <exception> using namespace Lpm; using namespace Voronoi; int main(int argc, char* argv[]) { ko::initialize(argc, argv); { std::ostringstream ss; ss << "Sphere Voronoi Mesh Unit tests:\n"; Int nerr=0; MeshSeed<IcosTriDualSeed> seed; VoronoiMesh<IcosTriDualSeed> vmesh0(seed, 0); std::vector<Index> vinds; std::vector<Index> einds0; std::vector<Index> einds1; std::vector<Index> finds; // std::cout << vmesh0.infoString(true); Voronoi::VtkInterface<IcosTriDualSeed> vtk; auto pd = vtk.toVtkPolyData(vmesh0); vtk.writePolyData("vmesh0.vtk", pd); for (Short i=0; i<vmesh0.nverts(); ++i) { vmesh0.getEdgesAndCellsAtVertex(einds0, finds, i); } for (Short i=0; i<vmesh0.ncells(); ++i) { vmesh0.getEdgesAndVerticesInCell(einds1, vinds, i); } for (Short i=0; i<vmesh0.ncells(); ++i) { const Real qpt[3] = {vmesh0.cells[i].xyz[0], vmesh0.cells[i].xyz[1], vmesh0.cells[i].xyz[2]}; const auto loc = vmesh0.cellContainingPoint(qpt, 0); if (loc != i) { ++nerr; } } for (Int i=5; i<7; ++i) { ss.str(std::string()); VoronoiMesh<IcosTriDualSeed> vmesh(seed,i); std::cout << vmesh.infoString(false); pd = vtk.toVtkPolyData(vmesh); ss << "vmesh" << i << ".vtk"; vtk.writePolyData(ss.str(),pd); } if (nerr>0) { throw std::runtime_error("point location identity test failed."); } if (nerr == 0) { ss << "\tall tests pass.\n"; std::cout << ss.str(); } else { throw std::runtime_error(ss.str()); } } ko::finalize(); return 0; }
24.2125
101
0.603511
pbosler
fe3f3a182ade1097886de34a2afef91e94945431
4,877
cpp
C++
sources/Base/spVertexFormatUniversal.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
14
2015-08-16T21:05:20.000Z
2019-08-21T17:22:01.000Z
sources/Base/spVertexFormatUniversal.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
null
null
null
sources/Base/spVertexFormatUniversal.cpp
rontrek/softpixel
73a13a67e044c93f5c3da9066eedbaf3805d6807
[ "Zlib" ]
3
2016-10-31T06:08:44.000Z
2019-08-02T16:12:33.000Z
/* * Universal vertex format file * * This file is part of the "SoftPixel Engine" (Copyright (c) 2008 by Lukas Hermanns) * See "SoftPixelEngine.hpp" for license information. */ #include "Base/spVertexFormatUniversal.hpp" #include "RenderSystem/spRenderSystem.hpp" namespace sp { extern video::RenderSystem* GlbRenderSys; namespace video { VertexFormatUniversal::VertexFormatUniversal() : VertexFormat( ), FormatSize_ (0 ) { } VertexFormatUniversal::~VertexFormatUniversal() { } u32 VertexFormatUniversal::getFormatSize() const { return FormatSize_; } void VertexFormatUniversal::addCoord(const ERendererDataTypes Type, s32 Size) { addAttribute(VERTEXFORMAT_COORD, Coord_, Size, Type, "POSITION", (Type == DATATYPE_FLOAT && Size == 3)); } void VertexFormatUniversal::addColor(const ERendererDataTypes Type, s32 Size) { addAttribute(VERTEXFORMAT_COLOR, Color_, Size, Type, "COLOR", (Type == DATATYPE_UNSIGNED_BYTE && Size == 4)); } void VertexFormatUniversal::addNormal(const ERendererDataTypes Type) { addAttribute(VERTEXFORMAT_NORMAL, Normal_, 3, Type, "NORMAL", (Type == DATATYPE_FLOAT)); } void VertexFormatUniversal::addBinormal(const ERendererDataTypes Type) { addAttribute(VERTEXFORMAT_BINORMAL, Binormal_, 3, Type, "BINORMAL", (Type == DATATYPE_FLOAT)); } void VertexFormatUniversal::addTangent(const ERendererDataTypes Type) { addAttribute(VERTEXFORMAT_TANGENT, Tangent_, 3, Type, "TANGENT", (Type == DATATYPE_FLOAT)); } void VertexFormatUniversal::addTexCoord(const ERendererDataTypes Type, s32 Size) { TexCoords_.resize(TexCoords_.size() + 1); addAttribute(VERTEXFORMAT_TEXCOORDS, TexCoords_[TexCoords_.size() - 1], Size, Type, "TEXCOORD" + io::stringc(TexCoords_.size() - 1)); } void VertexFormatUniversal::addFogCoord(const ERendererDataTypes Type) { addAttribute(VERTEXFORMAT_FOGCOORD, FogCoord_, 1, Type, "", (Type == DATATYPE_FLOAT)); } void VertexFormatUniversal::addUniversal( const ERendererDataTypes Type, s32 Size, const io::stringc &Name, bool Normalize, const EVertexFormatFlags Attribute) { Universals_.resize(Universals_.size() + 1); addAttribute(VERTEXFORMAT_UNIVERSAL, Universals_.back(), Size, Type, Name, false, Normalize); /* Link with special attribute */ switch (Attribute) { case VERTEXFORMAT_COORD: addVirtualAttribute(Attribute, Coord_); break; case VERTEXFORMAT_COLOR: addVirtualAttribute(Attribute, Color_); break; case VERTEXFORMAT_NORMAL: addVirtualAttribute(Attribute, Normal_); break; case VERTEXFORMAT_BINORMAL: addVirtualAttribute(Attribute, Binormal_); break; case VERTEXFORMAT_TANGENT: addVirtualAttribute(Attribute, Tangent_); break; case VERTEXFORMAT_FOGCOORD: addVirtualAttribute(Attribute, FogCoord_); break; case VERTEXFORMAT_TEXCOORDS: TexCoords_.resize(TexCoords_.size() + 1); addVirtualAttribute(Attribute, TexCoords_[TexCoords_.size() - 1]); break; default: break; } updateConstruction(); } void VertexFormatUniversal::remove(const EVertexFormatFlags Type) { switch (Type) { case VERTEXFORMAT_TEXCOORDS: TexCoords_.pop_back(); if (TexCoords_.empty()) removeFlag(Type); break; case VERTEXFORMAT_UNIVERSAL: Universals_.pop_back(); if (Universals_.empty()) removeFlag(Type); break; default: removeFlag(Type); break; } updateConstruction(); } void VertexFormatUniversal::clear() { if (FormatSize_) { /* Clear vertex attributes */ TexCoords_.clear(); Universals_.clear(); /* Reset format size */ FormatSize_ = 0; /* Delete vertex-input-layout (for D3D11 only) */ GlbRenderSys->updateVertexInputLayout(this, false); } } /* * ======= Private: ======= */ void VertexFormatUniversal::updateConstruction() { constructFormat(); VertexFormat::getFormatSize(FormatSize_); } void VertexFormatUniversal::addAttribute( const EVertexFormatFlags Flag, SVertexAttribute &Attrib, s32 Size, const ERendererDataTypes Type, const io::stringc &Name, bool hasDefaultSetting, bool Normalize) { addFlag(Flag); Attrib = SVertexAttribute(Size, Name, Type, hasDefaultSetting, Normalize); updateConstruction(); } void VertexFormatUniversal::addVirtualAttribute(const EVertexFormatFlags Attribute, SVertexAttribute &DestAttrib) { DestAttrib = Universals_.back(); DestAttrib.isReference = true; addFlag(Attribute); } } // /namespace video } // /namespace sp // ================================================================================
28.688235
137
0.67316
rontrek
fe414fd5ca9e82c15c166379487841e8f3ede12f
1,841
hpp
C++
GenericSimulator/GenericSimulatorTemplates/core/EntityFreeFunc.hpp
ducis/pile-of-cpp
af5a123ec67cff589f27bf20d435b2db29a0a7c8
[ "MIT" ]
null
null
null
GenericSimulator/GenericSimulatorTemplates/core/EntityFreeFunc.hpp
ducis/pile-of-cpp
af5a123ec67cff589f27bf20d435b2db29a0a7c8
[ "MIT" ]
null
null
null
GenericSimulator/GenericSimulatorTemplates/core/EntityFreeFunc.hpp
ducis/pile-of-cpp
af5a123ec67cff589f27bf20d435b2db29a0a7c8
[ "MIT" ]
null
null
null
//#pragma once // //#include <Meta/entity.hpp> //#include <entity_as_boost_fusion_sequence.hpp> // //namespace GenericSim{ // namespace Entities{ // template < // typename GenericSim::Meta::GetEntityLabels<_Entity>::Type N0, // typename _Entity // > // typename GenericSim::Meta::GetEntityAtResultType_E1<_Entity,N0>::Type // At_E(_Entity &e){// overload this function for different types // return e.at_e<N0>(); // } // // template < // typename GenericSim::Meta::GetEntityLabels<_Entity>::Type N0, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0>::Type >::Type N1, // typename _Entity // > // typename GenericSim::Meta::GetEntityAtResultType_E2<_Entity,N0,N1>::Type // At_E(_Entity &e){ // return At_E1<N1>(At_E1<N0>(e)); // } // // template < // typename GenericSim::Meta::GetEntityLabels<_Entity>::Type N0, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0>::Type >::Type N1, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0,N1>::Type >::Type N2, // typename _Entity // > // typename GenericSim::Meta::GetEntityAtResultType_E3<_Entity,N0,N1,N2>::Type // At_E(_Entity &e){ // return At_E1<N2>(At_E2<N0,N1>(e)); // } // // template < // typename GenericSim::Meta::GetEntityLabels<_Entity>::Type N0, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0>::Type >::Type N1, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0,N1>::Type >::Type N2, // typename GetEntityLabels< typename GetEntityStateType_E<_Entity,N0,N1,N2>::Type >::Type N3, // typename _Entity // > // typename GenericSim::Meta::GetEntityAtResultType_E4<_Entity,N0,N1,N2,N3>::Type // At_E(_Entity &e){ // return At_E1<N3>(At_E3<N0,N1,N2>(e)); // } // } //}
36.82
97
0.674633
ducis