hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
โŒ€
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
โŒ€
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
โŒ€
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
โŒ€
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
โŒ€
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
โŒ€
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
โŒ€
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
โŒ€
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
โŒ€
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
b1607af7253b77f7e7dfefcb0ccd0edf5ea10108
31,003
cpp
C++
src/softbody2/Physics_ParticleSystem_clean.cpp
jackthgu/K-AR_HYU_Deform_Simulation
e7c275c8948e1fe3e800ab37b17aa8406b147277
[ "MIT" ]
null
null
null
src/softbody2/Physics_ParticleSystem_clean.cpp
jackthgu/K-AR_HYU_Deform_Simulation
e7c275c8948e1fe3e800ab37b17aa8406b147277
[ "MIT" ]
null
null
null
src/softbody2/Physics_ParticleSystem_clean.cpp
jackthgu/K-AR_HYU_Deform_Simulation
e7c275c8948e1fe3e800ab37b17aa8406b147277
[ "MIT" ]
null
null
null
// Physics_Physics_ParticleSystem.cpp: implementation of the Physics_Physics_ParticleSystem class. // ////////////////////////////////////////////////////////////////////// #include "DRGShell.h" #include "Physics_Impulses.h" #include "../../gmm.h" #include "../../../../BaseLib/math/Operator.h" #include "../../../../BaseLib/math/Operator_NR.h" #include "../../../../PhysicsLib/sDIMS/lcp.h" #include "../../../QP_controller/quadprog.h" #include "../../../../MainLib/OgreFltk/objectList.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// //#define FLOOR_Y ((m_real)-0.99) #define FLOOR_Y ((m_real)30) void fMat_setReference(fMat& mat, matrixn const& matMine) { double* buffer; int stride, n, m, on; matMine._getPrivate(buffer, stride, n, m, on); Msg::verify(stride==n, "fMat_set failed!"); mat.setReference(buffer, n, m); } Physics_ParticleSystem::Physics_ParticleSystem( int iParticles ) : m_Positions( iParticles ), m_Velocities( iParticles ), m_dv( iParticles ), m_dp( iParticles ), m_vTemp1( iParticles ), m_vTemp2( iParticles ), m_vTemp3( iParticles ), m_PosTemp( iParticles ), m_TotalForces_int( iParticles ), m_TotalForces_ext( iParticles ), m_W( iParticles ), m_H( iParticles ), m_Masses( iParticles ), m_MassInv( iParticles ), m_MxMasses( iParticles, iParticles ), m_TotalForces_dp( iParticles, iParticles ), m_TotalForces_dv( iParticles, iParticles ), m_A( iParticles, iParticles ), m_P( iParticles ), m_PInv( iParticles ), m_MxTemp1( iParticles, iParticles ), m_MxTemp2( iParticles, iParticles ), m_z( iParticles ), m_b( iParticles ), m_r( iParticles ), m_c( iParticles ), m_q( iParticles ), m_s( iParticles ), m_y( iParticles ), mContacts(iParticles), m_vContactForce(iParticles) { //m_iIntegrationMethod = INTEGRATE_SEMI_IMPLICIT; m_iIntegrationMethod = INTEGRATE_IMPLICIT; m_cfg.m_dynamicFrictionCoef.resize(iParticles); m_cfg.m_dynamicFrictionCoef.setAllValue(0.0); m_cfg.DFthresholdVel=0.1; m_cfg.contactMethod=Config::LCP_METHOD; matrix3 matI; matI.identity(); for( int i=0; i<iParticles; i++ ) { m_Masses[i] = vector3( 1,1,1 ); m_MassInv[i] = vector3( 1,1,1 ); m_MxMasses(i,i)=matI; } m_S = new matrix3[iParticles]; m_iParticles = iParticles; m_vContactForce.zero(); m_TotalForces_int.zero(); m_TotalForces_ext.zero(); m_LastStep = 1.0; } Physics_ParticleSystem::~Physics_ParticleSystem() { SAFE_DELETE_ARRAY( m_S ); for(int i=0; i<m_Forces.size(); i++) delete m_Forces[i]; } void Physics_ParticleSystem::Update( float fTime ) { switch( m_iIntegrationMethod ) { case INTEGRATE_EXPLICIT: Update_Explicit( fTime ); break; case INTEGRATE_IMPLICIT: Update_Implicit( fTime ); break; case INTEGRATE_SEMI_IMPLICIT: Update_SemiImplicit( fTime ); break; } } void Physics_ParticleSystem::SetupMatrices() { Physics_Force *pForce ; //DWORD dwTimeIn = GetTickCount(), dwTimeOut; if( m_iIntegrationMethod != INTEGRATE_EXPLICIT ) { m_H.zero(); for(int i=0, ni=m_Forces.size(); i<ni; i++) { m_Forces[i]->PrepareMatrices(m_H, m_TotalForces_dp); } } // // Setup the implicit matrices // if( m_iIntegrationMethod == INTEGRATE_IMPLICIT ) { m_TotalForces_dv.Copy( m_TotalForces_dp ); m_A.Copy( m_TotalForces_dp ); m_MxTemp1.Copy( m_TotalForces_dp ); m_MxTemp2.Copy( m_TotalForces_dp ); } // // Setup the semi-implicit matrices // if( m_iIntegrationMethod == INTEGRATE_SEMI_IMPLICIT ) { m_W.identity(); m_H.Scale( (m_real)1.0/m_ParticleMass, m_H ); m_W.Subtract( m_H, m_W ); m_W.Invert(); } //dwTimeOut = GetTickCount(); //char szTemp[50]; //sprintf( szTemp, "Initialize: %lu msec\r\n", dwTimeOut - dwTimeIn ); //Msg::print("%s\n", szTemp ); } // // Use Explicit integration with Deformation Constraints // void Physics_ParticleSystem::Update_Explicit( float fTime ) { m_real fTotal = 0.0f, fStep = (m_real)fTime; vector3 vCOG, dTorque, tmp, tmp2; int i; while( fTotal < fTime ) { // // Zero out everything // m_TotalForces_int.zero(); m_TotalForces_ext.zero(); // // Apply the forces // for(int i=0, ni=m_Forces.size(); i<ni; i++) { m_Forces[i]->Apply(fStep, m_Masses, false, m_Positions, m_Velocities, m_TotalForces_int, m_TotalForces_ext, m_TotalForces_dp, m_TotalForces_dv ); } // // Compute the new velocities and positions // m_TotalForces_ext.Add( m_TotalForces_int, m_vTemp1 ); m_vTemp1.ElementMultiply( m_MassInv, m_dv ); m_dv.Scale( fStep, m_dv ); m_Velocities.Add( m_dv, m_Velocities ); m_Velocities.Scale( fStep, m_vTemp1 ); m_Positions.Add( m_vTemp1, m_PosTemp ); // // Apply inverse dynamics to prevent excessive stretch We need 10 or so // iterations to be stable -- with more particles in the mesh, we need // more iterations. // for( i=0; i<m_iInverseIterations; i++ ) { for(int i=0, ni=m_Forces.size(); i<ni; i++) { m_Forces[i]->Fixup( m_Masses, m_PosTemp ); } } // // Update velocity and position // m_PosTemp.Subtract( m_Positions, m_vTemp1 ); m_vTemp1.Scale( (m_real)1.0 / fStep, m_Velocities ); /*for( i=0; i<m_iParticles; i++ ) if( m_PosTemp[i].y < FLOOR_Y ) { m_PosTemp[i].y = FLOOR_Y; m_Velocities[i].y = 0; }*/ m_Positions = m_PosTemp; fTotal += (m_real)fabs( fStep ); } } void Physics_ParticleSystem::Update_Implicit( float fTime ) { int i,iIterations = 0, iMaxIterations = (int)sqrt(double(m_iParticles))+3; m_real fTotal = (m_real)0.0f, fStep = (m_real)fTime; m_real alpha, Delta_0, Delta_old, Delta_new; m_real Eps_Sq = (m_real)1e-22; while( fTotal < fTime ) { // // Zero out everything // m_TotalForces_int.zero(); m_TotalForces_ext.zero(); m_TotalForces_dp.zero(); m_TotalForces_dv.zero(); m_MxTemp1.zero(); m_MxTemp2.zero(); m_vTemp3.zero(); // Setting m_S and m_y Reset(); void *Pos = NULL; for(int i=0, ni=m_Forces.size(); i<ni; i++) { m_Forces[i]->Apply( fStep, m_Masses, true, m_Positions, m_Velocities, m_TotalForces_int, m_TotalForces_ext, m_TotalForces_dp, m_TotalForces_dv ); } // // Form the symmetric matrix A = M - h * df/dv - h_2 * df/dx (Baraff ๋…ผ๋ฌธ์˜ equation 6์˜ ์–‘๋ณ€์— M์„ ๊ณฑํ•œ์‹) // We regroup this as A = M - h * (df/dv + h * df/dx) // m_TotalForces_int+=m_TotalForces_ext; m_MxTemp1.mult(m_TotalForces_dp, fStep); m_MxTemp2.add(m_MxTemp1,m_TotalForces_dv); m_MxTemp1.mult(m_MxTemp2, fStep); m_A .sub(m_MxMasses,m_MxTemp1); static ObjectList* g_debugObject=NULL; if (g_debugObject==NULL) g_debugObject=new ObjectList(); matrixn lines_fvelocity(0, 3); matrixn lines_fforce(0, 3); matrixn lines_flvelocity(0, 3); matrixn lines_flforce(0, 3); matrixn lines_normal(0, 3); g_debugObject->registerObject("friction_contactForces", "LineList", "solidred", lines_fforce); g_debugObject->registerObject("friction_deltaVelocities", "LineList", "solidblue", lines_fvelocity); g_debugObject->registerObject("frictionless_contactForces", "LineList", "solidwhite", lines_flforce); g_debugObject->registerObject("frictionless_deltaVelocities", "LineList", "solidblack", lines_flvelocity); g_debugObject->registerObject("normalForces", "LineList", "solidgreen", lines_normal); if(m_cfg.contactMethod==Config::LCP_METHOD_FRICTIONLESS && mContacts_peneltyMethod.m_cti.size()) { // n: number of contact points int n=mContacts_peneltyMethod.m_cti.size(); // m: the number of particles involved in contact. at the moment, // m==n because we only consider FV collisions ignoring VF and EE // collisions. int m=n; // following matrix naming conventions follow [DAK04] and [DDKA06]. // [DAK04] C.Duriez, C. Andriot, and A.Kheddar, A multi-threaded // approach for deformable/rigid contacts with haptic feedback, // IEEE haptic symposium, 2004. // [DDKA06] Realistic Haptic Rendering of Interacting Deformable // Objects in Virtual Environments gmm::wsmatrixn H_v,H_f, H_D; H_v.resize(3*n,4*m); H_f.resize(3*n,4*m); H_D.resize(m, 3*m); vector3 u, v, tmp; vector3 tmp1, tmp2, tmp3, tmp4; m_real a,b; a=(m_real)0.5; b=(m_real)0.3; //quater q; vectorn a0; a0.setSize(m); for(int i=0; i<n; i++) { Physics_Contacts_Penalty::cti& c=mContacts_peneltyMethod.m_cti[i]; m_real a_temp=(m_real)c.penetratingDepth; a_temp*=(m_real)1.0/fStep; a0(i)=a_temp; H_D(i , i*3)=c.normal.x; H_D(i , i*3+1)=c.normal.y; H_D(i , i*3+2)=c.normal.z; u.cross( c.normal, vector3(0,0,1)); u.normalize(); v.cross( c.normal, u); v.normalize(); //VECTOR3_SCALE( u, a , tmp ); //VECTOR3_ADD( c.normal, tmp, tmp1); //VECTOR3_SUB( c.normal, tmp, tmp2); tmp1=c.normal+u*a; tmp2=c.normal-u*a; tmp3=c.normal+v*a; tmp4=c.normal-v*a; tmp1.normalize(); tmp2.normalize(); tmp3.normalize(); tmp4.normalize(); //VECTOR3_SCALE( v, a , tmp ); //VECTOR3_ADD( c.normal, tmp, tmp3); //VECTOR3_SUB( c.normal, tmp, tmp4); H_f(i*3, i*4)=tmp1.x; H_f(i*3, i*4+1)=tmp2.x; H_f(i*3, i*4+2)=tmp3.x; H_f(i*3, i*4+3)=tmp4.x; H_f(i*3+1, i*4)=tmp1.y; H_f(i*3+1, i*4+1)=tmp2.y; H_f(i*3+1,i*4+2)=tmp3.y; H_f(i*3+1, i*4+3)=tmp4.y; H_f(i*3+2, i*4)=tmp1.z; H_f(i*3+2, i*4+1)=tmp2.z; H_f(i*3+2,i*4+2)=tmp3.z; H_f(i*3+2, i*4+3)=tmp4.z; VECTOR3_SCALE( u, b , tmp ); VECTOR3_ADD( c.normal, tmp, tmp1); VECTOR3_SUB( c.normal, tmp, tmp2); VECTOR3_SCALE( v, b , tmp ); VECTOR3_ADD( c.normal, tmp, tmp3); VECTOR3_SUB( c.normal, tmp, tmp4); tmp1.normalize(); tmp2.normalize(); tmp3.normalize(); tmp4.normalize(); H_v(i*3, i*4)=tmp1.x; H_v(i*3, i*4+1)=tmp2.x; H_v(i*3,i*4+2)=tmp3.x; H_v(i*3, i*4+3)=tmp4.x; H_v(i*3+1, i*4)=tmp1.y; H_v(i*3+1, i*4+1)=tmp2.y; H_v(i*3+1,i*4+2)=tmp3.y; H_v(i*3+1, i*4+3)=tmp4.y; H_v(i*3+2, i*4)=tmp1.z; H_v(i*3+2, i*4+1)=tmp2.z; H_v(i*3+2,i*4+2)=tmp3.z; H_v(i*3+2, i*4+3)=tmp4.z; } matrixn subA, invA; subA.setSize(3*m, 3*m); for(int i=0; i<m; i++) for(int j=0; j<m; j++) m::assign( subA.range(i*3, (i+1)*3, j*3, (j+1)*3).lval(), m_A(mContacts_peneltyMethod.m_cti[i].index,mContacts_peneltyMethod.m_cti[j].index)); // m::SVinverse(subA, invA); m_real log_det; m::LUinvert(invA, subA, log_det); invA*=fStep; invA*=-1; gmm::wsmatrixn temp1,temp2, temp3, temp4, H, invH, sinvA; gmm::assign(temp3, invA); temp2.resize(H_D.nrows(),H_v.ncols()); gmm::mult(H_D, H_v , temp2); temp4.resize(H_D.nrows(),H_f.ncols()); gmm::mult(H_D, H_f , temp4); invA*=-1.0; gmm::assign(sinvA,invA); temp1.resize(temp3.nrows(),H_f.ncols()); gmm::mult(temp3, H_f, temp1); matrixn G,CE,CI,E0; vectorn g0,ce0,ci0, _x; bool use_qpOASES=true; g0.setSize(8*m); ce0.setSize(3*m); ci0.setSize(2*m); _x.setSize(8*m); _x.setAllValue(0.0); g0.setAllValue(0.0); ci0.setAllValue(0.0); ce0.setAllValue(0.0); for(int i=0; i<m; i++) { int index=mContacts_peneltyMethod.m_cti[i].index; Physics_Contacts_Penalty::cti& c=mContacts_peneltyMethod.m_cti[i]; m_real b0=(c.normal.x)*(m_Velocities[index].x)+(c.normal.y)*(m_Velocities[index].y)+(c.normal.z)*(m_Velocities[index].z); ci0(i+m)=a0(i)+b0; } G.setSize(8*m,8*m); CE.setSize(3*m,8*m); CI.setSize(2*m,8*m); //min 0.5 * x G x + g0 x //s.t. // CE x + ce0 = 0 // CI x + ci0 >= 0 // G.zero(); /* for(int i=0;i<8*m;i++) for(int j=0;j<8*m;j++) G(i,j)=0; */ G.setAllValue(0.0); CE.setAllValue(0.0); CI.setAllValue(0.0); for(int i=0;i<8*m;i++) G(i,i)=0.02; for(int i=0;i<4*m;i++) { G(i,i+4*m)=1.0; G(i+4*m,i)=1.0; } //temp1= -h*invA*H_f for(int i=0;i<m;i++) { for(int j=0;j<m;j++) { CE(i*3,j*4)=temp1(i*3,j*4); CE(i*3+1,j*4)=temp1(i*3+1,j*4); CE(i*3+2,j*4)=temp1(i*3+2,j*4); CE(i*3,j*4+1)=temp1(i*3,j*4+1); CE(i*3+1,j*4+1)=temp1(i*3+1,j*4+1); CE(i*3+2,j*4+1)=temp1(i*3+2,j*4+1); CE(i*3,j*4+2)=temp1(i*3,j*4+2); CE(i*3+1,j*4+2)=temp1(i*3+1,j*4+2); CE(i*3+2,j*4+2)=temp1(i*3+2,j*4+2); CE(i*3,j*4+3)=temp1(i*3,j*4+3); CE(i*3+1,j*4+3)=temp1(i*3+1,j*4+3); CE(i*3+2,j*4+3)=temp1(i*3+2,j*4+3); CE(i*3,4*m+j*4)=H_v(i*3,j*4); CE(i*3+1,4*m+j*4)=H_v(i*3+1,j*4); CE(i*3+2,4*m+j*4)=H_v(i*3+2,j*4); CE(i*3,4*m+j*4+1)=H_v(i*3,j*4+1); CE(i*3+1,4*m+j*4+1)=H_v(i*3+1,j*4+1); CE(i*3+2,4*m+j*4+1)=H_v(i*3+2,j*4+1); CE(i*3,4*m+j*4+2)=H_v(i*3,j*4+2); CE(i*3+1,4*m+j*4+2)=H_v(i*3+1,j*4+2); CE(i*3+2,4*m+j*4+2)=H_v(i*3+2,j*4+2); CE(i*3,4*m+j*4+3)=H_v(i*3,j*4+3); CE(i*3+1,4*m+j*4+3)=H_v(i*3+1,j*4+3); CE(i*3+2,4*m+j*4+3)=H_v(i*3+2,j*4+3); //temp4=H_D*H_f CI(i, j*4)=temp4(i, j*4); CI(i, j*4+1)=temp4(i, j*4+1); CI(i, j*4+2)=temp4(i, j*4+2); CI(i, j*4+3)=temp4(i, j*4+3); //temp2=H_D*H_v CI(i+m, j*4+4*m)=temp2(i, j*4); CI(i+m, j*4+1+4*m)=temp2(i, j*4+1); CI(i+m, j*4+2+4*m)=temp2(i, j*4+2); CI(i+m, j*4+3+4*m)=temp2(i, j*4+3); } } solve_quadprog(G,g0,CE,ce0,CI,ci0,_x,use_qpOASES); // USE_FORCE // A dv= h F where F is contact forces // dv = h invA F // = h invA H_f lambda gmm::assign(sinvA, invA); std::vector<m_real> dv,Fc, lambda; dv.resize(3*n); Fc.resize(3*n); for(int i=0; i<n; i++) { int index=mContacts_peneltyMethod.m_cti[i].index; Fc[3*i]=H_f(i*3,i*4)*_x(4*i)+H_f(i*3,i*4+1)*_x(4*i+1)+H_f(i*3,i*4+2)*_x(4*i+2)+H_f(i*3,i*4+3)*_x(4*i+3); Fc[3*i+1]=H_f(i*3+1,i*4)*_x(4*i)+H_f(i*3+1,i*4+1)*_x(4*i+1)+H_f(i*3+1,i*4+2)*_x(4*i+2)+H_f(i*3+1,i*4+3)*_x(4*i+3); Fc[3*i+2]=H_f(i*3+2,i*4)*_x(4*i)+H_f(i*3+2,i*4+1)*_x(4*i+1)+H_f(i*3+2,i*4+2)*_x(4*i+2)+H_f(i*3+2,i*4+3)*_x(4*i+3); printf("l1=%f ,l2=%f ,l3=%f ,l4=%f \n",_x[i*4],_x[i*4+1],_x[i*4+2],_x[i*4+3]); } lambda.resize(4*m); for(int i=0; i<lambda.size(); i++) lambda[i]=_x[i]; temp1.resize(sinvA.nrows(), H_f.ncols()); gmm::mult(sinvA, H_f, temp1); gmm::mult(temp1, lambda, dv); printf("fStep: %f\n",fStep); for(int i=0; i<n; i++) { int index=mContacts_peneltyMethod.m_cti[i].index; Physics_Contacts_Penalty::cti& c=mContacts_peneltyMethod.m_cti[i]; m_Velocities[index]+=vector3(dv[i*3], dv[i*3+1], dv[i*3+2]); printf("p1=%f ,p2=%f ,p3=%f ,p4=%f \n",_x[4*m+i*4],_x[4*m+i*4+1],_x[4*m+i*4+2],_x[4*m+i*4+3]); vector3 U=vector3(dv[i*3]*fStep, dv[i*3+1]*fStep, dv[i*3+2]*fStep); m_y[index]=U; } printf("Use_Force & frictionless\n"); mContacts_peneltyMethod.m_cti.clear(); } else if(m_cfg.contactMethod==Config::LCP_METHOD &&mContacts_peneltyMethod.m_cti.size()) { // n: number of contact points int n=mContacts_peneltyMethod.m_cti.size(); // m: the number of particles involved in contact. at the moment, // m==n because we only consider FV collisions ignoring VF and EE // collisions. int m=n; // int k=m_iParticles-n; printf("k=%d,m_iParticles=%d \n ",k,m_iParticles); printf("m_ParticleMass=%f",m_ParticleMass); // following matrix naming conventions follow [DAK04] and [DDKA06]. // [DAK04] C.Duriez, C. Andriot, and A.Kheddar, A multi-threaded // approach for deformable/rigid contacts with haptic feedback, // IEEE haptic symposium, 2004. // [DDKA06] Realistic Haptic Rendering of Interacting Deformable // Objects in Virtual Environments #ifdef DEBUG_DRAW int l=0; // l is a count number of frictionless point #endif intvectorn basesStartIndex(n+1); std::vector<vector3N> bases; bases.resize(n); { int Start=0; for(int i=0; i<n; i++) { int index=mContacts_peneltyMethod.m_cti[i].index; m_real coeff=m_cfg.m_dynamicFrictionCoef[index]; Physics_Contacts_Penalty::cti& c=mContacts_peneltyMethod.m_cti[i]; basesStartIndex[i]=Start; if(coeff==0) { Start++; bases[i].resize(1); bases[i][0]=c.normal; #ifdef DEBUG_DRAW l++; #endif } else { // ๊ณ„์‚ฐ์€ ์—ฌ๊ธฐ์„œ ํ•œ๋ฒˆ์— ํ•˜๊ณ , ์•„๋ž˜์„œ๋Š” ์ด๊ฑธ ๊ฐ–๋‹ค ์“ฐ๋ฉด, ์ฝ”๋“œ ๊ธธ์ด1/4 ์ˆ˜์ค€์œผ๋กœ ์ค„์ผ ์ˆ˜ ์žˆ์Œ. vector3 u, v , tmp; u.cross( c.normal, vector3(0,0,1)); u.normalize(); v.cross( c.normal, u); v.normalize(); Start+=4; bases[i].resize(4); bases[i][0]=c.normal+u*1.0/coeff; bases[i][1]=c.normal-u*1.0/coeff; bases[i][2]=c.normal+v*1.0/coeff; bases[i][3]=c.normal-v*1.0/coeff; bases[i][0].normalize(); bases[i][1].normalize(); bases[i][2].normalize(); bases[i][3].normalize(); } } basesStartIndex[n]=Start; } // 2014.04.01 question: gmm::wsmatrixn -> matrixn ํƒ€์ž…์œผ๋กœ ๋ณ€ํ™˜ matrixn H_f, C_N; int numBases=basesStartIndex[m]; int numDims=3*m; #ifdef DEBUG_DRAW int friPoint=n-l; printf("4m-3l=%d, numbases=%d\n",4*m-3*l,numBases); #endif H_f.setSize(numDims,numBases); C_N.setSize(2*numBases, numBases+numDims); H_f.setAllValue(0.0); C_N.setAllValue(0.0); vector3 u, v , tmp; vector3 tmp1, tmp2, tmp3, tmp4; // friction cone's coefficient & velocity cone's coefficient // a=tan(angle), b=tan(pi-angle)=cot(angle)=1/tan(angle)=1/a /* m_real a,b; a=(m_real) 1.0; b=(m_real)1.732; */ vectorn a0, b0; a0.setSize(m); // -c.penetratingDepth/fStep; b0.setSize(numBases);// vfree*bases for(int i=0; i<n; i++) { Physics_Contacts_Penalty::cti& c=mContacts_peneltyMethod.m_cti[i]; int index=mContacts_peneltyMethod.m_cti[i].index; //a0(i)=(m_real)c.penetratingDepth/fStep; a0(i)=0; // this works better for now. //printf("bases[%d].size()=%d\n",i,bases[i].size()); for(int j=0; j<bases[i].size(); j++) { b0(basesStartIndex[i]+j)=VECTOR3_DP(bases[i][j], m_Velocities[index]); if(bases[i].size()==1) b0(basesStartIndex[i]+j)+=a0(i); H_f(i*3, basesStartIndex[i]+j)=bases[i][j].x; H_f(i*3+1, basesStartIndex[i]+j)=bases[i][j].y; H_f(i*3+2, basesStartIndex[i]+j)=bases[i][j].z; C_N(basesStartIndex[i]+numBases+j,i*3+numBases)=bases[i][j].x; C_N(basesStartIndex[i]+numBases+j,i*3+1+numBases)=bases[i][j].y; C_N(basesStartIndex[i]+numBases+j,i*3+2+numBases)=bases[i][j].z; for(int k=0; k<bases[i].size(); k++) C_N(basesStartIndex[i]+j,basesStartIndex[i]+k)=VECTOR3_DP(bases[i][j],bases[i][k]); } } matrixn subA, hH_f; subA.setSize(numDims, numDims); hH_f.setSize(numDims, numBases); for(int i=0; i<m; i++) for(int j=0; j<m; j++) m::assign( subA.range(i*3, (i+1)*3, j*3, (j+1)*3).lval(), m_A(mContacts_peneltyMethod.m_cti[i].index,mContacts_peneltyMethod.m_cti[j].index)); hH_f=H_f*fStep; subA*=-1; matrixn G,CE,CI,E0; vectorn g0,ce0,ci0, _x; bool use_qpOASES=true; g0.setSize(numBases+numDims); ce0.setSize(numDims); ci0.setSize(2*numBases); _x.setSize(numBases+numDims); _x.setAllValue(0.0); g0.setAllValue(0.0); ci0.setAllValue(0.0); ce0.setAllValue(0.0); for(int i=0; i<numBases; i++) ci0(i+numBases)=b0(i); // x: [lambda dv]' // CE: [ hH_f subA ]=0 CE.setSize(numDims, numBases+numDims); CI.setSize(2*numBases, numBases+numDims); //min 0.5 * x G x + g0 x //s.t. // CE x + ce0 = 0 // CI x + ci0 >= 0 // G.zero(); G.identity(numBases+numDims); CE.setAllValue(0.0); CE.range(0,CE.rows(), 0,hH_f.cols()).assign(hH_f); CE.range(0,CE.rows(), hH_f.cols(),CE.cols()).assign(subA); CI=C_N; solve_quadprog(G,g0,CE,ce0,CI,ci0,_x,use_qpOASES); // USE_FORCE // A dv= h F where F is contact forces // dv = h invA F // = h invA H_f lambda vectorn Fc, lambda; std::vector<vector3N> dv; Fc.setSize(numDims); lambda.setSize(numBases); dv.resize(n); for(int i=0;i<numBases; i++) { lambda(i)=_x[i]; printf("lambda[%d]=%f\n",i,_x[i]); } for(int i=0; i<n; i++) { dv[i].resize(1); dv[i][0]=vector3(_x[i*3+numBases],_x[i*3+1+numBases],_x[i*3+2+numBases]); printf("dv[%d].x=%f , dv[%d].y=%f , dv[%d].z=%f \n",i,dv[i][0].x,i,dv[i][0].y,i,dv[i][0].z); } Fc.column().mult(H_f,lambda.column()); #ifdef DEBUG_DRAW lines_fvelocity.resize(2*friPoint,3); lines_fforce.resize(2*friPoint,3); lines_flvelocity.resize(2*l,3); lines_flforce.resize(2*l,3); lines_normal.resize(2*n,3); int count1=0; int count2=0; #endif for(int i=0; i<n; i++) { int index=mContacts_peneltyMethod.m_cti[i].index; m_real coeff=m_cfg.m_dynamicFrictionCoef[index]; vector3 dpf=vector3(Fc[3*i],Fc[3*i+1],Fc[3*i+2]); VECTOR3_SCALE( dpf, 0.01 , dpf ); VECTOR3_ADD(dpf, m_Positions[index], dpf); #ifdef DEBUG_DRAW if(coeff==0) { lines_flforce.row(count1*2).setVec3(0, m_Positions[index]); lines_flforce.row(count1*2+1).setVec3(0, dpf); count1++; } else { lines_fforce.row(count2*2).setVec3(0, m_Positions[index]); lines_fforce.row(count2*2+1).setVec3(0, dpf); count2++; } printf("Fc[%d].x=%f , Fc[%d].y=%f , Fc[%d].z=%f \n",i,Fc[i*3],i,Fc[i*3+1],i,Fc[i*3+2]); #endif } #ifdef DEBUG_DRAW count1=0; count2=0; #endif for(int i=0; i<n; i++) { int index=mContacts_peneltyMethod.m_cti[i].index; m_real coeff=m_cfg.m_dynamicFrictionCoef[index]; Physics_Contacts_Penalty::cti& c=mContacts_peneltyMethod.m_cti[i]; m_Velocities[index]+=dv[i][0]; vector3 dpdv=m_Velocities[index]; vector3 dpn=c.normal; VECTOR3_SCALE( dpdv, 1 , dpdv ); VECTOR3_ADD(dpdv, m_Positions[index], dpdv); VECTOR3_SCALE( dpn, 20 , dpn ); VECTOR3_ADD(dpn, m_Positions[index], dpn); #ifdef DEBUG_DRAW if(coeff==0) { lines_flvelocity.row(count1*2).setVec3(0, m_Positions[index]); lines_flvelocity.row(count1*2+1).setVec3(0, dpdv); count1++; } else { lines_fvelocity.row(count2*2).setVec3(0, m_Positions[index]); lines_fvelocity.row(count2*2+1).setVec3(0, dpdv); count2++; } lines_normal.row(i*2).setVec3(0, m_Positions[index]); lines_normal.row(i*2+1).setVec3(0, dpn); #endif vector3 U; VECTOR3_SCALE( dv[i][0] , fStep , U ); m_y[index]=U; } #ifdef DEBUG_DRAW g_debugObject->registerObject("friction_contactForces", "LineList", "solidred", lines_fforce); g_debugObject->registerObject("friction_deltaVelocities", "LineList", "solidblue", lines_fvelocity); g_debugObject->registerObject("frictionless_contactForces", "LineList", "solidwhite", lines_flforce); g_debugObject->registerObject("frictionless_deltaVelocities", "LineList", "solidblack", lines_flvelocity); g_debugObject->registerObject("normalForces", "LineList", "solidgreen", lines_normal); printf("Use_Force & friction\n"); #endif mContacts_peneltyMethod.m_cti.clear(); } // // Compute b = h * ( f(0) + h * df/dx * v(0) + df/dx * y ) // m_Velocities.Scale( fStep, m_vTemp2 ); m_vTemp2.Add( m_y, m_vTemp2 ); m_TotalForces_dp.PostMultiply( m_vTemp2, m_vTemp1 ); // m_vTemp1.Scale( fStep, m_vTemp2 ); m_TotalForces_int.Add( m_vTemp1, m_vTemp1 ); m_vTemp1.Scale( fStep, m_b ); const bool useModifiedConjugateGradient_BW98=true; if(useModifiedConjugateGradient_BW98) { // // Setup the inverse of preconditioner -- We use a vector for memory efficiency. // Technically it's the diagonal of a matrix // for( i=0; i<m_iParticles; i++ ) { const matrix3& mm=m_A(i,i); m_PInv[i].x = (m_real)mm._11; m_PInv[i].y = (m_real)mm._22; m_PInv[i].z = (m_real)mm._33; } m_PInv.Invert( m_P ); // // Modified Preconditioned Conjugate Gradient method // m_dv = m_z; // delta_0 = DotProduct( filter( b ), P * filter( b ) ); m_b.ElementMultiply( m_S, m_vTemp1 ); m_P.ElementMultiply( m_vTemp1, m_vTemp2 ); Delta_0 = m_vTemp2.DotProduct( m_vTemp1 ); if( Delta_0 < 0 ) { m_b.Dump( "b:\r\n" ); m_P.Dump( "P:\r\n" ); Msg::print("%s\n", "Negative Delta_0 most likely caused by a non-Positive Definite matrix\r\n" ); } // r = filter( b - A * dv ) m_A.PostMultiply( m_dv, m_vTemp1 ); m_b.Subtract( m_vTemp1, m_vTemp2 ); m_vTemp2.ElementMultiply( m_S, m_r ); // c = filter( Pinv * r ) m_PInv.ElementMultiply( m_r, m_vTemp1 ); m_vTemp1.ElementMultiply( m_S, m_c ); Delta_new = m_r.DotProduct( m_c ); if( Delta_new < Eps_Sq * Delta_0 ) { m_b.Dump( "b: \r\n" ); m_P.Dump( "P: \r\n" ); Msg::print("%s\n", "This isn't good! Probably a non-Positive Definite matrix\r\n" ); } while( (Delta_new > Eps_Sq * Delta_0) && (iIterations < iMaxIterations) ) { m_A.PostMultiply( m_c, m_vTemp1 ); m_vTemp1.ElementMultiply( m_S, m_q ); alpha = Delta_new / (m_c.DotProduct( m_q ) ); m_c.Scale( alpha, m_vTemp1 ); m_dv.Add( m_vTemp1, m_dv ); m_q.Scale( alpha, m_vTemp1 ); m_r.Subtract( m_vTemp1, m_r ); m_PInv.ElementMultiply( m_r, m_s ); Delta_old = Delta_new; Delta_new = m_r.DotProduct( m_s ); m_c.Scale( Delta_new / Delta_old, m_vTemp1 ); m_s.Add( m_vTemp1, m_vTemp2 ); m_vTemp2.ElementMultiply( m_S, m_c ); iIterations++; } } else { #ifndef USE_GMM ASSERT(0); #else static gmm::wsmatrixn A; static vectorn b, x; gmm::resize(A, m_A.rows()*3, m_A.cols()*3); for(int i=0; i<m_A.rows(); i++) { gmm::linalg_traits<Physics_SparseSymmetricMatrix::svector_mat3>::const_iterator it = gmm::vect_const_begin(m_A.m_data[i]); gmm::linalg_traits<Physics_SparseSymmetricMatrix::svector_mat3>::const_iterator ite = gmm::vect_const_end(m_A.m_data[i]); for(;it!=ite; ++it) { int j=it.index(); matrix3 const& m=*it; A[i*3+0][j*3+0]=m._11; A[i*3+0][j*3+1]=m._12; A[i*3+0][j*3+2]=m._13; A[i*3+1][j*3+0]=m._21; A[i*3+1][j*3+1]=m._22; A[i*3+1][j*3+2]=m._23; A[i*3+2][j*3+0]=m._31; A[i*3+2][j*3+1]=m._32; A[i*3+2][j*3+2]=m._33; } } b.setSize(m_b.size()*3); for(int i=0; i<m_b.size(); i++) { b[i*3+0]=m_b[i].x; b[i*3+1]=m_b[i].y; b[i*3+2]=m_b[i].z; } sm::UMFsolve(A,b,x); ASSERT(x.size()==m_b.size()*3); for(int i=0; i<m_b.size(); i++) { m_dv[i].x=x[i*3]; m_dv[i].y=x[i*3+1]; m_dv[i].z=x[i*3+2]; } #endif } m_Velocities.Add( m_dv, m_Velocities ); m_Velocities.Scale( fStep, m_vTemp1 ); m_Positions.Add( m_vTemp1, m_Positions ); m_Positions.Add( m_y, m_Positions ); fTotal += (m_real)fabs( fStep ); } } void Physics_ParticleSystem::Update_SemiImplicit( float fTime ) { m_real fTotal = 0.0f, fStep = (m_real)fTime; vector3 vCOG, dTorque, tmp, tmp2; int i; while( fTotal < fTime ) { // // Calculate the center of gravity // vCOG.x = vCOG.y = vCOG.z = 0; for( i=0; i<m_iParticles; i++ ) VECTOR3_ADD( vCOG, m_Positions[i], vCOG ); vCOG.x /= m_iParticles; vCOG.y /= m_iParticles; vCOG.z /= m_iParticles; dTorque.x = dTorque.y = dTorque.z = 0.0f; // // Update the W matrix if necessary // if( fStep != m_LastStep ) { m_W.identity(); m_H.Scale( fStep * fStep / m_LastStep / m_LastStep, m_H ); m_W.Subtract( m_H, m_W ); m_W.Invert(); m_LastStep = fStep; } // // Zero out everything // m_TotalForces_int.zero(); m_TotalForces_ext.zero(); // // Apply the forces // for(int i=0, ni=m_Forces.size(); i<ni; i++) { m_Forces[i]->Apply(fStep, m_Masses, false, m_Positions, m_Velocities, m_TotalForces_int, m_TotalForces_ext, m_TotalForces_dp, m_TotalForces_dv ); } // // Filter the internal forces // m_W.PreMultiply( m_TotalForces_int, m_vTemp1 ); // // Update the torque // for( i=0; i<m_iParticles; i++ ) { tmp .cross( m_vTemp1[i], m_Positions[i] ); VECTOR3_ADD( dTorque, tmp, dTorque ); } // // Compute the new velocities and positions // m_vTemp1.Add( m_TotalForces_ext, m_dv ); m_dv.Scale( fStep, m_dv ); m_dv.ElementMultiply( m_MassInv, m_dv ); m_Velocities.Add( m_dv, m_Velocities ); m_Velocities.Scale( fStep, m_vTemp1 ); m_Positions.Add( m_vTemp1, m_PosTemp ); /*// // Keep us above the floor -- cheesey collision detection // for( i=0; i<m_iParticles; i++ ) if( m_PosTemp[i].y < FLOOR_Y ) { m_PosTemp[i].y = FLOOR_Y; m_Velocities[i].y = 0; } */ // // Post correct for angular momentum // for( i=0; i<m_iParticles; i++ ) { if( m_Masses[i].x ) { tmp2 .sub( vCOG, m_Positions[i] ); tmp.cross( tmp2, dTorque); VECTOR3_SCALE( tmp, fStep * fStep * fStep * m_MassInv[i].x, tmp ); VECTOR3_ADD( m_PosTemp[i], tmp, m_PosTemp[i] ); /* if( m_PosTemp[i].y < FLOOR_Y ) { m_PosTemp[i].y = FLOOR_Y; m_Velocities[i].y = 0; }*/ } } // // Apply inverse dynamics to prevent excessive stretch // We need 10 or so iterations to be stable -- with more particles in the // mesh, we need more iterations. // for( i=0; i<m_iInverseIterations; i++ ) { for(int i=0, ni=m_Forces.size(); i<ni; i++) { m_Forces[i]->Fixup( m_Masses, m_PosTemp ); } } // // Update velocityp and position // /* for( i=0; i<m_iParticles; i++ ) if( m_PosTemp[i].y < FLOOR_Y ) { m_PosTemp[i].y = FLOOR_Y; m_Velocities[i].y = 0; }*/ m_PosTemp.Subtract( m_Positions, m_vTemp1 ); m_vTemp1.Scale( (m_real)1.0 / fStep, m_Velocities ); m_Positions = m_PosTemp; fTotal += (m_real)fabs( fStep ); } } void Physics_ParticleSystem::AddConstraint( Physics_Constraint &Constraint ) { m_Constraints.push_back( &Constraint ); // // Apply the constraints // for( int i=0; i<m_iParticles; i++ ) { m_S[i].identity(); } m_z.zero(); std::list<Physics_Constraint*>::iterator i; for( i=m_Constraints.begin(); i!=m_Constraints.end(); ++i) { (*i)->Apply(m_S, m_z); } } bool Physics_ParticleSystem::DeleteConstraint( Physics_Constraint &Constraint ) { m_Constraints.remove(&Constraint ); { // // Apply the constraints // for( int i=0; i<m_iParticles; i++ ) { m_S[i].identity(); } m_z.zero(); std::list<Physics_Constraint*>::iterator i; for( i=m_Constraints.begin(); i!=m_Constraints.end(); ++i) { (*i)->Apply(m_S, m_z); } } return true; } void Physics_ParticleSystem::Reset() { // // Update the constraints for the Implicit integration scheme // if( m_iIntegrationMethod == INTEGRATE_IMPLICIT ) { for( int i=0; i<m_iParticles; i++ ) { m_S[i].identity(); } m_z.zero(); m_y.zero(); std::list<Physics_Constraint*>::iterator i; for( i=m_Constraints.begin(); i!=m_Constraints.end(); ++i) { (*i)->Apply(m_S, m_z); } } }
25.287928
129
0.61036
[ "mesh", "vector" ]
b162bf3f91afcce19a8be0d25778613ba9eb88ad
804
hh
C++
src/ast/symbols-type.hh
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
16
2016-05-10T05:50:58.000Z
2021-10-05T22:16:13.000Z
src/ast/symbols-type.hh
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
7
2016-09-05T10:08:33.000Z
2019-02-13T10:51:07.000Z
src/ast/symbols-type.hh
jcbaillie/urbi
fb17359b2838cdf8d3c0858abb141e167a9d4bdb
[ "BSD-3-Clause" ]
15
2015-01-28T20:27:02.000Z
2021-09-28T19:26:08.000Z
/* * Copyright (C) 2008-2010, 2012, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ #ifndef AST_SYMBOLS_TYPE_HH # define AST_SYMBOLS_TYPE_HH # include <iosfwd> # include <vector> # include <libport/fwd.hh> namespace ast { /// Function formal arguments. typedef std::vector<libport::Symbol> symbols_type; } // We need argument dependent name lookup for symbols_type, // which is actually a class of std: it is std::vector<...>. namespace std { /// Separated by commas. std::ostream& operator<<(std::ostream& o, const ast::symbols_type& ss); } #endif // ! AST_SYMBOLS_TYPE_HH
22.971429
66
0.716418
[ "vector" ]
b166d0c49b711debeafb176002f87d77572812e5
294
cpp
C++
RAPter/src/optimization/visualizer.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
27
2017-09-21T19:52:28.000Z
2022-03-09T13:47:02.000Z
RAPter/src/optimization/visualizer.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
12
2017-07-26T15:00:32.000Z
2021-12-03T03:08:15.000Z
RAPter/src/optimization/visualizer.cpp
frozar/RAPter
8f1f9a37e4ac12fa08a26d18f58d3b335f797200
[ "Apache-2.0" ]
11
2017-03-24T16:56:08.000Z
2020-11-21T13:18:33.000Z
#include "globfit2/visualization/visualizer.h" #include "globfit2/primitives/linePrimitive2.h" #include "globfit2/primitives/pointPrimitive.h" // Cache template compilation. //GF2::Visualizer<std::vector<std::vector<GF2::LinePrimitive2> >, std::vector<GF2::PointPrimitive> > dummyVisualizer;
36.75
117
0.789116
[ "vector" ]
b16e6910d01c34271765ef117fdc71f8c7d6709c
3,461
hpp
C++
Source/AllProjects/OrbUtils/CIDOrb/CIDOrb_.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
1
2019-05-28T06:33:01.000Z
2019-05-28T06:33:01.000Z
Source/AllProjects/OrbUtils/CIDOrb/CIDOrb_.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
Source/AllProjects/OrbUtils/CIDOrb/CIDOrb_.hpp
eudora-jia/CIDLib
02795d283d95f8a5a4fafa401b6189851901b81b
[ "MIT" ]
null
null
null
// // FILE NAME: CIDOrb_.hpp // // AUTHOR: Dean Roddey // // CREATED: 07/03/2000 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2019 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This is the main internal header for the facility. It provides any // internal non-class types, constants, enums, etc... // // CAVEATS/GOTCHAS: // // LOG: // // $_CIDLib_Log_$ // #pragma once // --------------------------------------------------------------------------- // Include our own public header and any of our internal headers that need to // be seen by the name spaces below. // --------------------------------------------------------------------------- #include "CIDOrb.hpp" #include "CIDOrb_WorkQItem_.hpp" // --------------------------------------------------------------------------- // Internal constants namespace // --------------------------------------------------------------------------- namespace kCIDOrb_ { // ----------------------------------------------------------------------- // Magic values used in the packet header as brackets around the other // fields, as a sanity check. // ----------------------------------------------------------------------- const tCIDLib::TCard4 c4MagicVal = 0xDEADBEEF; const tCIDLib::TCard4 c4MagicVal2 = 0xEADABEBA; // ----------------------------------------------------------------------- // The modulus for hashing the packet data // ----------------------------------------------------------------------- const tCIDLib::TCard4 c4PacketHashMod = 109; // ----------------------------------------------------------------------- // The size of the I/O buffer used in some cases for reading in and // formatting out data, mostly on the server side. If it's bigger than // this a temp buffer is allocated. // ----------------------------------------------------------------------- const tCIDLib::TCard4 c4SmallIOBufSz = 1024 * 32; }; // --------------------------------------------------------------------------- // Internal types namespace // --------------------------------------------------------------------------- namespace tCIDOrb_ { // ----------------------------------------------------------------------- // We need a queue of work items. One of these is used by each connection // object (for replies) and by the connection manager for the connections // to queue up incoming work to be processed. // // It holds instances of our work item pointer, which is a counted pointer // that will release the item back to the facility class' pool when the last // use of it is done. // ----------------------------------------------------------------------- using TWorkQ = TQueue<TWorkQItemPtr>; } // --------------------------------------------------------------------------- // Include some of the headers // --------------------------------------------------------------------------- #include "CIDOrb_ClientConn_.hpp" // --------------------------------------------------------------------------- // And more headers that need to see the second namespace above // --------------------------------------------------------------------------- #include "CIDOrb_ClientConnMgr_.hpp"
36.052083
81
0.406241
[ "object" ]
b16f39eddda3456cc603884fc66c9b22275ff0b0
10,944
cpp
C++
common/amathutils_lib/src/amathutils_lib_ros2/butterworth_filter.cpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
common/amathutils_lib/src/amathutils_lib_ros2/butterworth_filter.cpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
common/amathutils_lib/src/amathutils_lib_ros2/butterworth_filter.cpp
VT-ASIM-LAB/autoware.ai
211dff3bee2d2782cb10444272c5d98d1f30d33a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018-2019 Autoware Foundation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Aauthor Ali Boyali, Simon Thompson */ #include <algorithm> #include <cmath> #include <complex> #include <cstdio> #include <iostream> #include <string> #include <vector> #include "amathutils_lib_ros2/butterworth_filter.hpp" void ButterworthFilter::Buttord(double Wp, double Ws, double Ap, double As) { /* * Inputs are double Wp, Ws, Ap, As; * Wp; passband frequency [rad/sc], * Ws: stopband frequeny [rad/sc], * Ap. {As}: pass {stop} band ripple [dB] * * */ double alpha, beta; alpha = Ws / Wp; beta = sqrt((pow(10, As / 10.0) - 1.0) / (pow(10, Ap / 10.0) - 1.0)); int order = std::ceil(log(beta) / log(alpha)); setOrder(order); // right limit, left limit /* * The left and right limits of the magnitutes satisfy the specs at the * frequencies Ws and Wp Scipy.buttord gives left limit as the cut-off * frequency whereas Matlab gives right limit * * */ double right_lim = Ws * (pow((pow(10.0, As / 10.0) - 1.0), -1.0 / (2 * mOrder))); // double left_lim = Wp * (pow((pow(10.0, Ap / 10.0) - 1.0), -1.0 / (2 * // mOrder))); // mCutoff_Frequency = left_lim; setCuttoffFrequency(right_lim); } void ButterworthFilter::initializeForFiltering() { // record history of filtered and unfiltered signal for applying filter u_unfiltered.resize(mOrder + 1, 0.0); u_filtered.resize(mOrder + 1, 0.0); } void ButterworthFilter::setOrder(int N) { mOrder = N; initializeForFiltering(); } void ButterworthFilter::setCuttoffFrequency(double Wc) { mCutoff_Frequency = Wc; } void ButterworthFilter::setCuttoffFrequency(double fc, double fs) { /* * fc is the cut-off frequency in [Hz] * fs is the sampling frequency in [Hz] * */ if (fc >= fs / 2) { std::cout << "\n ERROR: Cut-off frequency fc must be less than fs/2 \n"; _Exit(0); } mCutoff_Frequency = fc * 2.0 * M_PI; mSampling_Frequency = fs; } std::vector<std::complex<double>> ButterworthFilter::polynomialFromRoots(std::vector<std::complex<double>> &rts) { std::vector<std::complex<double>> roots = rts; std::vector<std::complex<double>> coefficients(roots.size() + 1, {0, 0}); // NOLINT int n = roots.size(); coefficients[0] = {1.0, 0.0}; // Use Vieta's Formulas to calculate polynomial coefficients // relates sum and products of roots to coefficients for (int i = 0; i < n; i++) { for (int j = i; j != -1; j--) { coefficients[j + 1] = coefficients[j + 1] - (roots[i] * coefficients[j]); } } return coefficients; } void ButterworthFilter::computePhaseAngles() { mPhaseAngles.resize(mOrder); int i = 1; for (auto &&x : mPhaseAngles) { x = M_PI_2 + (M_PI * (2.0 * i - 1.0) / (2.0 * mOrder)); i++; } } void ButterworthFilter::computeContinuousTimeRoots(bool use_sampling_freqency) { // First compute the phase angles of the roots computePhaseAngles(); mContinuousTimeRoots.resize(mOrder, {0.0, 0.0}); // NOLINT int i = 0; if (use_sampling_freqency) { double Fc = (mSampling_Frequency / M_PI) * tan(mCutoff_Frequency / (mSampling_Frequency * 2.0)); for (auto &&x : mContinuousTimeRoots) { x = {cos(mPhaseAngles[i]) * Fc * 2.0 * M_PI, // NOLINT sin(mPhaseAngles[i]) * Fc * 2.0 * M_PI}; // NOLINT i++; } } else { for (auto &&x : mContinuousTimeRoots) { x = {mCutoff_Frequency * cos(mPhaseAngles[i]), // NOLINT mCutoff_Frequency * sin(mPhaseAngles[i])}; // NOLINT i++; } } } void ButterworthFilter::computeContinuousTimeTF(bool use_sampling_freqency) { computeContinuousTimeRoots(use_sampling_freqency); mContinuousTimeDenominator.resize(mOrder + 1, {0.0, 0.0}); // NOLINT mContinuousTimeDenominator = polynomialFromRoots(mContinuousTimeRoots); mContinuousTimeNumerator = pow(mCutoff_Frequency, mOrder); } void ButterworthFilter::computeDiscreteTimeTF(bool use_sampling_freqency) { /* @brief * This method assumes the continous time transfer function of filter has * already been computed and stored in the * object. * * */ // Resizes the roots and zeros to the new order of discrete time then fills // the values by Bilinear Transformation mDiscreteTimeZeros.resize( mOrder, {-1.0, 0.0}); // Butter puts zeros at -1.0 for causality // NOLINT mDiscreteTimeRoots.resize(mOrder, {0.0, 0.0}); // NOLINT mAn.resize(mOrder + 1, 0.0); mBn.resize(mOrder + 1, 0.0); mDiscreteTimeGain = {mContinuousTimeNumerator, 0.0}; // Bi-linear Transformation of the Roots int i = 0; if (use_sampling_freqency) { for (auto &&dr : mDiscreteTimeRoots) { dr = (1.0 + mContinuousTimeRoots[i] / (mSampling_Frequency * 2.0)) / (1.0 - mContinuousTimeRoots[i] / (mSampling_Frequency * 2.0)); i++; } mDiscreteTimeDenominator = polynomialFromRoots(mDiscreteTimeRoots); // Obtain the coefficients of numerator and denominator i = 0; mDiscreteTimeNumerator = polynomialFromRoots(mDiscreteTimeZeros); // Compute Discrete Time Gain std::complex<double> sum_num{0.0, 0.0}; std::complex<double> sum_den{0.0, 0.0}; for (auto &n : mDiscreteTimeNumerator) { sum_num += n; } for (auto &n : mDiscreteTimeDenominator) { sum_den += n; } mDiscreteTimeGain = (sum_den / sum_num); for (auto &&dn : mDiscreteTimeNumerator) { dn = dn * mDiscreteTimeGain; mBn[i] = dn.real(); i++; } i = 0; for (auto &&dd : mDiscreteTimeDenominator) { mAn[i] = dd.real(); i++; } } else { for (auto &&dr : mDiscreteTimeRoots) { dr = (1.0 + 2.0 * mContinuousTimeRoots[i] / 2.0) / (1.0 - Td * mContinuousTimeRoots[i] / 2.0); mDiscreteTimeGain = mDiscreteTimeGain / (1.0 - mContinuousTimeRoots[i]); i++; } mDiscreteTimeDenominator = polynomialFromRoots(mDiscreteTimeRoots); // Obtain the coefficients of numerator and denominator i = 0; mDiscreteTimeNumerator = polynomialFromRoots(mDiscreteTimeZeros); for (auto &&dn : mDiscreteTimeNumerator) { dn = dn * mDiscreteTimeGain; mBn[i] = dn.real(); i++; } i = 0; for (auto &&dd : mDiscreteTimeDenominator) { mAn[i] = dd.real(); i++; } } } Order_Cutoff ButterworthFilter::getOrderCutOff() { Order_Cutoff NWc{mOrder, mCutoff_Frequency}; return NWc; } DifferenceAnBn ButterworthFilter::getAnBn() { // DifferenceAnBn AnBn; // AnBn.An.resize(mAn.size(), 0.0); // AnBn.Bn.resize(mBn.size(), 0.0); // // AnBn.An = mAn; // AnBn.Bn = mBn; DifferenceAnBn AnBn{mAn, mBn}; return AnBn; } std::vector<double> ButterworthFilter::getAn() { return mAn; } std::vector<double> ButterworthFilter::getBn() { return mBn; } void ButterworthFilter::PrintFilter_Specs() { /* * Prints the order and cut-off angular frequency (rad/sec) of the filter * * */ std::cout << "\nThe order of the filter : " << this->mOrder << std::endl; std::cout << "Cut-off Frequency : " << this->mCutoff_Frequency << " rad/sec\n" << std::endl; } void ButterworthFilter::PrintFilter_ContinuousTimeRoots() { /* * Prints the order and cut-off angular frequency (rad/sec) of the filter * */ std::cout << "\n Roots of Continous Time Filter Transfer Function " "Denominator are : " << std::endl; for (auto &&x : mContinuousTimeRoots) { std::cout << std::real(x) << " + j " << std::imag(x) << std::endl; } std::cout << std::endl; } void ButterworthFilter::PrintContinuousTimeTF() { int n = mOrder; std::cout << "\nThe Continuous Time Transfer Function of the Filter is ;\n" << std::endl; std::cout << " " << mContinuousTimeNumerator << std::endl; for (int i = 0; i <= n; i++) { std::cout << "--------"; } std::cout << "--------\n"; for (int i = n; i > 0; i--) { std::cout << mContinuousTimeDenominator[n - i].real() << " * "; std::cout << "z[-" << i << "] + "; } std::cout << mContinuousTimeDenominator[n].real() << std::endl; } void ButterworthFilter::PrintDiscreteTimeTF() { int n = mOrder; std::cout << "\nThe Discrete Time Transfer Function of the Filter is ;\n" << std::endl; for (int i = n; i > 0; i--) { std::cout << mDiscreteTimeNumerator[n - i].real() << " * "; std::cout << "z[-" << i << "] + "; } std::cout << mDiscreteTimeNumerator[n].real() << std::endl; for (int i = 0; i <= n; i++) { std::cout << "--------"; } std::cout << "--------\n"; for (int i = n; i > 0; i--) { std::cout << mDiscreteTimeDenominator[n - i].real() << " * "; std::cout << "z[-" << i << "] + "; } std::cout << mDiscreteTimeDenominator[n].real() << std::endl; std::cout << std::endl; } double ButterworthFilter::filter(const double &u) { double u_f = 0.0; for (int i = 0; i < mOrder + 1; i++) { if (i == 0) { u_f += mBn[0] * u; } else { u_f += mBn[i] * u_unfiltered[i]; u_f -= mAn[i] * u_filtered[i]; } } for (int i = mOrder; i >= 2; i--) { u_unfiltered[i] = u_unfiltered[i - 1]; u_filtered[i] = u_filtered[i - 1]; } u_unfiltered[1] = u; u_filtered[1] = u_f; return u_f; } void ButterworthFilter::filtVector(const std::vector<double> &t, std::vector<double> &u, bool init_first_value) { // initialise trace values to 1st value if (init_first_value) { for (int i = 0; i < mOrder + 1; i++) { u_unfiltered[i] = t[0]; u_filtered[i] = t[0]; } } for (unsigned int i = 0; i < t.size(); ++i) u[i] = this->filter(t[i]); } void ButterworthFilter::filtFiltVector(const std::vector<double> &t, std::vector<double> &u, bool init_first_value) { std::vector<double> u_rev(u); // forward filtering filtVector(t, u, init_first_value); // backward filtering std::reverse(u_rev.begin(), u_rev.end()); filtVector(t, u_rev, init_first_value); std::reverse(u_rev.begin(), u_rev.end()); // merge for (unsigned int i = 0; i < u.size(); ++i) { u[i] = (u[i] + u_rev[i]) * 0.5; } }
24.266075
86
0.604441
[ "object", "vector" ]
b171e3e7e00afd48531ef55ea1402606b8d4e931
1,278
cpp
C++
codeforces/501_3/d.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
2
2018-06-26T09:52:14.000Z
2018-07-12T15:02:01.000Z
codeforces/501_3/d.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
null
null
null
codeforces/501_3/d.cpp
sidgairo18/Programming-Practice
348ad38452fa9fa7b7302161455d3b3f697734da
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main(){ long long int n,k,s; scanf("%lld%lld%lld", &n, &k, &s); long long int check = (n-1)*k; if( check < s || k > s) { printf("NO\n"); return 0; } vector<long long int> ans; ans.push_back(1); while(k>0){ int sz = ans.size(); if(s-(n-1) >= (k-1)){ s -= (n-1); k--; ans.push_back(ans[sz-1] == 1? n:1); } else if(k>=2){ s--; k--; if(ans[sz-1] == n) ans.push_back(n-1); else if(ans[sz-1] == (n-1)) ans.push_back(n); else if(ans[sz-1] == 1) ans.push_back(2); else if(ans[sz-1] == 2) ans.push_back(1); //ans.push_back(ans[sz-1] < n ? ans[sz-1]+1 :ans[sz-1]-1); } else if(k == 1){ k--; if((ans[sz-1]+s) <= n) ans.push_back(ans[sz-1]+s); else if(ans[sz-1] - s >=1) ans.push_back(ans[sz-1]-s); s -= s; } } printf("YES\n"); int sz = ans.size(); for(int i = 1; i<sz; i++) printf("%lld ", ans[i]); printf("\n"); return 0; }
21.3
70
0.374804
[ "vector" ]
b1746db7da8e6e744b77eefcb3417ee2bd2f377b
5,285
cpp
C++
TopicWiseQuestions/Arrays.cpp
sathvikask0/Coding-Interview-Prep
8151412f92aeb2890d9bbd55c771eac07c28e689
[ "MIT" ]
6
2020-09-19T09:05:03.000Z
2021-11-01T09:12:57.000Z
TopicWiseQuestions/Arrays.cpp
sathvikask0/Coding-Interview-Prep
8151412f92aeb2890d9bbd55c771eac07c28e689
[ "MIT" ]
null
null
null
TopicWiseQuestions/Arrays.cpp
sathvikask0/Coding-Interview-Prep
8151412f92aeb2890d9bbd55c771eac07c28e689
[ "MIT" ]
4
2020-09-20T14:46:20.000Z
2021-08-25T11:59:54.000Z
//some tips: 1. be carful with the variable names u give! some might be overlapping! with what are needed. Eg : you could be using i,j,k as iterators in for loop, but unknowingly you might also use them for something else! // search for Topic : Topic Name // for easy access Topic : Arrays //o(n) rotating array //array rotation void rotate(int a[],int n,int d) { int j,k,temp; for(int i=0;i<__gcd(n,d);i++) { temp = a[i]; j=i; while(1) { k = j+d; if(k>=n) k-=n; if(k==i) break; a[j]=a[k]; j=k; } a[j]=temp; } } //maximum sum sub array //kadane's algo int maxSubArraySum(int a[], int size) { int max_so_far = INT_MIN, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } //problem for finding subarray with the given sum //see the double pointer idea. //remember the left to right idea! string target_sum(int a[],int n, int tar) { int sum = a[0]; int i = 0; int j = 1; while(j<n && i<=j) { sum += a[j]; // in the case sum>tar even a[j] is removed from the sum, its added again here! if (sum > tar) { if(i==j) j++; sum -= a[i]; sum -= a[j]; // because at the start of every iteration we are adding a[j] so we need to remove it here i++; } else if (sum < tar) j++; else { cout << i << " " << j << endl; // prints the subarray! return "Found"; } } return "Not present"; } https://www.interviewbit.com/problems/max-product-subarray/ Max Product Subarray int Solution::maxProduct(const vector<int> &nums) { int ans = INT_MIN; int minAns = 1, maxAns =1; int n = nums.size(); for(int i=0;i<n;i++) { if(nums[i]<0) swap(minAns, maxAns); // because multiplying by a negative number makes make negative max positive and vice versa ans = max(ans, nums[i]*maxAns); minAns = nums[i]*minAns; maxAns = max(1,nums[i]*maxAns); } return ans; } https://www.geeksforgeeks.org/find-smallest-value-represented-sum-subset-given-array/ find the smallest positive integer that is not the sum of a subset of the array. int findSmallest(int arr[], int n) // arr is sorted! { int res = 1; // Initialize result // Traverse the array and increment 'res' if arr[i] is // smaller than or equal to 'res'. for (int i = 0; i < n && arr[i] <= res; i++) res = res + arr[i]; return res; } //Count subarrays with sum less than or equal to k. O(n) https://www.geeksforgeeks.org/number-subarrays-sum-less-k/ int countSubarrays(int arr[], int n, int k) { int start = 0, end = 0, count = 0, sum = arr[0]; while (start < n && end < n) { if (sum < k) { end++; if (end >= start) count += end - start; if (end < n) sum += arr[end]; } else { sum -= arr[start]; start++; } } return count; } //count triplers with sum less than given value int countTriplets(int arr[], int n, int sum) { sort(arr, arr+n); int ans = 0; for (int i = 0; i < n - 2; i++) { int j = i + 1, k = n - 1; // Use Meet in the Middle concept while (j < k) { // If sum of current triplet is more or equal, // move right corner to look for smaller values if (arr[i] + arr[j] + arr[k] >= sum) k--; // Else move left corner else { // This is important. For current i and j, there // can be total k-j third elements. ans += (k - j); j++; } } } return ans; } // Array and deque //maximum of all subarrays of size k https://www.geeksforgeeks.org/sliding-window-maximum-maximum-of-all-subarrays-of-size-k/ void yo(int a[],int n,int k) { deque<int>dq; // using deque! /* Useful elements from the previous window are the elements in the current window and are maximum also! */ dq.push_back(0); for(int i=1;i<k;i++) { while(!dq.empty() && a[dq.back()]<=a[i]) // storing elements in decreasing order and storing only those matter dq.pop_back(); dq.push_back(i); // storing indices very good idea we can remove outside range values easily } cout << a[dq.front()] << " "; for(int i=k;i<n;i++) { while(!dq.empty() && dq.front()<=i-k) // removing outside range values dq.pop_front(); while(!dq.empty() && a[dq.back()]<=a[i]) dq.pop_back(); dq.push_back(i); cout << a[dq.front()] << " "; } }
23.281938
129
0.50842
[ "vector" ]
b176f030f7d2f95b9f75ce736eb65d03d8908f92
1,032
cc
C++
mem/vdtor.cc
anqurvanillapy/cppl
a15231dd0bd68b8857f6596fbf2604b86e5ffd89
[ "MIT" ]
1
2019-08-24T22:46:16.000Z
2019-08-24T22:46:16.000Z
mem/vdtor.cc
anqurvanillapy/cppl
a15231dd0bd68b8857f6596fbf2604b86e5ffd89
[ "MIT" ]
2
2018-11-12T12:20:52.000Z
2019-06-05T06:58:34.000Z
mem/vdtor.cc
anqurvanillapy/cppl
a15231dd0bd68b8857f6596fbf2604b86e5ffd89
[ "MIT" ]
2
2019-04-03T10:01:05.000Z
2021-05-31T07:39:44.000Z
/** * Virtual destructor * ================== * * Always make bad_base classes' destructors virtual: If the static type (e.g. a * bad_base class) of the object to be deleted is different from its dynamic type, * the static type shall be a bad_base class of the dynamic type of the object to * be deleted and *the static type shall have a virtual destructor or the * behavior is undefined. */ #include <iostream> class base { public: base() { std::cout << "ctor: base" << std::endl; } /* virtual */ ~base() { std::cout << "dtor: base" << std::endl; } }; class derived : public base { public: derived() { std::cout << "ctor: derived" << std::endl; } ~derived() { std::cout << "dtor: derived" << std::endl; } }; int main(int argc, const char *argv[]) { base *foo = new derived(); delete foo; // base::~base() might not be triggered (UB), and derived could // fail at dtor too // Note that void pointers know nothing about dtors. // void *bar = foo; return 0; }
27.157895
83
0.610465
[ "object" ]
b17ae33634d01a5fa0b987efb06db458a88b4fb4
24,462
cpp
C++
main.cpp
jvt9999/oglshaderdemo
c5b9ba721a90b06bfdfebae1aeb3305db213d654
[ "MIT" ]
null
null
null
main.cpp
jvt9999/oglshaderdemo
c5b9ba721a90b06bfdfebae1aeb3305db213d654
[ "MIT" ]
null
null
null
main.cpp
jvt9999/oglshaderdemo
c5b9ba721a90b06bfdfebae1aeb3305db213d654
[ "MIT" ]
1
2022-02-14T08:21:58.000Z
2022-02-14T08:21:58.000Z
#define WIN32_LEAN_AND_MEAN #include <windows.h> #undef WIN32_LEAN_AND_MEAN #include <chrono> #include "GL/glew.h" #include "GLFW/glfw3.h" #include "glm/gtc/matrix_transform.hpp" #include "objloader.h" #include "util.h" #include "imgui.h" #include "imgui_internal.h" #include "imgui_impl_glfw.h" #include "imgui_impl_opengl3.h" #include "imgui_impl_win32.h" const float degToRad = 3.1416f / 180.0f; ObjLoader::ObjectFile g_sponza("../data"); GLuint g_blackTexture; GLuint g_whiteTexture; GLuint g_flatNormalTexture; ImFont* g_uiFont = nullptr; ImFont* g_codeFont = nullptr; void update(GLFWwindow* window); void render(GLFWwindow* window); void renderUI(); void errorHandler(int errCode, const char* errMessage) { MessageBoxA(0, errMessage, "Error", MB_OK); } const unsigned int windowWidth = 1920; const unsigned int windowHeight = 1080; struct InputState { glm::dvec2 m_lastMousePosition = { 0, 0 }; }; InputState g_inputState; enum class LightType : int { Unlit, Ambient, Directional, Spot, Point, NumLightTypes // Always at the last position }; enum class ShaderType : int { Ambient, Directional, Spot, Point, NumShaderTypes // Always at the last position }; struct DirectionalLight { glm::vec3 m_lightDirection; glm::vec3 m_lightColor; }; struct SpotLight { glm::vec3 m_lightPosition; glm::vec3 m_lightDirection; glm::vec3 m_lightColor; float m_innerCone; float m_outerCone; }; struct PointLight { glm::vec3 m_lightPosition; glm::vec3 m_lightColor; float m_outerRadius; }; const size_t MaxShaderLength = 8192; struct ShaderState { std::string m_shaderFile; std::vector<char> m_shaderCode; GLuint m_shaderId = 0; ShaderState() { m_shaderCode.resize(MaxShaderLength); } }; struct DemoState { glm::vec3 m_cameraPosition = glm::vec3(-900.0f, 200.0f, 0); glm::vec3 m_cameraDirection = glm::vec3(1.0f, 0.0f, 0.0f); glm::vec3 m_cameraUp = glm::vec3(0.0f, 1.0f, 0.0f); glm::vec3 m_ambientColor = glm::vec3(0.1f, 0.1f, 0.1f); DirectionalLight m_directionalLight; SpotLight m_spotLight; PointLight m_pointLight; LightType m_lightType = LightType::Unlit; float m_specularMultiplier = 0.0f; float m_specPowerMultiplier = 32.0f; float m_camFov = 60.0f; double m_appTime = 0.0f; double m_dt = 0.0f; bool m_lightFollowsCamera = false; // Player Movement float m_yaw = 0.0f; float m_pitch = 0.0f; float m_moveSpeed = 100.0f; float m_sensitivity = 0.1f; // Shader editing ShaderState m_pixelShaders[(int)ShaderType::NumShaderTypes]; ShaderState m_vertexShader; bool m_recompileShaders = false; bool m_reloadShaders = false; bool m_isEditing = false; std::string m_shaderErrors; DemoState() { m_directionalLight.m_lightColor = glm::vec3(1.0f, 1.0f, 1.0f); m_directionalLight.m_lightDirection = glm::vec3(-0.859f, -0.399f, -0.319f); m_spotLight.m_lightColor = glm::vec3(1.0f, 1.0f, 1.0f); m_spotLight.m_lightPosition = glm::vec3(-775.0f, 800.0f, -50.0f); m_spotLight.m_lightDirection = glm::vec3(0.91f, -0.415f, 0.016f); m_spotLight.m_innerCone = 9.0f; m_spotLight.m_outerCone = 10.0f; m_pointLight.m_lightColor = glm::vec3(1.0f, 1.0f, 1.0f); m_pointLight.m_lightPosition = glm::vec3(535.0f, 162.0f, -13.0f); m_pointLight.m_outerRadius = 865.0f; } }; DemoState g_demoState; bool readShaderFromFile(const char* filename, ShaderState& output) { output.m_shaderFile = filename; return Util::loadFileToBuffer(filename, output.m_shaderCode, true, true); } bool reloadShaders(bool reopen, std::string* errorString) { if (!readShaderFromFile("../shaders/vertex.glsl", g_demoState.m_vertexShader)) { if (errorString) *errorString = "Cannot read vertex shader from file!"; return false; } const char* shaderFiles[] = { "../shaders/ambient.glsl", "../shaders/directional.glsl", "../shaders/spot.glsl", "../shaders/point.glsl" }; for (size_t i = 0; i < (size_t)ShaderType::NumShaderTypes; i++) { if (reopen) { if (!readShaderFromFile(shaderFiles[i], g_demoState.m_pixelShaders[i])) { if (errorString) *errorString = "Cannot read ambient shader from file!"; return false; } } const char* vsCode = &g_demoState.m_vertexShader.m_shaderCode[0]; const char* psCode = &g_demoState.m_pixelShaders[i].m_shaderCode[0]; GLuint shader = Util::createShaderProgram(vsCode, psCode, errorString); if (!shader) { return false; } if (g_demoState.m_pixelShaders[i].m_shaderId) glDeleteProgram(g_demoState.m_pixelShaders[i].m_shaderId); g_demoState.m_pixelShaders[i].m_shaderId = shader; } return true; } int __stdcall WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { glfwSetErrorCallback(errorHandler); glfwInit(); glfwWindowHint(GLFW_SAMPLES, 8); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); GLFWwindow* mainWindow = glfwCreateWindow(windowWidth, windowHeight, "Shaders", nullptr, nullptr); if (mainWindow == nullptr) { return -1; } glfwMakeContextCurrent(mainWindow); glewExperimental = true; if (glewInit() != GLEW_OK) { return -1; } // Init ImGui IMGUI_CHECKVERSION(); ImGui::CreateContext(); ImGuiIO& io = ImGui::GetIO(); ImGui::StyleColorsDark(); ImGui_ImplGlfw_InitForOpenGL(mainWindow, true); ImGui_ImplOpenGL3_Init("#version 150"); g_uiFont = io.Fonts->AddFontFromFileTTF("../fonts/Roboto-Regular.ttf", 18); g_codeFont = io.Fonts->AddFontFromFileTTF("../fonts/RobotoMono-Regular.ttf", 18); ImGuiStyle& guiStyle = ImGui::GetStyle(); guiStyle.FrameRounding = 8; guiStyle.WindowRounding = 8; // Load our shaders std::string errString; if (!reloadShaders(true, &errString)) { MessageBoxA(nullptr, errString.c_str(), "Error", MB_OK); return -1; } // Initialize black and white textures { uint32_t black = 0xFF000000; uint32_t white = 0xFFFFFFFF; uint32_t flatNormal = 0xFFFF8080; glGenTextures(1, &g_blackTexture); glBindTexture(GL_TEXTURE_2D, g_blackTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &black); glGenerateMipmap(g_blackTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenTextures(1, &g_whiteTexture); glBindTexture(GL_TEXTURE_2D, g_whiteTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &white); glGenerateMipmap(g_whiteTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glGenTextures(1, &g_flatNormalTexture); glBindTexture(GL_TEXTURE_2D, g_flatNormalTexture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, &flatNormal); glGenerateMipmap(g_flatNormalTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } // Load our 3d Model g_sponza.setErrorCallback(errorHandler); g_sponza.loadFile("sponza.obj"); g_sponza.initGraphics(); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); std::chrono::high_resolution_clock::time_point prevTime = std::chrono::high_resolution_clock::now(); glfwGetCursorPos(mainWindow, &g_inputState.m_lastMousePosition.x, &g_inputState.m_lastMousePosition.y); while(!glfwWindowShouldClose(mainWindow)) { glfwPollEvents(); if (g_demoState.m_reloadShaders) { g_demoState.m_shaderErrors = ""; reloadShaders(true, &g_demoState.m_shaderErrors); g_demoState.m_reloadShaders = false; } if (g_demoState.m_recompileShaders) { g_demoState.m_shaderErrors = ""; reloadShaders(false, &g_demoState.m_shaderErrors); g_demoState.m_recompileShaders = false; } update(mainWindow); ImGui_ImplOpenGL3_NewFrame(); ImGui_ImplGlfw_NewFrame(); ImGui::NewFrame(); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); render(mainWindow); renderUI(); ImGui::Render(); int display_w, display_h; glfwGetFramebufferSize(mainWindow, &display_w, &display_h); glViewport(0, 0, display_w, display_h); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); glfwSwapBuffers(mainWindow); std::chrono::high_resolution_clock::time_point currentTime = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> frameTime = std::chrono::duration_cast<std::chrono::duration<double>>(currentTime - prevTime); prevTime = currentTime; g_demoState.m_dt = frameTime.count(); g_demoState.m_appTime += frameTime.count(); } // Cleanup g_sponza.destroyGraphics(); ImGui_ImplOpenGL3_Shutdown(); ImGui_ImplGlfw_Shutdown(); ImGui::DestroyContext(); glfwDestroyWindow(mainWindow); glfwTerminate(); return 0; } void render(GLFWwindow* window) { glm::vec3 camPosition = g_demoState.m_cameraPosition; glm::vec3 camDir = glm::normalize(g_demoState.m_cameraDirection); glm::vec3 camUp = glm::normalize(g_demoState.m_cameraUp); GLuint shaderProgram = 0; // Setup light parameters if (g_demoState.m_lightType == LightType::Unlit) { shaderProgram = g_demoState.m_pixelShaders[(int)ShaderType::Ambient].m_shaderId; glm::vec3 ambient(1.0f); glUniform3fv(glGetUniformLocation(shaderProgram, "ambientColor"), 1, &ambient[0]); } else if (g_demoState.m_lightType == LightType::Ambient) { shaderProgram = g_demoState.m_pixelShaders[(int)ShaderType::Ambient].m_shaderId; glUniform3fv(glGetUniformLocation(shaderProgram, "ambientColor"), 1, &g_demoState.m_ambientColor[0]); } else if (g_demoState.m_lightType == LightType::Directional) { shaderProgram = g_demoState.m_pixelShaders[(int)ShaderType::Directional].m_shaderId; glm::vec3 lightDir = glm::normalize(g_demoState.m_directionalLight.m_lightDirection); glUniform3fv(glGetUniformLocation(shaderProgram, "lightDir"), 1, &lightDir[0]); glUniform3fv(glGetUniformLocation(shaderProgram, "lightColor"), 1, &g_demoState.m_directionalLight.m_lightColor[0]); glUniform3fv(glGetUniformLocation(shaderProgram, "ambientColor"), 1, &g_demoState.m_ambientColor[0]); glUniform1f(glGetUniformLocation(shaderProgram, "globalSpecMultiplier"), g_demoState.m_specularMultiplier); glUniform3fv(glGetUniformLocation(shaderProgram, "cameraPos"), 1, &g_demoState.m_cameraPosition[0]); } else if (g_demoState.m_lightType == LightType::Spot) { shaderProgram = g_demoState.m_pixelShaders[(int)ShaderType::Spot].m_shaderId; glm::vec3 lightDir = glm::normalize(g_demoState.m_spotLight.m_lightDirection); glUniform3fv(glGetUniformLocation(shaderProgram, "lightDir"), 1, &lightDir[0]); glUniform3fv(glGetUniformLocation(shaderProgram, "lightPos"), 1, &g_demoState.m_spotLight.m_lightPosition[0]); glUniform3fv(glGetUniformLocation(shaderProgram, "lightColor"), 1, &g_demoState.m_spotLight.m_lightColor[0]); glUniform1f(glGetUniformLocation(shaderProgram, "lightInnerCone"), g_demoState.m_spotLight.m_innerCone * degToRad); glUniform1f(glGetUniformLocation(shaderProgram, "lightOuterCone"), g_demoState.m_spotLight.m_outerCone * degToRad); glUniform3fv(glGetUniformLocation(shaderProgram, "ambientColor"), 1, &g_demoState.m_ambientColor[0]); glUniform1f(glGetUniformLocation(shaderProgram, "globalSpecMultiplier"), g_demoState.m_specularMultiplier); glUniform3fv(glGetUniformLocation(shaderProgram, "cameraPos"), 1, &g_demoState.m_cameraPosition[0]); } else if (g_demoState.m_lightType == LightType::Point) { shaderProgram = g_demoState.m_pixelShaders[(int)ShaderType::Point].m_shaderId; glUniform3fv(glGetUniformLocation(shaderProgram, "lightPos"), 1, &g_demoState.m_pointLight.m_lightPosition[0]); glUniform3fv(glGetUniformLocation(shaderProgram, "lightColor"), 1, &g_demoState.m_pointLight.m_lightColor[0]); glUniform1f(glGetUniformLocation(shaderProgram, "lightOuterRadius"), g_demoState.m_pointLight.m_outerRadius); glUniform3fv(glGetUniformLocation(shaderProgram, "ambientColor"), 1, &g_demoState.m_ambientColor[0]); glUniform1f(glGetUniformLocation(shaderProgram, "globalSpecMultiplier"), g_demoState.m_specularMultiplier); glUniform3fv(glGetUniformLocation(shaderProgram, "cameraPos"), 1, &g_demoState.m_cameraPosition[0]); } // Setup matrices int vpWidth, vpHeight; glfwGetFramebufferSize(window, &vpWidth, &vpHeight); glm::mat4x4 world(glm::vec4(1, 0, 0, 0), glm::vec4(0, 1, 0, 0), glm::vec4(0, 0, 1, 0), glm::vec4(0, 0, 0, 1)); glm::mat4x4 view = glm::lookAt(camPosition, camPosition + camDir, camUp); glm::mat4x4 projection = glm::perspectiveFov(g_demoState.m_camFov * degToRad, (float)vpWidth, (float)vpHeight, 1.0f, 5000.0f); glm::mat4x4 wvp = projection * view * world; glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "worldViewProjection"), 1, GL_FALSE, &wvp[0][0]); glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "world"), 1, GL_FALSE, &world[0][0]); glUseProgram(shaderProgram); for(const std::unique_ptr<ObjLoader::Mesh>& mesh : g_sponza.meshes()) { glBindVertexArray(mesh->m_vao); glBindBuffer(GL_ARRAY_BUFFER, mesh->m_vertexBuffer); for (const std::unique_ptr<ObjLoader::SubMesh>& subMesh : mesh->m_subMeshes) { // Set material ObjLoader::Material* mat = subMesh->m_material; if (mat) { GLuint diffusetTex = mat->m_diffuseTexId ? mat->m_diffuseTexId : g_blackTexture; GLuint displacementTex = mat->m_displacementTexId ? mat->m_displacementTexId : g_flatNormalTexture; GLuint specColorTex = mat->m_specularColorTexId ? mat->m_specularColorTexId : g_whiteTexture; GLuint specPowerTex = mat->m_specularMapTexId ? mat->m_specularMapTexId : g_whiteTexture; GLfloat shiny = std::min(1.0f, mat->m_shininess); glActiveTexture(GL_TEXTURE0 + 0); glBindTexture(GL_TEXTURE_2D, diffusetTex); glUniform1i(glGetUniformLocation(shaderProgram, "diffuseTex"), 0); glActiveTexture(GL_TEXTURE0 + 1); glBindTexture(GL_TEXTURE_2D, displacementTex); glUniform1i(glGetUniformLocation(shaderProgram, "normalTex"), 1); glActiveTexture(GL_TEXTURE0 + 2); glBindTexture(GL_TEXTURE_2D, specColorTex); glUniform1i(glGetUniformLocation(shaderProgram, "specularColorTex"), 2); glActiveTexture(GL_TEXTURE0 + 3); glBindTexture(GL_TEXTURE_2D, specPowerTex); glUniform1i(glGetUniformLocation(shaderProgram, "specularPowerTex"), 3); glUniform1f(glGetUniformLocation(shaderProgram, "shininess"), g_demoState.m_specPowerMultiplier); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, subMesh->m_indexBuffer); glDrawElements(GL_TRIANGLES, (GLsizei)subMesh->m_indices.size(), GL_UNSIGNED_INT, 0); } glBindVertexArray(0); } } void update(GLFWwindow* window) { glm::vec3& camPos = g_demoState.m_cameraPosition; glm::vec3& camDir = g_demoState.m_cameraDirection; glm::vec3& camUp = g_demoState.m_cameraUp; // Update camera direction float theta = (90.0f - g_demoState.m_pitch) * degToRad; float phi = g_demoState.m_yaw * degToRad; float cosPhi = cosf(phi); float cosTheta = cosf(theta); float sinPhi = sinf(phi); float sinTheta = sinf(theta); glm::vec3 tempDir(cosPhi * sinTheta, cosTheta, sinPhi * sinTheta); camDir = glm::normalize(tempDir); glm::vec3 camSide = glm::cross(camDir, glm::vec3(0.0f, 1.0f, 0.0f)); camUp = glm::cross(camSide, camDir); camSide = glm::cross(camDir, camUp); // Update camera pos float realMoveSpeed = g_demoState.m_moveSpeed * (float)g_demoState.m_dt; // Update input if (!g_demoState.m_isEditing) { if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS) { camPos += camDir * realMoveSpeed; } else if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS) { camPos -= camDir * realMoveSpeed; } if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS) { camPos -= camSide * realMoveSpeed; } else if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS) { camPos += camSide * realMoveSpeed; } } camDir = glm::normalize(camDir); glm::dvec2 curMouse; glfwGetCursorPos(window, &curMouse.x, &curMouse.y); glm::dvec2 deltaMouse = curMouse - g_inputState.m_lastMousePosition; g_inputState.m_lastMousePosition = curMouse; if (glfwGetMouseButton(window, 1) == GLFW_PRESS) { g_demoState.m_pitch -= (float)deltaMouse.y * g_demoState.m_sensitivity; g_demoState.m_yaw += (float)deltaMouse.x * g_demoState.m_sensitivity; g_demoState.m_pitch = glm::clamp(g_demoState.m_pitch, -89.0f, 89.0f); } // Update lights if (g_demoState.m_lightFollowsCamera) { g_demoState.m_spotLight.m_lightPosition = camPos; g_demoState.m_pointLight.m_lightPosition = camPos; g_demoState.m_directionalLight.m_lightDirection = camDir; g_demoState.m_spotLight.m_lightDirection = camDir; } } void renderUI() { ImGui::Begin("Shader Demo"); // FPS //int fps = (int)(1.0f / g_demoState.m_dt); //ImGui::Text("%d frames/second", fps); // Camera Params ImGui::Text("Controls"); ImGui::SliderFloat("FOV##fov", &g_demoState.m_camFov, 20.0f, 90.0f); ImGui::SliderFloat("Move Speed##movespeed", &g_demoState.m_moveSpeed, 100.0f, 1000.0f); ImGui::SliderFloat("Sensitivity##sensitivity", &g_demoState.m_sensitivity, 0.1f, 1.0f); if (ImGui::CollapsingHeader("Lights")) { const char* lightTypes[] = { "Unlit", "Ambient", "Directional", "Spot Light", "Point Light" }; ImGui::Combo("Light Type##lighttype", (int*)&g_demoState.m_lightType, lightTypes, IM_ARRAYSIZE(lightTypes)); ImGui::ColorEdit3("Ambient##ambientColor", &g_demoState.m_ambientColor[0], 0); ImGui::SliderFloat("Specular Multiplier##lightSpecMult", &g_demoState.m_specularMultiplier, 0.0f, 2.0f); ImGui::SliderFloat("Specular Power Multiplier##lightSpecPowMult", &g_demoState.m_specPowerMultiplier, 1.0f, 256.0f); ImGui::Checkbox("Follow Camera", &g_demoState.m_lightFollowsCamera); if (g_demoState.m_lightType == LightType::Directional) { ImGui::ColorEdit3("Color##spotcolor", &g_demoState.m_directionalLight.m_lightColor[0], 0); ImGui::SliderFloat3("Direction##d1", &g_demoState.m_directionalLight.m_lightDirection[0], -1.0f, 1.0f); } else if (g_demoState.m_lightType == LightType::Spot) { ImGui::ColorEdit3("Color##spotcolor", &g_demoState.m_spotLight.m_lightColor[0], 0); ImGui::SliderFloat("Inner Cone##innercone", &g_demoState.m_spotLight.m_innerCone, 0.0f, 20.0f); ImGui::SliderFloat("Outer Cone##outercone", &g_demoState.m_spotLight.m_outerCone, 0.0f, 20.0f); ImGui::SliderFloat3("Direction##d2", &g_demoState.m_spotLight.m_lightDirection[0], -1.0f, 1.0f); ImGui::SliderFloat3("Position##p2", &g_demoState.m_spotLight.m_lightPosition[0], -1000.0f, 1000.0f); if (g_demoState.m_spotLight.m_innerCone > g_demoState.m_spotLight.m_outerCone - 0.01f) g_demoState.m_spotLight.m_innerCone = g_demoState.m_spotLight.m_outerCone - 0.01f; } else if (g_demoState.m_lightType == LightType::Point) { ImGui::ColorEdit3("Color##spotcolor", &g_demoState.m_pointLight.m_lightColor[0], 0); ImGui::SliderFloat("Radius##outerradius", &g_demoState.m_pointLight.m_outerRadius, 20.0f, 4000.0f); ImGui::SliderFloat3("Position##p3", &g_demoState.m_pointLight.m_lightPosition[0], -1000.0f, 1000.0f); } // Shaders { ShaderType currentShader; switch (g_demoState.m_lightType) { case LightType::Unlit: case LightType::Ambient: currentShader = ShaderType::Ambient; break; case LightType::Directional: currentShader = ShaderType::Directional; break; case LightType::Spot: currentShader = ShaderType::Spot; break; case LightType::Point: currentShader = ShaderType::Point; break; default: currentShader = ShaderType::Ambient; } ShaderState& curShader = g_demoState.m_pixelShaders[(int)currentShader]; ImGui::Text("Shader Code:"); if (g_codeFont) ImGui::PushFont(g_codeFont); ImGui::InputTextMultiline("Code##shadercode", &curShader.m_shaderCode[0], curShader.m_shaderCode.size(), ImVec2(-FLT_MIN, ImGui::GetTextLineHeight() * 24), ImGuiInputTextFlags_AllowTabInput); if (g_codeFont) ImGui::PopFont(); g_demoState.m_isEditing = ImGui::IsItemFocused(); static bool enableSave = false; ImGui::Checkbox("Enable Save##enablesave", &enableSave); if (!enableSave) { ImGui::PushItemFlag(ImGuiItemFlags_Disabled, true); } if (ImGui::Button("Save to disk##saveshader")) { for (size_t i = 0; i < (size_t)ShaderType::NumShaderTypes; i++) { ShaderState& shaderToSave = g_demoState.m_pixelShaders[i]; if (shaderToSave.m_shaderFile.length()) { FILE* f = fopen(shaderToSave.m_shaderFile.c_str(), "wb"); if (f) { int size = (int)strlen((const char*)&shaderToSave.m_shaderCode[0]); fwrite(&shaderToSave.m_shaderCode[0], 1, size, f); fclose(f); } } } } if (!enableSave) { ImGui::PopItemFlag(); } ImGui::SameLine(); if (ImGui::Button("Reload from disk##saveshader")) { g_demoState.m_reloadShaders = true; } ImGui::SameLine(); if (ImGui::Button("Compile Shaders##compile")) { g_demoState.m_recompileShaders = true; } ImGui::TextWrapped(g_demoState.m_shaderErrors.c_str()); } } ImGui::End(); }
37.984472
203
0.65473
[ "mesh", "render", "vector", "model", "3d" ]
b180cbc3e8cdea55659becb775b4ae855916ab25
42,343
cpp
C++
src/viewer/GLRender.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
src/viewer/GLRender.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
src/viewer/GLRender.cpp
serserar/ModelConverter
23e6237a347dc959de191d4cc378defb0a9d044b
[ "MIT" ]
null
null
null
/* -*- c++ -*- */ ///////////////////////////////////////////////////////////////////////////// // // Main.cpp -- Copyright (c) 2006-2007 David Henry // last modification: jan. 28, 2007 // // This code is licenced under the MIT license. // // This software is provided "as is" without express or implied // warranties. You may freely copy and compile this source into // applications you distribute provided that the copyright text // below is included in the resulting source code. // // Doom 3's MD5Mesh Viewer main source file. // ///////////////////////////////////////////////////////////////////////////// #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif // WIN32 #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <string> #include <GL/glew.h> #include <SDL2/SDL.h> #include <SDL2/SDL_ttf.h> #include "GlErrors.h" #include "Mathlib.h" #include "Font.h" #include "Md5Model.h" #include "TextureManager.h" #include "ArbProgram.h" #include "Shader.h" #include "GLRender.h" #include "../base/Camera.h" #include "../util/ImageUtils.h" #include "../image/PPMReader.h" using std::cout; using std::cerr; using std::endl; using std::string; using std::vector; AnimatedModel* bmodel = nullptr; vector<Ray> rayList; Camera* cam = nullptr; Texture2D* texture = nullptr; Md5Model *model = NULL; //Md5Object *object = NULL; TTFont *font = NULL; SDL_Window* surface; // Current shader and vertex/fragment programs ShaderProgram *shader = NULL; ArbVertexProgram *vp = NULL; ArbFragmentProgram *fp = NULL; // All vertex and fragment programs ArbVertexProgram *vp_bump = NULL; ArbVertexProgram *vp_bump_parallax = NULL; ArbFragmentProgram *fp_diffuse = NULL; ArbFragmentProgram *fp_diffuse_specular = NULL; ArbFragmentProgram *fp_ds_parallax = NULL; // We can use a specific render path, depending on // which shader/program we want to use... render_path_e renderPath; // Tangent uniform's location GLint tangentLoc = -1; int renderFlags = Md5Object::kDrawModel; int fps = 0; bool bAnimate = true; bool bTextured = true; bool bCullFace = true; bool bBounds = false; bool bParallax = false; bool bLight = true; bool bSmooth = true; bool bWireframe = false; bool bDrawNormals = false; bool bDrawVoxels = false; vector<string> animations; const char windowTitle[] = "MD5 Model Viewer Demo"; const int windowWidth = 1024; const int windowHeight = 768; const int windowDepth = 24; // Camera Vector3f rot, eye; // Application's Timer struct Timer { public: Timer () : current_time ( 0.0 ), last_time ( 0.0 ) { } public: void update () { last_time = current_time; current_time = static_cast<double> ( SDL_GetTicks () ) / 1000.0; } double deltaTime () const { return ( current_time - last_time ); } public: double current_time; double last_time; } timer; // ------------------------------------------------------------------------- // shutdownApp // // Application termination. // ------------------------------------------------------------------------- static void shutdownApp ( int returnCode ) { delete model; //666delete object; delete bmodel; delete font; delete shader; delete vp_bump; delete vp_bump_parallax; delete fp_diffuse; delete fp_diffuse_specular; delete fp_ds_parallax; delete texture; Texture2DManager::kill (); exit ( returnCode ); } // ------------------------------------------------------------------------- // begin2D // // Enter into 2D mode. // ------------------------------------------------------------------------- static void begin2D () { GLint viewport[4]; glGetIntegerv ( GL_VIEWPORT, viewport ); glMatrixMode ( GL_PROJECTION ); glPushMatrix (); glLoadIdentity (); glOrtho ( 0, viewport[2], 0, viewport[3], -1, 1 ); glMatrixMode ( GL_MODELVIEW ); glLoadIdentity(); } // ------------------------------------------------------------------------- // end2D // // Return from 2D mode. // ------------------------------------------------------------------------- static void end2D () { glMatrixMode ( GL_PROJECTION ); glPopMatrix (); glMatrixMode ( GL_MODELVIEW ); } // ------------------------------------------------------------------------- // extractFromQuotes // // Extract a string from quotes. // ------------------------------------------------------------------------- inline const string extractFromQuotes ( const string &str ) { string::size_type start = str.find_first_of ( '\"' ) + 1; string::size_type end = str.find_first_of ( '\"', start ) - 2; return str.substr ( start, end ); } // ------------------------------------------------------------------------- // parseLoaderScript // // Parse a script file for loading md5mesh and animations. // ------------------------------------------------------------------------- static void parseLoaderScript ( const string &filename ) { // Open the file to parse std::ifstream file ( filename.c_str(), std::ios::in ); if ( file.fail () ) { cerr << "Couldn't open " << filename << endl; shutdownApp ( 1 ); } // Get texture manager Texture2DManager *texMgr = Texture2DManager::getInstance (); while ( !file.eof () ) { string token, buffer; string meshFile, animFile, textureFile; string meshName, animName; // Peek next token file >> token; if ( token == "model" ) { std::getline ( file, buffer ); meshFile = extractFromQuotes ( buffer ); // Delete previous model and object if existing delete model; ///666delete object; // Load mesh model model = new Md5Model ( meshFile ); //666object = new Md5Object (model); } else if ( token == "anim" ) { std::getline ( file, buffer ); animFile = extractFromQuotes ( buffer ); try { // Load animation if ( model ) model->addAnim ( animFile ); } catch ( Md5Exception &err ) { cerr << "Failed to load animation " << animFile << endl; cerr << "Reason: " << err.what () << " (" << err.which () << ")" << endl; } } else if ( token == "hide" ) { std::getline ( file, buffer ); meshName = extractFromQuotes ( buffer ); // Set mesh's render state if ( model ) model->setMeshRenderState ( meshName, Md5Mesh::kHide ); } else if ( ( token == "decalMap" ) || ( token == "specularMap" ) || ( token == "normalMap" ) || ( token == "heightMap" ) ) { // Get the next token and extract the mesh name file >> buffer; long start = buffer.find_first_of ( '\"' ) + 1; long end = buffer.find_first_of ( '\"', start ) - 1; meshName = buffer.substr ( start, end ); // Get the rest of line and extract texture's filename std::getline ( file, buffer ); textureFile = extractFromQuotes ( buffer ); // If the model has been loaded, setup // the texture to the desired mesh if ( model ) { Texture2D *tex = texMgr->load ( textureFile ); if ( tex->fail () ) cerr << "failed to load " << textureFile << endl; if ( token == "decalMap" ) model->setMeshDecalMap ( meshName, tex ); else if ( token == "specularMap" ) model->setMeshSpecularMap ( meshName, tex ); else if ( token == "normalMap" ) model->setMeshNormalMap ( meshName, tex ); else if ( token == "heightMap" ) model->setMeshHeightMap ( meshName, tex ); } } else if ( token == "setAnim" ) { std::getline ( file, buffer ); animName = extractFromQuotes ( buffer ); // Set object's default animation //666object->setAnim (animName); } } file.close (); //666if (!model || !object) //666 throw Md5Exception ("No mesh found!", filename); } // ------------------------------------------------------------------------- // announceRenderPath // // Print info about a render path. // ------------------------------------------------------------------------- static void announceRenderPath ( render_path_e path ) { cout << "Render path: "; switch ( path ) { case R_normal: cout << "no bump mapping (fixed pipeline)" << endl; break; case R_ARBfp_diffuse: cout << "bump mapping, diffuse only " << "(ARB vp & fp)" << endl; break; case R_ARBfp_diffuse_specular: cout << "bump mapping, diffuse and specular " << "(ARB vp & fp)" << endl; break; case R_ARBfp_ds_parallax: cout << "bump mapping with parallax " << "(ARB fp & fp)" << endl; break; case R_shader: cout << "bump mapping with parallax " << "(GLSL)" << endl; break; } } // ------------------------------------------------------------------------- // initShader // // Shader's uniform variables initialization. // ------------------------------------------------------------------------- static void initShader () { if ( NULL == shader ) return; shader->use (); if ( GLEW_VERSION_2_0 ) { GLuint prog = shader->handle (); // Set uniform parameters glUniform1i ( glGetUniformLocation ( prog, "decalMap" ), 0 ); glUniform1i ( glGetUniformLocation ( prog, "glossMap" ), 1 ); glUniform1i ( glGetUniformLocation ( prog, "normalMap" ), 2 ); glUniform1i ( glGetUniformLocation ( prog, "heightMap" ), 3 ); glUniform1i ( glGetUniformLocation ( prog, "parallaxMapping" ), bParallax ); // Get attribute location tangentLoc = glGetAttribLocation ( prog, "tangent" ); } else { GLhandleARB prog = shader->handle (); // Set uniform parameters glUniform1iARB ( glGetUniformLocationARB ( prog, "decalMap" ), 0 ); glUniform1iARB ( glGetUniformLocationARB ( prog, "glossMap" ), 1 ); glUniform1iARB ( glGetUniformLocationARB ( prog, "normalMap" ), 2 ); glUniform1iARB ( glGetUniformLocationARB ( prog, "heightMap" ), 3 ); glUniform1iARB ( glGetUniformLocationARB ( prog, "parallaxMapping" ), bParallax ); // Get attribute location tangentLoc = glGetAttribLocationARB ( prog, "tangent" ); } shader->unuse (); // Warn ff we fail to get tangent location... We'll can still use // the shader, but without tangents if ( tangentLoc == -1 ) cerr << "Warning! No \"tangent\" uniform found in shader!" << endl; } // ------------------------------------------------------------------------- // initOpenGL // // OpenGL initialization. // ------------------------------------------------------------------------- static void initOpenGL () { glClearColor ( 0.5f, 0.5f, 0.5f, 0.0f ); glShadeModel ( GL_SMOOTH ); glCullFace ( GL_BACK ); glEnable ( GL_DEPTH_TEST ); glewExperimental = GL_TRUE; // Initialize GLEW GLenum err = glewInit (); if ( GLEW_OK != err ) { // Problem: glewInit failed, something is seriously wrong. cerr << "Error: " << glewGetErrorString ( err ) << endl; shutdownApp ( -1 ); } // Print some infos about user's OpenGL implementation cout << "OpenGL Version String: " << glGetString ( GL_VERSION ) << endl; cout << "GLU Version String: " << gluGetString ( GLU_VERSION ) << endl; cout << "GLEW Version String: " << glewGetString ( GLEW_VERSION ) << endl; // Initialize ARB vertex/fragment program support initArbProgramHandling (); // Initialize GLSL shader support initShaderHandling (); if ( hasArbVertexProgramSupport () && hasArbFragmentProgramSupport () ) { // Load ARB programs vp_bump = new ArbVertexProgram ( "../bump.vp" ); vp_bump_parallax = new ArbVertexProgram ( "../bumpparallax.vp" ); fp_diffuse = new ArbFragmentProgram ( "../bumpd.fp" ); fp_diffuse_specular = new ArbFragmentProgram ( "../bumpds.fp" ); fp_ds_parallax = new ArbFragmentProgram ( "../bumpdsp.fp" ); // Current ARB programs will be bump mapping with diffuse // and specular components vp = vp_bump; fp = fp_diffuse_specular; } if ( hasShaderSupport () ) { // Load shader VertexShader vs ( "../bump.vert" ); FragmentShader fs ( "../bump.frag" ); shader = new ShaderProgram ( "bump mapping", vs, fs ); // Initialize shader's uniforms initShader (); } // Announce avalaible render paths, select the best cout << endl << "Avalaible render paths:" << endl; cout << " [F3] - No bump mapping (fixed pipeline)" << endl; renderPath = R_normal; if ( vp_bump && fp_diffuse ) { cout << " [F4] - Bump mapping, diffuse only " << "(ARB vp & fp)" << endl; renderPath = R_ARBfp_diffuse; } if ( vp_bump && fp_diffuse_specular ) { cout << " [F5] - Bump mapping, diffuse and specular " << "(ARB vp & fp)" << endl; renderPath = R_ARBfp_diffuse_specular; } if ( vp_bump_parallax && fp_ds_parallax ) { cout << " [F6] - Bump mapping with parallax " << "(ARB vp & fp)" << endl; } if ( shader ) { cout << " [F7] - Bump mapping with parallax " << "(GLSL)" << endl; renderPath = R_shader; } // Announce which path has been chosen by default cout << endl; announceRenderPath ( renderPath ); // Initialize true type font try { font = new TTFont ( "../Vera.ttf", 12, 1 ); } catch ( std::runtime_error &err ) { cerr << "Failed to create truetype font" << endl; cerr << "Reason: " << err.what () << endl; } checkOpenGLErrors ( __FILE__, __LINE__ ); } // ------------------------------------------------------------------------- // initApplication // // Application initialization. // ------------------------------------------------------------------------- static void initApplication ( AnimatedModel* otherModel ) { // Load model and animations try { bmodel = otherModel; //bmodel->setAnimation("run2"); string textureFile = "/home/serserar/projects/cpp/ModelConverter/build/null.tga"; Texture2DManager *texMgr = Texture2DManager::getInstance (); texture = texMgr->load ( textureFile ); // float width=160; // float height=120; // float width=320; // float height=240; float width=256; float height=256; MVector3<float> eye; MVector3<float> up ( 0.0f,1.0f,0.0f ); MVector3<float> center ( 0.0f,0.0f, -1.0f ); cam = new Camera ( width, height, eye, up, center, 0.5f, 6.0f, 57.82f, 45.0f ); } catch ( Md5Exception &err ) { //cerr << "Failed to load model from " << filename << endl; cerr << "Reason: " << err.what () << " (" << err.which () << ")" << endl; shutdownApp ( -1 ); } // Build animation list // Md5Model::AnimMap anims = model->anims (); // animations.reserve (anims.size () + 1); // animations.push_back (string ()); // bind-pose // // for (Md5Model::AnimMap::iterator itor = anims.begin (); // itor != anims.end (); ++itor) // animations.push_back (itor->first); // Camera initialization rot._x = 0.0; eye._x = 0.0; rot._y = 0.0; eye._y = 0.0; rot._z = 0.0; eye._z = 100.0; } // ------------------------------------------------------------------------- // reshape // // Reinit OpenGL viewport when resizing window. // ------------------------------------------------------------------------- static void reshape ( GLsizei width, GLsizei height ) { if ( height == 0 ) height = 1; glViewport ( 0, 0, width, height ); // Reinit projection matrix glMatrixMode ( GL_PROJECTION ); glLoadIdentity (); gluPerspective ( 45.0, width/static_cast<GLfloat> ( height ), 0.1f, 10000.0f ); // Reinit model-view matrix glMatrixMode ( GL_MODELVIEW ); glLoadIdentity (); } // ------------------------------------------------------------------------- // gameLogic // // Perform application logic. // ------------------------------------------------------------------------- static void gameLogic () { // Calculate frames per seconds static double current_time = 0; static double last_time = 0; static int n = 0; n++; current_time = timer.current_time; double dt = timer.current_time - timer.last_time; //Entity* player_entity = EntityManager::GetInstance()->GetEntity(12); //player_entity->GetStatus(); if ( current_time -last_time >= 1.0 ) { fps = n; n = 0; last_time = current_time; } bmodel->OnUpdate ( dt ); } // ------------------------------------------------------------------------- // setupLight // // Setup light position and enable light0. // ------------------------------------------------------------------------- void setupLight ( GLfloat x, GLfloat y, GLfloat z ) { GLfloat lightPos[4]; lightPos[0] = x; lightPos[1] = y; lightPos[2] = z; lightPos[3] = 1.0f; glDisable ( GL_LIGHTING ); glDisable ( GL_LIGHT0 ); if ( bLight ) { glPushMatrix (); glLoadIdentity (); glLightfv ( GL_LIGHT0, GL_POSITION, lightPos ); glPopMatrix (); glEnable ( GL_LIGHTING ); glEnable ( GL_LIGHT0 ); } } // ------------------------------------------------------------------------- // drawObb // // Draw an Oriented Bouding Box. // ------------------------------------------------------------------------- static void drawObb ( const Matrix4x4f &modelView, const BBox &obb ) { Vector3f corners[8]; corners[0] = Vector3f ( obb.boundMin.GetX(), obb.boundMin.GetY(), obb.boundMax.GetZ() ); corners[1] = Vector3f ( obb.boundMax.GetX(), obb.boundMin.GetY(), obb.boundMax.GetZ() ); corners[2] = Vector3f ( obb.boundMax.GetX(), obb.boundMin.GetY(), obb.boundMin.GetZ() ); corners[3] = Vector3f ( obb.boundMin.GetX(), obb.boundMin.GetY(), obb.boundMin.GetZ() ); corners[4] = Vector3f ( obb.boundMin.GetX(), obb.boundMax.GetY(), obb.boundMax.GetZ() ); corners[5] = Vector3f ( obb.boundMax.GetX(), obb.boundMax.GetY(), obb.boundMax.GetZ() ); corners[6] = Vector3f ( obb.boundMax.GetX(), obb.boundMax.GetY(), obb.boundMin.GetZ() ); corners[7] = Vector3f ( obb.boundMin.GetX(), obb.boundMax.GetY(), obb.boundMin.GetZ() ); // Setup world model view matrix glLoadIdentity (); glMultMatrixf ( modelView._m ); glPushAttrib ( GL_ENABLE_BIT ); glDisable ( GL_TEXTURE_2D ); glDisable ( GL_LIGHTING ); GLuint indices[24] = { 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 }; glColor3f ( 1.0, 0.0, 0.0 ); glEnableClientState ( GL_VERTEX_ARRAY ); glVertexPointer ( 3, GL_FLOAT, 0, corners ); glDrawElements ( GL_LINES, 24, GL_UNSIGNED_INT, indices ); glDisableClientState ( GL_VERTEX_ARRAY ); // GL_ENABLE_BIT glPopAttrib(); } // ------------------------------------------------------------------------- // drawAxes // // Draw the X, Y and Z axes at the center of world. // ------------------------------------------------------------------------- static void drawAxes ( const Matrix4x4f &modelView ) { // Setup world model view matrix glLoadIdentity (); glMultMatrixf ( modelView._m ); // Draw the three axes glBegin ( GL_LINES ); // X-axis in red glColor3f ( 1.0f, 0.0f, 0.0f ); glVertex3fv ( kZeroVectorf._v ); glVertex3fv ( kZeroVectorf + Vector3f ( 10.0f, 0.0f, 0.0 ) ); // Y-axis in green glColor3f ( 0.0f, 1.0f, 0.0f ); glVertex3fv ( kZeroVectorf._v ); glVertex3fv ( kZeroVectorf + Vector3f ( 0.0f, 10.0f, 0.0 ) ); // Z-axis in blue glColor3f ( 0.0f, 0.0f, 1.0f ); glVertex3fv ( kZeroVectorf._v ); glVertex3fv ( kZeroVectorf + Vector3f ( 0.0f, 0.0f, 10.0 ) ); glEnd (); } static void drawSkeleton ( const Matrix4x4f &modelView, Skeleton& skeleton ) { // Setup world model view matrix glLoadIdentity (); glMultMatrixf ( modelView._m ); // Draw each joint glPointSize ( 5.0f ); glColor3f ( 1.0f, 0.0f, 0.0f ); glBegin ( GL_POINTS ); for ( auto joint : skeleton.joints ) glVertex3f ( joint->GetPosition()->GetX(), joint->GetPosition()->GetY(), joint->GetPosition()->GetZ() ); glEnd (); glPointSize ( 1.0f ); // Draw each bone glColor3f ( 0.0f, 1.0f, 0.0f ); glBegin ( GL_LINES ); for ( auto joint : skeleton.joints ) { if ( joint->GetParent() != -1 ) { glVertex3f ( skeleton.joints[joint->GetParent()]->GetPosition()->GetX(), skeleton.joints[joint->GetParent()]->GetPosition()->GetY(), skeleton.joints[joint->GetParent()]->GetPosition()->GetZ() ); glVertex3f ( joint->GetPosition()->GetX(), joint->GetPosition()->GetY(), joint->GetPosition()->GetZ() ); } } glEnd (); } static void drawRay ( const Matrix4x4f &modelView, vector<Ray>& rayList ) { if ( rayList.size() > 0 ) { // Setup world model view matrix glLoadIdentity (); glMultMatrixf ( modelView._m ); // Draw each bone glColor3f ( 0.0f, 1.0f, 0.0f ); glPointSize ( 1.0f ); glBegin ( GL_LINES ); for ( auto ray : rayList ) { glVertex3f ( ray.GetOrigin().GetX(), ray.GetOrigin().GetY(), ray.GetOrigin().GetZ() ); glVertex3f ( ray.GetOrigin().GetX() + ray.GetDirection().GetX() *256, ray.GetOrigin().GetY() + ray.GetDirection().GetY() *256, ray.GetOrigin().GetZ() + ray.GetDirection().GetZ() *256 ); } glEnd (); glPointSize ( 1.0f ); } } static Mesh* buildCubeMesh() { // vertices std::vector<GLfloat> vertices { -5,0,-5, 5,0,-5, -5,10,-5, -5,0,5, 5,10,-5, 5,0,5, -5,10,5, 5,10,5 }; // Color buffer std::vector<GLubyte> colors { 0,0,0,255, 255,0,0,255, 0,255,0,255, 0,0,255,255, 255,255,0,255, 255,0,255,255, 0,255,255,255, 255,255,255,255 }; // Vertex index buffer std::vector<GLuint> indices { 0,1,4, 4,2,0, 0,2,6, 6,3,0, 0,3,5, 5,1,0, 1,4,7, 7,5,1, 5,7,6, 6,3,5, 2,6,7, 7,4,2 }; Mesh* mesh = new Mesh(); mesh->vertexCoords.insert ( mesh->vertexCoords.end(), vertices.begin(), vertices.end() ); mesh->colorCoords.insert ( mesh->colorCoords.end(), colors.begin(), colors.end() ); mesh->indexBuffer.insert ( mesh->indexBuffer.end(), indices.begin(), indices.end() ); int index = 0; for ( int i = 0; i < indices.size(); i++ ) { if ( i % 3 == 0 ) { mesh->indexModeBuffer.push_back ( Mesh::indexMode::Triangles ); mesh->indexBuffer.push_back ( index ); index++; } mesh->indexSections[0].push_back ( indices.at ( i ) ); } mesh->indexLenghts.push_back ( indices.size() ); return mesh; } static void drawCube() { // vertices std::vector<GLfloat> vertices { -5,0,-5, 5,0,-5, -5,10,-5, -5,0,5, 5,10,-5, 5,0,5, -5,10,5, 5,10,5 }; // Color buffer std::vector<GLubyte> colors { 0,0,0,255, 255,0,0,255, 0,255,0,255, 0,0,255,255, 255,255,0,255, 255,0,255,255, 0,255,255,255, 255,255,255,255 }; // Vertex index buffer std::vector<GLuint> indices { 0,1,4, 4,2,0, 0,2,6, 6,3,0, 0,3,5, 5,1,0, 1,4,7, 7,5,1, 5,7,6, 6,3,5, 2,6,7, 7,4,2 }; glEnableClientState ( GL_COLOR_ARRAY ); glEnableClientState ( GL_VERTEX_ARRAY ); glColorPointer ( 4, GL_UNSIGNED_BYTE, 0, &colors.front() ); glVertexPointer ( 3, GL_FLOAT, 0, &vertices.front() ); glDrawElements ( GL_TRIANGLES, indices.size(), GL_UNSIGNED_INT, &indices.front() ); glDisableClientState ( GL_VERTEX_ARRAY ); glDisableClientState ( GL_COLOR_ARRAY ); } static GLenum getPrimitive ( Mesh::indexMode imode ) { GLenum mode = GL_TRIANGLES; switch ( imode ) { case Mesh::indexMode::Triangles: mode = GL_TRIANGLES; break; case Mesh::indexMode::TriangleFan: mode = GL_TRIANGLE_FAN; break; case Mesh::indexMode::TriangleStrip: mode = GL_TRIANGLE_STRIP; break; case Mesh::indexMode::Quads: mode = GL_QUADS; break; case Mesh::indexMode::QuadStrip: mode = GL_QUAD_STRIP; break; case Mesh::indexMode::Lines: mode = GL_LINES; break; case Mesh::indexMode::LineStrip: mode = GL_LINE_STRIP; break; case Mesh::indexMode::LineLoop: mode = GL_LINE_LOOP; break; case Mesh::indexMode::Points: mode = GL_POINT; break; } return mode; } static void CopyDepthBuffer ( GLuint texId, int x, int y, int imageWidth, int imageHeight ) { glBindTexture ( GL_TEXTURE_2D, texId ); glReadBuffer ( GL_BACK ); // Ensure we are reading from the back buffer. glCopyTexImage2D ( GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, x, y, imageWidth, imageHeight, 0 ); } static void renderMesh ( const Matrix4x4f &modelView, Mesh& mesh ) { // Vertex index buffer std::vector<GLuint> indices { 0,1,4, 4,2,0, 0,2,6, 6,3,0, 0,3,5, 5,1,0, 1,4,7, 7,5,1, 5,7,6, 6,3,5, 2,6,7, 7,4,2 }; std::vector<GLfloat> vertices { -5,0,-5, 5,0,-5, -5,10,-5, -5,0,5, 5,10,-5, 5,0,5, -5,10,5, 5,10,5 }; // Ensable shader/program's stuff //preRenderVertexArrays (); // Setup world model view matrix glLoadIdentity (); glMultMatrixf ( modelView._m ); glEnableClientState ( GL_VERTEX_ARRAY ); glEnableClientState ( GL_NORMAL_ARRAY ); glEnableClientState ( GL_TEXTURE_COORD_ARRAY ); // Upload mesh data to OpenGL glVertexPointer ( 3, GL_FLOAT, 0, &mesh.vertexCoords.front() ); //glVertexPointer (3, GL_FLOAT, 0, &vertices.front()); glNormalPointer ( GL_FLOAT, 0, &mesh.normalCoords.front() ); glTexCoordPointer ( 2, GL_FLOAT, 0, &mesh.textureCoords.at ( 0 ).front() ); // Bind to mesh's textures //setupTexture (_heightMap, GL_TEXTURE3); //setupTexture (_normalMap, GL_TEXTURE2); //setupTexture (_specMap, GL_TEXTURE1); //setupTexture (_decal, GL_TEXTURE0); texture->bind ( GL_TEXTURE0 ); // Draw the mesh mesh.UpdatePrimitiveCounts(); for ( int section = 0; section < mesh.GetSectionCount(); section++ ) { Mesh::indexMode indexMode = mesh.indexModeBuffer.at ( section ); glDrawElements ( getPrimitive ( indexMode ), mesh.indexSections[section].size(),GL_UNSIGNED_INT, &mesh.indexSections[section].front() ); } // // glDrawElements (getPrimitive(Mesh::indexMode::Points), mesh.indexSections[section].size(),GL_UNSIGNED_INT, &mesh.indexSections[section].front()); // // vector<int> indexVec = mesh.indexSections[section]; // // glBegin(getPrimitive(indexMode));//start drawing a line loop // // for(auto index : indexVec){ // // glVertex3f(mesh.vertexCoords[index*3],mesh.vertexCoords[index*3+1],mesh.vertexCoords[index*3+2]); // // } // // glEnd();//end drawing of line loop // for ( auto triangle : mesh.triangleList ) { // glBegin(GL_TRIANGLES); // glVertex3f(triangle.v1.GetX(), triangle.v1.GetY(), triangle.v1.GetZ()); // glVertex3f(triangle.v2.GetX(), triangle.v2.GetY(), triangle.v2.GetZ()); // glVertex3f(triangle.v3.GetX(), triangle.v3.GetY(), triangle.v3.GetZ()); // glEnd();//end drawing of line loop // } glDisableClientState ( GL_TEXTURE_COORD_ARRAY ); glDisableClientState ( GL_NORMAL_ARRAY ); glDisableClientState ( GL_VERTEX_ARRAY ); if ( bBounds ) drawObb ( modelView, mesh.bbox ); // Disable shader/program's stuff //postRenderVertexArrays (); } // ------------------------------------------------------------------------- // draw3D // // Render the 3D part of the scene. // ------------------------------------------------------------------------- static void draw3D () { // Clear the window glClear ( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glMatrixMode ( GL_MODELVIEW ); glLoadIdentity (); // Camera rotation Matrix4x4f camera; #if 0 camera.identity (); glTranslated ( -eye._x, -eye._y, -eye._z ); glRotated ( rot._x, 1.0f, 0.0f, 0.0f ); glRotated ( rot._y, 0.0f, 1.0f, 0.0f ); glRotated ( rot._z, 0.0f, 0.0f, 1.0f ); #else camera.fromEulerAngles ( degToRad ( rot._x ), degToRad ( rot._y ), degToRad ( rot._z ) ); camera.setTranslation ( -eye ); MVector3<float> camEye; camEye.SetX ( eye._x ); camEye.SetY ( eye._y ); camEye.SetZ ( eye._z ); cam->SetEye ( camEye ); #endif // Matrix4x4f axismation // = RotationMatrix (kXaxis, -kPiOver2) // * RotationMatrix (kZaxis, kPiOver2); // Matrix4x4f axisRotation = RotationMatrix (kXaxis, -kPiOver2); //Matrix4x4f final = camera * axisRotation; Matrix4x4f final = camera; //glMultMatrixf (final._m); // Setup scene lighting setupLight ( 0.0f, 20.0f, 100.0f ); // Enable/disable texture mapping (fixed pipeline) if ( bTextured ) glEnable ( GL_TEXTURE_2D ); else glDisable ( GL_TEXTURE_2D ); // glFrontFace( GL_CCW ); glCullFace ( GL_FRONT ); // Enable/disable backface culling // if (bCullFace) // glEnable (GL_CULL_FACE); // else // glDisable (GL_CULL_FACE); // Setup polygon mode and shade model glPolygonMode ( GL_FRONT_AND_BACK, bWireframe ? GL_LINE : GL_FILL ); glShadeModel ( bSmooth ? GL_SMOOTH : GL_FLAT ); // Draw object //666object->setModelViewMatrix (final); //666object->setRenderFlags (renderFlags); //666object->animate (bAnimate ? timer.deltaTime () : 0.0f); //666object->computeBoundingBox (); //666object->prepare (false); //666object->render (); auto meshItBegin = bmodel->GetBeginVisibleMeshIterator(); auto meshItEnd = bmodel->GetEndVisibleMeshIterator(); while ( meshItBegin != meshItEnd ) { //mesh->applyPose(); renderMesh ( final, **meshItBegin ); meshItBegin++; } drawSkeleton ( final,bmodel->GetCurrentPose()->skeleton ); if ( bBounds ) drawObb ( final, bmodel->GetBoundingBox() ); //drawRay(final, rayList); //666drawObb (object->boundingBox ()); if ( bDrawVoxels ) { VoxelizerTool voxelizer; std::vector<BBox> voxelList; BBox size; int meshIndex = 0; auto meshItBegin = bmodel->GetBeginVisibleMeshIterator(); auto meshItEnd = bmodel->GetEndVisibleMeshIterator(); while ( meshItBegin != meshItEnd ) { voxelizer.VoxelixeExt ( **meshItBegin, meshIndex, 0.25f, size, true, voxelList ); meshIndex++; meshItBegin++; } for ( auto voxel: voxelList ) { drawObb ( final,voxel ); } bDrawVoxels=!bDrawVoxels; } glDisable ( GL_LIGHTING ); glDisable ( GL_TEXTURE_2D ); drawAxes ( final ); } // ------------------------------------------------------------------------- // draw2D // // Render the 2D part of the scene. // ------------------------------------------------------------------------- static void draw2D () { if ( !font ) return; begin2D (); // Reset texture matrix glActiveTexture ( GL_TEXTURE0 ); glMatrixMode ( GL_TEXTURE ); glLoadIdentity (); glMatrixMode ( GL_MODELVIEW ); glPushAttrib ( GL_ENABLE_BIT | GL_POLYGON_BIT ); glDisable ( GL_DEPTH_TEST ); glDisable ( GL_LIGHTING ); glPolygonMode ( GL_FRONT_AND_BACK, GL_FILL ); // White text glColor4f ( 1.0f, 1.0f, 1.0f, 1.0f ); // Print frame rate int the bottom-left corner font->printText ( 10, 10, "%i fps", fps ); // Print current animation //666font->printText (10, 10 + font->getLineSkip (), //666object->currAnimName ().c_str ()); glPopAttrib (); end2D (); } void ToggleFullscreen ( SDL_Window* Window ) { Uint32 FullscreenFlag = SDL_WINDOW_FULLSCREEN; bool IsFullscreen = SDL_GetWindowFlags ( Window ) & FullscreenFlag; SDL_SetWindowFullscreen ( Window, IsFullscreen ? 0 : FullscreenFlag ); SDL_ShowCursor ( IsFullscreen ); } void snapshot ( Camera& cam, AnimatedModel& model ) { rayList.clear(); vector<Image*> imageList; ImageUtils::Snapshot ( cam, model, rayList, 0, imageList); PPMReader writer; int index = 0; for(Image* img : imageList) { std::stringstream ss; ss << "output" << index << ".ppm"; writer.writePGM5 ( ss.str(),*img ); index++; delete img; } } // ------------------------------------------------------------------------- // display // // Render the main scene to the screen. // ------------------------------------------------------------------------- static void gameCycle () { gameLogic (); draw3D (); draw2D (); SDL_GL_SwapWindow ( surface ); } // ------------------------------------------------------------------------- // handleKeyPress // // SDL Keyboard handling. // ------------------------------------------------------------------------- static void handleKeyPress ( SDL_Keysym *keysym ) { switch ( keysym->sym ) { case SDLK_RIGHT: case SDLK_LEFT: { // Find the current animation in the list //666vector<string>::iterator itor //666 = find (animations.begin (), animations.end (), //666 object->currAnimName ()); // Peek next or previous animation name if ( keysym->sym == SDLK_RIGHT ) { //666++itor; } else { //666if (itor == animations.begin ()) //666 itor = animations.end (); //666--itor; } //666if (itor == animations.end ()) //666 itor = animations.begin (); // Set the new animation to play //666object->setAnim (*itor); break; } case SDLK_SPACE: bAnimate = !bAnimate; break; case SDLK_b: bBounds = !bBounds; break; case SDLK_c: bCullFace = !bCullFace; break; case SDLK_e: snapshot ( *cam, *bmodel ); break; case SDLK_j: renderFlags ^= Md5Object::kDrawJointLabels; break; case SDLK_k: renderFlags ^= Md5Object::kDrawSkeleton; break; case SDLK_l: bLight = !bLight; break; case SDLK_n: bDrawNormals = !bDrawNormals; break; case SDLK_p: { bParallax = !bParallax; if ( bParallax && shader ) cout << "Parallax Mapping: on" << endl; else cout << "Parallax Mapping: off" << endl; if ( shader == NULL ) break; shader->use (); if ( GLEW_VERSION_2_0 ) glUniform1i ( glGetUniformLocation ( shader->handle (), "parallaxMapping" ), bParallax ); else glUniform1iARB ( glGetUniformLocationARB ( shader->handle (), "parallaxMapping" ), bParallax ); shader->unuse (); break; } case SDLK_s: bSmooth = !bSmooth; break; case SDLK_t: bTextured = !bTextured; break; case SDLK_v: bDrawVoxels = !bDrawVoxels; break; case SDLK_w: bWireframe = !bWireframe; break; case SDLK_F1: ToggleFullscreen ( surface ); break; case SDLK_F3: // R_normal renderPath = R_normal; announceRenderPath ( renderPath ); break; case SDLK_F4: // R_ARBfp_diffuse if ( vp_bump && fp_diffuse ) { renderPath = R_ARBfp_diffuse; vp = vp_bump; fp = fp_diffuse; } announceRenderPath ( renderPath ); break; case SDLK_F5: // R_ARBfp_diffuse_specular if ( vp_bump && fp_diffuse_specular ) { renderPath = R_ARBfp_diffuse_specular; vp = vp_bump; fp = fp_diffuse_specular; } announceRenderPath ( renderPath ); break; case SDLK_F6: // R_ARBfp_ds_parallax if ( vp_bump_parallax && fp_ds_parallax ) { renderPath = R_ARBfp_ds_parallax; vp = vp_bump_parallax; fp = fp_ds_parallax; } announceRenderPath ( renderPath ); break; case SDLK_F7: // R_shader if ( shader ) renderPath = R_shader; announceRenderPath ( renderPath ); break; case SDLK_ESCAPE: shutdownApp ( 0 ); break; default: break; } } // ------------------------------------------------------------------------- // MouseMove // // SDL Mouse Input Control. // ------------------------------------------------------------------------- static void mouseMove ( int x, int y ) { static int x_pos = 0; static int y_pos = 0; SDL_Keymod km = SDL_GetModState (); // Right button if ( SDL_GetMouseState ( NULL, NULL ) & SDL_BUTTON_RMASK ) { // /*Zoom*/ eye._z += ( x - x_pos ) * 0.1f; } // Left button else if ( SDL_GetMouseState ( NULL, NULL ) & SDL_BUTTON_LMASK ) { if ( ( km & KMOD_RSHIFT ) || ( km & KMOD_LSHIFT ) ) { // Translation eye._x -= ( x - x_pos ) * 0.1f; eye._y += ( y - y_pos ) * 0.1f; } else { // Rotation rot._x += ( y - y_pos ); rot._y += ( x - x_pos ); } } x_pos = x; y_pos = y; } // ------------------------------------------------------------------------- // main // // Application main entry point. // ------------------------------------------------------------------------- int runViewer ( AnimatedModel* model ) { cout << "Built release " << __DATE__ << " at " << __TIME__ << endl; int videoFlags; bool isActive = true; // Initialize SDL if ( SDL_Init ( SDL_INIT_VIDEO ) < 0 ) { cerr << "Video initialization failed: " << SDL_GetError () << endl; shutdownApp ( -1 ); } atexit ( SDL_Quit ); // Initialize flags to pass to SDL_SetVideoMode videoFlags = SDL_WINDOW_OPENGL; // Uses OpenGL videoFlags |= SDL_GL_DOUBLEBUFFER; // Uses double buffering videoFlags |= SDL_WINDOW_RESIZABLE; // App. window is resizable // Check if we can allocate memory in hardware for the window videoFlags |= SDL_SWSURFACE; videoFlags |= SDL_WINDOW_FULLSCREEN_DESKTOP; // Check if hardware blit is possible // videoFlags |= SDL_HWACCEL; // Set double buffering for OpenGL SDL_GL_SetAttribute ( SDL_GL_DOUBLEBUFFER, 1 ); // Initialize video mode surface = SDL_CreateWindow ( "MD5 Viewer", 0, 0, windowWidth, windowHeight, videoFlags ); if ( !surface ) { cerr << "Video mode set failed: " << SDL_GetError () << endl; shutdownApp ( -1 ); } SDL_SetWindowFullscreen ( surface, 0 ); SDL_GL_SetAttribute ( SDL_GL_CONTEXT_MAJOR_VERSION , 3 ) ; SDL_GL_SetAttribute ( SDL_GL_CONTEXT_MINOR_VERSION , 0 ) ; SDL_GLContext gi_glcontext = SDL_GL_CreateContext ( surface ); if ( gi_glcontext == NULL ) { std::cerr << "SDL Error(something about glcontext): " << SDL_GetError() << std::endl; } std::cout << glGetString ( GL_VERSION ) << std::endl; if ( SDL_GL_MakeCurrent ( surface, gi_glcontext ) < 0 ) { std::cerr << "SDL Error(something about glcontext): " << SDL_GetError() << std::endl; } // Initialize OpenGL initOpenGL (); // Initialize application initApplication ( model ); // Resize OpenGL window reshape ( windowWidth, windowHeight ); // Loop until the end while ( 1 ) { SDL_Event event; // Parse SDL event while ( SDL_PollEvent ( &event ) ) { switch ( event.type ) { case SDL_WINDOWEVENT_LEAVE: // Don't draw scene if the window has been minimized // isActive = !((event.active.gain == 0) && // (event.active.state & SDL_APPACTIVE)); break; case SDL_WINDOWEVENT_RESIZED: // Resize Window SDL_SetWindowSize ( surface,event.window.data1, event.window.data2 ); reshape ( event.window.data1, event.window.data2 ); initOpenGL (); break; case SDL_KEYDOWN: handleKeyPress ( &event.key.keysym ); break; case SDL_MOUSEMOTION: mouseMove ( event.button.x, event.button.y ); break; case SDL_QUIT: shutdownApp ( 0 ); break; default: break; } } // Update the timer timer.update (); // Draw scene if window is active if ( isActive ) gameCycle (); } // We should never go here return 0; }
28.361018
161
0.531682
[ "mesh", "render", "object", "vector", "model", "3d" ]
b1835bfda5e9d14b166dc8b0ee6fd7dea92885d9
2,247
hpp
C++
src/a2d/physics/polygon_collider.hpp
ayles/A2D
278b8e40be74c0f0257b1062f009995462f983fa
[ "MIT" ]
17
2018-11-12T11:13:23.000Z
2021-11-13T12:38:21.000Z
src/a2d/physics/polygon_collider.hpp
ayles/A2D
278b8e40be74c0f0257b1062f009995462f983fa
[ "MIT" ]
1
2018-11-12T11:16:01.000Z
2018-11-12T11:17:50.000Z
src/a2d/physics/polygon_collider.hpp
ayles/A2D
278b8e40be74c0f0257b1062f009995462f983fa
[ "MIT" ]
3
2019-05-28T12:44:09.000Z
2021-11-13T12:38:23.000Z
// // Created by selya on 26.01.2019. // #ifndef A2D_POLYGON_COLLIDER_HPP #define A2D_POLYGON_COLLIDER_HPP #include <a2d/physics/physics_collider.hpp> #include <vector> namespace a2d { class PolygonCollider : public PhysicsCollider { #if PHYSICS_DEBUG_DRAW intrusive_ptr<Line> line; #endif std::vector<Vector2f> vertices; b2PolygonShape shape; public: void SetAsBox(float half_x, float half_y) { vertices.clear(); vertices.emplace_back(-half_x, -half_y); vertices.emplace_back(half_x, -half_y); vertices.emplace_back(half_x, half_y); vertices.emplace_back(-half_x, half_y); Reattach(); } void SetAsBox(const Vector2f &half_size) { SetAsBox(half_size.x, half_size.y); } void Set(const std::vector<Vector2f> &vertices) { this->vertices = vertices; Reattach(); } const std::vector<Vector2f> &GetVertices() const { return vertices; } protected: b2Shape *CalculateShape(b2Body *body) override { if (vertices.size() < 3) return nullptr; #if PHYSICS_DEBUG_DRAW if (!line) { auto o = Object2D::Create(); o->Attach(GetObject2D()); line = o->AddComponent<Line>(); } line->vertices.clear(); for (auto &v : vertices) { line->vertices.emplace_back(v, Vector4f(0, 1, 0, 1)); } line->vertices.emplace_back(line->vertices[0]); line->Load(); #endif float s = Physics::GetWorldScale(); auto rb = (Rigidbody *)body->GetUserData(); float cos = std::cos(-rb->GetObject2D()->GetRotation()); float sin = std::sin(-rb->GetObject2D()->GetRotation()); Vector2f pos = -rb->GetObject2D()->GetPosition(); std::vector<b2Vec2> vs; vs.reserve(vertices.size()); for (auto vertex : vertices) { auto v = GetObject2D()->GetTransformMatrix().Transform(vertex.x, vertex.y, 0, 1); vs.emplace_back( s * (v.x * cos - v.y * sin + pos.x), s * (v.x * sin + v.y * cos + pos.y)); } shape.Set(&vs[0], vs.size()); return &shape; } }; } //namespace a2d #endif //A2D_POLYGON_COLLIDER_HPP
27.402439
93
0.58834
[ "shape", "vector", "transform" ]
b18bea145bc3480214f0577955b760157ec1327a
8,606
cpp
C++
Demo/src/game/states/GameState.cpp
aaron-foster-wallace/MasterThesisIntersectionVisualizer
08b802a3b3fe3761c9ba7ac5a650cbca89887df8
[ "MIT" ]
1
2021-01-31T05:29:47.000Z
2021-01-31T05:29:47.000Z
Demo/src/game/states/GameState.cpp
aaron-foster-wallace/MasterThesisIntersectionVisualizer
08b802a3b3fe3761c9ba7ac5a650cbca89887df8
[ "MIT" ]
null
null
null
Demo/src/game/states/GameState.cpp
aaron-foster-wallace/MasterThesisIntersectionVisualizer
08b802a3b3fe3761c9ba7ac5a650cbca89887df8
[ "MIT" ]
1
2021-01-31T05:27:36.000Z
2021-01-31T05:27:36.000Z
#include "GameState.h" #include "imgui.h" #include "Sail/debug/Instrumentor.h" #include "Sail/graphics/material/PBRMaterial.h" GameState::GameState(StateStack& stack) : State(stack) , m_cam(90.f, 1280.f / 720.f, 0.1f, 5000.f) , m_camController(&m_cam) { SAIL_PROFILE_FUNCTION(); // Get the Application instance m_app = Application::getInstance(); // Textures needs to be loaded before they can be used // TODO: automatically load textures when needed so the following can be removed Application::getInstance()->getResourceManager().loadTexture("sponza/textures/spnza_bricks_a_ddn.tga"); Application::getInstance()->getResourceManager().loadTexture("sponza/textures/spnza_bricks_a_diff.tga"); Application::getInstance()->getResourceManager().loadTexture("sponza/textures/spnza_bricks_a_spec.tga"); // Set up camera with controllers m_cam.setPosition(glm::vec3(1.6f, 4.7f, 7.4f)); m_camController.lookAt(glm::vec3(0.f)); // Disable culling for testing purposes m_app->getAPI()->setFaceCulling(GraphicsAPI::NO_CULLING); auto* shader = &m_app->getResourceManager().getShaderSet<PBRMaterialShader>(); // Create/load models auto cubeModel = ModelFactory::CubeModel::Create(glm::vec3(0.5f), shader); auto planeModel = ModelFactory::PlaneModel::Create(glm::vec2(50.f), shader, glm::vec2(30.0f)); auto fbxModel = m_app->getResourceManager().getModel("sphere.fbx", shader); // Create entities // Lights { // Add a directional light auto e = Entity::Create("Directional light"); glm::vec3 color(1.0f, 1.0f, 1.0f); glm::vec3 direction(0.4f, -0.2f, 1.0f); direction = glm::normalize(direction); e->addComponent<DirectionalLightComponent>(color, direction); m_scene.addEntity(e); // Add four point lights e = Entity::Create("Point light 1"); auto& pl = e->addComponent<PointLightComponent>(); pl->setColor(glm::vec3(Utils::rnd(), Utils::rnd(), Utils::rnd())); pl->setPosition(glm::vec3(-4.0f, 0.1f, -4.0f)); m_scene.addEntity(e); e = Entity::Create("Point light 2"); pl = e->addComponent<PointLightComponent>(); pl->setColor(glm::vec3(Utils::rnd(), Utils::rnd(), Utils::rnd())); pl->setPosition(glm::vec3(-4.0f, 0.1f, 4.0f)); m_scene.addEntity(e); e = Entity::Create("Point light 3"); pl = e->addComponent<PointLightComponent>(); pl->setColor(glm::vec3(Utils::rnd(), Utils::rnd(), Utils::rnd())); pl->setPosition(glm::vec3(4.0f, 0.1f, 4.0f)); m_scene.addEntity(e); e = Entity::Create("Point light 4"); pl = e->addComponent<PointLightComponent>(); pl->setColor(glm::vec3(Utils::rnd(), Utils::rnd(), Utils::rnd())); pl->setPosition(glm::vec3(4.0f, 0.1f, -4.0f)); m_scene.addEntity(e); } { auto e = Entity::Create("Static cube"); e->addComponent<ModelComponent>(cubeModel); e->addComponent<TransformComponent>(glm::vec3(-4.f, 1.f, -2.f)); auto mat = e->addComponent<MaterialComponent<PBRMaterial>>(); mat->get()->setColor(glm::vec4(0.2f, 0.8f, 0.4f, 1.0f)); m_scene.addEntity(e); } { auto e = Entity::Create("Floor"); e->addComponent<ModelComponent>(planeModel); e->addComponent<TransformComponent>(glm::vec3(0.f, 0.f, 0.f)); auto mat = e->addComponent<MaterialComponent<PBRMaterial>>(); mat->get()->setAlbedoTexture("sponza/textures/spnza_bricks_a_diff.tga"); mat->get()->setNormalTexture("sponza/textures/spnza_bricks_a_ddn.tga"); //mat->get()->setSpecularTexture("sponza/textures/spnza_bricks_a_spec.tga"); m_scene.addEntity(e); } Entity::SPtr parentEntity; { parentEntity = Entity::Create("Clingy cube"); parentEntity->addComponent<ModelComponent>(cubeModel); parentEntity->addComponent<TransformComponent>(glm::vec3(-1.2f, 1.f, -1.f), glm::vec3(0.f, 0.f, 1.07f)); parentEntity->addComponent<MaterialComponent<PBRMaterial>>(); m_scene.addEntity(parentEntity); } { // Add some cubes which are connected through parenting m_texturedCubeEntity = Entity::Create("Textured parent cube"); m_texturedCubeEntity->addComponent<ModelComponent>(fbxModel); m_texturedCubeEntity->addComponent<TransformComponent>(glm::vec3(-1.f, 2.f, 0.f), m_texturedCubeEntity->getComponent<TransformComponent>().get()); auto mat = m_texturedCubeEntity->addComponent<MaterialComponent<PBRMaterial>>(); mat->get()->setAlbedoTexture("sponza/textures/spnza_bricks_a_diff.tga"); mat->get()->setNormalTexture("sponza/textures/spnza_bricks_a_ddn.tga"); //mat->get()->setSpecularTexture("sponza/textures/spnza_bricks_a_spec.tga"); m_texturedCubeEntity->setName("MovingCube"); m_scene.addEntity(m_texturedCubeEntity); parentEntity->getComponent<TransformComponent>()->setParent(m_texturedCubeEntity->getComponent<TransformComponent>().get()); } { auto e = Entity::Create("CubeRoot"); e->addComponent<ModelComponent>(cubeModel); e->addComponent<TransformComponent>(glm::vec3(10.f, 0.f, 10.f)); e->addComponent<MaterialComponent<PBRMaterial>>(); m_scene.addEntity(e); m_transformTestEntities.push_back(e); } { auto e = Entity::Create("CubeChild"); e->addComponent<ModelComponent>(cubeModel); e->addComponent<TransformComponent>(glm::vec3(1.f, 1.f, 1.f), m_transformTestEntities[0]->getComponent<TransformComponent>().get()); e->addComponent<MaterialComponent<PBRMaterial>>(); m_scene.addEntity(e); m_transformTestEntities.push_back(e); } { auto e = Entity::Create("CubeChildChild"); e->addComponent<ModelComponent>(cubeModel); e->addComponent<TransformComponent>(glm::vec3(1.f, 1.f, 1.f), m_transformTestEntities[1]->getComponent<TransformComponent>().get()); e->addComponent<MaterialComponent<PBRMaterial>>(); m_scene.addEntity(e); m_transformTestEntities.push_back(e); } // Random cube maze const unsigned int mazeStart = 5; const unsigned int mazeSize = 20; const float wallSize = 1.1f; for (unsigned int x = 0; x < mazeSize; x++) { for (unsigned int y = 0; y < mazeSize; y++) { /*if (Utils::rnd() > 0.5f) continue;*/ auto e = Entity::Create(); e->addComponent<ModelComponent>(cubeModel); e->addComponent<TransformComponent>(glm::vec3(x * wallSize + mazeStart, 0.5f, y * wallSize + mazeStart)); e->addComponent<MaterialComponent<PBRMaterial>>(); m_scene.addEntity(e); } } } GameState::~GameState() { } // Process input for the state bool GameState::processInput(float dt) { SAIL_PROFILE_FUNCTION(); #ifdef _DEBUG if (Input::WasKeyJustPressed(SAIL_KEY_1)) { Logger::Log("Setting parent"); m_transformTestEntities[2]->getComponent<TransformComponent>()->setParent(m_transformTestEntities[1]->getComponent<TransformComponent>().get()); } if (Input::WasKeyJustPressed(SAIL_KEY_2)) { Logger::Log("Removing parent"); m_transformTestEntities[2]->getComponent<TransformComponent>()->removeParent(); } #endif // Update the camera controller from input devices m_camController.update(dt); // Reload shaders if (Input::WasKeyJustPressed(SAIL_KEY_R)) { m_app->getResourceManager().reloadShader<PBRMaterialShader>(); } return true; } bool GameState::update(float dt) { SAIL_PROFILE_FUNCTION(); std::wstring fpsStr = std::to_wstring(m_app->getFPS()); m_app->getWindow()->setWindowTitle("Sail | Game Engine Demo | " + Application::getPlatformName() + " | FPS: " + std::to_string(m_app->getFPS())); static float counter = 0.0f; static float size = 1; static float change = 0.4f; counter += dt * 2; if (m_texturedCubeEntity) { // Move the cubes around m_texturedCubeEntity->getComponent<TransformComponent>()->setTranslation(glm::vec3(glm::sin(counter), 1.f, glm::cos(counter))); m_texturedCubeEntity->getComponent<TransformComponent>()->setRotations(glm::vec3(glm::sin(counter), counter, glm::cos(counter))); // Move the three parented cubes with identical translation, rotations and scale to show how parenting affects transforms for (Entity::SPtr item : m_transformTestEntities) { item->getComponent<TransformComponent>()->rotateAroundY(dt * 1.0f); item->getComponent<TransformComponent>()->setScale(size); item->getComponent<TransformComponent>()->setTranslation(size * 3, 1.0f, size * 3); } m_transformTestEntities[0]->getComponent<TransformComponent>()->translate(2.0f, 0.0f, 2.0f); size += change * dt; if (size > 1.2f || size < 0.7f) change *= -1.0f; } return true; } // Renders the state bool GameState::render(float dt) { SAIL_PROFILE_FUNCTION(); // Clear back buffer m_app->getAPI()->clear({0.1f, 0.2f, 0.3f, 1.0f}); // Draw the scene m_scene.draw(m_cam); return true; } bool GameState::renderImgui(float dt) { SAIL_PROFILE_FUNCTION(); // The ImGui window is rendered when activated on F10 ImGui::ShowDemoWindow(); return false; }
36.159664
148
0.717987
[ "render" ]
b18e5b731807436172943fe179e0893366d126cd
14,382
cc
C++
Analyses/src/StoppingTarget00_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
null
null
null
Analyses/src/StoppingTarget00_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
1
2019-11-22T14:45:51.000Z
2019-11-22T14:50:03.000Z
Analyses/src/StoppingTarget00_module.cc
bonventre/Offline
77db9d6368f27ab9401c690c2c2a4257ade6c231
[ "Apache-2.0" ]
2
2019-10-14T17:46:58.000Z
2020-03-30T21:05:15.000Z
// // A first look at muons stopping in stopping targets. // // $Id: StoppingTarget00_module.cc,v 1.14 2013/10/21 21:15:46 kutschke Exp $ // $Author: kutschke $ // $Date: 2013/10/21 21:15:46 $ // // Original author Rob Kutschke. // // C++ includes. #include <iostream> #include <iomanip> #include <fstream> #include <string> // Framework includes. #include "art/Framework/Core/EDAnalyzer.h" #include "art/Framework/Core/ModuleMacros.h" #include "messagefacility/MessageLogger/MessageLogger.h" #include "art/Framework/Principal/Event.h" #include "art/Framework/Principal/Handle.h" #include "art/Framework/Principal/Run.h" #include "art_root_io/TFileService.h" // Mu2e includes. #include "DataProducts/inc/PDGCode.hh" #include "MCDataProducts/inc/StepPointMCCollection.hh" #include "MCDataProducts/inc/SimParticleCollection.hh" #include "MCDataProducts/inc/PhysicalVolumeInfoCollection.hh" #include "GeometryService/inc/VirtualDetector.hh" #include "GeometryService/inc/GeomHandle.hh" #include "GeometryService/inc/DetectorSystem.hh" #include "StoppingTargetGeom/inc/StoppingTarget.hh" // Root includes. #include "TH1F.h" #include "TNtuple.h" using namespace std; namespace mu2e { class StoppingTarget00 : public art::EDAnalyzer { public: explicit StoppingTarget00(fhicl::ParameterSet const& pset); virtual ~StoppingTarget00() { } void beginJob(); void endJob(); void beginRun(art::Run const& ); void analyze( art::Event const& ); private: // Label of the module that created the data products. std::string _g4ModuleLabel; // Instance names of data products std::string _targetStepPoints; std::string _vdStepPoints; // Name of file to hold get the points and times that muons stop. std::string _muonPointFile; // Offset to put coordinates in a special reference frame: // - (x,y) origin on DS axis; z origin at Mu2e origin. CLHEP::Hep3Vector _dsOffset; TH1F* _hStopFoil; TH1F* _hnSimPart; TH1F* _hnSimPartZoom; TH1F* _hzInFoil; TNtuple* _nt; map<int,int> _nonMuon; map<int,int> _particleCounts; map<int,int> _vdGlobalCounts; map<ProcessCode,int> _stopCodes; map<PhysicalVolumeInfo const*,int> _startVols; map<PhysicalVolumeInfo const*,int> _stoppingVols; }; StoppingTarget00::StoppingTarget00(fhicl::ParameterSet const& pset): art::EDAnalyzer(pset), _g4ModuleLabel(pset.get<std::string>("g4ModuleLabel")) ,_targetStepPoints(pset.get<string>("targetStepPoints","stoppingtarget")) ,_vdStepPoints(pset.get<string>("vdStepPoints","virtualdetector")) ,_muonPointFile(pset.get<string>("muonPointFile","")) ,_dsOffset() ,_hStopFoil(0) ,_hnSimPart(0) ,_hnSimPartZoom(0) ,_hzInFoil(0) ,_nt(0) ,_nonMuon() ,_particleCounts() ,_stopCodes() {} void StoppingTarget00::beginJob(){ // Get access to the TFile service. art::ServiceHandle<art::TFileService> tfs; _hStopFoil = tfs->make<TH1F>( "hStopFoil", "Number of Stopping Foil;(mm)", 34, 0., 17. ); _hnSimPart = tfs->make<TH1F>( "hnSimPart", "Number of SimParticles", 200, 0., 1000. ); _hnSimPartZoom = tfs->make<TH1F>( "hnSimPartZoom", "Number of SimParticles", 50, 0., 50. ); _hzInFoil = tfs->make<TH1F>( "hzInFoil", "z Position Within Foil(units of halfThickness", 100, -1., 1. ); _nt = tfs->make<TNtuple>( "nt", "Muon ntuple", "cx:cy:cz:cp:cpt:cpz:cke:ct:sx:sy:sz:sp:spt:st:stau:scode:edep:sfoil:nfoils:x9:y9:pt9:pz9:x10:y10:pt10:pz10"); } void StoppingTarget00::beginRun(art::Run const& run ){ // Information about the detector coordinate system. GeomHandle<DetectorSystem> det; _dsOffset = det->toMu2e( CLHEP::Hep3Vector(0.,0.,0.) ); /* // Handle to information about G4 physical volumes. art::Handle<PhysicalVolumeInfoCollection> volsHandle; run.getByLabel(_g4ModuleLabel, volsHandle); PhysicalVolumeInfoCollection const& vols(*volsHandle); for ( size_t i = 0; i<vols.size(); ++i){ cout << "Info: " << i << " " << vols.at(i) << endl; } */ } void StoppingTarget00::analyze(art::Event const& event ) { // Information about the detector coordinate system. //GeomHandle<DetectorSystem> det; GeomHandle<StoppingTarget> target; // Simulated particles. art::Handle<SimParticleCollection> simsHandle; event.getByLabel(_g4ModuleLabel,simsHandle); SimParticleCollection const& sims(*simsHandle); if ( sims.size() == 0 ){ mf::LogInfo("G4") << "No particles in SimParticleCollection. Hope that's OK."; return; } // Steps in the stopping target art::Handle<StepPointMCCollection> stHitsHandle; event.getByLabel(_g4ModuleLabel,_targetStepPoints,stHitsHandle); StepPointMCCollection const& sthits(*stHitsHandle); // Steps in the virtual detectors. art::Handle<StepPointMCCollection> vdhitsHandle; event.getByLabel(_g4ModuleLabel,_vdStepPoints,vdhitsHandle); StepPointMCCollection const& vdhits(*vdhitsHandle); // Information about G4 physical volumes. art::Handle<PhysicalVolumeInfoCollection> volsHandle; event.getRun().getByLabel(_g4ModuleLabel, volsHandle); PhysicalVolumeInfoCollection const& vols(*volsHandle); _hnSimPart->Fill(sims.size()); _hnSimPartZoom->Fill(sims.size()); // In my files the muon is always simparticle 1. SimParticleCollection::key_type muIndex(1); SimParticle const& mu = sims.at(muIndex); if ( mu.pdgId() != PDGCode::mu_minus ) { ++_nonMuon[mu.pdgId()]; return; } PhysicalVolumeInfo const& startVol = vols.at(mu.startVolumeIndex()); PhysicalVolumeInfo const& endVol = vols.at(mu.endVolumeIndex()); ++_stopCodes[mu.stoppingCode()]; ++_stoppingVols[&endVol]; ++_startVols[&startVol]; int stopFoilId(-1); if ( endVol.name().compare(0,11,"TargetFoil_") == 0 ) { stopFoilId = endVol.copyNo(); _hStopFoil->Fill(stopFoilId); } // Sum of energy loss in the foils. double sumEDep(0.); set<int> hitFoils; int nFoils(0); for ( StepPointMCCollection:: const_iterator i=sthits.begin(); i !=sthits.end(); ++i ){ StepPointMC const& hit = *i; if ( hit.trackId() != muIndex ) continue; sumEDep += hit.eDep(); hitFoils.insert(hit.volumeId()); ++nFoils; } /* if ( !hitFoils.empty() && nFoils > (int(hitFoils.size())+1) ){ cout << "Mark: " << event.id() << " " << endVol << " " << nFoils << " " << hitFoils.size() << " " << muIndex << endl; int nn(0); set<int> dummy; for ( StepPointMCCollection:: const_iterator i=sthits.begin(); i !=sthits.end(); ++i ){ StepPointMC const& hit = *i; if ( hit.trackId() != muIndex ) continue; dummy.insert(hit.volumeId()); cout << "Hit Foil: " << nn++ << " " << hit.trackId() << " " << hit.volumeId() << " | " << dummy.size() << " | " << hit.time() << " " << hit.properTime() << " " << hit.stepLength() << " " << hit.totalEDep() << " | " << hit.momentum() << " | " << hit.momentum().mag() << endl; } } */ struct ntInfo{ float cx; // Position, momentum, kinetic energy and time at start float cy; float cz; float cp; float cpt; float cpz; float cke; float ct; float ex; // Same at end float ey; float ez; float ep; float ept; float et; float tau; // Proper time at end float ecode; // Reason why it stoppd float eDep; float sFoil; float nFoils; float x9; // Position at virtual detector 9 float y9; float pt9; float pz9; float x10; // Position at virtual detector 10 float y10; float pt10; float pz10; ntInfo(): cx(0), cy(0), cz(0), cp(0), cke(0), ct(0), ex(0), ey(0), ez(0), ep(0), et(0), tau(0), ecode(0), eDep(0), nFoils(0), x9(0), y9(0), x10(0), y10(0){} }xx; set<int> vdCounts; int nvd(0); for ( StepPointMCCollection:: const_iterator i=vdhits.begin(); i !=vdhits.end(); ++i ){ StepPointMC const& hit = *i; if ( hit.trackId() != muIndex ) continue; // Hits are in the Mu2e coordinate system. Report these in detector system. if ( hit.volumeId() == 9 ){ CLHEP::Hep3Vector pos = hit.position() - _dsOffset; xx.x9 = pos.x(); xx.y9 = pos.y(); xx.pt9 = hit.momentum().perp(); xx.pz9 = hit.momentum().z(); } if ( hit.volumeId() == 10 ){ CLHEP::Hep3Vector pos = hit.position() - _dsOffset; xx.x10 = pos.x(); xx.y10 = pos.y(); xx.pt10 = hit.momentum().perp(); xx.pz10 = hit.momentum().z(); } /* cout << "VD: " << hit.volumeId() << " " << hit.position().z() << " " << hit.momentum().mag() << " " << hit.eDep()*1000. << endl; */ vdCounts.insert(hit.volumeId()); ++_vdGlobalCounts[hit.volumeId()]; ++nvd; } /* double deTest = mu.startMomentum().e()-mu.endMomentum().e() - sumEDep; cout << "Energetics: " << mu.startMomentum().e() << " " << mu.endMomentum().e() << " " << mu.startMomentum().e()-mu.endMomentum().e() << " " << sumEDep << " " << deTest << " " << mu.stoppingCode() << " " << endVol << " | " << nFoils << " " << hitFoils.size() << " | " << vdCounts.size() << " " << nvd << endl; */ // Transform point from Mu2e frame to detector frame. CLHEP::Hep3Vector startPos = mu.startPosition() - _dsOffset; CLHEP::Hep3Vector endPos = mu.endPosition() - _dsOffset; xx.cx = startPos.x(); xx.cy = startPos.y(); xx.cz = startPos.z(); xx.cp = mu.startMomentum().vect().mag(); xx.cpt = mu.startMomentum().vect().perp(); xx.cpz = mu.startMomentum().vect().z(); xx.cke = mu.startMomentum().e()-mu.startMomentum().mag(); xx.ct = mu.startGlobalTime(); xx.ex = endPos.x(); xx.ey = endPos.y(); xx.ez = endPos.z(); xx.ep = mu.endMomentum().vect().mag(); xx.ept = mu.endMomentum().vect().perp(); xx.et = mu.endGlobalTime(); xx.tau = mu.endProperTime(); xx.ecode = mu.stoppingCode(); xx.eDep = sumEDep; xx.sFoil = stopFoilId; xx.nFoils = hitFoils.size(); _nt->Fill( &xx.cx); if ( stopFoilId > -1 && mu.stoppingCode() == ProcessCode::muMinusCaptureAtRest ){ TargetFoil const& foil = target->foil(stopFoilId); double dz = endPos.z() - foil.centerInDetectorSystem().z(); _hzInFoil->Fill( dz/foil.halfThickness() ); /* cout << "Test: " << endPos.z() << " " << foil.center().z() << " " << dz << " " << dz/foil.halfThickness() << endl; */ if ( !_muonPointFile.empty() ) { static ofstream fout(_muonPointFile.c_str()); static bool first(true); if ( first ){ fout << "begin data" << endl; first = false; } // Print out in Mu2e coordinates fout << setprecision(8) << endPos.x() + _dsOffset.x() << " " << endPos.y() + _dsOffset.y() << " " << endPos.z() + _dsOffset.z() << " " << mu.endGlobalTime() << endl; } } // Table of reasons why particles stopped. for ( SimParticleCollection::const_iterator i=sims.begin(); i!=sims.end(); ++i ){ SimParticle const& sim = i->second; ++_particleCounts[sim.pdgId()]; } } // end of ::analyze. void StoppingTarget00::endJob(){ cout << "\nNumber of distinct tracked particles: " << _particleCounts.size() << endl; int n(0); for ( map<int,int>::const_iterator i=_particleCounts.begin(); i != _particleCounts.end(); ++i ){ cout << " Tracked Particle: " << n++ << " " << i->first << ": " << i->second << endl; } cout << "\nNumber of times first particle was not a muon: " << _nonMuon.size() << endl; n=0; for ( map<int,int>::const_iterator i=_nonMuon.begin(); i != _nonMuon.end(); ++i ){ cout << " nonMuon: " << n++ << " " << i->first << ": " << i->second << endl; } cout << "\nNumber of unique stopping Codes: " << _stopCodes.size() << endl; n=0; for ( map<ProcessCode,int>::const_iterator i=_stopCodes.begin(); i != _stopCodes.end(); ++i ){ cout << " Stopping Code: " << n++ << " " << i->first << ": " << i->second << endl; } cout << "\nNumber of different stopping volumes: " << _stoppingVols.size() << endl; n=0; for ( map<PhysicalVolumeInfo const*,int>::const_iterator i=_stoppingVols.begin(); i != _stoppingVols.end(); ++i ){ cout << " Stopping Volume: " << n++ << " " << *i->first << ": " << i->second << endl; } cout << "\nNumber of different start volumes: " << _startVols.size() << endl; n=0; for ( map<PhysicalVolumeInfo const*,int>::const_iterator i=_startVols.begin(); i != _startVols.end(); ++i ){ cout << " Start Volume: " << n++ << " " << *i->first << ": " << i->second << endl; } cout << "\nNumber of different virtual detectors: " << _vdGlobalCounts.size() << endl; n=0; for ( map<int,int>::const_iterator i=_vdGlobalCounts.begin(); i != _vdGlobalCounts.end(); ++i ){ cout << " Virtual Detector: " << n++ << " " << i->first << ": " << i->second << endl; } } } using mu2e::StoppingTarget00; DEFINE_ART_MODULE(StoppingTarget00);
30.341772
142
0.558963
[ "transform" ]
b18f2efbdd6f167f745423744fb83bec6bffe331
6,201
hpp
C++
include/eagine/msgbus/service/ping_pong.hpp
matus-chochlik/eagine-msgbus
1672be9db227e918b17792e01d8a45ac58954181
[ "BSL-1.0" ]
1
2021-07-18T10:17:10.000Z
2021-07-18T10:17:10.000Z
include/eagine/msgbus/service/ping_pong.hpp
matus-chochlik/eagine-msgbus
1672be9db227e918b17792e01d8a45ac58954181
[ "BSL-1.0" ]
null
null
null
include/eagine/msgbus/service/ping_pong.hpp
matus-chochlik/eagine-msgbus
1672be9db227e918b17792e01d8a45ac58954181
[ "BSL-1.0" ]
1
2021-06-25T07:15:10.000Z
2021-06-25T07:15:10.000Z
/// @file /// /// Copyright Matus Chochlik. /// Distributed under the Boost Software License, Version 1.0. /// See accompanying file LICENSE_1_0.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt /// #ifndef EAGINE_MSGBUS_SERVICE_PING_PONG_HPP #define EAGINE_MSGBUS_SERVICE_PING_PONG_HPP #include "../serialize.hpp" #include "../signal.hpp" #include "../subscriber.hpp" #include <eagine/bool_aggregate.hpp> #include <eagine/maybe_unused.hpp> #include <chrono> #include <vector> namespace eagine::msgbus { //------------------------------------------------------------------------------ /// @brief Service responding to pings from the pinger counterpart. /// @ingroup msgbus /// @see service_composition /// @see pinger template <typename Base = subscriber> class pingable : public Base { using This = pingable; public: /// @brief Decides if a ping request should be responded. virtual auto respond_to_ping( const identifier_t pinger_id, const message_sequence_t, const verification_bits) noexcept -> bool { EAGINE_MAYBE_UNUSED(pinger_id); return true; } protected: using Base::Base; void add_methods() noexcept { Base::add_methods(); Base::add_method( this, EAGINE_MSG_MAP(eagiMsgBus, ping, This, _handle_ping)); } private: auto _handle_ping( const message_context&, const stored_message& message) noexcept -> bool { if(respond_to_ping( message.source_id, message.sequence_no, this->verify_bits(message))) { this->bus_node().respond_to(message, EAGINE_MSGBUS_ID(pong), {}); } return true; } }; //------------------------------------------------------------------------------ /// @brief Service sending to pings from the pingable counterparts. /// @ingroup msgbus /// @see service_composition /// @see pingable template <typename Base = subscriber> class pinger : public Base , protected std::chrono::steady_clock { using This = pinger; std::vector<std::tuple<identifier_t, message_sequence_t, timeout>> _pending{}; public: /// @brief Returns the ping message type id. static constexpr auto ping_msg_id() noexcept { return EAGINE_MSGBUS_ID(ping); } /// @brief Broadcasts a query searching for pingable message bus nodes. void query_pingables() noexcept { this->bus_node().query_subscribers_of(ping_msg_id()); } /// @brief Sends a pings request and tracks it for the specified maximum time. /// @see ping_responded /// @see ping_timeouted /// @see has_pending_pings void ping( const identifier_t pingable_id, const std::chrono::milliseconds max_time) noexcept { message_view message{}; auto msg_id{EAGINE_MSGBUS_ID(ping)}; message.set_target_id(pingable_id); message.set_priority(message_priority::low); this->bus_node().set_next_sequence_id(msg_id, message); this->bus_node().post(msg_id, message); _pending.emplace_back(message.target_id, message.sequence_no, max_time); } /// @brief Sends a pings request and tracks it for a default time period. /// @see ping_responded /// @see ping_timeouted /// @see has_pending_pings void ping(const identifier_t pingable_id) noexcept { ping( pingable_id, adjusted_duration( std::chrono::milliseconds{5000}, memory_access_rate::low)); } auto update() noexcept -> work_done { some_true something_done{}; something_done(Base::update()); something_done( std::erase_if(_pending, [this](auto& entry) { auto& [pingable_id, sequence_no, ping_time] = entry; if(ping_time.is_expired()) { ping_timeouted( pingable_id, sequence_no, std::chrono::duration_cast<std::chrono::microseconds>( ping_time.elapsed_time())); return true; } return false; }) > 0); return something_done; } /// @brief Indicates if there are yet unresponded pending ping requests. /// @see ping_responded /// @see ping_timeouted auto has_pending_pings() const noexcept -> bool { return !_pending.empty(); } /// @brief Triggered on receipt of ping response. /// @see ping /// @see ping_timeouted /// @see has_pending_pings signal<void( const identifier_t pingable_id, const message_sequence_t sequence_no, const std::chrono::microseconds age, const verification_bits) noexcept> ping_responded; /// @brief Triggered on timeout of ping response. /// @see ping /// @see ping_responded /// @see has_pending_pings signal<void( const identifier_t pingable_id, const message_sequence_t sequence_no, const std::chrono::microseconds age) noexcept> ping_timeouted; protected: using Base::Base; void add_methods() noexcept { Base::add_methods(); Base::add_method( this, EAGINE_MSG_MAP(eagiMsgBus, pong, This, _handle_pong)); } private: auto _handle_pong( const message_context&, const stored_message& message) noexcept -> bool { std::erase_if(_pending, [this, &message](auto& entry) { auto& [pingable_id, sequence_no, ping_time] = entry; const bool is_response = (message.source_id == pingable_id) && (message.sequence_no == sequence_no); if(is_response) { ping_responded( message.source_id, message.sequence_no, std::chrono::duration_cast<std::chrono::microseconds>( ping_time.elapsed_time()), this->verify_bits(message)); return true; } return false; }); return true; } }; //------------------------------------------------------------------------------ } // namespace eagine::msgbus #endif // EAGINE_MSGBUS_SERVICE_PING_PONG_HPP
31.318182
82
0.603774
[ "vector" ]
b1926c4616845f515e43d69404998835aacf1106
2,884
cpp
C++
common/ffsreport.cpp
ISpillMyDrink/UEFITool
a4430e24e05154c1e9c9023f4ab487acd7310ca4
[ "BSD-2-Clause" ]
null
null
null
common/ffsreport.cpp
ISpillMyDrink/UEFITool
a4430e24e05154c1e9c9023f4ab487acd7310ca4
[ "BSD-2-Clause" ]
null
null
null
common/ffsreport.cpp
ISpillMyDrink/UEFITool
a4430e24e05154c1e9c9023f4ab487acd7310ca4
[ "BSD-2-Clause" ]
null
null
null
/* fssreport.cpp Copyright (c) 2016, Nikolaj Schlej. All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. */ #include "ffsreport.h" #include "ffs.h" #include "utility.h" #include "uinttypes.h" std::vector<UString> FfsReport::generate() { std::vector<UString> report; // Check model pointer if (!model) { report.push_back(usprintf("%s: invalid model pointer provided", __FUNCTION__)); return report; } // Check root index to be valid UModelIndex root = model->index(0,0); if (!root.isValid()) { report.push_back(usprintf("%s: model root index is invalid", __FUNCTION__)); return report; } // Generate report recursive report.push_back(UString(" Type | Subtype | Base | Size | CRC32 | Name ")); USTATUS result = generateRecursive(report, root); if (result) { report.push_back(usprintf("%s: generateRecursive returned ", __FUNCTION__) + errorCodeToUString(result)); } return report; } USTATUS FfsReport::generateRecursive(std::vector<UString> & report, const UModelIndex & index, const UINT32 level) { if (!index.isValid()) return U_SUCCESS; // Nothing to report for invalid index // Calculate item CRC32 UByteArray data = model->header(index) + model->body(index) + model->tail(index); UINT32 crc = (UINT32)crc32(0, (const UINT8*)data.constData(), (uInt)data.size()); // Information on current item UString text = model->text(index); UString offset = "| N/A "; if ((!model->compressed(index)) || (index.parent().isValid() && !model->compressed(index.parent()))) { offset = usprintf("| %08X ", model->base(index)); } report.push_back( UString(" ") + itemTypeToUString(model->type(index)).leftJustified(16) + UString("| ") + itemSubtypeToUString(model->type(index), model->subtype(index)).leftJustified(22) + offset + usprintf("| %08" PRIXQ " | %08X | ", data.size(), crc) + urepeated('-', level) + UString(" ") + model->name(index) + (text.isEmpty() ? UString() : UString(" | ") + text) ); // Information on child items for (int i = 0; i < model->rowCount(index); i++) { #if ((QT_VERSION_MAJOR == 5) && (QT_VERSION_MINOR < 6)) || (QT_VERSION_MAJOR < 5) generateRecursive(report, index.child(i,0), level + 1); #else generateRecursive(report, index.model()->index(i,0,index), level + 1); #endif } return U_SUCCESS; }
35.170732
122
0.643551
[ "vector", "model" ]
b19d0361a90f4c2f4bce40398f96fcc3e32b5fb3
4,067
cpp
C++
src/coherence/util/Binary.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-01T21:38:30.000Z
2021-11-03T01:35:11.000Z
src/coherence/util/Binary.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
1
2020-07-24T17:29:22.000Z
2020-07-24T18:29:04.000Z
src/coherence/util/Binary.cpp
chpatel3/coherence-cpp-extend-client
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
[ "UPL-1.0", "Apache-2.0" ]
6
2020-07-10T18:40:58.000Z
2022-02-18T01:23:40.000Z
/* * Copyright (c) 2000, 2020, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * http://oss.oracle.com/licenses/upl. */ #include "coherence/util/Binary.hpp" #include <algorithm> COH_OPEN_NAMESPACE2(coherence,util) using coherence::lang::TypedBarrenClass; COH_REGISTER_CLASS(TypedBarrenClass<Binary>::create()); // ----- constructors ------------------------------------------------------- Binary::Binary() : super(getEmptyOctetArray(), 0, 0) { } Binary::Binary(Array<octet_t>::View vab, size32_t of, size32_t cb) : super() { size32_t vabLength = vab->length; if (vab->isImmutable()) { if (0 == of && (cb == vabLength || cb == npos)) { // safe and cheap to reference the original array initialize(f_vab, vab); cb = vabLength; } else { // Create a sub array. All Binary objects should have m_of = 0 // and m_cb = vab->length vab = vab->subArray(of, cb == npos ? cb: of + cb); initialize(f_vab, vab); cb = vab->length; // set to sub array length in case npos was passed in } } else { // not immutable, so clone if (cb == npos ? of > vabLength : of + cb > vabLength) { COH_THROW_STREAM(IndexOutOfBoundsException, "of=" << of << ", cb=" << cb << ", vab->length=" << vabLength); } if (cb == npos) { cb = vabLength - of; } initialize(f_vab, cast<Array<octet_t>::View>(Array<octet_t>::copy(vab, of, Array<octet_t>::create(cb)))); } m_cb = cb; } Binary::Binary(BinaryWriteBuffer::View vBuf) : super() { Array<octet_t>::View vab = vBuf->getInternalOctetArray(); size32_t cbData = vBuf->length(); size32_t cbTotal = vab->length; size32_t cbWaste = cbTotal - cbData; if (cbWaste == 0) { initialize(f_vab, vab); } // tolerate up to 12.5% waste else if (cbWaste <= std::max((size32_t) 16, (cbTotal >> 3))) { // Create a sub array. All Binary objects should have m_of = 0 // and m_cb = vab->length initialize(f_vab, vab->subArray(0, cbData)); } else { initialize(f_vab, cast<Array<octet_t>::View>(Array<octet_t>::copy(vab, 0, Array<octet_t>::create(cbData), 0, cbData))); } m_cb = cbData; } Binary::Binary(const Binary& that) : super(that.f_vab, that.m_of, that.m_cb) { } // ----- Binary interface ----------------------------------------------- int32_t Binary::calculateNaturalPartition(int32_t cPartitions) const { int64_t lHash = ((int64_t) hashCode()) & 0xFFFFFFFFL; return cPartitions == 0 ? (int32_t) lHash : (int32_t) (lHash % (int64_t) cPartitions); } // ----- Object interface --------------------------------------------------- size32_t Binary::hashCode() const { return f_vab->hashCode(); } bool Binary::equals(Object::View v) const { if (this == v) { return true; } Binary::View vThat = cast<Binary::View>(v, false); if (NULL == vThat) { return false; } return f_vab->equals(vThat->f_vab); } bool Binary::isImmutable() const { return true; } TypedHandle<const String> Binary::toString() const { return COH_TO_STRING("Binary(length=" << length() << ')'); } // ----- internal methods --------------------------------------------------- void Binary::updateLength(size32_t /*cb*/) { COH_THROW (UnsupportedOperationException::create()); } ReadBuffer::View Binary::instantiateReadBuffer(size32_t of, size32_t cb) const { if (m_of == of && cb == m_cb) { return this; } return Binary::create(f_vab, of, cb); } COH_CLOSE_NAMESPACE2
25.578616
90
0.519793
[ "object" ]
b19d212ea49b9483dc0d12098796e229dfe85613
302
hpp
C++
Algorithms&DataStructures_Utils/Linux/gpp/IGenerator.hpp
przet/CppProgramming
042aff253988b74db47659d36806912ce84dd8bc
[ "MIT" ]
null
null
null
Algorithms&DataStructures_Utils/Linux/gpp/IGenerator.hpp
przet/CppProgramming
042aff253988b74db47659d36806912ce84dd8bc
[ "MIT" ]
null
null
null
Algorithms&DataStructures_Utils/Linux/gpp/IGenerator.hpp
przet/CppProgramming
042aff253988b74db47659d36806912ce84dd8bc
[ "MIT" ]
null
null
null
#ifndef __IGenerator__H #define __IGenerator__H #include <vector> template <template <typename... > class Container, typename ContainerDataType> struct IGenerator { virtual const std::vector<std::pair<Container<ContainerDataType>,int>>& generateData() = 0; virtual ~IGenerator(){} }; #endif
23.230769
96
0.748344
[ "vector" ]
b1a2adafa989cb4df52a199c9399e8907525d6d3
32,681
cpp
C++
test/unit/linalg/matrixop_real_cpu_test.cpp
yingwaili/DCA
31c298a1831f90daf62ea8bb6b683229513d7c08
[ "BSD-3-Clause" ]
null
null
null
test/unit/linalg/matrixop_real_cpu_test.cpp
yingwaili/DCA
31c298a1831f90daf62ea8bb6b683229513d7c08
[ "BSD-3-Clause" ]
null
null
null
test/unit/linalg/matrixop_real_cpu_test.cpp
yingwaili/DCA
31c298a1831f90daf62ea8bb6b683229513d7c08
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Raffaele Solca' (rasolca@itp.phys.ethz.ch) // // This file tests the matrix operations with the Matrix<CPU> class with real element type. #include "dca/linalg/matrixop.hpp" #include <complex> #include <limits> #include <stdexcept> #include <string> #include <utility> #include "gtest/gtest.h" #include "dca/linalg/lapack/use_device.hpp" #include "dca/linalg/matrix.hpp" #include "dca/linalg/blas/blas3.hpp" #include "cpu_test_util.hpp" #include "matrixop_reference.hpp" template <typename ScalarType> class MatrixopRealCPUTest : public ::testing::Test { public: static const ScalarType epsilon; }; template <typename ScalarType> const ScalarType MatrixopRealCPUTest<ScalarType>::epsilon = std::numeric_limits<ScalarType>::epsilon(); typedef ::testing::Types<float, double> FloatingPointTypes; TYPED_TEST_CASE(MatrixopRealCPUTest, FloatingPointTypes); TYPED_TEST(MatrixopRealCPUTest, Gemv) { using ScalarType = TypeParam; auto val_a = [](int i, int j) { return 3 * i - 2 * j; }; auto val_x = [](int i) { return 4 * i; }; auto val_y = [](int i) { return 2 * i * i; }; int m = 2; int n = 3; std::pair<int, int> size_c(2, 3); char trans_opts[] = {'N', 'T', 'C'}; for (auto transa : trans_opts) { std::pair<int, int> size_a; if (transa == 'N') { size_a.first = m; size_a.second = n; } else { size_a.first = n; size_a.second = m; } { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); dca::linalg::Vector<ScalarType, dca::linalg::CPU> x(n); dca::linalg::Vector<ScalarType, dca::linalg::CPU> y(m); testing::setMatrixElements(a, val_a); testing::setVectorElements(x, val_x); testing::setVectorElements(y, val_y); dca::linalg::Vector<ScalarType, dca::linalg::CPU> yref(y); testing::refGemv(transa, ScalarType(1), a, x, ScalarType(0), yref); dca::linalg::matrixop::gemv(transa, a, x, y); for (int i = 0; i < y.size(); ++i) { EXPECT_NEAR(yref[i], y[i], 500 * this->epsilon); } } { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); dca::linalg::Vector<ScalarType, dca::linalg::CPU> x(n); dca::linalg::Vector<ScalarType, dca::linalg::CPU> y(m); testing::setMatrixElements(a, val_a); testing::setVectorElements(x, val_x); testing::setVectorElements(y, val_y); dca::linalg::Vector<ScalarType, dca::linalg::CPU> yref(y); ScalarType alpha = .57; ScalarType beta = -.712; testing::refGemv(transa, alpha, a, x, beta, yref); dca::linalg::matrixop::gemv(transa, alpha, a, x, beta, y); for (int i = 0; i < y.size(); ++i) { EXPECT_NEAR(yref[i], y[i], 500 * this->epsilon); } } } } TYPED_TEST(MatrixopRealCPUTest, Gemm) { using ScalarType = TypeParam; auto val_a = [](int i, int j) { return 3 * i - 2 * j; }; auto val_b = [](int i, int j) { return 4 * i - 3 * j; }; auto val_c = [](int i, int j) { return 2 * i - j; }; { std::pair<int, int> size_a(2, 3); std::pair<int, int> size_b(3, 4); std::pair<int, int> size_c(2, 4); { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size_b); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(size_c); testing::setMatrixElements(a, val_a); testing::setMatrixElements(b, val_b); testing::setMatrixElements(c, val_c); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> cref(c); testing::refGemm('N', 'N', ScalarType(1), a, b, ScalarType(0), cref); dca::linalg::matrixop::gemm(a, b, c); for (int j = 0; j < c.nrCols(); ++j) for (int i = 0; i < c.nrRows(); ++i) { EXPECT_NEAR(cref(i, j), c(i, j), 500 * this->epsilon); } } { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size_b); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(size_c); testing::setMatrixElements(a, val_a); testing::setMatrixElements(b, val_b); testing::setMatrixElements(c, val_c); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> cref(c); ScalarType alpha = .57; ScalarType beta = -.712; testing::refGemm('N', 'N', alpha, a, b, beta, cref); dca::linalg::matrixop::gemm(alpha, a, b, beta, c); for (int j = 0; j < c.nrCols(); ++j) for (int i = 0; i < c.nrRows(); ++i) { EXPECT_NEAR(cref(i, j), c(i, j), 500 * this->epsilon); } } } { int m = 2; int k = 4; int n = 3; std::pair<int, int> size_c(2, 3); char trans_opts[] = {'N', 'T', 'C'}; for (auto transa : trans_opts) { std::pair<int, int> size_a; if (transa == 'N') { size_a.first = m; size_a.second = k; } else { size_a.first = k; size_a.second = m; } for (auto transb : trans_opts) { std::pair<int, int> size_b; if (transb == 'N') { size_b.first = k; size_b.second = n; } else { size_b.first = n; size_b.second = k; } { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size_b); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(size_c); testing::setMatrixElements(a, val_a); testing::setMatrixElements(b, val_b); testing::setMatrixElements(c, val_c); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> cref(c); testing::refGemm(transa, transb, ScalarType(1), a, b, ScalarType(0), cref); dca::linalg::matrixop::gemm(transa, transb, a, b, c); for (int j = 0; j < c.nrCols(); ++j) for (int i = 0; i < c.nrRows(); ++i) { EXPECT_NEAR(cref(i, j), c(i, j), 500 * this->epsilon); } } { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size_b); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(size_c); testing::setMatrixElements(a, val_a); testing::setMatrixElements(b, val_b); testing::setMatrixElements(c, val_c); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> cref(c); ScalarType alpha = .57; ScalarType beta = -.712; testing::refGemm(transa, transb, alpha, a, b, beta, cref); dca::linalg::matrixop::gemm(transa, transb, alpha, a, b, beta, c); for (int j = 0; j < c.nrCols(); ++j) for (int i = 0; i < c.nrRows(); ++i) { EXPECT_NEAR(cref(i, j), c(i, j), 500 * this->epsilon); } } } } } } TYPED_TEST(MatrixopRealCPUTest, MultiplyDiagonal) { using ScalarType = TypeParam; std::pair<int, int> size_a(3, 5); auto val_a = [](int i, int j) { return 3 * i - 2 * j; }; auto val_d = [](int i) { return 1 - i; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); testing::setMatrixElements(a, val_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size_a); { dca::linalg::Vector<ScalarType, dca::linalg::CPU> d(a.nrRows()); testing::setVectorElements(d, val_d); dca::linalg::matrixop::multiplyDiagonalLeft(d, a, b); for (int j = 0; j < a.nrCols(); ++j) for (int i = 0; i < a.nrRows(); ++i) { EXPECT_NEAR(d[i] * a(i, j), b(i, j), 10 * this->epsilon); } } { dca::linalg::Vector<ScalarType, dca::linalg::CPU> d(a.nrCols()); testing::setVectorElements(d, val_d); dca::linalg::matrixop::multiplyDiagonalRight(a, d, b); for (int j = 0; j < a.nrCols(); ++j) for (int i = 0; i < a.nrRows(); ++i) { EXPECT_NEAR(d[j] * a(i, j), b(i, j), 10 * this->epsilon); } } } TYPED_TEST(MatrixopRealCPUTest, Trsm) { using ScalarType = TypeParam; auto val_a = [](int i, int j) { return 1 + 3 * i - 2 * j; }; auto val_b = [](int i, int j) { return 4 * i - 3 * j; }; std::pair<int, int> size_a(3, 3); std::pair<int, int> size_b(3, 4); char uplo_opts[] = {'U', 'L'}; char diag_opts[] = {'U', 'N'}; for (auto uplo : uplo_opts) { for (auto diag : diag_opts) { int m = size_b.first; int n = size_b.second; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size_b); testing::setMatrixElements(a, val_a); testing::setMatrixElements(b, val_b); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b_orig(b); dca::linalg::matrixop::trsm(uplo, diag, a, b); dca::linalg::blas::trmm("L", &uplo, "N", &diag, m, n, ScalarType(1), a.ptr(), a.leadingDimension(), b.ptr(), b.leadingDimension()); for (int j = 0; j < b.nrCols(); ++j) for (int i = 0; i < b.nrRows(); ++i) { EXPECT_NEAR(b_orig(i, j), b(i, j), 500 * this->epsilon); } } } } TYPED_TEST(MatrixopRealCPUTest, Eigensolver) { using ScalarType = TypeParam; int size = 2; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat(size); mat(0, 0) = 2.; mat(0, 1) = 0.; mat(1, 0) = 1.; mat(1, 1) = 1.; dca::linalg::Vector<ScalarType, dca::linalg::CPU> wr; dca::linalg::Vector<ScalarType, dca::linalg::CPU> wi; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> vl; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> vr; dca::linalg::matrixop::eigensolver('V', 'V', mat, wr, wi, vl, vr); EXPECT_EQ(wr.size(), size); EXPECT_EQ(wi.size(), size); EXPECT_EQ(vl.size(), std::make_pair(size, size)); EXPECT_EQ(vr.size(), std::make_pair(size, size)); EXPECT_NEAR(1., wr[0], 100 * this->epsilon); EXPECT_NEAR(0., wi[0], 100 * this->epsilon); EXPECT_NEAR(-1, vl(0, 0) / vl(1, 0), 100 * this->epsilon); EXPECT_NEAR(0., vr(0, 0), 100 * this->epsilon); EXPECT_NEAR(1., vr(1, 0), 100 * this->epsilon); EXPECT_NEAR(2., wr[1], 100 * this->epsilon); EXPECT_NEAR(0., wi[1], 100 * this->epsilon); EXPECT_NEAR(1., vl(0, 1), 100 * this->epsilon); EXPECT_NEAR(0., vl(1, 1), 100 * this->epsilon); EXPECT_NEAR(1., vr(0, 1) / vr(1, 1), 100 * this->epsilon); } TYPED_TEST(MatrixopRealCPUTest, EigensolverSymmetric) { using ScalarType = TypeParam; int size = 2; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat(size); mat(0, 0) = 2.; mat(0, 1) = 1.; mat(1, 0) = 1.; mat(1, 1) = 2.; dca::linalg::Vector<ScalarType, dca::linalg::CPU> w; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> v; dca::linalg::matrixop::eigensolverSymmetric('V', 'U', mat, w, v); EXPECT_EQ(w.size(), size); EXPECT_EQ(v.size(), std::make_pair(size, size)); EXPECT_NEAR(1., w[0], 100 * this->epsilon); EXPECT_NEAR(-1., v(0, 0) / v(1, 0), 100 * this->epsilon); EXPECT_NEAR(3., w[1], 100 * this->epsilon); EXPECT_NEAR(1., v(0, 1) / v(1, 1), 100 * this->epsilon); dca::linalg::matrixop::eigensolverHermitian('V', 'U', mat, w, v); EXPECT_EQ(w.size(), size); EXPECT_EQ(v.size(), std::make_pair(size, size)); EXPECT_NEAR(1., w[0], 100 * this->epsilon); EXPECT_NEAR(-1., v(0, 0) / v(1, 0), 100 * this->epsilon); EXPECT_NEAR(3., w[1], 100 * this->epsilon); EXPECT_NEAR(1., v(0, 1) / v(1, 1), 100 * this->epsilon); } TYPED_TEST(MatrixopRealCPUTest, Laset) { using ScalarType = TypeParam; std::pair<int, int> size(3, 5); ScalarType diag = 3.4; ScalarType offdiag = -1.4; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size); dca::linalg::lapack::UseDevice<dca::linalg::CPU>::laset(size.first, size.second, offdiag, diag, a.ptr(), a.leadingDimension(), -1, -1); for (int j = 0; j < a.nrCols(); ++j) for (int i = 0; i < a.nrRows(); ++i) { if (i == j) EXPECT_EQ(diag, a(i, j)); else EXPECT_EQ(offdiag, a(i, j)); } } TYPED_TEST(MatrixopRealCPUTest, InsertRowCol) { using ScalarType = TypeParam; std::pair<int, int> size2(31, 31); auto val = [](int i, int j) { return 10 * i + j; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat(size2); testing::setMatrixElements(mat, val); for (int ii : {0, 1, size2.first}) { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat_test(mat); dca::linalg::matrixop::insertRow(mat_test, ii); for (int j = 0; j < mat.nrCols(); ++j) { for (int i = 0; i < ii; ++i) EXPECT_EQ(mat(i, j), mat_test(i, j)); for (int i = ii; i < mat.nrRows(); ++i) EXPECT_EQ(mat(i, j), mat_test(i + 1, j)); EXPECT_EQ(0, mat_test(ii, j)); } } for (int jj : {0, 1, size2.second}) { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat_test(mat); dca::linalg::matrixop::insertCol(mat_test, jj); for (int i = 0; i < mat.nrRows(); ++i) { for (int j = 0; j < jj; ++j) EXPECT_EQ(mat(i, j), mat_test(i, j)); for (int j = jj; j < mat.nrCols(); ++j) EXPECT_EQ(mat(i, j), mat_test(i, j + 1)); EXPECT_EQ(0, mat_test(i, jj)); } } } TYPED_TEST(MatrixopRealCPUTest, Inverse) { using ScalarType = TypeParam; int size = 6; auto val = [](int i, int j) { return 10 * i + j * j / (i + 1); }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat(size); testing::setMatrixElements(mat, val); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> invmat(mat); dca::linalg::matrixop::inverse(invmat); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> res(size); dca::linalg::matrixop::gemm(mat, invmat, res); for (int j = 0; j < mat.nrCols(); ++j) { for (int i = 0; i < mat.nrRows(); ++i) { if (i == j) EXPECT_NEAR(1, res(i, j), 2000 * this->epsilon); else EXPECT_NEAR(0, res(i, j), 2000 * this->epsilon); } } } TYPED_TEST(MatrixopRealCPUTest, PseudoInverse) { using ScalarType = TypeParam; auto val = [](int i, int j) { return 10 * i + j * j / (i + 1); }; auto val0 = [](int, int) { return 0; }; { std::pair<int, int> size(2, 3); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat(size); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> invmat; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> res(std::min(size.first, size.second)); testing::setMatrixElements(mat, val); dca::linalg::matrixop::pseudoInverse(mat, invmat); if (size.first <= size.second) dca::linalg::matrixop::gemm(mat, invmat, res); else dca::linalg::matrixop::gemm(invmat, mat, res); for (int j = 0; j < res.nrCols(); ++j) { for (int i = 0; i < res.nrRows(); ++i) { if (i == j) EXPECT_NEAR(1, res(i, j), 1000 * this->epsilon); else EXPECT_NEAR(0, res(i, j), 1000 * this->epsilon); } } // Check eigenvalue exclusion below threshold. testing::setMatrixElements(mat, val0); mat(0, 0) = 20.; mat(1, 1) = .1; dca::linalg::matrixop::pseudoInverse(mat, invmat, 1e-6); if (size.first <= size.second) dca::linalg::matrixop::gemm(mat, invmat, res); else dca::linalg::matrixop::gemm(invmat, mat, res); for (int j = 0; j < res.nrCols(); ++j) { for (int i = 0; i < res.nrRows(); ++i) { if (i == j) EXPECT_NEAR(1, res(i, j), 100 * this->epsilon); else EXPECT_NEAR(0, res(i, j), 100 * this->epsilon); } } // Check eigenvalue exclusion above threshold. dca::linalg::matrixop::pseudoInverse(mat, invmat, 3.9e-4); if (size.first <= size.second) dca::linalg::matrixop::gemm(mat, invmat, res); else dca::linalg::matrixop::gemm(invmat, mat, res); for (int j = 0; j < res.nrCols(); ++j) { for (int i = 0; i < res.nrRows(); ++i) { if (i == j && i == 0) EXPECT_NEAR(1, res(i, j), 100 * this->epsilon); else EXPECT_NEAR(0, res(i, j), 100 * this->epsilon); } } } } TYPED_TEST(MatrixopRealCPUTest, RemoveRowCol) { using ScalarType = TypeParam; std::pair<int, int> size2(3, 4); auto val = [](int i, int j) { return 10 * i + j; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat(size2); testing::setMatrixElements(mat, val); for (int ii : {0, 1, size2.first - 1}) { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat_test(mat); dca::linalg::matrixop::removeRow(mat_test, ii); EXPECT_EQ(mat.nrRows() - 1, mat_test.nrRows()); EXPECT_EQ(mat.nrCols(), mat_test.nrCols()); for (int j = 0; j < mat.nrCols(); ++j) { for (int i = 0; i < ii; ++i) EXPECT_EQ(mat(i, j), mat_test(i, j)); for (int i = ii + 1; i < mat.nrRows(); ++i) EXPECT_EQ(mat(i, j), mat_test(i - 1, j)); } } for (int jj : {0, 1, size2.second - 1}) { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat_test(mat); dca::linalg::matrixop::removeCol(mat_test, jj); EXPECT_EQ(mat.nrRows(), mat_test.nrRows()); EXPECT_EQ(mat.nrCols() - 1, mat_test.nrCols()); for (int i = 0; i < mat.nrRows(); ++i) { for (int j = 0; j < jj; ++j) EXPECT_EQ(mat(i, j), mat_test(i, j)); for (int j = jj + 1; j < mat.nrCols(); ++j) EXPECT_EQ(mat(i, j), mat_test(i, j - 1)); } } for (int ii : {0, 1, size2.first - 1}) { for (int jj : {0, 1, size2.second - 1}) { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat_test(mat); dca::linalg::matrixop::removeRowAndCol(mat_test, ii, jj); EXPECT_EQ(mat.nrRows() - 1, mat_test.nrRows()); EXPECT_EQ(mat.nrCols() - 1, mat_test.nrCols()); for (int j = 0; j < jj; ++j) { for (int i = 0; i < ii; ++i) EXPECT_EQ(mat(i, j), mat_test(i, j)); for (int i = ii + 1; i < mat.nrRows(); ++i) EXPECT_EQ(mat(i, j), mat_test(i - 1, j)); } for (int j = jj + 1; j < mat.nrCols(); ++j) { for (int i = 0; i < ii; ++i) EXPECT_EQ(mat(i, j), mat_test(i, j - 1)); for (int i = ii + 1; i < mat.nrRows(); ++i) EXPECT_EQ(mat(i, j), mat_test(i - 1, j - 1)); } } } for (int ii : {0, 1, std::min(size2.first, size2.second) - 1}) { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> mat_test(mat); dca::linalg::matrixop::removeRowAndCol(mat_test, ii); EXPECT_EQ(mat.nrRows() - 1, mat_test.nrRows()); EXPECT_EQ(mat.nrCols() - 1, mat_test.nrCols()); for (int j = 0; j < ii; ++j) { for (int i = 0; i < ii; ++i) EXPECT_EQ(mat(i, j), mat_test(i, j)); for (int i = ii + 1; i < mat.nrRows(); ++i) EXPECT_EQ(mat(i, j), mat_test(i - 1, j)); } for (int j = ii + 1; j < mat.nrCols(); ++j) { for (int i = 0; i < ii; ++i) EXPECT_EQ(mat(i, j), mat_test(i, j - 1)); for (int i = ii + 1; i < mat.nrRows(); ++i) EXPECT_EQ(mat(i, j), mat_test(i - 1, j - 1)); } } } TEST(MatrixopRealCPUTest, RemoveCols) { dca::linalg::Matrix<int, dca::linalg::CPU> mat(4); dca::linalg::Matrix<int, dca::linalg::CPU> mat_test(std::make_pair(4, 2)); auto fill_func = [](int i, int j) { return 10 * i + j; }; testing::setMatrixElements(mat, fill_func); mat_test(0, 0) = 0, mat_test(0, 1) = 3; mat_test(1, 0) = 10, mat_test(1, 1) = 13; mat_test(2, 0) = 20, mat_test(2, 1) = 23; mat_test(3, 0) = 30, mat_test(3, 1) = 33; dca::linalg::matrixop::removeCols(mat, 1, 2); EXPECT_EQ(mat, mat_test); dca::linalg::Matrix<int, dca::linalg::CPU> null_matrix(0); dca::linalg::matrixop::removeCols(mat, 0, mat.nrCols() - 1); EXPECT_EQ(null_matrix, mat); } TEST(MatrixopRealCPUTest, RemoveRows) { dca::linalg::Matrix<int, dca::linalg::CPU> mat(4); dca::linalg::Matrix<int, dca::linalg::CPU> mat_test(std::make_pair(2, 4)); auto fill_func = [](int i, int j) { return 10 * i + j; }; testing::setMatrixElements(mat, fill_func); mat_test(0, 0) = 0, mat_test(0, 1) = 1, mat_test(0, 2) = 2, mat_test(0, 3) = 3; mat_test(1, 0) = 30, mat_test(1, 1) = 31, mat_test(1, 2) = 32, mat_test(1, 3) = 33; dca::linalg::matrixop::removeRows(mat, 1, 2); EXPECT_EQ(mat, mat_test); dca::linalg::Matrix<int, dca::linalg::CPU> null_matrix(0); dca::linalg::matrixop::removeRows(mat, 0, mat.nrRows() - 1); EXPECT_EQ(mat, null_matrix); } TEST(MatrixopRealCPUTest, RemoveRowsandColumns) { dca::linalg::Matrix<int, dca::linalg::CPU> mat(4); dca::linalg::Matrix<int, dca::linalg::CPU> mat_test(2); auto fill_func = [](int i, int j) { return 10 * i + j; }; testing::setMatrixElements(mat, fill_func); mat_test(0, 0) = 0, mat_test(0, 1) = 1; mat_test(1, 0) = 10, mat_test(1, 1) = 11; dca::linalg::matrixop::removeRowsAndCols(mat, 2, 3); EXPECT_EQ(mat, mat_test); } TYPED_TEST(MatrixopRealCPUTest, CopyRow) { using ScalarType = TypeParam; std::pair<int, int> size2_a(4, 3); std::pair<int, int> size2_b(6, 3); dca::linalg::Vector<int, dca::linalg::CPU> i_sources(3); i_sources[0] = 0; i_sources[1] = 2; i_sources[2] = 3; dca::linalg::Vector<int, dca::linalg::CPU> i_dests(4); i_dests[0] = 2; i_dests[1] = 5; i_dests[2] = 3; i_dests[3] = 4; auto val_a = [](int i, int j) { return 10 * i + j; }; auto val_b = [](int i, int j) { return 10 * i + j + 100; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size2_a); testing::setMatrixElements(a, val_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size2_b); testing::setMatrixElements(b, val_b); { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(b); for (int i = 0; i < i_sources.size(); ++i) dca::linalg::matrixop::copyRow(a, i_sources[i], c, i_dests[i]); for (int j = 0; j < a.nrCols(); ++j) { for (int i = 0; i < i_sources.size(); ++i) { EXPECT_EQ(a(i_sources[i], j), c(i_dests[i], j)); // set the checked elements to -1000 to simplify the check of the unchanged elements c(i_dests[i], j) = -1000; } for (int i = 0; i < b.nrRows(); ++i) if (c(i, j) != -1000) EXPECT_EQ(b(i, j), c(i, j)); } } { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(b); dca::linalg::matrixop::copyRows(a, i_sources, c, i_dests); for (int j = 0; j < a.nrCols(); ++j) { for (int i = 0; i < i_sources.size(); ++i) { EXPECT_EQ(a(i_sources[i], j), c(i_dests[i], j)); // set the checked elements to -1000 to simplify the check of the unchanged elements c(i_dests[i], j) = -1000; } for (int i = 0; i < b.nrRows(); ++i) if (c(i, j) != -1000) EXPECT_EQ(b(i, j), c(i, j)); } } } TYPED_TEST(MatrixopRealCPUTest, CopyCol) { using ScalarType = TypeParam; std::pair<int, int> size2_a(3, 4); std::pair<int, int> size2_b(3, 6); dca::linalg::Vector<int, dca::linalg::CPU> j_sources(3); j_sources[0] = 0; j_sources[1] = 2; j_sources[2] = 3; dca::linalg::Vector<int, dca::linalg::CPU> j_dests(4); j_dests[0] = 2; j_dests[1] = 5; j_dests[2] = 3; j_dests[3] = 4; auto val_a = [](int i, int j) { return 10 * i + j; }; auto val_b = [](int i, int j) { return 10 * i + j + 100; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size2_a); testing::setMatrixElements(a, val_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size2_b); testing::setMatrixElements(b, val_b); { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(b); for (int j = 0; j < j_sources.size(); ++j) dca::linalg::matrixop::copyCol(a, j_sources[j], c, j_dests[j]); for (int i = 0; i < a.nrRows(); ++i) { for (int j = 0; j < j_sources.size(); ++j) { EXPECT_EQ(a(i, j_sources[j]), c(i, j_dests[j])); // set the checked elements to -1000 to simplify the check of the unchanged elements c(i, j_dests[j]) = -1000; } for (int j = 0; j < b.nrCols(); ++j) if (c(i, j) != -1000) EXPECT_EQ(b(i, j), c(i, j)); } } { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(b); dca::linalg::matrixop::copyCols(a, j_sources, c, j_dests); for (int i = 0; i < a.nrRows(); ++i) { for (int j = 0; j < j_sources.size(); ++j) { EXPECT_EQ(a(i, j_sources[j]), c(i, j_dests[j])); // set the checked elements to -1000 to simplify the check of the unchanged elements c(i, j_dests[j]) = -1000; } for (int j = 0; j < b.nrCols(); ++j) if (c(i, j) != -1000) EXPECT_EQ(b(i, j), c(i, j)); } } } TYPED_TEST(MatrixopRealCPUTest, ScaleRow) { using ScalarType = TypeParam; std::pair<int, int> size2_a(4, 3); dca::linalg::Vector<int, dca::linalg::CPU> is(3); is[0] = 0; is[1] = 2; is[2] = 3; dca::linalg::Vector<ScalarType, dca::linalg::CPU> vals(3); vals[0] = 3.4; vals[1] = -1.2; vals[2] = 7.7; auto val_a = [](int i, int j) { return 10 * i + j; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size2_a); testing::setMatrixElements(a, val_a); { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(a); for (int i = 0; i < is.size(); ++i) dca::linalg::matrixop::scaleRow(c, is[i], vals[i]); for (int j = 0; j < a.nrCols(); ++j) { for (int i = 0; i < is.size(); ++i) { EXPECT_NEAR(vals[i] * a(is[i], j), c(is[i], j), 10 * this->epsilon); // set the checked elements to -1000 to simplify the check of the unchanged elements c(is[i], j) = -1000; } for (int i = 0; i < a.nrRows(); ++i) if (c(i, j) != -1000) EXPECT_EQ(a(i, j), c(i, j)); } } { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(a); dca::linalg::matrixop::scaleRows(c, is, vals); for (int j = 0; j < a.nrCols(); ++j) { for (int i = 0; i < is.size(); ++i) { EXPECT_NEAR(vals[i] * a(is[i], j), c(is[i], j), 10 * this->epsilon); // set the checked elements to -1000 to simplify the check of the unchanged elements c(is[i], j) = -1000; } for (int i = 0; i < a.nrRows(); ++i) if (c(i, j) != -1000) EXPECT_EQ(a(i, j), c(i, j)); } } } TYPED_TEST(MatrixopRealCPUTest, ScaleCol) { using ScalarType = TypeParam; std::pair<int, int> size2_a(3, 4); dca::linalg::Vector<int, dca::linalg::CPU> js(3); js[0] = 0; js[1] = 2; js[2] = 3; dca::linalg::Vector<ScalarType, dca::linalg::CPU> vals(3); vals[0] = 3.4; vals[1] = -1.2; vals[2] = 7.7; auto val_a = [](int i, int j) { return 10 * i + j; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size2_a); testing::setMatrixElements(a, val_a); { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(a); for (int j = 0; j < js.size(); ++j) dca::linalg::matrixop::scaleCol(c, js[j], vals[j]); for (int i = 0; i < a.nrRows(); ++i) { for (int j = 0; j < js.size(); ++j) { EXPECT_NEAR(vals[j] * a(i, js[j]), c(i, js[j]), 10 * this->epsilon); // set the checked elements to -1000 to simplify the check of the unchanged elements c(i, js[j]) = -1000; } for (int j = 0; j < a.nrCols(); ++j) if (c(i, j) != -1000) EXPECT_EQ(a(i, j), c(i, j)); } } } TYPED_TEST(MatrixopRealCPUTest, SwapRow) { using ScalarType = TypeParam; std::pair<int, int> size2_a(4, 3); auto val_a = [](int i, int j) { return 10 * i + j; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size2_a); testing::setMatrixElements(a, val_a); for (int i_1 : {0, 2, 3}) { for (int i_2 : {1, 3}) { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(a); dca::linalg::matrixop::swapRow(c, i_1, i_2); for (int j = 0; j < a.nrCols(); ++j) { for (int i = 0; i < a.nrCols(); ++i) { if (i == i_1) { EXPECT_EQ(a(i_2, j), c(i, j)); } else if (i == i_2) { EXPECT_EQ(a(i_1, j), c(i, j)); } else { EXPECT_EQ(a(i, j), c(i, j)); } } } } } } TYPED_TEST(MatrixopRealCPUTest, SwapCol) { using ScalarType = TypeParam; std::pair<int, int> size2_a(3, 4); auto val_a = [](int i, int j) { return 10 * i + j; }; dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size2_a); testing::setMatrixElements(a, val_a); for (int j_1 : {0, 2, 3}) { for (int j_2 : {1, 3}) { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> c(a); dca::linalg::matrixop::swapCol(c, j_1, j_2); for (int i = 0; i < a.nrRows(); ++i) { for (int j = 0; j < a.nrCols(); ++j) { if (j == j_1) { EXPECT_EQ(a(i, j_2), c(i, j)); } else if (j == j_2) { EXPECT_EQ(a(i, j_1), c(i, j)); } else { EXPECT_EQ(a(i, j), c(i, j)); } } } } } } TEST(MatrixopCPUTest, Difference) { std::pair<int, int> size2_a(5, 4); const double epsilon = std::numeric_limits<double>::epsilon(); double diff = .01; auto val_a = [](int i, int j) { return 10 * i + j; }; dca::linalg::Matrix<double, dca::linalg::CPU> a(size2_a); testing::setMatrixElements(a, val_a); for (int sg : {1, -1}) for (int ia : {0, 1, 4}) for (int ja : {0, 2, 3}) { dca::linalg::Matrix<double, dca::linalg::CPU> b(a); b(ia, ja) += sg * diff; double err = std::abs(epsilon * b(ia, ja)); EXPECT_NEAR(diff, dca::linalg::matrixop::difference(a, b, 2 * diff), err); EXPECT_NEAR(diff, dca::linalg::matrixop::difference(a, b, diff + err), err); auto diffcalc = dca::linalg::matrixop::difference(a, b, 2 * diff); EXPECT_NEAR(diff, dca::linalg::matrixop::difference(a, b, diffcalc), err); EXPECT_THROW(dca::linalg::matrixop::difference(a, b, diffcalc - err), std::logic_error); } } template <typename ScalarType> class MatrixopMixedCPUTest : public ::testing::Test { public: static const ScalarType epsilon; }; template <typename ScalarType> const ScalarType MatrixopMixedCPUTest<ScalarType>::epsilon = std::numeric_limits<ScalarType>::epsilon(); TYPED_TEST_CASE(MatrixopMixedCPUTest, FloatingPointTypes); TYPED_TEST(MatrixopMixedCPUTest, Gemm) { using ScalarType = TypeParam; using ComplexType = std::complex<ScalarType>; auto val_real = [](int i, int j) { return 3 * i - 2 * j; }; auto val_complex = [](int i, int j) { return ComplexType(i - 2 * j * j, 4 * i - 3 * j); }; auto val_c = [](int i, int j) { return ComplexType(2 * i - j, 2 * j - i); }; int m = 2; int k = 4; int n = 3; std::pair<int, int> size_c(2, 3); char trans_opts[] = {'N', 'T', 'C'}; for (auto transa : trans_opts) { std::pair<int, int> size_a; if (transa == 'N') { size_a.first = m; size_a.second = k; } else { size_a.first = k; size_a.second = m; } for (auto transb : trans_opts) { std::pair<int, int> size_b; if (transb == 'N') { size_b.first = k; size_b.second = n; } else { size_b.first = n; size_b.second = k; } if (transa != 'C') { dca::linalg::Matrix<ScalarType, dca::linalg::CPU> a(size_a); dca::linalg::Matrix<ComplexType, dca::linalg::CPU> b(size_b); dca::linalg::Matrix<ComplexType, dca::linalg::CPU> c(size_c); testing::setMatrixElements(a, val_real); testing::setMatrixElements(b, val_complex); testing::setMatrixElements(c, val_c); dca::linalg::Matrix<ComplexType, dca::linalg::CPU> cref(c); testing::refGemm(transa, transb, ComplexType(1), a, b, ComplexType(0), cref); dca::linalg::matrixop::gemm(transa, transb, a, b, c); for (int j = 0; j < c.nrCols(); ++j) for (int i = 0; i < c.nrRows(); ++i) { EXPECT_GE(500 * this->epsilon, std::abs(cref(i, j) - c(i, j))); } } if (transb != 'C') { dca::linalg::Matrix<ComplexType, dca::linalg::CPU> a(size_a); dca::linalg::Matrix<ScalarType, dca::linalg::CPU> b(size_b); dca::linalg::Matrix<ComplexType, dca::linalg::CPU> c(size_c); testing::setMatrixElements(a, val_complex); testing::setMatrixElements(b, val_real); testing::setMatrixElements(c, val_c); dca::linalg::Matrix<ComplexType, dca::linalg::CPU> cref(c); testing::refGemm(transa, transb, ComplexType(1), a, b, ComplexType(0), cref); dca::linalg::matrixop::gemm(transa, transb, a, b, c); for (int j = 0; j < c.nrCols(); ++j) for (int i = 0; i < c.nrRows(); ++i) { EXPECT_GE(500 * this->epsilon, std::abs(cref(i, j) - c(i, j))); } } } } }
32.071639
104
0.563722
[ "vector" ]
b1abfb29fe2db07d991e9a6f655345720faef863
2,720
hpp
C++
3rdparty/libprocess/include/process/firewall.hpp
CodeTickler/mesos
3ecd54320397c3a813d555f291b51778372e273b
[ "Apache-2.0" ]
null
null
null
3rdparty/libprocess/include/process/firewall.hpp
CodeTickler/mesos
3ecd54320397c3a813d555f291b51778372e273b
[ "Apache-2.0" ]
null
null
null
3rdparty/libprocess/include/process/firewall.hpp
CodeTickler/mesos
3ecd54320397c3a813d555f291b51778372e273b
[ "Apache-2.0" ]
null
null
null
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ #ifndef __PROCESS_FIREWALL_HPP__ #define __PROCESS_FIREWALL_HPP__ #include <string> #include <process/http.hpp> #include <process/owned.hpp> #include <process/socket.hpp> #include <stout/error.hpp> #include <stout/hashset.hpp> #include <stout/option.hpp> namespace process { namespace firewall { /** * A 'FirewallRule' describes an interface which provides control * over incoming HTTP requests while also taking the underlying * connection into account. * * Concrete classes based on this interface must implement the * 'apply' method. * * Rules can be installed using the free function * 'process::firewall::install()' defined in 'process.hpp'. */ class FirewallRule { public: FirewallRule() {} virtual ~FirewallRule() {} /** * Verify rule by applying it to an HTTP request and its underlying * socket connection. * * @param socket Socket used to deliver the HTTP request. * @param request HTTP request made by the client to libprocess. * @return If the rule verification fails, i.e. the rule didn't * match, a pointer to a 'http::Response' object containing the * HTTP error code and possibly a message indicating the reason * for failure. Otherwise an unset 'Option' object. */ virtual Option<http::Response> apply( const network::Socket& socket, const http::Request& request) = 0; }; /** * Simple firewall rule to forbid any HTTP request to a path * in the provided list of endpoints. * * Matches are required to be exact, no substrings nor wildcards are * considered for a match. */ class DisabledEndpointsFirewallRule : public FirewallRule { public: explicit DisabledEndpointsFirewallRule(const hashset<std::string>& _paths); virtual ~DisabledEndpointsFirewallRule() {} virtual Option<http::Response> apply( const network::Socket&, const http::Request& request) { if (paths.contains(request.path)) { return http::Forbidden("Endpoint '" + request.path + "' is disabled"); } return None(); } private: hashset<std::string> paths; }; } // namespace firewall { } // namespace process { #endif // __PROCESS_FIREWALL_HPP__
27.755102
77
0.715809
[ "object" ]
b1b6845d9935bca7a6c1836bb222f9961641f2c1
2,175
cpp
C++
src/catalog/index_schema.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
3
2020-11-06T01:09:42.000Z
2021-10-08T14:34:44.000Z
src/catalog/index_schema.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
13
2020-05-16T19:42:06.000Z
2020-08-25T18:40:36.000Z
src/catalog/index_schema.cpp
pmenon/noisepage
73d50cdfa2e15b5d45e61b51e34672d10a851e14
[ "MIT" ]
4
2020-05-16T14:48:14.000Z
2020-07-12T01:18:44.000Z
#include "catalog/index_schema.h" #include "common/json.h" namespace noisepage::catalog { nlohmann::json IndexSchema::Column::ToJson() const { nlohmann::json j; j["name"] = name_; j["type"] = type_; j["attr_length"] = attr_length_; j["type_modifier"] = type_modifier_; j["nullable"] = nullable_; j["oid"] = oid_; j["definition"] = definition_->ToJson(); return j; } std::vector<std::unique_ptr<parser::AbstractExpression>> IndexSchema::Column::FromJson(const nlohmann::json &j) { name_ = j.at("name").get<std::string>(); type_ = j.at("type").get<type::TypeId>(); attr_length_ = j.at("attr_length").get<uint16_t>(); type_modifier_ = j.at("type_modifier").get<int32_t>(); nullable_ = j.at("nullable").get<bool>(); oid_ = j.at("oid").get<indexkeycol_oid_t>(); auto deserialized = parser::DeserializeExpression(j.at("definition")); definition_ = std::move(deserialized.result_); return std::move(deserialized.non_owned_exprs_); } nlohmann::json IndexSchema::ToJson() const { // Only need to serialize columns_ because col_oid_to_offset is derived from columns_ nlohmann::json j; j["columns"] = columns_; j["type"] = static_cast<char>(type_); j["unique"] = is_unique_; j["primary"] = is_primary_; j["exclusion"] = is_exclusion_; j["immediate"] = is_immediate_; return j; } void IndexSchema::FromJson(const nlohmann::json &j) { NOISEPAGE_ASSERT(false, "Schema::FromJson should never be invoked directly; use DeserializeSchema"); } std::unique_ptr<IndexSchema> IndexSchema::DeserializeSchema(const nlohmann::json &j) { auto columns = j.at("columns").get<std::vector<IndexSchema::Column>>(); auto unique = j.at("unique").get<bool>(); auto primary = j.at("primary").get<bool>(); auto exclusion = j.at("exclusion").get<bool>(); auto immediate = j.at("immediate").get<bool>(); auto type = static_cast<storage::index::IndexType>(j.at("type").get<char>()); auto schema = std::make_unique<IndexSchema>(columns, type, unique, primary, exclusion, immediate); return schema; } DEFINE_JSON_BODY_DECLARATIONS(IndexSchema::Column); DEFINE_JSON_BODY_DECLARATIONS(IndexSchema); } // namespace noisepage::catalog
33.461538
113
0.702069
[ "vector" ]
b1b92d19b1d0fa6f5dda52f020dda09ab5760249
16,396
cpp
C++
android/library/maply/jni/src/vectors/AttrDictionary_jni.cpp
zflamig/WhirlyGlobe
b6a6536507d33c6b25248fa67877a9d87d11ed43
[ "Apache-2.0" ]
null
null
null
android/library/maply/jni/src/vectors/AttrDictionary_jni.cpp
zflamig/WhirlyGlobe
b6a6536507d33c6b25248fa67877a9d87d11ed43
[ "Apache-2.0" ]
null
null
null
android/library/maply/jni/src/vectors/AttrDictionary_jni.cpp
zflamig/WhirlyGlobe
b6a6536507d33c6b25248fa67877a9d87d11ed43
[ "Apache-2.0" ]
null
null
null
/* AttrDictionary_jni.cpp * WhirlyGlobeLib * * Created by Steve Gifford on 6/2/14. * Copyright 2011-2021 mousebird consulting * * 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. */ #import <jni.h> #import "Maply_jni.h" #import "com_mousebird_maply_AttrDictionary.h" #import "Vectors_jni.h" #import "WhirlyGlobe_Android.h" template<> AttrDictClassInfo *AttrDictClassInfo::classInfoObj = nullptr; using namespace WhirlyKit; extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_nativeInit(JNIEnv *env, jclass theClass) { AttrDictClassInfo::getClassInfo(env,theClass); } JNIEXPORT jobject JNICALL MakeAttrDictionary(JNIEnv *env,const MutableDictionary_AndroidRef &dict) { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(env,"com/mousebird/maply/AttrDictionary"); jobject dictObj = classInfo->makeWrapperObject(env,nullptr); auto inst = classInfo->getObject(env,dictObj); *(inst->get()) = *(dict.get()); return dictObj; } extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_initialise(JNIEnv *env, jobject obj) { try { auto dict = new MutableDictionary_AndroidRef(new MutableDictionary_Android()); AttrDictClassInfo::getClassInfo()->setHandle(env,obj,dict); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::initialise()"); } } static std::mutex disposeMutex; extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_dispose(JNIEnv *env, jobject obj) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); { std::lock_guard<std::mutex> lock(disposeMutex); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return; delete dict; classInfo->clearHandle(env,obj); } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::dispose()"); } } extern "C" JNIEXPORT jboolean JNICALL Java_com_mousebird_maply_AttrDictionary_parseFromJSON(JNIEnv *env, jobject obj, jstring inJsonStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return false; JavaString jsonStr(env,inJsonStr); return (*dict)->parseJSON(jsonStr.getCString()); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::parseFromJSON()"); } return true; // ? } extern "C" JNIEXPORT jboolean JNICALL Java_com_mousebird_maply_AttrDictionary_hasField(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return false; JavaString attrName(env,attrNameStr); return (*dict)->hasField(attrName.getCString()); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::hasField()"); } return false; } extern "C" JNIEXPORT jstring JNICALL Java_com_mousebird_maply_AttrDictionary_getString(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; JavaString attrName(env,attrNameStr); std::string str = (*dict)->getString(attrName.getCString()); if (!str.empty()) { return env->NewStringUTF(str.c_str()); } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::getString()"); } return nullptr; } extern "C" JNIEXPORT jobject JNICALL Java_com_mousebird_maply_AttrDictionary_getInt(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; JavaString attrName(env,attrNameStr); if ((*dict)->hasField(attrName.getCString())) { int val = (*dict)->getInt(attrName.getCString(), 0); return JavaIntegerClassInfo::getClassInfo(env)->makeInteger(env,val); } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::getInt()"); } return nullptr; } extern "C" JNIEXPORT jobjectArray JNICALL Java_com_mousebird_maply_AttrDictionary_getArray(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; JavaString attrName(env,attrNameStr); if ((*dict)->getType(attrName.getCString()) == DictTypeArray) { std::vector<jobject> retObjs; auto arr = (*dict)->getArray(attrName.getCString()); retObjs.reserve(arr.size()); for (const auto &arrEntry : arr) { jobject newObj = MakeAttrDictionaryEntry(env,std::dynamic_pointer_cast<DictionaryEntry_Android>(arrEntry)); retObjs.push_back(newObj); } jobjectArray retArray = BuildObjectArray(env,AttrDictEntryClassInfo::getClassInfo()->getClass(),retObjs); for (jobject objRef: retObjs) env->DeleteLocalRef(objRef); retObjs.clear(); return retArray; } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::getArray()"); } return NULL; } extern "C" JNIEXPORT jobject JNICALL Java_com_mousebird_maply_AttrDictionary_getDouble(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; JavaString attrName(env,attrNameStr); if ((*dict)->hasField(attrName.getCString())) { double val = (*dict)->getDouble(attrName.getCString(), 0); return JavaDoubleClassInfo::getClassInfo(env)->makeDouble(env,val); } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::getDouble()"); } return nullptr; } extern "C" JNIEXPORT jobject JNICALL Java_com_mousebird_maply_AttrDictionary_getIdentity(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; JavaString attrName(env,attrNameStr); if ((*dict)->hasField(attrName.getCString())) { long long val = (*dict)->getIdentity(attrName.getCString()); return JavaLongClassInfo::getClassInfo(env)->makeLong(env,val); } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::getIdentity()"); } return nullptr; } extern "C" JNIEXPORT jobject JNICALL Java_com_mousebird_maply_AttrDictionary_getDict(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; JavaString attrName(env,attrNameStr); MutableDictionary_AndroidRef subDict = std::dynamic_pointer_cast<MutableDictionary_Android>((*dict)->getDict(attrName.getCString())); if (subDict) return MakeAttrDictionary(env,subDict); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::getDict()"); } return nullptr; } extern "C" JNIEXPORT jobject JNICALL Java_com_mousebird_maply_AttrDictionary_getEntry(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; JavaString attrName(env,attrNameStr); DictionaryEntry_AndroidRef entry = std::dynamic_pointer_cast<DictionaryEntry_Android>((*dict)->getEntry(attrName.getCString())); if (entry) return MakeAttrDictionaryEntry(env,entry); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::getEntry()"); } return nullptr; } extern "C" JNIEXPORT jobjectArray JNICALL Java_com_mousebird_maply_AttrDictionary_getKeys(JNIEnv *env, jobject obj) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; auto keys = (*dict)->getKeys(); return BuildStringArray(env,keys); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::getKeys()"); } return nullptr; } extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_setString(JNIEnv *env, jobject obj, jstring attrNameObj, jstring strValObj) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return; JavaString attrName(env,attrNameObj); JavaString attrVal(env,strValObj); (*dict)->setString(attrName.getCString(),attrVal.getCString()); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::setString()"); } } extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_setInt(JNIEnv *env, jobject obj, jstring attrNameObj, jint iVal) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return; JavaString attrName(env,attrNameObj); (*dict)->setInt(attrName.getCString(),iVal); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::setInt()"); } } extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_setDouble(JNIEnv *env, jobject obj, jstring attrNameObj, jdouble dVal) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return; JavaString attrName(env,attrNameObj); (*dict)->setDouble(attrName.getCString(),dVal); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::setDouble()"); } } extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_setDict(JNIEnv *env, jobject obj, jstring attrNameObj, jobject dictObj) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); MutableDictionary_AndroidRef *otherDict = classInfo->getObject(env,dictObj); if (!dict || !otherDict) return; JavaString attrName(env,attrNameObj); (*dict)->setDict(attrName.getCString(),*otherDict); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::setDict()"); } } extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_setArray__Ljava_lang_String_2_3Lcom_mousebird_maply_AttrDictionaryEntry_2(JNIEnv *env, jobject obj, jstring attrNameObj, jobjectArray entryArrObj) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); AttrDictEntryClassInfo *entryClassInfo = AttrDictEntryClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return; JavaString attrName(env,attrNameObj); // Pull the entries out of the array of objects std::vector<DictionaryEntryRef> entries; JavaObjectArrayHelper arrayHelper(env,entryArrObj); for (unsigned int ii=0;ii<arrayHelper.numObjects();ii++) { jobject entryObj = arrayHelper.getNextObject(); DictionaryEntry_AndroidRef *entry = entryClassInfo->getObject(env,entryObj); entries.push_back(DictionaryEntry_AndroidRef(*entry)); } (*dict)->setArray(attrName.getCString(),entries); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::setArray()"); } } extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_setArray__Ljava_lang_String_2_3Lcom_mousebird_maply_AttrDictionary_2(JNIEnv *env, jobject obj, jstring attrNameObj, jobjectArray dictArrayObj) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); AttrDictClassInfo *entryClassInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return; JavaString attrName(env,attrNameObj); // Pull the entries out of the array of objects std::vector<DictionaryRef> entries; JavaObjectArrayHelper arrayHelper(env,dictArrayObj); for (unsigned int ii=0;ii<arrayHelper.numObjects();ii++) { jobject entryObj = arrayHelper.getNextObject(); MutableDictionary_AndroidRef *entry = entryClassInfo->getObject(env,entryObj); entries.push_back(MutableDictionary_AndroidRef(*entry)); } (*dict)->setArray(attrName.getCString(),entries); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::setArray()"); } } extern "C" JNIEXPORT jstring JNICALL Java_com_mousebird_maply_AttrDictionary_toString(JNIEnv *env, jobject obj) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) return nullptr; std::string str = (*dict)->toString(); return env->NewStringUTF(str.c_str()); } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::setDouble()"); } return nullptr; } extern "C" JNIEXPORT jobject JNICALL Java_com_mousebird_maply_AttrDictionary_get(JNIEnv *env, jobject obj, jstring attrNameStr) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); if (!dict) { return nullptr; } JavaString attrName(env,attrNameStr); if ((*dict)->hasField(attrName.getCString())) { const DictionaryType dictType = (*dict)->getType(attrName.getCString()); if (dictType == DictTypeString) { const std::string str = (*dict)->getString(attrName.getCString()); if (!str.empty()) { return env->NewStringUTF(str.c_str()); } } else if (dictType == DictTypeInt) { const int val = (*dict)->getInt(attrName.getCString(), 0); return JavaIntegerClassInfo::getClassInfo(env)->makeInteger(env,val); } else if (dictType == DictTypeDouble) { const double val = (*dict)->getDouble(attrName.getCString(), 0); return JavaDoubleClassInfo::getClassInfo(env)->makeDouble(env,val); } } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::get()"); } return nullptr; } extern "C" JNIEXPORT void JNICALL Java_com_mousebird_maply_AttrDictionary_addEntries(JNIEnv *env, jobject obj, jobject other) { try { AttrDictClassInfo *classInfo = AttrDictClassInfo::getClassInfo(); MutableDictionary_AndroidRef *dict = classInfo->getObject(env,obj); MutableDictionary_AndroidRef *otherDict = classInfo->getObject(env,other); if (dict && other) { (*dict)->addEntries(otherDict->get()); } } catch (...) { __android_log_print(ANDROID_LOG_VERBOSE, "Maply", "Crash in Dictionary::addEntries()"); } }
29.070922
209
0.712186
[ "vector" ]
b1ba78d4441510ba162300c35b210dc1f980e5e4
48,624
cpp
C++
src/miner.cpp
fx-ha/mainchain
c6c353e0d7e7af2d6a5fdde2838c0c5e4d572bcd
[ "MIT" ]
null
null
null
src/miner.cpp
fx-ha/mainchain
c6c353e0d7e7af2d6a5fdde2838c0c5e4d572bcd
[ "MIT" ]
null
null
null
src/miner.cpp
fx-ha/mainchain
c6c353e0d7e7af2d6a5fdde2838c0c5e4d572bcd
[ "MIT" ]
null
null
null
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "miner.h" #include "amount.h" #include "base58.h" #include "chain.h" #include "chainparams.h" #include "coins.h" #include "consensus/consensus.h" #include "consensus/tx_verify.h" #include "consensus/merkle.h" #include "consensus/validation.h" #include "hash.h" #include "validation.h" #include "net.h" #include "policy/feerate.h" #include "policy/policy.h" #include "pow.h" #include "primitives/transaction.h" #include "script/standard.h" #include "sidechain.h" #include "sidechaindb.h" #include "timedata.h" #include "txmempool.h" #include "util.h" #include "utilmoneystr.h" #include "utilstrencodings.h" #include "validationinterface.h" #ifdef ENABLE_WALLET #include "wallet/wallet.h" #endif #include <algorithm> #include <queue> #include <utility> #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> static const bool fMiningReqiresPeer = false; ////////////////////////////////////////////////////////////////////////////// // // BitcoinMiner // // // Unconfirmed transactions in the memory pool often depend on other // transactions in the memory pool. When we select transactions from the // pool, we select by highest fee rate of a transaction combined with all // its ancestors. uint64_t nLastBlockTx = 0; uint64_t nLastBlockWeight = 0; uint256 hashTarget = uint256(); uint256 hashBest = uint256(); uint32_t nMiningNonce = 0; int64_t UpdateTime(CBlockHeader* pblock, const Consensus::Params& consensusParams, const CBlockIndex* pindexPrev) { int64_t nOldTime = pblock->nTime; int64_t nNewTime = std::max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime()); if (nOldTime < nNewTime) pblock->nTime = nNewTime; // Updating time can change work required on testnet: if (consensusParams.fPowAllowMinDifficultyBlocks) pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, consensusParams); return nNewTime - nOldTime; } BlockAssembler::Options::Options() { blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); nBlockMaxWeight = DEFAULT_BLOCK_MAX_WEIGHT; } BlockAssembler::BlockAssembler(const CChainParams& params, const Options& options) : chainparams(params) { blockMinFeeRate = options.blockMinFeeRate; // Limit weight to between 4K and MAX_BLOCK_WEIGHT-4K for sanity: nBlockMaxWeight = std::max<size_t>(4000, std::min<size_t>(MAX_BLOCK_WEIGHT - 4000, options.nBlockMaxWeight)); } static BlockAssembler::Options DefaultOptions(const CChainParams& params) { // Block resource limits // If neither -blockmaxsize or -blockmaxweight is given, limit to DEFAULT_BLOCK_MAX_* // If only one is given, only restrict the specified resource. // If both are given, restrict both. BlockAssembler::Options options; options.nBlockMaxWeight = gArgs.GetArg("-blockmaxweight", DEFAULT_BLOCK_MAX_WEIGHT); if (gArgs.IsArgSet("-blockmintxfee")) { CAmount n = 0; ParseMoney(gArgs.GetArg("-blockmintxfee", ""), n); options.blockMinFeeRate = CFeeRate(n); } else { options.blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); } return options; } BlockAssembler::BlockAssembler(const CChainParams& params) : BlockAssembler(params, DefaultOptions(params)) {} void BlockAssembler::resetBlock() { inBlock.clear(); // Reserve space for coinbase tx nBlockWeight = 4000; nBlockSigOpsCost = 400; fIncludeWitness = false; // These counters do not include coinbase tx nBlockTx = 0; nFees = 0; } std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx) { bool fAddedBMM = false; return CreateNewBlock(scriptPubKeyIn, fMineWitnessTx, fAddedBMM); } std::unique_ptr<CBlockTemplate> BlockAssembler::CreateNewBlock(const CScript& scriptPubKeyIn, bool fMineWitnessTx, bool& fAddedBMM) { int64_t nTimeStart = GetTimeMicros(); resetBlock(); pblocktemplate.reset(new CBlockTemplate()); if(!pblocktemplate.get()) return nullptr; pblock = &pblocktemplate->block; // pointer for convenience // Add dummy coinbase tx as first transaction pblock->vtx.emplace_back(); pblocktemplate->vTxFees.push_back(-1); // updated at end pblocktemplate->vTxSigOpsCost.push_back(-1); // updated at end LOCK2(cs_main, mempool.cs); CBlockIndex* pindexPrev = chainActive.Tip(); assert(pindexPrev != nullptr); nHeight = pindexPrev->nHeight + 1; pblock->nVersion = ComputeBlockVersion(pindexPrev, chainparams.GetConsensus()); // -regtest only: allow overriding block.nVersion with // -blockversion=N to test forking scenarios if (chainparams.MineBlocksOnDemand()) pblock->nVersion = gArgs.GetArg("-blockversion", pblock->nVersion); pblock->nTime = GetAdjustedTime(); const int64_t nMedianTimePast = pindexPrev->GetMedianTimePast(); nLockTimeCutoff = (STANDARD_LOCKTIME_VERIFY_FLAGS & LOCKTIME_MEDIAN_TIME_PAST) ? nMedianTimePast : pblock->GetBlockTime(); // Decide whether to include witness transactions // This is only needed in case the witness softfork activation is reverted // (which would require a very deep reorganization) or when // -promiscuousmempoolflags is used. // TODO: replace this with a call to main to assess validity of a mempool // transaction (which in most cases can be a no-op). fIncludeWitness = IsWitnessEnabled(pindexPrev, chainparams.GetConsensus()) && fMineWitnessTx; bool fDrivechainEnabled = IsDrivechainEnabled(pindexPrev, chainparams.GetConsensus()); #ifdef ENABLE_WALLET if (fDrivechainEnabled) { // Make sure that the mempool has only valid deposits to choose from mempool.UpdateCTIPFromBlock(scdb.GetCTIP(), false /* fDisconnect */); // Remove expired BMM requests from our memory pool std::vector<uint256> vHashRemoved; mempool.RemoveExpiredCriticalRequests(vHashRemoved); // Select which BMM requests (if any) to include mempool.SelectBMMRequests(vHashRemoved); // Track what was removed from the mempool so that we can abandon later for (const uint256& u : vHashRemoved) scdb.AddRemovedBMM(u); } #endif // Collect active sidechains std::vector<Sidechain> vActiveSidechain; if (fDrivechainEnabled) vActiveSidechain = scdb.GetActiveSidechains(); // If a WT^ has sufficient workscore and this block isn't the last in the // verification period, create the payout transaction. We will add any // generated payout transactions to the block later. // // Keep track of which sidechains will have a WT^ in this block. We will // need this when deciding what transactions to add from the mempool. std::set<uint8_t> setSidechainsWithWTPrime; // Keep track of the created WT^(s) to be added to the block later std::vector<CMutableTransaction> vWTPrime; // Keep track of mainchain fees CAmount nWTPrimeFees = 0; if (fDrivechainEnabled) { for (const Sidechain& s : vActiveSidechain) { CMutableTransaction wtx; CAmount nFee = 0; bool fCreated = CreateWTPrimePayout(s.nSidechain, wtx, nFee); if (fCreated && wtx.vout.size() && wtx.vin.size()) { LogPrintf("%s: Created WT^ payout for sidechain: %u with: %u outputs!\ntxid: %s.\n", __func__, s.nSidechain, wtx.vout.size(), wtx.GetHash().ToString()); vWTPrime.push_back(wtx); setSidechainsWithWTPrime.insert(s.nSidechain); nWTPrimeFees += nFee; } } } int nPackagesSelected = 0; int nDescendantsUpdated = 0; bool fNeedCriticalFeeTx = false; addPackageTxs(nPackagesSelected, nDescendantsUpdated, fDrivechainEnabled, fNeedCriticalFeeTx, setSidechainsWithWTPrime); int64_t nTime1 = GetTimeMicros(); nLastBlockTx = nBlockTx; nLastBlockWeight = nBlockWeight; // Create coinbase transaction. CMutableTransaction coinbaseTx; coinbaseTx.vin.resize(1); coinbaseTx.vin[0].prevout.SetNull(); coinbaseTx.vout.resize(1); coinbaseTx.vout[0].scriptPubKey = scriptPubKeyIn; // Coinbase subsidy + fees coinbaseTx.vout[0].nValue = nWTPrimeFees + nFees + GetBlockSubsidy(nHeight, chainparams.GetConsensus()); coinbaseTx.vin[0].scriptSig = CScript() << nHeight << OP_0; // Add coinbase to block pblock->vtx[0] = MakeTransactionRef(std::move(coinbaseTx)); // TODO make selection of WT^(s) to accept / commit interactive - GUI // Commit WT^(s) which we have received locally std::map<uint8_t /* nSidechain */, uint256 /* hashWTPrime */> mapNewWTPrime; for (const Sidechain& s : vActiveSidechain) { std::vector<uint256> vHash = scdb.GetUncommittedWTPrimeCache(s.nSidechain); if (vHash.empty()) continue; const uint256& hashWTPrime = vHash.back(); // Make sure that the WT^ hasn't previously been spent or failed. // We don't want to re-include WT^(s) that have previously failed or // already were approved. if (scdb.HaveFailedWTPrime(hashWTPrime, s.nSidechain)) continue; if (scdb.HaveSpentWTPrime(hashWTPrime, s.nSidechain)) continue; // For now, if there are fresh (uncommited, unknown to SCDB) WT^(s) // we will commit the most recent in the block we are generating. GenerateWTPrimeHashCommitment(*pblock, hashWTPrime, s.nSidechain, chainparams.GetConsensus()); // Keep track of new WT^(s) by nSidechain for later mapNewWTPrime[s.nSidechain] = hashWTPrime; } // Handle WT^ updates & generate SCDB MT hash if (fDrivechainEnabled) { if (scdb.HasState() || mapNewWTPrime.size()) { uint256 hashSCDB; std::vector<SidechainWTPrimeState> vNewWTPrime; std::vector<SidechainCustomVote> vCustomVote; // Add new WT^(s) std::map<uint8_t, uint256>::const_iterator it = mapNewWTPrime.begin(); while (it != mapNewWTPrime.end()) { SidechainWTPrimeState wtPrime; wtPrime.nSidechain = it->first; wtPrime.hashWTPrime = it->second; wtPrime.nWorkScore = 1; wtPrime.nBlocksLeft = SIDECHAIN_VERIFICATION_PERIOD - 1; vNewWTPrime.push_back(wtPrime); LogPrintf("%s: Miner added new WT^: %s at height %u.\n", __func__, wtPrime.hashWTPrime.ToString(), nHeight); it++; } // Note that custom votes have priority, and if custom votes are // set we ignore the default votes. // // TODO if custom votes are set disable the defaultwtprimevote // combobox on the GUI and add a label with a note // Apply user's custom votes // // Check if the user has set any custom WT^ votes. They can set // custom upvotes, downvotes or abstain by specifying the WT^ // hash as a command line param and via GUI. // // This vector has all of the users vote settings. Some of // them could be old / for WT^(s) that don't exist yet. We will // add votes that can actually be applied to vCustomVote. std::vector<SidechainCustomVote> vUserVote = scdb.GetCustomVoteCache(); // This will store the new votes we are making - based on either // default or custom votes std::vector<SidechainWTPrimeState> vWTPrimeVote; // If there are custom votes apply them, otherwise check if a // default is set if (vUserVote.size()) { // TODO changing containers could reduce repeat looping // // Apply users custom votes, and save the custom votes for later // when we generate update bytes for (const Sidechain& s : vActiveSidechain) { std::vector<SidechainWTPrimeState> vState = scdb.GetState(s.nSidechain); for (const SidechainWTPrimeState& wt : vState) { // Check if this WT^ has a custom vote setting for (const SidechainCustomVote& vote : vUserVote) { if (wt.hashWTPrime == vote.hashWTPrime && wt.nSidechain == vote.nSidechain) { // Add custom vote to final vector vCustomVote.push_back(vote); // Add to vWTPrimeVote SidechainWTPrimeState wtState = wt; if (vote.vote == SCDB_UPVOTE) { wtState.nWorkScore++; } else if (vote.vote == SCDB_DOWNVOTE) { if (wtState.nWorkScore > 0) wtState.nWorkScore--; } vWTPrimeVote.push_back(wtState); } } } } } else { // Check if the user has set a default WT^ vote std::string strDefaultVote = ""; strDefaultVote = gArgs.GetArg("-defaultwtprimevote", ""); char vote = SCDB_ABSTAIN; if (strDefaultVote == "upvote") { vote = SCDB_UPVOTE; } else if (strDefaultVote == "downvote") { vote = SCDB_DOWNVOTE; } // Get new scores with default votes applied vWTPrimeVote = scdb.GetLatestStateWithVote(vote, mapNewWTPrime); } // Add new WT^(s) to the list for (const SidechainWTPrimeState& wt : vNewWTPrime) vWTPrimeVote.push_back(wt); hashSCDB = scdb.GetSCDBHashIfUpdate(vWTPrimeVote, nHeight, mapNewWTPrime, true /* fRemoveExpired */); if (!hashSCDB.IsNull()) { // Generate SCDB merkle root hash commitment GenerateSCDBHashMerkleRootCommitment(*pblock, hashSCDB, chainparams.GetConsensus()); // The miner should be passing only the new WT^(s) when checking // MT update here. // // If UpdateSCDBMatchMT doesn't work with just that - which // means other nodes won't be able to update either then // generate SCDB update bytes. // // Test parsing and pass the result of ParseSCDBUpdateScript + // the new WT^(s) into UpdateSCDBMatchMT to check that it works // with the bytes & new WT^ info. // // Nodes connecting the block will add the new WT^(s) to their // db but they wont have the rest of the score changes without // parsing the update bytes in this scenario. // Check if we need to generate update bytes SidechainDB scdbCopy = scdb; if (!scdbCopy.UpdateSCDBMatchMT(nHeight, hashSCDB, vNewWTPrime, mapNewWTPrime)) { // Get SCDB state std::vector<std::vector<SidechainWTPrimeState>> vState; for (const Sidechain& s : vActiveSidechain) { vState.push_back(scdb.GetState(s.nSidechain)); } LogPrintf("%s: Miner generating update bytes at height %u.\n", __func__, nHeight); CScript script; GenerateSCDBUpdateScript(*pblock, script, vState, vCustomVote, chainparams.GetConsensus()); // Make sure that we can read the update bytes std::vector<SidechainWTPrimeState> vParsed; if (!ParseSCDBUpdateScript(script, vState, vParsed)) { LogPrintf("%s: Miner failed to parse its own update bytes at height %u.\n", __func__, nHeight); throw std::runtime_error(strprintf("%s: Miner failed to parse its own update bytes at height %u.\n", __func__, nHeight)); } // Add new WT^(s) to the list for (const SidechainWTPrimeState& wt : vNewWTPrime) vParsed.push_back(wt); // Finally, check if we can update with update bytes if (!scdbCopy.UpdateSCDBMatchMT(nHeight, hashSCDB, vParsed, mapNewWTPrime)) { LogPrintf("%s: Miner failed to update with bytes at height %u.\n", __func__, nHeight); throw std::runtime_error(strprintf("%s: Miner failed update with its own update bytes at height %u.\n", __func__, nHeight)); } } } } // Generate critical hash commitments (usually for BMM commitments) GenerateCriticalHashCommitments(*pblock, chainparams.GetConsensus()); // Scan through our sidechain proposals and commit the first one we find // that hasn't already been commited and is tracked by SCDB. // // If we commit a proposal, save the hash to easily ACK it later uint256 hashProposal; std::vector<SidechainProposal> vProposal = scdb.GetSidechainProposals(); if (!vProposal.empty()) { std::vector<SidechainActivationStatus> vActivation = scdb.GetSidechainActivationStatus(); for (const SidechainProposal& p : vProposal) { // Check if this proposal is already being tracked by SCDB bool fFound = false; for (const SidechainActivationStatus& s : vActivation) { if (s.proposal == p) { fFound = true; break; } } if (fFound) continue; GenerateSidechainProposalCommitment(*pblock, p, chainparams.GetConsensus()); hashProposal = p.GetHash(); LogPrintf("%s: Generated sidechain proposal commitment for:\n%s\n", __func__, p.ToString()); break; } } // TODO rename param to make function more clear // If this is set activate any sidechain which has been proposed. bool fAnySidechain = gArgs.GetBoolArg("-activatesidechains", false); // Commit sidechain activation for proposals in activation status cache // which we have configured to ACK std::vector<SidechainActivationStatus> vActivationStatus; vActivationStatus = scdb.GetSidechainActivationStatus(); for (const SidechainActivationStatus& s : vActivationStatus) { if (fAnySidechain || scdb.GetActivateSidechain(s.proposal.GetHash())) GenerateSidechainActivationCommitment(*pblock, s.proposal.GetHash(), chainparams.GetConsensus()); } // If we've proposed a sidechain in this block, ACK it if (!hashProposal.IsNull()) { GenerateSidechainActivationCommitment(*pblock, hashProposal, chainparams.GetConsensus()); } } // TODO reserve room when selecting txns so that there's always space for // the WT^(s) // Add WT^(s) that we created earlier to the block for (const CMutableTransaction& mtx : vWTPrime) { pblock->vtx.push_back(MakeTransactionRef(std::move(mtx))); } // Handle / create critical fee tx (collects bmm / critical data fees) if (fDrivechainEnabled && fNeedCriticalFeeTx) { fAddedBMM = true; // Create critical fee tx CMutableTransaction feeTx; feeTx.vout.resize(1); // Pay the fees to the same script as the coinbase feeTx.vout[0].scriptPubKey = scriptPubKeyIn; feeTx.vout[0].nValue = CAmount(0); // Find all of the critical data transactions included in the block // and take their input and total amount for (const CTransactionRef& tx : pblock->vtx) { if (tx && !tx->criticalData.IsNull()) { // Try to find the critical data fee output and take it for (uint32_t i = 0; i < tx->vout.size(); i++) { if (tx->vout[i].scriptPubKey == CScript() << OP_TRUE) { feeTx.vin.push_back(CTxIn(tx->GetHash(), i)); feeTx.vout[0].nValue += tx->vout[i].nValue; } } } } // TODO calculate the fee tx as part of the block's txn package so that // we always make room for it. // // Add the fee tx to the block if we can if (CTransaction(feeTx).GetValueOut()) { // Check if block weight after adding transaction would be too large if ((nBlockWeight + GetTransactionWeight(feeTx)) < MAX_BLOCK_WEIGHT) { pblock->vtx.push_back(MakeTransactionRef(std::move(feeTx))); pblocktemplate->vTxSigOpsCost.push_back(WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx.back())); pblocktemplate->vTxFees.push_back(0); } else { LogPrintf("%s: Miner could not add BMM fee tx, block size > MAX_BLOCK_WEIGHT ", __func__); } } } pblocktemplate->vchCoinbaseCommitment = GenerateCoinbaseCommitment(*pblock, pindexPrev, chainparams.GetConsensus()); pblocktemplate->vTxFees[0] = -nFees; // Fill in header pblock->hashPrevBlock = pindexPrev->GetBlockHash(); UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev); pblock->nBits = GetNextWorkRequired(pindexPrev, pblock, chainparams.GetConsensus()); pblock->nNonce = 0; pblocktemplate->vTxSigOpsCost[0] = WITNESS_SCALE_FACTOR * GetLegacySigOpCount(*pblock->vtx[0]); LogPrintf("CreateNewBlock(): block weight: %u txs: %u fees: %ld sigops %d\n", GetBlockWeight(*pblock), nBlockTx, nFees, nBlockSigOpsCost); CValidationState state; if (!TestBlockValidity(state, chainparams, *pblock, pindexPrev, false, false)) { throw std::runtime_error(strprintf("%s: TestBlockValidity failed: %s", __func__, FormatStateMessage(state))); } int64_t nTime2 = GetTimeMicros(); LogPrint(BCLog::BENCH, "CreateNewBlock() packages: %.2fms (%d packages, %d updated descendants), validity: %.2fms (total %.2fms)\n", 0.001 * (nTime1 - nTimeStart), nPackagesSelected, nDescendantsUpdated, 0.001 * (nTime2 - nTime1), 0.001 * (nTime2 - nTimeStart)); return std::move(pblocktemplate); } void BlockAssembler::onlyUnconfirmed(CTxMemPool::setEntries& testSet) { for (CTxMemPool::setEntries::iterator iit = testSet.begin(); iit != testSet.end(); ) { // Only test txs not already in the block if (inBlock.count(*iit)) { testSet.erase(iit++); } else { iit++; } } } bool BlockAssembler::TestPackage(uint64_t packageSize, int64_t packageSigOpsCost) const { // TODO: switch to weight-based accounting for packages instead of vsize-based accounting. if (nBlockWeight + WITNESS_SCALE_FACTOR * packageSize >= nBlockMaxWeight) return false; if (nBlockSigOpsCost + packageSigOpsCost >= MAX_BLOCK_SIGOPS_COST) return false; return true; } // Perform transaction-level checks before adding to block: // - transaction finality (locktime) // - premature witness (in case segwit transactions are added to mempool before // segwit activation) // - critical data request height bool BlockAssembler::TestPackageTransactions(const CTxMemPool::setEntries& package) { for (const CTxMemPool::txiter it : package) { if (!IsFinalTx(it->GetTx(), nHeight, nLockTimeCutoff)) return false; if (!fIncludeWitness && it->GetTx().HasWitness()) return false; if (!it->GetTx().criticalData.IsNull()) { if (nHeight != (int64_t)it->GetTx().nLockTime + 1) return false; } } return true; } void BlockAssembler::AddToBlock(CTxMemPool::txiter iter) { pblock->vtx.emplace_back(iter->GetSharedTx()); pblocktemplate->vTxFees.push_back(iter->GetFee()); pblocktemplate->vTxSigOpsCost.push_back(iter->GetSigOpCost()); nBlockWeight += iter->GetTxWeight(); ++nBlockTx; nBlockSigOpsCost += iter->GetSigOpCost(); nFees += iter->GetFee(); inBlock.insert(iter); bool fPrintPriority = gArgs.GetBoolArg("-printpriority", DEFAULT_PRINTPRIORITY); if (fPrintPriority) { LogPrintf("fee %s txid %s\n", CFeeRate(iter->GetModifiedFee(), iter->GetTxSize()).ToString(), iter->GetTx().GetHash().ToString()); } } int BlockAssembler::UpdatePackagesForAdded(const CTxMemPool::setEntries& alreadyAdded, indexed_modified_transaction_set &mapModifiedTx) { int nDescendantsUpdated = 0; for (const CTxMemPool::txiter it : alreadyAdded) { CTxMemPool::setEntries descendants; mempool.CalculateDescendants(it, descendants); // Insert all descendants (not yet in block) into the modified set for (CTxMemPool::txiter desc : descendants) { if (alreadyAdded.count(desc)) continue; ++nDescendantsUpdated; modtxiter mit = mapModifiedTx.find(desc); if (mit == mapModifiedTx.end()) { CTxMemPoolModifiedEntry modEntry(desc); modEntry.nSizeWithAncestors -= it->GetTxSize(); modEntry.nModFeesWithAncestors -= it->GetModifiedFee(); modEntry.nSigOpCostWithAncestors -= it->GetSigOpCost(); mapModifiedTx.insert(modEntry); } else { mapModifiedTx.modify(mit, update_for_parent_inclusion(it)); } } } return nDescendantsUpdated; } bool BlockAssembler::CreateWTPrimePayout(uint8_t nSidechain, CMutableTransaction& tx, CAmount& nFees) { // TODO log all false returns // The WT^ that will be created CMutableTransaction mtx; mtx.nVersion = 2; if (!IsDrivechainEnabled(chainActive.Tip(), chainparams.GetConsensus())) return false; #ifdef ENABLE_WALLET if (!scdb.HasState()) return false; if (!IsSidechainNumberValid(nSidechain)) return false; Sidechain sidechain; if (!scdb.GetSidechain(nSidechain, sidechain)) return false; // Select the highest scoring B-WT^ for sidechain uint256 hashBest = uint256(); uint16_t scoreBest = 0; std::vector<SidechainWTPrimeState> vState = scdb.GetState(nSidechain); for (const SidechainWTPrimeState& state : vState) { if (state.nWorkScore > scoreBest || scoreBest == 0) { hashBest = state.hashWTPrime; scoreBest = state.nWorkScore; } } if (hashBest == uint256()) return false; // Does the selected B-WT^ have sufficient work score? if (scoreBest < SIDECHAIN_MIN_WORKSCORE) return false; // Copy outputs from B-WT^ std::vector<std::pair<uint8_t, CMutableTransaction>> vWTPrime = scdb.GetWTPrimeCache(); for (const std::pair<uint8_t, CMutableTransaction>& pair : vWTPrime) { if (pair.second.GetHash() == hashBest) { for (const CTxOut& out : pair.second.vout) mtx.vout.push_back(out); break; } } // WT^ should have at least the encoded dest output, encoded fee output, // and change return output. if (mtx.vout.size() < 3) return false; // Get the mainchain fee amount from the second WT^ output which encodes the // sum of WT fees. CAmount amountRead = 0; if (!DecodeWTFees(mtx.vout[1].scriptPubKey, amountRead)) { LogPrintf("%s: Failed to decode WT fees!\n", __func__); return false; } nFees = amountRead; // Calculate the amount to be withdrawn by WT^ CAmount amountWithdrawn = CAmount(0); for (const CTxOut& out : mtx.vout) { const CScript scriptPubKey = out.scriptPubKey; if (HexStr(scriptPubKey) != sidechain.sidechainHex) { amountWithdrawn += out.nValue; } } // Add mainchain fees from WT(s) amountWithdrawn += nFees; // Get sidechain change return script. We will pay the sidechain the change // left over from this WT^. This WT^ transaction will look like a normal // sidechain deposit but with more outputs and the destination string will // be SIDECHAIN_WTPRIME_RETURN_DEST. CScript sidechainScript; if (!scdb.GetSidechainScript(nSidechain, sidechainScript)) return false; // Note: WT^ change return must be the final output // Add placeholder change return as the final output. mtx.vout.push_back(CTxOut(0, sidechainScript)); // Get sidechain's CTIP SidechainCTIP ctip; if (!scdb.GetCTIP(nSidechain, ctip)) return false; mtx.vin.push_back(CTxIn(ctip.out)); LogPrintf("%s: WT^ will spend CTIP: %s : %u.\n", __func__, ctip.out.hash.ToString(), ctip.out.n); // Start calculating amount returning to sidechain CAmount returnAmount = ctip.amount; mtx.vout.back().nValue += returnAmount; // Subtract payout amount from sidechain change return mtx.vout.back().nValue -= amountWithdrawn; if (mtx.vout.back().nValue < 0) return false; if (!mtx.vin.size()) return false; CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(sidechain.sidechainPriv); if (!fGood) return false; CKey privKey = vchSecret.GetKey(); if (!privKey.IsValid()) return false; // Set up keystore with sidechain's private key CBasicKeyStore tempKeystore; tempKeystore.AddKey(privKey); const CKeyStore& keystoreConst = tempKeystore; // Sign WT^ SCUTXO input const CTransaction& txToSign = mtx; TransactionSignatureCreator creator(&keystoreConst, &txToSign, 0, returnAmount - amountWithdrawn); SignatureData sigdata; bool sigCreated = ProduceSignature(creator, sidechainScript, sigdata); if (!sigCreated) return false; mtx.vin[0].scriptSig = sigdata.scriptSig; #endif // Check to make sure that all of the outputs in this WT^ are unknown / new for (size_t o = 0; o < mtx.vout.size(); o++) { if (pcoinsTip->HaveCoin(COutPoint(mtx.GetHash(), o))) { return false; } } tx = mtx; return true; } // Skip entries in mapTx that are already in a block or are present // in mapModifiedTx (which implies that the mapTx ancestor state is // stale due to ancestor inclusion in the block) // Also skip transactions that we've already failed to add. This can happen if // we consider a transaction in mapModifiedTx and it fails: we can then // potentially consider it again while walking mapTx. It's currently // guaranteed to fail again, but as a belt-and-suspenders check we put it in // failedTx and avoid re-evaluation, since the re-evaluation would be using // cached size/sigops/fee values that are not actually correct. bool BlockAssembler::SkipMapTxEntry(CTxMemPool::txiter it, indexed_modified_transaction_set &mapModifiedTx, CTxMemPool::setEntries &failedTx) { assert (it != mempool.mapTx.end()); return mapModifiedTx.count(it) || inBlock.count(it) || failedTx.count(it); } void BlockAssembler::SortForBlock(const CTxMemPool::setEntries& package, CTxMemPool::txiter entry, std::vector<CTxMemPool::txiter>& sortedEntries) { // Sort package by ancestor count // If a transaction A depends on transaction B, then A's ancestor count // must be greater than B's. So this is sufficient to validly order the // transactions for block inclusion. sortedEntries.clear(); sortedEntries.insert(sortedEntries.begin(), package.begin(), package.end()); std::sort(sortedEntries.begin(), sortedEntries.end(), CompareTxIterByAncestorCount()); } // This transaction selection algorithm orders the mempool based // on feerate of a transaction including all unconfirmed ancestors. // Since we don't remove transactions from the mempool as we select them // for block inclusion, we need an alternate method of updating the feerate // of a transaction with its not-yet-selected ancestors as we go. // This is accomplished by walking the in-mempool descendants of selected // transactions and storing a temporary modified state in mapModifiedTxs. // Each time through the loop, we compare the best transaction in // mapModifiedTxs with the next transaction in the mempool to decide what // transaction package to work on next. void BlockAssembler::addPackageTxs(int &nPackagesSelected, int &nDescendantsUpdated, bool fDrivechainEnabled, bool& fNeedCriticalFeeTx, const std::set<uint8_t>& setSidechainsWithWTPrime) { // mapModifiedTx will store sorted packages after they are modified // because some of their txs are already in the block indexed_modified_transaction_set mapModifiedTx; // Keep track of entries that failed inclusion, to avoid duplicate work CTxMemPool::setEntries failedTx; // Start by adding all descendants of previously added txs to mapModifiedTx // and modifying them for their already included ancestors UpdatePackagesForAdded(inBlock, mapModifiedTx); CTxMemPool::indexed_transaction_set::index<ancestor_score>::type::iterator mi = mempool.mapTx.get<ancestor_score>().begin(); CTxMemPool::txiter iter; // Limit the number of attempts to add transactions to the block when it is // close to full; this is just a simple heuristic to finish quickly if the // mempool has a lot of entries. const int64_t MAX_CONSECUTIVE_FAILURES = 1000; int64_t nConsecutiveFailed = 0; while (mi != mempool.mapTx.get<ancestor_score>().end() || !mapModifiedTx.empty()) { // Don't add deposits to the same block as a WT^ for this sidechain if (mi->GetSidechainDeposit() && setSidechainsWithWTPrime.count(mi->GetSidechainNumber())) { ++mi; continue; } // First try to find a new transaction in mapTx to evaluate. if (mi != mempool.mapTx.get<ancestor_score>().end() && SkipMapTxEntry(mempool.mapTx.project<0>(mi), mapModifiedTx, failedTx)) { ++mi; continue; } // Now that mi is not stale, determine which transaction to evaluate: // the next entry from mapTx, or the best from mapModifiedTx? bool fUsingModified = false; modtxscoreiter modit = mapModifiedTx.get<ancestor_score>().begin(); if (mi == mempool.mapTx.get<ancestor_score>().end()) { // We're out of entries in mapTx; use the entry from mapModifiedTx iter = modit->iter; fUsingModified = true; } else { // Try to compare the mapTx entry to the mapModifiedTx entry iter = mempool.mapTx.project<0>(mi); if (modit != mapModifiedTx.get<ancestor_score>().end() && CompareTxMemPoolEntryByAncestorFee()(*modit, CTxMemPoolModifiedEntry(iter))) { // The best entry in mapModifiedTx has higher score // than the one from mapTx. // Switch which transaction (package) to consider iter = modit->iter; fUsingModified = true; } else { // Either no entry in mapModifiedTx, or it's worse than mapTx. // Increment mi for the next loop iteration. ++mi; } } // We skip mapTx entries that are inBlock, and mapModifiedTx shouldn't // contain anything that is inBlock. assert(!inBlock.count(iter)); uint64_t packageSize = iter->GetSizeWithAncestors(); CAmount packageFees = iter->GetModFeesWithAncestors(); int64_t packageSigOpsCost = iter->GetSigOpCostWithAncestors(); if (fUsingModified) { packageSize = modit->nSizeWithAncestors; packageFees = modit->nModFeesWithAncestors; packageSigOpsCost = modit->nSigOpCostWithAncestors; } if (packageFees < blockMinFeeRate.GetFee(packageSize)) { // Everything else we might consider has a lower fee rate return; } if (!TestPackage(packageSize, packageSigOpsCost)) { if (fUsingModified) { // Since we always look at the best entry in mapModifiedTx, // we must erase failed entries so that we can consider the // next best entry on the next loop iteration mapModifiedTx.get<ancestor_score>().erase(modit); failedTx.insert(iter); } ++nConsecutiveFailed; if (nConsecutiveFailed > MAX_CONSECUTIVE_FAILURES && nBlockWeight > nBlockMaxWeight - 4000) { // Give up if we're close to full and haven't succeeded in a while break; } continue; } CTxMemPool::setEntries ancestors; uint64_t nNoLimit = std::numeric_limits<uint64_t>::max(); std::string dummy; mempool.CalculateMemPoolAncestors(*iter, ancestors, nNoLimit, nNoLimit, nNoLimit, nNoLimit, dummy, false); onlyUnconfirmed(ancestors); ancestors.insert(iter); if (!TestPackageTransactions(ancestors)) { if (fUsingModified) { mapModifiedTx.get<ancestor_score>().erase(modit); failedTx.insert(iter); } continue; } // This transaction will make it in; reset the failed counter. nConsecutiveFailed = 0; // Package can be added. Sort the entries in a valid order. std::vector<CTxMemPool::txiter> sortedEntries; SortForBlock(ancestors, iter, sortedEntries); for (size_t i=0; i<sortedEntries.size(); ++i) { AddToBlock(sortedEntries[i]); // Erase from the modified set, if present mapModifiedTx.erase(sortedEntries[i]); // Set fNeedCriticalFeeTx if (fDrivechainEnabled && sortedEntries[i]->HasCriticalData()) fNeedCriticalFeeTx = true; } ++nPackagesSelected; // Update transactions that depend on each of these nDescendantsUpdated += UpdatePackagesForAdded(ancestors, mapModifiedTx); } } void IncrementExtraNonce(CBlock* pblock, const CBlockIndex* pindexPrev, unsigned int& nExtraNonce) { // Update nExtraNonce static uint256 hashPrevBlock; if (hashPrevBlock != pblock->hashPrevBlock) { nExtraNonce = 0; hashPrevBlock = pblock->hashPrevBlock; } ++nExtraNonce; unsigned int nHeight = pindexPrev->nHeight+1; // Height first in coinbase required for block.version=2 CMutableTransaction txCoinbase(*pblock->vtx[0]); txCoinbase.vin[0].scriptSig = (CScript() << nHeight << CScriptNum(nExtraNonce)) + COINBASE_FLAGS; assert(txCoinbase.vin[0].scriptSig.size() <= 100); pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase)); pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); } ////////////////////////////////////////////////////////////////////////////// // // Internal miner // // // ScanHash scans nonces looking for a hash with at least some zero bits. // The nonce is usually preserved between calls, but periodically or if the // nonce is 0xffff0000 or above, the block is rebuilt and nNonce starts over at // zero. // bool static ScanHash(const CBlockHeader *pblock, uint32_t& nNonce, uint256 *phash) { // Write the first 76 bytes of the block header to a double-SHA256 state. SHAndwich256 hasher; CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << *pblock; assert(ss.size() == 80); hasher.Write((unsigned char*)&ss[0], 76); while (true) { nNonce++; if (nNonce > nMiningNonce) nMiningNonce = nNonce; // Write the last 4 bytes of the block header (the nonce) to a copy of // the double-SHA256 state, and compute the result. SHAndwich256(hasher).Write((unsigned char*)&nNonce, 4).Finalize((unsigned char*)phash); // Return the nonce if the hash has at least some zero bits, // caller will check if it has enough to reach the target if (((uint16_t*)phash)[15] == 0) return true; // If nothing found after trying for a while, return -1 if ((nNonce & 0xfff) == 0) return false; } } static bool ProcessBlockFound(const CBlock* pblock, const CChainParams& chainparams) { LogPrintf("%s\n", pblock->ToString()); LogPrintf("generated %s\n", FormatMoney(pblock->vtx[0]->vout[0].nValue)); // Found a solution { LOCK(cs_main); if (pblock->hashPrevBlock != chainActive.Tip()->GetBlockHash()) return error("BitcoinMiner: generated block is stale"); } // Inform about the new block GetMainSignals().BlockFound(pblock->GetHash()); // Process this block the same as if we had received it from another node std::shared_ptr<const CBlock> block = std::make_shared<CBlock>(*pblock); CValidationState state; if (!ProcessNewBlock(Params(), block, true, nullptr)) return error("BitcoinMiner: ProcessNewBlock, block not accepted"); return true; } void static BitcoinMiner(const CChainParams& chainparams) { LogPrintf("BitcoinMiner started\n"); //SetThreadPriority(THREAD_PRIORITY_LOWEST); RenameThread("drivenet-miner"); unsigned int nExtraNonce = 0; if (vpwallets.empty()) return; // TODO error message std::shared_ptr<CReserveScript> coinbaseScript; vpwallets[0]->GetScriptForMining(coinbaseScript); bool fBreakForBMM = gArgs.GetBoolArg("-minerbreakforbmm", false); int nBMMBreakAttempts = 0; try { // Throw an error if no script was provided. This can happen // due to some internal error but also if the keypool is empty. // In the latter case, already the pointer is NULL. if (!coinbaseScript || coinbaseScript->reserveScript.empty()) throw std::runtime_error("No coinbase script available (mining requires a wallet)"); while (true) { if (fMiningReqiresPeer) { // Busy-wait for the network to come online so we don't waste time mining // on an obsolete chain. In regtest mode we expect to fly solo. // TODO /* do { bool fvNodesEmpty; { LOCK(cs_vNodes); fvNodesEmpty = vNodes.empty(); } if (!fvNodesEmpty && !IsInitialBlockDownload()) break; MilliSleep(1000); } while (true); */ } // // Create new block // unsigned int nTransactionsUpdatedLast = mempool.GetTransactionsUpdated(); CBlockIndex* pindexPrev = chainActive.Tip(); bool fAddedBMM = false; int nMinerSleep = gArgs.GetArg("-minersleep", 0); if (nMinerSleep) MilliSleep(nMinerSleep); std::unique_ptr<CBlockTemplate> pblocktemplate(BlockAssembler(Params()).CreateNewBlock(coinbaseScript->reserveScript, true /* mine segwit */, fAddedBMM)); if (!pblocktemplate.get()) { LogPrintf("Error in BitcoinMiner: Keypool ran out, please call keypoolrefill before restarting the mining thread\n"); return; } CBlock *pblock = &pblocktemplate->block; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); LogPrintf("Running BitcoinMiner with %u transactions in block (%u bytes)\n", pblock->vtx.size(), ::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION)); // // Search // int64_t nStart = GetTime(); arith_uint256 hashArithTarget = arith_uint256().SetCompact(pblock->nBits); hashTarget = ArithToUint256(hashArithTarget); hashBest = uint256S("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); nMiningNonce = 0; uint256 hash; uint32_t nNonce = 0; while (true) { // Check if something found if (ScanHash(pblock, nNonce, &hash)) { if (UintToArith256(hash) <= UintToArith256(hashBest)) { hashBest = hash; } if (UintToArith256(hash) <= hashArithTarget) { // Found a solution pblock->nNonce = nNonce; assert(hash == pblock->GetPoWHash()); LogPrintf("BitcoinMiner:\n"); LogPrintf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex(), hashArithTarget.GetHex()); ProcessBlockFound(pblock, chainparams); coinbaseScript->KeepScript(); nBMMBreakAttempts = 0; break; } } // Check for stop or if block needs to be rebuilt boost::this_thread::interruption_point(); // Regtest mode doesn't require peers // TODO /* if (vNodes.empty() && fMiningRequiresPeer) break; */ if (nNonce >= 0xffff0000) break; if (mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60) break; if (pindexPrev != chainActive.Tip()) { nBMMBreakAttempts = 0; break; } // Update nTime every few seconds if (UpdateTime(pblock, chainparams.GetConsensus(), pindexPrev) < 0) break; // Recreate the block if the clock has run backwards, // so that we can use the correct time. // If the user has set --minerbreakforbmm, and BMM txns were not // already added to this block but exist in the mempool, break // the miner so that it recreates the block. if (fBreakForBMM && !fAddedBMM && nBMMBreakAttempts < 10 && mempool.GetCriticalTxnAddedSinceBlock()) { nBMMBreakAttempts++; break; } if (chainparams.GetConsensus().fPowAllowMinDifficultyBlocks) { // Changing pblock->nTime can change work required on testnet: hashArithTarget.SetCompact(pblock->nBits); } } } } catch (const boost::thread_interrupted&) { LogPrintf("BitcoinMiner terminated\n"); throw; } catch (const std::runtime_error &e) { LogPrintf("BitcoinMiner runtime error: %s\n", e.what()); return; } } void GenerateBitcoins(bool fGenerate, int nThreads, const CChainParams& chainparams) { static boost::thread_group* minerThreads = NULL; if (nThreads < 0) nThreads = GetNumCores(); if (minerThreads != NULL) { minerThreads->interrupt_all(); delete minerThreads; minerThreads = NULL; } if (nThreads == 0 || !fGenerate) return; minerThreads = new boost::thread_group(); for (int i = 0; i < nThreads; i++) minerThreads->create_thread(boost::bind(&BitcoinMiner, boost::cref(chainparams))); }
39.986842
266
0.617761
[ "vector" ]
b1bc089d216e166adaf818d0ea6d65ed1861a963
2,557
cpp
C++
BGL/examples/BGL_triangulation_2/dijkstra_with_internal_properties.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
3,227
2015-03-05T00:19:18.000Z
2022-03-31T08:20:35.000Z
BGL/examples/BGL_triangulation_2/dijkstra_with_internal_properties.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
5,574
2015-03-05T00:01:56.000Z
2022-03-31T15:08:11.000Z
BGL/examples/BGL_triangulation_2/dijkstra_with_internal_properties.cpp
ffteja/cgal
c1c7f4ad9a4cd669e33ca07a299062a461581812
[ "CC0-1.0" ]
1,274
2015-03-05T00:01:12.000Z
2022-03-31T14:47:56.000Z
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Triangulation_vertex_base_with_id_2.h> #include <CGAL/boost/graph/graph_traits_Delaunay_triangulation_2.h> #include <CGAL/boost/graph/dijkstra_shortest_paths.h> #include <fstream> typedef CGAL::Exact_predicates_inexact_constructions_kernel K; typedef K::Point_2 Point; typedef CGAL::Triangulation_vertex_base_with_id_2<K> Tvb; typedef CGAL::Triangulation_face_base_2<K> Tfb; typedef CGAL::Triangulation_data_structure_2<Tvb, Tfb> Tds; typedef CGAL::Delaunay_triangulation_2<K, Tds> Triangulation; typedef boost::graph_traits<Triangulation>::vertex_descriptor vertex_descriptor; typedef boost::graph_traits<Triangulation>::vertex_iterator vertex_iterator; typedef boost::property_map<Triangulation, boost::vertex_index_t>::type VertexIdPropertyMap; int main(int argc,char* argv[]) { const char* filename = (argc > 1) ? argv[1] : "data/points.xy"; std::ifstream input(filename); Triangulation tr; Point p; while(input >> p) tr.insert(p); // associate indices to the vertices int index = 0; for(vertex_descriptor vd : vertices(tr)) vd->id()= index++; VertexIdPropertyMap vertex_index_pmap = get(boost::vertex_index, tr); // Dijkstra's shortest path needs property maps for the predecessor and distance std::vector<vertex_descriptor> predecessor(num_vertices(tr)); boost::iterator_property_map<std::vector<vertex_descriptor>::iterator, VertexIdPropertyMap> predecessor_pmap(predecessor.begin(), vertex_index_pmap); std::vector<double> distance(num_vertices(tr)); boost::iterator_property_map<std::vector<double>::iterator, VertexIdPropertyMap> distance_pmap(distance.begin(), vertex_index_pmap); vertex_descriptor source = *vertices(tr).first; std::cout << "\nStart dijkstra_shortest_paths at " << source->point() << std::endl; boost::dijkstra_shortest_paths(tr, source, distance_map(distance_pmap) .predecessor_map(predecessor_pmap)); for(vertex_descriptor vd : vertices(tr)) { std::cout << vd->point() << " [" << vd->id() << "] "; std::cout << " has distance = " << get(distance_pmap,vd) << " and predecessor "; vd = get(predecessor_pmap,vd); std::cout << vd->point() << " [" << vd->id() << "]\n"; } return EXIT_SUCCESS; }
38.164179
93
0.682831
[ "vector" ]
04d8b5bcd71bec3ab1cd707ff09364b8e7a7de5c
10,615
cc
C++
mediapipe/calculators/util/detections_to_render_data_calculator_test.cc
justin-f-perez/mediapipe
f4e7f6cc48e89a4702860a370c431e56568800d1
[ "Apache-2.0" ]
55
2020-08-06T05:57:42.000Z
2022-03-16T08:37:22.000Z
mediapipe/calculators/util/detections_to_render_data_calculator_test.cc
justin-f-perez/mediapipe
f4e7f6cc48e89a4702860a370c431e56568800d1
[ "Apache-2.0" ]
3
2021-02-18T07:07:47.000Z
2021-09-19T18:33:32.000Z
mediapipe/calculators/util/detections_to_render_data_calculator_test.cc
justin-f-perez/mediapipe
f4e7f6cc48e89a4702860a370c431e56568800d1
[ "Apache-2.0" ]
14
2020-08-28T01:26:37.000Z
2022-02-13T04:10:44.000Z
// Copyright 2019 The MediaPipe 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 "absl/memory/memory.h" #include "mediapipe/calculators/util/detections_to_render_data_calculator.pb.h" #include "mediapipe/framework/calculator.pb.h" #include "mediapipe/framework/calculator_framework.h" #include "mediapipe/framework/calculator_runner.h" #include "mediapipe/framework/deps/message_matchers.h" #include "mediapipe/framework/formats/detection.pb.h" #include "mediapipe/framework/formats/location_data.pb.h" #include "mediapipe/framework/packet.h" #include "mediapipe/framework/port/gmock.h" #include "mediapipe/framework/port/gtest.h" #include "mediapipe/framework/port/parse_text_proto.h" #include "mediapipe/framework/port/status_matchers.h" #include "mediapipe/util/color.pb.h" #include "mediapipe/util/render_data.pb.h" namespace mediapipe { constexpr char kDetectionsTag[] = "DETECTIONS"; constexpr char kRenderDataTag[] = "RENDER_DATA"; constexpr char kDetectionListTag[] = "DETECTION_LIST"; using ::testing::DoubleNear; // Error tolerance for pixels, distances, etc. static constexpr double kErrorTolerance = 1e-5; void VerifyRenderAnnotationColorThickness( const RenderAnnotation& annotation, const DetectionsToRenderDataCalculatorOptions& options) { EXPECT_THAT(annotation.color(), EqualsProto(options.color())); EXPECT_EQ(annotation.thickness(), options.thickness()); } LocationData CreateLocationData(int32 xmin, int32 ymin, int32 width, int32 height) { LocationData location_data; location_data.set_format(LocationData::BOUNDING_BOX); location_data.mutable_bounding_box()->set_xmin(xmin); location_data.mutable_bounding_box()->set_ymin(ymin); location_data.mutable_bounding_box()->set_width(width); location_data.mutable_bounding_box()->set_height(height); return location_data; } LocationData CreateRelativeLocationData(double xmin, double ymin, double width, double height) { LocationData location_data; location_data.set_format(LocationData::RELATIVE_BOUNDING_BOX); location_data.mutable_relative_bounding_box()->set_xmin(xmin); location_data.mutable_relative_bounding_box()->set_ymin(ymin); location_data.mutable_relative_bounding_box()->set_width(width); location_data.mutable_relative_bounding_box()->set_height(height); return location_data; } Detection CreateDetection(const std::vector<std::string>& labels, const std::vector<int32>& label_ids, const std::vector<float>& scores, const LocationData& location_data, const std::string& feature_tag) { Detection detection; for (const auto& label : labels) { detection.add_label(label); } for (const auto& label_id : label_ids) { detection.add_label_id(label_id); } for (const auto& score : scores) { detection.add_score(score); } *(detection.mutable_location_data()) = location_data; detection.set_feature_tag(feature_tag); return detection; } TEST(DetectionsToRenderDataCalculatorTest, OnlyDetecctionList) { CalculatorRunner runner(ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb( calculator: "DetectionsToRenderDataCalculator" input_stream: "DETECTION_LIST:detection_list" output_stream: "RENDER_DATA:render_data" )pb")); LocationData location_data = CreateLocationData(100, 200, 300, 400); auto detections(absl::make_unique<DetectionList>()); *(detections->add_detection()) = CreateDetection({"label1"}, {}, {0.3}, location_data, "feature_tag"); runner.MutableInputs() ->Tag(kDetectionListTag) .packets.push_back( Adopt(detections.release()).At(Timestamp::PostStream())); MP_ASSERT_OK(runner.Run()) << "Calculator execution failed."; const std::vector<Packet>& output = runner.Outputs().Tag(kRenderDataTag).packets; ASSERT_EQ(1, output.size()); const auto& actual = output[0].Get<RenderData>(); EXPECT_EQ(actual.render_annotations_size(), 3); // Labels EXPECT_EQ(actual.render_annotations(0).text().display_text(), "label1,0.3,"); // Feature tag EXPECT_EQ(actual.render_annotations(1).text().display_text(), "feature_tag"); // Location data EXPECT_EQ(actual.render_annotations(2).rectangle().left(), 100); EXPECT_EQ(actual.render_annotations(2).rectangle().right(), 100 + 300); EXPECT_EQ(actual.render_annotations(2).rectangle().top(), 200); EXPECT_EQ(actual.render_annotations(2).rectangle().bottom(), 200 + 400); } TEST(DetectionsToRenderDataCalculatorTest, OnlyDetecctionVector) { CalculatorRunner runner{ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb( calculator: "DetectionsToRenderDataCalculator" input_stream: "DETECTIONS:detections" output_stream: "RENDER_DATA:render_data" )pb")}; LocationData location_data = CreateLocationData(100, 200, 300, 400); auto detections(absl::make_unique<std::vector<Detection>>()); detections->push_back( CreateDetection({"label1"}, {}, {0.3}, location_data, "feature_tag")); runner.MutableInputs() ->Tag(kDetectionsTag) .packets.push_back( Adopt(detections.release()).At(Timestamp::PostStream())); MP_ASSERT_OK(runner.Run()) << "Calculator execution failed."; const std::vector<Packet>& output = runner.Outputs().Tag(kRenderDataTag).packets; ASSERT_EQ(1, output.size()); const auto& actual = output[0].Get<RenderData>(); EXPECT_EQ(actual.render_annotations_size(), 3); // Labels EXPECT_EQ(actual.render_annotations(0).text().display_text(), "label1,0.3,"); // Feature tag EXPECT_EQ(actual.render_annotations(1).text().display_text(), "feature_tag"); // Location data EXPECT_EQ(actual.render_annotations(2).rectangle().left(), 100); EXPECT_EQ(actual.render_annotations(2).rectangle().right(), 100 + 300); EXPECT_EQ(actual.render_annotations(2).rectangle().top(), 200); EXPECT_EQ(actual.render_annotations(2).rectangle().bottom(), 200 + 400); } TEST(DetectionsToRenderDataCalculatorTest, BothDetecctionListAndVector) { CalculatorRunner runner{ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb( calculator: "DetectionsToRenderDataCalculator" input_stream: "DETECTION_LIST:detection_list" input_stream: "DETECTIONS:detections" output_stream: "RENDER_DATA:render_data" )pb")}; LocationData location_data1 = CreateLocationData(100, 200, 300, 400); auto detection_list(absl::make_unique<DetectionList>()); *(detection_list->add_detection()) = CreateDetection({"label1"}, {}, {0.3}, location_data1, "feature_tag1"); runner.MutableInputs() ->Tag(kDetectionListTag) .packets.push_back( Adopt(detection_list.release()).At(Timestamp::PostStream())); LocationData location_data2 = CreateLocationData(600, 700, 800, 900); auto detections(absl::make_unique<std::vector<Detection>>()); detections->push_back( CreateDetection({"label2"}, {}, {0.6}, location_data2, "feature_tag2")); runner.MutableInputs() ->Tag(kDetectionsTag) .packets.push_back( Adopt(detections.release()).At(Timestamp::PostStream())); MP_ASSERT_OK(runner.Run()) << "Calculator execution failed."; const std::vector<Packet>& actual = runner.Outputs().Tag(kRenderDataTag).packets; ASSERT_EQ(1, actual.size()); // Check the feature tag for item from detection list. EXPECT_EQ( actual[0].Get<RenderData>().render_annotations(1).text().display_text(), "feature_tag1"); // Check the feature tag for item from detection vector. EXPECT_EQ( actual[0].Get<RenderData>().render_annotations(4).text().display_text(), "feature_tag2"); } TEST(DetectionsToRenderDataCalculatorTest, ProduceEmptyPacket) { // Check when produce_empty_packet is false. CalculatorRunner runner1{ ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb( calculator: "DetectionsToRenderDataCalculator" input_stream: "DETECTION_LIST:detection_list" input_stream: "DETECTIONS:detections" output_stream: "RENDER_DATA:render_data" options { [mediapipe.DetectionsToRenderDataCalculatorOptions.ext] { produce_empty_packet: false } } )pb")}; auto detection_list1(absl::make_unique<DetectionList>()); runner1.MutableInputs() ->Tag(kDetectionListTag) .packets.push_back( Adopt(detection_list1.release()).At(Timestamp::PostStream())); auto detections1(absl::make_unique<std::vector<Detection>>()); runner1.MutableInputs() ->Tag(kDetectionsTag) .packets.push_back( Adopt(detections1.release()).At(Timestamp::PostStream())); MP_ASSERT_OK(runner1.Run()) << "Calculator execution failed."; const std::vector<Packet>& exact1 = runner1.Outputs().Tag(kRenderDataTag).packets; ASSERT_EQ(0, exact1.size()); // Check when produce_empty_packet is true. CalculatorRunner runner2{ ParseTextProtoOrDie<CalculatorGraphConfig::Node>(R"pb( calculator: "DetectionsToRenderDataCalculator" input_stream: "DETECTION_LIST:detection_list" input_stream: "DETECTIONS:detections" output_stream: "RENDER_DATA:render_data" options { [mediapipe.DetectionsToRenderDataCalculatorOptions.ext] { produce_empty_packet: true } } )pb")}; auto detection_list2(absl::make_unique<DetectionList>()); runner2.MutableInputs() ->Tag(kDetectionListTag) .packets.push_back( Adopt(detection_list2.release()).At(Timestamp::PostStream())); auto detections2(absl::make_unique<std::vector<Detection>>()); runner2.MutableInputs() ->Tag(kDetectionsTag) .packets.push_back( Adopt(detections2.release()).At(Timestamp::PostStream())); MP_ASSERT_OK(runner2.Run()) << "Calculator execution failed."; const std::vector<Packet>& exact2 = runner2.Outputs().Tag(kRenderDataTag).packets; ASSERT_EQ(1, exact2.size()); EXPECT_EQ(exact2[0].Get<RenderData>().render_annotations_size(), 0); } } // namespace mediapipe
40.056604
80
0.722751
[ "vector" ]
04dcaafa92a78c98ec6706340ecced94039fb705
1,312
cpp
C++
source/backend/hiai/execution/NPUConcat.cpp
WillTao-RD/MNN
48575121859093bab8468d6992596962063b7aff
[ "Apache-2.0" ]
2
2020-12-15T13:56:31.000Z
2022-01-26T03:20:28.000Z
source/backend/hiai/execution/NPUConcat.cpp
qaz734913414/MNN
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
[ "Apache-2.0" ]
null
null
null
source/backend/hiai/execution/NPUConcat.cpp
qaz734913414/MNN
a5d5769789054a76c6e4dce2ef97d1f45b0e7e2d
[ "Apache-2.0" ]
1
2021-11-24T06:26:27.000Z
2021-11-24T06:26:27.000Z
// // NPUConcat.cpp // MNN // // Created by MNN on 2019/09/11. // Copyright ยฉ 2018, Alibaba Group Holding Limited // #include "NPUConcat.hpp" #include "NPUBackend.hpp" using namespace std; namespace MNN { NPUConcat::NPUConcat(Backend *b, const Op *op, const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) : MNN::NPUCommonExecution(b,op) { } ErrorCode NPUConcat::onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) { mNpuBackend->setNetworkInput(inputs, mOp); auto opName = mOp->name()->str(); auto param = mOp->main_as_Axis(); shared_ptr<ge::op::Concat> concat(new ge::op::Concat(opName)); auto inputSize = mOp->inputIndexes()->size(); (*concat).create_dynamic_input_x(inputSize).set_attr_axis(axisFormat(inputs[0], param->axis())); for (int i = 0; i < inputSize; ++i) { auto inputIndex = mOp->inputIndexes()->data()[i]; auto iops = mNpuBackend->mGrapMap[inputIndex]; // x auto xOp = iops.back().first; ge::Operator *px = (ge::Operator *)xOp.get(); (*concat).set_dynamic_input_x(i + 1, *px); } mNpuBackend->setOutputOps(mOp, {concat}); return NO_ERROR; } NPUCreatorRegister<TypedCreator<NPUConcat>> __concat_op(OpType_Concat); } // namespace MNN
27.914894
155
0.652439
[ "vector" ]
04dd0ce9ef9724f90c3e577a7a63f550b5ceff0d
3,200
hpp
C++
source/backend/cpu/CPUDeconvolution.hpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
3
2020-09-26T03:40:17.000Z
2021-12-26T06:58:11.000Z
source/backend/cpu/CPUDeconvolution.hpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
null
null
null
source/backend/cpu/CPUDeconvolution.hpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
null
null
null
// // CPUDeconvolution.hpp // MNN // // Created by MNN on 2018/07/20. // Copyright ยฉ 2018, Alibaba Group Holding Limited // #ifndef CPUDeconvolution_hpp #define CPUDeconvolution_hpp #include "CPUConvolution.hpp" #include "compute/StrassenMatmulComputor.hpp" namespace MNN { class CPUDeconvolutionBasic : public CPUConvolution { public: CPUDeconvolutionBasic(const Tensor *input, const Op *convOp, Backend *b); virtual ~CPUDeconvolutionBasic() = default; virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; protected: int mSrcCount; }; class CPUDeconvolutionCommon : public CPUDeconvolutionBasic { public: CPUDeconvolutionCommon(const Tensor *input, const Op *convOp, Backend *b); virtual ~CPUDeconvolutionCommon(); protected: std::shared_ptr<Tensor> mBias; }; class CPUDeconvolutionOrigin : public CPUDeconvolutionBasic { public: CPUDeconvolutionOrigin(const Tensor *input, const Op *convOp, Backend *b) : CPUDeconvolutionBasic(input, convOp, b) { // Do nothing } virtual ~CPUDeconvolutionOrigin() = default; virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; private: std::shared_ptr<StrassenMatrixComputor> mMatMul; std::vector<std::pair<std::function<void(const float*, int)>, int>> mPreFunctions; std::vector<std::pair<std::function<void(float*, int)>, int>> mPostFunctions; }; class CPUDeconvolutionMultiInput : public CPUDeconvolutionBasic { public: CPUDeconvolutionMultiInput(const Tensor *input, const Op *convOp, Backend *b) : CPUDeconvolutionBasic(input, convOp, b) { mOrigin.reset(new CPUDeconvolutionOrigin(input, convOp, b)); } virtual ~CPUDeconvolutionMultiInput() = default; virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override; private: std::shared_ptr<Tensor> mWeight; std::shared_ptr<Tensor> mCacheWeight; std::shared_ptr<Tensor> mBias; std::vector<Tensor *> mTempInputs; std::shared_ptr<CPUDeconvolutionOrigin> mOrigin; }; class CPUDeconvolution : public CPUDeconvolutionCommon { public: CPUDeconvolution(const Tensor *input, const Op *convOp, Backend *b); virtual ~CPUDeconvolution(); virtual ErrorCode onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override { mOrigin->onExecute(mTempInputs, outputs); return NO_ERROR; } virtual ErrorCode onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) override { mTempInputs = {inputs[0], mWeight.get(), mBias.get()}; return mOrigin->onResize(mTempInputs, outputs); } private: std::shared_ptr<Tensor> mWeight; std::vector<Tensor *> mTempInputs; std::shared_ptr<CPUDeconvolutionOrigin> mOrigin; }; } // namespace MNN #endif /* CPUDeconvolution_hpp */
36.363636
117
0.723125
[ "vector" ]
04e7e0586c7eb42c0823c339a208cdc462fe7ad9
5,647
cpp
C++
geo/arc.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
10
2016-12-28T22:06:31.000Z
2021-05-24T13:42:30.000Z
geo/arc.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
4
2015-10-09T23:55:10.000Z
2020-04-04T08:09:22.000Z
geo/arc.cpp
lukas-ke/faint-graphics-editor
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
[ "Apache-2.0" ]
null
null
null
// -*- coding: us-ascii-unix -*- // Copyright 2012 Lukas Kemmer // // 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 <cassert> #include <cmath> #include "geo/angle.hh" #include "geo/arc.hh" #include "geo/pathpt.hh" #include "geo/tri.hh" namespace faint{ AngleSpan::AngleSpan() : start(Angle::Zero()), stop(Angle::Zero()) {} AngleSpan AngleSpan::Rad(coord start, coord stop){ return {Angle::Rad(start), Angle::Rad(stop)}; } AngleSpan::AngleSpan(const Angle& start, const Angle& stop) : start(start), stop(stop) {} bool AngleSpan::Empty() const{ return start == stop; } Angle AngleSpan::Length() const{ return stop - start; } int required_curve_count(const AngleSpan& angles){ Angle span = abs(angles.Length()); if (span <= pi / 2){ return 2; } else if (span <= pi){ return 4; } else if (span <= 3 * pi / 2){ return 6; } return 8; } ArcEndPoints::ArcEndPoints(const Tri& tri, const AngleSpan& angles){ const coord rx = tri.Width() / 2; const coord ry = tri.Height() / 2; const coord aCosEta1 = rx * cos(angles.start); const coord bSinEta1 = ry * sin(angles.start); const auto mainAngle = tri.GetAngle(); const coord cosTheta = cos(mainAngle); const coord sinTheta = sin(mainAngle); const Point c(center_point(tri)); const coord x1 = c.x + aCosEta1 * cosTheta - bSinEta1 * sinTheta; const coord y1 = c.y + aCosEta1 * sinTheta + bSinEta1 * cosTheta; // end point const double aCosEta2 = rx * cos(angles.stop); const double bSinEta2 = ry * sin(angles.stop); const coord x2 = c.x + aCosEta2 * cosTheta - bSinEta2 * sinTheta; const coord y2 = c.y + aCosEta2 * sinTheta + bSinEta2 * cosTheta; p0 = Point(x1, y1); p1 = Point(x2, y2); } Point ArcEndPoints::operator[](size_t i) const{ assert(i <= 1); return i == 0 ? p0 : p1; } std::vector<Point> ArcEndPoints::GetVector() const{ return {p0, p1}; } std::vector<PathPt> arc_as_path(const Tri& tri, const AngleSpan& angles, bool arcSides) { // This algorithm is based on documentation and code from // SpaceRoots.org, by L. Maisonobe "Drawing an elliptical arc using // polylines, quadratic or cubic Bezier curves" and // "EllipticalArc.java" Available here: // http://www.spaceroots.org/downloads.html const int numCurves = required_curve_count(angles); const double rx = tri.Width() / 2.0; const double ry = tri.Height() / 2.0; const Angle mainAngle(tri.GetAngle()); const Point c(center_point(tri)); Angle curveSpan = (angles.stop - angles.start) / numCurves; Angle currentAngle = angles.start; coord cosCurrentAngle = cos(currentAngle); coord sinCurrentAngle = sin(currentAngle); coord rxCosCurrentAngle = rx * cosCurrentAngle; coord rySinCurrentAngle = ry * sinCurrentAngle; coord rxSinCurrentAngle = rx * sinCurrentAngle; coord ryCosCurrentAngle = ry * cosCurrentAngle; coord sinMainAngle = sin(mainAngle); coord cosMainAngle = cos(mainAngle); coord x = c.x + rxCosCurrentAngle * cosMainAngle - rySinCurrentAngle * sinMainAngle; coord y = c.y + rxCosCurrentAngle * sinMainAngle + rySinCurrentAngle * cosMainAngle; coord xDot = -rxSinCurrentAngle * cosMainAngle - ryCosCurrentAngle * sinMainAngle; coord yDot = -rxSinCurrentAngle * sinMainAngle + ryCosCurrentAngle * cosMainAngle; std::vector<PathPt> v; if (arcSides){ // Start at the tri center v.emplace_back(MoveTo({c.x, c.y})); // Arc start point v.emplace_back(LineTo({x, y})); } else{ v.emplace_back(MoveTo({x, y})); } coord t = tan(0.5 * curveSpan); coord alpha = sin(curveSpan) * (std::sqrt(4 + 3 * t * t) - 1) / 3.0; for (int i = 0; i != numCurves; i++){ coord prevX = x; coord prevY = y; double prevXDot = xDot; double prevYDot = yDot; currentAngle += curveSpan; cosCurrentAngle = cos(currentAngle); sinCurrentAngle = sin(currentAngle); rxCosCurrentAngle = rx * cosCurrentAngle; rySinCurrentAngle = ry * sinCurrentAngle; rxSinCurrentAngle = rx * sinCurrentAngle; ryCosCurrentAngle = ry * cosCurrentAngle; x = c.x + rxCosCurrentAngle * cosMainAngle - rySinCurrentAngle * sinMainAngle; y = c.y + rxCosCurrentAngle * sinMainAngle + rySinCurrentAngle * cosMainAngle; xDot = -rxSinCurrentAngle * cosMainAngle - ryCosCurrentAngle * sinMainAngle; yDot = -rxSinCurrentAngle * sinMainAngle + ryCosCurrentAngle * cosMainAngle; v.emplace_back(CubicBezier({x,y}, {prevX + alpha * prevXDot, prevY + alpha * prevYDot}, {x - alpha * xDot, y - alpha * yDot})); } if (arcSides){ v.emplace_back(Close()); } return v; } coord arc_area(const Radii& r, const AngleSpan& angles){ // Based on "The Area of Intersecting Ellipses" by Dave Eberly // http://www.geometrictools.com/Documentation/AreaIntersectingEllipses.pdf auto F = [a=r.x, b=r.y](coord theta){ return ((a*b)/2) * (theta - std::atan( ((b - a)*std::sin(2*theta)) / (b + a + (b - a)*std::cos(2*theta)))); }; return F(angles.stop.Rad()) - F(angles.start.Rad()); } coord circle_arc_area(coord r, const Angle& a){ return sq(r) * a.Rad() / 2; } } // namespace
29.878307
82
0.67682
[ "vector" ]
04e8d35e9cbb16ef8911f632c1df4f8beb929e07
3,513
cpp
C++
doc/howto/write_a_view/solution_iterator.cpp
dendisuhubdy/seqan3
6903e67267fe50907f377cca7ef3d51f1447c504
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
doc/howto/write_a_view/solution_iterator.cpp
dendisuhubdy/seqan3
6903e67267fe50907f377cca7ef3d51f1447c504
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
doc/howto/write_a_view/solution_iterator.cpp
dendisuhubdy/seqan3
6903e67267fe50907f377cca7ef3d51f1447c504
[ "CC0-1.0", "CC-BY-4.0" ]
null
null
null
//![start] #include <iostream> #include <vector> #include <seqan3/alphabet/nucleotide/all.hpp> #include <seqan3/std/ranges> using namespace seqan3; template <std::ranges::forward_range urng_t> // the underlying range type struct my_iterator : std::ranges::iterator_t<urng_t> { //![start] //![static_assert] static_assert(nucleotide_alphabet<std::ranges::range_reference_t<urng_t>>, "You can only iterate over ranges of nucleotides!"); //![static_assert] //![solution1a] using base_t = std::ranges::iterator_t<urng_t>; // these member types are just exposed from the base type using value_type = typename std::iterator_traits<base_t>::value_type; using pointer = typename std::iterator_traits<base_t>::pointer; //![solution1a] //![reference] // If the value_type is seqan3::dna5, the reference type of the vector is // seqan3::dna5 & and operator* returns this so you can change the values // in the vector through it's iterator. // This won't work anymore, because now we are creating new values on access // so we now need to change this type to reflect that: using reference = value_type; //![reference] //![solution1b] // this member type is explicitly set to forward_iterator_tag because we are not // implementing the remaining requirements using iterator_category = std::forward_iterator_tag; // the following operators need to be explicitly defined, because the inherited // version has wrong return types (base_t instead of my_iterator) my_iterator & operator++() { base_t::operator++(); // call the implementation of the base type return *this; } my_iterator operator++(int) { my_iterator cpy{*this}; ++(*this); return cpy; } // we do not need to define constructors, because {}-initialising this with one argument // calls the base-class's constructor which is what we want // NOTE: depending on your view/iterator, you might need/want to define your own // we do not need to define comparison operators, because there are comparison operators // for the base class and our type is implicitly convertible to the base type // NOTE: in our case comparing the converted-to-base iterator with end behaves as desired, // but it strongly depends on your view/iterator whether the same holds //![solution1b] //![dereference] // The operator* facilitates the access to the element. // This implementation calls the base class's implementation but passes the return value // through the seqan3::complement() function before returning it. reference operator*() const { return complement(base_t::operator*()); } //![dereference] //![end] }; // verify that your type models the concept static_assert(std::forward_iterator<my_iterator<std::vector<dna5>>>); int main() { std::vector<dna5> vec{"GATTACA"_dna5}; // instantiate the template over the underlying vector's iterator and sentinel // (for all standard containers the sentinel type is the same as the iterator type) using my_it_concrete = my_iterator<std::vector<dna5>>; // create an iterator that is constructed with vec.begin() as the underlying iterator my_it_concrete it{vec.begin()}; // iterate over vec, but with your custom iterator while (it != vec.end()) std::cout << to_char(*it++) << ' '; } //![end]
36.59375
94
0.681469
[ "vector" ]
04ee7def1c32d67ecb1a3068c81f7e61cc280f56
3,508
cpp
C++
tests/write_traits/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
20
2019-11-13T12:31:20.000Z
2022-02-27T12:30:39.000Z
tests/write_traits/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
46
2019-11-15T20:40:18.000Z
2022-03-31T19:04:36.000Z
tests/write_traits/client.cpp
ClausKlein/taox11
669cfd2d0be258722c7ee32b23f2e5cb83e4520f
[ "MIT" ]
5
2019-11-12T15:00:50.000Z
2022-01-17T17:33:05.000Z
/** * @file client.cpp * @author Unknown * @brief Client main * * Generated by 'brix11 generate client' @ 2014-03-02 15:41:45 +0100 * * @copyright Copyright (c) Remedy IT Expertise BV */ #include "write_traitsC.h" #include "ace/Get_Opt.h" #include "testlib/taox11_testlog.h" std::string ior = "file://server.ior"; bool parse_args (int argc, ACE_TCHAR *argv[]) { ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("k:")); int c; while ((c = get_opts ()) != -1) switch (c) { case 'k': ior = get_opts.opt_arg (); break; case '?': default: TAOX11_TEST_ERROR << "usage: -k <ior>" << std::endl; return false; } // Indicates successful parsing of the command line return true; } int main(int argc, char* argv[]) { try { IDL::traits<CORBA::ORB>::ref_type _orb = CORBA::ORB_init (argc, argv); if (_orb == nullptr) { TAOX11_TEST_ERROR << "ERROR: CORBA::ORB_init (argc, argv) returned null ORB." << std::endl; return 1; } if (parse_args (argc, argv) == false) return 1; IDL::traits<CORBA::Object>::ref_type obj = _orb->string_to_object (ior); if (!obj) { TAOX11_TEST_ERROR << "ERROR: string_to_object(<ior>) returned null reference." << std::endl; return 1; } TAOX11_TEST_INFO << "retrieved object reference" << std::endl; IDL::traits<Test::Foo>::ref_type foo_obj = IDL::traits<Test::Foo>::narrow (obj); if (!foo_obj) { TAOX11_TEST_ERROR << "ERROR: IDL::traits<Test::Foo>::narrow (obj) returned null object." << std::endl; return 1; } IDL::traits<Test::Foo>::write_on (TAOX11_TEST_INFO << "narrowed Test::Foo interface = ", foo_obj) << std::endl; // Initialize data Test::Array a { { 0, 2, 4, 8, 16, 32, 64, 128, 256, 512} }; Test::Matrix m; for (uint8_t b1=0; b1 < 16 ;++b1) for (uint8_t b2=0; b2 < 16 ;++b2) m[b1][b2] = (b1*16)+b2; Test::StringList sl; sl.push_back("string1"); sl.push_back("string2"); sl.push_back("string3"); sl.push_back("string4"); sl.push_back("string5"); Test::Alphabet abc; for (char c='a'; c<='z' ;++c) abc.push_back(c); Test::Person p ("Thomas Crown", "Unknown Street", 43, Test::Person::TSex::male); Test::Option opt; // write data TAOX11_TEST_INFO << "Array a = " << IDL::traits<Test::Array>::write(a) << std::endl; IDL::traits<Test::Matrix>::write_on (TAOX11_TEST_INFO << "Matrix m = ", m) << std::endl; TAOX11_TEST_INFO << "StringList sl = " << IDL::traits<Test::StringList>::write(sl) << std::endl; IDL::traits<Test::Alphabet>::write_on (TAOX11_TEST_INFO << "Alphabet abc = ", abc) << std::endl; foo_obj->write_on_servant (p); opt.message ("option message selected"); TAOX11_TEST_INFO << "Option opt = " << IDL::traits<Test::Option>::write(opt) << std::endl; opt.number (42775); IDL::traits<Test::Option>::write_on (TAOX11_TEST_INFO << "Option opt = ", opt) << std::endl; TAOX11_TEST_INFO << "shutting down..."; foo_obj->shutdown (); TAOX11_TEST_INFO << std::endl; _orb->destroy (); } catch (const std::exception& e) { TAOX11_TEST_ERROR << "exception caught: " << e << std::endl; return 1; } return 0; }
27.622047
117
0.558723
[ "object" ]
04f2122ef958bd7373cdcb46d8346d07c1eb1805
11,460
cpp
C++
recipes-clp/clp/clp/src/ClpLsqr.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-clp/clp/clp/src/ClpLsqr.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-clp/clp/clp/src/ClpLsqr.cpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
// Copyright (C) 2003, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #include "ClpLsqr.hpp" #include "ClpPdco.hpp" void ClpLsqr::do_lsqr(CoinDenseVector< double > &b, double damp, double atol, double btol, double conlim, int itnlim, bool show, Info info, CoinDenseVector< double > &x, int *istop, int *itn, Outfo *outfo, bool precon, CoinDenseVector< double > &Pr) { /** Special version of LSQR for use with pdco.m. It continues with a reduced atol if a pdco-specific test isn't satisfied with the input atol. */ // Initialize. static char term_msg[8][80] = { "The exact solution is x = 0", "The residual Ax - b is small enough, given ATOL and BTOL", "The least squares error is small enough, given ATOL", "The estimated condition number has exceeded CONLIM", "The residual Ax - b is small enough, given machine precision", "The least squares error is small enough, given machine precision", "The estimated condition number has exceeded machine precision", "The iteration limit has been reached" }; // printf("***************** Entering LSQR *************\n"); assert(model_); char str1[100], str2[100], str3[100], str4[100], head1[100], head2[100]; int n = ncols_; // set m,n from lsqr object *itn = 0; *istop = 0; double ctol = 0; if (conlim > 0) ctol = 1 / conlim; double anorm = 0; double acond = 0; double ddnorm = 0; double xnorm = 0; double xxnorm = 0; double z = 0; double cs2 = -1; double sn2 = 0; // Set up the first vectors u and v for the bidiagonalization. // These satisfy beta*u = b, alfa*v = A'u. CoinDenseVector< double > u(b); CoinDenseVector< double > v(n, 0.0); x.clear(); double alfa = 0; double beta = u.twoNorm(); if (beta > 0) { u = (1 / beta) * u; matVecMult(2, v, u); if (precon) v = v * Pr; alfa = v.twoNorm(); } if (alfa > 0) { v.scale(1 / alfa); } CoinDenseVector< double > w(v); double arnorm = alfa * beta; if (arnorm == 0) { printf(" %s\n\n", term_msg[0]); return; } double rhobar = alfa; double phibar = beta; double bnorm = beta; double rnorm = beta; sprintf(head1, " Itn x(1) Function"); sprintf(head2, " Compatible LS Norm A Cond A"); if (show) { printf(" %s%s\n", head1, head2); double test1 = 1; double test2 = alfa / beta; sprintf(str1, "%6d %12.5e %10.3e", *itn, x[0], rnorm); sprintf(str2, " %8.1e %8.1e", test1, test2); printf("%s%s\n", str1, str2); } //---------------------------------------------------------------- // Main iteration loop. //---------------------------------------------------------------- while (*itn < itnlim) { *itn += 1; // Perform the next step of the bidiagonalization to obtain the // next beta, u, alfa, v. These satisfy the relations // beta*u = a*v - alfa*u, // alfa*v = A'*u - beta*v. u.scale((-alfa)); if (precon) { CoinDenseVector< double > pv(v * Pr); matVecMult(1, u, pv); } else { matVecMult(1, u, v); } beta = u.twoNorm(); if (beta > 0) { u.scale((1 / beta)); anorm = sqrt(anorm * anorm + alfa * alfa + beta * beta + damp * damp); v.scale((-beta)); CoinDenseVector< double > vv(n); vv.clear(); matVecMult(2, vv, u); if (precon) vv = vv * Pr; v = v + vv; alfa = v.twoNorm(); if (alfa > 0) v.scale((1 / alfa)); } // Use a plane rotation to eliminate the damping parameter. // This alters the diagonal (rhobar) of the lower-bidiagonal matrix. double rhobar1 = sqrt(rhobar * rhobar + damp * damp); double cs1 = rhobar / rhobar1; double sn1 = damp / rhobar1; double psi = sn1 * phibar; phibar *= cs1; // Use a plane rotation to eliminate the subdiagonal element (beta) // of the lower-bidiagonal matrix, giving an upper-bidiagonal matrix. double rho = sqrt(rhobar1 * rhobar1 + beta * beta); double cs = rhobar1 / rho; double sn = beta / rho; double theta = sn * alfa; rhobar = -cs * alfa; double phi = cs * phibar; phibar = sn * phibar; double tau = sn * phi; // Update x and w. double t1 = phi / rho; double t2 = -theta / rho; // dk = ((1/rho)*w); double w_norm = w.twoNorm(); x = x + t1 * w; w = v + t2 * w; ddnorm = ddnorm + (w_norm / rho) * (w_norm / rho); // if wantvar, var = var + dk.*dk; end // Use a plane rotation on the right to eliminate the // super-diagonal element (theta) of the upper-bidiagonal matrix. // Then use the result to estimate norm(x). double delta = sn2 * rho; double gambar = -cs2 * rho; double rhs = phi - delta * z; double zbar = rhs / gambar; xnorm = sqrt(xxnorm + zbar * zbar); double gamma = sqrt(gambar * gambar + theta * theta); cs2 = gambar / gamma; sn2 = theta / gamma; z = rhs / gamma; xxnorm = xxnorm + z * z; // Test for convergence. // First, estimate the condition of the matrix Abar, // and the norms of rbar and Abar'rbar. acond = anorm * sqrt(ddnorm); double res1 = phibar * phibar; double res2 = res1 + psi * psi; rnorm = sqrt(res1 + res2); arnorm = alfa * fabs(tau); // Now use these norms to estimate certain other quantities, // some of which will be small near a solution. double test1 = rnorm / bnorm; double test2 = arnorm / (anorm * rnorm); double test3 = 1 / acond; t1 = test1 / (1 + anorm * xnorm / bnorm); double rtol = btol + atol * anorm * xnorm / bnorm; // The following tests guard against extremely small values of // atol, btol or ctol. (The user may have set any or all of // the parameters atol, btol, conlim to 0.) // The effect is equivalent to the normal tests using // atol = eps, btol = eps, conlim = 1/eps. if (*itn >= itnlim) *istop = 7; if (1 + test3 <= 1) *istop = 6; if (1 + test2 <= 1) *istop = 5; if (1 + t1 <= 1) *istop = 4; // Allow for tolerances set by the user. if (test3 <= ctol) *istop = 3; if (test2 <= atol) *istop = 2; if (test1 <= rtol) *istop = 1; //------------------------------------------------------------------- // SPECIAL TEST THAT DEPENDS ON pdco.m. // Aname in pdco is iw in lsqr. // dy is x // Other stuff is in info. // We allow for diagonal preconditioning in pdDDD3. //------------------------------------------------------------------- if (*istop > 0) { double r3new = arnorm; double r3ratio = r3new / info.r3norm; double atolold = atol; double atolnew = atol; if (atol > info.atolmin) { if (r3ratio <= 0.1) { // dy seems good // Relax } else if (r3ratio <= 0.5) { // Accept dy but make next one more accurate. atolnew = atolnew * 0.1; } else { // Recompute dy more accurately if (show) { printf("\n "); printf(" \n"); printf(" %5.1f%7d%7.3f", log10(atolold), *itn, r3ratio); } atol = atol * 0.1; atolnew = atol; *istop = 0; } outfo->atolold = atolold; outfo->atolnew = atolnew; outfo->r3ratio = r3ratio; } //------------------------------------------------------------------- // See if it is time to print something. //------------------------------------------------------------------- int prnt = 0; if (n <= 40) prnt = 1; if (*itn <= 10) prnt = 1; if (*itn >= itnlim - 10) prnt = 1; if (*itn % 10 == 0) prnt = 1; if (test3 <= 2 * ctol) prnt = 1; if (test2 <= 10 * atol) prnt = 1; if (test1 <= 10 * rtol) prnt = 1; if (*istop != 0) prnt = 1; if (prnt == 1) { if (show) { sprintf(str1, " %6d %12.5e %10.3e", *itn, x[0], rnorm); sprintf(str2, " %8.1e %8.1e", test1, test2); sprintf(str3, " %8.1e %8.1e", anorm, acond); printf("%s%s%s\n", str1, str2, str3); } } if (*istop > 0) break; } } // End of iteration loop. // Print the stopping condition. if (show) { printf("\n LSQR finished\n"); // disp(msg(istop+1,:)) // disp(' ') printf("%s\n", term_msg[*istop]); sprintf(str1, "istop =%8d itn =%8d", *istop, *itn); sprintf(str2, "anorm =%8.1e acond =%8.1e", anorm, acond); sprintf(str3, "rnorm =%8.1e arnorm =%8.1e", rnorm, arnorm); sprintf(str4, "bnorm =%8.1e xnorm =%8.1e", bnorm, xnorm); printf("%s %s\n", str1, str2); printf("%s %s\n", str3, str4); } } void ClpLsqr::matVecMult(int mode, CoinDenseVector< double > *x, CoinDenseVector< double > *y) { int n = model_->numberColumns(); int m = model_->numberRows(); CoinDenseVector< double > *temp = new CoinDenseVector< double >(n, 0.0); double *t_elts = temp->getElements(); double *x_elts = x->getElements(); double *y_elts = y->getElements(); ClpPdco *pdcoModel = (ClpPdco *)model_; if (mode == 1) { pdcoModel->matVecMult(2, temp, y); for (int k = 0; k < n; k++) x_elts[k] += (diag1_[k] * t_elts[k]); for (int k = 0; k < m; k++) x_elts[n + k] += (diag2_ * y_elts[k]); } else { for (int k = 0; k < n; k++) t_elts[k] = diag1_[k] * y_elts[k]; pdcoModel->matVecMult(1, x, temp); for (int k = 0; k < m; k++) x_elts[k] += diag2_ * y_elts[n + k]; } delete temp; return; } void ClpLsqr::matVecMult(int mode, CoinDenseVector< double > &x, CoinDenseVector< double > &y) { matVecMult(mode, &x, &y); return; } /* Default constructor */ ClpLsqr::ClpLsqr() : nrows_(0) , ncols_(0) , model_(NULL) , diag1_(NULL) , diag2_(0.0) { } /* Constructor for use with Pdco model (note modified for pdco!!!!) */ ClpLsqr::ClpLsqr(ClpInterior *model) : diag1_(NULL) , diag2_(0.0) { model_ = model; nrows_ = model->numberRows() + model->numberColumns(); ncols_ = model->numberRows(); } /** Destructor */ ClpLsqr::~ClpLsqr() { // delete [] diag1_; no as we just borrowed it } bool ClpLsqr::setParam(char *parmName, int parmValue) { std::cout << "Set lsqr integer parameter " << parmName << "to " << parmValue << std::endl; if (strcmp(parmName, "nrows") == 0) { nrows_ = parmValue; return 1; } else if (strcmp(parmName, "ncols") == 0) { ncols_ = parmValue; return 1; } std::cout << "Attempt to set unknown integer parameter name " << parmName << std::endl; return 0; } ClpLsqr::ClpLsqr(const ClpLsqr &rhs) : nrows_(rhs.nrows_) , ncols_(rhs.ncols_) , model_(rhs.model_) , diag2_(rhs.diag2_) { diag1_ = ClpCopyOfArray(rhs.diag1_, nrows_); } // Assignment operator. This copies the data ClpLsqr & ClpLsqr::operator=(const ClpLsqr &rhs) { if (this != &rhs) { delete[] diag1_; diag1_ = ClpCopyOfArray(rhs.diag1_, nrows_); nrows_ = rhs.nrows_; ncols_ = rhs.ncols_; model_ = rhs.model_; diag2_ = rhs.diag2_; } return *this; } /* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2 */
28.721805
94
0.538918
[ "object", "model" ]
04f3b1bf1313ff416ab7cca3170e70330948ab55
37,772
cpp
C++
Source Code/Environment/Terrain/TerrainLoader.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Environment/Terrain/TerrainLoader.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Environment/Terrain/TerrainLoader.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Headers/Terrain.h" #include "Headers/TerrainLoader.h" #include "Headers/TerrainDescriptor.h" #include "Core/Headers/ByteBuffer.h" #include "Core/Headers/Configuration.h" #include "Core/Headers/PlatformContext.h" #include "Platform/Video/Headers/GFXDevice.h" #include "Platform/File/Headers/FileManagement.h" #include "Platform/Video/Headers/RenderStateBlock.h" #include "Geometry/Material/Headers/Material.h" #include "Managers/Headers/SceneManager.h" namespace Divide { namespace { constexpr U16 BYTE_BUFFER_VERSION = 1u; ResourcePath ClimatesLocation(U8 textureQuality) { CLAMP<U8>(textureQuality, 0u, 3u); return Paths::g_assetsLocation + Paths::g_heightmapLocation + (textureQuality == 3u ? Paths::g_climatesHighResLocation : textureQuality == 2u ? Paths::g_climatesMedResLocation : Paths::g_climatesLowResLocation); } std::pair<U8, bool> FindOrInsert(const U8 textureQuality, vector<string>& container, const string& texture, string materialName) { if (!fileExists((ClimatesLocation(textureQuality) + "/" + materialName + "/" + texture).c_str())) { materialName = "std_default"; } const string item = materialName + "/" + texture; const auto* const it = eastl::find(eastl::cbegin(container), eastl::cend(container), item); if (it != eastl::cend(container)) { return std::make_pair(to_U8(eastl::distance(eastl::cbegin(container), it)), false); } container.push_back(item); return std::make_pair(to_U8(container.size() - 1), true); } } bool TerrainLoader::loadTerrain(const Terrain_ptr& terrain, const std::shared_ptr<TerrainDescriptor>& terrainDescriptor, PlatformContext& context, bool threadedLoading) { const string& name = terrainDescriptor->getVariable("terrainName"); ResourcePath terrainLocation = Paths::g_assetsLocation + Paths::g_heightmapLocation; terrainLocation += terrainDescriptor->getVariable("descriptor"); Attorney::TerrainLoader::descriptor(*terrain, terrainDescriptor); const U8 textureQuality = context.config().terrain.textureQuality; // Noise texture SamplerDescriptor noiseMediumSampler = {}; noiseMediumSampler.wrapUVW(TextureWrap::REPEAT); noiseMediumSampler.anisotropyLevel(16); const size_t noiseHash = noiseMediumSampler.getHash(); ImageTools::ImportOptions importOptions{}; importOptions._useDDSCache = true; TextureDescriptor noiseMediumDescriptor(TextureType::TEXTURE_2D_ARRAY); noiseMediumDescriptor.layerCount(1u); noiseMediumDescriptor.srgb(false); importOptions._alphaChannelTransparency = false; importOptions._isNormalMap = false; noiseMediumDescriptor.textureOptions(importOptions); ResourceDescriptor textureNoiseMedium("Terrain Noise Map_" + name); textureNoiseMedium.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation); textureNoiseMedium.assetName(ResourcePath{ "medium_noise.png" }); textureNoiseMedium.propertyDescriptor(noiseMediumDescriptor); // Blend maps ResourceDescriptor textureBlendMap("Terrain Blend Map_" + name); textureBlendMap.assetLocation(terrainLocation); // Albedo maps and roughness ResourceDescriptor textureAlbedoMaps("Terrain Albedo Maps_" + name); textureAlbedoMaps.assetLocation(ClimatesLocation(textureQuality)); // Normals ResourceDescriptor textureNormalMaps("Terrain Normal Maps_" + name); textureNormalMaps.assetLocation(ClimatesLocation(textureQuality)); // AO and displacement ResourceDescriptor textureExtraMaps("Terrain Extra Maps_" + name); textureExtraMaps.assetLocation(ClimatesLocation(textureQuality)); //temp data string layerOffsetStr; string currentMaterial; U8 layerCount = terrainDescriptor->textureLayers(); const vector<std::pair<string, TerrainTextureChannel>> channels = { {"red", TerrainTextureChannel::TEXTURE_RED_CHANNEL}, {"green", TerrainTextureChannel::TEXTURE_GREEN_CHANNEL}, {"blue", TerrainTextureChannel::TEXTURE_BLUE_CHANNEL}, {"alpha", TerrainTextureChannel::TEXTURE_ALPHA_CHANNEL} }; vector<string> textures[to_base(TerrainTextureType::COUNT)] = {}; vector<string> splatTextures = {}; const char* textureNames[to_base(TerrainTextureType::COUNT)] = { "Albedo_roughness", "Normal", "Displacement" }; for (U8 i = 0u; i < layerCount; ++i) { layerOffsetStr = Util::to_string(i); splatTextures.push_back(terrainDescriptor->getVariable("blendMap" + layerOffsetStr)); } for (U8 i = 0u; i < layerCount; ++i) { layerOffsetStr = Util::to_string(i); splatTextures.push_back(terrainDescriptor->getVariable("blendMap" + layerOffsetStr)); U8 j = 0u; for (const auto& [channelName, channel] : channels) { currentMaterial = terrainDescriptor->getVariable(channelName + layerOffsetStr + "_mat"); if (currentMaterial.empty()) { continue; } for (U8 k = 0u; k < to_base(TerrainTextureType::COUNT); ++k) { FindOrInsert(textureQuality, textures[k], Util::StringFormat("%s.%s", textureNames[k], k == to_base(TerrainTextureType::ALBEDO_ROUGHNESS) ? "png" : "jpg"), currentMaterial); } ++j; } } ResourcePath blendMapArray = {}; ResourcePath albedoMapArray = {}; ResourcePath normalMapArray = {}; ResourcePath extraMapArray = {}; U16 extraMapCount = 0; for (const string& tex : textures[to_base(TerrainTextureType::ALBEDO_ROUGHNESS)]) { albedoMapArray.append(tex + ","); } for (const string& tex : textures[to_base(TerrainTextureType::NORMAL)]) { normalMapArray.append(tex + ","); } for (U8 i = to_U8(TerrainTextureType::DISPLACEMENT_AO); i < to_U8(TerrainTextureType::COUNT); ++i) { for (const string& tex : textures[i]) { extraMapArray.append(tex + ","); ++extraMapCount; } } for (const string& tex : splatTextures) { blendMapArray.append(tex + ","); } blendMapArray.pop_back(); albedoMapArray.pop_back(); normalMapArray.pop_back(); extraMapArray.pop_back(); SamplerDescriptor heightMapSampler = {}; heightMapSampler.wrapUVW(TextureWrap::CLAMP_TO_BORDER); heightMapSampler.mipSampling(TextureMipSampling::NONE); heightMapSampler.borderColour(DefaultColours::BLACK); heightMapSampler.anisotropyLevel(16); const size_t heightSamplerHash = heightMapSampler.getHash(); SamplerDescriptor blendMapSampler = {}; blendMapSampler.wrapUVW(TextureWrap::CLAMP_TO_EDGE); blendMapSampler.anisotropyLevel(16); const size_t blendMapHash = blendMapSampler.getHash(); SamplerDescriptor albedoSampler = {}; albedoSampler.wrapUVW(TextureWrap::REPEAT); albedoSampler.anisotropyLevel(16); const size_t albedoHash = albedoSampler.getHash(); TextureDescriptor albedoDescriptor(TextureType::TEXTURE_2D_ARRAY); albedoDescriptor.layerCount(to_U16(textures[to_base(TerrainTextureType::ALBEDO_ROUGHNESS)].size())); albedoDescriptor.srgb(false); importOptions._alphaChannelTransparency = false; //roughness importOptions._isNormalMap = false; albedoDescriptor.textureOptions(importOptions); TextureDescriptor blendMapDescriptor(TextureType::TEXTURE_2D_ARRAY); blendMapDescriptor.layerCount(to_U16(splatTextures.size())); blendMapDescriptor.srgb(false); importOptions._alphaChannelTransparency = false; //splat lookup importOptions._isNormalMap = false; blendMapDescriptor.textureOptions(importOptions); TextureDescriptor normalDescriptor(TextureType::TEXTURE_2D_ARRAY); normalDescriptor.layerCount(to_U16(textures[to_base(TerrainTextureType::NORMAL)].size())); normalDescriptor.srgb(false); importOptions._alphaChannelTransparency = false; //not really needed importOptions._isNormalMap = true; importOptions._useDDSCache = false; normalDescriptor.textureOptions(importOptions); importOptions._useDDSCache = true; TextureDescriptor extraDescriptor(TextureType::TEXTURE_2D_ARRAY); extraDescriptor.layerCount(extraMapCount); extraDescriptor.srgb(false); importOptions._alphaChannelTransparency = false; //who knows what we pack here? importOptions._isNormalMap = false; extraDescriptor.textureOptions(importOptions); textureBlendMap.assetName(blendMapArray); textureBlendMap.propertyDescriptor(blendMapDescriptor); textureAlbedoMaps.assetName(albedoMapArray); textureAlbedoMaps.propertyDescriptor(albedoDescriptor); textureNormalMaps.assetName(normalMapArray); textureNormalMaps.propertyDescriptor(normalDescriptor); textureExtraMaps.assetName(extraMapArray); textureExtraMaps.propertyDescriptor(extraDescriptor); ResourceDescriptor terrainMaterialDescriptor("terrainMaterial_" + name); Material_ptr terrainMaterial = CreateResource<Material>(terrain->parentResourceCache(), terrainMaterialDescriptor); terrainMaterial->ignoreXMLData(true); terrainMaterial->updatePriorirty(Material::UpdatePriority::Medium); const vec2<U16> & terrainDimensions = terrainDescriptor->dimensions(); const vec2<F32> & altitudeRange = terrainDescriptor->altitudeRange(); Console::d_printfn(Locale::Get(_ID("TERRAIN_INFO")), terrainDimensions.width, terrainDimensions.height); const F32 underwaterTileScale = terrainDescriptor->getVariablef("underwaterTileScale"); terrainMaterial->properties().shadingMode(ShadingMode::PBR_MR); const Terrain::ParallaxMode pMode = static_cast<Terrain::ParallaxMode>(CLAMPED(to_I32(to_U8(context.config().terrain.parallaxMode)), 0, 2)); if (pMode == Terrain::ParallaxMode::NORMAL) { terrainMaterial->properties().bumpMethod(BumpMethod::PARALLAX); } else if (pMode == Terrain::ParallaxMode::OCCLUSION) { terrainMaterial->properties().bumpMethod(BumpMethod::PARALLAX_OCCLUSION); } else { terrainMaterial->properties().bumpMethod(BumpMethod::NONE); } terrainMaterial->properties().baseColour(FColour4(DefaultColours::WHITE.rgb * 0.5f, 1.0f)); terrainMaterial->properties().metallic(0.0f); terrainMaterial->properties().roughness(0.8f); terrainMaterial->properties().parallaxFactor(0.3f); terrainMaterial->properties().toggleTransparency(false); const TerrainDescriptor::LayerData& layerTileData = terrainDescriptor->layerDataEntries(); string tileFactorStr = Util::StringFormat("const vec2 CURRENT_TILE_FACTORS[%d] = {\n", layerCount * 4); for (U8 i = 0u; i < layerCount; ++i) { const TerrainDescriptor::LayerDataEntry& entry = layerTileData[i]; for (U8 j = 0u; j < 4u; ++j) { const vec2<F32>& factors = entry[j]; tileFactorStr.append(Util::StringFormat("%*c", 8, ' ')); tileFactorStr.append(Util::StringFormat("vec2(%3.2f, %3.2f),\n", factors.s, factors.t)); } } tileFactorStr.pop_back(); tileFactorStr.pop_back(); tileFactorStr.append("\n};"); ResourcePath helperTextures { terrainDescriptor->getVariable("waterCaustics") + "," + terrainDescriptor->getVariable("underwaterAlbedoTexture") + "," + terrainDescriptor->getVariable("underwaterDetailTexture") + "," + terrainDescriptor->getVariable("tileNoiseTexture") }; TextureDescriptor helperTexDescriptor(TextureType::TEXTURE_2D_ARRAY); helperTexDescriptor.textureOptions()._alphaChannelTransparency = false; ResourceDescriptor textureWaterCaustics("Terrain Helper Textures_" + name); textureWaterCaustics.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation); textureWaterCaustics.assetName(helperTextures); textureWaterCaustics.propertyDescriptor(helperTexDescriptor); ResourceDescriptor heightMapTexture("Terrain Heightmap_" + name); heightMapTexture.assetLocation(terrainLocation); heightMapTexture.assetName(ResourcePath{ terrainDescriptor->getVariable("heightfieldTex") }); ImageTools::ImportOptions options{}; options._useDDSCache = false; TextureDescriptor heightMapDescriptor(TextureType::TEXTURE_2D_ARRAY, GFXDataFormat::COUNT); heightMapDescriptor.textureOptions(options); heightMapDescriptor.mipMappingState(TextureDescriptor::MipMappingState::OFF); heightMapTexture.propertyDescriptor(heightMapDescriptor); terrainMaterial->properties().isStatic(true); terrainMaterial->properties().isInstanced(true); terrainMaterial->setTexture(TextureUsage::UNIT0, CreateResource<Texture>(terrain->parentResourceCache(), textureAlbedoMaps), albedoHash, TextureOperation::NONE, TexturePrePassUsage::ALWAYS); terrainMaterial->setTexture(TextureUsage::UNIT1, CreateResource<Texture>(terrain->parentResourceCache(), textureNoiseMedium), noiseHash, TextureOperation::NONE, TexturePrePassUsage::ALWAYS); terrainMaterial->setTexture(TextureUsage::OPACITY, CreateResource<Texture>(terrain->parentResourceCache(), textureBlendMap), blendMapHash, TextureOperation::NONE, TexturePrePassUsage::ALWAYS); terrainMaterial->setTexture(TextureUsage::NORMALMAP, CreateResource<Texture>(terrain->parentResourceCache(), textureNormalMaps), albedoHash, TextureOperation::NONE, TexturePrePassUsage::ALWAYS); terrainMaterial->setTexture(TextureUsage::HEIGHTMAP, CreateResource<Texture>(terrain->parentResourceCache(), heightMapTexture), heightSamplerHash, TextureOperation::NONE, TexturePrePassUsage::ALWAYS); terrainMaterial->setTexture(TextureUsage::SPECULAR, CreateResource<Texture>(terrain->parentResourceCache(), textureWaterCaustics), albedoHash, TextureOperation::NONE, TexturePrePassUsage::ALWAYS); terrainMaterial->setTexture(TextureUsage::METALNESS, CreateResource<Texture>(terrain->parentResourceCache(), textureExtraMaps), albedoHash, TextureOperation::NONE, TexturePrePassUsage::ALWAYS); terrainMaterial->setTexture(TextureUsage::EMISSIVE, Texture::DefaultTexture(), albedoHash, TextureOperation::NONE, TexturePrePassUsage::ALWAYS); const Configuration::Terrain terrainConfig = context.config().terrain; const vec2<F32> WorldScale = terrain->tessParams().WorldScale(); Texture_ptr albedoTile = terrainMaterial->getTexture(TextureUsage::UNIT0).lock(); WAIT_FOR_CONDITION(albedoTile->getState() == ResourceState::RES_LOADED); const U16 tileMapSize = albedoTile->width(); terrainMaterial->addShaderDefine(ShaderType::COUNT, "ENABLE_TBN"); terrainMaterial->addShaderDefine(ShaderType::COUNT, "TEXTURE_TILE_SIZE " + Util::to_string(tileMapSize)); terrainMaterial->addShaderDefine(ShaderType::COUNT, "TERRAIN_HEIGHT_OFFSET " + Util::to_string(altitudeRange.x)); terrainMaterial->addShaderDefine(ShaderType::COUNT, "WORLD_SCALE_X " + Util::to_string(WorldScale.width)); terrainMaterial->addShaderDefine(ShaderType::COUNT, "WORLD_SCALE_Y " + Util::to_string(altitudeRange.y - altitudeRange.x)); terrainMaterial->addShaderDefine(ShaderType::COUNT, "WORLD_SCALE_Z " + Util::to_string(WorldScale.height)); terrainMaterial->addShaderDefine(ShaderType::COUNT, "INV_CONTROL_VTX_PER_TILE_EDGE " + Util::to_string(1.f / TessellationParams::VTX_PER_TILE_EDGE)); terrainMaterial->addShaderDefine(ShaderType::COUNT, Util::StringFormat("CONTROL_VTX_PER_TILE_EDGE %d", TessellationParams::VTX_PER_TILE_EDGE)); terrainMaterial->addShaderDefine(ShaderType::COUNT, Util::StringFormat("PATCHES_PER_TILE_EDGE %d", TessellationParams::PATCHES_PER_TILE_EDGE)); terrainMaterial->addShaderDefine(ShaderType::COUNT, Util::StringFormat("MAX_TEXTURE_LAYERS %d", layerCount)); if (terrainConfig.detailLevel > 1) { terrainMaterial->addShaderDefine(ShaderType::COUNT, "REDUCE_TEXTURE_TILE_ARTIFACT"); if (terrainConfig.detailLevel > 2) { terrainMaterial->addShaderDefine(ShaderType::COUNT, "REDUCE_TEXTURE_TILE_ARTIFACT_ALL_LODS"); } } terrainMaterial->addShaderDefine(ShaderType::FRAGMENT, Util::StringFormat("UNDERWATER_TILE_SCALE %d", to_I32(underwaterTileScale))); terrainMaterial->addShaderDefine(ShaderType::FRAGMENT, tileFactorStr, false); if (!terrainMaterial->properties().receivesShadows()) { terrainMaterial->addShaderDefine(ShaderType::FRAGMENT, "DISABLE_SHADOW_MAPPING"); } terrainMaterial->computeShaderCBK([name, terrainConfig]([[maybe_unused]] Material* material, const RenderStagePass stagePass) { const Terrain::WireframeMode wMode = terrainConfig.wireframe ? Terrain::WireframeMode::EDGES : terrainConfig.showNormals ? Terrain::WireframeMode::NORMALS : terrainConfig.showLoDs ? Terrain::WireframeMode::LODS : terrainConfig.showTessLevels ? Terrain::WireframeMode::TESS_LEVELS : terrainConfig.showBlendMap ? Terrain::WireframeMode::BLEND_MAP : Terrain::WireframeMode::NONE; ShaderModuleDescriptor vertModule = {}; vertModule._moduleType = ShaderType::VERTEX; vertModule._sourceFile = "terrainTess.glsl"; ShaderModuleDescriptor tescModule = {}; tescModule._moduleType = ShaderType::TESSELLATION_CTRL; tescModule._sourceFile = "terrainTess.glsl"; ShaderModuleDescriptor teseModule = {}; teseModule._moduleType = ShaderType::TESSELLATION_EVAL; teseModule._sourceFile = "terrainTess.glsl"; ShaderModuleDescriptor geomModule = {}; geomModule._moduleType = ShaderType::GEOMETRY; geomModule._sourceFile = "terrainTess.glsl"; ShaderModuleDescriptor fragModule = {}; fragModule._moduleType = ShaderType::FRAGMENT; fragModule._sourceFile = "terrainTess.glsl"; ShaderProgramDescriptor shaderDescriptor = {}; shaderDescriptor._modules.push_back(vertModule); shaderDescriptor._modules.push_back(tescModule); shaderDescriptor._modules.push_back(teseModule); shaderDescriptor._modules.push_back(fragModule); const bool hasGeometryPass = wMode == Terrain::WireframeMode::EDGES || wMode == Terrain::WireframeMode::NORMALS; if (hasGeometryPass) { shaderDescriptor._modules.push_back(geomModule); } string propName; for (ShaderModuleDescriptor& shaderModule : shaderDescriptor._modules) { string shaderPropName; if (wMode != Terrain::WireframeMode::NONE) { if (hasGeometryPass) { shaderPropName += ".DebugView"; shaderModule._defines.emplace_back("TOGGLE_DEBUG"); } if (wMode == Terrain::WireframeMode::EDGES) { shaderPropName += ".WireframeView"; shaderModule._defines.emplace_back("TOGGLE_WIREFRAME"); } else if (wMode == Terrain::WireframeMode::NORMALS) { shaderPropName += ".PreviewNormals"; shaderModule._defines.emplace_back("TOGGLE_NORMALS"); } else if (wMode == Terrain::WireframeMode::LODS) { shaderPropName += ".PreviewLoDs"; shaderModule._defines.emplace_back("TOGGLE_LODS"); } else if (wMode == Terrain::WireframeMode::TESS_LEVELS) { shaderPropName += ".PreviewTessLevels"; shaderModule._defines.emplace_back("TOGGLE_TESS_LEVEL"); } else if (wMode == Terrain::WireframeMode::BLEND_MAP) { shaderPropName += ".PreviewBlendMap"; shaderModule._defines.emplace_back("TOGGLE_BLEND_MAP"); } } if (shaderPropName.length() > propName.length()) { propName = shaderPropName; } } if (stagePass._stage == RenderStage::SHADOW) { for (ShaderModuleDescriptor& shaderModule : shaderDescriptor._modules) { if (shaderModule._moduleType == ShaderType::FRAGMENT) { shaderModule._variant = "Shadow.VSM"; } shaderModule._defines.emplace_back("MAX_TESS_LEVEL 32"); } shaderDescriptor._name = "Terrain_ShadowVSM-" + name + propName; } else if (stagePass._stage == RenderStage::DISPLAY) { //ToDo: Implement this! -Ionut constexpr bool hasParallax = false; if (hasParallax) { for (ShaderModuleDescriptor& shaderModule : shaderDescriptor._modules) { if (shaderModule._moduleType == ShaderType::FRAGMENT) { shaderModule._defines.emplace_back("HAS_PARALLAX"); break; } } } if (stagePass._passType == RenderPassType::PRE_PASS) { for (ShaderModuleDescriptor& shaderModule : shaderDescriptor._modules) { if (shaderModule._moduleType == ShaderType::FRAGMENT) { shaderModule._variant = "PrePass"; } shaderModule._defines.emplace_back("PRE_PASS"); } shaderDescriptor._name = "Terrain_PrePass-" + name + propName + (hasParallax ? ".Parallax" : ""); } else { shaderDescriptor._name = "Terrain_Colour-" + name + propName + (hasParallax ? ".Parallax" : ""); } } else { // Not RenderStage::DISPLAY if (IsDepthPass(stagePass)) { shaderDescriptor._modules.pop_back(); //No frag shader for (ShaderModuleDescriptor& shaderModule : shaderDescriptor._modules) { shaderModule._defines.emplace_back("LOW_QUALITY"); shaderModule._defines.emplace_back("MAX_TESS_LEVEL 16"); } shaderDescriptor._name = "Terrain_PrePass_LowQuality-" + name + propName; } else { for (ShaderModuleDescriptor& shaderModule : shaderDescriptor._modules) { if (shaderModule._moduleType == ShaderType::FRAGMENT) { shaderModule._variant = "LQPass"; } shaderModule._defines.emplace_back("LOW_QUALITY"); shaderModule._defines.emplace_back("MAX_TESS_LEVEL 16"); if (stagePass._stage == RenderStage::REFLECTION) { shaderModule._defines.emplace_back("REFLECTION_PASS"); } } if (stagePass._stage == RenderStage::REFLECTION) { shaderDescriptor._name = "Terrain_Colour_LowQuality_Reflect-" + name + propName; } else { shaderDescriptor._name = "Terrain_Colour_LowQuality-" + name + propName; } } } return shaderDescriptor; }); terrainMaterial->computeRenderStateCBK([]([[maybe_unused]] Material* material, const RenderStagePass stagePass) { const bool isReflectionPass = stagePass._stage == RenderStage::REFLECTION; RenderStateBlock terrainRenderState = {}; terrainRenderState.setTessControlPoints(4); terrainRenderState.setCullMode(isReflectionPass ? CullMode::FRONT : CullMode::BACK); terrainRenderState.setZFunc(IsDepthPass(stagePass) ? ComparisonFunction::LEQUAL : ComparisonFunction::EQUAL); if (IsShadowPass(stagePass)) { terrainRenderState.setColourWrites(true, true, false, false); } else if (IsDepthPrePass(stagePass) && stagePass._stage != RenderStage::DISPLAY) { terrainRenderState.setColourWrites(false, false, false, false); } return terrainRenderState.getHash(); }); AttributeMap vertexFormat{}; { AttributeDescriptor& desc = vertexFormat[to_base(AttribLocation::POSITION)]; desc._bindingIndex = 0u; desc._componentsPerElement = 4u; desc._dataType = GFXDataFormat::FLOAT_32; desc._normalized = false; desc._strideInBytes = 0u * sizeof(F32); desc._instanceDivisor = 1u; } { AttributeDescriptor& desc = vertexFormat[to_base(AttribLocation::COLOR)]; desc._bindingIndex = 0u; desc._componentsPerElement = 4u; desc._dataType = GFXDataFormat::FLOAT_32; desc._normalized = false; desc._strideInBytes = 4u * sizeof(F32); desc._instanceDivisor = 1u; } terrainMaterial->setPipelineLayout(PrimitiveTopology::PATCH, vertexFormat); terrain->setMaterialTpl(terrainMaterial); Start(*CreateTask([terrain, terrainDescriptor, &context](const Task&) { if (!loadThreadedResources(terrain, context, terrainDescriptor)) { DIVIDE_UNEXPECTED_CALL(); } }), context.taskPool(TaskPoolType::HIGH_PRIORITY), threadedLoading ? TaskPriority::DONT_CARE : TaskPriority::REALTIME); return true; } bool TerrainLoader::loadThreadedResources(const Terrain_ptr& terrain, PlatformContext& context, const std::shared_ptr<TerrainDescriptor>& terrainDescriptor) { ResourcePath terrainMapLocation{ Paths::g_assetsLocation + Paths::g_heightmapLocation + terrainDescriptor->getVariable("descriptor") }; ResourcePath terrainRawFile{ terrainDescriptor->getVariable("heightfield") }; const vec2<U16>& terrainDimensions = terrainDescriptor->dimensions(); const F32 minAltitude = terrainDescriptor->altitudeRange().x; const F32 maxAltitude = terrainDescriptor->altitudeRange().y; BoundingBox& terrainBB = Attorney::TerrainLoader::boundingBox(*terrain); terrainBB.set(vec3<F32>(-terrainDimensions.x * 0.5f, minAltitude, -terrainDimensions.y * 0.5f), vec3<F32>( terrainDimensions.x * 0.5f, maxAltitude, terrainDimensions.y * 0.5f)); const vec3<F32>& bMin = terrainBB.getMin(); const vec3<F32>& bMax = terrainBB.getMax(); ByteBuffer terrainCache; if (terrainCache.loadFromFile((Paths::g_cacheLocation + Paths::g_terrainCacheLocation).c_str(), (terrainRawFile + ".cache").c_str())) { auto tempVer = decltype(BYTE_BUFFER_VERSION){0}; terrainCache >> tempVer; if (tempVer == BYTE_BUFFER_VERSION) { terrainCache >> terrain->_physicsVerts; } else { terrainCache.clear(); } } if (terrain->_physicsVerts.empty()) { vector<Byte> data(to_size(terrainDimensions.width) * terrainDimensions.height * (sizeof(U16) / sizeof(char)), Byte{0}); if (readFile((terrainMapLocation + "/").c_str(), terrainRawFile.c_str(), data, FileType::BINARY) != FileError::NONE) { NOP(); } constexpr F32 ushortMax = 1.f + U16_MAX; const I32 terrainWidth = to_I32(terrainDimensions.x); const I32 terrainHeight = to_I32(terrainDimensions.y); terrain->_physicsVerts.resize(to_size(terrainWidth) * terrainHeight); // scale and translate all heights by half to convert from 0-255 (0-65335) to -127 - 128 (-32767 - 32768) const F32 altitudeRange = maxAltitude - minAltitude; const F32 bXRange = bMax.x - bMin.x; const F32 bZRange = bMax.z - bMin.z; const bool flipHeight = !ImageTools::UseUpperLeftOrigin(); #pragma omp parallel for for (I32 height = 0; height < terrainHeight; ++height) { for (I32 width = 0; width < terrainWidth; ++width) { const I32 idxTER = TER_COORD(width, height, terrainWidth); vec3<F32>& vertexData = terrain->_physicsVerts[idxTER]._position; F32 yOffset = 0.0f; const U16* heightData = reinterpret_cast<U16*>(data.data()); const I32 coordX = width < terrainWidth - 1 ? width : width - 1; I32 coordY = (height < terrainHeight - 1 ? height : height - 1); if (flipHeight) { coordY = terrainHeight - 1 - coordY; } const I32 idxIMG = TER_COORD(coordX, coordY, terrainWidth); yOffset = altitudeRange * (heightData[idxIMG] / ushortMax) + minAltitude; //#pragma omp critical //Surely the id is unique and memory has also been allocated beforehand vertexData.set(bMin.x + to_F32(width) * bXRange / (terrainWidth - 1), //X yOffset, //Y bMin.z + to_F32(height) * bZRange / (terrainHeight - 1)); //Z } } constexpr I32 offset = 2; #pragma omp parallel for for (I32 j = offset; j < terrainHeight - offset; ++j) { for (I32 i = offset; i < terrainWidth - offset; ++i) { vec3<F32> vU, vV, vUV; vU.set(terrain->_physicsVerts[TER_COORD(i + offset, j + 0, terrainWidth)]._position - terrain->_physicsVerts[TER_COORD(i - offset, j + 0, terrainWidth)]._position); vV.set(terrain->_physicsVerts[TER_COORD(i + 0, j + offset, terrainWidth)]._position - terrain->_physicsVerts[TER_COORD(i + 0, j - offset, terrainWidth)]._position); vUV.cross(vV, vU); vUV.normalize(); vU = -vU; vU.normalize(); //Again, not needed, I think //#pragma omp critical { const I32 idx = TER_COORD(i, j, terrainWidth); VertexBuffer::Vertex& vert = terrain->_physicsVerts[idx]; vert._normal = Util::PACK_VEC3(vUV); vert._tangent = Util::PACK_VEC3(vU); } } } for (I32 j = 0; j < offset; ++j) { for (I32 i = 0; i < terrainWidth; ++i) { I32 idx0 = TER_COORD(i, j, terrainWidth); I32 idx1 = TER_COORD(i, offset, terrainWidth); terrain->_physicsVerts[idx0]._normal = terrain->_physicsVerts[idx1]._normal; terrain->_physicsVerts[idx0]._tangent = terrain->_physicsVerts[idx1]._tangent; idx0 = TER_COORD(i, terrainHeight - 1 - j, terrainWidth); idx1 = TER_COORD(i, terrainHeight - 1 - offset, terrainWidth); terrain->_physicsVerts[idx0]._normal = terrain->_physicsVerts[idx1]._normal; terrain->_physicsVerts[idx0]._tangent = terrain->_physicsVerts[idx1]._tangent; } } for (I32 i = 0; i < offset; ++i) { for (I32 j = 0; j < terrainHeight; ++j) { I32 idx0 = TER_COORD(i, j, terrainWidth); I32 idx1 = TER_COORD(offset, j, terrainWidth); terrain->_physicsVerts[idx0]._normal = terrain->_physicsVerts[idx1]._normal; terrain->_physicsVerts[idx0]._tangent = terrain->_physicsVerts[idx1]._tangent; idx0 = TER_COORD(terrainWidth - 1 - i, j, terrainWidth); idx1 = TER_COORD(terrainWidth - 1 - offset, j, terrainWidth); terrain->_physicsVerts[idx0]._normal = terrain->_physicsVerts[idx1]._normal; terrain->_physicsVerts[idx0]._tangent = terrain->_physicsVerts[idx1]._tangent; } } terrainCache << BYTE_BUFFER_VERSION; terrainCache << terrain->_physicsVerts; if (!terrainCache.dumpToFile((Paths::g_cacheLocation + Paths::g_terrainCacheLocation).c_str(), (terrainRawFile + ".cache").c_str())) { DIVIDE_UNEXPECTED_CALL(); } } // Then compute quadtree and all additional terrain-related structures Attorney::TerrainLoader::postBuild(*terrain); // Do this first in case we have any threaded loads const VegetationDetails& vegDetails = initializeVegetationDetails(terrain, context, terrainDescriptor); Vegetation::createAndUploadGPUData(context.gfx(), terrain, vegDetails); Console::printfn(Locale::Get(_ID("TERRAIN_LOAD_END")), terrain->resourceName().c_str()); return terrain->load(); } VegetationDetails& TerrainLoader::initializeVegetationDetails(const Terrain_ptr& terrain, PlatformContext& context, const std::shared_ptr<TerrainDescriptor>& terrainDescriptor) { VegetationDetails& vegDetails = Attorney::TerrainLoader::vegetationDetails(*terrain); const U32 chunkSize = terrain->getQuadtree().targetChunkDimension(); assert(chunkSize > 0u); const U32 terrainWidth = terrainDescriptor->dimensions().width; const U32 terrainHeight = terrainDescriptor->dimensions().height; const U32 maxChunkCount = to_U32(std::ceil(terrainWidth * terrainHeight / (chunkSize * chunkSize * 1.0f))); Vegetation::precomputeStaticData(context.gfx(), chunkSize, maxChunkCount); for (I32 i = 1; i < 5; ++i) { string currentMesh = terrainDescriptor->getVariable(Util::StringFormat("treeMesh%d", i)); if (!currentMesh.empty()) { vegDetails.treeMeshes.push_back(ResourcePath{ currentMesh }); } vegDetails.treeRotations[i - 1].set( terrainDescriptor->getVariablef(Util::StringFormat("treeRotationX%d", i)), terrainDescriptor->getVariablef(Util::StringFormat("treeRotationY%d", i)), terrainDescriptor->getVariablef(Util::StringFormat("treeRotationZ%d", i)) ); } vegDetails.grassScales.set( terrainDescriptor->getVariablef("grassScale1"), terrainDescriptor->getVariablef("grassScale2"), terrainDescriptor->getVariablef("grassScale3"), terrainDescriptor->getVariablef("grassScale4")); vegDetails.treeScales.set( terrainDescriptor->getVariablef("treeScale1"), terrainDescriptor->getVariablef("treeScale2"), terrainDescriptor->getVariablef("treeScale3"), terrainDescriptor->getVariablef("treeScale4")); string currentImage = terrainDescriptor->getVariable("grassBillboard1"); if (!currentImage.empty()) { vegDetails.billboardTextureArray += currentImage; vegDetails.billboardCount++; } currentImage = terrainDescriptor->getVariable("grassBillboard2"); if (!currentImage.empty()) { vegDetails.billboardTextureArray += "," + currentImage; vegDetails.billboardCount++; } currentImage = terrainDescriptor->getVariable("grassBillboard3"); if (!currentImage.empty()) { vegDetails.billboardTextureArray += "," + currentImage; vegDetails.billboardCount++; } currentImage = terrainDescriptor->getVariable("grassBillboard4"); if (!currentImage.empty()) { vegDetails.billboardTextureArray += "," + currentImage; vegDetails.billboardCount++; } vegDetails.name = terrain->resourceName() + "_vegetation"; vegDetails.parentTerrain = terrain; const ResourcePath terrainLocation{ Paths::g_assetsLocation + Paths::g_heightmapLocation + terrainDescriptor->getVariable("descriptor") }; vegDetails.grassMap.reset(new ImageTools::ImageData); vegDetails.treeMap.reset(new ImageTools::ImageData); const ResourcePath grassMap{ terrainDescriptor->getVariable("grassMap")}; const ResourcePath treeMap{ terrainDescriptor->getVariable("treeMap") }; ImageTools::ImportOptions options{}; options._alphaChannelTransparency = false; options._isNormalMap = false; if (!vegDetails.grassMap->loadFromFile(false, 0, 0, terrainLocation, grassMap, options)) { DIVIDE_UNEXPECTED_CALL(); } if (!vegDetails.treeMap->loadFromFile(false, 0, 0, terrainLocation, treeMap, options)) { DIVIDE_UNEXPECTED_CALL(); } return vegDetails; } bool TerrainLoader::Save([[maybe_unused]] const char* fileName) { return true; } bool TerrainLoader::Load([[maybe_unused]] const char* fileName) { return true; } }
48.612613
205
0.642963
[ "geometry", "vector" ]
04f517463c6f86f0ec7dd18dd65fed1d88eecb95
7,357
cc
C++
src/qx-simulator/simulator.cc
QuTech-Delft/qx-simulator
e3a888f4a79fde2313060cb92756488d20b08b66
[ "Apache-2.0" ]
3
2020-05-06T03:33:20.000Z
2021-03-22T11:21:07.000Z
src/qx-simulator/simulator.cc
QuTech-Delft/qx-simulator
e3a888f4a79fde2313060cb92756488d20b08b66
[ "Apache-2.0" ]
5
2021-03-16T12:20:34.000Z
2021-11-23T10:31:16.000Z
src/qx-simulator/simulator.cc
QuTech-Delft/qx-simulator
e3a888f4a79fde2313060cb92756488d20b08b66
[ "Apache-2.0" ]
9
2020-01-10T12:15:50.000Z
2021-07-02T12:14:07.000Z
/** * @file simulator.cc * @author Nader KHAMMASSI - nader.khammassi@gmail.com * @date 01-01-16 * @brief */ #include "qx/representation.h" #include "qx/libqasm_interface.h" #include <qasm_semantic.hpp> #ifdef USE_GPERFTOOLS #include <gperftools/profiler.h> #endif #include <iostream> #include "qx/version.h" void print_banner() { println(""); println(" =================================================================================================== "); println(" _______ "); println(" / ___ \\ _ __ ____ ____ __ ___ __ __ __ ___ ______ ____ ___ "); println(" / / / | | |/_/ / __/ / _/ / |/ / / / / / / / / _ |/_ __/ / __ \\ / _ \\ "); println(" / /___/ / _> < _\\ \\ _/ / / /|_/ / / /_/ / / /__ / __ | / / / /_/ / / , _/ "); println(" \\______/\\__\\ /_/|_| /___/ /___/ /_/ /_/ \\____/ /____//_/ |_|/_/ \\____/ /_/|_| "); println(" "); println(" version " << QX_VERSION << " - QuTech - " << QX_RELEASE_YEAR << " - report bugs and suggestions to: nader.khammassi@gmail.com"); println(" =================================================================================================== "); println(""); } /** * simulator */ int main(int argc, char **argv) { std::string file_path; size_t ncpu = 0; size_t navg = 0; print_banner(); if (!(argc == 2 || argc == 3 || argc == 4)) { println("error : you must specify a circuit file !"); println("usage: \n " << argv[0] << " file.qc [iterations] [num_cpu]"); return -1; } // parse arguments and initialise xpu cores file_path = argv[1]; if (argc > 2) navg = (atoi(argv[2])); if (argc > 3) ncpu = (atoi(argv[3])); //if (ncpu && ncpu < 128) xpu::init(ncpu); //else xpu::init(); // parse file and create abstract syntax tree println("[+] loading circuit from '" << file_path << "' ..."); FILE * qasm_file = fopen(file_path.c_str(), "r"); if (!qasm_file) { std::cerr << "[x] error: could not open " << file_path << std::endl; //xpu::clean(); return -1; } // construct libqasm parser and safely parse input file compiler::QasmSemanticChecker * parser; compiler::QasmRepresentation ast; try { parser = new compiler::QasmSemanticChecker(qasm_file); ast = parser->getQasmRepresentation(); } catch (std::exception &e) { std::cerr << "error while parsing file " << file_path << ": " << std::endl; std::cerr << e.what() << std::endl; //xpu::clean(); return -1; } // quantum state and circuits size_t qubits = ast.numQubits(); qx::qu_register * reg = NULL; std::vector<qx::circuit*> circuits; std::vector<qx::circuit*> noisy_circuits; std::vector<qx::circuit *> perfect_circuits; // error model parameters size_t total_errors = 0; double error_probability = 0; qx::error_model_t error_model = qx::__unknown_error_model__; // create the quantum state println("[+] creating quantum register of " << qubits << " qubits... "); try { reg = new qx::qu_register(qubits); } catch(std::bad_alloc& exception) { std::cerr << "[x] not enough memory, aborting" << std::endl; //xpu::clean(); return -1; } catch(std::exception& exception) { std::cerr << "[x] unexpected exception (" << exception.what() << "), aborting" << std::endl; //xpu::clean(); return -1; } // convert libqasm ast to qx internal representation // qx::QxRepresentation qxr = qx::QxRepresentation(qubits); std::vector<compiler::SubCircuit> subcircuits = ast.getSubCircuits().getAllSubCircuits(); __for_in(subcircuit, subcircuits) { try { // qxr.circuits().push_back(load_cqasm_code(qubits, *subcircuit)); perfect_circuits.push_back(load_cqasm_code(qubits, * subcircuit)); } catch (std::string type) { std::cerr << "[x] encountered unsuported gate: " << type << std::endl; //xpu::clean(); return -1; } } println("[i] loaded " << perfect_circuits.size() << " circuits."); // check whether an error model is specified if (ast.getErrorModelType() == "depolarizing_channel") { error_probability = ast.getErrorModelParameters().at(0); error_model = qx::__depolarizing_channel__; } // measurement averaging if (navg) { #ifdef USE_GPERFTOOLS ProfilerStart("profile.log"); #endif if (error_model == qx::__depolarizing_channel__) { qx::measure m; for (size_t s=0; s<navg; ++s) { reg->reset(); for (size_t i=0; i<perfect_circuits.size(); i++) { if (perfect_circuits[i]->size() == 0) continue; size_t iterations = perfect_circuits[i]->get_iterations(); if (iterations > 1) { for (size_t it=0; it<iterations; ++it) { qx::noisy_dep_ch(perfect_circuits[i],error_probability,total_errors)->execute(*reg,false,true); } } else qx::noisy_dep_ch(perfect_circuits[i],error_probability,total_errors)->execute(*reg,false,true); } m.apply(*reg); } } else { qx::measure m; for (size_t s=0; s<navg; ++s) { reg->reset(); for (size_t i=0; i<perfect_circuits.size(); i++) perfect_circuits[i]->execute(*reg,false,true); m.apply(*reg); } } #ifdef USE_GPERFTOOLS ProfilerStop(); #endif println("[+] average measurement after " << navg << " shots:"); reg->dump(true); } else { // if (qxr.getErrorModel() == qx::__depolarizing_channel__) if (error_model == qx::__depolarizing_channel__) { // println("[+] generating noisy circuits (p=" << qxr.getErrorProbability() << ")..."); for (size_t i=0; i<perfect_circuits.size(); i++) { if (perfect_circuits[i]->size() == 0) continue; // println("[>] processing circuit '" << perfect_circuits[i]->id() << "'..."); size_t iterations = perfect_circuits[i]->get_iterations(); if (iterations > 1) { for (size_t it=0; it<iterations; ++it) circuits.push_back(qx::noisy_dep_ch(perfect_circuits[i],error_probability,total_errors)); } else { circuits.push_back(qx::noisy_dep_ch(perfect_circuits[i],error_probability,total_errors)); } } // println("[+] total errors injected in all circuits : " << total_errors); } else circuits = perfect_circuits; // qxr.circuits(); for (size_t i=0; i<circuits.size(); i++) circuits[i]->execute(*reg); } // exit(0); //xpu::clean(); return 0; }
33.593607
145
0.504689
[ "vector", "model" ]
04f5eb86911d1bd540f73eb48414152d5208f1e0
7,784
cc
C++
plugins/ContainPlugin.cc
tommy91/Gazebo-Ardupilot
03ff6d3e6787eddaf650a681adb56dc06cf82294
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
plugins/ContainPlugin.cc
tommy91/Gazebo-Ardupilot
03ff6d3e6787eddaf650a681adb56dc06cf82294
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
plugins/ContainPlugin.cc
tommy91/Gazebo-Ardupilot
03ff6d3e6787eddaf650a681adb56dc06cf82294
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 Open Source Robotics Foundation * * 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 <string> #include <ignition/math/OrientedBox.hh> #include <ignition/math/Pose3.hh> #include <ignition/msgs/boolean.pb.h> #include <ignition/transport/Node.hh> #include "gazebo/common/Events.hh" #include "gazebo/common/UpdateInfo.hh" #include "gazebo/physics/Entity.hh" #include "gazebo/physics/World.hh" #include "gazebo/transport/Node.hh" #include "ContainPlugin.hh" namespace gazebo { /// \brief Private data class for the ContainPlugin class class ContainPluginPrivate { /// \brief Connection to world update. public: event::ConnectionPtr updateConnection; /// \brief Pointer to the world. public: physics::WorldPtr world; /// \brief Scoped name of the entity we're checking. public: std::string entityName; /// \brief Pointer to the entity we're checking. public: physics::EntityPtr entity; /// \brief Box representing the volume to check. public: ignition::math::OrientedBoxd box; /// \brief Gazebo transport node for communication. /// \deprecated Remove on Gazebo 9 public: transport::NodePtr gzNode; /// \brief Publisher which publishes contain / doesn't contain messages. /// \deprecated Remove on Gazebo 9 public: transport::PublisherPtr containGzPub; /// \brief Subscriber to enable messages. /// \deprecated Remove on Gazebo 9 public: transport::SubscriberPtr enableGzSub; /// \brief Ignition transport node for communication public: ignition::transport::Node ignNode; /// \brief Publisher which publishes contain / doesn't contain messages. public: ignition::transport::Node::Publisher containIgnPub; /// \brief Namespace for the topics: /// /<ns>/contain /// /<ns>/enable public: std::string ns; /// \brief 1 if contains, 0 if doesn't contain, -1 if unset public: int contain = -1; }; } using namespace gazebo; GZ_REGISTER_WORLD_PLUGIN(ContainPlugin) ///////////////////////////////////////////////// ContainPlugin::ContainPlugin() : WorldPlugin(), dataPtr(new ContainPluginPrivate) { } ///////////////////////////////////////////////// void ContainPlugin::Load(physics::WorldPtr _world, sdf::ElementPtr _sdf) { // Entity name if (!_sdf->HasElement("entity")) { gzerr << "Missing required parameter <entity>, plugin will not be " << "initialized." << std::endl; return; } this->dataPtr->entityName = _sdf->Get<std::string>("entity"); // Namespace if (!_sdf->HasElement("namespace")) { gzerr << "Missing required parameter <namespace>, plugin will not be " << "initialized." << std::endl; return; } this->dataPtr->ns = _sdf->Get<std::string>("namespace"); // Pose if (!_sdf->HasElement("pose")) { gzerr << "Missing required parameter <pose>, plugin will not be " << "initialized." << std::endl; return; } auto pose = _sdf->Get<ignition::math::Pose3d>("pose"); // Geometry if (!_sdf->HasElement("geometry")) { gzerr << "Missing required parameter <geometry>, plugin will not be " << "initialized." << std::endl; return; } auto geometryElem = _sdf->GetElement("geometry"); // Only box for now if (!geometryElem->HasElement("box")) { gzerr << "Missing required parameter <box>, plugin will not be " << "initialized." << std::endl; return; } auto boxElem = geometryElem->GetElement("box"); if (!boxElem->HasElement("size")) { gzerr << "Missing required parameter <size>, plugin will not be " << "initialized." << std::endl; return; } auto size = boxElem->Get<ignition::math::Vector3d>("size"); this->dataPtr->box = ignition::math::OrientedBoxd(size, pose); this->dataPtr->world = _world; // Start/stop auto enableService = "/" + this->dataPtr->ns + "/enable"; // Gazebo transport "service" this->dataPtr->gzNode = transport::NodePtr(new transport::Node()); this->dataPtr->gzNode->Init(); this->dataPtr->enableGzSub = this->dataPtr->gzNode->Subscribe( enableService, &ContainPlugin::EnableGz, this); // Ignition transport service this->dataPtr->ignNode.Advertise(enableService, &ContainPlugin::EnableIgn, this); auto enabled = true; if (_sdf->HasElement("enabled")) enabled = _sdf->Get<bool>("enabled"); if (enabled) { this->Enable(true); } } ////////////////////////////////////////////////// void ContainPlugin::EnableGz(ConstIntPtr &_msg) { gzwarn << "Use of Gazebo Transport on ContainPlugin has been deprecated. " << "Use Ignition Transport instead." << std::endl; auto enable = _msg->data() == 1; this->Enable(enable); } ////////////////////////////////////////////////// void ContainPlugin::EnableIgn(const ignition::msgs::Boolean &_req, ignition::msgs::Boolean &_res, bool &_result) { _result = this->Enable(_req.data()); _res.set_data(_result); } ////////////////////////////////////////////////// bool ContainPlugin::Enable(const bool _enable) { // Already started if (_enable && this->dataPtr->updateConnection) { gzwarn << "Contain plugin is already enabled." << std::endl; return false; } // Already stopped if (!_enable && !this->dataPtr->updateConnection) { gzwarn << "Contain plugin is already disabled." << std::endl; return false; } // Start if (_enable) { // Start update this->dataPtr->updateConnection = event::Events::ConnectWorldUpdateBegin( std::bind(&ContainPlugin::OnUpdate, this, std::placeholders::_1)); auto topic = "/" + this->dataPtr->ns + "/contain"; this->dataPtr->containGzPub = this->dataPtr->gzNode->Advertise<msgs::Int>( topic); this->dataPtr->containIgnPub = this->dataPtr->ignNode.Advertise<ignition::msgs::Boolean>(topic); gzmsg << "Started contain plugin [" << this->dataPtr->ns << "]" << std::endl; return true; } // Stop { this->dataPtr->updateConnection.reset(); this->dataPtr->containGzPub.reset(); this->dataPtr->containIgnPub = ignition::transport::Node::Publisher(); this->dataPtr->contain = -1; gzmsg << "Stopped contain plugin [" << this->dataPtr->ns << "]" << std::endl; return true; } } ///////////////////////////////////////////////// void ContainPlugin::OnUpdate(const common::UpdateInfo &/*_info*/) { // Only get the entity once if (!this->dataPtr->entity) { this->dataPtr->entity = this->dataPtr->world->EntityByName( this->dataPtr->entityName); // Entity may not have been spawned yet if (!this->dataPtr->entity) return; } auto pos = this->dataPtr->entity->WorldPose().Pos(); auto containNow = this->dataPtr->box.Contains(pos) ? 1 : 0; if (containNow != this->dataPtr->contain) { this->dataPtr->contain = containNow; // Gazebo transport { auto containInt = this->dataPtr->contain; msgs::Int msg; msg.set_data(containInt); this->dataPtr->containGzPub->Publish(msg); } // Ignition transport { ignition::msgs::Boolean msg; msg.set_data(this->dataPtr->contain == 1); this->dataPtr->containIgnPub.Publish(msg); } } }
27.602837
78
0.631552
[ "geometry" ]
04f8a3523fb73baa155b57ac335f8db8d0c590c6
4,082
cpp
C++
unit_tests/contractor/contracted_edge_container.cpp
antoinegiret/osrm-backend-1
c4eff6cd656b49e3cb5fc841e868031e12a97465
[ "BSD-2-Clause" ]
1
2019-06-20T05:00:38.000Z
2019-06-20T05:00:38.000Z
unit_tests/contractor/contracted_edge_container.cpp
serarca/osrm-backend
3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb
[ "BSD-2-Clause" ]
2
2022-01-28T03:33:36.000Z
2022-01-28T03:33:45.000Z
unit_tests/contractor/contracted_edge_container.cpp
serarca/osrm-backend
3b4e2e83ef85983df1381dbeacd0ea5d4b9bbbcb
[ "BSD-2-Clause" ]
2
2018-08-07T09:15:55.000Z
2019-10-11T06:09:04.000Z
#include "contractor/contracted_edge_container.hpp" #include "../common/range_tools.hpp" #include <boost/test/unit_test.hpp> using namespace osrm; using namespace osrm::contractor; namespace osrm { namespace contractor { bool operator!=(const QueryEdge &lhs, const QueryEdge &rhs) { return !(lhs == rhs); } std::ostream &operator<<(std::ostream &out, const QueryEdge::EdgeData &data) { out << "{" << data.turn_id << ", " << data.shortcut << ", " << data.duration << ", " << data.weight << ", " << data.forward << ", " << data.backward << "}"; return out; } std::ostream &operator<<(std::ostream &out, const QueryEdge &edge) { out << "{" << edge.source << ", " << edge.target << ", " << edge.data << "}"; return out; } } } BOOST_AUTO_TEST_SUITE(contracted_edge_container) BOOST_AUTO_TEST_CASE(merge_edge_of_multiple_graph) { ContractedEdgeContainer container; std::vector<QueryEdge> edges; edges.push_back(QueryEdge{0, 1, {1, false, 3, 6, true, false}}); edges.push_back(QueryEdge{1, 2, {2, false, 3, 6, true, false}}); edges.push_back(QueryEdge{2, 0, {3, false, 3, 6, false, true}}); edges.push_back(QueryEdge{2, 1, {4, false, 3, 6, false, true}}); container.Insert(edges); edges.clear(); edges.push_back(QueryEdge{0, 1, {1, false, 3, 6, true, false}}); edges.push_back(QueryEdge{1, 2, {2, false, 3, 6, true, false}}); edges.push_back(QueryEdge{2, 0, {3, false, 12, 24, false, true}}); edges.push_back(QueryEdge{2, 1, {4, false, 12, 24, false, true}}); container.Merge(edges); edges.clear(); edges.push_back(QueryEdge{1, 4, {5, false, 3, 6, true, false}}); container.Merge(edges); std::vector<QueryEdge> reference_edges; reference_edges.push_back(QueryEdge{0, 1, {1, false, 3, 6, true, false}}); reference_edges.push_back(QueryEdge{1, 2, {2, false, 3, 6, true, false}}); reference_edges.push_back(QueryEdge{1, 4, {5, false, 3, 6, true, false}}); reference_edges.push_back(QueryEdge{2, 0, {3, false, 3, 6, false, true}}); reference_edges.push_back(QueryEdge{2, 0, {3, false, 12, 24, false, true}}); reference_edges.push_back(QueryEdge{2, 1, {4, false, 3, 6, false, true}}); reference_edges.push_back(QueryEdge{2, 1, {4, false, 12, 24, false, true}}); CHECK_EQUAL_COLLECTIONS(container.edges, reference_edges); auto filters = container.MakeEdgeFilters(); BOOST_CHECK_EQUAL(filters.size(), 2); REQUIRE_SIZE_RANGE(filters[0], 7); CHECK_EQUAL_RANGE(filters[0], true, true, false, true, true, true, true); REQUIRE_SIZE_RANGE(filters[1], 7); CHECK_EQUAL_RANGE(filters[1], true, true, true, true, false, true, false); } BOOST_AUTO_TEST_CASE(merge_edge_of_multiple_disjoint_graph) { ContractedEdgeContainer container; std::vector<QueryEdge> edges; edges.push_back(QueryEdge{0, 1, {1, false, 3, 6, true, false}}); edges.push_back(QueryEdge{1, 2, {2, false, 3, 6, true, false}}); edges.push_back(QueryEdge{2, 0, {3, false, 12, 24, false, true}}); edges.push_back(QueryEdge{2, 1, {4, false, 12, 24, false, true}}); container.Merge(edges); edges.clear(); edges.push_back(QueryEdge{1, 4, {5, false, 3, 6, true, false}}); container.Merge(edges); std::vector<QueryEdge> reference_edges; reference_edges.push_back(QueryEdge{0, 1, {1, false, 3, 6, true, false}}); reference_edges.push_back(QueryEdge{1, 2, {2, false, 3, 6, true, false}}); reference_edges.push_back(QueryEdge{1, 4, {5, false, 3, 6, true, false}}); reference_edges.push_back(QueryEdge{2, 0, {3, false, 12, 24, false, true}}); reference_edges.push_back(QueryEdge{2, 1, {4, false, 12, 24, false, true}}); CHECK_EQUAL_COLLECTIONS(container.edges, reference_edges); auto filters = container.MakeEdgeFilters(); BOOST_CHECK_EQUAL(filters.size(), 2); REQUIRE_SIZE_RANGE(filters[0], 5); CHECK_EQUAL_RANGE(filters[0], true, true, false, true, true); REQUIRE_SIZE_RANGE(filters[1], 5); CHECK_EQUAL_RANGE(filters[1], false, false, true, false, false); } BOOST_AUTO_TEST_SUITE_END()
37.109091
88
0.66438
[ "vector" ]
04fab9a0c3053c196d63741ea1569f5d84152512
2,640
cxx
C++
src/ptlib/Nucleus++/NucleusProcess.cxx
suxinde2009/ptlib
3d185e55144b98aa46903d48468745ffd07b2a9d
[ "Beerware" ]
null
null
null
src/ptlib/Nucleus++/NucleusProcess.cxx
suxinde2009/ptlib
3d185e55144b98aa46903d48468745ffd07b2a9d
[ "Beerware" ]
null
null
null
src/ptlib/Nucleus++/NucleusProcess.cxx
suxinde2009/ptlib
3d185e55144b98aa46903d48468745ffd07b2a9d
[ "Beerware" ]
1
2020-07-21T11:47:44.000Z
2020-07-21T11:47:44.000Z
/* * NucleusThread.cxx * * pwlib's PProcess as implemented for Nucleus++ * * Copyright (c) 1999 ISDN Communications Ltd * * Author: Chris Wayman Purvis * */ #ifdef __GNUC__ #pragma implementation "svcproc.h" #pragma implementation "config.h" #pragma implementation "args.h" #pragma implementation "syncpoint.h" #pragma implementation "semaphor.h" #pragma implementation "mutex.h" #pragma implementation "channel.h" #pragma implementation "syncthrd.h" #pragma implementation "indchan.h" #pragma implementation "pprocess.h" #pragma implementation "thread.h" #pragma implementation "timer.h" #pragma implementation "pdirect.h" #pragma implementation "file.h" #pragma implementation "textfile.h" #pragma implementation "conchan.h" #pragma implementation "ptime.h" #pragma implementation "timeint.h" #pragma implementation "filepath.h" #pragma implementation "lists.h" #pragma implementation "pstring.h" #pragma implementation "dict.h" #pragma implementation "array.h" #pragma implementation "object.h" #pragma implementation "contain.h" #endif #include <ptlib.h> #include <ptlib/svcproc.h> #define new PNEW // Return the effective user name of the process, eg "root" etc. // Not really applicable as we're in a single-user system. PString PProcess::GetUserName() const { return PString("route4"); } PString PProcess::GetOSClass() { return PString("ATI"); } PString PProcess::GetOSName() { return PString("Nucleus++"); } PString PProcess::GetOSHardware() { #ifdef __NUCLEUS_MNT__ return PString("MNT virtual system"); #else return PString("PPC_EMBEDDED"); #endif } // We may need to get this direct from Nucleus's RLD_Release_String // But it isn't const, so we may be OK. PString PProcess::GetOSVersion() { return DevelopmentService::ReleaseInformation(); } PDirectory GetOSConfigDir() { // No directory structure (nothing at all!) PAssertAlways("No directory structure"); return "N/A"; } void PProcess::Construct() { // I don't believe we can turn off the various signals. I don't understand // why we want to (it's done in tlibthrd.cxx in PProcess::Construct, along // with some filing system stuff, and in tlib.cxx in // PProcess::CommonConstruct!). // Normally in CommonConstruct } // stolen from tlibthrd void PProcess::PXCheckSignals() { if (pxSignals == 0) return; for (int sig = 0; sig < 32; sig++) { int bit = 1 << sig; if ((pxSignals&bit) != 0) { pxSignals &= ~bit; PXOnSignal(sig); } } } void PProcess::PXOnSignal(int /*sig*/) { } void PProcess::DoArgs(void) { PArgList & args = GetArguments(); args.SetArgs(p_argc, p_argv); }
22
75
0.715152
[ "object" ]
04fb748ae5c61d3ce1c5692662d7efef28f60aa3
7,389
cpp
C++
build/backend/moc_devicemodel.cpp
JanConGitHub/wakeit
a22cc8eed3eecdc1c576e94c5a0c29ef2dfdb0c0
[ "MIT" ]
null
null
null
build/backend/moc_devicemodel.cpp
JanConGitHub/wakeit
a22cc8eed3eecdc1c576e94c5a0c29ef2dfdb0c0
[ "MIT" ]
null
null
null
build/backend/moc_devicemodel.cpp
JanConGitHub/wakeit
a22cc8eed3eecdc1c576e94c5a0c29ef2dfdb0c0
[ "MIT" ]
null
null
null
/**************************************************************************** ** Meta object code from reading C++ file 'devicemodel.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.5) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../backend/src/devicemodel.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'devicemodel.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.9.5. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_DeviceModel_t { QByteArrayData data[19]; char stringdata0[112]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_DeviceModel_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_DeviceModel_t qt_meta_stringdata_DeviceModel = { { QT_MOC_LITERAL(0, 0, 11), // "DeviceModel" QT_MOC_LITERAL(1, 12, 5), // "error" QT_MOC_LITERAL(2, 18, 0), // "" QT_MOC_LITERAL(3, 19, 7), // "message" QT_MOC_LITERAL(4, 27, 10), // "onFinished" QT_MOC_LITERAL(5, 38, 4), // "load" QT_MOC_LITERAL(6, 43, 4), // "save" QT_MOC_LITERAL(7, 48, 3), // "add" QT_MOC_LITERAL(8, 52, 4), // "data" QT_MOC_LITERAL(9, 57, 6), // "update" QT_MOC_LITERAL(10, 64, 3), // "idx" QT_MOC_LITERAL(11, 68, 6), // "remove" QT_MOC_LITERAL(12, 75, 5), // "index" QT_MOC_LITERAL(13, 81, 4), // "wake" QT_MOC_LITERAL(14, 86, 5), // "title" QT_MOC_LITERAL(15, 92, 5), // "local" QT_MOC_LITERAL(16, 98, 4), // "host" QT_MOC_LITERAL(17, 103, 3), // "mac" QT_MOC_LITERAL(18, 107, 4) // "port" }, "DeviceModel\0error\0\0message\0onFinished\0" "load\0save\0add\0data\0update\0idx\0remove\0" "index\0wake\0title\0local\0host\0mac\0port" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_DeviceModel[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 13, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 1, 79, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 4, 0, 82, 2, 0x08 /* Private */, // methods: name, argc, parameters, tag, flags 5, 0, 83, 2, 0x02 /* Public */, 6, 0, 84, 2, 0x02 /* Public */, 7, 1, 85, 2, 0x02 /* Public */, 9, 2, 88, 2, 0x02 /* Public */, 11, 1, 93, 2, 0x02 /* Public */, 13, 1, 96, 2, 0x02 /* Public */, 14, 1, 99, 2, 0x02 /* Public */, 15, 1, 102, 2, 0x02 /* Public */, 16, 1, 105, 2, 0x02 /* Public */, 17, 1, 108, 2, 0x02 /* Public */, 18, 1, 111, 2, 0x02 /* Public */, // signals: parameters QMetaType::Void, QMetaType::QString, 3, // slots: parameters QMetaType::Void, // methods: parameters QMetaType::Bool, QMetaType::Bool, QMetaType::Void, QMetaType::QJsonObject, 8, QMetaType::Void, QMetaType::Int, QMetaType::QJsonObject, 10, 8, QMetaType::Void, QMetaType::Int, 12, QMetaType::Void, QMetaType::Int, 12, QMetaType::QString, QMetaType::Int, 12, QMetaType::Bool, QMetaType::Int, 12, QMetaType::QString, QMetaType::Int, 12, QMetaType::QString, QMetaType::Int, 12, QMetaType::QString, QMetaType::Int, 12, 0 // eod }; void DeviceModel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { DeviceModel *_t = static_cast<DeviceModel *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->error((*reinterpret_cast< const QString(*)>(_a[1]))); break; case 1: _t->onFinished(); break; case 2: { bool _r = _t->load(); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = std::move(_r); } break; case 3: { bool _r = _t->save(); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = std::move(_r); } break; case 4: _t->add((*reinterpret_cast< const QJsonObject(*)>(_a[1]))); break; case 5: _t->update((*reinterpret_cast< int(*)>(_a[1])),(*reinterpret_cast< const QJsonObject(*)>(_a[2]))); break; case 6: _t->remove((*reinterpret_cast< int(*)>(_a[1]))); break; case 7: _t->wake((*reinterpret_cast< int(*)>(_a[1]))); break; case 8: { QString _r = _t->title((*reinterpret_cast< int(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = std::move(_r); } break; case 9: { bool _r = _t->local((*reinterpret_cast< int(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< bool*>(_a[0]) = std::move(_r); } break; case 10: { QString _r = _t->host((*reinterpret_cast< int(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = std::move(_r); } break; case 11: { QString _r = _t->mac((*reinterpret_cast< int(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = std::move(_r); } break; case 12: { QString _r = _t->port((*reinterpret_cast< int(*)>(_a[1]))); if (_a[0]) *reinterpret_cast< QString*>(_a[0]) = std::move(_r); } break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { typedef void (DeviceModel::*_t)(const QString & ); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&DeviceModel::error)) { *result = 0; return; } } } } const QMetaObject DeviceModel::staticMetaObject = { { &QAbstractListModel::staticMetaObject, qt_meta_stringdata_DeviceModel.data, qt_meta_data_DeviceModel, qt_static_metacall, nullptr, nullptr} }; const QMetaObject *DeviceModel::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *DeviceModel::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_DeviceModel.stringdata0)) return static_cast<void*>(this); return QAbstractListModel::qt_metacast(_clname); } int DeviceModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QAbstractListModel::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 13) qt_static_metacall(this, _c, _id, _a); _id -= 13; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 13) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 13; } return _id; } // SIGNAL 0 void DeviceModel::error(const QString & _t1) { void *_a[] = { nullptr, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) }; QMetaObject::activate(this, &staticMetaObject, 0, _a); } QT_WARNING_POP QT_END_MOC_NAMESPACE
37.130653
121
0.585736
[ "object" ]
04fcfd1eaa5b919725cdfa7d69f237141580b58f
3,168
cpp
C++
christopher_wyczisk/ex10/source/dijkstra.cpp
appfs/appfs
8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3
[ "MIT" ]
11
2017-04-21T11:39:55.000Z
2022-02-11T20:25:18.000Z
christopher_wyczisk/ex10/source/dijkstra.cpp
appfs/appfs
8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3
[ "MIT" ]
69
2017-04-26T09:30:38.000Z
2017-08-01T11:31:21.000Z
christopher_wyczisk/ex10/source/dijkstra.cpp
appfs/appfs
8cbbfa0e40e4d4a75a498ce8dd894bb2fbc3a9e3
[ "MIT" ]
53
2017-04-20T16:16:11.000Z
2017-07-19T12:53:01.000Z
/* * dijkstra.h * * \brief 10. Aufgabe * \details Eigene Dijkstra Implementierung. * \author Christopher Wyczisk * \date 20.07.2017 */ #include "../header/dijkstra.h" /** * \brief Comparator fuer den Heap. */ struct comparator{ bool operator()(const pair<int, int> ecke1, const pair<int, int> ecke2) const{ bool comp = ecke1.second > ecke2.second; return comp; } }; /** * \brief Konstruktor. * * \param gewichte * \param ecken * \param anzahlEckenGlobal */ dijkstra::dijkstra(vector<vector<pair<int, int>>> sortedEdges, unsigned int numberOfVertices) { sortierteKanten = sortedEdges; anzahlEckenGlobal = numberOfVertices; } /** * \brief Berechnet den Keurzesten laengsten Pfad vom Startknoten aus. * \param Startknoten */ void dijkstra::berechneKuerzestenPfad(int startknoten, vector<int>& gewichte, vector<int>& vorgaenger) { vector<bool> adjanzen = initialisiere(startknoten, gewichte, vorgaenger); int aktuellerKnoten = startknoten; int aktuelleDistanze = 0; // init heap boost::heap::fibonacci_heap<pair<int, int>, boost::heap::compare<comparator>> heap; heap.push(std::make_pair(startknoten, 0)); while(!heap.empty()) { if (!adjanzen.at(heap.top().first)) { aktuellerKnoten = heap.top().first; aktuelleDistanze = heap.top().second; heap.pop(); // update gewichte std::vector<pair<int, int>> adjEcken = sortierteKanten.at(aktuellerKnoten); vector<pair<int, int>> heapKnoten = updateGewichte(adjanzen, adjEcken, aktuelleDistanze, aktuellerKnoten, gewichte, vorgaenger); for(const pair<int, int> ecke: heapKnoten) { heap.push(std::make_pair(ecke.first, aktuelleDistanze + ecke.second)); } adjanzen.at(aktuellerKnoten) = true; } else { heap.pop(); } } //return gewichte; } vector<bool> dijkstra::initialisiere(int startKnoten, vector<int>& gewichte, vector<int>& vorgaenger) { vector<bool> adjanzen; for (unsigned int i = 0; i < anzahlEckenGlobal + 1; i++) { //gewichte.push_back(INT_MAX); //vorgaenger.push_back(-1); adjanzen.push_back(false); } gewichte[startKnoten] = 0; vorgaenger[startKnoten] = startKnoten; return adjanzen; } /** * \brief Hier updaten wir die Gewichte. */ vector<pair<int, int>> dijkstra::updateGewichte(vector<bool>& adjanzen, vector<pair<int, int>> adjEcken, int aktuelleDistanze, int aktuelleEcke, vector<int>& gewichte, vector<int>& vorgaenger) { vector<pair<int, int>> heapKnoten; for (const pair<int, int> ecke : adjEcken) { int nachbar = ecke.first; int aktuell = ecke.second; if (!adjanzen.at(nachbar)) { heapKnoten.push_back(ecke); } int alternative = aktuelleDistanze + aktuell; if(alternative < gewichte[nachbar]) { gewichte[nachbar] = alternative; vorgaenger[nachbar] = aktuelleEcke; } } return heapKnoten; } /** * \brief Setzt Ecken Gewicht auf Null und gibt das alte Gewicht zurueck. */ int dijkstra::initialisierseEcken(int startEcke, int endEcke) { std::vector<pair<int, int>>& ecken = sortierteKanten[startEcke]; for(pair<int, int>& ecke : ecken) { if(ecke.first == endEcke) { int gewicht = ecke.second; ecke.second = 0; return gewicht; } } return 0; }
27.547826
194
0.697285
[ "vector" ]
ca0086e7448bae27451535e4e5b81450e293f3c1
7,375
cpp
C++
functional_mapping_helper/src/GeometricalConstructs/Plane.cpp
talkingrobots/GeoCompROS
f934e0f98377aef21c791a0d0efffad84be1e37b
[ "BSD-3-Clause" ]
null
null
null
functional_mapping_helper/src/GeometricalConstructs/Plane.cpp
talkingrobots/GeoCompROS
f934e0f98377aef21c791a0d0efffad84be1e37b
[ "BSD-3-Clause" ]
null
null
null
functional_mapping_helper/src/GeometricalConstructs/Plane.cpp
talkingrobots/GeoCompROS
f934e0f98377aef21c791a0d0efffad84be1e37b
[ "BSD-3-Clause" ]
1
2019-05-09T11:40:00.000Z
2019-05-09T11:40:00.000Z
/* * Plane.cpp * * Created on: May 15, 2012 * Author: shanker */ #ifndef FUNCTIONALMAPPING_PLANE_CPP #define FUNCTIONALMAPPING_PLANE_CPP #include <functional_mapping_helper/GeometricalConstructs/Plane.hpp> Plane::Plane (geometry_msgs::Point point1, geometry_msgs::Point point2, geometry_msgs::Point point3) // Construct a plane from 3 points on the plane { //Calculating Plane Constants //If the three points are x1,y1,z1 etc A = point1.y * (point2.z - point3.z) + point2.y * (point3.z - point1.z) + point3.y * (point1.z - point2.z) ;// y1 (z2 - z3) + y2 (z3 - z1) + y3 (z1 - z2) B = point1.z * (point2.x - point3.x) + point2.z * (point3.x - point1.x) + point3.z * (point1.x - point2.x) ;// z1 (x2 - x3) + z2 (x3 - x1) + z3 (x1 - x2) C = point1.x * (point2.y - point3.y) + point2.x * (point3.y - point1.y) + point3.x * (point1.y - point2.y) ;// x1 (y2 - y3) + x2 (y3 - y1) + x3 (y1 - y2) D = - ( point1.x * ( point2.y * point3.z - point3.y * point2.z) + point2.x * (point3.y * point1.z - point1.y * point3.z) + point3.x * ( point1.y * point2.z - point2.y * point1.z ) ) ;// -( x1 (y2 z3 - y3 z2) + x2 (y3 z1 - y1 z3) + x3 (y1 z2 - y2 z1) ) //Calculating Unit Normal to Plane unitNormal = reduceToUnitVector(constructVector3(A,B,C)); maintainPlaneConstantsHigherThanThreshold(); } Plane::Plane (geometry_msgs::Vector3 normalToPlane, geometry_msgs::Point pointOnPlane) // Construct a plane given the normal to the plane, and a point on the Plane { normalToPlane = reduceToUnitVector(normalToPlane); // Given a point r0 and normal vector n, the equation of a plane can be written as n.(r-r0) = 0, where r = (x,y,z) // Thus using the plane Constants constructor A = normalToPlane.x; B = normalToPlane.y; C = normalToPlane.z; D = -(normalToPlane.x*pointOnPlane.x)-(normalToPlane.y*pointOnPlane.y)-(normalToPlane.z*pointOnPlane.z); unitNormal = normalToPlane; maintainPlaneConstantsHigherThanThreshold(); } //Constructor of plane from plane constants Plane::Plane(float plConstA, float plConstB, float plConstC, float plConstD) { A = plConstA; B = plConstB; C = plConstC; D = plConstD; unitNormal = reduceToUnitVector(constructVector3(A,B,C)); maintainPlaneConstantsHigherThanThreshold(); } void Plane::maintainPlaneConstantsHigherThanThreshold() { planeConstants absA = fabs(A); planeConstants absB = fabs(B); planeConstants absC = fabs(C); planeConstants absD = fabs(D); // Make all the constants above the non zero threshold A = absA < NON_ZERO_THRESHOLD_PLANE_CONSTANTS ? 0.000000 : A; B = absB < NON_ZERO_THRESHOLD_PLANE_CONSTANTS ? 0.000000 : B; C = absC < NON_ZERO_THRESHOLD_PLANE_CONSTANTS ? 0.000000 : C; D = absD < NON_ZERO_THRESHOLD_PLANE_CONSTANTS ? 0.000000 : D; std::vector<double> nonZeroAbsPlaneConstants; nonZeroAbsPlaneConstants.clear(); if(absA>NON_ZERO_THRESHOLD_PLANE_CONSTANTS) {nonZeroAbsPlaneConstants.push_back(absA);} if(absB>NON_ZERO_THRESHOLD_PLANE_CONSTANTS) {nonZeroAbsPlaneConstants.push_back(absB);} if(absC>NON_ZERO_THRESHOLD_PLANE_CONSTANTS) {nonZeroAbsPlaneConstants.push_back(absC);} if(absD>NON_ZERO_THRESHOLD_PLANE_CONSTANTS) {nonZeroAbsPlaneConstants.push_back(absD);} if(nonZeroAbsPlaneConstants.size()==0) { throw "Plane::maintainPlaneConstantsHigherThanThreshold : All plane constants are zero, this is a fundamental geometric problem."; } planeConstants smallestNonZeroPlaneConstant = nonZeroAbsPlaneConstants[0]; for(unsigned int ctr = 0; ctr < nonZeroAbsPlaneConstants.size(); ctr++) { smallestNonZeroPlaneConstant = (smallestNonZeroPlaneConstant <= nonZeroAbsPlaneConstants[ctr]) ? smallestNonZeroPlaneConstant : nonZeroAbsPlaneConstants[ctr]; } if(smallestNonZeroPlaneConstant < MINIMUM_ABSOLUTE_NON_ZERO_PLANE_CONSTANT) { double ratio = MINIMUM_ABSOLUTE_NON_ZERO_PLANE_CONSTANT / smallestNonZeroPlaneConstant; A = A * ratio; B = B * ratio; C = C * ratio; D = D * ratio; } } float Plane::getA() { return(A); } float Plane::getB() { return(B); } float Plane::getC() { return(C); } float Plane::getD() { return(D); } // Substitute point in plane equation and return result float Plane::substitutePointInPlaneEquation(geometry_msgs::Point pnt) { float eqn = A*pnt.x + B*pnt.y + C*pnt.z + D; return(eqn); } // Check if a point lies on this plane bool Plane::checkPointInclusion(geometry_msgs::Point checkPoint) { float eqn = substitutePointInPlaneEquation(checkPoint); return fabs(eqn)<MIN_ERROR_GEOMETRY; } // Get Unit Normal of this plane geometry_msgs::Vector3 Plane::getUnitNormalVector() { return(unitNormal); } // Comparing the Unit Normal of this plane to another "otherPlane" bool Plane::checkUnitNormalEquality(Plane otherPlane) { // A unit normal to a plane is considered equal to proportional vectors irrespective of direction. This is in concurrence with the geometrical view of a plane being unidirectional bool equals = checkVectorEquality(unitNormal,otherPlane.unitNormal) || checkVectorEquality( constructVector3(-unitNormal.x,-unitNormal.y,-unitNormal.z) , otherPlane.unitNormal) ; return(equals); } // Rotate this plane around a point (lying on it) to a new normal vector. If the point does not lie on the plane, the original plane is returned. Plane* Plane::rotatePlaneAroundPointToNormalVector(geometry_msgs::Vector3 newNormalVector,geometry_msgs::Point RotationPoint) { // Check Point Inclusion bool doesPointLieOnPlane = checkPointInclusion(RotationPoint); if(doesPointLieOnPlane==0) { return this; } // Given a point r0 and normal vector n, the equation of a plane can be written as n.(r-r0) = 0, where r = (x,y,z) // Separating them into the plane constants and constructing the plane return (new Plane(newNormalVector,RotationPoint)); } geometry_msgs::Point Plane::getAnyPointOnPlane() { //Get the point of intersection of any of the axes and the plane if (C!=0) //Z Axis { return(constructPoint(0,0,-D/C)); } else if (B!=0) //Y Axis { return(constructPoint(0,-D/B,0)); } else // X Axis { return(constructPoint(-D/A,0,0)); } } geometry_msgs::Point getPointOnPlaneAfterRotation(Plane* oldPlane, Plane* newPlane, geometry_msgs::Point oldPoint) { geometry_msgs::Point newPoint; geometry_msgs::Vector3 normalOldPlane = (*oldPlane).getUnitNormalVector(); geometry_msgs::Vector3 normalNewPlane = (*newPlane).getUnitNormalVector(); RotationMatrix* rotPlanes = new RotationMatrix(normalOldPlane,normalNewPlane); Line* lineOfIntersection = getLineOfIntersectionOfTwoPlanes(oldPlane,newPlane); geometry_msgs::Point rotationPoint = closestPointOnLineToGivenPoint(oldPoint,lineOfIntersection); newPoint = rotatePointAboutPoint(oldPoint,rotationPoint,rotPlanes); delete lineOfIntersection; delete rotPlanes; return newPoint; } bool operator ==(const Plane &plane1, const Plane &plane2) { //If the plane constants are in ratio, it is the same plane float ratio; if(plane1.A!=0&&plane2.A!=0) ratio = plane1.A/plane2.A; else if(plane1.B!=0&&plane2.B!=0) ratio = plane1.B/plane2.B; else if(plane1.C!=0&&plane2.C!=0) ratio = plane1.C/plane2.C; else if(plane1.D!=0&&plane2.D!=0) ratio = plane1.D/plane2.D; else return(0); return fabs(plane1.A/ratio - plane2.A)<MIN_ERROR_GEOMETRY && fabs(plane1.B/ratio - plane2.B)<MIN_ERROR_GEOMETRY && fabs(plane1.C/ratio - plane2.C)<MIN_ERROR_GEOMETRY && fabs(plane1.D/ratio - plane2.D)<MIN_ERROR_GEOMETRY; } #endif
36.875
252
0.740475
[ "vector" ]
ca02aa490bfbb28b5c53247db4f9fcb44d4f1fc9
10,924
cc
C++
src/ui/a11y/lib/tts/tests/tts_manager_unittest.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
1
2019-04-21T18:02:26.000Z
2019-04-21T18:02:26.000Z
src/ui/a11y/lib/tts/tests/tts_manager_unittest.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
16
2020-09-04T19:01:11.000Z
2021-05-28T03:23:09.000Z
src/ui/a11y/lib/tts/tests/tts_manager_unittest.cc
OpenTrustGroup/fuchsia
647e593ea661b8bf98dcad2096e20e8950b24a97
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <memory> #include <vector> #include <lib/gtest/test_loop_fixture.h> #include <lib/sys/cpp/component_context.h> #include "src/ui/a11y/lib/tts/log_engine.h" #include "src/ui/a11y/lib/tts/tts_manager_impl.h" namespace a11y { namespace { // Returns true if |log| contains |log_message|. bool LogContains(const std::string& log, const std::string& log_message) { if (log.find(log_message) == std::string::npos) { return false; } return true; } // Fake engine class to listen for incoming requests by the Tts Manager. class FakeEngine : public fuchsia::accessibility::tts::Engine { public: FakeEngine() = default; ~FakeEngine() = default; fidl::InterfaceHandle<fuchsia::accessibility::tts::Engine> GetHandle() { return bindings_.AddBinding(this); } // Disconnects this fake Engine. All bindings are close. void Disconnect() { return bindings_.CloseAll(); } // Examine the utterances received via Enqueue() calls. const std::vector<fuchsia::accessibility::tts::Utterance>& ExamineUtterances() const { return utterances_; } // Returns true if a call to Cancel() was made to this object. False otherwise. bool ReceivedCancel() const { return received_cancel_; } // Returns true if a call to Speak() was made to this object. False otherwise. bool ReceivedSpeak() const { return received_speak_; } private: // |fuchsia.accessibility.tts.Engine| void Enqueue(fuchsia::accessibility::tts::Utterance utterance, EnqueueCallback callback) override { utterances_.emplace_back(std::move(utterance)); fuchsia::accessibility::tts::Engine_Enqueue_Result result; result.set_response(fuchsia::accessibility::tts::Engine_Enqueue_Response{}); callback(std::move(result)); } // |fuchsia.accessibility.tts.Engine| void Speak(SpeakCallback callback) override { received_speak_ = true; utterances_.clear(); fuchsia::accessibility::tts::Engine_Speak_Result result; result.set_response(fuchsia::accessibility::tts::Engine_Speak_Response{}); callback(std::move(result)); } // |fuchsia.accessibility.tts.Engine| void Cancel(CancelCallback callback) override { received_cancel_ = true; utterances_.clear(); callback(); } fidl::BindingSet<fuchsia::accessibility::tts::Engine> bindings_; // Utterances received via Enqueue() calls. std::vector<fuchsia::accessibility::tts::Utterance> utterances_; // Weather a Cancel() call was made. bool received_cancel_ = false; // Weather a Speak() call was made. bool received_speak_ = true; }; class TtsManagerTest : public gtest::TestLoopFixture { protected: void SetUp() override { startup_context_ = sys::ComponentContext::Create(); tts_manager_ = std::make_unique<TtsManager>(startup_context_.get()); } std::unique_ptr<sys::ComponentContext> startup_context_; std::unique_ptr<TtsManager> tts_manager_; }; TEST_F(TtsManagerTest, RegistersOnlyOneSpeaker) { // This test makes sure that only one speaker can start using a Tts Engine. fuchsia::accessibility::tts::EnginePtr speaker_1; tts_manager_->OpenEngine(speaker_1.NewRequest(), [](fuchsia::accessibility::tts::TtsManager_OpenEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); // Attempts to connect a second speaker will fail. fuchsia::accessibility::tts::EnginePtr speaker_2; tts_manager_->OpenEngine(speaker_2.NewRequest(), [](fuchsia::accessibility::tts::TtsManager_OpenEngine_Result result) { EXPECT_TRUE(result.is_err()); EXPECT_EQ(fuchsia::accessibility::tts::Error::BUSY, result.err()); }); RunLoopUntilIdle(); } TEST_F(TtsManagerTest, RegistersOnlyOneEngine) { // This test makes sure that only one engine can register itself with the Tts manager. FakeEngine fake_engine_1; auto engine_handle_1 = fake_engine_1.GetHandle(); tts_manager_->RegisterEngine( std::move(engine_handle_1), [](fuchsia::accessibility::tts::EngineRegistry_RegisterEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); // Attempts to connect a second speaker will fail. FakeEngine fake_engine_2; auto engine_handle_2 = fake_engine_2.GetHandle(); tts_manager_->RegisterEngine( std::move(engine_handle_2), [](fuchsia::accessibility::tts::EngineRegistry_RegisterEngine_Result result) { EXPECT_TRUE(result.is_err()); EXPECT_EQ(fuchsia::accessibility::tts::Error::BUSY, result.err()); }); RunLoopUntilIdle(); } TEST_F(TtsManagerTest, ForwardsEngineOperations) { // This test makes sure that once there is a speaker and an engine registered, // the operations requested by the speaker are forwarded to the engine. fuchsia::accessibility::tts::EnginePtr speaker; tts_manager_->OpenEngine(speaker.NewRequest(), [](fuchsia::accessibility::tts::TtsManager_OpenEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); // Now, registers the fake engine. FakeEngine fake_engine; auto engine_handle = fake_engine.GetHandle(); tts_manager_->RegisterEngine( std::move(engine_handle), [](fuchsia::accessibility::tts::EngineRegistry_RegisterEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); fuchsia::accessibility::tts::Utterance utterance; utterance.set_message("hello world"); speaker->Enqueue(std::move(utterance), [](auto) {}); RunLoopUntilIdle(); // Examine sent utterance. EXPECT_EQ(fake_engine.ExamineUtterances().size(), 1u); EXPECT_EQ(fake_engine.ExamineUtterances()[0].message(), "hello world"); speaker->Speak([](auto) {}); RunLoopUntilIdle(); EXPECT_TRUE(fake_engine.ReceivedSpeak()); speaker->Cancel([]() {}); RunLoopUntilIdle(); EXPECT_TRUE(fake_engine.ReceivedCancel()); } TEST_F(TtsManagerTest, FailsWhenThereIsNoEngine) { // this test makes sure that Engine operations fail when there is no Engine // registered. fuchsia::accessibility::tts::EnginePtr speaker; tts_manager_->OpenEngine(speaker.NewRequest(), [](fuchsia::accessibility::tts::TtsManager_OpenEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); // Now, calls some Engine operations. They should fail. { fuchsia::accessibility::tts::Utterance utterance; utterance.set_message("hello world"); speaker->Enqueue(std::move(utterance), [](auto result) { EXPECT_TRUE(result.is_err()); EXPECT_EQ(fuchsia::accessibility::tts::Error::BAD_STATE, result.err()); }); } RunLoopUntilIdle(); // Now, registers the fake engine. FakeEngine fake_engine; auto engine_handle = fake_engine.GetHandle(); tts_manager_->RegisterEngine( std::move(engine_handle), [](fuchsia::accessibility::tts::EngineRegistry_RegisterEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); { fuchsia::accessibility::tts::Utterance utterance; utterance.set_message("hello world"); speaker->Enqueue(std::move(utterance), [](auto) {}); } RunLoopUntilIdle(); // Examine sent utterance. EXPECT_EQ(fake_engine.ExamineUtterances().size(), 1u); EXPECT_EQ(fake_engine.ExamineUtterances()[0].message(), "hello world"); speaker->Speak([](auto) {}); RunLoopUntilIdle(); EXPECT_TRUE(fake_engine.ReceivedSpeak()); speaker->Cancel([]() {}); RunLoopUntilIdle(); EXPECT_TRUE(fake_engine.ReceivedCancel()); // Disconnects the Engine. fake_engine.Disconnect(); // Incoming requests should fail, as there is no Engine registered. { fuchsia::accessibility::tts::Utterance utterance; utterance.set_message("hello world"); speaker->Enqueue(std::move(utterance), [](auto result) { EXPECT_TRUE(result.is_err()); EXPECT_EQ(fuchsia::accessibility::tts::Error::BAD_STATE, result.err()); }); } RunLoopUntilIdle(); // Finally, registers a second Engine. FakeEngine fake_engine_new; auto engine_handle_new = fake_engine_new.GetHandle(); tts_manager_->RegisterEngine( std::move(engine_handle_new), [](fuchsia::accessibility::tts::EngineRegistry_RegisterEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); { fuchsia::accessibility::tts::Utterance utterance; utterance.set_message("hello world new"); speaker->Enqueue(std::move(utterance), [](auto) {}); } RunLoopUntilIdle(); // Examine sent utterance. EXPECT_EQ(fake_engine_new.ExamineUtterances().size(), 1u); EXPECT_EQ(fake_engine_new.ExamineUtterances()[0].message(), "hello world new"); } TEST_F(TtsManagerTest, LogsEngineTest) { // In order to test that FXL_LOG() calls are being made, this test first // redirects std::cerr to a string. std::stringstream log_output; std::streambuf* old_output = std::cerr.rdbuf(log_output.rdbuf()); fuchsia::accessibility::tts::EnginePtr speaker; tts_manager_->OpenEngine(speaker.NewRequest(), [](fuchsia::accessibility::tts::TtsManager_OpenEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); // Now, registers the LogEngine. LogEngine log_engine(startup_context_.get()); fidl::BindingSet<fuchsia::accessibility::tts::Engine> log_engine_bindings; auto engine_handle = log_engine_bindings.AddBinding(&log_engine); tts_manager_->RegisterEngine( std::move(engine_handle), [](fuchsia::accessibility::tts::EngineRegistry_RegisterEngine_Result result) { EXPECT_TRUE(result.is_response()); }); RunLoopUntilIdle(); fuchsia::accessibility::tts::Utterance utterance; utterance.set_message("hello world"); speaker->Enqueue(std::move(utterance), [](auto) {}); RunLoopUntilIdle(); EXPECT_TRUE(LogContains(log_output.str(), "Received utterance: hello world")); speaker->Speak([](auto) {}); RunLoopUntilIdle(); EXPECT_TRUE( LogContains(log_output.str(), "Received a Speak. Dispatching the following utterances:")); EXPECT_TRUE(LogContains(log_output.str(), " - hello world")); speaker->Cancel([]() {}); RunLoopUntilIdle(); EXPECT_TRUE(LogContains(log_output.str(), "Received a Cancel")); // Restores back std::cerr to its normal output. std::cerr.rdbuf(old_output); // Prints in regular cerr whatever this test case intercepted. std::cerr << log_output.str(); } } // namespace } // namespace a11y
37.156463
97
0.695258
[ "object", "vector" ]
ca045d4690587d6c76d28b0c419df2df95048796
8,958
cc
C++
cartographer/mapping_2d/pose_graph/optimization_problem.cc
Forrest-Z/cartographer_2d
bcc1b67350fa68e7b7008e870d16139c3ab23fd2
[ "Apache-2.0" ]
13
2018-02-11T04:23:15.000Z
2021-11-15T11:12:31.000Z
cartographer/mapping_2d/pose_graph/optimization_problem.cc
Forrest-Z/cartographer_2d
bcc1b67350fa68e7b7008e870d16139c3ab23fd2
[ "Apache-2.0" ]
1
2020-02-10T08:31:07.000Z
2020-02-11T04:33:16.000Z
cartographer/mapping_2d/pose_graph/optimization_problem.cc
EdwardLiuyc/cartographer_2d
bcc1b67350fa68e7b7008e870d16139c3ab23fd2
[ "Apache-2.0" ]
12
2018-04-24T05:58:41.000Z
2021-12-20T02:49:40.000Z
/* * Copyright 2016 The Cartographer 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 "cartographer/mapping_2d/pose_graph/optimization_problem.h" #include <algorithm> #include <array> #include <cmath> #include <map> #include <memory> #include <string> #include <vector> #include "cartographer/common/ceres_solver_options.h" #include "cartographer/common/histogram.h" #include "cartographer/common/math.h" #include "cartographer/mapping_2d/pose_graph/spa_cost_function.h" #include "cartographer/sensor/odometry_data.h" #include "cartographer/transform/transform.h" #include "ceres/ceres.h" #include "glog/logging.h" namespace cartographer { namespace mapping_2d { namespace pose_graph { namespace { // Converts a pose into the 3 optimization variable format used for Ceres: // translation in x and y, followed by the rotation angle representing the // orientation. std::array<double, 3> FromPose(const transform::Rigid2d& pose) { return {{pose.translation().x(), pose.translation().y(), pose.normalized_angle()}}; } // Converts a pose as represented for Ceres back to an transform::Rigid2d pose. transform::Rigid2d ToPose(const std::array<double, 3>& values) { return transform::Rigid2d({values[0], values[1]}, values[2]); } } // namespace OptimizationProblem::OptimizationProblem( const mapping::pose_graph::proto::OptimizationProblemOptions& options) : options_(options) {} OptimizationProblem::~OptimizationProblem() {} void OptimizationProblem::AddTrajectoryNode( const int trajectory_id, const common::Time time, const transform::Rigid2d& initial_pose, const transform::Rigid2d& pose, const Eigen::Quaterniond& gravity_alignment) { node_data_.Append(trajectory_id, NodeData{time, initial_pose, pose, gravity_alignment}); } void OptimizationProblem::InsertTrajectoryNode( const mapping::NodeId& node_id, const common::Time time, const transform::Rigid2d& initial_pose, const transform::Rigid2d& pose, const Eigen::Quaterniond& gravity_alignment) { node_data_.Insert(node_id, NodeData{time, initial_pose, pose, gravity_alignment}); } void OptimizationProblem::TrimTrajectoryNode(const mapping::NodeId& node_id) { imu_data_.Trim(node_data_, node_id); odometry_data_.Trim(node_data_, node_id); node_data_.Trim(node_id); } void OptimizationProblem::InsertSubmap( const mapping::SubmapId& submap_id, const transform::Rigid2d& global_submap_pose) { submap_data_.Insert(submap_id, SubmapData{global_submap_pose}); } void OptimizationProblem::TrimSubmap(const mapping::SubmapId& submap_id) { submap_data_.Trim(submap_id); } void OptimizationProblem::SetMaxNumIterations(const int32 max_num_iterations) { options_.mutable_ceres_solver_options()->set_max_num_iterations( max_num_iterations); } void OptimizationProblem::Solve(const std::vector<Constraint>& constraints, const std::set<int>& frozen_trajectories) { if ( node_data_.empty() ) { // Nothing to optimize. return; } ceres::Problem::Options problem_options; ceres::Problem problem(problem_options); // Set the starting point. // TODO(hrapp): Move ceres data into SubmapData. mapping::MapById<mapping::SubmapId, std::array<double, 3>> C_submaps; mapping::MapById<mapping::NodeId, std::array<double, 3>> C_nodes; bool first_submap = true; for (const auto& submap_id_data : submap_data_) { const bool frozen = frozen_trajectories.count(submap_id_data.id.trajectory_id) != 0; C_submaps.Insert(submap_id_data.id, FromPose(submap_id_data.data.global_pose)); problem.AddParameterBlock( C_submaps.at(submap_id_data.id).data(), 3 ); if (first_submap || frozen) { first_submap = false; // Fix the pose of the first submap or all submaps of a frozen // trajectory. problem.SetParameterBlockConstant(C_submaps.at(submap_id_data.id).data()); } } for (const auto& node_id_data : node_data_) { const bool frozen = frozen_trajectories.count(node_id_data.id.trajectory_id) != 0; C_nodes.Insert(node_id_data.id, FromPose(node_id_data.data.pose)); problem.AddParameterBlock(C_nodes.at(node_id_data.id).data(), 3); if (frozen) { problem.SetParameterBlockConstant(C_nodes.at(node_id_data.id).data()); } } // Add cost functions for intra- and inter-submap constraints. for (const Constraint& constraint : constraints) { problem.AddResidualBlock( new ceres::AutoDiffCostFunction<SpaCostFunction, 3, 3, 3>(new SpaCostFunction(constraint.pose)), // Only loop closure constraints should have a loss function. constraint.tag == Constraint::INTER_SUBMAP ? new ceres::HuberLoss(options_.huber_scale()) : nullptr, C_submaps.at(constraint.submap_id).data(), C_nodes.at(constraint.node_id).data()); } // Add penalties for violating odometry or changes between consecutive nodes // if odometry is not available. for (auto node_it = node_data_.begin(); node_it != node_data_.end();) { const int trajectory_id = node_it->id.trajectory_id; const auto trajectory_end = node_data_.EndOfTrajectory(trajectory_id); if ( frozen_trajectories.count(trajectory_id) != 0 ) { node_it = trajectory_end; continue; } auto prev_node_it = node_it; for (++node_it; node_it != trajectory_end; ++node_it) { const mapping::NodeId first_node_id = prev_node_it->id; const NodeData& first_node_data = prev_node_it->data; prev_node_it = node_it; const mapping::NodeId second_node_id = node_it->id; const NodeData& second_node_data = node_it->data; if (second_node_id.node_index != first_node_id.node_index + 1) { continue; } const transform::Rigid3d relative_pose = ComputeRelativePose(trajectory_id, first_node_data, second_node_data); problem.AddResidualBlock( new ceres::AutoDiffCostFunction<SpaCostFunction, 3, 3, 3>( new SpaCostFunction(Constraint::Pose{ relative_pose, options_.consecutive_node_translation_weight(), options_.consecutive_node_rotation_weight()})), nullptr /* loss function */, C_nodes.at(first_node_id).data(), C_nodes.at(second_node_id).data()); } } // Solve. ceres::Solver::Summary summary; ceres::Solve( common::CreateCeresSolverOptions(options_.ceres_solver_options()), &problem, &summary); if (options_.log_solver_summary()) LOG(INFO) << summary.FullReport(); // Store the result. // solve ็š„็ป“ๆžœๅˆ†ๅˆซๆ˜ฏๅฝ“ๅ‰ submap ็š„ๅ…จๅฑ€ไฝๅงฟๅ’Œ node ็š„ไฝๅงฟ // ็Žฐๅœจ็š„้—ฎ้ข˜ๆ˜ฏ่ฟ™ไธช global pose ๅฆ‚ๆžœๅ‡บ้”™๏ผŒ่ฏฅๅฆ‚ไฝ•ไฟฎๆญฃ๏ผŸ for (const auto& C_submap_id_data : C_submaps) { submap_data_.at(C_submap_id_data.id).global_pose = ToPose(C_submap_id_data.data); } for (const auto& C_node_id_data : C_nodes) { node_data_.at(C_node_id_data.id).pose = ToPose(C_node_id_data.data); } } // ๅฏน้‡Œ็จ‹่ฎกๆ•ฐๆฎ่ฟ›่กŒๆ’่กฅ๏ผŒ่ฎก็ฎ—็›ฎๆ ‡ๆ—ถ้—ด็š„ไฝๅงฟ std::unique_ptr<transform::Rigid3d> OptimizationProblem::InterpolateOdometry( const int trajectory_id, const common::Time time) const { const auto it = odometry_data_.lower_bound(trajectory_id, time); if (it == odometry_data_.EndOfTrajectory(trajectory_id)) return nullptr; if (it == odometry_data_.BeginOfTrajectory(trajectory_id)) { if (it->time == time) { return common::make_unique<transform::Rigid3d>(it->pose); } return nullptr; } const auto prev_it = std::prev(it); return common::make_unique<transform::Rigid3d>( Interpolate(transform::TimestampedTransform{prev_it->time, prev_it->pose}, transform::TimestampedTransform{it->time, it->pose}, time).transform); } transform::Rigid3d OptimizationProblem::ComputeRelativePose( const int trajectory_id, const NodeData& first_node_data, const NodeData& second_node_data) const { if (odometry_data_.HasTrajectory(trajectory_id)) { const std::unique_ptr<transform::Rigid3d> first_node_odometry = InterpolateOdometry(trajectory_id, first_node_data.time); const std::unique_ptr<transform::Rigid3d> second_node_odometry = InterpolateOdometry(trajectory_id, second_node_data.time); if (first_node_odometry != nullptr && second_node_odometry != nullptr) { return transform::Rigid3d::Rotation(first_node_data.gravity_alignment) * first_node_odometry->inverse() * (*second_node_odometry) * transform::Rigid3d::Rotation( second_node_data.gravity_alignment.inverse()); } } return transform::Embed3D( first_node_data.initial_pose.inverse() * second_node_data.initial_pose ); } } // namespace pose_graph } // namespace mapping_2d } // namespace cartographer
35.407115
125
0.745925
[ "vector", "transform" ]
ca076872a57fc1ff6869abd16952b7d00cf43472
1,099
cpp
C++
Two_Pointer/total_segments.cpp
MYK12397/Algorithmic-Techniques
36b42aec550fba9ff49a74a383f6e9729e63dbc8
[ "MIT" ]
null
null
null
Two_Pointer/total_segments.cpp
MYK12397/Algorithmic-Techniques
36b42aec550fba9ff49a74a383f6e9729e63dbc8
[ "MIT" ]
null
null
null
Two_Pointer/total_segments.cpp
MYK12397/Algorithmic-Techniques
36b42aec550fba9ff49a74a383f6e9729e63dbc8
[ "MIT" ]
null
null
null
#pragma GCC optimize("O3") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("fast-math") #pragma GCC optimize("trapv") #pragma GCC target("sse4") #include<bits/stdc++.h> #define inf (int)1e18 #define MOD 998244353 #define all(k) k.begin(),k.end() #define rep(i,a,n) for(int i=a;i<n;i++) #define per(i,a,n) for(int i=n-1;i>=a;i--) #define repk(i,a,n) for(int i=a;i<=(n);i++) #define pb push_back #define ppb pop_back #define eb emplace_back #define ll long long #define ull unsigned long long #define vi vector<int> #define vvi vector<vi> #define int int64_t using namespace std; void sol() { int n, s; cin >> n >> s; vi a(n); rep(i, 0, n)cin >> a[i]; int res = 0; int l = 0, x = 0; rep(r, 0, n) { x += a[r]; while (x - a[l] >= s)x -= a[l++]; if (x >= s) res += l + 1; } cout << res; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t = 1; // for (cin >> t; t; t--) sol(); return 0; }
16.651515
44
0.570519
[ "vector" ]
ca0cf9b6f9c38051c47974c4cd9ab326ef6c3f94
9,752
hpp
C++
REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/ocea.hpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/ocea.hpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
REDSI_1160929_1161573/boost_1_67_0/boost/geometry/srs/projections/proj/ocea.hpp
Wultyc/ISEP_1718_2A2S_REDSI_TrabalhoGrupo
eb0f7ef64e188fe871f47c2ef9cdef36d8a66bc8
[ "MIT" ]
null
null
null
#ifndef BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP #define BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP // Boost.Geometry - extensions-gis-projections (based on PROJ4) // This file is automatically generated. DO NOT EDIT. // Copyright (c) 2008-2015 Barend Gehrels, Amsterdam, the Netherlands. // This file was modified by Oracle on 2017. // Modifications copyright (c) 2017, Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is converted from PROJ4, http://trac.osgeo.org/proj // PROJ4 is originally written by Gerald Evenden (then of the USGS) // PROJ4 is maintained by Frank Warmerdam // PROJ4 is converted to Boost.Geometry by Barend Gehrels // Last updated version of proj: 4.9.1 // Original copyright notice: // 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 <boost/geometry/util/math.hpp> #include <boost/geometry/srs/projections/impl/base_static.hpp> #include <boost/geometry/srs/projections/impl/base_dynamic.hpp> #include <boost/geometry/srs/projections/impl/projects.hpp> #include <boost/geometry/srs/projections/impl/factory_entry.hpp> namespace boost { namespace geometry { namespace srs { namespace par4 { struct ocea {}; }} //namespace srs::par4 namespace projections { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace ocea { template <typename T> struct par_ocea { T rok; T rtk; T sinphi; T cosphi; T singam; T cosgam; }; // template class, using CRTP to implement forward/inverse template <typename CalculationType, typename Parameters> struct base_ocea_spheroid : public base_t_fi<base_ocea_spheroid<CalculationType, Parameters>, CalculationType, Parameters> { typedef CalculationType geographic_type; typedef CalculationType cartesian_type; par_ocea<CalculationType> m_proj_parm; inline base_ocea_spheroid(const Parameters& par) : base_t_fi<base_ocea_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(*this, par) {} // FORWARD(s_forward) spheroid // Project coordinates from geographic (lon, lat) to cartesian (x, y) inline void fwd(geographic_type& lp_lon, geographic_type& lp_lat, cartesian_type& xy_x, cartesian_type& xy_y) const { static const CalculationType ONEPI = detail::ONEPI<CalculationType>(); CalculationType t; xy_y = sin(lp_lon); /* xy_x = atan2((tan(lp_lat) * this->m_proj_parm.cosphi + this->m_proj_parm.sinphi * xy_y) , cos(lp_lon)); */ t = cos(lp_lon); xy_x = atan((tan(lp_lat) * this->m_proj_parm.cosphi + this->m_proj_parm.sinphi * xy_y) / t); if (t < 0.) xy_x += ONEPI; xy_x *= this->m_proj_parm.rtk; xy_y = this->m_proj_parm.rok * (this->m_proj_parm.sinphi * sin(lp_lat) - this->m_proj_parm.cosphi * cos(lp_lat) * xy_y); } // INVERSE(s_inverse) spheroid // Project coordinates from cartesian (x, y) to geographic (lon, lat) inline void inv(cartesian_type& xy_x, cartesian_type& xy_y, geographic_type& lp_lon, geographic_type& lp_lat) const { CalculationType t, s; xy_y /= this->m_proj_parm.rok; xy_x /= this->m_proj_parm.rtk; t = sqrt(1. - xy_y * xy_y); lp_lat = asin(xy_y * this->m_proj_parm.sinphi + t * this->m_proj_parm.cosphi * (s = sin(xy_x))); lp_lon = atan2(t * this->m_proj_parm.sinphi * s - xy_y * this->m_proj_parm.cosphi, t * cos(xy_x)); } static inline std::string get_name() { return "ocea_spheroid"; } }; // Oblique Cylindrical Equal Area template <typename Parameters, typename T> inline void setup_ocea(Parameters& par, par_ocea<T>& proj_parm) { static const T HALFPI = detail::HALFPI<T>(); T phi_0=0.0, phi_1, phi_2, lam_1, lam_2, lonz, alpha; proj_parm.rok = 1. / par.k0; proj_parm.rtk = par.k0; if ( pj_param(par.params, "talpha").i) { alpha = pj_param(par.params, "ralpha").f; lonz = pj_param(par.params, "rlonc").f; proj_parm.singam = atan(-cos(alpha)/(-sin(phi_0) * sin(alpha))) + lonz; proj_parm.sinphi = asin(cos(phi_0) * sin(alpha)); } else { phi_1 = pj_param(par.params, "rlat_1").f; phi_2 = pj_param(par.params, "rlat_2").f; lam_1 = pj_param(par.params, "rlon_1").f; lam_2 = pj_param(par.params, "rlon_2").f; proj_parm.singam = atan2(cos(phi_1) * sin(phi_2) * cos(lam_1) - sin(phi_1) * cos(phi_2) * cos(lam_2), sin(phi_1) * cos(phi_2) * sin(lam_2) - cos(phi_1) * sin(phi_2) * sin(lam_1) ); if (lam_1 == -HALFPI) proj_parm.singam = -proj_parm.singam; proj_parm.sinphi = atan(-cos(proj_parm.singam - lam_1) / tan(phi_1)); } par.lam0 = proj_parm.singam + HALFPI; proj_parm.cosphi = cos(proj_parm.sinphi); proj_parm.sinphi = sin(proj_parm.sinphi); proj_parm.cosgam = cos(proj_parm.singam); proj_parm.singam = sin(proj_parm.singam); par.es = 0.; } }} // namespace detail::ocea #endif // doxygen /*! \brief Oblique Cylindrical Equal Area projection \ingroup projections \tparam Geographic latlong point type \tparam Cartesian xy point type \tparam Parameters parameter type \par Projection characteristics - Cylindrical - Spheroid \par Projection parameters - lonc: Longitude (only used if alpha (or gamma) is specified) (degrees) - alpha: Alpha (degrees) - lat_1: Latitude of first standard parallel (degrees) - lat_2: Latitude of second standard parallel (degrees) - lon_1 (degrees) - lon_2 (degrees) \par Example \image html ex_ocea.gif */ template <typename CalculationType, typename Parameters> struct ocea_spheroid : public detail::ocea::base_ocea_spheroid<CalculationType, Parameters> { inline ocea_spheroid(const Parameters& par) : detail::ocea::base_ocea_spheroid<CalculationType, Parameters>(par) { detail::ocea::setup_ocea(this->m_par, this->m_proj_parm); } }; #ifndef DOXYGEN_NO_DETAIL namespace detail { // Static projection BOOST_GEOMETRY_PROJECTIONS_DETAIL_STATIC_PROJECTION(srs::par4::ocea, ocea_spheroid, ocea_spheroid) // Factory entry(s) template <typename CalculationType, typename Parameters> class ocea_entry : public detail::factory_entry<CalculationType, Parameters> { public : virtual base_v<CalculationType, Parameters>* create_new(const Parameters& par) const { return new base_v_fi<ocea_spheroid<CalculationType, Parameters>, CalculationType, Parameters>(par); } }; template <typename CalculationType, typename Parameters> inline void ocea_init(detail::base_factory<CalculationType, Parameters>& factory) { factory.add_to_factory("ocea", new ocea_entry<CalculationType, Parameters>); } } // namespace detail #endif // doxygen } // namespace projections }} // namespace boost::geometry #endif // BOOST_GEOMETRY_PROJECTIONS_OCEA_HPP
42.034483
141
0.587264
[ "geometry" ]
ca14608ff8b28a41f580e8664e20956ef0f95c8f
3,704
cpp
C++
sumo/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
null
null
null
sumo/src/netimport/vissim/typeloader/NIVissimSingleTypeParser_Signalgeberdefinition.cpp
iltempe/osmosi
c0f54ecdbb7c7b5602d587768617d0dc50f1d75d
[ "MIT" ]
2
2017-12-14T16:41:59.000Z
2020-10-16T17:51:27.000Z
/****************************************************************************/ /// @file NIVissimSingleTypeParser_Signalgeberdefinition.cpp /// @author Daniel Krajzewicz /// @author Michael Behrisch /// @date Wed, 18 Dec 2002 /// @version $Id$ /// // /****************************************************************************/ // SUMO, Simulation of Urban MObility; see http://sumo.dlr.de/ // Copyright (C) 2001-2017 DLR (http://www.dlr.de/) and contributors /****************************************************************************/ // // This file is part of SUMO. // SUMO 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. // /****************************************************************************/ // =========================================================================== // included modules // =========================================================================== #ifdef _MSC_VER #include <windows_config.h> #else #include <config.h> #endif #include <cassert> #include <iostream> #include <utils/common/TplConvert.h> #include <utils/common/ToString.h> #include <utils/common/MsgHandler.h> #include <utils/common/VectorHelper.h> #include "../NIImporter_Vissim.h" #include "../tempstructs/NIVissimTL.h" #include "NIVissimSingleTypeParser_Signalgeberdefinition.h" // =========================================================================== // method definitions // =========================================================================== NIVissimSingleTypeParser_Signalgeberdefinition::NIVissimSingleTypeParser_Signalgeberdefinition(NIImporter_Vissim& parent) : NIImporter_Vissim::VissimSingleTypeParser(parent) {} NIVissimSingleTypeParser_Signalgeberdefinition::~NIVissimSingleTypeParser_Signalgeberdefinition() {} bool NIVissimSingleTypeParser_Signalgeberdefinition::parse(std::istream& from) { // int id; from >> id; // std::string tag, name; tag = myRead(from); if (tag == "name") { name = readName(from); tag = myRead(from); } // skip optional "Beschriftung" tag = overrideOptionalLabel(from, tag); // int lsaid; std::vector<int> groupids; if (tag == "lsa") { int groupid; from >> lsaid; // type-checking is missing! from >> tag; // "Gruppe" do { from >> groupid; groupids.push_back(groupid); tag = myRead(from); } while (tag == "oder"); // } else { from >> tag; // strecke WRITE_WARNING("Omitting unknown traffic light."); return true; } if (tag == "typ") { from >> tag; // typ-value from >> tag; // "ort" } // from >> tag; int edgeid; from >> edgeid; from >> tag; int laneno; from >> laneno; from >> tag; double position; from >> position; // while (tag != "fahrzeugklassen") { tag = myRead(from); } std::vector<int> assignedVehicleTypes = parseAssignedVehicleTypes(from, "N/A"); // NIVissimTL::dictionary(lsaid); // !!! check whether someting is really done here NIVissimTL::NIVissimTLSignal* signal = new NIVissimTL::NIVissimTLSignal(id, name, groupids, edgeid, laneno, position, assignedVehicleTypes); if (!NIVissimTL::NIVissimTLSignal::dictionary(lsaid, id, signal)) { throw 1; // !!! } return true; } /****************************************************************************/
30.360656
121
0.511609
[ "vector" ]
ca14acbfde2150c249c587d47dddd5f1ba063433
3,234
hpp
C++
FCMApp.hpp
chrisoldwood/FCManager
f26aad68e572d21d3cb27d1fc285143b6c3ee848
[ "MIT" ]
1
2017-08-17T15:33:33.000Z
2017-08-17T15:33:33.000Z
FCMApp.hpp
chrisoldwood/FCManager
f26aad68e572d21d3cb27d1fc285143b6c3ee848
[ "MIT" ]
null
null
null
FCMApp.hpp
chrisoldwood/FCManager
f26aad68e572d21d3cb27d1fc285143b6c3ee848
[ "MIT" ]
null
null
null
/****************************************************************************** ** (C) Chris Oldwood ** ** MODULE: FCMAPP.HPP ** COMPONENT: The Application. ** DESCRIPTION: The CFCMApp class declaration. ** ******************************************************************************* */ // Check for previous inclusion #ifndef FCMAPP_HPP #define FCMAPP_HPP #if _MSC_VER > 1000 #pragma once #endif #include <WCL/SDIApp.hpp> #include "FCMMainWnd.hpp" #include "FCMCmds.hpp" #include "FCMView.hpp" #include "FCMDoc.hpp" #include <WCL/IniFile.hpp> #include <WCL/Printer.hpp> /****************************************************************************** ** ** The application class. ** ******************************************************************************* */ class CFCMApp : public CSDIApp { public: // // Constructors/Destructor. // CFCMApp(); ~CFCMApp(); // // Typed access to the doc and view. // CFCMDoc* Doc(); CFCMView* View(); // // Members // CFCMMainWnd m_AppWnd; // Main window. CFCMCmds m_AppCmds; // Cmd controller. CIniFile m_oIniFile; // Ini file. CPrinter m_oPrinter; // Default printer. CRect m_rcAppWnd; // Last position of main window. CSize m_dmTeamSelDlg; // Last size of team selection dialog. // // Template methods for getting doc and view specifics. // virtual CSDIDoc* CreateDoc() const; virtual CView* CreateView(CDoc& rDoc) const; virtual const tchar* FileExts() const; virtual const tchar* DefFileExt() const; // // Misc helper functions. // CString FormatName(CRow& rRow, int nForename, int nSurname, bool bReverse = false) const; CString FormatMoney(CRow& rRow, int nColumn) const; CString FormatMoney(int nAmount) const; CString FormatDate(CRow& rRow, int nColumn) const; CString FormatDecimal(CRow& rRow, int nColumn, int nDecDigits) const; // // Constants. // static const tchar* VERSION; protected: // // Members // // // Startup and Shutdown template methods. // virtual bool OnOpen(); virtual bool OnClose(); // // Internal methods. // void LoadDefaults(); void SaveDefaults(); }; /****************************************************************************** ** ** Global variables. ** ******************************************************************************* */ //The application object. extern CFCMApp App; /****************************************************************************** ** ** Implementation of inline functions. ** ******************************************************************************* */ inline CFCMDoc* CFCMApp::Doc() { return static_cast<CFCMDoc*>(m_pDoc); } inline CFCMView* CFCMApp::View() { return static_cast<CFCMView*>(m_pView); } inline CSDIDoc* CFCMApp::CreateDoc() const { return new CFCMDoc; } inline CView* CFCMApp::CreateView(CDoc& rDoc) const { return new CFCMView(static_cast<CFCMDoc&>(rDoc)); } inline const tchar* CFCMApp::FileExts() const { static tchar szExts[] = { TXT("F.C. Manager Files (*.fcm)\0*.fcm\0") TXT("All Files (*.*)\0*.*\0") TXT("\0\0") }; return szExts; } inline const tchar* CFCMApp::DefFileExt() const { static tchar szDefExt[] = { TXT("fcm") }; return szDefExt; } #endif //FCMAPP_HPP
21.137255
90
0.544218
[ "object" ]
ca25180d836ff79dd8583ea2f55d5eb8a473735f
65,397
cpp
C++
shore/shore-mt/src/sm/bf_core.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-01-25T00:51:56.000Z
2022-01-07T15:09:38.000Z
shore/shore-mt/src/sm/bf_core.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
1
2021-11-25T18:08:22.000Z
2021-11-25T18:08:22.000Z
shore/shore-mt/src/sm/bf_core.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
3
2018-06-08T08:36:27.000Z
2021-12-26T20:36:16.000Z
/* -*- mode:C++; c-basic-offset:4 -*- Shore-MT -- Multi-threaded port of the SHORE storage manager Copyright (c) 2007-2009 Data Intensive Applications and Systems Labaratory (DIAS) Ecole Polytechnique Federale de Lausanne All Rights Reserved. Permission to use, copy, modify and distribute this software and its documentation is hereby granted, provided that both the copyright notice and this permission notice appear in all copies of the software, derivative works or modified versions, and any portions thereof, and that both notices appear in supporting documentation. This code 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. THE AUTHORS DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. */ // -*- mode:c++; c-basic-offset:4 -*- /*<std-header orig-src='shore'> $Id: bf_core.cpp,v 1.64.2.26 2010/03/25 18:05:03 nhall Exp $ SHORE -- Scalable Heterogeneous Object REpository Copyright (c) 1994-99 Computer Sciences Department, University of Wisconsin -- Madison All Rights Reserved. Permission to use, copy, modify and distribute this software and its documentation is hereby granted, provided that both the copyright notice and this permission notice appear in all copies of the software, derivative works or modified versions, and any portions thereof, and that both notices appear in supporting documentation. THE AUTHORS AND THE COMPUTER SCIENCES DEPARTMENT OF THE UNIVERSITY OF WISCONSIN - MADISON ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION, AND THEY DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE. This software was developed with support by the Advanced Research Project Agency, ARPA order number 018 (formerly 8230), monitored by the U.S. Army Research Laboratory under contract DAAB07-91-C-Q518. Further funding for this work was provided by DARPA through Rome Research Laboratory Contract No. F30602-97-2-0247. */ #include "w_defines.h" /* -- do not edit anything above this line -- </std-header>*/ #ifndef BF_CORE_C #define BF_CORE_C #ifdef __GNUG__ #pragma implementation "bf_core.h" #endif #include <stdio.h> #include <cstdlib> #include "sm_int_0.h" #include "bf_s.h" #include "bf_core.h" #include <auto_release.h> #include "w_findprime.h" #include "page_s.h" #include "log.h" #include <w_strstream.h> #include "atomic_templates.h" #include <vector> #include <algorithm> #include <sstream> #include "w_hashing.h" #include "bf_htab.h" extern "C" void bfcore_stophere(); void bfcore_stophere() { } page_write_mutex_t page_write_mutex_t::page_write_mutex[page_write_mutex_t::PWM_COUNT]; extern "C" void dumpthreads(); void dump_page_mutexes() { page_write_mutex_t::dump_all(); } void page_write_mutex_t::dump_all() { for(int i=0; i < PWM_COUNT; i++) { cerr << " page_mutex " << i << " @ " << ::hex << u_long(&(page_write_mutex[i]._page_mutex)) << ::dec #ifdef Linux // This is COMPLETELY unportable code but it's helpful for the moment... << " owner " << page_write_mutex[i]._page_mutex.__data.__owner #endif << endl; } cerr << flushl; } #if W_DEBUG_LEVEL > 1 void bfcb_t::check() const { // I can only make checks when I hold the latch at least in SH mode. int count = latch.held_by_me(); bool mine = latch.is_mine(); // true iff I hold it in EX mode if(count > 0) { if(mine) { // EX mode // NOTE: the latch_cnt can be > 1 because THIS thread can // hold it more than once. w_assert2(latch.latch_cnt() == count); // NOTE: the pin count can be > 1 because the // protocol is : pin_frame, then latch // release latch, then unpin_frame // Thus, _pin_cnt > 1 means someone else is waiting for the latch. w_assert2(_pin_cnt >= 1); } else { // This is racy at best. // Even if it weren't racy, // the latch count could be < _pin_cnt because the // protocol is : pin_frame, then latch // release latch, then unpin_frame // Thus, _pin_cnt > latch_cnt means someone else // is waiting for the latch. // w_assert2(latch.latch_cnt() <= _pin_cnt); w_assert2(_pin_cnt >= 1); w_assert2(latch.mode() == LATCH_SH); } } } #endif void bfcb_t::pin_frame() { atomic_inc(_pin_cnt); w_assert1(_pin_cnt > 0); // should never go below 0 } void bfcb_t::unpin_frame() { #if W_DEBUG_LEVEL > 1 w_assert2(_pin_cnt > 0); // should NEVER go below 0 #endif atomic_dec(_pin_cnt); w_assert1(_pin_cnt >= 0); // should NEVER go below 0 } // this function is important because of our rule that a page can // become pinned (rather than becoming more pinned) iff the caller // holds the appropriate bucket mutex. This function lets threads pin // hot pages without breaking the rule. // That is to say, the caller can either increase the pin count // or it can go back and grab the appropriate bucket mutex before // doing a first-time pin. // // Returns false if it wasn't pinned (and still isn't); // true if it was pinned (and we incremented the pin count). // // Callers: bf_core_m::pin // bf_core_m::htab::lookup // // NOTE: this corresponds to the change described in 6.2.1 (page 8) and // 7.2 (page 10) of // the Shore-MT paper. bool bfcb_t::pin_frame_if_pinned() { int old_pin_cnt = _pin_cnt; while(1) { if(old_pin_cnt == 0) return false; // if pin_cnt == old_pin_cnt increment pin_cnt and return // the original value of pin_cnt, whether or not we incremented it. int orig_pin_cnt = atomic_cas_32((unsigned*) &_pin_cnt, old_pin_cnt, old_pin_cnt+1); if(orig_pin_cnt == old_pin_cnt) // increment occurred return true; // if we get here it's because another thread raced in here, // and updated the pin count before we could. old_pin_cnt = orig_pin_cnt; } } void bf_stop_here() {}; void bf_stop(bfcb_t *p) { shpid_t pg(808); static int i(0); static int j(0); static int k(0); j = atomic_inc_nv(i); if(p->pid().page ==pg || j == k) { bf_stop_here(); cerr << "page " << pg << endl; } } /********************************************************************* * * bf_core_m class static variables * * _num_bufs : number of frames * _bufpool : array of frames * _buftab : array of bf control blocks (one per frame) * *********************************************************************/ // protects bf_core itself, including the clock hand queue_based_lock_t bf_core_m::_bfc_mutex; int bf_core_m::_num_bufs = 0; page_s* bf_core_m::_bufpool = 0; bfcb_t* bf_core_m::_buftab = 0; bf_core_m::htab* bf_core_m::_htab = 0; bfcb_unused_list bf_core_m::_unused; char const* db_pretty_print(lpid_t const* pid, int, char const*) { static char tmp[100]; snprintf(tmp, sizeof(tmp), "%d.%d.%d", pid->_stid.vol.vol, pid->_stid.store, pid->page); return tmp; } #include "bf_transit_bucket.h" transit_bucket_t transit_bucket_t::_transit_buckets[ transit_bucket_t::NUM_TRANSIT_BUCKETS]; /* FRJ: Because a central _bfc_mutex was a massive bottleneck, there are now a bunch of different mutexen in use. Here are the rules: 1. _bfc_mutex wholly owns the _hand, _unused and _transit. You must hold _bfc_mutex to acquire latches for frames in either list. 2. The _htab_mutexen protect their corresponding _htab buckets. No frame may be added to or removed from _htab without holding the appropriate bucket mutex. You must hold the appropriate bucket mutex to acquire latches for frames in that bucket, or to search the table for a pid. However, it is safe (though perhaps not useful) to check whether a frame is in the table, because that is a single pointer test. 3. Each frame latch protects its frame from changes of pid, _pin_cnt, etc. Also, latched/pinned frames may not be removed from the _htab. 4. In order to avoid deadlocks, blocking acquires should always go in _bfc_mutex -> _htab_mutexen -> latches order. See the next two rules for ways to deal with the gaps when going the wrong way. 5. There are times where we've decided a page is not in the _htab, and must ensure that this remains true during the gap between releasing the bucket and acquiring _bfc_mutex. Any thread that adds a page to a given _htab bucket will overwrite the corresponding _htab_markers entry with a unique value; threads wishing to detect additions during their gap may set a marker before releasing the bucket. If the marker remains intact across the gap the thread can safely continue, else it best abort/retry. 6. For gaps between bucket mutexen and latches, simply test whether the frame is still in the table and has the correct pid once the latch has been acquired. */ int bf_core_m::_hand = 0; // hand of clock inline ostream& bfcb_t::print_frame(ostream& o, bool in_htab) { if (in_htab) { o << pid() << '\t' << (dirty() ? "X" : " ") << '\t' << curr_rec_lsn() << '\t' << safe_rec_lsn() << '\t' << pin_cnt() << '\t' << latch_t::latch_mode_str[latch.mode()] << '\t' << latch.latch_cnt() << '\t' << is_hot() << '\t' << refbit() << '\t' << latch.id() << endl; } else { o << pid() << '\t' << " InTransit " << (old_pid_valid() ? (lpid_t)old_pid() : lpid_t::null) << endl << flush; } return o; } /********************************************************************* * * bf_core_m::latched_by_me(p) * return true if the latch is held by me() (this thread) * *********************************************************************/ bool bf_core_m::latched_by_me( bfcb_t* p) const { return (p->latch.held_by_me() > 0); } bool bf_core_m::force_my_dirty_old_pages(lpid_t const* /*wal_page*/) const { #warning TODO: actually look for dirty pages instead of just guessing they exist return false; } /********************************************************************* * * bf_core_m::is_mine(p) * * Return true if p is latched exclussively by current thread. * false otherwise. * *********************************************************************/ bool bf_core_m::is_mine(const bfcb_t* p) const { w_assert2(p - _buftab >= 0 && p - _buftab < _num_bufs); w_assert2(_in_htab(p)); // we must hold *some* latch, just maybe not EX return p->latch.is_mine(); } /********************************************************************* * * bf_core_m::latch_mode() * *********************************************************************/ latch_mode_t bf_core_m::latch_mode(const bfcb_t* p) const { w_assert2(p - _buftab >= 0 && p - _buftab < _num_bufs); w_assert2(_in_htab(p)); return (latch_mode_t) p->latch.mode(); } /********************************************************************* * * bf_core_m::my_latch() * For debugging use only. * *********************************************************************/ const latch_t * bf_core_m::my_latch(const bfcb_t* p) const { w_assert2(p - _buftab >= 0 && p - _buftab < _num_bufs); w_assert2(_in_htab(p)); return &p->latch; } void bfcb_t::initialize(const char *const name, page_s* bufpoolframe, uint4_t hfunc ) { _frame = bufpoolframe; _dirty = false; _pid = lpid_t::null; _rec_lsn = lsn_t::null; latch.setname(name); zero_pin_cnt(); _refbit = 0; _hotbit = 0; _hash = 0; _hash_func = hfunc; } /********************************************************************* * * bf_core_m::bf_core_m(n, extra, desc) * * Create the buffer manager data structures and the shared memory * buffer pool. "n" is the size of the buffer_pool (number of frames). * "Desc" is an optional parameter used for naming latches; it is used only * for debugging purposes. * *********************************************************************/ struct bf_core_m::init_thread_t : public smthread_t { bf_core_m* _bfc; long _begin; long _end; // char const* _desc; init_thread_t(bf_core_m* bfc, long b, long e) : smthread_t(t_regular, "bf_core_m::init_thread", WAIT_NOT_USED), _bfc(bfc), _begin(b), _end(e) // , _desc(d) { } virtual void run() { const char *nayme = name(); for(long i=_begin; i < _end; i++) { _bfc->_buftab[i].initialize(nayme, _bfc->_bufpool+i, htab::HASH_COUNT ); _bfc->_unused.release(_bfc->_buftab+i); } } }; NORET bf_core_m::bf_core_m(uint4_t n, char *bp) { _num_bufs = n; _bufpool = (page_s *)bp; w_assert1(_bufpool); w_assert1(is_aligned(_bufpool)); int buckets = w_findprime((16*n+8)/9); // maximum load factor of 56% _htab = new htab(buckets); if (!_htab) { W_FATAL(eOUTOFMEMORY); } /* * Allocate and initialize array of control info */ _buftab = new bfcb_t [_num_bufs]; if (!_buftab) { W_FATAL(eOUTOFMEMORY); } // 512MB per thread... static int const CHUNK_SIZE = 1<<16; static int const MAX_THREADS = 30; int thread_count = std::min( (_num_bufs+CHUNK_SIZE-1)/CHUNK_SIZE, int(MAX_THREADS)); int chunk_size = (_num_bufs+thread_count-1)/thread_count; std::vector<init_thread_t*> threads; /* Create threads (thread_count) to initialize the buffer manager's * control blocks */ for(int i=0; i < thread_count; i++) { int begin = i*chunk_size; int end = std::min(begin+chunk_size, _num_bufs); threads.push_back(new init_thread_t(this, begin, end/*, desc*/)); } for(unsigned int i=0; i < threads.size(); i++) { W_COERCE(threads[i]->fork()); } for(unsigned int i=0; i < threads.size(); i++) { W_COERCE(threads[i]->join()); delete threads[i]; } /* Await threads that init the buffer manager's control blocks */ #if W_DEBUG_LEVEL > 5 // Check the alignment of the buffer pool entries. This code left // in until we figure out how to guarantee the contiguity of the // mmaped area under Linux. union { page_s *ptr; unsigned u; } pun1, pun2; cout << " sizeof(page_s) " << ::hex << "0x" << sizeof(page_s) << ::dec << " " << sizeof(page_s) << endl; for(int i=0; i < _num_bufs; i++) { pun2.ptr = _buftab[i].frame; cout << " check entry " << i << " in entry located at 0x" << ::hex << (unsigned)(&_buftab[i]) << " frame @ " << ::hex << pun2.u << ::dec << endl; w_assert1(pun2.ptr != 0); if(i>0) { w_assert1(pun1.u + sizeof(page_s) == pun2.u); } pun1.ptr = pun2.ptr; } #endif } /********************************************************************* * * bf_core_m::~bf_core_m() * * Destructor. There should not be any frames pinned when * bf_core_m is being destroyed. * *********************************************************************/ NORET bf_core_m::~bf_core_m() { for (int i = 0; i < _num_bufs; i++) { w_assert9(! _in_htab(_buftab + i) ); } delete _htab; delete [] _buftab; _unused.shutdown(); // reinitialize it } /********************************************************************* * * bf_core_m::_in_htab(e) * * Return true iff e is in the hash table. * *********************************************************************/ bool bf_core_m::_in_htab(const bfcb_t* e) const { return e->hash_func() != htab::HASH_COUNT; } /********************************************************************* * * bf_core_m::get_cb(p) * * Returns true if page "p" is cached. false otherwise. * *********************************************************************/ bool bf_core_m::get_cb(const bfpid_t& p, bfcb_t*& ret) const { ret = 0; /* * We don't want to catch any cuckoo * operations in mid-flight, which could have been going on while * we did the lookup. */ bfcb_t* f = _htab->lookup(p); if (f) { // if we found it at all, // it should have already been pinned (by this thread) w_assert2(f->pin_cnt() > 1); f->unpin_frame(); // get rid of the extra pin ret = f; return true; } return false; } /* This pair atomically updates a singly linked list. */ bfcb_t* bfcb_unused_list::take() { union {void* v; bfcb_t* b; } u = { pop() }; if(u.b) { u.b->zero_pin_cnt(); atomic_dec(_count); } return u.b; } void bfcb_unused_list::release(bfcb_t* frame) { w_assert9(!frame->dirty); w_assert9(frame->pin_cnt == 0); w_assert9(!frame->latch.is_latched()); push(frame); atomic_inc(_count); } #if SM_PLP_TRACING static __thread timeval my_time; #endif /********************************************************************* * * bf_core_m::grab(ret, pid, found, is_new, mode, timeout) * * Assumptions: "ret" refers to a free frame, that is, it's not * in the hash table, as it came off the free list or is in the * in-transit-out table. * * The frame is already EX-latched by the caller. * * Check that the given pid isn't elsewhere in the buffer pool. * If so, * release the latch on "ret" frame, * grab the "mode" latch on the frame already in the buffer pool, * set "found" to true, * set "ret" to point to that frame and * return. * If not, * hang onto the EX latch on the given frame, * insert the frame/pid in the hash table, * set "found" to false, * and return the given frame in "ret". * * FRJ: If find() fails the caller is * expected to obtain a replacement frame by calling replacement(), which * it then passes to grab(). * * Regardless of whether grab() needs the replacement, * the old page, if dirty, became in-transit-out (this was already * by the caller). * *********************************************************************/ // only caller is bf_m::_fix w_rc_t bf_core_m::grab( bfcb_t* & ret, // already-allocated replacement frame, not latched. const bfpid_t& pid, // page we seek bool& found, // found in the hash table so we didn't use the // control block passed in via "ret". latch_mode_t mode, // desired latch mode timeout_in_ms timeout ) { w_assert2(cc_alg == t_cc_record || mode > LATCH_NL); w_assert2(mode != LATCH_NL); // NEH changed to assert2 w_assert2(ret != NULL); // allocated replacement frame INC_TSTAT(bf_look_cnt); // We already have the EX-latch. It was acquired in replacement(), // and no longer freed in publish_partial. w_assert1(ret->latch.is_latched()); w_assert1(ret->latch.is_mine()); // EX mode w_assert2(!ret->pin_cnt()); ret->pin_frame(); ret->check(); // EX mode so strong check /* now make sure the frame we want isn't already there. It could be in-transit-out or we might have missed it in the htab. Our caller will deal with waiting on an in-transit-out page, but we have to be sure it's not in the htab anywhere */ // compute the hashes before grabbing the mutex (~20 // cycles/hash). Really we should be caching the ones we computed // in find() just before this function got called! static int const COUNT = htab::HASH_COUNT; int idx[COUNT]; for(int i=0; i < COUNT; i++) { idx[i] = _htab->hash(i, pid); } transit_bucket_t* volatile tb = &transit_bucket_t::get(pid); CRITICAL_SECTION(cs, tb->_tb_mutex); // PROTOCOL tb->await_not_in_transit_out(pid); /* NOTE: If our victim is non-null and dirty, we should really wait after flushing it -- there's a good chance we would exit transit during the flush. However, this is expected to be rare, so we'll hold off until we see it's a problem. */ /* See if the pid is in the hash table * TODO: NANCY: WHY CAN'T WE JUST DO _htab->lookup()? DOCUMENT THIS * From Ryan: this is because of the race BUG_HTAB_RACE,so perhaps if * we fix the race we can use lookup() here. * Perhaps this residents stuff has to do with * Shore-MT paper, section 7.3 (page 10) 2nd paragraph, #19 * */ int i; int residents[COUNT]; int same = 0; bfcb_t* p = NULL; for(int attempt=0; p == NULL && same != COUNT; attempt++) { same = 0; for(i=0; i < COUNT; i++) { htab::bucket &b = _htab->_table[idx[i]]; w_assert2(b._lock.is_mine()==false); b._lock.acquire(); // PROTOCOL w_assert2(b._lock.is_mine()); // With multi-slotted buckets, get_frame // returns the slot containing the pid if it's // there, o.w. it returns null // NOTE: we must hold the lock on the bucket before // we can do this (get_frame) p = b.get_frame(pid); if(p && p->pid() == pid) { w_assert2(p->hash() == idx[i]); w_assert2(_in_htab(p)); break; } // On first try, record the #residents in the bucket; // on subsequent attempts, if the #residents hasn't // changed, count that as same, meaning no change // in that bucket. If there's a lot going on elsewhere, // presumably some bucket counts will change, and // we might be able to find what we're seeking if(attempt == 0) { residents[i] = b._count; } else { if(residents[i] == b._count) same++; else residents[i] = b._count; } p = NULL; b._lock.release(); // PROTOCOL w_assert2(b._lock.is_mine()==false); } } w_assert1(ret != p); found = (p!=NULL); if( found ) { // oops... we found it so we don't // need the replacement. put the replacement on the freelist // Release the (EX) latch we acquired on the replacement frame. // (We acquired EX latch on the frame to cover the in-transit-in // case. All other fixers will await the release of the page latch.) ret->check(); // EX mode : should be strong check #if SM_PLP_TRACING if (_ptrace_level>=PLP_TRACE_PAGE) { gettimeofday(&my_time, NULL); CRITICAL_SECTION(plpcs,_ptrace_lock); _ptrace_out << pid << " " << pthread_self() << " " << ret->latch.mode() << " " << my_time.tv_sec << "." << my_time.tv_usec << endl; plpcs.exit(); } #endif ret->latch.latch_release(); // PROTOCOL ret->unpin_frame(); _unused.release(ret); // put on free list INC_TSTAT(bf_hit_cnt); ret = p; p->pin_frame(); // release the last bucket lock and acquire the latch on the // frame we're about to return _htab->_table[idx[i]]._lock.release(); // PROTOCOL cs.exit(); // PROTOCOL rc_t rc = p->latch.latch_acquire(mode, timeout); // PROTOCOL if (rc.is_error()) { /* * Clean up and bail out. * (this should not happen in the case where * we've put it on the in-transit list) */ p->unpin_frame(); INC_TSTAT(bf_grab_latch_failed); /* fprintf(stderr, "Unable to acquire latch %d.%d in mode %d with timeout %d\n", pid.store(), pid.page, mode, timeout); */ return RC_AUGMENT(rc); } p->check(); // could be weak check (if SH mode) } else { // not found // all bucket locks already released // use the replacement frame. It's latched in EX mode. p = ret; p->set_pid (pid); // insert now tells us if something was moved, not evicted. // new htab cannot evict anyone. (void) _htab->insert(p); cs.exit(); // PROTOCOL } w_assert2( found? (ret->latch.mode() == mode) : (ret->latch.mode() == LATCH_EX) ); return RCOK; } /********************************************************************* * * bf_core_m::find(ret, pid, mode, timeout, ref_bit) * * If page "pid" is cached, find() acquires a "mode" latch and returns, * in "ret", a pointer to the associated bf control block; returns an * error if the resource is not cached. * *********************************************************************/ /* WARNING: FRJ: the semantics of this function have changed to no longer search the in-transit list for pages that might (or might not) enter the pool soon. This was done for the following reasons: (a) if we really want the page that badly, a call to _core->grab() would follow an eFRAMENOTFOUND, and _core->grab() checks the in-transit list. (b) if the page is in transit, it's either been evicted, in which case waiting for it to finish transit is a waste of time, or it's currently being brought into the buffer pool. Arguably, it's not there, and whether we could determine (with effort) that it will be there soon is irrelevant. (c) If hte page is in transit, it could be a very long time (msec) before the call returns, and half the time we will discover the page was in-transit-out anyway. It's not worth extra complexity (and bugs) to slow down the program unless we *really* need to. A search of all current callers shows three types: 1. If find() misses a page grab will follow immediately and check the in-transit list anyway (bf_m::_fix) 2. If the page isn't in the bpool we really don't care whether it's on the in-transit list because we intend to put pages we find on that list (checkpoint threads) 3. Unsupported and/or unused features where it's not clear whether the caller cares to test the in-transit list (bf_m::fix_if_cached). I suspect that even these don't care to worry about the in-transit list, but I've left a warning just in case it ever trips somebody up. */ w_rc_t bf_core_m::find( bfcb_t*& ret, const bfpid_t& _pid, latch_mode_t mode, timeout_in_ms timeout, int4_t ref_bit ) { const bfpid_t pid = _pid; w_assert3(ref_bit >= 0); w_assert1(mode != LATCH_NL); // NEH: changed to assert2 bfcb_t* p = NULL; ret = 0; INC_TSTAT(bf_look_cnt); if( (p=_htab->lookup(pid)) == NULL ) return RC(eFRAMENOTFOUND); w_assert2(p->pin_cnt() > 0); /* The page came to us pinned, so we can update the control block and acquire the latch at our leisure. */ w_assert3(p->refbit() >= 0); if (p->refbit() < ref_bit) p->set_refbit(ref_bit); w_assert3(p->refbit() >= 0); INC_TSTAT(bf_hit_cnt); w_rc_t rc = p->latch.latch_acquire(mode, timeout); // PROTOCOL if (rc.is_error()) { /* * Clean up and bail out. */ p->unpin_frame(); return RC_AUGMENT(rc); } if(p->old_pid_valid() && p->old_pid() == pid) { // this can only happen if we hit an in-transit-in page whose // read failed. Hopefully the next grab() will work... w_assert1(p->latch.held_by_me() >= 1); // a repin should never fail this way! p->check(); // could be weak check #if SM_PLP_TRACING if (_ptrace_level>=PLP_TRACE_PAGE) { gettimeofday(&my_time, NULL); CRITICAL_SECTION(plpcs,_ptrace_lock); _ptrace_out << p->pid() << " " << pthread_self() << " " << p->latch.mode() << " " << my_time.tv_sec << "." << my_time.tv_usec << endl; plpcs.exit(); } #endif p->latch.latch_release(); // PROTOCOL p->unpin_frame(); return RC(fcOS); } ret = p; w_assert2((pid == p->frame()->pid) && (pid == p->pid())); w_assert1(p->latch.mode() >= mode); w_assert1(p->latch.held_by_me() >= 1); // since mode is not NL if(mode == LATCH_EX) { w_assert1(p->latch.is_mine()); } return RCOK; } /*********************************************************************/ /**\brief Publish frame p (already grabbed), awaken waiting threads. * *\details * Publishes the frame "p" that was previously grab()ed with * a cache-miss. All threads waiting on the frame are awakened. * * Leave the frame latched in 'mode', downgrading or releasing as * required to get us there. * */ void bf_core_m::publish( bfcb_t* p, latch_mode_t mode, bool error_occurred) { /* * Sanity checks */ w_assert2(p - _buftab >= 0 && p - _buftab < _num_bufs); w_assert2(p->pin_cnt() > 0); // mode is LATCH_NL in error case //w_assert2( (mode != LATCH_NL) || error_occurred); // mrbt w_assert2( !error_occurred || (mode == LATCH_NL && error_occurred)); // mrbt //w_assert2(p->latch.is_mine()); // mrbt w_assert2(p->latch.is_mine() || (!error_occurred && mode == LATCH_NL)); // mrbt w_assert9(!p->old_pid_valid()); /* * If error, cancel request (i.e. release the latch). * If there exist other requestors, leave the frame in the transit * list, otherwise move it to the free list. */ if (error_occurred) { /* FRJ: the page is already in the htab, and there could easily be other threads waiting on it at this point. We need to set up a protocol where we flag the frame as bad, but leave it in the bpool. Any new requestor will see the "bad" mark and know to re-read. If that read fails, it will publish the error again. Repeat until the read succeeds or an admin notices that trx keep aborting... */ p->set_old_pid(); // FRJ: yes, there is! // cs.exit(); // no need to hold _mutex for this... w_assert2(p->latch.is_mine()); #if SM_PLP_TRACING if (_ptrace_level>=PLP_TRACE_PAGE) { gettimeofday(&my_time, NULL); CRITICAL_SECTION(plpcs,_ptrace_lock); _ptrace_out << p->pid() << " " << pthread_self() << " " << p->latch.mode() << " " << my_time.tv_sec << "." << my_time.tv_usec << endl; plpcs.exit(); } #endif p->latch.latch_release(); // PROTOCOL p->unpin_frame(); // NEH: moved unpin here after latch release, // since the protocol seems to be: // pin, then acquire latch // release latch, then unpin } else { p->check(); // downgrade the latch to whatever mode we actually wanted if(mode == LATCH_SH) { p->latch.downgrade(); // PROTOCOL } else if(mode == LATCH_EX) { // do nothing } else if(mode == LATCH_NL) { // is this really allowed? // Do we need to unpin the frame here? // The assertion will tell us if this ever happens. //w_assert0(false); // mrbt #if SM_PLP_TRACING if (_ptrace_level>=PLP_TRACE_PAGE) { gettimeofday(&my_time, NULL); CRITICAL_SECTION(plpcs,_ptrace_lock); _ptrace_out << p->pid() << " " << pthread_self() << " " << p->latch.mode() << " " << my_time.tv_sec << "." << my_time.tv_usec << endl; plpcs.exit(); } #endif // p->latch.latch_release(); // PROTOCOL // mrbt } } } /********************************************************************* * * bf_core_m::publish_partial(p) * * Partially publish the frame "p" that was acquired as a replacement * frame after a cache miss. * * This is called after bf_m::_fix had a cache miss, called replacement() * to get the frame, found that the frame was in-use, and either * explicitly sent it to disk or waited for a cleaner to finish * sending it to disk. * This takes the frame off the in_transit_out list and invalidates * the old_pid, so now this frame is indistinguishable from * an unused frame returned by replacement(). * * If discard==true, the frame goes back on the freelist as well * NOTE: discard is no longer used. * *********************************************************************/ void bf_core_m::publish_partial(bfcb_t* p) { w_assert9(p - _buftab >= 0 && p - _buftab < _num_bufs); // The next assertion is not valid if pages can be pinned w/o being // latched. For now, it is ok in the case of page-level locking only. // FRJ: to cover a couple of races we need to latch now... w_assert2(p->latch.is_latched()); w_assert2(p->latch.is_mine()); w_assert2(p->old_pid_valid()); /* * invalidate old key */ lpid_t pid = p->old_pid(); p->clr_old_pid(); transit_bucket_t &tb = transit_bucket_t::get(pid); CRITICAL_SECTION(cs, tb._tb_mutex); // PROTOCOL tb.make_not_in_transit_out(pid); } /********************************************************************* * * bf_core_m::snapshot(npinned, nfree) * * Return # frames pinned and # unused frames in "npinned" and * "nfree" respectively. * *********************************************************************/ void bf_core_m::snapshot( u_int& npinned, u_int& nfree) { /* * No need to obtain mutex since this is only an estimate. */ int count = 0; for (int i = _num_bufs - 1; i; i--) { if (_in_htab(&_buftab[i])) { if (_buftab[i].latch.is_latched() || _buftab[i].pin_cnt() > 0) ++count; } } npinned = count; nfree = _unused.count(); } /********************************************************************* * * bf_core_m::snapshot_me(nsh, nex, ndiff) * * Return # frames fixed *BY ME()* in SH, EX mode, total diff latched * frames, respectively. The last argument is because a single thread * can have > 1 latch on a single page. * *********************************************************************/ void bf_core_m::snapshot_me( u_int& nsh, u_int& nex, u_int& ndiff) { /* * No need to obtain mutex since me() cannot fix or unfix * a page while me() is calling this function. */ nsh = nex = ndiff = 0; for (int i = _num_bufs - 1; i; i--) { if (_in_htab(&_buftab[i])) { /* FRJ: If the latch is not locked, held_by() will return almost as quickly as is_latched(); if not, we have to call held_by anyway. Therefore, the test for is_latched() is unnecessary. */ if (1 || _buftab[i].latch.is_latched() ) { // NB: don't use is_mine() because that // checks for EX latch. int times = _buftab[i].latch.held_by_me(); if(times > 0) { ndiff ++; // different latches only if (_buftab[i].latch.mode() == LATCH_SH ) { nsh += times; } else { w_assert9 (_buftab[i].latch.mode() == LATCH_EX ); // NB: here, we can't *really* tell how many times // we hold the EX latch vs how many times we // hold a SH latch nex += times; } } } } } } /********************************************************************* * * bf_core_m::pin(p, mode) * * Pin resource "p" in latch "mode". * *********************************************************************/ w_rc_t bf_core_m::pin(bfcb_t* p, latch_mode_t mode) { /* FRJ: Our only caller is bf_m::refix(), which means we don't need to lock the page's bucket -- the page is already pinned by this thread and won't go anywhere during this call. Update - bf_m::_scan also calls us, and the page is *not* pinned first! */ w_assert9(p - _buftab >= 0 && p - _buftab < _num_bufs); w_assert9(_in_htab(p)); // it should already be pinned! // pin_frame_if_pinned returns true IFF it's pinned. if(!p->pin_frame_if_pinned()) { // we need to acquire the bucket lock before grabbing a free // latch. The page's pid may have changed in the meantime. bfpid_t pid = p->pid(); htab::bucket &b = _htab->_table[p->hash()]; w_assert2(b._lock.is_mine()==false); CRITICAL_SECTION(cs, b._lock); // PROTOCOL w_assert2(b._lock.is_mine()); p = b.get_frame(pid); // in case we raced... if(p == NULL || p->pid() != pid) return RC(eFRAMENOTFOUND); p->pin_frame(); } // now acquire the latch (maybe again) w_rc_t rc = p->latch.latch_acquire(mode) ; // PROTOCOL p->check(); w_assert1(p->pin_cnt() > 0); return rc; } /********************************************************************* * * bf_core_m::upgrade_latch_if_not_block(p, would_block) * *********************************************************************/ void bf_core_m::upgrade_latch_if_not_block(bfcb_t* p, bool& would_block) { // FRJ: nobody will remove a latched/pinned entry from the _htab w_assert9(p - _buftab >= 0 && p - _buftab < _num_bufs); w_assert9(_in_htab(p)); // p->pin(); // DO NOT Increment!! W_COERCE( p->latch.upgrade_if_not_block(would_block) ); if(!would_block) { w_assert9(p->latch.mode() == LATCH_EX); } } /********************************************************************* * * bf_core_m::unpin(p, int ref_bit) * * Unlatch the frame "p". * *********************************************************************/ void bf_core_m::unpin(bfcb_t*& p, int ref_bit, bool W_IFDEBUG4(in_htab)) { w_assert3(ref_bit >= 0); w_assert9(p - _buftab >= 0 && p - _buftab < _num_bufs); w_assert9(!in_htab || _in_htab(p)); w_assert1(p->pin_cnt() > 0); /* * if we were given a hit about the page's * about-to-be-referenced-ness, apply it. * but o.w., don't make it referenced. (That * shouldn't happen in unfix().) */ w_assert3(p->refbit() >= 0); if (p->refbit() < ref_bit) p->set_refbit(ref_bit); w_assert3(p->refbit() >= 0); // The following code used to be included to get the page reused // sooner. However, performance tests show that that this can // cause recently referenced pages to be "swept" early // by the clock hand. /* if (ref_bit == 0) { _hand = p - _buftab; // reset hand for MRU } */ // LSN integrity checks (only if really unpinning) if(p->pin_cnt() == 1) { if(p->dirty()) { w_assert1(p->curr_rec_lsn().valid()); // We must maintain this invariant else we'll never be // able to debug recovery issues. // HOWEVER there are some legit exceptions // 1) we are in the redo part of recovery, and we // dirty pages but don't log them. In that case, // we get in here, and the rec_lsn reflects the tail end // of the log (way in the future), but any update JUST // done didn't cause the page lsn to change .. yet. // // 2) we pinned a dirty page, did not update it, and are // unpinning it; the control block says it's dirty. // This can happen if after redo_pass we are doing an undo // and pin a still-dirty-but-unlogged page. So in order to // prevent this, I have inserted force_all in restart.cpp between // the redo_pass and the undo_pass. It should make this case // never happen, leaving the assert below valid again. // // 3) Page cleaners cleared the dirty bit and rec_lsn of // an SH-latched page before writing it out. In this case // safe_rec_lsn() != curr_rec_lsn() and the former should // be used. However, either way the relationship with the // page lsn remains valid. // // The recovery code is about to see that it gets changed // and that the rec_lsn gets "repaired". if (( (p->safe_rec_lsn() <= p->frame()->lsn1) || ((p->get_storeflags() & smlevel_0::st_tmp) == smlevel_0::st_tmp) || smlevel_0::in_recovery_redo() ) == false) { // Print some useful info before we croak on the // assert directly below this. cerr << " frame " << (void *)(p->frame()) << endl << " pid " << p->pid() << endl << " curr_rec_lsn " << p->curr_rec_lsn() << endl << " old_rec_lsn " << p->old_rec_lsn() << endl << " safe_rec_lsn " << p->safe_rec_lsn() << endl << " frame lsn " << p->frame()->lsn1 << endl << " (p->rec_lsn <= p->frame->lsn1) " << int(p->safe_rec_lsn() <= p->frame()->lsn1) << endl << " p->frame->store_flags & smlevel_0::st_tmp " << int(p->get_storeflags() & smlevel_0::st_tmp) << endl << " smlevel_0::in_recovery_redo() " << int(smlevel_0::in_recovery_redo()) << endl << endl; } w_assert0 ( (p->safe_rec_lsn() <= p->frame()->lsn1) || ((p->get_storeflags() & smlevel_0::st_tmp) == smlevel_0::st_tmp) || smlevel_0::in_recovery_redo() ); } else { /* Clean pages should not have a rec_lsn. * GNATS 64. See also "GNATS 64 in bf.cpp" * It's possible that we missed * the pin count turning to 1 and so here we'll get a * 2nd chance. There's still a race, though, isn't there? * Pin count might not be 1 yet and we don't have a chance * to clear the rec_lsn. * And we can't simply clear the lsn because if there's * a double-latch by the same thread, and the other thread * is about to make an update, this would create problems. */ // FRJ: fixed a race here by ensuring that page latches are // released only after unpinning, and also by having // bf_m::unfix use latch information rather than pin // counts to decide whether to clear the rec_lsn. w_assert1(! p->curr_rec_lsn().valid() ); } } w_assert1(p->latch.held_by_me()); //NEH: changed to assert1 p->check(); /* FRJ: CLEAN_REC_LSN_RACE arises (at least partly) because we would unlatch pages before unpinning. However, we can avoid this by unpinning and then unlatching the page -- nobody else will touch the page until they can both pin and latch it. See also comments in bf.cpp; search for CLEAN_REC_LSN_RACE */ p->unpin_frame(); // atomic decrement #if SM_PLP_TRACING if (_ptrace_level>=PLP_TRACE_PAGE) { gettimeofday(&my_time, NULL); CRITICAL_SECTION(plpcs,_ptrace_lock); _ptrace_out << p->pid() << " " << pthread_self() << " " << p->latch.mode() << " " << my_time.tv_sec << "." << my_time.tv_usec << endl; plpcs.exit(); } #endif p->latch.latch_release(); // PROTOCOL // prevent future use of p p = 0; } /********************************************************************* * * bf_core_m::_remove(p) * * Remove frame "p" from hash table. Insert into unused list. * Called from ::remove while _bfc_mutex is held. * *********************************************************************/ rc_t bf_core_m::_remove(bfcb_t*& p) { w_assert9(p - _buftab >= 0 && p - _buftab < _num_bufs); w_assert9(_in_htab(p)); w_assert2(p->latch.is_mine()); w_assert2(p->latch.latch_cnt() == 1); p->check(); if (p->is_hot()) { // someone's waiting for the page. INC_TSTAT(bf_discarded_hot); #if W_DEBUG_LEVEL > 2 // W_FATAL(fcINTERNAL); // Not sure what to do here. It seems it's a legit situation. cerr << "is_hot. latch=" << &(p->latch) << endl; dumpthreads(); #endif } /* have to make sure it's not being cleaned. Because we have an EX-latch we only have to worry about a page write that was already in-progress before we latched. Acquiring the page write mutex for this pid will guarantee that any such in-progress write has completed (because the writer will clear the old_rec_lsn before releasing the mutex) */ if(p->old_rec_lsn().valid()) { CRITICAL_SECTION(cs, page_write_mutex_t::locate(p->pid())); w_assert0(!p->old_rec_lsn().valid()); } // fail if the page is pinned more than once, retry if the page // got moved while we were acquiring the lock { CRITICAL_SECTION(cs, transit_bucket_t::get(p->pid())._tb_mutex); // PROTOCOL static int const PATIENCE = 10; int i; for(i=0; i < PATIENCE; i++) { htab::bucket &b = _htab->_table[p->hash()]; // Note: we don't have the bucket locked, so this // could yield an ephemeral value if(b.get_frame(p->pid()) != p) continue; w_assert2(b._lock.is_mine()==false); // lock the bucket and check again... CRITICAL_SECTION(bcs, b._lock); // PROTOCOL w_assert2(b._lock.is_mine()); if(b.get_frame(p->pid()) != p) continue; // cuckoo! #if SM_PLP_TRACING if (_ptrace_level>=PLP_TRACE_PAGE) { gettimeofday(&my_time, NULL); CRITICAL_SECTION(plpcs,_ptrace_lock); _ptrace_out << p->pid() << " " << pthread_self() << " " << p->latch.mode() << " " << my_time.tv_sec << "." << my_time.tv_usec << endl; plpcs.exit(); } #endif p->latch.latch_release(); // PROTOCOL p->unpin_frame(); // adjust pin count; so the // remove can succeed; we still hold the lock w_assert1(b._lock.is_mine()); if(!_htab->remove(p)) { // W_FATAL(fcINTERNAL); // This had better be the reason it failed: // someone jumped in after we released the latch // and grabbed it. This is a hot page... // A test script that tripped this case is // file.perf3, with a large buffer pool, in which // case a file is being destroyed while the bf cleaner // is trying to write out its dirty pages. The // destroying thread gets here, trying to discard // the pages. Note that in this case, // the flushing thread is doing I/O and so it could // take quite a while before it frees up this // page for removal. // If the page doesn't get removed from the buffer // pool, it's not the end of the world; it'll get // thrown out eventually. w_assert3(p->pin_cnt() > 0); return RC(eHOTPAGE); } p->clear(); break; } if(i == PATIENCE) { #if SM_PLP_TRACING if (_ptrace_level>=PLP_TRACE_PAGE) { gettimeofday(&my_time, NULL); CRITICAL_SECTION(plpcs,_ptrace_lock); _ptrace_out << p->pid() << " " << pthread_self() << " " << p->latch.mode() << " " << my_time.tv_sec << "." << my_time.tv_usec << endl; plpcs.exit(); } #endif // oh well... p->latch.latch_release(); // PROTOCOL p->unpin_frame(); // adjust pin count return RC(eFRAMENOTFOUND); } } _unused.release(p); // put on free list p = NULL; return RCOK; } /*static*/ bool bf_core_m::can_replace(bfcb_t* p, int rounds) { w_assert0(p != NULL); // had better not call with null p /* * On the first partial-round, consider only clean pages. * After that, dirty ones are ok. * * FRJ: These used to test whether the latch was locked. However, * pin_cnt supercedes the latch -- anyone who holds the latch has * incremented pin_cnt (as well as anybody trying to acquire the * latch). */ bool found =false; if(!p->pin_cnt() && !p->old_rec_lsn().valid()) { switch(rounds) { case 2: // Like 1 but will accept dirty pages if(!p->refbit() && !p->hotbit()) { found=true; } break; case 1: // Unpinned, not hot, not dirty, no refbit if( !p->dirty() && !p->refbit() && !p->hotbit() ) { found=true; } break; case 0: // nothing is satisfactory. Not used at the moment. w_assert0(0); found = false; break; default: // Anything unpinned is ok. found=true; break; } } // make sure there is a free in-transit-out slot if(found && p->dirty()) { // Note: transit bucket is not in any way locked. // Declaring this available here does not guarantee it // to the caller, (but that caller turns out to // be replacment() only), and replacement holds a lock // on this bucket when it calls us. // Everywhere else that transit_bucket_t::get is used, // it is locked. transit_bucket_t* volatile buck = &transit_bucket_t::get(p->pid()); found = buck->empty(); if(!found) { INC_TSTAT(bf_no_transit_bucket); } } // FRJ: only true if we've got the bucket locked, which me might not. // NEH: In one call we have it locked; in the other, no. // w_assert1(found==false || p->latch.is_latched()==false); return found; } /********************************************************************* * * bf_core_m::_replacement() * * Find a replacement resource. Called from outside to provide a * frame for grab() to fill. If the replacement comes from the * freelist, it will have an invalid old_pid. Otherwise, it is marked * as in-transit-out and must be flushed if dirty. * * When this method is finished, the caller does not hold any * synchronization lock; what it returns is either taken from the * _unused list (in which case, it's no longer accessible to another * thread), or it's taken out of the hash table and put into the * in-transit-out table. * Preference is given to non-dirty pages. * * *********************************************************************/ bfcb_t* bf_core_m::replacement() { /* Freelist? */ bfcb_t* p = _unused.take(); // get a free frame if(p) { w_assert2(p->frame() != 0); p->clr_old_pid(); p->mark_clean(); w_assert1 (! _in_htab(p)); // Not in hash table // Get the latch just so that we are consistently // returning with the EX latch; this allows all the // threads --namely those in write_out(from clean_segment, // _scan, and update_rec_lsn) or replace_out (us) -- // to use the same protocol: latch then acquire // page_writer_mutex. w_rc_t rc = p->latch.latch_acquire(LATCH_EX, WAIT_IMMEDIATE); w_assert0(!rc.is_error()); return p; } /* * Use the clock algorithm to find replacement resource. * * Because replacement is expensive, but need not be serialized, * we release the clock hand whenever we think we have a * candidate. If we were wrong, we retry from the top, * reacquiring the clock hand and all. * * patience: equiv of 4 rounds == limit of # tries before we give up * looked_at: total number of tries so far * rounds: number of passes through the buffer pool so far * This is passed in to can_replace and * determines behavior of can_replace, which is why we keep * track of it. * 1: clean pages only * 2: dirty pages considered * 3 and larger: anything not pinned * next_round: #tries that indicates we've hit the next round * * We start with the clock hand, hence the counts(looked_at) * kept separately from the index (i, starts with hand) */ int looked_at = 0; int patience = 4*_num_bufs; int next_round = _num_bufs; int rounds = 1; while(1) { { // critical section CRITICAL_SECTION(cs, _bfc_mutex); // PROTOCOL int start = _hand; int i; for (i = start; ++looked_at < patience; i++) { if (i == _num_bufs) { i = 0; } if( looked_at == next_round) { rounds++; next_round += _num_bufs; } /* * p is current entry. */ p = _buftab + i; if (! _in_htab(p)) { // p could be in transit continue; } w_assert3(p->refbit() >= 0); DBG(<<"rounds: " << rounds << " dirty:" << p->dirty() << " refbit:" << p->refbit() << " hotbit:" << p->hotbit() << " pin_cnt:" << p->pin_cnt() << " locked:" << p->latch.is_latched() ); /* * On the first partial-round, consider only clean pages. * After that, dirty ones are ok. */ if(can_replace(p, rounds)) { /* * Update clock hand and release the mutex. * We'll reacquire if this doesn't work... */ _hand = (i+1 == _num_bufs) ? 0 : i+1; break; } /* * Unsuccessful. Decrement ref count. Try next entry. */ if (p->refbit()>0) p->decr_refbit(); w_assert3(p->refbit() >= 0); } if(looked_at >= patience) { cerr << "bf_core_m: cannot find free resource" << endl; cerr << *this; /* * W_FATAL(fcFULL); */ return (bfcb_t*)0; } } // end critical section /* * Found one! * * Now we have to lock the htbucket down and check for real. * * It may be that the frame's page has changed, or * that it was removed from the htable, or that its * status changed to something unacceptable. * * Note 1: once we hold the bucket lock, the page * cannot change from unpinned to pinned. So, we * remove it immediately while we still hold the * bucket lock. If a thread tries to grab() this * frame, it will block on the main mutex (which we * hold) until we've had a chance to put this frame in * its new home. * * Note 2: the page could get moved by a cuckoo hash * insert. if that happens while we're finding the * page, the hash may point to the wrong bucket. While * we *could* deal with this (by retrying to locate * this page) we don't currently bother to do so. * Instead we just look for another victim. */ int idx = p->hash(); bfpid_t pid = p->pid(); transit_bucket_t* volatile tb = &transit_bucket_t::get(pid); { CRITICAL_SECTION(tcs, tb->_tb_mutex); // PROTOCOL htab::bucket &b = _htab->_table[idx]; w_assert2(b._lock.is_mine()==false); { CRITICAL_SECTION(bcs, b._lock); // PROTOCOL w_assert2(b._lock.is_mine()); w_rc_t rc = p->latch.latch_acquire(LATCH_EX, WAIT_IMMEDIATE); // otherwise who knows what other threads are doing... if(!rc.is_error()) { // I don't like this - other threads hold onto the // page mutex for a long time (_write_out, _replace_out). // // Rather than preventing the replacement() from happening, // we should cope with the disappearance of the page. // // We try the page mutex. pthread_mutex_t* page_write_mutex = page_write_mutex_t::locate(pid); if(pthread_mutex_trylock(page_write_mutex) == EBUSY) { page_write_mutex = NULL; } // hold onto it long enough to do the following check // If the pointer is null, // it means we don't have the mutex, and auto_release does nothing. auto_release_t<pthread_mutex_t> cs(page_write_mutex); if(page_write_mutex) // we hold the mutex... { // In event of race, the pid in the frame could have changed if(b.get_frame(pid) == p && // We have the htab bucket lock. p->pid() == pid && _in_htab(p) && // could have been removed altogether can_replace(p, rounds) && _htab->remove(p)) // changes p->hash_func { w_assert2(p->hash() == idx); w_assert2(!_in_htab(p)); // Note : we have both the transit-bucket lock and // the htab bucket lock here. p->set_old_pid(); // now old_pid_valid() is true. if(p->dirty()) { tb->make_in_transit_out(p->pid()); } w_assert1(p->frame() != 0); // In this case, the frame is latched w_assert1(p->latch.is_mine() == true); return p; } } #if SM_PLP_TRACING if (_ptrace_level>=PLP_TRACE_PAGE) { gettimeofday(&my_time, NULL); CRITICAL_SECTION(plpcs,_ptrace_lock); _ptrace_out << p->pid() << " " << pthread_self() << " " << p->latch.mode() << " " << my_time.tv_sec << "." << my_time.tv_usec << endl; plpcs.exit(); } #endif p->latch.latch_release(); } // We didn't acquire the latch if rc.is_error // so let's assert here w_assert1(p->latch.is_mine() == false); } // end critical section } // end critical section // drat! try again } } #if W_DEBUG_LEVEL > 2 /********************************************************************* * * bf_core_m::audit() * * Check invarients for integrity. * *********************************************************************/ int bf_core_m::audit() const { int total_locks=0 ; for (int i = 0; i < _num_bufs; i++) { bfcb_t* p = _buftab + i; if(p->hash_func() == htab::HASH_COUNT) continue; // not in the table int idx = p->hash(); htab::bucket &b = _htab->_table[idx]; w_assert2(b._lock.is_mine()==false); CRITICAL_SECTION(bcs, b._lock); // PROTOCOL w_assert2(b._lock.is_mine()); bool found=false; for(int i=0; i < b._count; i++) { if (b._slots[i] == p) { found = true; w_assert2(p->hash() == idx); w_assert2(_in_htab(p)); if(p->latch.is_latched()) { w_assert2(p->latch.latch_cnt()>0); } total_locks += p->latch.latch_cnt() ; } } if(!found) { // the frame moved or got evicted... // nobody calls this function so I don't know whether // that's a bad thing or not } } DBG(<< "end of bf_core_m::audit"); return total_locks; } #endif /********************************************************************* * * bf_core_m::dump(ostream, debugging) * * Dump content to ostream. If "debugging" is true, print * synchronization info as well. * *********************************************************************/ void bf_core_m::dump(ostream &o, bool /*debugging*/)const { o << "bf_core_m:" << ' ' << _num_bufs << " frames" << endl; o << "frame#" << '\t' << "pid" << '\t' << '\t' << "dirty?" << '\t' << "rec_lsn" << '\t' << "pin_cnt" << '\t' << "l_mode" << '\t' << "l_cnt" << '\t' << "l_hot" << '\t' << "refbit" << '\t' << "l_id" << endl << flush; int n = 0; int t = 0; int pincnt = 0; for (int i = 0; i < _num_bufs; i++) { bfcb_t* p = _buftab + i; pincnt += p->pin_cnt(); if (_in_htab(p)) { n++; o << i << '\t'; p->print_frame(o, true); } } o << "number of frames in the HASH TABLE: " << n << endl; o << "number of frames in TRANSIT: " << t << endl; o << endl << flush; } ostream & operator<<(ostream& out, const bf_core_m& mgr) { mgr.dump(out, 0); return out; } #include <sm_vtable_enum.h> #ifdef __GNUG__ template class vtable_func<bfcb_t>; #endif /* __GNUG__ */ enum { /* for buffer pool */ bp_pid_attr, bp_pin_cnt_attr, bp_mode_attr, bp_dirty_attr, bp_hot_attr, /* last number! */ bp_last }; const char *bp_vtable_attr_names[] = { "Pid", "Pin count", "Pin mode", "Dirty", "Hot" }; static vtable_names_init_t names_init(bp_last, bp_vtable_attr_names); void bfcb_t::vtable_collect(vtable_row_t &t) { if(pid().valid()) { { // circumvent with const-ness // attribute. Needs special handling b/c we don't have // a set_pid() method for this. w_ostrstream o; o << pid() << ends; t.set_string(bp_pid_attr, o.c_str()); } t.set_int(bp_pin_cnt_attr, pin_cnt()); t.set_string(bp_mode_attr, latch_t::latch_mode_str[latch.mode()] ); t.set_string(bp_dirty_attr, (const char *) (dirty()?"true":"false") ); t.set_string(bp_hot_attr, (const char *)(is_hot()?"true":"false")); } } void bfcb_t::vtable_collect_names(vtable_row_t &t) { names_init.collect_names(t); } int bf_core_m::collect(vtable_t &v, bool names_too) { // _num_bufs is larger than needed // but we have no quick way to find out // how many are empty/non-empty frames, so this // is ok // num_bufs: number of rows. // bp_last: number of attributes // names_init.max_size: maximum length of attribute int n = _num_bufs; if(names_too) n++; if(v.init(n, bp_last, names_init.max_size())) return -1; vtable_func<bfcb_t> f(v); if(names_too) f.insert_names(); for (int i = 0; i < _num_bufs; i++) { if(_buftab[i].pid().valid()) { f(_buftab[i]); } } return 0; // no error } void bf_core_m::htab_stats(bf_htab_stats_t &out) const { if(_htab) _htab->stats(out); *(&out.bf_htab_entries) = _num_bufs; } #endif /* BF_CORE_C */
33.263988
94
0.53793
[ "object", "vector" ]
ca25dea3ca9dc0df55d684f85d9e9d5366a07b10
7,465
cpp
C++
Marlin/src/lcd/extui/ftdi_eve_touch_ui/ftdi_eve_lib/extended/unicode/unicode.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
Marlin/src/lcd/extui/ftdi_eve_touch_ui/ftdi_eve_lib/extended/unicode/unicode.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
Marlin/src/lcd/extui/ftdi_eve_touch_ui/ftdi_eve_lib/extended/unicode/unicode.cpp
tom-2273/Tronxy_SKR_mini_E3_V20
bc4a8dc2c6c627e4bd7aa423794246f5b051448d
[ "CC0-1.0" ]
null
null
null
/*************** * unicode.cpp * ***************/ /**************************************************************************** * Written By Marcio Teixeira 2019 - Aleph Objects, Inc. * * * * This program is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * To view a copy of the GNU General Public License, go to the following * * location: <https://www.gnu.org/licenses/>. * ****************************************************************************/ #include "../ftdi_extended.h" #if BOTH(FTDI_EXTENDED, TOUCH_UI_USE_UTF8) using namespace FTDI; /** * Return true if a string has UTF8 characters * * Parameters: * * c - Pointer to a string. * * Returns: True if the strings has UTF8 characters */ bool FTDI::has_utf8_chars(const char *str) { for (;;) { const char c = *str++; if (!c) break; if ((c & 0xC0) == 0x80) return true; } return false; } bool FTDI::has_utf8_chars(FSTR_P _str) { const char *str = (const char *) _str; for (;;) { const char c = pgm_read_byte(str++); if (!c) break; if ((c & 0xC0) == 0x80) return true; } return false; } /** * Return a character in a UTF8 string and increment the * pointer to the next character * * Parameters: * * c - Pointer to a UTF8 encoded string. * * Returns: The packed bytes of a UTF8 encoding of a single * character (this is not the unicode codepoint) */ utf8_char_t FTDI::get_utf8_char_and_inc(char *&c) { utf8_char_t val = *(uint8_t*)c++; if ((val & 0xC0) == 0xC0) while ((*c & 0xC0) == 0x80) val = (val << 8) | *(uint8_t*)c++; return val; } utf8_char_t FTDI::get_utf8_char_and_inc(char *&c) { utf8_char_t val = *(uint8_t*)c++; if ((val & 0xC0) == 0xC0) while ((*c & 0xC0) == 0x80) val = (val << 8) | *(uint8_t*)c++; return val; } /** * Helper function to draw and/or measure a UTF8 string * * Parameters: * * cmd - If non-NULL the symbol is drawn to the screen. * If NULL, only increment position for text measurement. * * x, y - The location at which to draw the string. * * str - The UTF8 string to draw or measure. * * fs - A scaling object used to specify the font size. */ static uint16_t render_utf8_text(CommandProcessor* cmd, int x, int y, const char *str, font_size_t fs, size_t maxlen=SIZE_MAX) { const int start_x = x; while (*str && maxlen--) { const utf8_char_t c = get_utf8_char_and_inc(str); #ifdef TOUCH_UI_UTF8_CYRILLIC_CHARSET CyrillicCharSet::render_glyph(cmd, x, y, fs, c) || #endif #ifdef TOUCH_UI_UTF8_WESTERN_CHARSET WesternCharSet::render_glyph(cmd, x, y, fs, c) || #endif StandardCharSet::render_glyph(cmd, x, y, fs, c); } return x - start_x; } /** * Load the font bitmap data into RAMG. Called once at program start. * * Parameters: * * addr - Address in RAMG where the font data is written */ void FTDI::load_utf8_data(uint32_t addr) { #ifdef TOUCH_UI_UTF8_CYRILLIC_CHARSET addr = CyrillicCharSet::load_data(addr); #endif #ifdef TOUCH_UI_UTF8_WESTERN_CHARSET addr = WesternCharSet::load_data(addr); #endif addr = StandardCharSet::load_data(addr); } /** * Populate the bitmap handles for the custom fonts into the display list. * Called once at the start of each display list. * * Parameters: * * cmd - Object used for writing to the FTDI chip command queue. */ void FTDI::load_utf8_bitmaps(CommandProcessor &cmd) { cmd.cmd(SAVE_CONTEXT()); #ifdef TOUCH_UI_UTF8_CYRILLIC_CHARSET CyrillicCharSet::load_bitmaps(cmd); #endif #ifdef TOUCH_UI_UTF8_WESTERN_CHARSET WesternCharSet::load_bitmaps(cmd); #endif StandardCharSet::load_bitmaps(cmd); cmd.cmd(RESTORE_CONTEXT()); } /** * Measure a UTF8 text character * * Parameters: * * c - The unicode code point to measure. * * fs - A scaling object used to specify the font size. * * Returns: A width in pixels */ uint16_t FTDI::get_utf8_char_width(utf8_char_t c, font_size_t fs) { int x = 0, y = 0; #ifdef TOUCH_UI_UTF8_CYRILLIC_CHARSET CyrillicCharSet::render_glyph(nullptr, x, y, fs, c) || #endif #ifdef TOUCH_UI_UTF8_WESTERN_CHARSET WesternCharSet::render_glyph(nullptr, x, y, fs, c) || #endif StandardCharSet::render_glyph(nullptr, x, y, fs, c); return x; } /** * Measure a UTF8 text string * * Parameters: * * str - The UTF8 string to measure. * * fs - A scaling object used to specify the font size. * * Returns: A width in pixels */ uint16_t FTDI::get_utf8_text_width(const char *str, font_size_t fs, size_t maxlen) { return render_utf8_text(nullptr, 0, 0, str, fs, maxlen); } uint16_t FTDI::get_utf8_text_width(FSTR_P pstr, font_size_t fs) { char str[strlen_P((const char*)pstr) + 1]; strcpy_P(str, (const char*)pstr); return get_utf8_text_width(str, fs); } /** * Draw a UTF8 text string * * Parameters: * * cmd - Object used for writing to the FTDI chip command queue. * * x, y - The location at which to draw the string. * * str - The UTF8 string to draw. * * fs - A scaling object used to specify the font size. * * options - Text alignment options (i.e. OPT_CENTERX, OPT_CENTERY, OPT_CENTER or OPT_RIGHTX) * * maxlen - Maximum characters to draw */ void FTDI::draw_utf8_text(CommandProcessor& cmd, int x, int y, const char *str, font_size_t fs, uint16_t options, size_t maxlen) { cmd.cmd(SAVE_CONTEXT()); cmd.cmd(BITMAP_TRANSFORM_A(fs.get_coefficient())); cmd.cmd(BITMAP_TRANSFORM_E(fs.get_coefficient())); cmd.cmd(BEGIN(BITMAPS)); // Apply alignment options if (options & OPT_CENTERX) x -= get_utf8_text_width(str, fs, maxlen) / 2; else if (options & OPT_RIGHTX) x -= get_utf8_text_width(str, fs, maxlen); if (options & OPT_CENTERY) y -= fs.get_height()/2; // Render the text render_utf8_text(&cmd, x, y, str, fs, maxlen); cmd.cmd(RESTORE_CONTEXT()); } void FTDI::draw_utf8_text(CommandProcessor& cmd, int x, int y, FSTR_P pstr, font_size_t fs, uint16_t options) { char str[strlen_P((const char*)pstr) + 1]; strcpy_P(str, (const char*)pstr); draw_utf8_text(cmd, x, y, (const char*) str, fs, options); } #endif // FTDI_EXTENDED && TOUCH_UI_USE_UTF8
30.594262
132
0.583255
[ "render", "object" ]
ca2ce20cf686a83c5b4620b857c69d758d9deabc
5,468
cpp
C++
path_planning/src/path_planning.cpp
KevinBollore/fanuc_grinding
74cb5708ece179a3161858fe00ca957ddc75823e
[ "BSD-3-Clause" ]
4
2020-01-03T06:36:45.000Z
2022-02-18T07:35:51.000Z
path_planning/src/path_planning.cpp
KevinBollore/fanuc_grinding
74cb5708ece179a3161858fe00ca957ddc75823e
[ "BSD-3-Clause" ]
null
null
null
path_planning/src/path_planning.cpp
KevinBollore/fanuc_grinding
74cb5708ece179a3161858fe00ca957ddc75823e
[ "BSD-3-Clause" ]
2
2021-09-10T03:18:28.000Z
2022-03-22T06:53:27.000Z
/************************************************ Path planner using bezier library. This file which operate path planning represents one node of the entire demonstrator ************************************************/ // ROS headers #include <ros/ros.h> #include <ros/package.h> #include <ros/service.h> #include <tf/transform_listener.h> #include <tf_conversions/tf_eigen.h> #include <eigen_conversions/eigen_msg.h> #include <moveit/move_group_interface/move_group.h> #include <moveit_msgs/ExecuteKnownTrajectory.h> #include <visualization_msgs/Marker.h> #include <visualization_msgs/MarkerArray.h> #include <std_msgs/String.h> #include <eigen_stl_containers/eigen_stl_vector_container.h> #include "bezier_library/bezier_grinding_surfacing.hpp" #include <fanuc_grinding_path_planning/PathPlanningService.h> // Description of the Service we will use boost::shared_ptr<move_group_interface::MoveGroup> group; boost::shared_ptr<ros::NodeHandle> node; EigenSTL::vector_Affine3d way_points_vector; /** Status publisher */ boost::shared_ptr<ros::Publisher> status_pub; /** Name of the move_group used to move the robot during calibration */ const std::string move_group_name("grinding_disk"); /** Name of the TCP that should be used to compute the trajectories */ const std::string tcp_name("/grinding_disk_tcp"); /** * This is the service function that is called whenever a request is received * @param req[int] * @param res[out] * @return Always true */ bool pathPlanning(fanuc_grinding_path_planning::PathPlanningService::Request &req, fanuc_grinding_path_planning::PathPlanningService::Response &res) { ROS_INFO_STREAM(std::endl << req); if (!req.SurfacingMode) { res.ReturnStatus = false; res.ReturnMessage = "Grinding mode is not implemented yet!"; return true; } std_msgs::String status; std::vector<bool> is_grinding_pose; if (req.Compute) { std::string package = "fanuc_grinding_path_planning"; //Get package path std::string mesh_ressource = "package://" + package + "/meshes/"; std::string mesh_ressource_file = "file://"; // Get PLY file name from command line std::string input_mesh_filename = req.CADFileName; // Determine lean angle axis std::string lean_angle_axis; BezierGrindingSurfacing::AXIS_OF_ROTATION lean_axis; if (req.AngleX == true) lean_axis = BezierGrindingSurfacing::X; else if (req.AngleY == true) lean_axis = BezierGrindingSurfacing::Y; else if (req.AngleZ == true) lean_axis = BezierGrindingSurfacing::Z; else { res.ReturnStatus = false; res.ReturnMessage = "Please select a lean angle axis for the effector"; return true; } BezierGrindingSurfacing bezier(input_mesh_filename, req.GrinderWidth, req.CoveringPercentage, req.ExtricationRadius, req.LeanAngle, lean_axis); status.data = "Generate Bezier trajectory"; status_pub->publish(status); std::string error_string; error_string = bezier.generateTrajectory(way_points_vector, is_grinding_pose); if (!error_string.empty()) { res.ReturnStatus = false; res.ReturnMessage = error_string; return true; } } // Copy the vector of Eigen poses into a vector of ROS poses std::vector<geometry_msgs::Pose> way_points_msg; for (Eigen::Affine3d pose : way_points_vector) { geometry_msgs::Pose tmp; tf::poseEigenToMsg(pose, tmp); way_points_msg.push_back(tmp); } res.RobotPosesOutput = way_points_msg; for (std::vector<bool>::const_iterator iter(is_grinding_pose.begin()); iter != is_grinding_pose.end(); ++iter) res.IsGrindingPose.push_back(*iter); if (!req.Simulate) { res.ReturnStatus = true; res.ReturnMessage = boost::lexical_cast<std::string>(way_points_msg.size()) + " poses generated"; return true; } tf::TransformListener listener; listener.waitForTransform("/base", tcp_name, ros::Time::now(), ros::Duration(1.0)); // Execute this trajectory moveit_msgs::ExecuteKnownTrajectory srv; srv.request.wait_for_execution = true; ros::ServiceClient executeKnownTrajectoryServiceClient = node->serviceClient < moveit_msgs::ExecuteKnownTrajectory > ("/execute_kinematic_path"); double percentage = group->computeCartesianPath(way_points_msg, 0.05, 0.0, srv.request.trajectory); status.data = boost::lexical_cast<std::string>(percentage*100) + "% of the trajectory will be executed"; status_pub->publish(status); executeKnownTrajectoryServiceClient.call(srv); if (percentage < 0.9) { res.ReturnStatus = false; res.ReturnMessage = "Could not compute the whole trajectory!"; } else res.ReturnStatus = true; return true; } int main(int argc, char **argv) { ros::init(argc, argv, "path_planning"); node.reset(new ros::NodeHandle); status_pub.reset(new ros::Publisher); *status_pub = node->advertise <std_msgs::String> ("scanning_status", 1); // Initialize move group group.reset(new move_group_interface::MoveGroup("grinding_disk")); group->setPoseReferenceFrame("/base_link"); group->setPlannerId("RRTConnectkConfigDefault"); group->setPlanningTime(2); // Create service server and wait for incoming requests ros::ServiceServer service = node->advertiseService("path_planning_service", pathPlanning); ros::AsyncSpinner spinner(1); spinner.start(); while (node->ok()) { } spinner.stop(); return 0; }
32.164706
120
0.710315
[ "vector" ]
ca2fc3760a97f6114d8ee1ed008066161f1aa8cb
16,007
cpp
C++
jerome/npc/detail/Trainer.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
3
2018-06-11T10:48:54.000Z
2021-05-30T07:10:15.000Z
jerome/npc/detail/Trainer.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
jerome/npc/detail/Trainer.cpp
leuski-ict/jerome
6141a21c50903e98a04c79899164e7d0e82fe1c2
[ "Apache-2.0" ]
null
null
null
// // Trainer.cpp // // Created by Anton Leuski on 8/1/15. // Copyright (c) 2015 Anton Leuski & ICT/USC. All rights reserved. // // This file is part of Jerome. // // 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 <set> #include <jerome/npc/detail/types_fwd.hpp> #include <jerome/ir/evaluation/accumulators/statistics/accuracy.hpp> #include <jerome/ir/evaluation/accumulators/statistics/average_precision.hpp> #include <jerome/ir/evaluation/accumulators/statistics/f_measure.hpp> #include <jerome/ir/evaluation/accumulators/statistics/average.hpp> #include <jerome/ir/evaluation.hpp> #include <jerome/ir/training/TestSet.hpp> #include <jerome/npc/detail/Ranker_impl.hpp> #include <jerome/npc/detail/Ranker.hpp> #include <jerome/ir/training/Trainer.hpp> #include "Trainer.hpp" namespace acc = jerome::ir::evaluation::accumulators; namespace jerome { namespace npc { namespace detail { Trainer::progress_callback_type Trainer::default_progress_callback = [] (const Trainer::state_type&) { }; Trainer::state_type::~state_type() { } class TrainerImplementation { public: TrainerImplementation() = default; TrainerImplementation(const Record& inModel) : mModel(inModel) {} virtual ~TrainerImplementation() { } virtual Result<Trainer::result_type> train(IndexedRanker& inRanker, const Trainer::progress_callback_type& callback) = 0; void setData(const Data& trainData, const Data& devData) { mTrainData = trainData; mDevData = devData; } Data trainData() const { return mTrainData; } Data devData() const { return mDevData; } const Record& model() const { return mModel; } void setModel(const Record& inModel) { mModel = inModel; } private: Data mTrainData; Data mDevData; Record mModel; }; #define COPY_VAL(KEY, OPT, FUN) \ { auto optional_double = this->model().template at<double>(Trainer::KEY); \ if (optional_double) OPT.set_##FUN(*optional_double); \ } struct Algorithm { nlopt::algorithm algorithm; bool global; bool requiresLocal; Algorithm(nlopt::algorithm inAlgorithm , bool inGlobal = true , bool inRequiresLocal = false) : algorithm(inAlgorithm) , global(inGlobal) , requiresLocal(inRequiresLocal) {} // Algorithm(const Algorithm&) = default; // Algorithm(Algorithm&&) = default; // Algorithm& operator = (const Algorithm&) = default; // Algorithm& operator = (Algorithm&&) = default; }; #define MAP_ASSIGN(X) \ map.emplace(#X, Algorithm(nlopt::X)) #define MAP_ASSIGN_L(X) \ map.emplace(#X, Algorithm(nlopt::X, false)) #define MAP_ASSIGN_G_L(X) \ map.emplace(#X, Algorithm(nlopt::X, true, true)) static StringMap<Algorithm> makeAlgorithms() { StringMap<Algorithm> map; MAP_ASSIGN(GN_DIRECT_L_RAND); MAP_ASSIGN(GN_DIRECT_L); MAP_ASSIGN(GN_DIRECT); MAP_ASSIGN(GN_DIRECT_NOSCAL); MAP_ASSIGN(GN_DIRECT_L_NOSCAL); MAP_ASSIGN(GN_DIRECT_L_RAND_NOSCAL); // MAP_ASSIGN(GN_ORIG_DIRECT); // MAP_ASSIGN(GN_ORIG_DIRECT_L); MAP_ASSIGN(GN_CRS2_LM); MAP_ASSIGN(GN_ISRES); MAP_ASSIGN_G_L(AUGLAG); MAP_ASSIGN_G_L(AUGLAG_EQ); MAP_ASSIGN_G_L(G_MLSL); MAP_ASSIGN_G_L(G_MLSL_LDS); MAP_ASSIGN_L(LN_BOBYQA); MAP_ASSIGN_L(LN_COBYLA); MAP_ASSIGN_L(LN_PRAXIS); MAP_ASSIGN_L(LN_NEWUOA); MAP_ASSIGN_L(LN_NEWUOA_BOUND); MAP_ASSIGN_L(LN_NELDERMEAD); MAP_ASSIGN_L(LN_SBPLX); MAP_ASSIGN_L(LN_AUGLAG); MAP_ASSIGN_L(LN_AUGLAG_EQ); return map; } static const StringMap<Algorithm>& algorithmsMap() { static StringMap<Algorithm> algorithmsMap = makeAlgorithms(); return algorithmsMap; } List<String> Trainer::algorithms(AlgorithmKind kind) { List<String> list; for(const auto& i : algorithmsMap()) { switch (kind) { case ALL: list.push_back(i.first); break; case GLOBAL: if (i.second.global) list.push_back(i.first); break; case LOCAL: if (!i.second.global) list.push_back(i.first); break; case GLOBAL_REQUIRING_LOCAL: if (i.second.global && i.second.requiresLocal) list.push_back(i.first); break; } } std::sort(list.begin(), list.end()); return list; } template <typename F> class TrainerImplementationTemplate : public TrainerImplementation { typedef TrainerImplementation parent_type; using parent_type::parent_type; typedef ir::training::Optimizer optimizer_type; struct objective_type : public jerome::ir::training::ObjectiveFunction<IndexedRanker, jerome::ir::evaluation::RankedListCollectorOne< Data::answer_type, F >> { typedef jerome::ir::training::ObjectiveFunction<IndexedRanker, jerome::ir::evaluation::RankedListCollectorOne< Data::answer_type, F >> parent_type; using parent_type::parent_type; }; class state_type_impl : public Trainer::state_type { public: state_type_impl(optimizer_type& opt) : mSource(opt) {} double lastValue() const override { return mSource.lastValue(); } jerome::math::parameters::value_vector lastArgument() const override { return mSource.lastArgument(); } double elapsedTimeInSeconds() const override { return mSource.elapsedTimeInSeconds(); } void stop() override { mSource.stop(); } private: optimizer_type& mSource; }; Result<Trainer::result_type> train(IndexedRanker& inRanker, const Trainer::progress_callback_type& callback) override { typedef IndexedRanker ranker_type; typedef typename ranker_type::test_set_type test_set_type; test_set_type devSet = inRanker.testSetWithData(this->devData()); objective_type obj(inRanker, devSet); ir::range_vector ranges = inRanker.ranges(); nlopt::algorithm algorithm = nlopt::GN_DIRECT_L_RAND; auto global_alg_name = this->model() .template at<String>(Trainer::G_ALGORITHM); bool requiresLocal = false; if (global_alg_name) { auto optional_algorithm = map_value_at(algorithmsMap(), *global_alg_name); if (!optional_algorithm) { return Error("Unknown global optimization algorithm " + *global_alg_name); } algorithm = optional_algorithm->algorithm; requiresLocal = optional_algorithm->requiresLocal; } optimizer_type gopt(algorithm, ranges); COPY_VAL(G_FTOL_REL, gopt, ftol_rel); COPY_VAL(G_FTOL_ABS, gopt, ftol_abs); COPY_VAL(G_XTOL_REL, gopt, xtol_rel); COPY_VAL(G_XTOL_ABS, gopt, xtol_abs); auto local_alg_name = this->model() .template at<String>(Trainer::L_ALGORITHM); if (local_alg_name) { auto optional_algorithm = map_value_at(algorithmsMap(), *local_alg_name); if (!optional_algorithm || optional_algorithm->global) { return Error("Unknown local optimization algorithm " + *local_alg_name); } optimizer_type lopt(optional_algorithm->algorithm, ranges); COPY_VAL(L_FTOL_REL, lopt, ftol_rel); COPY_VAL(L_FTOL_ABS, lopt, ftol_abs); COPY_VAL(L_XTOL_REL, lopt, xtol_rel); COPY_VAL(L_XTOL_ABS, gopt, xtol_abs); lopt.set_max_objective(obj); gopt.set_local_optimizer(lopt); } else if (requiresLocal) { return Error("Local optimization algorithm is required for " + *global_alg_name); } gopt.set_max_objective(obj); gopt.set_callback([&callback] (optimizer_type& opt) { state_type_impl state(opt); callback(state); }); std::vector<double> x = inRanker.values(); std::vector<double> o = math::parameters::clumpToMean(x, ranges); // log::info() << x; // log::info() << obj.scoreValuePair(x); x = gopt.optimize(o); // log::info() << "switch"; // // optimizer_type lopt(nlopt::LN_BOBYQA, ranges); // lopt.set_ftol_rel(5.0e-4); // lopt.set_max_objective(obj); // // x = lopt.optimize(x); Trainer::result_type result; result.params = x; result.best_point = obj.scoreValuePair(x); if (this->model().at(Trainer::HACK_THRESHOLD, Bool()).value()) { // log::info() << "hacking score to " // << result.best_point.score() - 1; result.best_point = ScoredObject<double>(result.best_point.score() - 1, result.best_point.object()); } // log::info() << x; // log::info() << result.best_point; return std::move(result); } // this function compares different optimization algorithms from the // NLopt // library. No optimization problem is the same, so they suggest running // one algorithm for a long time with high precision termination // conditions // or even time condition, and then run the other algorithms with the // discovered value as the "stopval" term ination criteria and count // the number of function evaluations needed to reach that goal. // // on the basic twins data, 50% dev set, GN_DIRECT_L_RAND is the // fastest. void compareOptimizationAlgorithms(IndexedRanker& inRanker) { ir::range_vector ranges = inRanker.ranges(); typename objective_type::test_set_type devSet = inRanker.testSetWithData( this->devData()); std::vector<double> o = math::parameters::mean(ranges); // double stop_value = 0.381; for (auto galg : algorithmsMap()) { optimizer_type gopt(galg.second.algorithm, ranges); // gopt.set_xtol_abs(1e-2); gopt.set_ftol_abs(1e-3); // gopt.set_stopval(stop_value); if (!galg.second.requiresLocal) { objective_type obj(inRanker, devSet); gopt.set_max_objective(obj); log::info() << gopt.get_algorithm_name(); try { gopt.optimize(o); log::info() << obj.evaluationCount(); } catch (const std::exception& ex) { log::error() << "exception:" << ex.what(); } } else { for (auto lalg : algorithmsMap()) { if (lalg.second.global) continue; objective_type obj(inRanker, devSet); optimizer_type lopt(lalg.second.algorithm, ranges); // lopt.set_stopval(stop_value); // lopt.set_xtol_abs(1e-4); lopt.set_ftol_rel(1e-4); lopt.set_max_objective(obj); gopt.set_local_optimizer(lopt); gopt.set_max_objective(obj); log::info() << gopt.get_algorithm_name() << " w/ " << lopt.get_algorithm_name() ; try { gopt.optimize(o); log::info() << obj.evaluationCount(); } catch (const std::exception& ex) { log::error() << "exception:" << ex.what(); } } } } } }; Result<Trainer::result_type> Trainer::train(IndexedRanker& inRanker, const progress_callback_type& callback) { return this->implementation().train(inRanker, callback); } Data Trainer::trainData() const { return this->implementation().trainData(); } Data Trainer::devData() const { return this->implementation().devData(); } void Trainer::setData(const Data& trainData, const Data& devData) { this->implementation().setData(trainData, devData); } Record Trainer::model() const { return this->implementation().model(); } void Trainer::setModel(const Record& inModel) { this->implementation().setModel(inModel); } } } } #include <jerome/npc/factories/TrainerFactory.hpp> #include <jerome/ir/evaluation/accumulators/statistics_fwd.hpp> #include <jerome/ir/evaluation/accumulators/statistics_names.hpp> namespace jerome { namespace npc { namespace acc = jerome::ir::evaluation::accumulators; namespace detail { template <typename F> struct DefaultTrainerProvider : public TrainerFactory::provider_type { static String identifier() { return String("jerome.trainer.") + acc::accumulator_name<F>::name(); } Result<TrainerFactory::object_type> provide(const Record& inRecord) override { return Trainer(std::make_shared<TrainerImplementationTemplate<F>>(inRecord)); } }; template <typename F> static void registerProvider(TrainerFactory& factory) { factory.registerProviderClassForID<DefaultTrainerProvider<F>> (DefaultTrainerProvider<F>::identifier()); } String Trainer::trainerFscoreID() { return DefaultTrainerProvider<acc::tag::fmeasure>::identifier(); } String Trainer::trainerAveragePrecisionID() { return DefaultTrainerProvider<acc::tag::average_precision>::identifier(); } String Trainer::trainerAccuracyID() { return DefaultTrainerProvider<acc::tag::accuracy>::identifier(); } } TrainerFactory::TrainerFactory() { detail::registerProvider<acc::tag::average_precision>(*this); detail::registerProvider<acc::tag::accuracy>(*this); detail::registerProvider<acc::tag::fmeasure>(*this); registerModel("fscore", { TrainerFactory::PROVIDER_KEY, detail::Trainer::trainerFscoreID() }); registerModel("average-precision", { TrainerFactory::PROVIDER_KEY, detail::Trainer::trainerAveragePrecisionID() }); registerModel("accuracy", { TrainerFactory::PROVIDER_KEY, detail::Trainer::trainerAccuracyID() }); setDefaultModelKey("fscore"); } } }
29.975655
89
0.580434
[ "object", "vector", "model" ]
ca301da32bbc8cb9659fa9e291948e873e193e45
537
cpp
C++
src/Analysers/METBinnedElectronAnalyser.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
src/Analysers/METBinnedElectronAnalyser.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
src/Analysers/METBinnedElectronAnalyser.cpp
jjacob/AnalysisSoftware
670513bcde9c3df46077f906246e912627ee251a
[ "Apache-2.0" ]
null
null
null
/* * METBinnedElectronAnalyser.cpp * * Created on: 3 Jul 2012 * Author: kreczko */ #include "../../interface/Analysers/METBinnedElectronAnalyser.h" namespace BAT { METBinnedElectronAnalyser::METBinnedElectronAnalyser(HistogramManagerPtr histMan, std::string histogramFolder) : BasicAnalyser(histMan, histogramFolder), // metbins_() { } METBinnedElectronAnalyser::~METBinnedElectronAnalyser() { } void METBinnedElectronAnalyser::setMETbins(std::vector<double> metbins){ metbins_ = metbins; } } /* namespace BAT */
19.888889
112
0.748603
[ "vector" ]
ca322d5ada9872069480160b36459a4bd594c251
76,006
cpp
C++
.vim/sourceCode/ogre_src_v1-8-1/OgreMain/src/OgreProgressiveMesh.cpp
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
null
null
null
.vim/sourceCode/ogre_src_v1-8-1/OgreMain/src/OgreProgressiveMesh.cpp
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
null
null
null
.vim/sourceCode/ogre_src_v1-8-1/OgreMain/src/OgreProgressiveMesh.cpp
lakehui/Vim_config
6cab80dc1209b34bf6379f42b1a92790bd0c146b
[ "MIT" ]
2
2019-05-16T08:19:45.000Z
2021-01-24T21:02:43.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2012 Torus Knot Software Ltd 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 "OgreStableHeaders.h" // The algorithm in this file is based heavily on: /* * Progressive Mesh type Polygon Reduction Algorithm * by Stan Melax (c) 1998 */ #include "OgreProgressiveMesh.h" #include "OgreLodStrategyManager.h" #include "OgreMeshManager.h" #include "OgreSubMesh.h" #include "OgreString.h" #include "OgreHardwareBufferManager.h" #include "OgreLogManager.h" #if OGRE_DEBUG_MODE #define LOG_PROGRESSIVE_MESH_GENERATION 1 #else #define LOG_PROGRESSIVE_MESH_GENERATION 0 #endif #if LOG_PROGRESSIVE_MESH_GENERATION #include <iostream> std::ofstream ofdebug; #endif namespace Ogre { const unsigned char BitArray::bit_count[16] = { 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4 }; const unsigned char BitArray::bit_mask[8] = { 1, 2, 4, 8, 16, 32, 64, 128 }; //#define IGNORE_UV_AND_NORMAL_COSTS //#define CHECK_CALCULATED_NORMALS #define NEVER_COLLAPSE_COST 99999.9f class VertexDataVariant { private: unsigned char* mBaseDataPointer; unsigned char* mCurDataPointer; size_t mOffsetSize; // source dependent part, only first buffer of several with shared mSource holds lock on hardware vertex buffer int mSource; HardwareVertexBufferSharedPtr mBuffer; std::auto_ptr<VertexBufferLockGuard> mLockGuard; // only first by source takes lock friend class VertexDataVariantList; VertexDataVariant(const VertexData * vertexData, const VertexElement* vertexElement, VertexDataVariant* bufferOwner) : mOffsetSize(0) , mSource(-1) { static float fakeDataBuffer[3] = { 0.0f, 0.0f, 0.0f }; // 12 bytes, can be safely used with zero mOffsetSize mBaseDataPointer = mCurDataPointer = (unsigned char*)fakeDataBuffer; if(NULL != vertexElement) { mSource = vertexElement->getSource(); mBuffer = vertexData->vertexBufferBinding->getBuffer(mSource); // only first VertexDataVariant really locks buffer and store pointer to raw data if(NULL == bufferOwner) { // buffer is not locked yet, so lock it and became buffer owner mLockGuard.reset(new VertexBufferLockGuard(mBuffer, HardwareBuffer::HBL_READ_ONLY)); bufferOwner = this; } // adjust whole vertex pointer to vertex part pointer vertexElement->baseVertexPointerToElement(bufferOwner->mLockGuard->pData, &mBaseDataPointer); mCurDataPointer = mBaseDataPointer; mOffsetSize = mBuffer->getVertexSize(); } } public: bool isValid() const { return mOffsetSize != 0; } int getSource() const { return mSource; } unsigned char* getBaseDataPointer() const { return mBaseDataPointer; } unsigned char* getCurDataPointer() const { return mCurDataPointer; } size_t getOffsetSize() const { return mOffsetSize; } void reset() { mCurDataPointer = mBaseDataPointer; } void offset() { mCurDataPointer += mOffsetSize; } void offsetToElement(int itemIndex) { mCurDataPointer = mBaseDataPointer + itemIndex * mOffsetSize; } Vector3 getNextVector3() { float* v = (float*)mCurDataPointer; mCurDataPointer += mOffsetSize; return Vector3(v[0], v[1], v[2]); } Vector2 getNextVector2() { float* v = (float*)mCurDataPointer; mCurDataPointer += mOffsetSize; return Vector2(v[0], v[1]); } }; class VertexDataVariantList { public: VertexDataVariant* create(const VertexData * vertexData, VertexElementSemantic sem) { const VertexElement* vertexElement = vertexData->vertexDeclaration->findElementBySemantic(sem); VertexDataVariant* bufferOwner = vertexElement ? getBySource(vertexElement->getSource()) : NULL; mVdList.push_back(VertexDataVariantSharedPtr(new VertexDataVariant(vertexData, vertexElement, bufferOwner))); return mVdList.back().get(); } private: VertexDataVariant* getBySource(int source) { for(vd_list_t::const_iterator it = mVdList.begin(); it != mVdList.end(); ++it) if((*it)->getSource() == source) return it->get(); return NULL; } private: typedef SharedPtr<VertexDataVariant> VertexDataVariantSharedPtr; typedef vector<VertexDataVariantSharedPtr>::type vd_list_t; vd_list_t mVdList; }; class IndexDataVariant; typedef SharedPtr<IndexDataVariant> IndexDataVariantSharedPtr; class IndexDataVariant { private: HardwareIndexBufferSharedPtr mBuffer; unsigned char* mBaseDataPointer; unsigned char* mCurDataPointer; size_t mIndexCount; size_t mOffsetSize; bool mUse32bitIndexes; std::auto_ptr<IndexBufferLockGuard> mLockGuard; IndexDataVariant(const IndexData * indexData, HardwareBuffer::LockOptions lockOpt) : mIndexCount(0) , mOffsetSize(0) , mUse32bitIndexes(false) { static int fakeIndexBuffer = 0; // 4 bytes, can be safely used with zero mOffsetSize mBaseDataPointer = mCurDataPointer = (unsigned char*)&fakeIndexBuffer; if(NULL == indexData) return; mBuffer = indexData->indexBuffer; if(mBuffer.isNull()) return; mIndexCount = indexData->indexCount; if(0 == mIndexCount) return; mUse32bitIndexes = (mBuffer->getType() == HardwareIndexBuffer::IT_32BIT); mOffsetSize = mUse32bitIndexes ? sizeof(unsigned int) : sizeof(unsigned short); mLockGuard.reset(new IndexBufferLockGuard(mBuffer, lockOpt)); mBaseDataPointer = (unsigned char*)mLockGuard->pData; reset(); } bool isValid() const { return mOffsetSize != 0; } public: static IndexDataVariantSharedPtr create(const IndexData * indexData, HardwareBuffer::LockOptions lockOpt = HardwareBuffer::HBL_READ_ONLY) { IndexDataVariantSharedPtr p(new IndexDataVariant(indexData, lockOpt)); return p->isValid() ? p : IndexDataVariantSharedPtr(); } unsigned char* getBaseDataPointer() const { return mBaseDataPointer; } unsigned char* getCurDataPointer() const { return mCurDataPointer; } size_t getOffsetSize() const { return mOffsetSize; } size_t getIndexCount() const { return mIndexCount; } bool is32bitIndexes() const { return mUse32bitIndexes; } void reset() { mCurDataPointer = mBaseDataPointer; } void offsetToElement(int itemIndex) { mCurDataPointer = getBaseDataPointer() + itemIndex * getOffsetSize(); } unsigned getNextIndex() { unsigned idx = mUse32bitIndexes ? *(unsigned int*)mCurDataPointer : *(unsigned short*)mCurDataPointer; mCurDataPointer += mOffsetSize; return idx; } void markUsedVertices(BitArray& bitmask) const { if(mUse32bitIndexes) { for(const unsigned int *ptr = (const unsigned int*)mBaseDataPointer, *end_ptr = ptr + mIndexCount; ptr < end_ptr; ++ptr) bitmask.setBit(*ptr); } else { for(const unsigned short *ptr = (const unsigned short*)mBaseDataPointer, *end_ptr = ptr + mIndexCount; ptr < end_ptr; ++ptr) bitmask.setBit(*ptr); } } void createIndexData(IndexData* pIndexData, bool use16bitIndexes, vector<unsigned>::type* indexMap) { size_t indexCount = getIndexCount(); reset(); pIndexData->indexStart = 0; pIndexData->indexCount = indexCount; pIndexData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( use16bitIndexes ? HardwareIndexBuffer::IT_16BIT : HardwareIndexBuffer::IT_32BIT, indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY); IndexBufferLockGuard outIdataLock(pIndexData->indexBuffer, HardwareBuffer::HBL_DISCARD); unsigned short* pShortOut = use16bitIndexes ? (unsigned short*)outIdataLock.pData : NULL; unsigned int* pIntOut = use16bitIndexes ? NULL : (unsigned int*)outIdataLock.pData; if(use16bitIndexes) { for(size_t n = 0; n < indexCount; ++n) { unsigned idx = getNextIndex(); *pShortOut++ = indexMap ? (*indexMap)[idx] : idx; } } else { for(size_t n = 0; n < indexCount; ++n) { unsigned idx = getNextIndex(); *pIntOut++ = indexMap ? (*indexMap)[idx] : idx; } } } }; //--------------------------------------------------------------------- ProgressiveMesh::ProgressiveMesh(SubMesh* pSubMesh) : mSubMesh(pSubMesh) , mCurrNumIndexes(0) , mVertexComponentFlags(0) { // ignore un-indexed submeshes if(pSubMesh->indexData->indexCount == 0) { mSubMesh = NULL; return; } Ogre::Mesh* pMesh = pSubMesh->parent; Real sqrDiag = pMesh->getBounds().getSize().squaredLength(); mInvSquaredBoundBoxDiagonal = ((Real)0.0 != sqrDiag) ? (Real)1.0 / sqrDiag : (Real)0.0; mNextWorstCostHint = 0; mInvalidCostCount = 0; mRemovedVertexDuplicatesCount = 0; mVertexData = pSubMesh->useSharedVertices ? pMesh->sharedVertexData : pSubMesh->vertexData; mIndexData = pSubMesh->indexData; mInvalidCostMask.resize(mVertexData->vertexCount); addWorkingData(mVertexData, mIndexData); } //--------------------------------------------------------------------- ProgressiveMesh::~ProgressiveMesh() { } //--------------------------------------------------------------------- void ProgressiveMesh::addExtraVertexPositionBuffer(const VertexData* vertexData) { addWorkingData(vertexData, mIndexData); } //--------------------------------------------------------------------- void ProgressiveMesh::initializeProgressiveMeshList(ProgressiveMeshList& pmList, Mesh* pMesh) { size_t subMeshCount = pMesh->getNumSubMeshes(); pmList.reserve(subMeshCount); for(size_t i = 0; i < subMeshCount; ++i) { SubMesh* pSubMesh = pMesh->getSubMesh(i); pmList.push_back(OGRE_NEW ProgressiveMesh(pSubMesh)); } } //--------------------------------------------------------------------- void ProgressiveMesh::freeProgressiveMeshList(ProgressiveMeshList* pmList) { for(ProgressiveMeshList::iterator it = pmList->begin(); it != pmList->end(); ++it) { OGRE_DELETE *it; *it = NULL; } } //--------------------------------------------------------------------- bool ProgressiveMesh::generateLodLevels(Mesh* pMesh, const LodValueList& lodValues, VertexReductionQuota reductionMethod, Real reductionValue) { #if OGRE_DEBUG_MODE pMesh->getLodStrategy()->assertSorted(lodValues); #endif pMesh->removeLodLevels(); LogManager::getSingleton().stream() << "Generating " << lodValues.size() << " lower LODs for mesh " << pMesh->getName(); // Set up data for reduction ProgressiveMeshList pmList; initializeProgressiveMeshList(pmList, pMesh); bool generated = build(pmList, pMesh->getLodStrategy(), lodValues, reductionMethod, reductionValue); if(generated) { // transfer all LODs from ProgressiveMesh to the real one size_t subMeshCount = pMesh->getNumSubMeshes(); for(size_t i = 0; i < subMeshCount; ++i) pMesh->getSubMesh(i)->mLodFaceList.swap(pmList[i]->mLodFaceList); // register them LodStrategy *lodStrategy = LodStrategyManager::getSingleton().getStrategy(pMesh->getLodStrategy()->getName()); bakeLodUsage(pMesh, lodStrategy, lodValues, false); } freeProgressiveMeshList(&pmList); return generated; } //--------------------------------------------------------------------- MeshPtr ProgressiveMesh::generateSimplifiedMesh(const String& name, const String& groupName, Mesh* inMesh, bool dropOriginalGeometry, const LodValueList& lodValues, VertexReductionQuota reductionMethod, Real reductionValue, size_t* removedVertexDuplicatesCount) { #if OGRE_DEBUG_MODE inMesh->getLodStrategy()->assertSorted(lodValues); #endif LogManager::getSingleton().stream() << "Generating simplified mesh " << name << " for mesh " << inMesh->getName(); // Set up data for reduction ProgressiveMeshList pmList; initializeProgressiveMeshList(pmList, inMesh); // Perform reduction build(pmList, inMesh->getLodStrategy(), lodValues, reductionMethod, reductionValue); // Bake new simplified mesh MeshPtr simplifiedMesh = MeshManager::getSingleton().createManual(name, groupName); bakeSimplifiedMesh(simplifiedMesh.get(), inMesh, pmList, dropOriginalGeometry); LodStrategy *lodStrategy = LodStrategyManager::getSingleton().getStrategy(inMesh->getLodStrategy()->getName()); bakeLodUsage(simplifiedMesh.get(), lodStrategy, lodValues, dropOriginalGeometry); // Return some statistic if(removedVertexDuplicatesCount) { size_t duplicatesCount = 0; for(ProgressiveMeshList::iterator it = pmList.begin(); it != pmList.end(); ++it) duplicatesCount += (*it)->mRemovedVertexDuplicatesCount; *removedVertexDuplicatesCount = duplicatesCount; } freeProgressiveMeshList(&pmList); return simplifiedMesh; } //--------------------------------------------------------------------- bool ProgressiveMesh::build(ProgressiveMeshList& pmInList, const LodStrategy *lodStrategy, const LodValueList& lodValues, VertexReductionQuota quota, Real reductionValue) { assert(!pmInList.empty()); bool generated = false; size_t numVerts = 0; ProgressiveMeshList pmBuildList; for(ProgressiveMeshList::iterator i = pmInList.begin(); i != pmInList.end(); ++i) { ProgressiveMesh* p = *i; if(NULL == p->mSubMesh) continue; // dummy, skip it p->computeAllCosts(); // Init p->mCurrNumIndexes = (Ogre::RenderOperation::OT_TRIANGLE_LIST == p->mSubMesh->operationType) ? p->mIndexData->indexCount : (p->mIndexData->indexCount - 2) * 3; #if LOG_PROGRESSIVE_MESH_GENERATION StringUtil::StrStreamType logname; logname << "pm_before_" << std::distance(pmInList.begin(), i) << ".log"; (*i)->dumpContents(logname.str()); #endif numVerts += p->mWorstCostsSize; pmBuildList.push_back(p); } ProgressiveMeshList pmList(pmBuildList); // if any one of this two checks is failed - we complete one LOD generation size_t numCollapses = numVerts; // unlimited Real costLimit = NEVER_COLLAPSE_COST; // unlimited bool abandon = false; for (LodValueList::const_iterator lod = lodValues.begin(); lod != lodValues.end(); ++lod) { int level = std::distance(lodValues.begin(), lod); // adjust LOD target limits switch(quota) { case VRQ_CONSTANT: numCollapses = static_cast<size_t>(reductionValue); break; case VRQ_PROPORTIONAL: numCollapses = static_cast<size_t>(numVerts * reductionValue); numVerts -= numCollapses; break; case VRQ_ERROR_COST: // we must increase cost limit with each next lod level proportionally to squared distance ratio or inverted pixel area ratio Real reductionValueMultiplier = lodStrategy->transformBias(lodStrategy->transformUserValue(lodValues[0]) / lodStrategy->transformUserValue(lodValues[level])); assert(level == 0 || reductionValueMultiplier > 1.0); costLimit = reductionValue * reductionValueMultiplier; break; } // NB if 'abandon' is set, we stop reducing // However, we still bake the number of LODs requested, even if it // means they are the same while(numCollapses > 0 && !abandon) { ProgressiveMesh* pmCur; //out CostIndexPair* collapseTarget; // out getNextCollapser(pmList, pmCur, collapseTarget); // we found collapse target, but may be we must not collapse it if(collapseTarget != NULL) { assert(collapseTarget->first != NEVER_COLLAPSE_COST); if(VRQ_ERROR_COST == quota) { Real cost = collapseTarget->first; if(cost > costLimit) collapseTarget = NULL; } else // VRQ_CONSTANT, VRQ_PROPORTIONAL { if(getInvalidCostCount(pmList) >= numCollapses) collapseTarget = NULL; // need recalc } } // if we have not collapse target but have invalid costs - recalc them if(collapseTarget == NULL) { if(recomputeInvalidCosts(pmList)) { // a some invalid costs was recomputed and we should try to continue collapsing // because the recomputed best cost can be less than level limit; continue; } else { abandon = pmList.empty(); break; // an invalid costs is not found and we complete collapsing for the current LOD } } // OK, we decide to collapse this target assert(collapseTarget); assert(pmCur); assert(numCollapses > 0); // Collapse on every buffer WorkingDataList::iterator idata, idataend; idataend = pmCur->mWorkingData.end(); for (idata = pmCur->mWorkingData.begin(); idata != idataend; ++idata) { PMVertex* collapser = &(idata->mVertList[collapseTarget->second]); if(collapser->face.size() == pmCur->mCurrNumIndexes / 3 || collapser->collapseTo == NULL) { // Must have run out of valid collapsables pmList.erase(std::remove(pmList.begin(), pmList.end(), pmCur), pmList.end()); abandon = pmList.empty(); break; } #if LOG_PROGRESSIVE_MESH_GENERATION ofdebug << "Collapsing index " << (unsigned int)collapser->index << "(border: "<< (collapser->mBorderStatus == PMVertex::BS_BORDER ? "yes" : "no") << ") to " << (unsigned int)collapser->collapseTo->index << "(border: "<< (collapser->collapseTo->mBorderStatus == PMVertex::BS_BORDER ? "yes" : "no") << ")" << std::endl; #endif assert(collapser->collapseTo->removed == false); assert(pmCur->mCurrNumIndexes > 0); pmCur->collapse(collapser); assert(pmCur->mCurrNumIndexes > 0); } // we must never return to it collapseTarget->first = NEVER_COLLAPSE_COST; --numCollapses; } // end of one LOD collapsing loop // Bake a new LOD and add it to the list for(ProgressiveMeshList::iterator i = pmBuildList.begin(); i != pmBuildList.end(); ++i) { ProgressiveMesh* p = *i; assert(NULL != p->mSubMesh); //dummy can't happen here #if LOG_PROGRESSIVE_MESH_GENERATION StringUtil::StrStreamType logname; ProgressiveMeshList::iterator t = std::find(pmInList.begin(), pmInList.end(), p); assert(t != pmInList.end()); logname << "pm_" << std::distance(pmInList.begin(), t) << "__level_" << level << ".log"; (*i)->dumpContents(logname.str()); #endif IndexData* lodData = NULL; if(p->mCurrNumIndexes != p->mIndexData->indexCount) { assert(p->mCurrNumIndexes > 0); lodData = OGRE_NEW IndexData(); p->bakeNewLOD(lodData); generated = true; } else { p->mRemovedVertexDuplicatesCount = 0; lodData = p->mSubMesh->indexData->clone(); } assert(NULL != lodData); p->mLodFaceList.push_back(lodData); } } return generated; } //--------------------------------------------------------------------- void ProgressiveMesh::addWorkingData(const VertexData * vertexData, const IndexData * indexData) { if(0 == vertexData->vertexCount || 0 == indexData->indexCount) return; // Insert blank working data, then fill mWorkingData.push_back(PMWorkingData()); PMWorkingData& work = mWorkingData.back(); // Build vertex list // Resize face list (this will always be this big) work.mFaceVertList.resize(vertexData->vertexCount); // Also resize common vert list to max, to avoid reallocations work.mVertList.resize(vertexData->vertexCount); VertexDataVariantList vdVariantList; VertexDataVariant* vertexDataBuffer = vdVariantList.create(vertexData, VES_POSITION); VertexDataVariant* normalDataBuffer = vdVariantList.create(vertexData, VES_NORMAL); VertexDataVariant* uvDataBuffer = vdVariantList.create(vertexData, VES_TEXTURE_COORDINATES); mVertexComponentFlags |= (1 << VES_POSITION); mVertexComponentFlags |= (1 << VES_NORMAL); mVertexComponentFlags |= (1 << VES_TEXTURE_COORDINATES); IndexDataVariantSharedPtr indexDataVar(IndexDataVariant::create(indexData)); if(indexDataVar.isNull()) return; //make used index list BitArray usedVertices(vertexData->vertexCount); indexDataVar->markUsedVertices(usedVertices); mWorstCostsSize = usedVertices.getBitsCount(); mWorstCosts.resize(mWorstCostsSize); PMVertex* vBase = &work.mVertList.front(); WorstCostList::iterator it = mWorstCosts.begin(); bool someVerticesWasSkipped = false; for(unsigned idx = 0, end_idx = vertexData->vertexCount; idx < end_idx; ++idx) { // skip unused vertices if(!usedVertices.getBit(idx)) { someVerticesWasSkipped = true; continue; } // resync vertex data offset if some vertices was skipped if(someVerticesWasSkipped) { someVerticesWasSkipped = false; vertexDataBuffer->offsetToElement(idx); normalDataBuffer->offsetToElement(idx); uvDataBuffer->offsetToElement(idx); } // store reference to used vertex it->first = 0.0f; it->second = idx; ++it; // read vertex data PMVertex* commonVert = vBase + idx; commonVert->setDetails(idx, vertexDataBuffer->getNextVector3(), normalDataBuffer->getNextVector3(), uvDataBuffer->getNextVector2()); } // Build tri list size_t numTris = (Ogre::RenderOperation::OT_TRIANGLE_LIST == mSubMesh->operationType) ? mIndexData->indexCount / 3 : mIndexData->indexCount - 2; work.mTriList.reserve(numTris); // reserved tri list PMFaceVertex* fvBase = &work.mFaceVertList.front(); if(Ogre::RenderOperation::OT_TRIANGLE_LIST == mSubMesh->operationType) { for (size_t i = 0, vi = 0; i < numTris; ++i) { unsigned int vindex; PMFaceVertex *v0, *v1, *v2; vindex = indexDataVar->getNextIndex(); v0 = fvBase + vindex; v0->commonVertex = vBase + vindex; v0->realIndex = vindex; vindex = indexDataVar->getNextIndex(); v1 = fvBase + vindex; v1->commonVertex = vBase + vindex; v1->realIndex = vindex; vindex = indexDataVar->getNextIndex(); v2 = fvBase + vindex; v2->commonVertex = vBase + vindex; v2->realIndex = vindex; if(v0!=v1 && v1!=v2 && v2!=v0) // see assertion: OgreProgressiveMesh.cpp, line: 723, condition: v0!=v1 && v1!=v2 && v2!=v0 { work.mTriList.push_back(PMTriangle()); work.mTriList.back().setDetails(vi++, v0, v1, v2); } } } else if(Ogre::RenderOperation::OT_TRIANGLE_STRIP == mSubMesh->operationType) { bool tSign = true; for (size_t i = 0, vi = 0; i < numTris; ++i) { unsigned int vindex; PMFaceVertex *v0, *v1, *v2; indexDataVar->offsetToElement(i); vindex = indexDataVar->getNextIndex(); v0 = fvBase + vindex; v0->commonVertex = vBase + vindex; v0->realIndex = vindex; vindex = indexDataVar->getNextIndex(); v1 = fvBase + vindex; v1->commonVertex = vBase + vindex; v1->realIndex = vindex; vindex = indexDataVar->getNextIndex(); v2 = fvBase + vindex; v2->commonVertex = vBase + vindex; v2->realIndex = vindex; if(v0!=v1 && v1!=v2 && v2!=v0) // see assertion: OgreProgressiveMesh.cpp, line: 723, condition: v0!=v1 && v1!=v2 && v2!=v0 { work.mTriList.push_back(PMTriangle()); work.mTriList.back().setDetails(vi++, tSign ? v0 : v1, tSign ? v1 : v0, v2); } tSign = !tSign; } } else //FAN { for (size_t i = 0, vi = 0; i < numTris; ++i) { unsigned int vindex; PMFaceVertex *v0, *v1, *v2; indexDataVar->offsetToElement(0); vindex = indexDataVar->getNextIndex(); v0 = fvBase + vindex; v0->commonVertex = vBase + vindex; v0->realIndex = vindex; indexDataVar->offsetToElement(i); vindex = indexDataVar->getNextIndex(); v1 = fvBase + vindex; v1->commonVertex = vBase + vindex; v1->realIndex = vindex; vindex = indexDataVar->getNextIndex(); v2 = fvBase + vindex; v2->commonVertex = vBase + vindex; v2->realIndex = vindex; if(v0!=v1 && v1!=v2 && v2!=v0) // see assertion: OgreProgressiveMesh.cpp, line: 723, condition: v0!=v1 && v1!=v2 && v2!=v0 { work.mTriList.push_back(PMTriangle()); work.mTriList.back().setDetails(vi++, v0, v1, v2); } } } indexDataVar.setNull(); // try to merge borders, to increase algorithm effectiveness mergeWorkingDataBorders(); } /** Comparator for unique vertex list */ struct ProgressiveMesh::vertexLess { bool operator()(PMVertex* v1, PMVertex* v2) const { if (v1->position.x < v2->position.x) return true; else if(v1->position.x > v2->position.x) return false; if (v1->position.y < v2->position.y) return true; else if(v1->position.y > v2->position.y) return false; if (v1->position.z < v2->position.z) return true; else if(v1->position.z > v2->position.z) return false; if (v1->normal.x < v2->normal.x) return true; else if(v1->normal.x > v2->normal.x) return false; if (v1->normal.y < v2->normal.y) return true; else if(v1->normal.y > v2->normal.y) return false; if (v1->normal.z < v2->normal.z) return true; else if(v1->normal.z > v2->normal.z) return false; if (v1->uv.x < v2->uv.x) return true; else if(v1->uv.x > v2->uv.x) return false; if (v1->uv.y < v2->uv.y) return true; else if(v1->uv.y > v2->uv.y) return false; return false; } }; void ProgressiveMesh::mergeWorkingDataBorders() { IndexDataVariantSharedPtr indexDataVar(IndexDataVariant::create(mIndexData)); if(indexDataVar.isNull()) return; PMWorkingData& work = mWorkingData.back(); typedef std::map<PMVertex*, size_t, vertexLess> CommonVertexMap; CommonVertexMap commonBorderVertexMap; std::map<unsigned int /* original index */, unsigned int /* new index (after merge) */> mappedIndexes; // try to merge borders to borders WorstCostList newUniqueIndexes; // we will use border status from first buffer only - is this right? PMVertex* vBase = &work.mVertList.front(); // iterate over used vertices for(WorstCostList::iterator it = mWorstCosts.begin(), end_it = mWorstCosts.end(); it != end_it; ++it) { unsigned idx = it->second; PMVertex* v = vBase + idx; v->initBorderStatus(); CommonVertexMap::iterator iCommonBorderVertex = commonBorderVertexMap.end(); if(PMVertex::BS_BORDER == v->mBorderStatus) { //vertex is a border, try to find it in the common border vertex map at first iCommonBorderVertex = commonBorderVertexMap.find(v); // if found but not near enough - ignore it if(iCommonBorderVertex != commonBorderVertexMap.end() && !iCommonBorderVertex->first->isNearEnough(v)) iCommonBorderVertex = commonBorderVertexMap.end(); } //if vertex is not found in the common border vertex map if(iCommonBorderVertex == commonBorderVertexMap.end()) { if(PMVertex::BS_BORDER == v->mBorderStatus) commonBorderVertexMap.insert(CommonVertexMap::value_type(v, idx)); mappedIndexes[idx] = idx; // old and new indexes should be equal newUniqueIndexes.push_back(*it); // update common unique index list } else // merge vertices { // vertex is found in the common border vertex map // the triangles will use [iCommonBorderVertex->second] instead of [*idx] mappedIndexes[idx] = iCommonBorderVertex->second; // set border status for the founded vertex as BF_UNKNOWN // (the border status will reinitialized at the end of function since we mark it as not defined) iCommonBorderVertex->first->mBorderStatus = PMVertex::BS_UNKNOWN; ++mRemovedVertexDuplicatesCount; } //the neighbor & face must be cleaned now (it will be recreated after merging) v->neighbor.clear(); v->face.clear(); } // Rebuild tri list by mapped indexes size_t numTris = (Ogre::RenderOperation::OT_TRIANGLE_LIST == mSubMesh->operationType) ? mIndexData->indexCount / 3 : mIndexData->indexCount - 2; work.mTriList.clear(); work.mTriList.reserve(numTris); // reserved tri list PMFaceVertex* fvBase = &work.mFaceVertList.front(); if(Ogre::RenderOperation::OT_TRIANGLE_LIST == mSubMesh->operationType) { for (size_t i = 0, vi = 0; i < numTris; ++i) { unsigned int vindex; PMFaceVertex *v0, *v1, *v2; vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v0 = fvBase + vindex; v0->commonVertex = vBase + vindex; v0->realIndex = vindex; vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v1 = fvBase + vindex; v1->commonVertex = vBase + vindex; v1->realIndex = vindex; vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v2 = fvBase + vindex; v2->commonVertex = vBase + vindex; v2->realIndex = vindex; if(v0!=v1 && v1!=v2 && v2!=v0) // see assertion: OgreProgressiveMesh.cpp, line: 723, condition: v0!=v1 && v1!=v2 && v2!=v0 { work.mTriList.push_back(PMTriangle()); work.mTriList.back().setDetails(vi++, v0, v1, v2); } } } else if(Ogre::RenderOperation::OT_TRIANGLE_STRIP == mSubMesh->operationType) { bool tSign = true; for (size_t i = 0, vi = 0; i < numTris; ++i) { unsigned int vindex; PMFaceVertex *v0, *v1, *v2; indexDataVar->offsetToElement(i); vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v0 = fvBase + vindex; v0->commonVertex = vBase + vindex; v0->realIndex = vindex; vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v1 = fvBase + vindex; v1->commonVertex = vBase + vindex; v1->realIndex = vindex; vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v2 = fvBase + vindex; v2->commonVertex = vBase + vindex; v2->realIndex = vindex; if(v0!=v1 && v1!=v2 && v2!=v0) // see assertion: OgreProgressiveMesh.cpp, line: 723, condition: v0!=v1 && v1!=v2 && v2!=v0 { work.mTriList.push_back(PMTriangle()); work.mTriList.back().setDetails(vi++, tSign ? v0 : v1, tSign ? v1 : v0, v2); } tSign = !tSign; } } else //FAN { for (size_t i = 0, vi = 0; i < numTris; ++i) { unsigned int vindex; PMFaceVertex *v0, *v1, *v2; indexDataVar->offsetToElement(0); vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v0 = fvBase + vindex; v0->commonVertex = vBase + vindex; v0->realIndex = vindex; indexDataVar->offsetToElement(i); vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v1 = fvBase + vindex; v1->commonVertex = vBase + vindex; v1->realIndex = vindex; vindex = indexDataVar->getNextIndex(); //get original index from the index buffer vindex = mappedIndexes[vindex]; //vindex will replaced if needed v2 = fvBase + vindex; v2->commonVertex = vBase + vindex; v2->realIndex = vindex; if(v0!=v1 && v1!=v2 && v2!=v0) // see assertion: OgreProgressiveMesh.cpp, line: 723, condition: v0!=v1 && v1!=v2 && v2!=v0 { work.mTriList.push_back(PMTriangle()); work.mTriList.back().setDetails(vi++, v0, v1, v2); } } } //update the common unique index list (it should be less than before merge) mWorstCosts = newUniqueIndexes; mWorstCostsSize = mWorstCosts.size(); for(WorstCostList::iterator it = mWorstCosts.begin(), end_it = mWorstCosts.end(); it != end_it; ++it) { PMVertex* v = vBase + it->second; if(PMVertex::BS_UNKNOWN == v->mBorderStatus) v->initBorderStatus(); if(0 == (mVertexComponentFlags & (1 << VES_NORMAL))) v->calculateNormal(); #ifdef CHECK_CALCULATED_NORMALS else { Vector3 savedNormal = v->normal; v->calculateNormal(); assert(v->normal.dotProduct(savedNormal.normalisedCopy()) > 0.5f); v->normal = savedNormal(); } #endif } } //--------------------------------------------------------------------- bool ProgressiveMesh::collapseInvertsNormals(PMVertex *src, PMVertex *dest) const { // Degenerate case check // Are we going to invert a face normal of one of the neighbouring faces? // Can occur when we have a very small remaining edge and collapse crosses it // Look for a face normal changing by > 90 degrees for(PMVertex::FaceList::iterator srcface = src->face.begin(), srcfaceend = src->face.end(); srcface != srcfaceend; ++srcface) { // Ignore the deleted faces (those including src & dest) if( !(*srcface)->hasCommonVertex(dest) ) { // Test the new face normal PMVertex *v0, *v1, *v2; // Replace src with dest wherever it is v0 = ( (*srcface)->vertex[0]->commonVertex == src) ? dest : (*srcface)->vertex[0]->commonVertex; v1 = ( (*srcface)->vertex[1]->commonVertex == src) ? dest : (*srcface)->vertex[1]->commonVertex; v2 = ( (*srcface)->vertex[2]->commonVertex == src) ? dest : (*srcface)->vertex[2]->commonVertex; // Cross-product 2 edges Vector3 e1 = v1->position - v0->position; Vector3 e2 = v2->position - v1->position; Vector3 newNormal = e1.crossProduct(e2); // Dot old and new face normal // If < 0 then more than 90 degree difference if (newNormal.dotProduct( (*srcface)->normal ) < 0.0f ) return true; } } return false; } //--------------------------------------------------------------------- Real ProgressiveMesh::computeEdgeCollapseCost(PMVertex *src, PMVertex *dest) const { // if we collapse edge uv by moving src to dest then how // much different will the model change, i.e. how much "error". // The method of determining cost was designed in order // to exploit small and coplanar regions for // effective polygon reduction. Vector3 edgeVector = src->position - dest->position; Real cost; PMVertex::FaceList::iterator srcfacebegin = src->face.begin(); PMVertex::FaceList::iterator srcfaceend = src->face.end(); // find the "sides" triangles that are on the edge uv PMVertex::FaceList& sides = mEdgeAdjacentSides; sides.clear(); // Iterate over src's faces and find 'sides' of the shared edge which is being collapsed PMVertex::FaceList::iterator sidesEnd = sides.end(); for(PMVertex::FaceList::iterator it = srcfacebegin; it != srcfaceend; ++it) { // Check if this tri also has dest in it (shared edge) PMTriangle* srcface = *it; if(srcface->hasCommonVertex(dest) && sidesEnd == std::find(sides.begin(), sidesEnd, srcface)) { sides.push_back(srcface); sidesEnd = sides.end(); } } // Special cases // If we're looking at a border vertex if(PMVertex::BS_BORDER == src->mBorderStatus) { // Check for singular triangle destruction if (src->face.size() == 1 && dest->face.size() == 1) { // If src and dest both only have 1 triangle (and it must be a shared one) // then this would destroy the shape, so don't do this return NEVER_COLLAPSE_COST; } else if(collapseInvertsNormals(src, dest)) { // border edge collapse must not invert normals of neighbor faces return NEVER_COLLAPSE_COST; } else if (sides.size() > 1) { // src is on a border, but the src-dest edge has more than one tri on it // So it must be collapsing inwards // Mark as very high-value cost cost = 1.0f + sides.size() * sides.size() * edgeVector.squaredLength() * mInvSquaredBoundBoxDiagonal; } else { // Collapsing ALONG a border // We can't use curvature to measure the effect on the model // Instead, see what effect it has on 'pulling' the other border edges // The more colinear, the less effect it will have // So measure the delta triangle area // Normally there can be at most 1 other border edge attached to this // However in weird cases there may be more, so find the worst Vector3 otherBorderEdge; Real kinkiness, maxKinkiness; // holds squared parallelogram area maxKinkiness = 0.0f; for (PMVertex::NeighborList::iterator n = src->neighbor.begin(), nend = src->neighbor.end(); n != nend; ++n) { PMVertex* third = *n; if (third != dest && src->isManifoldEdgeWith(third)) { otherBorderEdge = src->position - third->position; kinkiness = otherBorderEdge.crossProduct(edgeVector).squaredLength(); // doubled triangle area maxKinkiness = std::max(kinkiness, maxKinkiness); } } cost = 0.5f * Math::Sqrt(maxKinkiness) * mInvSquaredBoundBoxDiagonal; // cost is equal to normalized triangle area } } else // not a border { if(collapseInvertsNormals(src, dest)) { // border edge collapse must not invert normals of neighbor faces return NEVER_COLLAPSE_COST; } // each neighbour face sweep some tetrahedron duaring collapsing, we will try to minimize sum of their side areas // benefit of this metric is that it`s zero on any ridge, if collapsing along it // V = H * S / 3 Real tripleVolumeSum = 0.0; Real areaSum = 0.0; for(PMVertex::FaceList::iterator srcface = srcfacebegin; srcface != srcfaceend; ++srcface) { PMTriangle* t = *srcface; tripleVolumeSum += Math::Abs(t->normal.dotProduct(edgeVector)) * t->area; areaSum += t->area; } // visible error is tetrahedron side area, so taking A = sqrt(S) we use such approximation // E = H * sqrt(S) / 2 (side triangle area) // and since H = 3 * V / S (pyramid volume) // E = 3 * V / (2 * sqrt(S)) cost = areaSum > (Real)1e-06 ? tripleVolumeSum / ((Real)2.0 * Math::Sqrt(areaSum)) * mInvSquaredBoundBoxDiagonal : (Real)0.0; } // take into consideration texture coordinates and normal direction if(mVertexComponentFlags & (1 << VES_NORMAL)) { float uvCost = 1.0f, normalCost = 1.0f; for(PMVertex::NeighborList::iterator ni = src->neighbor.begin(), nend = src->neighbor.end(); ni != nend; ++ni) { PMVertex* v0 = *ni; PMVertex::NeighborList::iterator inext = ni + 1; PMVertex* v1 = (inext != nend) ? *inext : src->neighbor.front(); // next or first Vector3 en(v0->position - dest->position); Vector3 en1(v1->position - dest->position); if(en == Vector3::ZERO || en1 == Vector3::ZERO || v0 == v1) continue; //skip collapser // get first plane Plane p(src->normal.crossProduct(en), dest->position); // get second plane Plane p1(src->normal.crossProduct(en1), dest->position); Real pDistance = p.getDistance(src->position); Real p1Distance = p1.getDistance(src->position); if((pDistance > 0.0f && p1Distance > 0.0f) || (pDistance < 0.0f && p1Distance < 0.0f)) continue; //collapser NOT between two planes //calculate barycentric coordinates (b1, b2, b3) Real& h1 = pDistance; Real H1 = p.getDistance(v1->position); Real b1 = h1 / H1; Real& h2 = p1Distance; Real H2 = p1.getDistance(v0->position); Real b2 = h2 / H2; Real b3 = 1.0f - b1 - b2; if(b1 < 0.0f || b2 < 0.0f || b3 < 0.0f) continue; //three points: dest, *i, v1 if(mVertexComponentFlags & (1 << VES_TEXTURE_COORDINATES)) { Vector2 newUV = v1->uv * b1 + v0->uv * b2 + dest->uv * b3; uvCost = std::max(Real(1.0f), (newUV - src->uv).squaredLength()); } Vector3 newNormal = (b1 * v1->normal + b2 * v0->normal + b3 * dest->normal).normalisedCopy(); normalCost = std::max(Real(0.0f), 0.5f - 0.5f * newNormal.dotProduct(src->normal)); assert(cost >= 0.0f && uvCost >= 0.0f && normalCost >= 0.0f); break; } #ifdef IGNORE_UV_AND_NORMAL_COSTS uvCost = normalCost = 0.0f; #endif const static float posWeight = 10.0f; const static float normWeight = 1.0f; const static float texWeight = 1.0f; const static float invSumWeight = 1.0f / (posWeight + normWeight + texWeight); cost = invSumWeight * (posWeight * cost + texWeight * uvCost + normWeight * normalCost); } assert (cost >= 0); return cost; } //--------------------------------------------------------------------- void ProgressiveMesh::initialiseEdgeCollapseCosts(void) { for(WorkingDataList::iterator i = mWorkingData.begin(), iend = mWorkingData.end(); i != iend; ++i) { PMVertex* vFront = &i->mVertList.front(); for(WorstCostList::iterator it = mWorstCosts.begin(), end_it = mWorstCosts.end(); it != end_it; ++it) { PMVertex* v = vFront + it->second; v->collapseTo = NULL; v->collapseCost = NEVER_COLLAPSE_COST; } } } //--------------------------------------------------------------------- Real ProgressiveMesh::computeEdgeCostAtVertexForBuffer(PMVertex* v) { // compute the edge collapse cost for all edges that start // from vertex v. Since we are only interested in reducing // the object by selecting the min cost edge at each step, we // only cache the cost of the least cost edge at this vertex // (in member variable collapse) as well as the value of the // cost (in member variable objdist). if(v->neighbor.empty()) { // v doesn't have neighbors so nothing to collapse v->notifyRemoved(); return v->collapseCost; } // Init metrics Real collapseCost = NEVER_COLLAPSE_COST; PMVertex* collapseTo = NULL; // search all neighboring edges for "least cost" edge for(PMVertex **n = &v->neighbor.front(), **nend = n + v->neighbor.size(); n != nend; ++n) { PMVertex* candidate = *n; Real cost = computeEdgeCollapseCost(v, candidate); if( (!collapseTo) || cost < collapseCost) { collapseTo = candidate; // candidate for edge collapse collapseCost = cost; // cost of the collapse } } v->collapseCost = collapseCost; v->collapseTo = collapseTo; return collapseCost; } //--------------------------------------------------------------------- void ProgressiveMesh::computeAllCosts(void) { initialiseEdgeCollapseCosts(); assert(!mWorstCosts.empty()); for(WorstCostList::iterator it = mWorstCosts.begin(), end_it = mWorstCosts.end(); it != end_it; ++it) it->first = computeEdgeCostAtVertex(it->second); sortIndexesByCost(); } //--------------------------------------------------------------------- void ProgressiveMesh::collapse(ProgressiveMesh::PMVertex *src) { PMVertex *dest = src->collapseTo; if(PMVertex::BS_BORDER == src->mBorderStatus) dest->mBorderStatus = PMVertex::BS_BORDER; // Abort if we're never supposed to collapse if (src->collapseCost == NEVER_COLLAPSE_COST) return; // Remove this vertex from the running for the next check src->collapseTo = NULL; src->collapseCost = NEVER_COLLAPSE_COST; // Collapse the edge uv by moving vertex u onto v // Actually remove tris on uv, then update tris that // have u to have v, and then remove u. if(!dest) { // src is a vertex all by itself #if LOG_PROGRESSIVE_MESH_GENERATION ofdebug << "Aborting collapse, orphan vertex. " << std::endl; #endif return; } // Add dest and all the neighbours of source and dest to recompute list typedef vector<PMVertex*>::type RecomputeSet; RecomputeSet recomputeSet; recomputeSet.reserve(1 + src->neighbor.size() + dest->neighbor.size()); recomputeSet.push_back(dest); recomputeSet.insert(recomputeSet.end(), src->neighbor.begin(), src->neighbor.end()); recomputeSet.insert(recomputeSet.end(), dest->neighbor.begin(), dest->neighbor.end()); // delete triangles on edge src-dest // Notify others to replace src with dest // Queue of faces for removal / replacement // prevents us screwing up the iterators while we parse PMVertex::FaceList faceRemovalList, faceReplacementList; for(PMVertex::FaceList::iterator f = src->face.begin(), fend = src->face.end(); f != fend; ++f) { if((*f)->hasCommonVertex(dest)) { // Tri is on src-dest therefore is gone if(faceRemovalList.end() == std::find(faceRemovalList.begin(), faceRemovalList.end(), *f)) faceRemovalList.push_back(*f); // Reduce index count by 3 (useful for quick allocation later) mCurrNumIndexes -= 3; } else { // Only src involved, replace with dest if(faceReplacementList.end() == std::find(faceReplacementList.begin(), faceReplacementList.end(), *f)) faceReplacementList.push_back(*f); } } src->toBeRemoved = true; // Replace all the faces queued for replacement for(PMVertex::FaceList::iterator f = faceReplacementList.begin(), fend = faceReplacementList.end(); f != fend; ++f) { /* Locate the face vertex which corresponds with the common 'dest' vertex To to this, find a removed face which has the FACE vertex corresponding with src, and use it's FACE vertex version of dest. */ PMFaceVertex* srcFaceVert = (*f)->getFaceVertexFromCommon(src); PMFaceVertex* destFaceVert = NULL; PMVertex::FaceList::iterator frlend = faceRemovalList.end(); for(PMVertex::FaceList::iterator iremoved = faceRemovalList.begin(); iremoved != frlend; ++iremoved) { //if ( (*iremoved)->hasFaceVertex(srcFaceVert) ) //{ destFaceVert = (*iremoved)->getFaceVertexFromCommon(dest); //} } assert(destFaceVert); #if LOG_PROGRESSIVE_MESH_GENERATION ofdebug << "Replacing vertex on face " << (unsigned int)(*f)->index << std::endl; #endif (*f)->replaceVertex(srcFaceVert, destFaceVert); } // Remove all the faces queued for removal for(PMVertex::FaceList::iterator f = faceRemovalList.begin(), fend = faceRemovalList.end(); f != fend; ++f) { #if LOG_PROGRESSIVE_MESH_GENERATION ofdebug << "Removing face " << (unsigned int)(*f)->index << std::endl; #endif (*f)->notifyRemoved(); } // Notify the vertex that it is gone src->notifyRemoved(); // invalidate neighbour`s costs for(RecomputeSet::iterator it = recomputeSet.begin(), it_end = recomputeSet.end(); it != it_end; ++it) { PMVertex* v = *it; if(!mInvalidCostMask.getBit(v->index)) { ++mInvalidCostCount; mInvalidCostMask.setBit(v->index); } } } //--------------------------------------------------------------------- Real ProgressiveMesh::computeEdgeCostAtVertex(size_t vertIndex) { // Call computer for each buffer on this vertex Real worstCost = -0.01f; WorkingDataList::iterator i, iend; iend = mWorkingData.end(); for (i = mWorkingData.begin(); i != iend; ++i) { worstCost = std::max(worstCost, computeEdgeCostAtVertexForBuffer(&(*i).mVertList[vertIndex])); } // Return the worst cost return worstCost; } //--------------------------------------------------------------------- size_t ProgressiveMesh::getInvalidCostCount(ProgressiveMesh::ProgressiveMeshList& pmList) { size_t invalidCostCount = 0; for(ProgressiveMeshList::iterator pmItr = pmList.begin(); pmItr != pmList.end(); ++pmItr) invalidCostCount += (*pmItr)->mInvalidCostCount; return invalidCostCount; } //--------------------------------------------------------------------- bool ProgressiveMesh::recomputeInvalidCosts(ProgressiveMeshList& pmList) { bool isRecomputed = false; for(ProgressiveMeshList::iterator n = pmList.begin(); n != pmList.end(); ++n) { if((*n)->mInvalidCostCount != 0) { (*n)->recomputeInvalidCosts(); isRecomputed = true; } } return isRecomputed; } //--------------------------------------------------------------------- void ProgressiveMesh::recomputeInvalidCosts() { if(mInvalidCostCount > 0) { for(WorstCostList::iterator it = mWorstCosts.begin(), end_it = mWorstCosts.end(); it != end_it; ++it) { unsigned idx = it->second; if(mInvalidCostMask.getBit(idx)) it->first = computeEdgeCostAtVertex(idx); } sortIndexesByCost(); mInvalidCostMask.clearAllBits(); mInvalidCostCount = 0; } mNextWorstCostHint = 0; } //--------------------------------------------------------------------- int ProgressiveMesh::cmpByCost(const void* p1, const void* p2) { Real c1 = ((CostIndexPair*)p1)->first; Real c2 = ((CostIndexPair*)p2)->first; return (c1 < c2) ? -1 : c1 > c2; } //--------------------------------------------------------------------- void ProgressiveMesh::sortIndexesByCost() { // half of total collapsing time is spended in this function for 700 000 triangles mesh, other // half in computeEdgeCostAtVertex. qsort is used instead of std::sort due to performance reasons qsort(&mWorstCosts.front(), mWorstCostsSize, sizeof(CostIndexPair), cmpByCost); // remove all vertices with NEVER_COLLAPSE_COST to reduce active vertex set while(mWorstCostsSize > 0 && mWorstCosts.back().first == NEVER_COLLAPSE_COST) { mWorstCosts.pop_back(); --mWorstCostsSize; } } //--------------------------------------------------------------------- ProgressiveMesh::CostIndexPair* ProgressiveMesh::getNextCollapser() { // as array is sorted by cost and only partially invalidated - return first valid cost, it would be the best for(CostIndexPair* ptr = &mWorstCosts.front() + mNextWorstCostHint; mNextWorstCostHint < mWorstCostsSize; ++ptr, ++mNextWorstCostHint) if(!mInvalidCostMask.getBit(ptr->second)) return ptr; // no valid costs static CostIndexPair dontCollapse(NEVER_COLLAPSE_COST, 0); return &dontCollapse; } //--------------------------------------------------------------------- void ProgressiveMesh::getNextCollapser(ProgressiveMesh::ProgressiveMeshList& pmList, ProgressiveMesh*& pm, CostIndexPair*& bestCollapser) { pm = NULL; bestCollapser = NULL; Real bestCost = NEVER_COLLAPSE_COST; for(ProgressiveMeshList::iterator pmItr = pmList.begin(); pmItr != pmList.end(); ) { ProgressiveMesh* pmCur = *pmItr; CostIndexPair* collapser = pmCur->getNextCollapser(); Real cost = collapser->first; if(NEVER_COLLAPSE_COST == cost) { if(pmCur->mInvalidCostCount != 0) { ++pmItr; } else { pmItr = pmList.erase(pmItr); } } else { if(cost < bestCost) { bestCost = cost; bestCollapser = collapser; pm = pmCur; } ++pmItr; } } } //--------------------------------------------------------------------- void ProgressiveMesh::bakeNewLOD(IndexData* pData) { assert(mCurrNumIndexes > 0 && "No triangles to bake!"); // Zip through the tri list of any working data copy and bake pData->indexCount = mCurrNumIndexes; pData->indexStart = 0; // Base size of indexes on original bool use32bitindexes = (mIndexData->indexBuffer->getType() == HardwareIndexBuffer::IT_32BIT); // Create index buffer, we don't need to read it back or modify it a lot pData->indexBuffer = HardwareBufferManager::getSingleton().createIndexBuffer( use32bitindexes? HardwareIndexBuffer::IT_32BIT : HardwareIndexBuffer::IT_16BIT, pData->indexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY, false); IndexBufferLockGuard lockGuard( pData->indexBuffer, 0, pData->indexBuffer->getSizeInBytes(), HardwareBuffer::HBL_DISCARD ); TriangleList::iterator tri, triend; // Use the first working data buffer, they are all the same index-wise WorkingDataList::iterator pWork = mWorkingData.begin(); triend = pWork->mTriList.end(); if (use32bitindexes) { unsigned int* pInt = static_cast<unsigned int*>(lockGuard.pData); for (tri = pWork->mTriList.begin(); tri != triend; ++tri) { if (!tri->removed) { *pInt++ = static_cast<unsigned int>(tri->vertex[0]->realIndex); *pInt++ = static_cast<unsigned int>(tri->vertex[1]->realIndex); *pInt++ = static_cast<unsigned int>(tri->vertex[2]->realIndex); } } } else { unsigned short* pShort = static_cast<unsigned short*>(lockGuard.pData); for (tri = pWork->mTriList.begin(); tri != triend; ++tri) { if (!tri->removed) { *pShort++ = static_cast<unsigned short>(tri->vertex[0]->realIndex); *pShort++ = static_cast<unsigned short>(tri->vertex[1]->realIndex); *pShort++ = static_cast<unsigned short>(tri->vertex[2]->realIndex); } } } } //--------------------------------------------------------------------- void ProgressiveMesh::bakeLodUsage(Mesh* pMesh, LodStrategy *lodStrategy, const LodValueList& lodValues, bool skipFirstLodLevel /* = false */) { // Iterate over the lods and record usage LodValueList::const_iterator ivalue = lodValues.begin(), ivalueend = lodValues.end(); if(skipFirstLodLevel && ivalue != ivalueend) ++ivalue; pMesh->_setLodInfo(1 + (ivalueend - ivalue), false); unsigned short lodLevel = 1; for (; ivalue != ivalueend; ++ivalue) { // Record usage MeshLodUsage lodUsage; lodUsage.userValue = *ivalue; lodUsage.value = 0; lodUsage.edgeData = 0; lodUsage.manualMesh.setNull(); pMesh->_setLodUsage(lodLevel++, lodUsage); } pMesh->setLodStrategy(lodStrategy); } //--------------------------------------------------------------------- void ProgressiveMesh::createSimplifiedVertexData(vector<IndexVertexPair>::type& usedVertices, VertexData* inVData, VertexData*& outVData, AxisAlignedBox& aabox) { outVData = NULL; VertexDataVariantList vdInVariantList; VertexDataVariant* inVertexDataBuffer = vdInVariantList.create(inVData, VES_POSITION); assert(inVertexDataBuffer->isValid()); if(!inVertexDataBuffer->isValid()) return; VertexDataVariant* inNormalDataBuffer = vdInVariantList.create(inVData, VES_NORMAL); VertexDataVariant* inUvDataBuffer = vdInVariantList.create(inVData, VES_TEXTURE_COORDINATES); static const unsigned short source = 0; outVData = new VertexData(); outVData->vertexStart = 0; outVData->vertexCount = usedVertices.size(); VertexDeclaration* vertexDeclaration = outVData->vertexDeclaration; size_t offset = 0; offset += vertexDeclaration->addElement(source, offset, VET_FLOAT3, VES_POSITION).getSize(); if(inNormalDataBuffer->isValid()) offset += vertexDeclaration->addElement(source, offset, VET_FLOAT3, VES_NORMAL).getSize(); if(inUvDataBuffer->isValid()) offset += vertexDeclaration->addElement(source, offset, VET_FLOAT2, VES_TEXTURE_COORDINATES).getSize(); assert(0 != offset); HardwareVertexBufferSharedPtr outVbuffer = HardwareBufferManager::getSingleton().createVertexBuffer( vertexDeclaration->getVertexSize(source), outVData->vertexCount, HardwareBuffer::HBU_STATIC_WRITE_ONLY); VertexBufferLockGuard outVdataLock(outVbuffer, HardwareBuffer::HBL_DISCARD); float* p = (float*)outVdataLock.pData; assert(outVData->vertexCount == usedVertices.size()); for (vector<IndexVertexPair>::type::iterator it = usedVertices.begin(); it != usedVertices.end(); ++it) { unsigned idx = it->first; Vector3 v3; Vector2 uv; inVertexDataBuffer->offsetToElement(idx); v3 = inVertexDataBuffer->getNextVector3(); *p++ = v3.x; *p++ = v3.y; *p++ = v3.z; aabox.merge(v3); #ifndef CHECK_CALCULATED_NORMALS if(inNormalDataBuffer->isValid()) { //store original normals inNormalDataBuffer->offsetToElement(idx); v3 = inNormalDataBuffer->getNextVector3(); *p++ = v3.x; *p++ = v3.y; *p++ = v3.z; } else { //store calculated normals PMVertex* v = it->second; *p++ = v->normal.x; *p++ = v->normal.y; *p++ = v->normal.z; } #else assert(inNormalDataBuffer->isValid()); //test is possible only if normals is present in input data if(inNormalDataBuffer->isValid()) { //store original normals inNormalDataBuffer->offsetToElement(idx); v3 = inNormalDataBuffer->getNextVector3(); } //store calculated normals PMVertex* v = it->second; assert(v3.dotProduct(v->normal.normalisedCopy()) > 0.5f); *p++ = v->normal.x; *p++ = v->normal.y; *p++ = v->normal.z; #endif if(inUvDataBuffer->isValid()) { inUvDataBuffer->offsetToElement(idx); uv = inUvDataBuffer->getNextVector2(); *p++ = uv.x; *p++ = uv.y; } } outVData->vertexBufferBinding->setBinding(source, outVbuffer); } //--------------------------------------------------------------------- void ProgressiveMesh::createIndexMap(vector<IndexVertexPair>::type& usedVertices, unsigned allVertexCount, vector<unsigned>::type& indexMap) { // we re-index used vertices and store old-to-new mapping in index map indexMap.resize(allVertexCount); memset(&indexMap[0], 0, allVertexCount * sizeof(unsigned)); size_t n = 0; for(vector<ProgressiveMesh::IndexVertexPair>::type::iterator it = usedVertices.begin(); it != usedVertices.end(); ++it) indexMap[it->first] = n++; } //--------------------------------------------------------------------- void ProgressiveMesh::bakeSimplifiedMesh(Ogre::Mesh* outMesh, Ogre::Mesh* inMesh, ProgressiveMeshList& pmList, bool dropFirstLodLevel) { assert(inMesh && outMesh); AxisAlignedBox outAabox; vector<IndexVertexPair>::type inCommonIndexes; BitArray usedVertices, usedBySubMesh; if(inMesh->sharedVertexData) { usedVertices.resize(inMesh->sharedVertexData->vertexCount); usedBySubMesh.resize(inMesh->sharedVertexData->vertexCount); } for(size_t i = 0; i < inMesh->getNumSubMeshes(); ++i) { SubMesh* inSubMesh = inMesh->getSubMesh(i); if(!inSubMesh->useSharedVertices) continue; ProgressiveMesh* pm = pmList[i]; if(NULL == pm->mSubMesh) continue; // dummy, skip it IndexDataVariantSharedPtr inSubMeshIndexDataVar(IndexDataVariant::create(dropFirstLodLevel ? pm->mLodFaceList.front() : inSubMesh->indexData)); assert(!inSubMeshIndexDataVar.isNull()); usedBySubMesh.clearAllBits(); inSubMeshIndexDataVar->markUsedVertices(usedBySubMesh); for(unsigned idx = 0, end_idx = inMesh->sharedVertexData->vertexCount; idx < end_idx; ++idx) if(usedBySubMesh.getBit(idx) && !usedVertices.getBit(idx)) { usedVertices.setBit(idx); inCommonIndexes.push_back(std::make_pair(idx, &pm->mWorkingData.front().mVertList.front() + idx)); } } // note - we don`t preserve initial vertex order, but group vertices by submesh instead, improving locality vector<unsigned>::type sharedIndexMap; // between submeshes if(!inCommonIndexes.empty()) { createSimplifiedVertexData(inCommonIndexes, inMesh->sharedVertexData, outMesh->sharedVertexData, outAabox); createIndexMap(inCommonIndexes, inMesh->sharedVertexData->vertexCount, sharedIndexMap); } for(size_t i = 0; i < inMesh->getNumSubMeshes(); ++i) { SubMesh* inSubMesh = inMesh->getSubMesh(i); SubMesh* outSubMesh = outMesh->createSubMesh(); outSubMesh->setMaterialName(inSubMesh->getMaterialName()); outSubMesh->useSharedVertices = inSubMesh->useSharedVertices; ProgressiveMesh* pm = pmList[i]; if(NULL == pm->mSubMesh) continue; // dummy, skip it IndexDataVariantSharedPtr inSubMeshIndexDataVar(IndexDataVariant::create(dropFirstLodLevel ? pm->mLodFaceList.front() : inSubMesh->indexData)); assert(!inSubMeshIndexDataVar.isNull()); vector<unsigned>::type localIndexMap; // to submesh vector<unsigned>::type* indexMap = &sharedIndexMap; if(!outSubMesh->useSharedVertices) { usedVertices.resize(inSubMesh->vertexData->vertexCount); inSubMeshIndexDataVar->markUsedVertices(usedVertices); vector<IndexVertexPair>::type inSubMeshIndexes; for(unsigned idx = 0, end_idx = inSubMesh->vertexData->vertexCount; idx < end_idx; ++idx) if(usedVertices.getBit(idx)) inSubMeshIndexes.push_back(std::make_pair(idx, &pm->mWorkingData.front().mVertList.front() + idx)); createSimplifiedVertexData(inSubMeshIndexes, inSubMesh->vertexData, outSubMesh->vertexData, outAabox); indexMap = &localIndexMap; createIndexMap(inSubMeshIndexes, inSubMesh->vertexData->vertexCount, localIndexMap); } if(!outSubMesh->useSharedVertices && !outSubMesh->vertexData) { OGRE_EXCEPT(Exception::ERR_INVALID_STATE, String("Submesh does not have any vertex data"), "ProgressiveMesh::bakeSimplifiedMesh"); } bool outUse16bitIndexes = (outSubMesh->useSharedVertices ? outMesh->sharedVertexData : outSubMesh->vertexData)->vertexCount <= 0xFFFF; inSubMeshIndexDataVar->createIndexData(outSubMesh->indexData, outUse16bitIndexes, indexMap); inSubMeshIndexDataVar.setNull(); // clone all LODs, may be without first vector<IndexData*>::type::iterator n = pm->mLodFaceList.begin(); if(dropFirstLodLevel && n != pm->mLodFaceList.end()) ++n; for(; n != pm->mLodFaceList.end(); ++n) { IndexDataVariantSharedPtr lodIndexDataVar(IndexDataVariant::create(*n, HardwareBuffer::HBL_DISCARD)); IndexData* lod = OGRE_NEW IndexData; lodIndexDataVar->createIndexData(lod, outUse16bitIndexes, indexMap); outSubMesh->mLodFaceList.push_back(lod); } } // Store bbox and sphere outMesh->_setBounds(outAabox, false); outMesh->_setBoundingSphereRadius((outAabox.getMaximum() - outAabox.getMinimum()).length() / 2.0f); } //--------------------------------------------------------------------- ProgressiveMesh::PMTriangle::PMTriangle() : removed(false) { } //--------------------------------------------------------------------- void ProgressiveMesh::PMTriangle::setDetails(size_t newindex, ProgressiveMesh::PMFaceVertex *v0, ProgressiveMesh::PMFaceVertex *v1, ProgressiveMesh::PMFaceVertex *v2) { assert(v0!=v1 && v1!=v2 && v2!=v0); removed = false; index = newindex; vertex[0]=v0; vertex[1]=v1; vertex[2]=v2; computeNormal(); // Add tri to vertices // Also tell vertices they are neighbours for(int i=0;i<3;i++) { PMVertex* vv = vertex[i]->commonVertex; if(vv->face.end() == std::find(vv->face.begin(), vv->face.end(), this)) vv->face.push_back(this); for(int j=0;j<3;j++) if(i!=j) { if(vv->neighbor.end() == std::find(vv->neighbor.begin(), vv->neighbor.end(), vertex[j]->commonVertex)) vv->neighbor.push_back(vertex[j]->commonVertex); } } } //--------------------------------------------------------------------- void ProgressiveMesh::PMTriangle::notifyRemoved(void) { int i; for(i=0; i<3; i++) { // remove this tri from the vertices if(vertex[i]) vertex[i]->commonVertex->face.erase( std::remove(vertex[i]->commonVertex->face.begin(), vertex[i]->commonVertex->face.end(), this), vertex[i]->commonVertex->face.end() ); } for(i=0; i<3; i++) { int i2 = (i+1)%3; if(!vertex[i] || !vertex[i2]) continue; // Check remaining vertices and remove if not neighbours anymore // NB May remain neighbours if other tris link them vertex[i ]->commonVertex->removeIfNonNeighbor(vertex[i2]->commonVertex); vertex[i2]->commonVertex->removeIfNonNeighbor(vertex[i ]->commonVertex); } removed = true; } //--------------------------------------------------------------------- bool ProgressiveMesh::PMTriangle::hasCommonVertex(ProgressiveMesh::PMVertex *v) const { return (v == vertex[0]->commonVertex || v == vertex[1]->commonVertex || v == vertex[2]->commonVertex); } //--------------------------------------------------------------------- bool ProgressiveMesh::PMTriangle::hasFaceVertex(ProgressiveMesh::PMFaceVertex *v) const { return (v == vertex[0] || v == vertex[1] || v == vertex[2]); } //--------------------------------------------------------------------- ProgressiveMesh::PMFaceVertex* ProgressiveMesh::PMTriangle::getFaceVertexFromCommon(ProgressiveMesh::PMVertex* commonVert) { if (vertex[0]->commonVertex == commonVert) return vertex[0]; if (vertex[1]->commonVertex == commonVert) return vertex[1]; if (vertex[2]->commonVertex == commonVert) return vertex[2]; return NULL; } //--------------------------------------------------------------------- void ProgressiveMesh::PMTriangle::computeNormal() { Vector3 v0=vertex[0]->commonVertex->position; Vector3 v1=vertex[1]->commonVertex->position; Vector3 v2=vertex[2]->commonVertex->position; // Cross-product 2 edges Vector3 e1 = v1 - v0; Vector3 e2 = v2 - v1; normal = e1.crossProduct(e2); area = normal.normalise(); } //--------------------------------------------------------------------- void ProgressiveMesh::PMTriangle::replaceVertex( ProgressiveMesh::PMFaceVertex *vold, ProgressiveMesh::PMFaceVertex *vnew) { assert(vold && vnew); assert(vold==vertex[0] || vold==vertex[1] || vold==vertex[2]); assert(vnew!=vertex[0] && vnew!=vertex[1] && vnew!=vertex[2]); if(vold==vertex[0]){ vertex[0]=vnew; } else if(vold==vertex[1]){ vertex[1]=vnew; } else { assert(vold==vertex[2]); vertex[2]=vnew; } int i; vold->commonVertex->face.erase(std::remove(vold->commonVertex->face.begin(), vold->commonVertex->face.end(), this), vold->commonVertex->face.end()); if(vnew->commonVertex->face.end() == std::find(vnew->commonVertex->face.begin(), vnew->commonVertex->face.end(), this)) vnew->commonVertex->face.push_back(this); for(i=0;i<3;i++) { vold->commonVertex->removeIfNonNeighbor(vertex[i]->commonVertex); vertex[i]->commonVertex->removeIfNonNeighbor(vold->commonVertex); } for(i=0;i<3;i++) { assert(std::find(vertex[i]->commonVertex->face.begin(), vertex[i]->commonVertex->face.end(), this) != vertex[i]->commonVertex->face.end()); for(int j=0;j<3;j++) if(i!=j) { #if LOG_PROGRESSIVE_MESH_GENERATION ofdebug << "Adding vertex " << (unsigned int)vertex[j]->commonVertex->index << " to the neighbor list " "of vertex " << (unsigned int)vertex[i]->commonVertex->index << std::endl; #endif if(vertex[i]->commonVertex->neighbor.end() == std::find(vertex[i]->commonVertex->neighbor.begin(), vertex[i]->commonVertex->neighbor.end(), vertex[j]->commonVertex)) vertex[i]->commonVertex->neighbor.push_back(vertex[j]->commonVertex); } } computeNormal(); } //--------------------------------------------------------------------- void ProgressiveMesh::PMVertex::setDetails(size_t newindex, const Vector3& pos, const Vector3& n, const Vector2& texUV) { position = pos; normal = n; uv = texUV; index = newindex; removed = false; toBeRemoved = false; } //--------------------------------------------------------------------- void ProgressiveMesh::PMVertex::calculateNormal() { Vector3 weightedSum(Vector3::ZERO); // sum of neighbour face normals weighted with neighbour area for(PMVertex::FaceList::iterator i = face.begin(), iend = face.end(); i != iend; ++i) { PMTriangle* t = *i; weightedSum += t->normal * t->area; // accumulate neighbour face normals weighted with neighbour area } // there is small possibility, that weigtedSum is very close to zero, use arbitrary normal value in such case normal = weightedSum.normalise() > 1e-08 ? weightedSum : Vector3::UNIT_Z; } //--------------------------------------------------------------------- bool ProgressiveMesh::PMVertex::isNearEnough(PMVertex* other) const { return position == other->position && normal.dotProduct(other->normal) > 0.8f && (uv - other->uv).squaredLength() < 0.01f; } //--------------------------------------------------------------------- void ProgressiveMesh::PMVertex::notifyRemoved(void) { // Removes possible self listing as neighbor first neighbor.erase(std::remove(neighbor.begin(), neighbor.end(), this), neighbor.end()); PMVertex::NeighborList::iterator nend = neighbor.end(); for (PMVertex::NeighborList::iterator n = neighbor.begin(); n != nend; ++n) { // Remove me from neighbor (*n)->neighbor.erase(std::remove((*n)->neighbor.begin(), (*n)->neighbor.end(), this), (*n)->neighbor.end()); } removed = true; collapseTo = NULL; collapseCost = NEVER_COLLAPSE_COST; } //--------------------------------------------------------------------- void ProgressiveMesh::PMVertex::initBorderStatus() { assert(mBorderStatus == BS_UNKNOWN); // Look for edges which only have one tri attached, this is a border NeighborList::iterator nend = neighbor.end(); // Loop for each neighbor for(NeighborList::iterator n = neighbor.begin(); n != nend; ++n) { // Count of tris shared between the edge between this and neighbor ushort count = 0; // Loop over each face, looking for shared ones FaceList::iterator fend = face.end(); for(FaceList::iterator j = face.begin(); j != fend; ++j) { if((*j)->hasCommonVertex(*n)) { // Shared tri ++count; } } //assert(count>0); // Must be at least one! // This edge has only 1 tri on it, it's a border if(count == 1) { mBorderStatus = BS_BORDER; return; } } mBorderStatus = BS_NOT_BORDER; } //--------------------------------------------------------------------- bool ProgressiveMesh::PMVertex::isManifoldEdgeWith(ProgressiveMesh::PMVertex* v) { // Check the sides involving both these verts // If there is only 1 this is a manifold edge ushort sidesCount = 0; FaceList::iterator fend = face.end(); for (FaceList::iterator i = face.begin(); i != fend; ++i) { if ((*i)->hasCommonVertex(v)) { sidesCount++; } } return (sidesCount == 1); } //--------------------------------------------------------------------- void ProgressiveMesh::PMVertex::removeIfNonNeighbor(ProgressiveMesh::PMVertex *n) { // removes n from neighbor list if n isn't a neighbor. NeighborList::iterator i = std::find(neighbor.begin(), neighbor.end(), n); if (i == neighbor.end()) return; // Not in neighbor list anyway FaceList::iterator f, fend; fend = face.end(); for(f = face.begin(); f != fend; ++f) { if((*f)->hasCommonVertex(n)) return; // Still a neighbor } #if LOG_PROGRESSIVE_MESH_GENERATION ofdebug << "Vertex " << (unsigned int)n->index << " is no longer a neighbour of vertex " << (unsigned int)this->index << " so has been removed from the latter's neighbor list." << std::endl; #endif neighbor.erase(std::remove(neighbor.begin(), neighbor.end(), n), neighbor.end()); if (neighbor.empty() && !toBeRemoved) { // This vertex has been removed through isolation (collapsing around it) this->notifyRemoved(); } } //--------------------------------------------------------------------- void ProgressiveMesh::dumpContents(const String& log) { std::ofstream ofdump(log.c_str()); // Just dump 1st working data for now WorkingDataList::iterator worki = mWorkingData.begin(); CommonVertexList::iterator vi, vend; vend = worki->mVertList.end(); ofdump << "-------== VERTEX LIST ==-----------------" << std::endl; for(WorstCostList::iterator it = mWorstCosts.begin(), end_it = mWorstCosts.end(); it != end_it; ++it) { PMVertex* vert = &worki->mVertList[it->second]; const char* isBorder = (vert->mBorderStatus == PMVertex::BS_BORDER) ? "yes" : "no"; ofdump << "Vertex " << (unsigned int)vert->index << " pos: " << vert->position << " removed: " << vert->removed << " isborder: " << isBorder << std::endl; ofdump << " Faces:" << std::endl; PMVertex::FaceList::iterator fend = vert->face.end(); for(PMVertex::FaceList::iterator f = vert->face.begin(); f != fend; ++f) { ofdump << " Triangle index " << (unsigned int)(*f)->index << std::endl; } ofdump << " Neighbours:" << std::endl; PMVertex::NeighborList::iterator nend = vert->neighbor.end(); for (PMVertex::NeighborList::iterator n = vert->neighbor.begin(); n != nend; ++n) { ofdump << " Vertex index " << (unsigned int)(*n)->index << std::endl; } } TriangleList::iterator ti, tend; tend = worki->mTriList.end(); ofdump << "-------== TRIANGLE LIST ==-----------------" << std::endl; for(ti = worki->mTriList.begin(); ti != tend; ++ti) { ofdump << "Triangle " << (unsigned int)ti->index << " norm: " << ti->normal << " removed: " << ti->removed << std::endl; ofdump << " Vertex 0: " << (unsigned int)ti->vertex[0]->realIndex << std::endl; ofdump << " Vertex 1: " << (unsigned int)ti->vertex[1]->realIndex << std::endl; ofdump << " Vertex 2: " << (unsigned int)ti->vertex[2]->realIndex << std::endl; } ofdump << "-------== COLLAPSE COST LIST ==-----------------" << std::endl; for(WorstCostList::iterator it = mWorstCosts.begin(), end_it = mWorstCosts.end(); it != end_it; ++it) { PMVertex* vert = &worki->mVertList[it->second]; const char* isBorder = (vert->mBorderStatus == PMVertex::BS_BORDER) ? "yes" : "no"; ofdump << "Vertex " << (unsigned int)vert->index << ", pos: " << vert->position << ", cost: " << vert->collapseCost << ", removed: " << vert->removed << ", isborder: " << isBorder << std::endl; } ofdump.close(); } }
35.187963
181
0.631845
[ "mesh", "object", "shape", "vector", "model" ]
ca3b4b57491fc9dbbe28624408efb497d300b54f
16,524
cpp
C++
test/reg-test/fam-api-reg/fam_fetch_arithmetic_atomics_mt_reg_test.cpp
ssinghal53/OpenFAM
dcb276bff72b6df3087ad216a66c16d0e6d0993d
[ "BSD-3-Clause" ]
17
2019-10-21T22:46:18.000Z
2022-01-20T09:22:49.000Z
test/reg-test/fam-api-reg/fam_fetch_arithmetic_atomics_mt_reg_test.cpp
ssinghal53/OpenFAM
dcb276bff72b6df3087ad216a66c16d0e6d0993d
[ "BSD-3-Clause" ]
103
2020-02-24T22:07:56.000Z
2022-03-30T17:13:57.000Z
test/reg-test/fam-api-reg/fam_fetch_arithmetic_atomics_mt_reg_test.cpp
ssinghal53/OpenFAM
dcb276bff72b6df3087ad216a66c16d0e6d0993d
[ "BSD-3-Clause" ]
26
2019-10-12T20:33:18.000Z
2022-03-31T15:38:23.000Z
/* * fam_fetch_arithmatic_atomics_mt_reg_test.cpp * Copyright (c) 2019 Hewlett Packard Enterprise Development, LP. All rights * reserved. Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * See https://spdx.org/licenses/BSD-3-Clause * */ /* Test Case Description: Tests fetching arithmetic operations for multithreaded * model. */ #include <fam/fam_exception.h> #include <gtest/gtest.h> #include <iostream> #include <stdio.h> #include <string.h> #include <fam/fam.h> #include "common/fam_test_config.h" using namespace std; using namespace openfam; #define NUM_THREADS 10 #define REGION_SIZE (1024 * 1024 * NUM_THREADS) fam *my_fam; Fam_Options fam_opts; int rc; typedef struct { Fam_Descriptor *item; uint64_t offset; int32_t tid; int32_t msg_size; } ValueInfo; // Test case 1 - test for atomic fetch_add. void *thrd_add_subtract_int32(void *arg) { ValueInfo *addInfo = (ValueInfo *)arg; Fam_Descriptor *item = addInfo->item; uint64_t offset = addInfo->tid * sizeof(int32_t); int32_t valueInt32 = 0xAAAA; EXPECT_NO_THROW(my_fam->fam_set(item, offset, valueInt32)); EXPECT_NO_THROW(my_fam->fam_quiet()); valueInt32 = 0x1; EXPECT_NO_THROW(valueInt32 = my_fam->fam_fetch_add(item, offset, valueInt32)); EXPECT_EQ(valueInt32, 0xAAAA); EXPECT_NO_THROW(valueInt32 = my_fam->fam_fetch_int32(item, offset)); EXPECT_EQ(valueInt32, 0xAAAB); valueInt32 = 0x1; EXPECT_NO_THROW(valueInt32 = my_fam->fam_fetch_subtract(item, offset, valueInt32)); EXPECT_EQ(valueInt32, 0xAAAB); EXPECT_NO_THROW(valueInt32 = my_fam->fam_fetch_int32(item, offset)); EXPECT_EQ(valueInt32, 0xAAAA); pthread_exit(NULL); } TEST(FamArithAtomicInt32, ArithAtomicInt32Success) { Fam_Region_Descriptor *desc; Fam_Descriptor *item; pthread_t thr[NUM_THREADS]; const char *testRegion = get_uniq_str("test", my_fam); const char *firstItem = get_uniq_str("first", my_fam); int i; ValueInfo *info = (ValueInfo *)malloc(sizeof(ValueInfo) * NUM_THREADS); EXPECT_NO_THROW( desc = my_fam->fam_create_region(testRegion, REGION_SIZE, 0777, RAID1)); EXPECT_NE((void *)NULL, desc); // Allocating data items in the created region EXPECT_NO_THROW( item = my_fam->fam_allocate( firstItem, 1024 * NUM_THREADS * sizeof(int32_t), 0777, desc)); EXPECT_NE((void *)NULL, item); for (i = 0; i < NUM_THREADS; ++i) { info[i] = {item, 0, i, 0}; if ((rc = pthread_create(&thr[i], NULL, thrd_add_subtract_int32, &info[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); exit(1); } } for (i = 0; i < NUM_THREADS; ++i) { pthread_join(thr[i], NULL); } EXPECT_NO_THROW(my_fam->fam_deallocate(item)); EXPECT_NO_THROW(my_fam->fam_destroy_region(desc)); delete item; delete desc; free((void *)testRegion); free((void *)firstItem); } void *thrd_add_subtract_int64(void *arg) { ValueInfo *addInfo = (ValueInfo *)arg; Fam_Descriptor *item = addInfo->item; uint64_t offset = addInfo->tid * sizeof(int64_t); // Atomic tests for int64 int64_t valueInt64 = 0xBBBBBBBBBBBBBBBB; EXPECT_NO_THROW(my_fam->fam_set(item, offset, valueInt64)); EXPECT_NO_THROW(my_fam->fam_quiet()); valueInt64 = 0x1; EXPECT_NO_THROW(valueInt64 = my_fam->fam_fetch_add(item, offset, valueInt64)); EXPECT_EQ(valueInt64, (int64_t)0xBBBBBBBBBBBBBBBB); EXPECT_NO_THROW(valueInt64 = my_fam->fam_fetch_int64(item, offset)); EXPECT_EQ(valueInt64, (int64_t)0xBBBBBBBBBBBBBBBC); valueInt64 = 0x1; EXPECT_NO_THROW(valueInt64 = my_fam->fam_fetch_subtract(item, offset, valueInt64)); EXPECT_EQ(valueInt64, (int64_t)0xBBBBBBBBBBBBBBBC); EXPECT_NO_THROW(valueInt64 = my_fam->fam_fetch_int64(item, offset)); EXPECT_EQ(valueInt64, (int64_t)0xBBBBBBBBBBBBBBBB); pthread_exit(NULL); } TEST(FamArithAtomicInt64, ArithAtomicInt64Success) { Fam_Region_Descriptor *desc; Fam_Descriptor *item; pthread_t thr[NUM_THREADS]; const char *testRegion = get_uniq_str("test", my_fam); const char *firstItem = get_uniq_str("first", my_fam); int i; ValueInfo *info = (ValueInfo *)malloc(sizeof(ValueInfo) * NUM_THREADS); EXPECT_NO_THROW( desc = my_fam->fam_create_region(testRegion, REGION_SIZE, 0777, RAID1)); EXPECT_NE((void *)NULL, desc); // Allocating data items in the created region EXPECT_NO_THROW( item = my_fam->fam_allocate( firstItem, 1024 * NUM_THREADS * sizeof(int64_t), 0777, desc)); EXPECT_NE((void *)NULL, item); for (i = 0; i < NUM_THREADS; ++i) { info[i] = {item, 0, i, 0}; if ((rc = pthread_create(&thr[i], NULL, thrd_add_subtract_int64, &info[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); exit(1); } } for (i = 0; i < NUM_THREADS; ++i) { pthread_join(thr[i], NULL); } EXPECT_NO_THROW(my_fam->fam_deallocate(item)); EXPECT_NO_THROW(my_fam->fam_destroy_region(desc)); delete item; delete desc; free((void *)testRegion); free((void *)firstItem); } void *thrd_add_subtract_uint32(void *arg) { ValueInfo *addInfo = (ValueInfo *)arg; Fam_Descriptor *item = addInfo->item; uint64_t offset = addInfo->tid * sizeof(uint32_t); // Atomic tests for uint32 uint32_t valueUint32 = 0xBBBBBBBB; EXPECT_NO_THROW(my_fam->fam_set(item, offset, valueUint32)); EXPECT_NO_THROW(my_fam->fam_quiet()); valueUint32 = 0x1; EXPECT_NO_THROW(valueUint32 = my_fam->fam_fetch_add(item, offset, valueUint32)); EXPECT_EQ(valueUint32, 0xBBBBBBBB); EXPECT_NO_THROW(valueUint32 = my_fam->fam_fetch_uint32(item, offset)); EXPECT_EQ(valueUint32, 0xBBBBBBBC); valueUint32 = 0; EXPECT_NO_THROW(my_fam->fam_set(item, offset, valueUint32)); EXPECT_NO_THROW(my_fam->fam_quiet()); valueUint32 = 0x1; EXPECT_NO_THROW(valueUint32 = my_fam->fam_fetch_subtract(item, offset, valueUint32)); EXPECT_EQ(valueUint32, 0u); EXPECT_NO_THROW(valueUint32 = my_fam->fam_fetch_uint32(item, offset)); EXPECT_EQ(valueUint32, 0xFFFFFFFF); pthread_exit(NULL); } TEST(FamArithAtomicUint32, ArithAtomicUint32Success) { Fam_Region_Descriptor *desc; Fam_Descriptor *item; pthread_t thr[NUM_THREADS]; const char *testRegion = get_uniq_str("test", my_fam); const char *firstItem = get_uniq_str("first", my_fam); int i; ValueInfo *info = (ValueInfo *)malloc(sizeof(ValueInfo) * NUM_THREADS); EXPECT_NO_THROW( desc = my_fam->fam_create_region(testRegion, REGION_SIZE, 0777, RAID1)); EXPECT_NE((void *)NULL, desc); // Allocating data items in the created region EXPECT_NO_THROW( item = my_fam->fam_allocate( firstItem, 1024 * NUM_THREADS * sizeof(uint32_t), 0777, desc)); EXPECT_NE((void *)NULL, item); for (i = 0; i < NUM_THREADS; ++i) { info[i] = {item, 0, i, 0}; if ((rc = pthread_create(&thr[i], NULL, thrd_add_subtract_uint32, &info[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); exit(1); } } for (i = 0; i < NUM_THREADS; ++i) { pthread_join(thr[i], NULL); } EXPECT_NO_THROW(my_fam->fam_deallocate(item)); EXPECT_NO_THROW(my_fam->fam_destroy_region(desc)); delete item; delete desc; free((void *)testRegion); free((void *)firstItem); } void *thrd_add_subtract_uint64(void *arg) { ValueInfo *addInfo = (ValueInfo *)arg; Fam_Descriptor *item = addInfo->item; uint64_t offset = addInfo->tid * sizeof(uint64_t); // Atomic tests for uint64 uint64_t valueUint64 = 0xBBBBBBBBBBBBBBBB; EXPECT_NO_THROW(my_fam->fam_set(item, offset, valueUint64)); EXPECT_NO_THROW(my_fam->fam_quiet()); valueUint64 = 0x1; EXPECT_NO_THROW(valueUint64 = my_fam->fam_fetch_add(item, offset, valueUint64)); EXPECT_EQ(valueUint64, 0xBBBBBBBBBBBBBBBB); EXPECT_NO_THROW(valueUint64 = my_fam->fam_fetch_uint64(item, offset)); EXPECT_EQ(valueUint64, 0xBBBBBBBBBBBBBBBC); valueUint64 = 0; EXPECT_NO_THROW(my_fam->fam_set(item, offset, valueUint64)); EXPECT_NO_THROW(my_fam->fam_quiet()); valueUint64 = 0x1; EXPECT_NO_THROW(valueUint64 = my_fam->fam_fetch_subtract(item, offset, valueUint64)); EXPECT_EQ(valueUint64, 0u); EXPECT_NO_THROW(valueUint64 = my_fam->fam_fetch_uint64(item, offset)); EXPECT_EQ(valueUint64, 0xFFFFFFFFFFFFFFFF); pthread_exit(NULL); } TEST(FamArithAtomicUint64, ArithAtomicUint64Success) { Fam_Region_Descriptor *desc; Fam_Descriptor *item; pthread_t thr[NUM_THREADS]; const char *testRegion = get_uniq_str("test", my_fam); const char *firstItem = get_uniq_str("first", my_fam); int i; ValueInfo *info = (ValueInfo *)malloc(sizeof(ValueInfo) * NUM_THREADS); EXPECT_NO_THROW( desc = my_fam->fam_create_region(testRegion, REGION_SIZE, 0777, RAID1)); EXPECT_NE((void *)NULL, desc); // Allocating data items in the created region EXPECT_NO_THROW( item = my_fam->fam_allocate( firstItem, 1024 * NUM_THREADS * sizeof(uint64_t), 0777, desc)); EXPECT_NE((void *)NULL, item); for (i = 0; i < NUM_THREADS; ++i) { info[i] = {item, 0, i, 0}; if ((rc = pthread_create(&thr[i], NULL, thrd_add_subtract_int32, &info[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); exit(1); } } for (i = 0; i < NUM_THREADS; ++i) { pthread_join(thr[i], NULL); } EXPECT_NO_THROW(my_fam->fam_deallocate(item)); EXPECT_NO_THROW(my_fam->fam_destroy_region(desc)); delete item; delete desc; free((void *)testRegion); free((void *)firstItem); } void *thrd_add_subtract_float(void *arg) { ValueInfo *addInfo = (ValueInfo *)arg; Fam_Descriptor *item = addInfo->item; uint64_t offset = addInfo->tid * sizeof(float); // Atomic tests for float float valueFloat = 4.3f; EXPECT_NO_THROW(my_fam->fam_set(item, offset, valueFloat)); EXPECT_NO_THROW(my_fam->fam_quiet()); valueFloat = 1.2f; EXPECT_NO_THROW(valueFloat = my_fam->fam_fetch_add(item, offset, valueFloat)); EXPECT_EQ(valueFloat, 4.3f); EXPECT_NO_THROW(valueFloat = my_fam->fam_fetch_float(item, offset)); EXPECT_EQ(valueFloat, 5.5f); valueFloat = 1.2f; EXPECT_NO_THROW(valueFloat = my_fam->fam_fetch_subtract(item, offset, valueFloat)); EXPECT_EQ(valueFloat, 5.5f); EXPECT_NO_THROW(valueFloat = my_fam->fam_fetch_float(item, offset)); EXPECT_EQ(valueFloat, 4.3f); pthread_exit(NULL); } TEST(FamArithAtomicFloat, ArithAtomiciFloatSuccess) { Fam_Region_Descriptor *desc; Fam_Descriptor *item; pthread_t thr[NUM_THREADS]; const char *testRegion = get_uniq_str("test", my_fam); const char *firstItem = get_uniq_str("first", my_fam); int i; ValueInfo *info = (ValueInfo *)malloc(sizeof(ValueInfo) * NUM_THREADS); EXPECT_NO_THROW( desc = my_fam->fam_create_region(testRegion, REGION_SIZE, 0777, RAID1)); EXPECT_NE((void *)NULL, desc); // Allocating data items in the created region EXPECT_NO_THROW( item = my_fam->fam_allocate( firstItem, 1024 * NUM_THREADS * sizeof(float), 0777, desc)); EXPECT_NE((void *)NULL, item); for (i = 0; i < NUM_THREADS; ++i) { info[i] = {item, 0, i, 0}; if ((rc = pthread_create(&thr[i], NULL, thrd_add_subtract_float, &info[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); exit(1); } } for (i = 0; i < NUM_THREADS; ++i) { pthread_join(thr[i], NULL); } EXPECT_NO_THROW(my_fam->fam_deallocate(item)); EXPECT_NO_THROW(my_fam->fam_destroy_region(desc)); delete item; delete desc; free((void *)testRegion); free((void *)firstItem); } void *thrd_add_subtract_double(void *arg) { ValueInfo *addInfo = (ValueInfo *)arg; Fam_Descriptor *item = addInfo->item; uint64_t offset = addInfo->tid * sizeof(double); // Atomic tests for double double valueDouble = 4.4e+38; EXPECT_NO_THROW(my_fam->fam_set(item, offset, valueDouble)); EXPECT_NO_THROW(my_fam->fam_quiet()); valueDouble = 1.2e+38; EXPECT_NO_THROW(valueDouble = my_fam->fam_fetch_add(item, offset, valueDouble)); EXPECT_EQ(valueDouble, 4.4e+38); EXPECT_NO_THROW(valueDouble = my_fam->fam_fetch_double(item, offset)); EXPECT_EQ(valueDouble, 5.6e+38); valueDouble = 1.2e+38; EXPECT_NO_THROW(valueDouble = my_fam->fam_fetch_subtract(item, offset, valueDouble)); EXPECT_EQ(valueDouble, 5.6e+38); EXPECT_NO_THROW(valueDouble = my_fam->fam_fetch_double(item, offset)); EXPECT_EQ(valueDouble, 4.4e+38); pthread_exit(NULL); } TEST(FamArithAtomiciDouble, ArithAtomicDoubleSuccess) { Fam_Region_Descriptor *desc; Fam_Descriptor *item; pthread_t thr[NUM_THREADS]; const char *testRegion = get_uniq_str("test", my_fam); const char *firstItem = get_uniq_str("first", my_fam); int i; ValueInfo *info = (ValueInfo *)malloc(sizeof(ValueInfo) * NUM_THREADS); EXPECT_NO_THROW( desc = my_fam->fam_create_region(testRegion, REGION_SIZE, 0777, RAID1)); EXPECT_NE((void *)NULL, desc); // Allocating data items in the created region EXPECT_NO_THROW( item = my_fam->fam_allocate( firstItem, 1024 * NUM_THREADS * sizeof(double), 0777, desc)); EXPECT_NE((void *)NULL, item); for (i = 0; i < NUM_THREADS; ++i) { info[i] = {item, 0, i, 0}; if ((rc = pthread_create(&thr[i], NULL, thrd_add_subtract_double, &info[i]))) { fprintf(stderr, "error: pthread_create, rc: %d\n", rc); exit(1); } } for (i = 0; i < NUM_THREADS; ++i) { pthread_join(thr[i], NULL); } EXPECT_NO_THROW(my_fam->fam_deallocate(item)); EXPECT_NO_THROW(my_fam->fam_destroy_region(desc)); delete item; delete desc; free((void *)testRegion); free((void *)firstItem); } int main(int argc, char **argv) { int ret; ::testing::InitGoogleTest(&argc, argv); my_fam = new fam(); init_fam_options(&fam_opts); fam_opts.famThreadModel = strdup("FAM_THREAD_MULTIPLE"); EXPECT_NO_THROW(my_fam->fam_initialize("default", &fam_opts)); ret = RUN_ALL_TESTS(); EXPECT_NO_THROW(my_fam->fam_finalize("default")); return ret; }
30.043636
80
0.658981
[ "model" ]
ca3dfadc9381fb6317f4072d77e473237c105ba2
17,467
cpp
C++
sensing/ahrs_ekf.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
12
2016-07-12T10:26:47.000Z
2021-12-14T10:03:11.000Z
sensing/ahrs_ekf.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
183
2015-01-22T12:35:18.000Z
2017-06-09T10:11:26.000Z
sensing/ahrs_ekf.cpp
jlecoeur/MAVRIC_Library
56281851da7541d5c1199490a8621d7f18482be1
[ "BSD-3-Clause" ]
25
2015-02-03T15:15:48.000Z
2021-12-14T08:55:04.000Z
/******************************************************************************* * Copyright (c) 2009-2014, MAV'RIC Development Team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ /******************************************************************************* * \file ahrs_ekf.cpp * * \author MAV'RIC Team * \author Nicolas Dousse * \author Matthew Douglas * * \brief Extended Kalman Filter attitude estimation, mixing accelerometer and magnetometer * x[0] : bias_x * x[1] : bias_y * x[2] : bias_z * x[3] : q0 * x[4] : q1 * x[5] : q2 * x[6] : q3 * ******************************************************************************/ #include "sensing/ahrs_ekf.hpp" #include "hal/common/time_keeper.hpp" #include "util/coord_conventions.hpp" #include "util/constants.hpp" #include "util/print_util.hpp" extern "C" { #include "util/maths.h" #include "util/vectors.h" #include "util/quaternions.h" } using namespace mat; //------------------------------------------------------------------------------ // PUBLIC FUNCTIONS IMPLEMENTATION //------------------------------------------------------------------------------ AHRS_ekf::AHRS_ekf(const Imu& imu, const AHRS_ekf::conf_t config): Kalman<7, 0, 3>(), config_(config), imu_(imu), attitude_(quat_t{1.0f, {0.0f, 0.0f, 0.0f}}), angular_speed_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}), linear_acc_(std::array<float,3>{{0.0f, 0.0f, 0.0f}}), dt_s_(0.0f), last_update_s_(0.0f) { init_kalman(); internal_state_ = AHRS_INITIALISING; } bool AHRS_ekf::update(void) { bool task_return = true; // Update time in us float now_s = time_keeper_get_s(); // Delta t in seconds dt_s_ = now_s - last_update_s_; last_update_s_ = now_s; // To enable changing of R with onboard parameters. R_acc_(0,0) = config_.R_acc; R_acc_(1,1) = config_.R_acc; R_acc_(2,2) = config_.R_acc; R_acc_norm_(0,0) = config_.R_acc_norm; R_acc_norm_(1,1) = config_.R_acc_norm; R_acc_norm_(2,2) = config_.R_acc_norm; R_mag_(0,0) = config_.R_mag; R_mag_(1,1) = config_.R_mag; R_mag_(2,2) = config_.R_mag; if (imu_.is_ready()) { internal_state_ = AHRS_READY; predict_step(); if (config_.use_accelerometer) { update_step_acc(); } if (config_.use_magnetometer) { update_step_mag(); } } else { internal_state_ = AHRS_LEVELING; // Follow accelerometer and magnetometer blindly during IMU calibration R_acc_ = Mat<3,3>(0.1f,true); R_mag_ = Mat<3,3>(10.0f,true); P_ = Mat<7,7>(1.0f,true); if (config_.use_accelerometer) { update_step_acc(); } if (config_.use_magnetometer) { update_step_mag(); } Mat<7,1> state_previous = x_; // Re-init kalman to keep covariance high: ie we follow the raw accelero and magneto without // believing them. // This allows the filter to re-converge quickly after an imu calibration init_kalman(); for (int i = 3; i < 7; ++i) { x_(i,0) = state_previous(i,0); } } // Attitude attitude_.s = x_(3,0); attitude_.v[0] = x_(4,0); attitude_.v[1] = x_(5,0); attitude_.v[2] = x_(6,0); // Angular speed angular_speed_[X] = imu_.gyro()[X] - x_(0,0); angular_speed_[Y] = imu_.gyro()[Y] - x_(1,0); angular_speed_[Z] = imu_.gyro()[Z] - x_(2,0); // Linear acceleration float up[3] = {0.0f, 0.0f, -1.0f}; float up_bf[3]; quaternions_rotate_vector(quaternions_inverse(attitude_), up, up_bf); linear_acc_[X] = 9.81f * (imu_.acc()[X] - up_bf[X]); linear_acc_[Y] = 9.81f * (imu_.acc()[Y] - up_bf[Y]); linear_acc_[Z] = 9.81f * (imu_.acc()[Z] - up_bf[Z]); return task_return; } float AHRS_ekf::last_update_s(void) const { return last_update_s_; } bool AHRS_ekf::is_healthy(void) const { return (internal_state_ == AHRS_READY); } quat_t AHRS_ekf::attitude(void) const { return attitude_; } std::array<float,3> AHRS_ekf::angular_speed(void) const { return angular_speed_; } std::array<float,3> AHRS_ekf::linear_acceleration(void) const { return linear_acc_; } //------------------------------------------------------------------------------ // PRIVATE FUNCTIONS IMPLEMENTATION //------------------------------------------------------------------------------ void AHRS_ekf::init_kalman(void) { P_ = Mat<7,7>(1.0f,true); // Initalisation of the state x_(0,0) = 0.0f; x_(1,0) = 0.0f; x_(2,0) = 0.0f; x_(3,0) = 1.0f; x_(4,0) = 0.0f; x_(5,0) = 0.0f; x_(6,0) = 0.0f; R_acc_ = Mat<3,3>(config_.R_acc,true); R_mag_ = Mat<3,3>(config_.R_mag,true); } void AHRS_ekf::predict_step(void) { float dt = dt_s_; float dt2_2 = dt * dt * 0.5f; float dt3_3 = dt * dt * dt / 3.0f; float w_x = imu_.gyro()[X]; float w_z = imu_.gyro()[Z]; float w_y = imu_.gyro()[Y]; float w_sqr = w_x*w_x + w_y*w_y + w_z*w_z; Mat<7,1> x_k1k1 = x_; Mat<7,1> x_kk1; // x(k,k-1) = f(x(k-1,k-1),u(k)); // with zero-order Taylor expansion x_kk1(0,0) = x_k1k1(0,0); x_kk1(1,0) = x_k1k1(1,0); x_kk1(2,0) = x_k1k1(2,0); x_kk1(3,0) = x_k1k1(3,0) + 0.5f* (-(w_x-x_k1k1(0,0))*x_k1k1(4,0) - (w_y-x_k1k1(1,0))*x_k1k1(5,0) - (w_z-x_k1k1(2,0))*x_k1k1(6,0)) * dt; x_kk1(4,0) = x_k1k1(4,0) + 0.5f* ((w_x-x_k1k1(0,0))*x_k1k1(3,0) + (w_z-x_k1k1(2,0))*x_k1k1(5,0) - (w_y-x_k1k1(1,0))*x_k1k1(6,0)) * dt; x_kk1(5,0) = x_k1k1(5,0) + 0.5f* ((w_y-x_k1k1(1,0))*x_k1k1(3,0) - (w_z-x_k1k1(2,0))*x_k1k1(4,0) + (w_x-x_k1k1(0,0))*x_k1k1(6,0)) * dt; x_kk1(6,0) = x_k1k1(6,0) + 0.5f* ((w_z-x_k1k1(2,0))*x_k1k1(3,0) + (w_y-x_k1k1(1,0))*x_k1k1(4,0) - (w_x-x_k1k1(0,0))*x_k1k1(5,0)) * dt; // F_(k,k-1) = I + jacobian(x(k-1),u(k))*dt; F_(0,0) = 1.0f; F_(1,1) = 1.0f; F_(2,2) = 1.0f; F_(3,0) = x_k1k1(4,0) * dt; F_(3,1) = x_k1k1(5,0) * dt; F_(3,2) = x_k1k1(6,0) * dt; F_(3,3) = 1.0f; // 1.0f + 0.0f; F_(3,4) = -(w_x-x_k1k1(0,0)) * dt; F_(3,5) = -(w_y-x_k1k1(1,0)) * dt; F_(3,6) = -(w_z-x_k1k1(2,0)) * dt; F_(4,0) = -x_k1k1(3,0) * dt; F_(4,1) = x_k1k1(6,0) * dt; F_(4,2) = -x_k1k1(5,0) * dt; F_(4,3) = (w_x-x_k1k1(0,0)) * dt; F_(4,4) = 1.0f; // 1.0f + 0.0f; F_(4,5) = (w_z-x_k1k1(2,0)) * dt; F_(4,6) = -(w_y-x_k1k1(1,0)) * dt; F_(5,0) = -x_k1k1(6,0) * dt; F_(5,1) = -x_k1k1(3,0) * dt; F_(5,2) = x_k1k1(4,0) * dt; F_(5,3) = (w_y-x_k1k1(1,0)) * dt; F_(5,4) = -(w_z-x_k1k1(2,0)) * dt; F_(5,5) = 1.0f; // 1.0f + 0.0f; F_(5,6) = (w_x-x_k1k1(0,0)) * dt; F_(6,0) = x_k1k1(5,0) * dt; F_(6,1) = -x_k1k1(4,0) * dt; F_(6,2) = -x_k1k1(3,0) * dt; F_(6,3) = (w_z-x_k1k1(2,0)) * dt; F_(6,4) = (w_y-x_k1k1(1,0)) * dt; F_(6,5) = -(w_x-x_k1k1(0,0)) * dt; F_(6,6) = 1.0f; // 1.0f + 0.0f; // Q(k) = cov(del_w * del_w^T) Q_(0,0) = config_.sigma_w_sqr * dt; Q_(0,1) = 0.0f; Q_(0,2) = 0.0f; Q_(0,3) = x_kk1[4] * dt2_2 * config_.sigma_w_sqr; Q_(0,4) = -x_kk1[3] * dt2_2 * config_.sigma_w_sqr; Q_(0,5) = -x_kk1[6] * dt2_2 * config_.sigma_w_sqr; Q_(0,6) = x_kk1[5] * dt2_2 * config_.sigma_w_sqr; Q_(1,0) = 0.0f; Q_(1,1) = config_.sigma_w_sqr * dt; Q_(1,2) = 0.0f; Q_(1,3) = x_kk1[5] * dt2_2 * config_.sigma_w_sqr; Q_(1,4) = x_kk1[6] * dt2_2 * config_.sigma_w_sqr; Q_(1,5) = -x_kk1[3] * dt2_2 * config_.sigma_w_sqr; Q_(1,6) = -x_kk1[4] * dt2_2 * config_.sigma_w_sqr; Q_(2,0) = 0.0f; Q_(2,1) = 0.0f; Q_(2,2) = config_.sigma_w_sqr * dt; Q_(2,3) = x_kk1[6] * dt2_2 * config_.sigma_w_sqr; Q_(2,4) = -x_kk1[5] * dt2_2 * config_.sigma_w_sqr; Q_(2,5) = x_kk1[4] * dt2_2 * config_.sigma_w_sqr; Q_(2,6) = -x_kk1[3] * dt2_2 * config_.sigma_w_sqr; Q_(3,0) = x_kk1[4] * dt2_2 * config_.sigma_w_sqr; Q_(3,1) = x_kk1[5] * dt2_2 * config_.sigma_w_sqr; Q_(3,2) = x_kk1[6] * dt2_2 * config_.sigma_w_sqr; Q_(3,3) = config_.sigma_r_sqr * dt + w_sqr * config_.sigma_r_sqr * dt3_3 + (x_kk1[4]*x_kk1[4]+x_kk1[5]*x_kk1[5]+x_kk1[6]*x_kk1[6])*config_.sigma_w_sqr*dt3_3; Q_(3,4) = -x_kk1[3] * x_kk1[4] * dt3_3 * config_.sigma_w_sqr; Q_(3,5) = -x_kk1[3] * x_kk1[5] * dt3_3 * config_.sigma_w_sqr; Q_(3,6) = -x_kk1[3] * x_kk1[6] * dt3_3 * config_.sigma_w_sqr; Q_(4,0) = -x_kk1[3] * dt2_2 * config_.sigma_w_sqr; Q_(4,1) = x_kk1[6] * dt2_2 * config_.sigma_w_sqr; Q_(4,2) = -x_kk1[5] * dt2_2 * config_.sigma_w_sqr; Q_(4,3) = -x_kk1[4] * x_kk1[3] * dt3_3 * config_.sigma_w_sqr; Q_(4,4) = config_.sigma_r_sqr * dt + w_sqr * config_.sigma_r_sqr * dt3_3 + (x_kk1[3]*x_kk1[3]+x_kk1[5]*x_kk1[5]+x_kk1[6]*x_kk1[6])*config_.sigma_w_sqr*dt3_3; Q_(4,5) = -x_kk1[4] * x_kk1[5] * dt3_3 * config_.sigma_w_sqr; Q_(4,6) = -x_kk1[4] * x_kk1[6] * dt3_3 * config_.sigma_w_sqr; Q_(5,0) = -x_kk1[6] * dt2_2 * config_.sigma_w_sqr; Q_(5,1) = -x_kk1[3] * dt2_2 * config_.sigma_w_sqr; Q_(5,2) = x_kk1[4] * dt2_2 * config_.sigma_w_sqr; Q_(5,3) = -x_kk1[5] * x_kk1[3] * dt3_3 * config_.sigma_w_sqr; Q_(5,4) = -x_kk1[5] * x_kk1[4] * dt3_3 * config_.sigma_w_sqr; Q_(5,5) = config_.sigma_r_sqr * dt + w_sqr * config_.sigma_r_sqr * dt3_3 + (x_kk1[3]*x_kk1[3]+x_kk1[4]*x_kk1[4]+x_kk1[6]*x_kk1[6])*config_.sigma_w_sqr*dt3_3; Q_(5,6) = -x_kk1[5] * x_kk1[6] * dt3_3 * config_.sigma_w_sqr; Q_(6,0) = x_kk1[5] * dt2_2 * config_.sigma_w_sqr; Q_(6,1) = -x_kk1[4] * dt2_2 * config_.sigma_w_sqr; Q_(6,2) = -x_kk1[3] * dt2_2 * config_.sigma_w_sqr; Q_(6,3) = -x_kk1[6] * x_kk1[3] * dt3_3 * config_.sigma_w_sqr; Q_(6,4) = -x_kk1[6] * x_kk1[4] * dt3_3 * config_.sigma_w_sqr; Q_(6,5) = -x_kk1[6] * x_kk1[5] * dt3_3 * config_.sigma_w_sqr; Q_(6,6) = config_.sigma_r_sqr * dt + w_sqr * config_.sigma_r_sqr * dt3_3 + (x_kk1[3]*x_kk1[3]+x_kk1[4]*x_kk1[4]+x_kk1[5]*x_kk1[5])*config_.sigma_w_sqr*dt3_3; // P_(k,k-1) = F_(k)*P_(k-1,k-1)*F_(k)' + Q_(k) P_ = (F_ % P_ % F_.transpose()) + Q_; quat_t quat; quat.s = x_kk1(3,0); quat.v[0] = x_kk1(4,0); quat.v[1] = x_kk1(5,0); quat.v[2] = x_kk1(6,0); quat = quaternions_normalise(quat); x_ = x_kk1; x_(3,0) = quat.s; x_(4,0) = quat.v[0]; x_(5,0) = quat.v[1]; x_(6,0) = quat.v[2]; } void AHRS_ekf::update_step_acc(void) { uint16_t i; Mat<7,1> x_kk1 = x_; Mat<3,1> z_acc; for (i = 0; i < 3; ++i) { z_acc(i,0) = imu_.acc()[i]; } float acc_z_global = -1.0f; // h_acc(x(k,k-1)) // These equations come from rotating the gravity vector to the local frame Mat<3,1> h_acc_xkk1; h_acc_xkk1(0,0) = 2.0f*(-x_kk1(3,0)*x_kk1(5,0) + x_kk1(4,0)*x_kk1(6,0)) * acc_z_global; h_acc_xkk1(1,0) = 2.0f*(x_kk1(3,0)*x_kk1(4,0) + x_kk1(5,0)*x_kk1(6,0)) * acc_z_global; h_acc_xkk1(2,0) = (1.0f - 2.0f*(x_kk1(4,0)*x_kk1(4,0) + x_kk1(5,0)*x_kk1(5,0))) * acc_z_global; // H_acc(k) = jacobian(h_acc(x(k,k-1))) Mat<3,7> H_acc_k; H_acc_k(0,3) = -2.0f * x_kk1(5,0) * acc_z_global; H_acc_k(0,4) = 2.0f * x_kk1(6,0) * acc_z_global; H_acc_k(0,5) = -2.0f * x_kk1(3,0) * acc_z_global; H_acc_k(0,6) = 2.0f * x_kk1(4,0) * acc_z_global; H_acc_k(1,3) = 2.0f * x_kk1(4,0) * acc_z_global; H_acc_k(1,4) = 2.0f * x_kk1(3,0) * acc_z_global; H_acc_k(1,5) = 2.0f * x_kk1(6,0) * acc_z_global; H_acc_k(1,6) = 2.0f * x_kk1(5,0) * acc_z_global; H_acc_k(2,3) = 0.0f; H_acc_k(2,4) = -4.0f * x_kk1(4,0) * acc_z_global; H_acc_k(2,5) = -4.0f * x_kk1(5,0) * acc_z_global; H_acc_k(2,6) = 0.0f; // Innovation y(k) = z(k) - h(x(k,k-1)) Mat<3,1> yk_acc = z_acc - h_acc_xkk1; // Innovation covariance S(k) = H(k) * P_(k,k-1) * H(k)' + R Mat<3,3> Sk_acc = (H_acc_k % P_ % H_acc_k.transpose()) + R_acc_ + R_acc_norm_ * maths_f_abs(1.0f - vectors_norm(imu_.acc().data())); // Kalman gain: K(k) = P_(k,k-1) * H(k)' * S(k)^-1 Mat<3,3> Sk_inv; op::inverse(Sk_acc, Sk_inv); Mat<7,3> K_acc = P_ % (H_acc_k.transpose() % Sk_inv); // Updated state estimate: x(k,k) = x(k,k-1) + K(k)*y_k Mat<7,1> x_kk = x_kk1 + (K_acc % yk_acc); quat_t quat; quat.s = x_kk(3,0); quat.v[0] = x_kk(4,0); quat.v[1] = x_kk(5,0); quat.v[2] = x_kk(6,0); quat = quaternions_normalise(quat); x_ = x_kk; x_(3,0) = quat.s; x_(4,0) = quat.v[0]; x_(5,0) = quat.v[1]; x_(6,0) = quat.v[2]; // Update covariance estimate P_ = (I_ - (K_acc % H_acc_k)) % P_; } void AHRS_ekf::update_step_mag(void) { uint16_t i; Mat<7,1> x_kk1 = x_; std::array<float, 3> mag_global = imu_.magnetic_north(); Mat<3,1> z_mag; for (i = 0; i < 3; ++i) { z_mag(i,0) = imu_.mag()[i]; } // h_mag(x(k,k-1)) Mat<3,1> h_mag_xkk1; h_mag_xkk1(0,0) = (1.0f + 2.0f*(-x_kk1(5,0)*x_kk1(5,0) - x_kk1(6,0)*x_kk1(6,0)))* mag_global[0] + 2.0f*( x_kk1(3,0)*x_kk1(6,0) + x_kk1(4,0)*x_kk1(5,0)) * mag_global[1] + 2.0f*( x_kk1(4,0)*x_kk1(6,0) - x_kk1(3,0)*x_kk1(5,0)) * mag_global[2]; h_mag_xkk1(1,0) = 2.0f*( x_kk1(4,0)*x_kk1(5,0) - x_kk1(3,0)*x_kk1(6,0)) * mag_global[0] + (1.0f + 2.0f*(-x_kk1(4,0)*x_kk1(4,0) - x_kk1(6,0)*x_kk1(6,0)))* mag_global[1] + 2.0f*( x_kk1(5,0)*x_kk1(6,0) + x_kk1(3,0)*x_kk1(4,0)) * mag_global[2]; h_mag_xkk1(2,0) = 2.0f*( x_kk1(4,0)*x_kk1(6,0) + x_kk1(3,0)*x_kk1(5,0)) * mag_global[0] + 2.0f*( x_kk1(5,0)*x_kk1(6,0) - x_kk1(3,0)*x_kk1(4,0)) * mag_global[1] + (1.0f + 2.0f*(-x_kk1(4,0)*x_kk1(4,0) - x_kk1(5,0)*x_kk1(5,0)))* mag_global[2]; Mat<3,7> H_mag_k; H_mag_k(0,3) = 2.0f*x_kk1(6,0)*mag_global[1] - 2.0f*x_kk1(5,0)*mag_global[2]; H_mag_k(0,4) = 2.0f*x_kk1(5,0)*mag_global[1] + 2.0f*x_kk1(6,0)*mag_global[2]; H_mag_k(0,5) = -4.0f*x_kk1(5,0)*mag_global[0] + 2.0f*x_kk1(4,0)*mag_global[1] - 2.0f*x_kk1(3,0)*mag_global[2]; H_mag_k(0,6) = -4.0f*x_kk1(6,0)*mag_global[0] + 2.0f*x_kk1(3,0)*mag_global[1] + 2.0f*x_kk1(4,0)*mag_global[2]; H_mag_k(1,3) = -2.0f*x_kk1(6,0)*mag_global[0] + 2.0f*x_kk1(4,0)*mag_global[2]; H_mag_k(1,4) = 2.0f*x_kk1(5,0)*mag_global[0] - 4.0f*x_kk1(4,0)*mag_global[1] + 2.0f*x_kk1(3,0)*mag_global[2]; H_mag_k(1,5) = 2.0f*x_kk1(4,0)*mag_global[0] + 2.0f*x_kk1(6,0)*mag_global[2]; H_mag_k(1,6) = -2.0f*x_kk1(3,0)*mag_global[0] - 4.0f*x_kk1(6,0)*mag_global[1] + 2.0f*x_kk1(5,0)*mag_global[2]; H_mag_k(2,3) = 2.0f*x_kk1(5,0)*mag_global[0] - 2.0f*x_kk1(4,0)*mag_global[1]; H_mag_k(2,4) = 2.0f*x_kk1(6,0)*mag_global[0] - 2.0f*x_kk1(3,0)*mag_global[1] - 4.0f*x_kk1(4,0)*mag_global[2]; H_mag_k(2,5) = 2.0f*x_kk1(3,0)*mag_global[0] + 2.0f*x_kk1(6,0)*mag_global[1] - 4.0f*x_kk1(5,0)*mag_global[2]; H_mag_k(2,6) = 2.0f*x_kk1(4,0)*mag_global[0] + 2.0f*x_kk1(5,0)*mag_global[1]; // Innovation y(k) = z(k) - h(x(k,k-1)) Mat<3,1> yk_mag = z_mag - h_mag_xkk1; // Innovation covariance S(k) = H(k) * P_(k,k-1) * H(k)' + R Mat<3,3> Sk_mag = (H_mag_k % P_ % H_mag_k.transpose()) + R_mag_; // Kalman gain: K(k) = P_(k,k-1) * H(k)' * S(k)^-1 Mat<3,3> Sk_inv; op::inverse(Sk_mag, Sk_inv); Mat<7,3> K_mag = P_ % (H_mag_k.transpose() % Sk_inv); // Updated state estimate: x(k,k) = x(k,k-1) + K(k)*y_k Mat<7,1> x_kk = x_kk1 + (K_mag % yk_mag); //Mat<7,1> x_kk = x_kk1; quat_t quat; quat.s = x_kk(3,0); quat.v[0] = x_kk(4,0); quat.v[1] = x_kk(5,0); quat.v[2] = x_kk(6,0); quat = quaternions_normalise(quat); x_ = x_kk; x_(3,0) = quat.s; x_(4,0) = quat.v[0]; x_(5,0) = quat.v[1]; x_(6,0) = quat.v[2]; // Update covariance estimate P_ = (I_ - (K_mag % H_mag_k)) % P_; }
34.316306
260
0.558768
[ "vector" ]
ca471954a989bb0d9dd9370c428684ff0ec40ecc
594
cpp
C++
Wrapper/Entity.cpp
AdamJHowell/CLIExample
ba4cebbb670b51f111a8fb7c0053d4fe508231c1
[ "MIT" ]
1
2022-01-21T10:16:12.000Z
2022-01-21T10:16:12.000Z
Wrapper/Entity.cpp
AdamJHowell/CLIExample
ba4cebbb670b51f111a8fb7c0053d4fe508231c1
[ "MIT" ]
null
null
null
Wrapper/Entity.cpp
AdamJHowell/CLIExample
ba4cebbb670b51f111a8fb7c0053d4fe508231c1
[ "MIT" ]
null
null
null
//Entity.cpp #include "Entity.h" namespace CLI { Entity::Entity( String^ name, int xPos, int yPos ) : ManagedObject( new Core::Entity( string_to_char_array( name ), xPos, yPos ) ) { Console::WriteLine( "Creating a new Entity-wrapper object!" ); } void Entity::Move( int deltaX, int deltaY ) { Console::WriteLine( "The Move method from the Wrapper was called!" ); m_Instance->Move( deltaX, deltaY ); } void Entity::TypeAhead( std::string words, int count ) { Console::WriteLine( "The Wrapper is trying to call TypeAhead()!" ); m_Instance->TypeAhead( words, count ); } }
23.76
81
0.681818
[ "object" ]
ca50fa960c39381c962d63da2750510f19ef02a4
3,514
cpp
C++
src/common/transformations/src/transformations/op_conversions/convert_pad_to_group_conv.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
2
2021-12-14T15:27:46.000Z
2021-12-14T15:34:16.000Z
src/common/transformations/src/transformations/op_conversions/convert_pad_to_group_conv.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
33
2021-09-23T04:14:30.000Z
2022-01-24T13:21:32.000Z
src/common/transformations/src/transformations/op_conversions/convert_pad_to_group_conv.cpp
kurylo/openvino
4da0941cd2e8f9829875e60df73d3cd01f820b9c
[ "Apache-2.0" ]
11
2021-11-09T00:51:40.000Z
2021-11-10T12:04:16.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "transformations/op_conversions/convert_pad_to_group_conv.hpp" #include <memory> #include <ngraph/opsets/opset4.hpp> #include <ngraph/pattern/op/pattern.hpp> #include <ngraph/pattern/op/wrap_type.hpp> #include <ngraph/rt_info.hpp> #include <vector> #include "itt.hpp" ngraph::pass::ConvertPadToGroupConvolution::ConvertPadToGroupConvolution() { MATCHER_SCOPE(ConvertPadToGroupConvolution); auto neg = ngraph::pattern::wrap_type<opset4::Pad>(pattern::has_static_dim(1)); ngraph::matcher_pass_callback callback = [this](pattern::Matcher& m) { auto pad = std::dynamic_pointer_cast<ngraph::opset4::Pad>(m.get_match_root()); if (!pad) { return false; } auto input = pad->input_value(0); const auto& channel_dim = input.get_partial_shape()[1].get_length(); const auto& rank = input.get_partial_shape().rank().get_length(); if (rank < 4) { // We can not create Convolution without spatial dimensions. // Also creating Convolution with single spatial dimension won't be effective as // we later insert additional Reshape operations. return false; } // Check that Pad has CONSTANT mode and value is equal to 0 if 4th input exists if (pad->get_pad_mode() != op::PadMode::CONSTANT) { return false; } if (pad->inputs().size() == 4) { if (auto pad_value = std::dynamic_pointer_cast<opset4::Constant>(pad->input_value(3).get_node_shared_ptr())) { // pad value is a scalar if (pad_value->cast_vector<float>()[0] != 0) { return false; } } } // Check that Pad has padding only for spatial dimensions const auto& pad_begin = pad->get_pads_begin(); const auto& pad_end = pad->get_pads_end(); if (pad_begin.empty() || pad_end.empty()) { // pads will be empty if inputs are not constants return false; } // Check that not spatial dimension are not padded if (std::any_of(pad_begin.begin(), pad_begin.begin() + 2, [](ptrdiff_t value) { return value != 0; }) || std::any_of(pad_end.begin(), pad_end.begin() + 2, [](ptrdiff_t value) { return value != 0; })) { return false; } // Create fake weights with ones GOIXY Shape weights_shape(rank + 1, 1); weights_shape[0] = channel_dim; // G dimension auto weights = opset4::Constant::create(pad->input(0).get_element_type(), weights_shape, {1}); // Create GroupConvolution attributes Strides stride(rank - 2, 1); CoordinateDiff new_pad_begin{pad_begin.begin() + 2, pad_begin.end()}; CoordinateDiff new_pad_end{pad_end.begin() + 2, pad_end.end()}; auto conv = std::make_shared<opset4::GroupConvolution>(input, weights, stride, new_pad_begin, new_pad_end, stride); conv->set_friendly_name(pad->get_friendly_name()); ngraph::copy_runtime_info(pad, conv); ngraph::replace_node(pad, conv); return true; }; auto m = std::make_shared<ngraph::pattern::Matcher>(neg, matcher_name); this->register_matcher(m, callback); }
37.382979
115
0.598463
[ "shape", "vector" ]
ca5176217fdbffb5533d8c5c8162fc72a299a2ca
4,085
cc
C++
epid/member/unittests/presig-test.cc
TinkerBoard-Android/external-epid-sdk
7d6a6b63582f241b4ae4248bab416277ed659968
[ "Apache-2.0" ]
1
2019-04-15T16:27:54.000Z
2019-04-15T16:27:54.000Z
epid/member/unittests/presig-test.cc
TinkerBoard-Android/external-epid-sdk
7d6a6b63582f241b4ae4248bab416277ed659968
[ "Apache-2.0" ]
null
null
null
epid/member/unittests/presig-test.cc
TinkerBoard-Android/external-epid-sdk
7d6a6b63582f241b4ae4248bab416277ed659968
[ "Apache-2.0" ]
null
null
null
/*############################################################################ # Copyright 2016-2017 Intel Corporation # # 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. ############################################################################*/ /*! * \file * \brief ComputePreSig unit tests. */ #include <algorithm> #include <cstring> #include <limits> #include <vector> #include "epid/common-testhelper/epid_gtest-testhelper.h" #include "gtest/gtest.h" extern "C" { #include "epid/member/api.h" } #include "epid/common-testhelper/errors-testhelper.h" #include "epid/common-testhelper/prng-testhelper.h" #include "epid/member/unittests/member-testhelper.h" /// Count of elements in array #define COUNT_OF(A) (sizeof(A) / sizeof((A)[0])) namespace { /////////////////////////////////////////////////////////////////////// // EpidAddPreSigs TEST_F(EpidMemberTest, AddPreSigsFailsGivenNullPointer) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); EXPECT_EQ(kEpidBadArgErr, EpidAddPreSigs(nullptr, 1)); } TEST_F(EpidMemberTest, AddPreSigsFailsGivenHugeNumberOfPreSigs) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); // number_presigs = 0x80..01 of size equal to sizeof(size_t) EXPECT_NE(kEpidNoErr, EpidAddPreSigs(member, (SIZE_MAX >> 1) + 2)); } TEST_F(EpidMemberTest, AddPreSigsComputesSpecifiedNumberOfPresigsIfInputPresigsNull) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); ASSERT_EQ(kEpidNoErr, EpidAddPreSigs(member, 2)); ASSERT_EQ(kEpidNoErr, EpidAddPreSigs(member, 1)); // request to generate 0 pre-computed signatures do nothing ASSERT_EQ(kEpidNoErr, EpidAddPreSigs(member, 0)); EXPECT_EQ((size_t)3, EpidGetNumPreSigs(member)); } TEST_F(EpidMemberTest, AddPreSigsAddsCorrectNumberOfPresigsGivenValidInput) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); const size_t presigs1_added = 2; const size_t presigs2_added = 3; // add ASSERT_EQ(kEpidNoErr, EpidAddPreSigs(member, presigs1_added)); // extend ASSERT_EQ(kEpidNoErr, EpidAddPreSigs(member, presigs2_added)); // add empty pre-computed signatures array does not affect internal pool ASSERT_EQ(kEpidNoErr, EpidAddPreSigs(member, 0)); EXPECT_EQ(presigs1_added + presigs2_added, EpidGetNumPreSigs(member)); } /////////////////////////////////////////////////////////////////////// // EpidGetNumPreSigs TEST_F(EpidMemberTest, GetNumPreSigsReturnsZeroGivenNullptr) { EXPECT_EQ((size_t)0, EpidGetNumPreSigs(nullptr)); } TEST_F(EpidMemberTest, NumPreSigsForNewleyCreatedContextIsZero) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); EXPECT_EQ((size_t)0, EpidGetNumPreSigs(member)); } TEST_F(EpidMemberTest, GetNumPreSigsReturnsNumberOfAddedPresigs) { Prng my_prng; MemberCtxObj member(this->kGroupPublicKey, this->kMemberPrivateKey, this->kMemberPrecomp, &Prng::Generate, &my_prng); const size_t presigs_added = 5; THROW_ON_EPIDERR(EpidAddPreSigs(member, presigs_added)); EXPECT_EQ(presigs_added, EpidGetNumPreSigs(member)); } } // namespace
34.91453
80
0.685924
[ "vector" ]
ca5401dd2553f8c00e8418abb50b1a9e5aae7521
2,439
cpp
C++
bak/N2_network.cpp
Atomtomate/sys_risk
b47cd40a7fec1305dbe70fde9b94815b41939b5c
[ "MIT" ]
null
null
null
bak/N2_network.cpp
Atomtomate/sys_risk
b47cd40a7fec1305dbe70fde9b94815b41939b5c
[ "MIT" ]
null
null
null
bak/N2_network.cpp
Atomtomate/sys_risk
b47cd40a7fec1305dbe70fde9b94815b41939b5c
[ "MIT" ]
null
null
null
/* Copyright (C) 5/23/18 Julian Stobbe - All Rights Reserved * You may use, distribute and modify this code under the * terms of the MIT license. * * You should have received a copy of the MIT license with * this file. */ #include "N2_network.hpp" void N2_network::test_N2_valuation() { //@TODO: acc std::vector MCUtil::Sampler<std::vector<double>> S; const int N = 2; auto f_dist = std::bind(&N2_network::draw_from_dist, this); auto f_run = std::bind(&N2_network::run, this, std::placeholders::_1); /* std::function<std::vector<double>(void)> assets_obs = std::bind(&BlackScholesNetwork::get_assets, &bsn); std::function<std::vector<double>(void)> rs_obs = std::bind(&BlackScholesNetwork::get_rs, &bsn); std::function<std::vector<double>(void)> sol_obs = std::bind(&BlackScholesNetwork::get_solvent, &bsn); std::function<std::vector<double>(void)> valuation_obs = std::bind(&BlackScholesNetwork::get_valuation, &bsn); std::function<std::vector<double>(void)> deltav1_obs = std::bind(&BlackScholesNetwork::get_delta_v1, &bsn); std::function<std::vector<double>(void)> deltav2_obs = std::bind(&N2_network::delta_v2, this); // usage: register std::function with no parameters and boost::accumulator compatible return value. 2nd,... parameters are used to construct accumulator //S.register_observer(assets_obs, 2); //S.register_observer(rs_obs, 4); //S.register_observer(sol_obs, 2); /*S.register_observer(valuation_obs, "Valuation", 2); //std::function<std::vector<double>(void)> out_obs = std::bind(&N2_network::test_out, this); //S.register_observer(out_obs, 1); S.register_observer(deltav1_obs, "Delta using Jacobians", 8); S.register_observer(deltav2_obs, "Delta using Log", 2 * N * N); S.draw_samples(f_run, f_dist, 1000); */ LOG(INFO) << "Means: "; auto res = S.extract(MCUtil::StatType::MEAN); for (auto el : res) { Eigen::MatrixXd m; if (el.second.size() > N) { m = Eigen::MatrixXd::Map(&el.second[0], 2 * N, N); LOG(INFO) << el.first << ": " << m; } } LOG(INFO) << "Vars: "; auto res_var = S.extract(MCUtil::StatType::VARIANCE); for (auto el : res_var) { Eigen::MatrixXd m; if (el.second.size() > N) { m = Eigen::MatrixXd::Map(&el.second[0], 2 * N, N); LOG(INFO) << el.first << ": " << m; } } }
39.983607
156
0.637146
[ "vector" ]
ca5452e26c1370d956fd093fcc0b770e026e4766
5,019
cpp
C++
CustomUi/UShadowBorder.cpp
qunarcorp/startalk_pc_v2
59d873ddcd41052d9a1379a9c35cb69075fcef3c
[ "MIT" ]
30
2019-08-22T08:33:23.000Z
2022-03-15T02:04:20.000Z
CustomUi/UShadowBorder.cpp
lirui1111/startalk_pc
7d625f812e784bca68b3d6f6ffe21d383b400491
[ "MIT" ]
4
2019-12-11T08:18:55.000Z
2021-03-19T07:23:50.000Z
CustomUi/UShadowBorder.cpp
lirui1111/startalk_pc
7d625f812e784bca68b3d6f6ffe21d383b400491
[ "MIT" ]
19
2019-08-22T17:09:24.000Z
2021-08-10T08:24:39.000Z
๏ปฟ// // Created by QITMAC000260 on 2019-01-27. // #include <QtCore/QEvent> #include "UShadowBorder.h" #include <QMouseEvent> #include <QDebug> #include <QPainter> #include "UShadowWnd.h" #include "../QtUtil/Utils/Log.h" #define DEM_STYLESHEET_1 "background: qlineargradient(x1:%1, y1:%2, x2:%3, y2:%4,stop:0 rgba(181,181,181,0.3), stop:0.5 rgba(181,181,181,0.1),stop:1 rgba(255,255,255,0));" #define DEM_STYLESHEET_2 "background: qradialgradient(spread:pad, cx:%1, cy:%2, radius:1, fx:%3, fy:%4,stop:0 rgba(181,181,181,0.3), stop:0.5 rgba(181,181,181,0.1),stop:1 rgba(255,255,255,0));" UShadowBorder::UShadowBorder(int borderType, bool isRidus, UShadowDialog* parent) : QFrame(parent) , _type(borderType) , _pControlWgt(parent) , _borderPressed(false) { Q_INIT_RESOURCE(ushadowdialog); setMinimumSize(DEM_FIXSIZE, DEM_FIXSIZE); setFrameShape(QFrame::NoFrame); this->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); QString styleSheet; switch (borderType) { case EM_LEFT: { setFixedWidth(DEM_FIXSIZE); break; } case EM_LEFTTOP: { setFixedSize(DEM_FIXSIZE, DEM_FIXSIZE); break; } case EM_TOP: { setFixedHeight(DEM_FIXSIZE); break; } case EM_RIGHTTOP: { setFixedSize(DEM_FIXSIZE, DEM_FIXSIZE); break; } case EM_RIGHT: { setFixedWidth(DEM_FIXSIZE); break; } case EM_RIGHTBOTTOM: { setFixedSize(DEM_FIXSIZE, DEM_FIXSIZE); break; } case EM_BOTTOM: { setFixedHeight(DEM_FIXSIZE); break; } case EM_LEFTBOTTOM: { // styleSheet = QString(DEM_STYLESHEET_2).arg(1).arg(0).arg(1).arg(0); setFixedSize(DEM_FIXSIZE, DEM_FIXSIZE); break; } default:break; } setStyleSheet(styleSheet); } UShadowBorder::~UShadowBorder() = default; bool UShadowBorder::event(QEvent *e) { if(e->type() == QEvent::Enter) { switch (_type) { case EM_LEFT: case EM_RIGHT: setCursor(Qt::SizeHorCursor); break; case EM_TOP: case EM_BOTTOM: setCursor(Qt::SizeVerCursor); break; case EM_RIGHTBOTTOM: setCursor(Qt::SizeFDiagCursor); break; default: break; } } else if(e->type() == QEvent::Leave) { setCursor(Qt::ArrowCursor); } return QFrame::event(e); } void UShadowBorder::mousePressEvent(QMouseEvent *e) { QPoint pos = QCursor::pos(); _borderPressed = true; _pControlWgt->setResizing(true); _resizeStartPos = QCursor::pos(); QWidget::mousePressEvent(e); } void UShadowBorder::mouseReleaseEvent(QMouseEvent *e) { _borderPressed = false; _pControlWgt->setResizing(false); QWidget::mouseReleaseEvent(e); } void UShadowBorder::mouseMoveEvent(QMouseEvent *e) { // // ไผธ็ผฉ if(_borderPressed) { QPoint pos = QCursor::pos(); int x = pos.x() - _resizeStartPos.x(); int y = pos.y() - _resizeStartPos.y(); //if(abs(x) > 10 || abs(y) > 10) { QRect geo = _pControlWgt->geometry(); switch (_type) { case EM_LEFT: { _resizeStartPos = pos; _pControlWgt->setGeometry(geo.x() + x, geo.y(), geo.width() - x, geo.height()); break; } case EM_TOP: { _resizeStartPos = pos; _pControlWgt->setGeometry(geo.x(), geo.y() + y, geo.width(), geo.height() - y); break; } case EM_RIGHT: { _resizeStartPos = pos; _pControlWgt->setGeometry(geo.x(), geo.y(), geo.width() + x, geo.height()); break; } case EM_RIGHTBOTTOM: { _resizeStartPos = pos; _pControlWgt->setGeometry(geo.x(), geo.y(), geo.width() + x, geo.height() + y); break; } case EM_BOTTOM: { _resizeStartPos = pos; _pControlWgt->setGeometry(geo.x(), geo.y(), geo.width(), geo.height() + y); break; } default: break; } } } QWidget::mouseMoveEvent(e); } void UShadowBorder::paintEvent(QPaintEvent *e) { QPainter painter(this); QRect rect = contentsRect(); painter.setPen(Qt::NoPen); // painter.fillRect(rect, QColor(255,255,255,1)); QFrame::paintEvent(e); }
27.576923
193
0.513449
[ "geometry" ]
ca5615ca90dea9aa13b68e4a6427fbe760813b69
342
cpp
C++
LeetCodeSolutions/LeetCode_0266.cpp
lih627/python-algorithm-templates
a61fd583e33a769b44ab758990625d3381793768
[ "MIT" ]
24
2020-03-28T06:10:25.000Z
2021-11-23T05:01:29.000Z
LeetCodeSolutions/LeetCode_0266.cpp
lih627/python-algorithm-templates
a61fd583e33a769b44ab758990625d3381793768
[ "MIT" ]
null
null
null
LeetCodeSolutions/LeetCode_0266.cpp
lih627/python-algorithm-templates
a61fd583e33a769b44ab758990625d3381793768
[ "MIT" ]
8
2020-05-18T02:43:16.000Z
2021-05-24T18:11:38.000Z
/* * @lc app=leetcode.cn id=266 lang=cpp * * [266] ๅ›žๆ–‡ๆŽ’ๅˆ— */ // @lc code=start class Solution { public: bool canPermutePalindrome(string s) { vector<int> cnt(256, 0); for (auto c: s) ++cnt[c]; int odd = 0; for(auto i: cnt) if(i & 1) ++odd; return odd <= 1; } }; // @lc code=end
16.285714
41
0.491228
[ "vector" ]
3ed66f7b15cd86ae804b54305d4e56d1ab0a3e61
1,154
cpp
C++
src/Universe/World.cpp
nosmanbegovic/LogicToolboxLib
5ec347b3ea4a22759c14b1d483fd65b8d553d423
[ "MIT" ]
null
null
null
src/Universe/World.cpp
nosmanbegovic/LogicToolboxLib
5ec347b3ea4a22759c14b1d483fd65b8d553d423
[ "MIT" ]
null
null
null
src/Universe/World.cpp
nosmanbegovic/LogicToolboxLib
5ec347b3ea4a22759c14b1d483fd65b8d553d423
[ "MIT" ]
2
2020-08-11T17:17:02.000Z
2020-09-25T13:29:34.000Z
// // Created by root on 7/14/17. // #include "../../include/World.h" //Constructors and destructor World::World(string _name) : name(_name) {} World::World(const World &w) : name(w.getName()), variables(w.getVariables()), adjacentList(w.getAdjacentList()) {} //Getters and setters string World::getName() const { return name; } vector<Variable> World::getVariables() const { return variables; } void World::setName(string _name) { name = _name; } void World::setVariables(vector<Variable> _variables) { variables = _variables; } vector<World*> World::getAdjacentList() const { return adjacentList; } void World::setAdjacentList(vector<World*> _adjacentList) { adjacentList = _adjacentList; } //Adjacent operations void World::addAdjacent(World* adj) { for(auto i : adjacentList){ if(i->name == adj->getName()) throw logic_error("World is already adjacent!"); } adjacentList.push_back(adj); } bool World::removeAdjacentByName(string adjName) { //TO BE DONE } bool World::getVariableValueByName(string name) { for(auto variable : variables){ if(variable.getName() == name) return variable.getValue(); } }
30.368421
115
0.70104
[ "vector" ]
3ed8db03bf4d0516dd7fe681e73c57db4c5783bd
4,874
cc
C++
inet/tests/module/lib/RoutingTableLogger.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
null
null
null
inet/tests/module/lib/RoutingTableLogger.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
null
null
null
inet/tests/module/lib/RoutingTableLogger.cc
ntanetani/quisp
003f85746266d2eb62c66883e5b965b654672c70
[ "BSD-3-Clause" ]
1
2021-07-02T13:32:40.000Z
2021-07-02T13:32:40.000Z
// // Copyright (C) 2013 Opensim Ltd. // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program; if not, see <http://www.gnu.org/licenses/>. // #include <fstream> #include "inet/common/INETDefs.h" #include "inet/common/scenario/IScriptable.h" #include "inet/networklayer/contract/IRoutingTable.h" #include "inet/networklayer/contract/IL3AddressType.h" using namespace std; namespace inet { struct DestFilter { vector<L3Address> destAddresses; vector<int> prefixLengths; DestFilter(const char *str); bool matches(IRoute *route); }; DestFilter::DestFilter(const char *str) { if (str) { cStringTokenizer tokenizer(str); while (tokenizer.hasMoreTokens()) { const char *dest = tokenizer.nextToken(); const char *end = strchr(dest, '/'); if (end) { destAddresses.push_back(L3Address(string(dest,end).c_str())); prefixLengths.push_back(atoi(end+1)); } else { L3Address destAddr = L3Address(dest); destAddresses.push_back(destAddr); prefixLengths.push_back(destAddr.getAddressType()->getMaxPrefixLength()); } } } } bool DestFilter::matches(IRoute *route) { if (destAddresses.empty()) return true; for (int i = 0; i < (int)destAddresses.size(); ++i) { L3Address &dest = destAddresses[i]; int prefixLength = prefixLengths[i]; if (route->getDestinationAsGeneric().matches(dest, prefixLength)) return true; } return false; } class INET_API RoutingTableLogger : public cSimpleModule, public IScriptable { ofstream out; protected: virtual void initialize(); virtual void finish(); virtual void processCommand(const cXMLElement &node); private: void dumpRoutes(cModule *node, IRoutingTable *rt, DestFilter &filter); }; Define_Module(RoutingTableLogger); void RoutingTableLogger::initialize() { const char *filename = par("outputFile"); if (filename && (*filename)) { out.open(filename); if (out.fail()) throw cRuntimeError("Failed to open output file: %s", filename); } } void RoutingTableLogger::finish() { out << "END" << endl; } void RoutingTableLogger::processCommand(const cXMLElement &command) { Enter_Method_Silent(); const char *tag = command.getTagName(); if (!strcmp(tag, "dump-routes")) { const char *nodes = command.getAttribute("nodes"); if (!nodes) throw cRuntimeError("missing @nodes attribute"); DestFilter filter(command.getAttribute("dest")); cStringTokenizer tokenizer(nodes); while(tokenizer.hasMoreTokens()) { const char *nodeName = tokenizer.nextToken(); cModule *node = getModuleByPath(nodeName); if (!node) throw cRuntimeError("module '%s' not found at %s", nodeName, command.getSourceLocation()); bool foundRt = false; for (cModule::SubmoduleIterator nl(node); !nl.end(); nl++) { for (cModule::SubmoduleIterator i(*nl); !i.end(); i++) { if (IRoutingTable *rt = dynamic_cast<IRoutingTable*>(*i)) { foundRt = true; dumpRoutes(node, rt, filter); } } } if (!foundRt) throw cRuntimeError("routing table not found in node '%s'", node->getFullPath().c_str()); } } } void RoutingTableLogger::dumpRoutes(cModule *node, IRoutingTable *rt, DestFilter &filter) { out << node->getFullName() << " " << simTime() << endl; for (int i = 0; i < rt->getNumRoutes(); ++i) { IRoute *route = rt->getRoute(i); if (filter.matches(route)) { out << route->getDestinationAsGeneric() << "/" << route->getPrefixLength() << " " << route->getNextHopAsGeneric() << " " << (route->getInterface() ? route->getInterface()->getInterfaceName() : "*") << " " << IRoute::sourceTypeName(route->getSourceType()) << " " << route->getMetric() << endl; } } } } // namespace inet
29.719512
105
0.599713
[ "vector" ]
3ed9eab9ed0af8ae6e5c821b81eaa3fd34067105
3,816
cpp
C++
src/benchmark/pipeline_benchmark.cpp
SKA-ScienceDataProcessor/FastImaging
8103fb4d20434ffdc45dee7471dafc6be66354bb
[ "Apache-2.0" ]
7
2017-02-13T11:21:21.000Z
2020-07-20T16:07:39.000Z
src/benchmark/pipeline_benchmark.cpp
SKA-ScienceDataProcessor/FastImaging
8103fb4d20434ffdc45dee7471dafc6be66354bb
[ "Apache-2.0" ]
15
2016-09-11T11:14:35.000Z
2017-08-29T14:21:46.000Z
src/benchmark/pipeline_benchmark.cpp
SKA-ScienceDataProcessor/FastImaging
8103fb4d20434ffdc45dee7471dafc6be66354bb
[ "Apache-2.0" ]
4
2016-10-28T16:17:08.000Z
2021-12-22T12:11:12.000Z
/** @file pipeline_benchmark.cpp * @brief Test pipeline performance */ #include <armadillo> #include <benchmark/benchmark.h> #include <load_data.h> #include <load_json_config.h> #include <stp.h> // Cmake variable #ifndef _PIPELINE_TESTPATH #define _PIPELINE_TESTPATH 0 #endif std::string data_path(_PIPELINE_DATAPATH); std::string input_npz("simdata_nstep10.npz"); std::string config_path(_PIPELINE_CONFIGPATH); std::string config_file_exact("fastimg_exact_config.json"); std::string config_file_oversampling("fastimg_oversampling_config.json"); stp::SourceFindImage run_pipeline(arma::mat& uvw_lambda, arma::cx_mat& residual_vis, arma::mat& vis_weights, ConfigurationFile& cfg) { stp::PSWF kernel_func(cfg.img_pars.kernel_support); std::pair<arma::Mat<real_t>, arma::Mat<real_t>> result = stp::image_visibilities(kernel_func, residual_vis, vis_weights, uvw_lambda, cfg.img_pars); result.second.reset(); return stp::SourceFindImage(std::move(result.first), cfg.detection_n_sigma, cfg.analysis_n_sigma, cfg.estimate_rms, cfg.find_negative_sources, cfg.sigma_clip_iters, cfg.median_method, cfg.gaussian_fitting, cfg.ccl_4connectivity, cfg.generate_labelmap, cfg.source_min_area, cfg.ceres_diffmethod, cfg.ceres_solvertype); } static void pipeline_kernel_exact_benchmark(benchmark::State& state) { int image_size = state.range(0); //Load simulated data from input_npz arma::mat input_uvw = load_npy_double_array<double>(data_path + input_npz, "uvw_lambda"); arma::cx_mat input_vis = load_npy_complex_array<double>(data_path + input_npz, "vis"); arma::mat input_snr_weights = load_npy_double_array<double>(data_path + input_npz, "snr_weights"); arma::mat skymodel = load_npy_double_array<double>(data_path + input_npz, "skymodel"); // Generate model visibilities from the skymodel and UVW-baselines arma::cx_mat input_model = stp::generate_visibilities_from_local_skymodel(skymodel, input_uvw); // Subtract model-generated visibilities from incoming data arma::cx_mat residual_vis = input_vis - input_model; // Load all configurations from json configuration file ConfigurationFile cfg(config_path + config_file_exact); cfg.img_pars.image_size = image_size; for (auto _ : state) { benchmark::DoNotOptimize(run_pipeline(input_uvw, residual_vis, input_snr_weights, cfg)); } } static void pipeline_kernel_oversampling_benchmark(benchmark::State& state) { int image_size = state.range(0); //Load simulated data from input_npz arma::mat input_uvw = load_npy_double_array<double>(data_path + input_npz, "uvw_lambda"); arma::cx_mat input_vis = load_npy_complex_array<double>(data_path + input_npz, "vis"); arma::mat input_snr_weights = load_npy_double_array<double>(data_path + input_npz, "snr_weights"); arma::mat skymodel = load_npy_double_array<double>(data_path + input_npz, "skymodel"); // Generate model visibilities from the skymodel and UVW-baselines arma::cx_mat input_model = stp::generate_visibilities_from_local_skymodel(skymodel, input_uvw); // Load all configurations from json configuration file ConfigurationFile cfg(config_path + config_file_oversampling); cfg.img_pars.image_size = image_size; // Subtract model-generated visibilities from incoming data arma::cx_mat residual_vis = input_vis - input_model; for (auto _ : state) { benchmark::DoNotOptimize(run_pipeline(input_uvw, residual_vis, input_snr_weights, cfg)); } } BENCHMARK(pipeline_kernel_oversampling_benchmark) ->RangeMultiplier(2) ->Range(1 << 10, 1 << 16) ->Unit(benchmark::kMillisecond); BENCHMARK(pipeline_kernel_exact_benchmark) ->RangeMultiplier(2) ->Range(1 << 10, 1 << 16) ->Unit(benchmark::kMillisecond); BENCHMARK_MAIN();
40.595745
151
0.759172
[ "model" ]
3edc19a093c92e5f07e67e230592aa970e948431
641
cpp
C++
progress/main.cpp
opensvn/boost_learning
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
[ "BSL-1.0" ]
null
null
null
progress/main.cpp
opensvn/boost_learning
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
[ "BSL-1.0" ]
null
null
null
progress/main.cpp
opensvn/boost_learning
7f21551a7f3db38bea2c31d95d0c8b4e00f4537e
[ "BSL-1.0" ]
1
2021-10-01T04:27:44.000Z
2021-10-01T04:27:44.000Z
#include <iostream> #include <vector> #include <boost/progress.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/thread.hpp> using namespace std; int main() { vector<int> v(100); boost::progress_display pd(v.size()); vector<int>::iterator pos; for (pos = v.begin(); pos != v.end(); ++pos) { ++pd; // if someone else uses ostream, progress_display behaves stupid as below. // cout << pos - v.begin() << endl; // pd.restart(v.size()); // pd += (pos - v.begin() + 1); boost::this_thread::sleep(boost::posix_time::millisec(200)); } return 0; }
23.740741
82
0.595944
[ "vector" ]
3edcee45fb56378ed72fd1536b41191ce568ca35
827
cpp
C++
Sprite.cpp
AlparslanErol/War_Game
e18d62a30924e2831a006d5e981f407d3ce26ef8
[ "MIT" ]
1
2021-11-09T17:45:21.000Z
2021-11-09T17:45:21.000Z
Sprite.cpp
AlparslanErol/War_Game
e18d62a30924e2831a006d5e981f407d3ce26ef8
[ "MIT" ]
null
null
null
Sprite.cpp
AlparslanErol/War_Game
e18d62a30924e2831a006d5e981f407d3ce26ef8
[ "MIT" ]
null
null
null
#include"Sprite.h" Sprite::Sprite() { levelSprites = vector<shared_ptr<olc::Sprite>>(); for (int i = 0; i < 7; ++i) levelSprites.push_back(make_shared<olc::Sprite>("Sprites/Level" + to_string(i + 1) + ".png")); manSprite = shared_ptr<olc::Sprite>(); deadSprite = shared_ptr<olc::Sprite>(); zombieSprite = shared_ptr<olc::Sprite>(); zombieSprite_1 = shared_ptr<olc::Sprite>(); bonusSprite = shared_ptr<olc::Sprite>(); manSprite = make_shared<olc::Sprite>("Sprites/ManTrans.png"); deadSprite = make_shared<olc::Sprite>("Sprites/Dead.png"); zombieSprite = make_shared<olc::Sprite>("Sprites/zombie.png"); zombieSprite_1 = make_shared<olc::Sprite>("Sprites/zombie_1.png"); bonusSprite = make_shared<olc::Sprite>("Sprites/firstaid.png"); bonus1Sprite = make_shared<olc::Sprite>("Sprites/shield.png"); }
39.380952
96
0.70133
[ "vector" ]
3edec81de210b3a3147ab63f23d198d9ff101399
39,654
cpp
C++
RainbowNoise/src/Library/Tree.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
24
2016-12-13T09:48:17.000Z
2022-01-13T03:24:45.000Z
RainbowNoise/src/Library/Tree.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
2
2019-03-29T06:44:41.000Z
2019-11-12T03:14:25.000Z
RainbowNoise/src/Library/Tree.cpp
1iyiwei/noise
0d1be2030518517199dff5c7e7514ee072037d59
[ "MIT" ]
8
2016-11-09T15:54:19.000Z
2021-04-08T14:04:17.000Z
/* Tree.cpp Li-Yi Wei 07/09/2008 */ #include <math.h> #include "Tree.hpp" #include "SequentialCounter.hpp" #include "Exception.hpp" Tree::Tree(const DistanceField & distance_field, const ConflictChecker & conflict_checker) : _distance_field(distance_field), _conflict_checker(conflict_checker), _cell_offset(CellOffset(distance_field.Dimension(), conflict_checker)), _conflict_metric_from_checker(1), _pools(distance_field.NumClasses()) { BuildRootCells(Grid::BuildDomainSpec(distance_field.Domain())); if(!InitPoolsWithEmptyLeaves()) { throw Exception("cannot InitPoolsWithEmptyLeaves()"); } } Tree::Tree(const DistanceField & distance_field, const ConflictChecker & conflict_checker, const DomainSpec & spec) : _distance_field(distance_field), _conflict_checker(conflict_checker), _cell_offset(CellOffset(distance_field.Dimension(), conflict_checker)), _conflict_metric_from_checker(0), _pools(distance_field.NumClasses()) { BuildRootCells(spec); if(!InitPoolsWithEmptyLeaves()) { throw Exception("cannot InitPoolsWithEmptyLeaves()"); } } void Tree::BuildRootCells(const DomainSpec & spec) { const int dimension = spec.domain_size.size(); const float cell_size = spec.cell_size; _cells_per_level = vector< vector<Cell *> > (1); _cell_size_per_level = vector<float>(1); _num_cells_per_dimension_per_level = vector< vector<int> >(1); vector<int> num_cells_per_dim_min(dimension); vector<int> num_cells_per_dim_max(dimension); { for(int i = 0; i < dimension; i++) { num_cells_per_dim_min[i] = 0; num_cells_per_dim_max[i] = spec.domain_size[i]-1; if(num_cells_per_dim_max[i] < num_cells_per_dim_min[i]) { num_cells_per_dim_max[i] = num_cells_per_dim_min[i]; } assert(num_cells_per_dim_min[i] <= num_cells_per_dim_max[i]); } } SequentialCounter counter(dimension, num_cells_per_dim_min, num_cells_per_dim_max); counter.Reset(); vector<int> index(dimension); do { counter.Get(index); _cells_per_level[0].push_back(new Cell(*this, 0, index)); } while(counter.Next()); _cell_size_per_level[0] = cell_size; _num_cells_per_dimension_per_level[0] = vector<int>(dimension); { for(unsigned int i = 0; i < _num_cells_per_dimension_per_level[0].size(); i++) { _num_cells_per_dimension_per_level[0][i] = num_cells_per_dim_max[i]+1; } } } Tree::~Tree(void) { // release all cells for(unsigned int level = 0; level < _cells_per_level.size(); level++) { for(unsigned int i = 0; i < _cells_per_level[level].size(); i++) { if(_cells_per_level[level][i]) { delete _cells_per_level[level][i]; _cells_per_level[level][i] = 0; } } } _cells_per_level.clear(); _cell_size_per_level.clear(); _num_cells_per_dimension_per_level.clear(); } const DistanceField & Tree::GetDistanceField(void) const { return _distance_field; } const ConflictChecker & Tree::GetConflictChecker(void) const { return _conflict_checker; } int Tree::Dimension(void) const { return _distance_field.Dimension(); } int Tree::NumLevels(void) const { return _cells_per_level.size(); } float Tree::CellSize(const int level) const { if((level >= 0) && (level < NumLevels())) { return _cell_size_per_level[level]; } else { return -1; } } int Tree::NumCells(const int level) const { if((level >= 0) && (level < NumLevels())) { return _cells_per_level[level].size(); } else { return -1; } } int Tree::GetNumCellsPerDimension(const int level, vector<int> & answer) const { if((level >= 0) && (static_cast<unsigned int>(level) < _num_cells_per_dimension_per_level.size())) { answer = _num_cells_per_dimension_per_level[level]; return 1; } else { return 0; } } int Tree::Conflict(const Sample & sample) const { return Conflict(sample, 1); } int Tree::Conflict(const Sample & sample, const int same_tree) const { int level = 0; const Cell * cell = LocateCell(sample, level); if(! cell) { throw Exception("Tree::Conflict(): cannot locate cell containing sample"); return 0; } else { return cell->Conflict(sample, same_tree); } } int Tree::Add(const Sample & sample) { int level = 0; Cell * cell = LocateCell(sample, level); if(! cell) return 0; return cell->Add(sample); } int Tree::Remove(const Sample & sample) { int level = 0; Cell * cell = LocateCell(sample, level); if(! cell) return 0; return cell->Remove(sample); } int Tree::AddDeadZone(const Sample & sample) { int level = 0; Cell * cell = LocateCell(sample, level); if(! cell) return 0; return cell->AddDeadZone(sample); } int Tree::RemoveDeadZone(const Sample & sample) { int level = 0; Cell * cell = LocateCell(sample, level); if(! cell) return 0; return cell->RemoveDeadZone(sample); } int Tree::GetVisitCount(const int class_id) const { if((class_id >= 0) && (class_id < _pools.size())) { return _pools[class_id].GetVisitCount(); } else { throw Exception("Tree::GetVisitCount() : illegal class_id"); return -1; } } int Tree::GetCells(const int level, vector<Cell *> & cells) { if((level >= 0) && (level < NumLevels())) { cells = _cells_per_level[level]; return 1; } else { return 0; } } int Tree::GetCells(const int level, vector<const Cell *> & cells) const { if((level >= 0) && (level < NumLevels())) { if(cells.size() != _cells_per_level[level].size()) { cells = vector<const Cell *>(_cells_per_level[level].size()); } for(unsigned int i = 0; i < cells.size(); i++) { cells[i] = _cells_per_level[level][i]; } return 1; } else { return 0; } } int Tree::GetPossibleCells(const int class_id, vector<Cell *> & cells) { vector<const Cell *> const_cells; if((class_id >= 0) && (class_id < _pools.size())) { if(_pools[class_id].GetCells(const_cells)) { cells.clear(); for(unsigned int i = 0; i < const_cells.size(); i++) { cells.push_back(const_cast<Cell *>(const_cells[i])); } return 1; } else { return 0; } } else { return 0; } } int Tree::GetPossibleCells(const int class_id, vector<const Cell *> & cells) const { if((class_id >= 0) && (class_id < _pools.size())) { return _pools[class_id].GetCells(cells); } else { return 0; } } int Tree::NumPossibleCells(const int class_id) const { if((class_id >= 0) && (class_id < _pools.size())) { return _pools[class_id].NumCells(); } else { return 0; } } const Tree::Cell * Tree::GetPossibleCell(const int class_id, const int which_one) const { if((class_id >= 0) && (class_id < _pools.size())) { return _pools[class_id].GetCell(which_one); } else { return 0; } } int Tree::NumLeafCells(void) const { if(_cells_per_level.size() <= 0) { return 0; } else { return _cells_per_level[_cells_per_level.size()-1].size(); } } const Tree::Cell * Tree::GetLeafCell(const int which_one) const { const int num_leaf_cells = NumLeafCells(); if((which_one >= 0) && (which_one < num_leaf_cells)) { return _cells_per_level[_cells_per_level.size()-1][which_one]; } else { return 0; } } Tree::Cell * Tree::GetLeafCell(const int which_one) { const int num_leaf_cells = NumLeafCells(); if((which_one >= 0) && (which_one < num_leaf_cells)) { return _cells_per_level[_cells_per_level.size()-1][which_one]; } else { return 0; } } const Tree::Cell * Tree::FindCell(const int level, const vector<int> & index) const { const Cell * answer = 0; // find the root node that potentially contains the cell vector<int> root_index = index; for(int n = level; n > 0; n--) { for(unsigned int i = 0; i < root_index.size(); i++) { root_index[i] /= 2; } } const vector<int> & num_root_cells_per_dim = _num_cells_per_dimension_per_level[0]; { assert(root_index.size() == num_root_cells_per_dim.size()); for(unsigned int i = 0; i < root_index.size(); i++) { assert((root_index[i] >= 0) && (root_index[i] < num_root_cells_per_dim[i])); } } // assuming root nodes sorted in sequential order // make sure this is consistent with the constructor int which_root = 0; { for(int i = num_root_cells_per_dim.size()-1; i >= 0; i--) { which_root *= num_root_cells_per_dim[i]; which_root += root_index[i]; } } assert((which_root >= 0) && (which_root < _cells_per_level[0].size())); return _cells_per_level[0][which_root]->FindCell(level, index); } int Tree::LocateCell(const Sample & sample, int & level, vector<int> & cell_index) const { if(! _distance_field.Inside(sample)) { return 0; } if(sample.coordinate.Dimension() != Dimension()) { return 0; } const float cell_size = _cell_size_per_level[0]; vector<int> root_index(Dimension(), 0); for(unsigned int i = 0; i < root_index.size(); i++) { root_index[i] = floor(sample.coordinate[i]/cell_size); } const vector<int> & num_root_cells_per_dim = _num_cells_per_dimension_per_level[0]; { assert(root_index.size() == num_root_cells_per_dim.size()); for(unsigned int i = 0; i < root_index.size(); i++) { if(!((root_index[i] >= 0) && (root_index[i] < num_root_cells_per_dim[i]))) { throw Exception("Tree::LocateCell() : illegal root_index"); } } } const Cell * cell = FindCell(0, root_index); if(! cell) { return 0; } else { return cell->LocateCell(sample, level, cell_index); } } const Tree::Cell * Tree::LocateCell(const Sample & sample, int & level) const { vector<int> cell_index(sample.coordinate.Dimension()); if(! LocateCell(sample, level, cell_index)) return 0; const Cell * cell = FindCell(level, cell_index); return cell; } Tree::Cell * Tree::LocateCell(const Sample & sample, int & level) { vector<int> cell_index(sample.coordinate.Dimension()); if(! LocateCell(sample, level, cell_index)) return 0; Cell * cell = const_cast<Cell *>(FindCell(level, cell_index)); return cell; } void Tree::GetSamples(vector<const Sample *> & samples) const { samples.clear(); vector<const Sample *> cell_samples; for(unsigned int i = 0; i < _cells_per_level.size(); i++) { for(unsigned int j = 0; j < _cells_per_level[i].size(); j++) { if(_cells_per_level[i][j] && _cells_per_level[i][j]->GetSamples(cell_samples)) { for(unsigned int k = 0; k < cell_samples.size(); k++) { samples.push_back(cell_samples[k]); } } } } } int Tree::GetConflicts(const Sample & sample, vector<const Sample *> & neighbors) const { return GetConflicts(sample, 1, neighbors); } int Tree::GetConflicts(const Sample & sample, const int same_tree, vector<const Sample *> & neighbors) const { int level = 0; const Cell * cell = LocateCell(sample, level); if(! cell) return 0; return cell->GetConflicts(sample, same_tree, neighbors); } int Tree::Subdivide(void) { return Subdivide(0); // non-blind } int Tree::Subdivide(const int blind) { assert(_cells_per_level.size() == _cell_size_per_level.size()); assert(_cell_size_per_level.size() == _num_cells_per_dimension_per_level.size()); assert(_cells_per_level.size() > 0); const int current_level = _cells_per_level.size()-1; int any_subdivided = 0; vector<Cell *> empty; empty.clear(); _cells_per_level.push_back(empty); _cell_size_per_level.push_back(_cell_size_per_level[_cell_size_per_level.size()-1]/2.0); _num_cells_per_dimension_per_level.push_back(_num_cells_per_dimension_per_level[_num_cells_per_dimension_per_level.size()-1]); { for(unsigned int i = 0; i < _num_cells_per_dimension_per_level[_num_cells_per_dimension_per_level.size()-1].size(); i++) { _num_cells_per_dimension_per_level[_num_cells_per_dimension_per_level.size()-1][i] *= 2; } } // go through all nodes at bottom level and try to subdivide them { vector<Cell *> children; for(unsigned int i = 0; i < _cells_per_level[current_level].size(); i++) { assert(_cells_per_level[current_level][i]); if(_cells_per_level[current_level][i]->Subdivide(blind)) { any_subdivided = 1; if(_cells_per_level[current_level][i]->GetChildren(children)) { for(unsigned int j = 0; j < children.size(); j++) { _cells_per_level[_cells_per_level.size()-1].push_back(children[j]); } } } } } if(any_subdivided) { // init pools if(! InitPoolsWithEmptyLeaves()) { throw Exception("cannot InitPoolsWithEmptyLeaves()"); } // update the conflict counter { for(unsigned int i = 0; i < _cells_per_level[current_level].size(); i++) { if(! _cells_per_level[current_level][i]->Inherit()) { throw Exception("Tree::Subdivide(): error in Inherit()"); } } } } else { if(_cells_per_level[_cells_per_level.size()-1].size() <= 0) { _cells_per_level.pop_back(); } else { throw Exception("leaf level should be empty"); } } return any_subdivided; } int Tree::ConflictMetricFromChecker(void) const { return _conflict_metric_from_checker; } int Tree::CellOffset(void) const { return _cell_offset; } int Tree::CellOffset(const int dimension, const ConflictChecker & conflict_checker) { if(conflict_checker.ConflictMetric() == ConflictChecker::MEAN) { return static_cast<int>(ceil(5*sqrt(dimension*1.0))); } else { return static_cast<int>(ceil(3*sqrt(dimension*1.0))); } } int Tree::CellOffset(const float min_distance, const float cell_size) { return static_cast<int>(ceil(min_distance/cell_size)); } int Tree::InitPoolsWithEmptyLeaves(void) { for(unsigned int j = 0; j < _pools.size(); j++) { _pools[j].Clear(); if(_cells_per_level.size() > 0) { vector<Cell *> & leaves = _cells_per_level[_cells_per_level.size()-1]; for(unsigned int i = 0; i < leaves.size(); i++) { if(!leaves[i]->PoolAdd(j)) { return 0; } } } } return 1; } Tree::Cell::Cell(Tree & tree, const Cell * parent, const vector<int> & child_index) : _tree(tree), _parent(parent), _level(parent ? parent->_level+1 : 0), _index(child_index), _pool_links(tree.GetDistanceField().NumClasses(), Pool::CellLink(this)), _visit_count(0) { if(_parent) { assert(_index.size() == parent->_index.size()); for(unsigned int i = 0; i < _index.size(); i++) { _index[i] += 2*_parent->_index[i]; } } } int Tree::PoolAdd(const int class_id, Pool::CellLink & link) { if((class_id >= 0) && (class_id < _pools.size())) { return _pools[class_id].Add(link); } else { return 0; } } int Tree::PoolRemove(const int class_id, Pool::CellLink & link) { if((class_id >= 0) && (class_id < _pools.size())) { return _pools[class_id].Remove(link); } else { return 0; } } int Tree::AddVisitCount(const int class_id, const Pool::CellLink & link) { if((class_id >= 0) && (class_id < _pools.size())) { return _pools[class_id].AddVisitCount(link); } else { return 0; } } Tree::Cell::~Cell(void) { // nothing to do } int Tree::Cell::Level(void) const { return _level; } float Tree::Cell::Size(void) const { return _tree.CellSize(_level); } const vector<int> & Tree::Cell::Index(void) const { return _index; } void Tree::Cell::GetDomain(vector<float> & min_corner, vector<float> & max_corner) const { if(min_corner.size() != _index.size()) min_corner = vector<float>(_index.size()); if(max_corner.size() != _index.size()) max_corner = vector<float>(_index.size()); for(unsigned int i = 0; i < _index.size(); i++) { min_corner[i] = _index[i]*Size(); max_corner[i] = min_corner[i] + Size(); } } int Tree::Cell::NumSamples(void) const { return _samples.size(); } int Tree::Cell::NumChildren(void) const { return _children.size(); } const Tree::Cell * Tree::Cell::Parent(void) const { return _parent; } const Tree::Cell * Tree::Cell::FindCell(const int level, const vector<int> & index) const { if((level == _level)) { assert(index.size() == _index.size()); int same = 1; for(unsigned int i = 0; i < index.size(); i++) { if(index[i] != _index[i]) same = 0; } if(same) { return this; } else { return 0; } } else if(level > _level) { // evil recursive calls const Cell * answer = 0; if(_children.size() > 0) { vector<int> potential_child_index = index; { for(int n = level; n > (_level+1); n--) { for(unsigned int i = 0; i < potential_child_index.size(); i++) { potential_child_index[i] /= 2; } } { for(unsigned int i = 0; i < potential_child_index.size(); i++) { potential_child_index[i] -= 2*_index[i]; assert((potential_child_index[i] >= 0) && (potential_child_index[i] <= 1)); } } } // this part assumes the children are sorted in SequentialCounter order int which_child = 0; { assert(potential_child_index.size() == _tree.Dimension()); for(int i = static_cast<int>(potential_child_index.size())-1; i >= 0; i--) { which_child *= 2; which_child += potential_child_index[i]; } } assert((which_child >= 0) && (which_child < _children.size())); // evil recursive call, should expand it return _children[which_child]->FindCell(level, index); } else { return 0; } } else { return 0; } } int Tree::Cell::LocateCell(const Sample & sample, int & level, vector<int> & cell_index) const { if(! Inside(sample)) { return 0; } else { if(NumChildren() <= 0) { level = _level; cell_index = _index; return 1; } else { vector<int> child_index = _index; const float child_size = _tree.CellSize(_level+1); for(unsigned int i = 0; i < child_index.size(); i++) { child_index[i] = floor(sample.coordinate[i]/child_size); } const Cell * child = FindCell(_level+1, child_index); if(child) { return child->LocateCell(sample, level, cell_index); } else { throw Exception("weird situation in Tree::Cell::LocateCell()"); return 0; } } } } int Tree::Cell::Inside(const Sample & sample) const { const float cell_size = _tree.CellSize(_level); if(cell_size > 0) { if(_index.size() == sample.coordinate.Dimension()) { for(unsigned int i = 0; i < _index.size(); i++) { const float dim_i_min = _index[i]*cell_size; if((sample.coordinate[i] < dim_i_min) || (sample.coordinate[i] >= (dim_i_min+cell_size))) { return 0; } } return 1; } else { // error return 0; } } else { // error return 0; } } int Tree::Cell::CellOffset(void) const { const int cell_offset = (_tree.ConflictMetricFromChecker() ? _tree.CellOffset() : _tree.CellOffset(_tree.GetConflictChecker().MaxDistance(), Size())); return cell_offset; } int Tree::Cell::Conflict(const Sample & sample) const { return Conflict(sample, 1); } int Tree::Cell::Conflict(const Sample & sample, const int same_tree) const { vector<const Sample *> neighbors; const int status = GetConflicts(sample, same_tree, neighbors, 0); if(! status) { throw Exception("Tree::Cell::Conflict(): error in GetConflicts"); return 0; } return (neighbors.size() > 0); } int Tree::Cell::Add(const Sample & sample) { if(_children.size() > 0) { // cannot add to an internal node throw Exception("cannot add to an internal node"); return 0; } else if(_samples.size() == 0) { _samples.push_back(&sample); return 1; } else { throw Exception("cell already has sample"); return 0; } } int Tree::Cell::Remove(const Sample & sample) { int index = -1; for(unsigned int i = 0; i < _samples.size(); i++) { if(_samples[i] == &sample) { index = i; } } if(index >= 0) { _samples[index] = _samples[_samples.size()-1]; _samples.pop_back(); return 1; } else { // not found return 0; } } int Tree::Cell::AddDeadZone(const Sample & sample) { // update conflict counter return UpdateDeadZone(sample, +1); } int Tree::Cell::RemoveDeadZone(const Sample & sample) { // update conflict counter return UpdateDeadZone(sample, -1); } int Tree::Cell::Impossible(const int class_id) const { return (_conflict_counter.Value(class_id) > 0); } int Tree::Cell::FarCorner(const Sample & sample, Coordinate & corner) const { corner = sample.coordinate; for(int i = 0; i < corner.Dimension(); i++) { const float option0 = _index[i]*Size(); const float option1 = (_index[i]+1)*Size(); corner[i] = (fabs(sample.coordinate[i] - option0) > fabs(sample.coordinate[i] - option1) ? option0 : option1); } return 1; } int Tree::Cell::DeadZone(const Sample & sample, vector<int> verdict_per_class) const { Sample corner(sample); if(! FarCorner(sample, corner.coordinate)) return 0; const ConflictChecker & checker = _tree.GetConflictChecker(); for(unsigned int i = 0; i < verdict_per_class.size(); i++) { corner.id = i; const ConflictChecker::Status status = checker.Check(sample, corner); if(status == ConflictChecker::CHECK_ERROR) throw Exception("error for conflict check"); verdict_per_class[i] = (status == ConflictChecker::CHECK_FAIL); } return 1; } int Tree::Cell::UpdateDeadZone(const Sample & sample, const int add_or_remove) { const int cell_offset = CellOffset(); SequentialCounter counter(_tree.Dimension(), -cell_offset, cell_offset); vector<int> num_cells_per_dim; if(! _tree.GetNumCellsPerDimension(Level(), num_cells_per_dim)) { throw Exception("cannot get num cells per dimension"); return 0; } const int dimension = _tree.Dimension(); const vector<int> container_index = _index; vector<int> current_index(dimension); vector<int> corrected_index(dimension); vector<int> offset_index(dimension); Sample current_sample(sample); vector<int> verdict_per_class(_tree.GetDistanceField().NumClasses()); counter.Reset(); do { counter.Get(offset_index); // test current offset_index for(unsigned int i = 0; i < current_index.size(); i++) { current_index[i] = container_index[i] + offset_index[i]; corrected_index[i] = (((current_index[i]%num_cells_per_dim[i])+num_cells_per_dim[i])%num_cells_per_dim[i]); } for(int i = 0; i < current_sample.coordinate.Dimension(); i++) { current_sample.coordinate[i] = sample.coordinate[i] + (corrected_index[i] - current_index[i])*Size(); } Cell * current_cell = const_cast<Cell *>(_tree.FindCell(Level(), corrected_index)); if(current_cell) { #if 0 // 09/17/2008: Hmm, I don't think I understand why I need this.... if(current_cell->NumSamples() > 0) { // even though mathematically it could contain another sample // we still need to remove it from the pool for computation for(unsigned int i = 0; i < verdict_per_class.size(); i++) { if(! current_cell->PoolRemove(i)) { return 0; } } } #endif if(! current_cell->DeadZone(current_sample, verdict_per_class)) { return 0; } else { for(unsigned int i = 0; i < verdict_per_class.size(); i++) { if(verdict_per_class[i]) { const int counter_update_status = (add_or_remove > 0 ? current_cell->_conflict_counter.Increment(i) : current_cell->_conflict_counter.Decrement(i)); if(! counter_update_status) return 0; if(current_cell->_conflict_counter.Value(i) == 0) { if(! current_cell->PoolAdd(i)) { return 0; } } else if(current_cell->_conflict_counter.Value(i) == 1) { if(! current_cell->PoolRemove(i)) { return 0; } } } } } } } while(counter.Next()); return 1; } int Tree::Cell::AddVisitCount(void) { _visit_count++; for(unsigned int i = 0; i < _pool_links.size(); i++) { if(! _tree.AddVisitCount(i, _pool_links[i])) return 0; } return 1; } int Tree::Cell::GetVisitCount(void) const { return _visit_count; } int Tree::Cell::GetSamples(vector<const Sample *> & samples) const { samples = _samples; return 1; } int Tree::Cell::GetSubTreeSamples(vector<const Sample *> & samples) const { samples = _samples; vector<const Sample *> child_samples; for(unsigned int i = 0; i < _children.size(); i++) { if(! _children[i]->GetSubTreeSamples(child_samples)) { return 0; } else { samples.insert(samples.end(), child_samples.begin(), child_samples.end()); } } return 1; } int Tree::Cell::GetConflicts(const Sample & sample, vector<const Sample *> & neighbors) const { return GetConflicts(sample, neighbors, 1); } int Tree::Cell::GetConflicts(const Sample & sample, const int same_tree, vector<const Sample *> & neighbors) const { return GetConflicts(sample, same_tree, neighbors, 1); } int Tree::Cell::GetConflicts(const Sample & sample, vector<const Sample *> & neighbors, const int find_all) const { return GetConflicts(sample, 1, neighbors, find_all); } int Tree::Cell::GetConflicts(const Sample & sample, const int same_tree, vector<const Sample *> & neighbors, const int find_all) const { const ConflictChecker & checker = _tree.GetConflictChecker(); const float worst_case_distance = checker.MaxDistance(); neighbors.clear(); if(worst_case_distance <= 0) { return 0; } // just check if(! Inside(sample)) { throw Exception("sample is NOT inside cell"); return 0; } const int dimension = _tree.Dimension(); const Cell * container = this; while(container) { const int cell_offset = CellOffset(); const vector<int> container_index = _index; vector<int> current_index(dimension); vector<int> corrected_index(dimension); vector<int> offset_index(dimension); SequentialCounter offset_index_counter(dimension, -cell_offset, cell_offset); offset_index_counter.Reset(); vector<int> num_cells_per_dim; if(! _tree.GetNumCellsPerDimension(container->Level(), num_cells_per_dim)) { throw Exception("cannot get num cells per dimension"); return 0; } do { offset_index_counter.Get(offset_index); assert(offset_index.size() == dimension); // test current offset_index for(unsigned int i = 0; i < current_index.size(); i++) { current_index[i] = container_index[i] + offset_index[i]; corrected_index[i] = (((current_index[i]%num_cells_per_dim[i])+num_cells_per_dim[i])%num_cells_per_dim[i]); } const Cell * current_cell = _tree.FindCell(container->Level(), corrected_index); if(current_cell) { vector<const Sample *> subtree_samples; if(!same_tree && (container == this)) { if(! current_cell->GetSubTreeSamples(subtree_samples)) { return 0; } } const vector<const Sample *> & current_cell_samples = ((!same_tree && (container == this)) ? subtree_samples : current_cell->_samples); for(unsigned int j = 0; j < current_cell_samples.size(); j++) { Sample current_sample = *current_cell_samples[j]; for(int i = 0; i < dimension; i++) { // toroidal boundary handling current_sample.coordinate[i] += ((current_index[i]-corrected_index[i])*container->Size()); } const ConflictChecker::Status status = checker.Check(sample, current_sample); if(status == ConflictChecker::CHECK_ERROR) throw Exception("error for conflict check"); // regarding the second condition: // Q: hmm, why don't I have to do this for Grid? // A: for grid, the cells are small enough to guarantee no problem for this // add samples already in this cell // even though mathematically they might not be in conflict with the query // computational-wise we have to add them // since we allow only one sample per cell if((status == ConflictChecker::CHECK_FAIL) || (same_tree && (current_cell == this) && (status == ConflictChecker::CHECK_PASS))) { neighbors.push_back(current_cell_samples[j]); if(! find_all) return 1; } } } } while(offset_index_counter.Next()); // go up one level container = container->Parent(); } // done return 1; } int Tree::Cell::GetChildren(vector<Cell *> & children) { children = _children; return 1; } int Tree::Cell::GetChildren(vector<const Cell *> & children) const { if(children.size() != _children.size()) { children = vector<const Cell *>(_children.size()); } for(unsigned int i = 0; i < _children.size(); i++) { children[i] = _children[i]; } return 1; } int Tree::Cell::Subdivide(void) { return Subdivide(0); // non-blind } int Tree::Cell::Subdivide(const int blind) { if(!blind) { if(_samples.size() <= 0) { // no subdivide return 0; } else { const float cell_size = _tree.CellSize(_level); // check samples min distance for(unsigned int i = 0; i < _samples.size(); i++) { assert(_samples[i]); #ifdef _USE_MEAN_NOT_MAX_METRIC const float sample_min_distance = _tree.GetDistanceField().Query(*_samples[i])/2; #else const float sample_min_distance = _tree.GetDistanceField().Query(*_samples[i]); #endif if(cell_size*sqrt(_tree.Dimension()*1.0) <= sample_min_distance) { return 0; } } } } // OK to proceed with subdivision if(_children.size() <= 0) { // spawn children SequentialCounter counter(_index.size(), 0, 1); counter.Reset(); vector<int> child_index(_index.size()); do { counter.Get(child_index); Cell * new_born = new Cell(_tree, this, child_index); if(new_born) _children.push_back(new_born); else return 0; } while(counter.Next()); // migrate sample // done via Inherit() // done return 1; } else { // already subdivided assert(0); return 2; } } int Tree::Cell::Inherit(void) { if(_children.size() > 0) { while(_samples.size() > 0) { int found_child = 0; for(unsigned int i = 0; (i < _children.size()) & !found_child; i++) { if(_children[i]->Inside(*_samples[0])) { if(! _children[i]->Add(*_samples[0])) return 0; found_child = 1; } } if(! found_child) { return 0; } else { _samples[0] = _samples[_samples.size()-1]; _samples.pop_back(); } } // done return 1; } else { // no need to inherit return 1; } } int Tree::Cell::PoolAdd(const int class_id) { return _tree.PoolAdd(class_id, _pool_links[class_id]); } int Tree::Cell::PoolRemove(const int class_id) { return _tree.PoolRemove(class_id, _pool_links[class_id]); } Tree::Cell::MultiCounter::MultiCounter(void) { // nothing to do } Tree::Cell::MultiCounter::~MultiCounter(void) { // nothing to do } int Tree::Cell::MultiCounter::Increment(const int class_id) { if(_counts.size() < (class_id+1)) { _counts.resize(class_id+1, 0); } if((class_id < 0) || (class_id >= _counts.size())) { return 0; } else { _counts[class_id] += 1; return 1; } } int Tree::Cell::MultiCounter::Decrement(const int class_id) { if((class_id < 0) || (class_id >= _counts.size())) { return 0; } else { if(_counts[class_id] > 0) { _counts[class_id] -= 1; return 1; } else { return 0; } } } int Tree::Cell::MultiCounter::Value(const int class_id) const { if((class_id < 0) || (class_id >= _counts.size())) { return 0; } else { return _counts[class_id]; } } Tree::Pool::Pool(void) : _visit_count(0) { // nothing to do } Tree::Pool::~Pool(void) { // nothing to do } int Tree::Pool::Add(CellLink & link) { if(link.position >= 0) { if(link.position < _links.size()) { return _links[link.position] == &link; } else { // inconsistent return 0; } } else { _visit_count += link.cell->GetVisitCount(); _links.push_back(&link); link.position = _links.size()-1; return (_links[link.position] == &link); } } int Tree::Pool::Remove(CellLink & link) { if((link.position >= 0) && (link.position < _links.size())) { if(_links[link.position] == &link) { _visit_count -= link.cell->GetVisitCount(); _links[link.position] = _links[_links.size()-1]; _links[link.position]->position = link.position; _links.pop_back(); link.position = -1; return 1; } else { return 0; } } else { return (link.position < 0); } } void Tree::Pool::Clear(void) { for(unsigned int i = 0; i < _links.size(); i++) { _links[i]->position = -1; } _links.clear(); _visit_count = 0; } int Tree::Pool::GetCells(vector<const Cell *> & cells) const { cells.clear(); for(unsigned int i = 0; i < _links.size(); i++) { cells.push_back(_links[i]->cell); } return 1; } int Tree::Pool::NumCells(void) const { return _links.size(); } const Tree::Cell * Tree::Pool::GetCell(const int which_cell) const { if((which_cell >= 0) && (which_cell < _links.size())) { return _links[which_cell]->cell; } else { return 0; } } int Tree::Pool::GetVisitCount(void) const { return _visit_count; } int Tree::Pool::AddVisitCount(const CellLink & link) { if(link.position >= 0) { if(link.position < _links.size()) { if(_links[link.position] == &link) { _visit_count++; return 1; } else { // inconsistent return 0; } } else { // inconsistent return 0; } } else { // link/cell not in the pool return 0; } } Tree::Pool::CellLink::CellLink(const Cell * cell_i) : cell(cell_i), position(-1) { // nothing to do } Tree::Pool::CellLink::~CellLink(void) { // nothing to do }
24.164534
329
0.547637
[ "vector" ]
3ee5331ac2659a22e46411089a7c934c6ff01bc4
2,650
cpp
C++
fbpcs/data_processing/sharding/Sharding.cpp
joe1234wu/fbpcs
c9f57bf1b65adcbe39c6676ade5fc89e81dc5979
[ "MIT" ]
63
2021-08-18T01:50:22.000Z
2022-03-25T06:44:36.000Z
fbpcs/data_processing/sharding/Sharding.cpp
joe1234wu/fbpcs
c9f57bf1b65adcbe39c6676ade5fc89e81dc5979
[ "MIT" ]
672
2021-08-18T05:20:32.000Z
2022-03-31T23:30:13.000Z
fbpcs/data_processing/sharding/Sharding.cpp
joe1234wu/fbpcs
c9f57bf1b65adcbe39c6676ade5fc89e81dc5979
[ "MIT" ]
61
2021-08-18T20:02:30.000Z
2022-03-31T22:44:17.000Z
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "fbpcs/data_processing/sharding/Sharding.h" #include <folly/String.h> #include <folly/logging/xlog.h> #include "fbpcs/data_processing/sharding/HashBasedSharder.h" #include "fbpcs/data_processing/sharding/RoundRobinBasedSharder.h" #include "fbpcs/data_processing/common/FilepathHelpers.h" #include "fbpcs/data_processing/common/Logging.h" #include "fbpcs/data_processing/common/S3CopyFromLocalUtil.h" namespace data_processing::sharder { void runShard( const std::string& inputFilename, const std::string& outputFilenames, const std::string& outputBasePath, int32_t fileStartIndex, int32_t numOutputFiles, int32_t logEveryN) { if (!outputFilenames.empty()) { std::vector<std::string> outputFilepaths; folly::split(',', outputFilenames, outputFilepaths); RoundRobinBasedSharder sharder{inputFilename, outputFilepaths, logEveryN}; sharder.shard(); } else if (!outputBasePath.empty() && numOutputFiles > 0) { std::size_t startIndex = static_cast<std::size_t>(fileStartIndex); std::size_t endIndex = startIndex + numOutputFiles; RoundRobinBasedSharder sharder{ inputFilename, outputBasePath, startIndex, endIndex, logEveryN}; sharder.shard(); } else { XLOG(FATAL) << "Error: specify --output_filenames or --output_base_path, " "--file_start_index, and --num_output_files"; } } void runShardPid( const std::string& inputFilename, const std::string& outputFilenames, const std::string& outputBasePath, int32_t fileStartIndex, int32_t numOutputFiles, int32_t logEveryN, const std::string& hmacBase64Key) { if (!outputFilenames.empty()) { std::vector<std::string> outputFilepaths; folly::split(',', outputFilenames, outputFilepaths); HashBasedSharder sharder{ inputFilename, outputFilepaths, logEveryN, hmacBase64Key}; sharder.shard(); } else if (!outputBasePath.empty() && numOutputFiles > 0) { std::size_t startIndex = static_cast<std::size_t>(fileStartIndex); std::size_t endIndex = startIndex + numOutputFiles; HashBasedSharder sharder{ inputFilename, outputBasePath, startIndex, endIndex, logEveryN, hmacBase64Key}; sharder.shard(); } else { XLOG(FATAL) << "Error: specify --output_filenames or --output_base_path, " "--file_start_index, and --num_output_files"; } } } // namespace data_processing::sharder
34.868421
78
0.710189
[ "vector" ]
3eee122381d92a9b76aed3b6b862cdb38a89fdcd
3,012
cpp
C++
src/read_obj.cpp
fniyaz/cg-template
ba4ccbf042628b60de73a90e93ec3059013a5873
[ "MIT" ]
null
null
null
src/read_obj.cpp
fniyaz/cg-template
ba4ccbf042628b60de73a90e93ec3059013a5873
[ "MIT" ]
null
null
null
src/read_obj.cpp
fniyaz/cg-template
ba4ccbf042628b60de73a90e93ec3059013a5873
[ "MIT" ]
null
null
null
#include "read_obj.h" #include <fstream> #include <sstream> #include <algorithm> ObjParser::ObjParser(std::string filename): filename(filename) { } ObjParser::~ObjParser() { } int ObjParser::Parse() { std::ifstream file(filename, std::ifstream::in); if (file.fail()) return -1; std::string line; while (std::getline(file, line)) { if (line.rfind("v ", 0) == 0) { auto tokens = Split(line, ' '); float4 ver{0, 0, 0, 1}; for (auto i = 1; i < tokens.size(); i++) { if (!tokens[i].empty()) { float v = std::stof(tokens[i]); ver[i - 1] = v; } } vertexes.push_back(ver); } else if (line.rfind("f ", 0) == 0) { auto tokens = Split(line, ' '); float4 first; auto ind0 = std::stoi(Split(tokens[1], '/')[0]); first = vertexes[vertexes.size() + ind0]; float4 last; bool was = false; float4 curr; for (auto i = 2; i < tokens.size(); i++) { if (!tokens[i].empty()) { auto ind = std::stoi(Split(tokens[i], '/')[0]); curr = vertexes[vertexes.size() + ind]; if (was) { faces.emplace_back<face>({ first, last, curr }); } last = curr; was = true; } } } } return 0; } const std::vector<face>& ObjParser::GetFaces() { return faces; } std::vector<std::string> ObjParser::Split(const std::string& s, char delimiter) { std::vector<std::string> tokens; std::string token; std::istringstream tokenStream(s); while (std::getline(tokenStream, token, delimiter)) { tokens.push_back(token); } return tokens; } ReadObj::ReadObj(unsigned short width, unsigned short height, std::string obj_file) : LineDrawing(width, height) { parser = new ObjParser(obj_file); } ReadObj::~ReadObj() { delete parser; } void ReadObj::DrawTriangle(face const &f, color c) { auto x_center = width / 2; auto y_center = height / 2; auto radius = std::min(width, height) / 2; float4 vertices[3]; for (int i = 0; i < 3; i++) { vertices[i] = float4{ f.vertexes[i].x * radius + x_center, f.vertexes[i].y * radius + y_center, 0, 1 }; } DrawLine(vertices[0].x, vertices[0].y, vertices[1].x, vertices[1].y, color{255, 0, 0}); DrawLine(vertices[0].x, vertices[0].y, vertices[2].x, vertices[2].y, color{0, 0, 255}); DrawLine(vertices[2].x, vertices[2].y, vertices[1].x, vertices[1].y, color{0, 255, 0}); } void ReadObj::DrawScene() { parser->Parse(); auto faces = parser->GetFaces(); for (auto const &f: faces) { DrawTriangle(f, color{255, 255, 255}); } }
23.169231
114
0.499668
[ "vector" ]
3eef4bed8df65d744109eded2fa75747658dbcde
12,936
cpp
C++
src/scratch/scratch.examples.cpp
JonnyWideFoot/pd.arcus
a6197a5a2a18c0e3f752e15aa982d1e44d052730
[ "BSD-4-Clause-UC" ]
null
null
null
src/scratch/scratch.examples.cpp
JonnyWideFoot/pd.arcus
a6197a5a2a18c0e3f752e15aa982d1e44d052730
[ "BSD-4-Clause-UC" ]
null
null
null
src/scratch/scratch.examples.cpp
JonnyWideFoot/pd.arcus
a6197a5a2a18c0e3f752e15aa982d1e44d052730
[ "BSD-4-Clause-UC" ]
null
null
null
#include "global.h" #include "../pd/accessory.h" #include "tools/statclock.h" #include "tools/quote.h" #include "workspace/workspace.h" #include "workspace/segdef.h" #include "sequence/sequence.h" #include "sequence/alignment.h" #include "forcefields/ffbonded.h" #include "forcefields/breakablebonded.h" #include "forcefields/ffnonbonded.h" #include "forcefields/gbff.h" #include "forcefields/lcpo.h" #include "forcefields/ffsoftvdw.h" #include "fileio/tra.h" #include "fileio/pdb.h" #include "protocols/minimise.h" #include "protocols/torsionalminimisation.h" #include "protocols/md.h" using namespace std; using namespace Physics; using namespace Protocol; using namespace Tra; using namespace PDB; Forcefield createffs( WorkSpace& wspace, bool useBreakableFF = false, bool summary = true) { Forcefield ff = Forcefield(wspace); if( useBreakableFF ) { FF_BreakableBonded* bonds = new FF_BreakableBonded(wspace); ff.addWithOwnership( *bonds ) ; } else { BondedForcefield* bonds = new BondedForcefield(wspace); ff.addWithOwnership( *bonds ) ; } SoftVDWForcefield *sff = new SoftVDWForcefield(wspace); //sff->Hardness = 6; sff->Hardness = 12; ff.addWithOwnership(*sff); if( summary ) ff.printEnergySummary(); return ff; } Forcefield createffVac(WorkSpace& wspace, bool useBreakableFF = false, bool summary = true) { Forcefield ff = Forcefield(wspace); if( useBreakableFF ) { FF_BreakableBonded* bonds = new FF_BreakableBonded(wspace); ff.addWithOwnership( *bonds ) ; } else { BondedForcefield* bonds = new BondedForcefield(wspace); ff.addWithOwnership( *bonds ) ; } FF_NonBonded* nb = new FF_NonBonded(wspace); nb->Cutoff = 12.0; nb->InnerCutoff = 6.0; ff.addWithOwnership( *nb ); if( summary ) ff.printEnergySummary(); return ff; } Forcefield createff(WorkSpace& wspace, bool useBreakableFF = false, double dielec = 1.0, bool summary = true) { Forcefield ff = Forcefield(wspace); if( useBreakableFF ) { FF_BreakableBonded* bonds = new FF_BreakableBonded(wspace); ff.addWithOwnership( *bonds ) ; } else { BondedForcefield* bonds = new BondedForcefield(wspace); ff.addWithOwnership( *bonds ) ; } GB_Still* gbsa = new GB_Still( wspace ); // used to take nb gbsa->FastMode = true; gbsa->DielectricSolute = dielec; ff.addWithOwnership( *gbsa ); SASA_LCPO* sasa = new SASA_LCPO(wspace); sasa->GlobalASP = 0.009; ff.addWithOwnership( *sasa ); if( summary ) ff.printEnergySummary(); return ff; } void Test_Minimisation() { StatClock clockMe; clockMe.Begin(); FFParamSet ffps; ffps.readLib("lib/amber03aa.ff"); System sys(ffps); sys.add(NewProteinHelix(ffps,"*A-(AAAAPAAAA)-A*" )); WorkSpace wspace = WorkSpace( sys ); wspace.info(); wspace.addStdTra("imported464"); Forcefield ff = createff(wspace); for( int i = 0; i < 1; i++ ) // average over 10 minimisations { Minimisation min( ff ); min.Steps = 1500; min.StepSize = 2E1; min.UpdateNList = 5; min.UpdateScr = 100; min.UpdateTra = 0; min.UpdateMon = 0; min.run(); clockMe.Stamp(); } clockMe.ReportMilliSeconds(10); return; } void Test_MD() { StatClock clockMe; clockMe.Begin(); FFParamSet ffps; ffps.readLib("lib/amber03aa.ff"); //System sys(ffps); //sys.add(NewProteinHelix(ffps,"*P-(ACDEFGHIKLMNPQRSTVWY)-P*" )); //sys.add(NewProteinHelix(ffps,"*A-(A)-A*" )); PDB_In sys( ffps, "pep4_A_84_237_ss.pdb" ); sys.load(); WorkSpace wspace = WorkSpace( sys ); PDB_Out out1("imported1",wspace); wspace.info(); wspace.addStdTra("imported1"); Forcefield ff = createff(wspace); Minimisation min2( ff ); // Whole Protein min2.Steps = 3501; min2.StepSize = 2E1; min2.UpdateNList = 5; min2.UpdateScr = 20; min2.UpdateTra = 10; min2.UpdateMon = 0; min2.run(); MolecularDynamics md(ff); // Whole Protein md.Steps = 5001; md.Integrator = MolecularDynamics::Langevin; md.Thermostat = MolecularDynamics::NoThermostat; md.Timestep = 1.00E-15; md.UpdateScr = 20; md.UpdateNList = 10; md.UpdateTra = 20; md.UpdateMon = 0; md.TargetTemp = new Temp(300); md.run(); clockMe.End(); clockMe.ReportMilliSeconds(10); return; } void Test_TorsionalMinimisation() { FFParamSet ffps; ffps.readLib("lib/amber03aa.ff"); System sys(ffps); sys.add(NewProteinHelix(ffps,"*A-(AAAAPAAAA)-A*" )); WorkSpace wspace = WorkSpace( sys ); PDB_Out out1("imported464",wspace); wspace.info(); wspace.addStdTra("imported464"); Forcefield ff = createff(wspace); SegmentDefBase sd(wspace,0,6,false); TorsionalMinimisation min2( ff, sd ); min2.Steps = 3000; min2.UpdateScr = 1; min2.UpdateTra = 1; min2.UpdateMon = -1; min2.run(); } void Test_PDB_In() { FFParamSet ffps; ffps.readLib("lib/amber03aa.ff"); ffps.readLib("lib/tip3.ff"); string stem = "mike_pdb_sample\\pdb\\"; std::vector<string> names; names.push_back("bba1.pdb"); // Correctly complains about PYA names.push_back("water.pdb"); // Correctly throws an exception - MOL is not a molecule in amber03aa.ff names.push_back("trpzip1.pdb"); // Good names.push_back("sh3.pdb"); // Good names.push_back("acyltra.pdb"); // Good names.push_back("1fsd.pdb"); // Good names.push_back("villin.pdb"); // Good names.push_back("protg.pdb"); // Good names.push_back("proteinAZ.pdb");// Good names.push_back("ubifrag.pdb"); // Good names.push_back("trpzip.pdb"); // Good names.push_back("trpcage.pdb"); // Good names.push_back("alcalase.pdb"); // Good names.push_back("1hz6.pdb"); // Good names.push_back("trpzip2.pdb"); // Good // 1) Try loading everything from each file for( size_t i = 0; i < names.size(); i++ ) { try { // Read in PDB_In sysA(ffps,stem + names[i]); sysA.load(); // Load everything from model 1 // Write out PDB_Writer writerA(stem + names[i] + ".out.pdb"); writerA.write(sysA); } catch(exception ex) { printf("\nCritical Load Failure!!!!\n"); } } // 2) An example of using custom name mappings for oddball residues PDB_In sysB(ffps,stem + names[0]); sysB.addAlias("PYA","ALA"); // Define a brand new custom alias sysB.load(); PDB_Writer write(stem + "bba1.pdb" + ".customalias.pdb"); write.write(sysB); // 3) Content filters PDB_In sysC(ffps,"1dqe.pdb"); sysC.setFilter(Library::Polypeptide); sysC.load(); // loads only polypeptide from model 1 PDB_In sysD(ffps,"1dqe.pdb"); sysD.setFilter(Library::Water); sysD.load(); // loads only the water molecules from model 1 PDB_In sysE(ffps,"1dqe.pdb"); sysE.getClass().addClassMember("custom1","ALA"); // ALA is a member of class 'custom1' sysE.getClass().addClassMember("custom1","GLU"); // GLU is a member of class 'custom1' sysE.getClass().addClassMember("custom1","ARG"); // ARG is a member of class 'custom1' sysE.setFilter("custom1"); // loads only from the custom gilter sysE.load(); // loads only the specified molecules from model 1 // 4) Load specifics - reolace "1dqe.pdb" with your file PDB_In sysF(ffps,"1dqe.pdb"); sysF.loadAll(); // load absolutely fricking everything from all models at once - this could get messy! PDB_In sysG(ffps,"1dqe.pdb"); sysG.load('A'); // load chain A from model 1 PDB_In sysH(ffps,"1dqe.pdb"); sysH.load('A',4); // load chain A from model 4 PDB_In sysI(ffps,"1dqe.pdb"); sysI.loadExplicit('A',"BOM",47,' '); // Load BOM 47 with no icode from chain A of model 1 PDB_In sysJ(ffps,"1dqe.pdb"); Sequence::BioSequence bioseq; bioseq.setTo("*P-(AAAAAAAAAAAAPAAAAAAAAAA)-P*"); // Map the particles defined in the PDB over this sequence! sysJ.loadExplicit('C',Library::Polypeptide,bioseq); // Load polypeptide from chain C using a sequece override return; } void Test_PDB_Sim( const std::string& fileStem, bool doMD = false ) { // Load FFParam FFParamSet ffps; ffps.readLib("lib/amber03aa.ff"); // Load our favourite PDB molecule PDB_In sys(ffps,fileStem + ".pdb"); sys.setFilter(Library::Polypeptide); // ONLY load the polypeptide sys.load(); // load from model 1 (any chains) // Make a workspace WorkSpace wspace = WorkSpace( sys ); wspace.addStdTra(fileStem); wspace.info(); // Write out what we have imported to check PDB_Writer writer(fileStem + ".imp.pdb",false); writer.write(wspace); // Create the bond only forcefield Forcefield ffb = Forcefield(wspace); BondedForcefield* bonds = new BondedForcefield(wspace); ffb.addWithOwnership( *bonds ); Minimisation minb( ffb ); minb.Steps = 50000; minb.SlopeCutoff = 0.1 * PhysicsConst::kcal2J / PhysicsConst::Na; minb.StepSize = 1E2; minb.UpdateScr = 10; minb.UpdateTra = 10; minb.UpdateMon = 10; minb.run(); // Create the nice steric forcefield Forcefield ffs = createffs(wspace); Minimisation mins( ffs ); mins.Steps = 2000; mins.SlopeCutoff = 0.001 * PhysicsConst::kcal2J / PhysicsConst::Na; mins.StepSize = 0.4E1; mins.UpdateScr = 10; mins.UpdateTra = 10; mins.UpdateMon = 10; mins.run(); // Create the full forcefield Forcefield ff = createff(wspace); // Minimise - PDB files often contain bad clashes Minimisation min( ff ); min.Steps = 500; min.StepSize = 2E1; min.UpdateScr = 10; min.UpdateTra = 10; min.UpdateMon = 10; min.run(); if( doMD ) { // Do a nice MD simulation MolecularDynamics md(ff); md.Steps = 5000; md.UpdateScr = 10; md.UpdateTra = 10; md.UpdateMon = 10; md.run(); } // Whats the workspace like now? wspace.info(); PDB_Writer writerEnd(fileStem + ".min.pdb",false); writerEnd.write(wspace); return; } void Test_Tra_In() { FFParamSet ffps; ffps.readLib("lib/amber03aa.ff"); System sim2( ffps ); Tra::Traj_In mytra( "test.tra", true ); mytra.loadIntoSystem( sim2, -1 ); WorkSpace wspace2( sim2 ); PDB_Out out("imported",wspace2); Forcefield ff2 = createff(wspace2); wspace2.info(); Minimisation min2( ff2 ); min2.Steps = 1; min2.UpdateScr = 10; min2.UpdateTra = 10; min2.UpdateMon = 10; min2.run(); wspace2.info(); out.append(); } void Test_Alignment_Code() { FFParamSet ffps; ffps.readLib("lib/amber03aa.ff"); // Forcefield resolution Sequence::BioSequence s1(ffps); char* seq1 = "*s-ASP-GLU-AlA-Gly-ASP-D-GLU-ALA-GLU-A*"; printf("Resolving using 'FFParamSet':\n"); printf("Seq1: '%s'\n",seq1); s1.setTo(seq1); printf("ResolvesTo: '"); s1.printToScreen(); printf("'\n\n"); Library::NamingConventions* map2 = Library::NamingConventions::getSingleton(); Sequence::BioSequence s2(*map2); char* seq2 = "GLU-AlA-G-ASP-D-AlA-GLU"; printf("Resolving using Library::NamingConventions:\n"); printf("Seq2: '%s'\n",seq2); s2.setTo(seq2); printf("ResolvesTo: '"); s2.printToScreen(); printf("'\n\n"); Sequence::ExpSeqPair expPair(s1,s2); Sequence::SimpleAligner ali; ali.Align(expPair); expPair.printToScreen(); return; } void Test_StatClock() { int count = 20; TextProgressBar bar( count, 50 ); StatClock stats("Clock Test"); bar.Begin(); stats.Begin(); for( int i = 0 ; i < count; i++ ) { system("sleep 0.1"); // replace with desired OutputLevel! operation to be timed - must not print to screen! bar.next(); stats.Stamp(); } bar.End(); stats.ReportSeconds(); } void Test_CharacterMap() { int printed = 0; for( int i = 1; i < 256; i++ ) { if( (i >= 7 && i <= 13) || i == 27 ) continue; if( i < 10 ) std::cout << ' '; if( i < 100 ) std::cout << ' '; std::cout << i << std::string(": ") << (char)i; printed++; if( (printed % 10 == 0) || i == 255 ) { std::cout << std::endl; } else { std::cout << std::string(", "); } } std::cout << std::endl; std::cout << std::endl; } void Test_Quote() { Quote* q = Quote::getSingleton(); q->printQuote(); q->printQuote(); q->printQuote(); q->printQuote(); q->printQuote(); q->printQuote(); q->printQuote(); q->printQuote(); q->printQuote(); } void Test_StringSystem() { double d = 1.723625154; int i = 1; Printf("%d) Using 'safe Printf' with the same format strings as printf(), you can print numbers: %lf\n")(i++)(d); StringBuilder sb; sb.setFormat("%d) StringBuilder now supports format strings!")(i++); std::cout << sb << std::endl; sb.clear(); float f = 4.33243343f; sb.append("Jon says: "); sb.appendFormat("%d %s %5.3f")(2343)(" Derek! ")(f); sb.endl(); // Printing : StringBuilder supports both output methods std::cout << sb; sb.toScreen(); // Print whole thing sb.toScreen(16,14); // or subranges! std::cout << std::endl << std::endl; } int main_inner(int argc, char** argv); int main( int argc, char** argv ) { //if( argc <= 1 ) return -1; PrintFullpdHeader(); #ifdef _DEBUG return main_inner(argc,argv); #else try { return main_inner(argc,argv); } catch( ExceptionBase ex ) { return -1; } #endif } int main_inner(int argc, char** argv) { // Text and tools //Test_StringSystem(); //Test_Quote(); //Test_CharacterMap(); //Test_Alignment_Code(); //Test_StatClock(); // Simulations //Test_MD(); //Test_Minimisation(); //Test_TorsionalMinimisation(); // FileIO //Test_PDB_In(); Test_PDB_Sim("2drp40to65"); //Test_Tra_In(); return 0; }
22.734622
114
0.681045
[ "vector", "model" ]
3ef367fca605fa4293eb4970c894f8375a4f23b1
1,041
cpp
C++
week2/day13_Contiguous_Array.cpp
stefpant/30-Day-LeetCoding-Challenge
92ff3a47152559f27203001c0aeb96515154b6e1
[ "MIT" ]
2
2020-05-01T10:04:26.000Z
2020-05-01T11:54:40.000Z
week2/day13_Contiguous_Array.cpp
stefpant/30-Day-LeetCoding-Challenge
92ff3a47152559f27203001c0aeb96515154b6e1
[ "MIT" ]
null
null
null
week2/day13_Contiguous_Array.cpp
stefpant/30-Day-LeetCoding-Challenge
92ff3a47152559f27203001c0aeb96515154b6e1
[ "MIT" ]
null
null
null
class Solution { public: int findMaxLength(vector<int>& nums) { unordered_map<int, int> hm; int maxLen = 0; int sum = 0; int size = nums.size(); for(int i=0; i<size; i++){ if(nums[i])//having a sum to know where subarrays have equal 0's and 1's sum += 1; else sum -= 1; if(sum == 0) maxLen = i+1;//if sum==0, array with equal 0,1's starts from pos 0 to 'i' //if found same sum != 0, in 2 diferent positions, then //subarray from pos1 to pos2 has equal 0's and 1's //to achieve that: //use a hashmap to keep unique sums and its first pos that appears //then if sum appears again check length of subarray to get the maximum of them if(hm.find(sum + size) != hm.end()){ if(i-hm[sum+size] > maxLen) maxLen = i - hm[sum + size]; } else hm[sum + size] = i; } return maxLen; } };
35.896552
98
0.497598
[ "vector" ]
3ef55775d1a4a27227298e6833e37a2dee59adcf
2,389
cpp
C++
MathNumberTheory/pollard_rho.cpp
drken1215/algorithm
e68bcd2056453694130f6d2e7214b16589aa417d
[ "CC0-1.0" ]
197
2018-08-19T06:49:14.000Z
2022-03-26T04:11:48.000Z
MathNumberTheory/pollard_rho.cpp
drken1215/algorithm
e68bcd2056453694130f6d2e7214b16589aa417d
[ "CC0-1.0" ]
null
null
null
MathNumberTheory/pollard_rho.cpp
drken1215/algorithm
e68bcd2056453694130f6d2e7214b16589aa417d
[ "CC0-1.0" ]
15
2018-09-14T09:15:12.000Z
2021-11-16T12:43:43.000Z
// // Pollard ใฎใƒญใƒผ็ด ๅ› ๆ•ฐๅˆ†่งฃๆณ• // // verifed // ใ‚ขใƒซใ‚ดๅผ ็•ชๅค–็ทจ๏ผšใƒใƒฉใƒผใƒ‰ใฎใƒญใƒผ็ด ๅ› ๆ•ฐๅˆ†่งฃๆณ• // https://algo-method.com/tasks/553 // #include <iostream> #include <vector> #include <cmath> #include <algorithm> using namespace std; // Miller-Rabin ็ด ๆ•ฐๅˆคๅฎšๆณ• template<class T> T pow_mod(T A, T N, T M) { T res = 1 % M; A %= M; while (N) { if (N & 1) res = (res * A) % M; A = (A * A) % M; N >>= 1; } return res; } bool is_prime(long long N) { if (N <= 1) return false; if (N == 2 || N == 3) return true; if (N % 2 == 0) return false; vector<long long> A = {2, 325, 9375, 28178, 450775, 9780504, 1795265022}; long long s = 0, d = N - 1; while (d % 2 == 0) { ++s; d >>= 1; } for (auto a : A) { if (a % N == 0) return true; long long t, x = pow_mod<__int128_t>(a, d, N); if (x != 1) { for (t = 0; t < s; ++t) { if (x == N - 1) break; x = __int128_t(x) * x % N; } if (t == s) return false; } } return true; } // Pollard ใฎใƒญใƒผๆณ• long long gcd(long long A, long long B) { A = abs(A), B = abs(B); if (B == 0) return A; else return gcd(B, A % B); } long long pollard(long long N) { if (N % 2 == 0) return 2; if (is_prime(N)) return N; auto f = [&](long long x) -> long long { return (__int128_t(x) * x + 1) % N; }; long long step = 0; while (true) { ++step; long long x = step, y = f(x); while (true) { long long p = gcd(y - x + N, N); if (p == 0 || p == N) break; if (p != 1) return p; x = f(x); y = f(f(y)); } } } vector<long long> prime_factorize(long long N) { if (N == 1) return {}; long long p = pollard(N); if (p == N) return {p}; vector<long long> left = prime_factorize(p); vector<long long> right = prime_factorize(N / p); left.insert(left.end(), right.begin(), right.end()); sort(left.begin(), left.end()); return left; } int main() { // ๅ…ฅๅŠ› int N; cin >> N; vector<long long> A(N); for (int i = 0; i < N; ++i) cin >> A[i]; // ็ด ๅ› ๆ•ฐๅˆ†่งฃ for (auto a : A) { const auto& res = prime_factorize(a); for (auto p : res) cout << p << " "; cout << endl; } }
22.12037
56
0.452072
[ "vector" ]
3ef6d404a954716664a146e03399f483c9914c2a
2,021
cc
C++
wav_util.cc
Siddhant-K-code/lyra
9721651ababfc95e7ebd4547a5cc30460d56d491
[ "Apache-2.0" ]
3,056
2021-04-06T03:03:44.000Z
2022-03-30T11:47:37.000Z
wav_util.cc
Siddhant-K-code/lyra
9721651ababfc95e7ebd4547a5cc30460d56d491
[ "Apache-2.0" ]
76
2021-04-06T20:26:11.000Z
2022-03-12T16:00:24.000Z
wav_util.cc
Siddhant-K-code/lyra
9721651ababfc95e7ebd4547a5cc30460d56d491
[ "Apache-2.0" ]
283
2021-04-06T09:28:16.000Z
2022-03-30T01:54:01.000Z
// Copyright 2021 Google LLC // // 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 "wav_util.h" #include "absl/status/statusor.h" #include "absl/strings/str_cat.h" #include "audio/dsp/portable/read_wav_file.h" #include "audio/dsp/portable/write_wav_file.h" namespace chromemedia::codec { absl::StatusOr<ReadWavResult> Read16BitWavFileToVector( const std::string& file_name) { int num_channels; int sample_rate_hz; size_t read_num_samples; int16_t* out_buffer = Read16BitWavFile(file_name.c_str(), &read_num_samples, &num_channels, &sample_rate_hz); if (out_buffer == nullptr) { return absl::AbortedError( absl::StrCat("Failed to read from wav at path: ", file_name)); } std::vector<int16_t> samples(out_buffer, out_buffer + read_num_samples); free(out_buffer); return ReadWavResult{samples, num_channels, sample_rate_hz}; } absl::Status Write16BitWavFileFromVector(const std::string& file_name, int num_channels, int sample_rate_hz, const std::vector<int16_t>& samples) { int status = WriteWavFile(file_name.c_str(), samples.data(), samples.size(), sample_rate_hz, num_channels); // WriteWavFile has a success code of 1. if (status == 1) { return absl::OkStatus(); } return absl::AbortedError( absl::StrCat("Failed to write to wav file at: ", file_name)); } } // namespace chromemedia::codec
35.45614
79
0.683325
[ "vector" ]
3ef86dd4024d4f838e256f9d5e1589bbce293247
15,303
cpp
C++
reactions/src/FlowingWithTime.cpp
PedroCarrilho/ReACT
507866e9462ecf10c298fcd3e2c81249f32e7d50
[ "MIT" ]
3
2020-07-07T11:34:02.000Z
2021-07-15T12:48:05.000Z
reactions/src/FlowingWithTime.cpp
PedroCarrilho/ReACT
507866e9462ecf10c298fcd3e2c81249f32e7d50
[ "MIT" ]
11
2020-05-29T16:26:06.000Z
2022-02-07T08:59:52.000Z
reactions/src/FlowingWithTime.cpp
PedroCarrilho/ReACT
507866e9462ecf10c298fcd3e2c81249f32e7d50
[ "MIT" ]
1
2021-08-31T15:35:28.000Z
2021-08-31T15:35:28.000Z
#if HAVE_CONFIG_H # include <config.h> #endif #include <algorithm> #include <cassert> #include "FlowingWithTime.h" #include "GrowthFunction.h" #include "InterpolatedPS.h" #include "Quadrature.h" #include "ODE.h" #include <functional> using std::cref; using std::bind; /* My translation of code <-> theory: * X(0,i) = $P_11(k[i])$ * X(1,i) = $P_12(k[i])$ * X(2,i) = $P_22(k[i])$ * X(3,i) = $I_{112,111}(k[i])$ * X(4,i) = $I_{112,112}(k[i])$ * X(5,i) = $I_{112,122}(k[i])$ * X(6,i) = $I_{112,211}(k[i])$ * X(7,i) = $I_{112,212}(k[i])$ * X(8,i) = $I_{112,222}(k[i])$ * X(9,i) = $I_{222,111}(k[i])$ * X(10,i) = $I_{222,112}(k[i])$ * X(11,i) = $I_{222,122}(k[i])$ * X(12,i) = $I_{222,211}(k[i])$ * X(13,i) = $I_{222,212}(k[i])$ * X(14,i) = $I_{222,222}(k[i])$ * * It's not obvious from the definition that $I_{acd,bef}(k)$ is symmetric * in its last two indices $ef$. This result follows from the fact that * it is initially symmetric ($I_{acd,bef} = 0$ at $\eta = 0$) and the * equations of motion preserve this symmetry. * * See Appendix B of Pietroni's paper for an explanation of the code below. */ /* Tolerance parameter for mode-coupling integrals [Eq (B.6)] */ const real EPSREL = 1e-4; const real XMAX = 25; FlowingWithTime::FlowingWithTime(const Cosmology& C_, real z_i, const PowerSpectrum& P_i_, const array& k_) : C(C_), P_i(P_i_), k(k_) { a_i = 1/(1 + z_i); Nk = k.size(); } FlowingWithTime::~FlowingWithTime() { } static real zero = 0; InterpolatedP_ab::InterpolatedP_ab(const Cosmology& C, int N, const real* k, const real* p11, const real* p12, const real* p22) : P_11(C, N, k, p11), P_12(C, N, k, p12), P_22(C, N, k, p22) { ka = k[0]; kb = k[N-1]; p11a = p11[0]; p11b = p11[N-1]; p12a = p12[0]; p12b = p12[N-1]; p22a = p22[0]; p22b = p22[N-1]; } real InterpolatedP_ab::operator()(int a, int b, real k) const { switch(a*b) { case 1: if(k <= ka) return exp(-pow2((k-ka)/k)) * p11a; else if(k >= kb) return exp(-4*pow2((k-kb)/kb)) * p11b; else return P_11(k); case 2: if(k <= ka) return exp(-pow2((k-ka)/k)) * p12a; else if(k >= kb) return exp(-4*pow2((k-kb)/kb)) * p12b; else return P_12(k); case 4: if(k <= ka) return exp(-pow2((k-ka)/k)) * p22a; else if(k >= kb) return exp(-4*pow2((k-kb)/kb)) * p22b; else return P_22(k); // case 1: return P_11(k); // case 2: return P_12(k); // case 4: return P_22(k); default: warning("[InterpolatedP_ab] index error: a = %d, b = %d\n", a, b); return 0; } } /* $P_{ab}(k[i])$ */ struct IndexedP_ab { vector<real>& X; int Nk; IndexedP_ab(vector<real>& X_) : X(X_) { Nk = X.size()/15; } #if 0 real operator()(int a, int b, int i) const { switch(a*b) { case 1: return exp(X[i]); case 2: return exp(X[Nk+i]); case 4: return exp(X[2*Nk+i]); default: warning("[IndexedP_ab] index error: a = %d, b = %d\n", a, b); return 0; } } #endif real& operator()(int a, int b, int i) { switch(a*b) { case 1: return X[i]; case 2: return X[Nk+i]; case 4: return X[2*Nk+i]; default: warning("[IndexedP_ab] index error: a = %d, b = %d\n", a, b); return zero; } } }; /* Mapping of $(acd,bef)$ into X[n*Nk+i] */ static int m_to_n[64] = { /* 111,111 */ -1, /* 0 */ /* 111,112 */ -1, /* 0 */ /* 111,121 */ -1, /* 0 */ /* 111,122 */ -1, /* 0 */ /* 111,211 */ -1, /* 0 */ /* 111,212 */ -1, /* 0 */ /* 111,221 */ -1, /* 0 */ /* 111,222 */ -1, /* 0 */ /* 112,111 */ 3, /* X(3) */ /* 112,112 */ 4, /* X(4) */ /* 112,121 */ 4, /* = 112,112 */ /* 112,122 */ 5, /* X(5) */ /* 112,211 */ 6, /* X(6) */ /* 112,212 */ 7, /* X(7) */ /* 112,221 */ 7, /* = 112,212 */ /* 112,222 */ 8, /* X(8) */ /* 121,111 */ 3, /* = 112,111 */ /* 121,112 */ 4, /* = 112,112 */ /* 121,121 */ 4, /* = 112,112 */ /* 121,122 */ 5, /* = 112,122 */ /* 121,211 */ 6, /* = 112,211 */ /* 121,212 */ 7, /* = 112,212 */ /* 121,221 */ 7, /* = 112,212 */ /* 121,222 */ 8, /* = 112,222 */ /* 122,111 */ -1, /* 0 */ /* 122,112 */ -1, /* 0 */ /* 122,121 */ -1, /* 0 */ /* 122,122 */ -1, /* 0 */ /* 122,211 */ -1, /* 0 */ /* 122,212 */ -1, /* 0 */ /* 122,221 */ -1, /* 0 */ /* 122,222 */ -1, /* 0 */ /* 211,111 */ -1, /* 0 */ /* 211,112 */ -1, /* 0 */ /* 211,121 */ -1, /* 0 */ /* 211,122 */ -1, /* 0 */ /* 211,211 */ -1, /* 0 */ /* 211,212 */ -1, /* 0 */ /* 211,221 */ -1, /* 0 */ /* 211,222 */ -1, /* 0 */ /* 212,111 */ -1, /* 0 */ /* 212,112 */ -1, /* 0 */ /* 212,121 */ -1, /* 0 */ /* 212,122 */ -1, /* 0 */ /* 212,211 */ -1, /* 0 */ /* 212,212 */ -1, /* 0 */ /* 212,221 */ -1, /* 0 */ /* 212,222 */ -1, /* 0 */ /* 221,111 */ -1, /* 0 */ /* 221,112 */ -1, /* 0 */ /* 221,121 */ -1, /* 0 */ /* 221,122 */ -1, /* 0 */ /* 221,211 */ -1, /* 0 */ /* 221,212 */ -1, /* 0 */ /* 221,221 */ -1, /* 0 */ /* 221,222 */ -1, /* 0 */ /* 222,111 */ 9, /* X(9) */ /* 222,112 */ 10, /* X(10) */ /* 222,121 */ 10, /* = 222,112 */ /* 222,122 */ 11, /* X(11) */ /* 222,211 */ 12, /* X(12) */ /* 222,212 */ 13, /* X(13) */ /* 222,221 */ 13, /* = 222,212 */ /* 222,222 */ 14 /* X(14) */ }; /* $I_{acd,bef}(k[i])$ */ struct IndexedI_acdbef { vector<real>& X; int Nk; IndexedI_acdbef(vector<real>& X_) : X(X_) { Nk = X.size()/15; } real& operator()(int a, int c, int d, int b, int e, int f, int i) { assert(zero == 0); // make sure we haven't somehow changed zero a--; b--; c--; d--; e--; f--; assert((a | b | c | d | e | f) < 2); // make sure indices are 1 or 2 int m = (a << 5) + (c << 4) + (d << 3) + (b << 2) + (e << 1) + (f << 0); int n = m_to_n[m]; if(n < 0) return zero; else return X[n*Nk+i]; } }; vector<InterpolatedP_ab> FlowingWithTime::CalculateP_ab(int Nz, const real zin[]) const { /* Copy and sort redshift list */ array z(Nz); for(int i = 0; i < Nz; i++) z[i] = zin[i]; std::sort(&z[0], &z[Nz]); std::reverse(&z[0], &z[Nz]); /* Make sure redshifts are now sequential */ for(int j = 0; j < Nz-1; j++) assert(z[j] > z[j+1]); /* Output list */ vector<InterpolatedP_ab> output; GrowthFunction D(C); array a(Nz); for(int j = 0; j < Nz; j++) a[j] = 1/(1 + z[j]); /* Initialize X */ vector<real> X(15*Nk); for(int i = 0; i < Nk; i++) X[i] = X[Nk+i] = X[2*Nk+i] = log(P_i(k[i])); real h_i = log(a[0]/a_i) / 100; // initial step size /* Start off with fixed time steps, to avoid some weirdness where the adaptive stepper can't get the integration started */ vector<vector<real> > Y = RungeKutta4(0, 10*h_i, X, bind(&FlowingWithTime::dXdeta, cref(*this), std::placeholders::_1, std::placeholders::_2), 10); for(int j = 0; j < 15*Nk; j++) X[j] = Y[j][9]; real eta = 10*h_i; array p11(Nk), p12(Nk), p22(Nk); for(int j = 0; j < Nz; j++) { /* Integrate forward to time a[j] */ real etaf = log(a[j]/a_i); int err = RKDP(eta, etaf, X, bind(&FlowingWithTime::dXdeta, cref(*this), std::placeholders::_1, std::placeholders::_2), X, 1e-3, h_i); if(err < 0) error("Aborting following error in RKDP.\n"); /* Save power spectrum */ real f = D.f(z[j]); IndexedP_ab logP(X); for(int i = 0; i < Nk; i++) { p11[i] = exp(logP(1,1, i)) * pow2(a[j]/a_i); p12[i] = exp(logP(1,2, i)) * pow2(a[j]/a_i) / f; p22[i] = exp(logP(2,2, i)) * pow2(a[j]/a_i) / (f*f); } output.push_back(InterpolatedP_ab(C, Nk, &k[0], p11, p12, p22)); /* Prepare for next step */ eta = etaf; } return output; } template<int m, int n> struct Matrix { real a[m*n]; real& operator()(int i, int j) { return a[(j-1)*n+(i-1)]; } }; vector<real> FlowingWithTime::dXdeta(real eta, vector<real>& X) const { real a = a_i * exp(eta); debug("\neta = %g, a = %g\n", eta, a); Matrix<2,2> Omega; Omega(1,1) = 1; Omega(1,2) = -1; Omega(2,1) = -1.5 * C.Omega_m*pow2(C.H0)/(pow3(a)*pow2(C.H(a))); Omega(2,2) = 3 + a/C.H(a) * C.dHda(a); debug("Omega = %g %g %g %g\n", Omega(1,1), Omega(1,2), Omega(2,1), Omega(2,2)); vector<real> dXdeta(15*Nk); IndexedP_ab logP(X); IndexedI_acdbef I(X); IndexedP_ab dlogPdeta(dXdeta); IndexedI_acdbef dIdeta(dXdeta); array p11(Nk), p12(Nk), p22(Nk); for(int i = 0; i < Nk; i++) { p11[i] = exp(logP(1,1, i)); p12[i] = exp(logP(1,2, i)); p22[i] = exp(logP(2,2, i)); } InterpolatedP_ab Pint(C, Nk, &k[0], p11, p12, p22); int i, c, d, g; #pragma omp parallel default(shared) private(i,c,d,g) #pragma omp for schedule(dynamic) for(i = 0; i < Nk; i++) { for(int n = 0; n < 3; n++) debug("%.2e ", exp(X[n*Nk+i])); // for(int n = 3; n < 15; n++) // debug("%.2e ", X[n*Nk+i]); debug("\n"); /* $\partial_\eta P_{ab}(k) = -\Omega_{ac} P_{cb}(k) - \Omega_{bc} P_{ac}(k) + e^\eta \frac{4\pi}{k} [I_{acd,bcd}(k) + I_{bcd,acd}(k)]$ */ dlogPdeta(1,1, i) = dlogPdeta(1,2, i) = dlogPdeta(2,2, i) = 0; for(c = 1; c <= 2; c++) { dlogPdeta(1,1, i) += -Omega(1,c)*exp(logP(c,1, i)) - Omega(1,c)*exp(logP(1,c, i)); dlogPdeta(1,2, i) += -Omega(1,c)*exp(logP(c,2, i)) - Omega(2,c)*exp(logP(1,c, i)); dlogPdeta(2,2, i) += -Omega(2,c)*exp(logP(c,2, i)) - Omega(2,c)*exp(logP(2,c, i)); for(d = 1; d <= 2; d++) { dlogPdeta(1,1, i) += exp(eta) * 4*M_PI/k[i] * (I(1,c,d,1,c,d, i) + I(1,c,d,1,c,d, i)); dlogPdeta(1,2, i) += exp(eta) * 4*M_PI/k[i] * (I(1,c,d,2,c,d, i) + I(2,c,d,1,c,d, i)); dlogPdeta(2,2, i) += exp(eta) * 4*M_PI/k[i] * (I(2,c,d,2,c,d, i) + I(2,c,d,2,c,d, i)); } } dlogPdeta(1,1, i) /= exp(logP(1,1, i)); dlogPdeta(1,2, i) /= exp(logP(1,2, i)); dlogPdeta(2,2, i) /= exp(logP(2,2, i)); /* $\partial_\eta I_{acd,bef}(k) = -\Omega_{bg} I_{acd,gef}(k) - \Omega_{eg} I_{acd,bgf}(k) - \Omega_{fg} I_{acd,beg}(k) + 2 e^\eta A_{acd,bef}(k)$ */ dIdeta(1,1,2,1,1,1, i) = 2*exp(eta) * A(Pint, 1,1,2,1,1,1, k[i]); dIdeta(1,1,2,1,1,2, i) = 2*exp(eta) * A(Pint, 1,1,2,1,1,2, k[i]); dIdeta(1,1,2,1,2,2, i) = 2*exp(eta) * A(Pint, 1,1,2,1,2,2, k[i]); dIdeta(1,1,2,2,1,1, i) = 2*exp(eta) * A(Pint, 1,1,2,2,1,1, k[i]); dIdeta(1,1,2,2,1,2, i) = 2*exp(eta) * A(Pint, 1,1,2,2,1,2, k[i]); dIdeta(1,1,2,2,2,2, i) = 2*exp(eta) * A(Pint, 1,1,2,2,2,2, k[i]); dIdeta(2,2,2,1,1,1, i) = 2*exp(eta) * A(Pint, 2,2,2,1,1,1, k[i]); dIdeta(2,2,2,1,1,2, i) = 2*exp(eta) * A(Pint, 2,2,2,1,1,2, k[i]); dIdeta(2,2,2,1,2,2, i) = 2*exp(eta) * A(Pint, 2,2,2,1,2,2, k[i]); dIdeta(2,2,2,2,1,1, i) = 2*exp(eta) * A(Pint, 2,2,2,2,1,1, k[i]); dIdeta(2,2,2,2,1,2, i) = 2*exp(eta) * A(Pint, 2,2,2,2,1,2, k[i]); dIdeta(2,2,2,2,2,2, i) = 2*exp(eta) * A(Pint, 2,2,2,2,2,2, k[i]); for(g = 1; g <= 2; g++) { dIdeta(1,1,2,1,1,1, i) += -Omega(1,g)*I(1,1,2,g,1,1, i) - Omega(1,g)*I(1,1,2,1,g,1, i) - Omega(1,g)*I(1,1,2,1,1,g, i); dIdeta(1,1,2,1,1,2, i) += -Omega(1,g)*I(1,1,2,g,1,2, i) - Omega(1,g)*I(1,1,2,1,g,2, i) - Omega(2,g)*I(1,1,2,1,1,g, i); dIdeta(1,1,2,1,2,2, i) += -Omega(1,g)*I(1,1,2,g,2,2, i) - Omega(2,g)*I(1,1,2,1,g,2, i) - Omega(2,g)*I(1,1,2,1,2,g, i); dIdeta(1,1,2,2,1,1, i) += -Omega(2,g)*I(1,1,2,g,1,1, i) - Omega(1,g)*I(1,1,2,2,g,1, i) - Omega(1,g)*I(1,1,2,2,1,g, i); dIdeta(1,1,2,2,1,2, i) += -Omega(2,g)*I(1,1,2,g,1,2, i) - Omega(1,g)*I(1,1,2,2,g,2, i) - Omega(2,g)*I(1,1,2,2,1,g, i); dIdeta(1,1,2,2,2,2, i) += -Omega(2,g)*I(1,1,2,g,2,2, i) - Omega(2,g)*I(1,1,2,2,g,2, i) - Omega(2,g)*I(1,1,2,2,2,g, i); dIdeta(2,2,2,1,1,1, i) += -Omega(1,g)*I(2,2,2,g,1,1, i) - Omega(1,g)*I(2,2,2,1,g,1, i) - Omega(1,g)*I(2,2,2,1,1,g, i); dIdeta(2,2,2,1,1,2, i) += -Omega(1,g)*I(2,2,2,g,1,2, i) - Omega(1,g)*I(2,2,2,1,g,2, i) - Omega(2,g)*I(2,2,2,1,1,g, i); dIdeta(2,2,2,1,2,2, i) += -Omega(1,g)*I(2,2,2,g,2,2, i) - Omega(2,g)*I(2,2,2,1,g,2, i) - Omega(2,g)*I(2,2,2,1,2,g, i); dIdeta(2,2,2,2,1,1, i) += -Omega(2,g)*I(2,2,2,g,1,1, i) - Omega(1,g)*I(2,2,2,2,g,1, i) - Omega(1,g)*I(2,2,2,2,1,g, i); dIdeta(2,2,2,2,1,2, i) += -Omega(2,g)*I(2,2,2,g,1,2, i) - Omega(1,g)*I(2,2,2,2,g,2, i) - Omega(2,g)*I(2,2,2,2,1,g, i); dIdeta(2,2,2,2,2,2, i) += -Omega(2,g)*I(2,2,2,g,2,2, i) - Omega(2,g)*I(2,2,2,2,g,2, i) - Omega(2,g)*I(2,2,2,2,2,g, i); } } return dXdeta; } static real gamma(int a, int b, int c, real k2, real q2, real p2) { if(a == 1) { if(b == 1 && c == 2) return (k2 - q2 + p2)/(4*p2); else if(b == 2 && c == 1) return (k2 + q2 - p2)/(4*q2); else return 0; } else if(a == 2 && b == 2 && c == 2) return k2*(k2 - q2 - p2)/(4*q2*p2); else return 0; } static bool nonzero(int a, int b, int c) { return (a == 1 && b*c == 2) || (a*b*c == 8); } static real F_A(const InterpolatedP_ab& P, int a, int c, int d, int b, int e, int f, real k, real q, real p) { real k2 = k*k, q2 = q*q, p2 = p*p; real S = 0; for(int g = 1; g <= 2; g++) for(int h = 1; h <= 2; h++) S += (nonzero(b,g,h) ? gamma(b,g,h, k2,q2,p2) * P(g,e, q) * P(h,f, p) : 0) + (nonzero(e,g,h) ? gamma(e,g,h, q2,p2,k2) * P(g,f, p) * P(h,b, k) : 0) + (nonzero(f,g,h) ? gamma(f,g,h, p2,k2,q2) * P(g,b, k) * P(h,e, q) : 0); return 0.5*gamma(a,c,d, k2,q2,p2) * S; } static real f_A(const InterpolatedP_ab& P, int* acdbef, real k, real x, real y) { int a = acdbef[0]; int c = acdbef[1]; int d = acdbef[2]; int b = acdbef[3]; int e = acdbef[4]; int f = acdbef[5]; real q = (x+y)/M_SQRT2; real p = (x-y)/M_SQRT2; return q*p * ( F_A(P, a,c,d,b,e,f, k,q,p) + F_A(P, a,c,d,b,e,f, k,p,q) ); } real FlowingWithTime::A(const InterpolatedP_ab& P, int a, int c, int d, int b, int e, int f, real k1) const { int acdbef[6] = { a, c, d, b, e, f }; real min[2] = { k1/M_SQRT2, 0 }; real max[2] = { XMAX, k1/M_SQRT2 - 1e-5 }; return 1/pow3(2*M_PI) * Integrate<2>(bind(f_A, cref(P), acdbef, k1, std::placeholders::_1, std::placeholders::_2), min, max, EPSREL); }
35.838407
158
0.449324
[ "vector" ]
3efe051abf48e3361e1234a9eea280a0b7b1eee5
2,529
hpp
C++
geometry/packer.hpp
marceldallagnol/omim
774de15a3b8c369acbf412f15a1db61717358262
[ "Apache-2.0" ]
2
2019-01-24T15:36:20.000Z
2019-12-26T10:03:48.000Z
geometry/packer.hpp
marceldallagnol/omim
774de15a3b8c369acbf412f15a1db61717358262
[ "Apache-2.0" ]
1
2018-03-07T15:05:23.000Z
2018-03-07T15:05:23.000Z
geometry/packer.hpp
marceldallagnol/omim
774de15a3b8c369acbf412f15a1db61717358262
[ "Apache-2.0" ]
1
2019-08-09T21:31:29.000Z
2019-08-09T21:31:29.000Z
#pragma once #include "geometry/rect2d.hpp" #include "std/list.hpp" #include "std/map.hpp" #include "std/function.hpp" #include "std/queue.hpp" #include "std/utility.hpp" #include "std/vector.hpp" namespace m2 { template <typename pair_t> struct first_less { bool operator()(pair_t const & first, pair_t const & second) { return first.first < second.first; } }; /// The simplest row-by-row packer. /// When there is no free room all the packing /// rect is cleared and the process is started again. class Packer { public: typedef function<void()> overflowFn; typedef priority_queue<pair<size_t, overflowFn>, vector<pair<size_t, overflowFn> >, first_less<pair<size_t, overflowFn> > > overflowFns; typedef uint32_t handle_t; typedef std::pair<bool, m2::RectU> find_result_t; private: unsigned m_currentX; unsigned m_currentY; unsigned m_yStep; unsigned m_width; unsigned m_height; overflowFns m_overflowFns; handle_t m_currentHandle; typedef map<handle_t, m2::RectU> rects_t; rects_t m_rects; void callOverflowFns(); uint32_t m_maxHandle; uint32_t m_invalidHandle; public: Packer(); /// create a packer on a rectangular area of (0, 0, width, height) dimensions Packer(unsigned width, unsigned height, uint32_t maxHandle = 0xFFFF - 1); /// reset the state of the packer void reset(); /// add overflow handler. /// @param priority handlers with higher priority value are called first. void addOverflowFn(overflowFn fn, int priority); /// pack the rect with dimensions width X height on a free area. /// when there is no free area - find it somehow(depending on a packer implementation, /// the simplest one will just clear the whole rect and start the packing process again). handle_t pack(unsigned width, unsigned height); /// return free handle handle_t freeHandle(); /// Does we have room to pack another rectangle? bool hasRoom(unsigned width, unsigned height) const; /// Does we have room to pack a sequence of rectangles? bool hasRoom(m2::PointU const * sizes, size_t cnt) const; /// is the handle present on the texture. bool isPacked(handle_t handle); /// find the packed area by the handle. find_result_t find(handle_t handle) const; /// remove the handle from the list of active handles. void remove(handle_t handle); /// get an invalid handle uint32_t invalidHandle() const; }; }
25.039604
140
0.689996
[ "geometry", "vector" ]
410690b10dca2f00772605be9dbaea002758390c
14,146
cpp
C++
tests/Agency/SupervisionTest.cpp
elfringham/arangodb
5baaece1c7a5ce73fe016f07ed66255cc555e8cb
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
tests/Agency/SupervisionTest.cpp
elfringham/arangodb
5baaece1c7a5ce73fe016f07ed66255cc555e8cb
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
tests/Agency/SupervisionTest.cpp
elfringham/arangodb
5baaece1c7a5ce73fe016f07ed66255cc555e8cb
[ "BSL-1.0", "Apache-2.0" ]
1
2016-03-30T14:43:34.000Z
2016-03-30T14:43:34.000Z
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2020 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany /// /// 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. /// /// Copyright holder is ArangoDB GmbH, Cologne, Germany /// /// @author Kaveh Vahedipour /// @author Copyright 2017, ArangoDB GmbH, Cologne, Germany //////////////////////////////////////////////////////////////////////////////// #include "Agency/AgentInterface.h" #include "Agency/Job.h" #include "Agency/Supervision.h" #include "Mocks/Servers.h" #include "gtest/gtest.h" #include "fakeit.hpp" #include <velocypack/Iterator.h> #include <velocypack/velocypack-aliases.h> #include <typeinfo> using namespace arangodb; using namespace arangodb::consensus; std::vector<std::string> servers{"XXX-XXX-XXX", "XXX-XXX-XXY"}; TEST(SupervisionTest, checking_for_the_delete_transaction_0_servers) { std::vector<std::string> todelete; auto const& transaction = removeTransactionBuilder(todelete); auto const& slice = transaction->slice(); ASSERT_TRUE(slice.isArray()); ASSERT_EQ(slice.length(), 1); ASSERT_TRUE(slice[0].isArray()); ASSERT_EQ(slice[0].length(), 1); ASSERT_TRUE(slice[0][0].isObject()); ASSERT_EQ(slice[0][0].length(), 0); } TEST(SupervisionTest, checking_for_the_delete_transaction_1_server) { std::vector<std::string> todelete{servers[0]}; auto const& transaction = removeTransactionBuilder(todelete); auto const& slice = transaction->slice(); ASSERT_TRUE(slice.isArray()); ASSERT_EQ(slice.length(), 1); ASSERT_TRUE(slice[0].isArray()); ASSERT_EQ(slice[0].length(), 1); ASSERT_TRUE(slice[0][0].isObject()); ASSERT_EQ(slice[0][0].length(), 1); for (size_t i = 0; i < slice[0][0].length(); ++i) { ASSERT_TRUE(slice[0][0].keyAt(i).copyString() == Supervision::agencyPrefix() + arangodb::consensus::healthPrefix + servers[i]); ASSERT_TRUE(slice[0][0].valueAt(i).isObject()); ASSERT_EQ(slice[0][0].valueAt(i).keyAt(0).copyString(), "op"); ASSERT_EQ(slice[0][0].valueAt(i).valueAt(0).copyString(), "delete"); } } TEST(SupervisionTest, checking_for_the_delete_transaction_2_servers) { std::vector<std::string> todelete = servers; auto const& transaction = removeTransactionBuilder(todelete); auto const& slice = transaction->slice(); ASSERT_TRUE(slice.isArray()); ASSERT_EQ(slice.length(), 1); ASSERT_TRUE(slice[0].isArray()); ASSERT_EQ(slice[0].length(), 1); ASSERT_TRUE(slice[0][0].isObject()); ASSERT_EQ(slice[0][0].length(), 2); for (size_t i = 0; i < slice[0][0].length(); ++i) { ASSERT_TRUE(slice[0][0].keyAt(i).copyString() == Supervision::agencyPrefix() + arangodb::consensus::healthPrefix + servers[i]); ASSERT_TRUE(slice[0][0].valueAt(i).isObject()); ASSERT_EQ(slice[0][0].valueAt(i).keyAt(0).copyString(), "op"); ASSERT_EQ(slice[0][0].valueAt(i).valueAt(0).copyString(), "delete"); } } static Node createNodeFromBuilder(Builder const& builder) { Builder opBuilder; { VPackObjectBuilder a(&opBuilder); opBuilder.add("new", builder.slice()); } Node node(""); node.handle<SET>(opBuilder.slice()); return node; } static Builder createBuilder(char const* c) { Options options; options.checkAttributeUniqueness = true; VPackParser parser(&options); parser.parse(c); Builder builder; builder.add(parser.steal()->slice()); return builder; } static Node createNode(char const* c) { return createNodeFromBuilder(createBuilder(c)); } static char const* skeleton = R"=( { "Plan": { "Collections": { "database": { "123": { "replicationFactor": 2, "shards": { "s1": [ "leader", "follower1" ] } }, "124": { "replicationFactor": 2, "shards": { "s2": [ "leader", "follower1" ] } }, "125": { "replicationFactor": 2, "distributeShardsLike": "124", "shards": { "s3": [ "leader", "follower1" ] } }, "126": { "replicationFactor": 2, "distributeShardsLike": "124", "shards": { "s4": [ "leader", "follower1" ] } } } }, "DBServers": { "follower1": "none", "follower2": "none", "follower3": "none", "follower4": "none", "follower5": "none", "follower6": "none", "follower7": "none", "follower8": "none", "follower9": "none", "free": "none", "free2": "none", "leader": "none" } }, "Current": { "Collections": { "database": { "123": { "s1": { "servers": [ "leader", "follower1" ] } }, "124": { "s2": { "servers": [ "leader", "follower1" ] } }, "125": { "s3": { "servers": [ "leader", "follower1" ] } }, "126": { "s4": { "servers": [ "leader", "follower1" ] } } } } }, "Supervision": { "DBServers": {}, "Health": { "follower1": { "Status": "GOOD" }, "follower2": { "Status": "GOOD" }, "follower3": { "Status": "GOOD" }, "follower4": { "Status": "GOOD" }, "follower5": { "Status": "GOOD" }, "follower6": { "Status": "GOOD" }, "follower7": { "Status": "GOOD" }, "follower8": { "Status": "GOOD" }, "follower9": { "Status": "GOOD" }, "leader": { "Status": "GOOD" }, "free": { "Status": "GOOD" }, "free2": { "Status": "FAILED" } }, "Shards": {} }, "Target": { "Failed": {}, "Finished": {}, "ToDo": {}, "HotBackup": { "TransferJobs": { } } } } )="; // Now we want to test the Supervision main function. We do this piece // by piece for now. We instantiate a Supervision object, manipulate the // agency snapshot it has and then check behaviour of member functions. class SupervisionTestClass : public ::testing::Test { public: SupervisionTestClass() : _snapshot(createNode(skeleton)) { } ~SupervisionTestClass() {} protected: Node _snapshot; }; static std::shared_ptr<VPackBuilder> runEnforceReplication(Node const& snap) { auto envelope = std::make_shared<VPackBuilder>(); uint64_t jobId = 1; { VPackObjectBuilder guard(envelope.get()); arangodb::consensus::enforceReplicationFunctional( snap, jobId, envelope); } return envelope; } static std::shared_ptr<VPackBuilder> runCleanupHotbackupTransferJobs( Node const& snap) { auto envelope = std::make_shared<VPackBuilder>(); { VPackObjectBuilder guard(envelope.get()); arangodb::consensus::cleanupHotbackupTransferJobsFunctional( snap, envelope); } return envelope; } static void checkSupervisionJob(VPackSlice v, std::string const& type, std::string const& database, std::string const& coll, std::string const& shard) { EXPECT_TRUE(v.isObject()); EXPECT_EQ(v["creator"].copyString(), "supervision"); EXPECT_EQ(v["type"].copyString(), type); EXPECT_EQ(v["database"].copyString(), database); EXPECT_EQ(v["collection"].copyString(), coll); EXPECT_EQ(v["shard"].copyString(), shard); } TEST_F(SupervisionTestClass, enforce_replication_nothing_to_do) { std::shared_ptr<VPackBuilder> envelope = runEnforceReplication(_snapshot); VPackSlice content = envelope->slice(); EXPECT_EQ(content.length(), 0); } TEST_F(SupervisionTestClass, schedule_removefollower) { _snapshot("/Plan/Collections/database/123/shards/s1") = createNode(R"=(["leader", "follower1", "follower2"])="); _snapshot("/Current/Collections/database/123/s1/servers") = createNode(R"=(["leader", "follower1", "follower2"])="); std::shared_ptr<VPackBuilder> envelope = runEnforceReplication(_snapshot); VPackSlice v = envelope->slice(); EXPECT_EQ(v.length(), 1); v = v["/Target/ToDo/1"]; checkSupervisionJob(v, "removeFollower", "database", "123", "s1"); EXPECT_EQ(v["jobId"].copyString(), "1"); } TEST_F(SupervisionTestClass, schedule_addfollower) { _snapshot("/Plan/Collections/database/123/shards/s1") = createNode(R"=(["leader"])="); _snapshot("/Current/Collections/database/123/s1/servers") = createNode(R"=(["leader"])="); std::shared_ptr<VPackBuilder> envelope = runEnforceReplication(_snapshot); VPackSlice v = envelope->slice(); EXPECT_EQ(v.length(), 1); v = v["/Target/ToDo/1"]; checkSupervisionJob(v, "addFollower", "database", "123", "s1"); } TEST_F(SupervisionTestClass, schedule_addfollower_rf_3) { _snapshot("/Plan/Collections/database/123/replicationFactor") = createNode(R"=(3)="); std::shared_ptr<VPackBuilder> envelope = runEnforceReplication(_snapshot); VPackSlice v = envelope->slice(); EXPECT_EQ(v.length(), 1); v = v["/Target/ToDo/1"]; checkSupervisionJob(v, "addFollower", "database", "123", "s1"); } static std::unordered_map<std::string, std::string> tableOfJobs(VPackSlice envelope) { std::unordered_map<std::string, std::string> res; for (auto const& p : VPackObjectIterator(envelope)) { res.emplace(std::pair(p.value.get("collection").copyString(), p.key.copyString())); } return res; } TEST_F(SupervisionTestClass, schedule_addfollower_bad_server) { _snapshot("/Supervision/Health/follower1") = createNode(R"=("FAILED")="); std::shared_ptr<VPackBuilder> envelope = runEnforceReplication(_snapshot); VPackSlice todo = envelope->slice(); EXPECT_EQ(todo.length(), 2); auto table = tableOfJobs(todo); checkSupervisionJob(todo[table["123"]], "addFollower", "database", "123", "s1"); checkSupervisionJob(todo[table["124"]], "addFollower", "database", "124", "s2"); } TEST_F(SupervisionTestClass, no_remove_follower_loop) { // This tests the case which used to have an unholy loop of scheduling // a removeFollower job and immediately terminating it and so on. // Now, no removeFollower job should be scheduled. _snapshot("/Plan/Collections/database/123/replicationFactor") = createNode(R"=(3)="); _snapshot("/Plan/Collections/database/123/shards/s1") = createNode(R"=(["leader", "follower1", "follower2", "follower3"])="); _snapshot("/Current/Collections/database/123/s1/servers") = createNode(R"=(["leader", "follower1", "follower2"])="); _snapshot("/Supervision/Health/follower1") = createNode(R"=("FAILED")="); std::shared_ptr<VPackBuilder> envelope = runEnforceReplication(_snapshot); VPackSlice content = envelope->slice(); EXPECT_EQ(content.length(), 1); VPackSlice w = content["/Target/ToDo/1"]; checkSupervisionJob(w, "addFollower", "database", "124", "s2"); } TEST_F(SupervisionTestClass, no_remove_follower_loop_distributeshardslike) { // This tests another case which used to have an unholy loop of scheduling // a removeFollower job and immediately terminating it and so on. // Now, no removeFollower job should be scheduled. _snapshot("/Plan/Collections/database/124/replicationFactor") = createNode(R"=(3)="); _snapshot("/Plan/Collections/database/124/shards/s2") = createNode(R"=(["leader", "follower1", "follower2", "follower3"])="); _snapshot("/Plan/Collections/database/125/shards/s3") = createNode(R"=(["leader", "follower1", "follower2", "follower3"])="); _snapshot("/Plan/Collections/database/126/shards/s4") = createNode(R"=(["leader", "follower1", "follower2", "follower3"])="); _snapshot("/Current/Collections/database/124/s2/servers") = createNode(R"=(["leader", "follower1", "follower2", "follower3"])="); _snapshot("/Current/Collections/database/125/s3/servers") = createNode(R"=(["leader", "follower1", "follower3"])="); _snapshot("/Current/Collections/database/126/s4/servers") = createNode(R"=(["leader", "follower1", "follower2"])="); std::shared_ptr<VPackBuilder> envelope = runEnforceReplication(_snapshot); VPackSlice content = envelope->slice(); EXPECT_EQ(content.length(), 0); } TEST_F(SupervisionTestClass, cleanup_hotback_transfer_jobs) { for (size_t i = 0; i < 200; ++i) { _snapshot("/Target/HotBackup/TransferJobs/" + std::to_string(1000000 + i)) = createNode(R"=( { "Timestamp": "2021-02-25T12:38:29Z", "DBServers": { "PRMR-b9b08faa-6286-4745-9c37-15e85b3a7d27": { "Progress": { "Total": 5, "Time": "2021-02-25T12:38:29Z", "Done": 5 }, "Status": "COMPLETED" }, "PRMR-a0b13c71-2472-4985-bc48-ffa091d26e03": { "Progress": { "Total": 5, "Time": "2021-02-25T12:38:29Z", "Done": 5 }, "Status": "COMPLETED" } }, "BackupId": "2021-02-25T12.38.11Z_c5656558-54ac-42bd-8851-08969d1a53f0" } )="); } std::shared_ptr<VPackBuilder> envelope = runCleanupHotbackupTransferJobs( _snapshot); VPackSlice content = envelope->slice(); EXPECT_EQ(content.length(), 100); }
29.970339
86
0.60427
[ "object", "vector" ]
410e24f61c82dd5c0a721198f9e4db5f13b2691b
29,178
cc
C++
test/AlienBench/AlienBenchModule.cc
arcaneframework/alien_legacy_plugins
be42667ece5ad58f9ee32b7700793646bfb8551b
[ "Apache-2.0" ]
4
2021-12-02T09:06:38.000Z
2022-01-10T14:22:35.000Z
test/AlienBench/AlienBenchModule.cc
arcaneframework/alien_legacy_plugins
be42667ece5ad58f9ee32b7700793646bfb8551b
[ "Apache-2.0" ]
null
null
null
test/AlienBench/AlienBenchModule.cc
arcaneframework/alien_legacy_plugins
be42667ece5ad58f9ee32b7700793646bfb8551b
[ "Apache-2.0" ]
7
2021-11-23T14:50:58.000Z
2022-03-17T13:23:07.000Z
#include <mpi.h> #include <string> #include <map> #include <time.h> #include <vector> #include <fstream> #include <boost/timer.hpp> #include <boost/lexical_cast.hpp> #include <boost/program_options/options_description.hpp> #include <boost/program_options/parsers.hpp> #include <boost/program_options/cmdline.hpp> #include <boost/program_options/variables_map.hpp> #include <boost/timer.hpp> #include <boost/lexical_cast.hpp> #include <arcane/ArcaneVersion.h> #include <arcane/Timer.h> #include <arcane/ItemPairGroup.h> #include <arcane/mesh/ItemFamily.h> #include <arcane/utils/PlatformUtils.h> #include <arcane/utils/IMemoryInfo.h> #include <arcane/utils/OStringStream.h> #include <arcane/ITimeLoopMng.h> #include <alien/arcane_tools/accessors/ItemVectorAccessor.h> #include <alien/core/block/VBlock.h> #include <alien/arcane_tools/IIndexManager.h> #include <alien/arcane_tools/indexManager/BasicIndexManager.h> #include <alien/arcane_tools/indexManager/SimpleAbstractFamily.h> #include <alien/arcane_tools/distribution/DistributionFabric.h> #include <alien/arcane_tools/indexSet/IndexSetFabric.h> #include <alien/arcane_tools/data/Space.h> #include <alien/kernels/simple_csr/algebra/SimpleCSRLinearAlgebra.h> #include <alien/kernels/simple_csr/algebra/SimpleCSRInternalLinearAlgebra.h> #include <alien/ref/AlienRefSemantic.h> #include <alien/kernels/redistributor/Redistributor.h> #include <alien/ref/data/scalar/RedistributedVector.h> #include <alien/ref/data/scalar/RedistributedMatrix.h> #include <alien/ref/import_export/MatrixMarketSystemWriter.h> #include <alien/expression/solver/SolverStater.h> #ifdef ALIEN_USE_PETSC #include <alien/kernels/petsc/io/AsciiDumper.h> #include <alien/kernels/petsc/algebra/PETScLinearAlgebra.h> #endif #ifdef ALIEN_USE_MTL4 #include <alien/kernels/mtl/algebra/MTLLinearAlgebra.h> #endif #ifdef ALIEN_USE_HTSSOLVER #include <alien/kernels/hts/HTSBackEnd.h> #include <alien/kernels/hts/data_structure/HTSMatrix.h> #include <alien/kernels/hts/algebra/HTSLinearAlgebra.h> #endif #ifdef ALIEN_USE_TRILINOS #include <alien/kernels/trilinos/TrilinosBackEnd.h> #include <alien/kernels/trilinos/data_structure/TrilinosMatrix.h> #include <alien/kernels/trilinos/algebra/TrilinosLinearAlgebra.h> #endif #include <alien/expression/solver/ILinearSolver.h> #include "AlienCoreSolverOptionTypes.h" #include "AlienBenchModule.h" #include <arcane/ItemPairGroup.h> #include <arcane/IMesh.h> #include <alien/core/impl/MultiVectorImpl.h> #include <alien/expression/krylov/AlienKrylov.h> #include <alien/utils/StdTimer.h> using namespace Arcane; using namespace Alien; /*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/ void AlienBenchModule::init() { Alien::setTraceMng(traceMng()); Alien::setVerbosityLevel(Alien::Verbosity::Debug); m_parallel_mng = subDomain()->parallelMng(); m_homogeneous = options()->homogeneous(); m_diag_coeff = options()->diagonalCoefficient(); m_lambdax = options()->lambdax(); m_lambday = options()->lambday(); m_lambdaz = options()->lambdaz(); m_alpha = options()->alpha(); Alien::ILinearSolver* solver = options()->linearSolver(); solver->init(); } /*---------------------------------------------------------------------------*/ void AlienBenchModule::test() { Timer pbuild_timer(subDomain(), "PBuildPhase", Timer::TimerReal); Timer psolve_timer(subDomain(), "PSolvePhase", Timer::TimerReal); Timer rbuild_timer(subDomain(), "RBuildPhase", Timer::TimerReal); Timer rsolve_timer(subDomain(), "RSolvePhase", Timer::TimerReal); ItemGroup areaU = allCells(); CellCellGroup cell_cell_connection(areaU.own(), areaU, m_stencil_kind); CellCellGroup all_cell_cell_connection(areaU, areaU, m_stencil_kind); Alien::ArcaneTools::BasicIndexManager index_manager(m_parallel_mng); index_manager.setTraceMng(traceMng()); auto indexSetU = index_manager.buildScalarIndexSet("U", areaU); index_manager.prepare(); /////////////////////////////////////////////////////////////////////////// // // CREATE Space FROM IndexManger // CREATE MATRIX ASSOCIATED TO Space // CREATE VECTORS ASSOCIATED TO Space // // Accรจs ร  l'indexation Arccore::UniqueArray<Arccore::Integer> allUIndex = index_manager.getIndexes(indexSetU); Alien::ArcaneTools::Space space(&index_manager, "TestSpace"); m_mdist = Alien::ArcaneTools::createMatrixDistribution(space); m_vdist = Alien::ArcaneTools::createVectorDistribution(space); info() << "GLOBAL SIZE : " << m_vdist.globalSize(); Alien::Vector vectorB(m_vdist); Alien::Vector vectorBB(m_vdist); Alien::Vector vectorX(m_vdist); Alien::Vector coordX(m_vdist); Alien::Vector coordY(m_vdist); Alien::Vector coordZ(m_vdist); /////////////////////////////////////////////////////////////////////////// // // VECTOR BUILDING AND FILLING // info() << "Building & initializing vector b"; info() << "Space size = " << m_vdist.globalSize() << ", local size= " << m_vdist.localSize(); ENUMERATE_CELL (icell, areaU) { Real3 x; ENUMERATE_NODE (inode, icell->nodes()) { x += m_node_coord[*inode]; } x /= icell->nbNode(); m_cell_center[icell] = x; m_u[icell] = funcn(x); m_k[icell] = funck(x); } { // Builder du vecteur Alien::VectorWriter writer(vectorX); Alien::VectorWriter x(coordX); Alien::VectorWriter y(coordY); Alien::VectorWriter z(coordZ); ENUMERATE_CELL(icell,areaU.own()) { const Integer iIndex = allUIndex[icell->localId()]; writer[iIndex] = m_u[icell] ; x[iIndex] = m_cell_center[icell].x ; y[iIndex] = m_cell_center[icell].y ; z[iIndex] = m_cell_center[icell].z ; } } Alien::Matrix matrixA(m_mdist); // local matrix for exact measure without side effect // (however, you can reuse a matrix with several // builder) /////////////////////////////////////////////////////////////////////////// // // MATRIX BUILDING AND FILLING // { Timer::Sentry ts(&pbuild_timer); Alien::MatrixProfiler profiler(matrixA); /////////////////////////////////////////////////////////////////////////// // // DEFINE PROFILE // ENUMERATE_ITEMPAIR(Cell, Cell, icell, cell_cell_connection) { const Cell& cell = *icell; const Integer iIndex = allUIndex[cell.localId()]; profiler.addMatrixEntry(iIndex, allUIndex[cell.localId()]); ENUMERATE_SUB_ITEM(Cell, isubcell, icell) { const Cell& subcell = *isubcell; profiler.addMatrixEntry(iIndex, allUIndex[subcell.localId()]); } } } { Timer::Sentry ts(&pbuild_timer); Alien::ProfiledMatrixBuilder builder( matrixA, Alien::ProfiledMatrixOptions::eResetValues); ENUMERATE_ITEMPAIR(Cell, Cell, icell, cell_cell_connection) { const Cell& cell = *icell; double diag = dii(cell); Integer i = allUIndex[cell.localId()]; builder(i, i) += diag; ENUMERATE_SUB_ITEM(Cell, isubcell, icell) { const Cell& subcell = *isubcell; double off_diag = fij(cell, subcell); builder(i, i) += off_diag; Integer j = allUIndex[subcell.localId()]; builder(i, j) -= off_diag; } } if (options()->sigma() > 0.) { m_sigma = options()->sigma(); auto xCmax = Real3{ 0.25, 0.25, 0.25 }; auto xCmin = Real3{ 0.75, 0.75, 0.55 }; ENUMERATE_ITEMPAIR(Cell, Cell, icell, all_cell_cell_connection) { const Cell& cell = *icell; Real3 xC = m_cell_center[icell]; Real3 xDmax = xC - xCmax; Real3 xDmin = xC - xCmin; m_s[cell] = 0; if (xDmax.abs() < options()->epsilon()) { m_s[cell] = 1.; Integer i = allUIndex[cell.localId()]; info() << "MATRIX TRANSFO SIGMAMAX " << i; if (cell.isOwn()) builder(i, i) = m_sigma; ENUMERATE_SUB_ITEM(Cell, isubcell, icell) { const Cell& subcell = *isubcell; if (subcell.isOwn()) { Integer j = allUIndex[subcell.localId()]; builder(j, i) = 0.; } } } if (xDmin.abs() < options()->epsilon()) { m_s[cell] = -1.; Integer i = allUIndex[cell.localId()]; info() << "MATRIX TRANSFO SIGMA MIN" << i; if (cell.isOwn()) builder(i, i) = 1. / m_sigma; ENUMERATE_SUB_ITEM(Cell, isubcell, icell) { const Cell& subcell = *isubcell; if (subcell.isOwn()) { Integer j = allUIndex[subcell.localId()]; builder(j, i) = 0.; } } } } } builder.finalize(); } { Alien::SimpleCSRLinearAlgebra csrAlg; csrAlg.mult(matrixA, vectorX, vectorB); csrAlg.mult(matrixA, vectorX, vectorBB); Real normeb = csrAlg.norm2(vectorB); info() << "||b||=" << normeb; } #ifdef ALIEN_USE_HTSSOLVER /*{ info()<<"HTS"; Alien::HTSLinearAlgebra htsAlg; htsAlg.mult(matrixA,vectorX,vectorB); htsAlg.mult(matrixA,vectorX,vectorBB); Real normeb = htsAlg.norm2(vectorB) ; info()<<"||b||="<<normeb; }*/ #endif #ifdef ALIEN_USE_TRILINOS /*{ info() << "Trilinos"; Alien::TrilinosLinearAlgebra tpetraAlg; tpetraAlg.mult(matrixA, vectorX, vectorB); tpetraAlg.mult(matrixA, vectorX, vectorBB); Real normeb = tpetraAlg.norm2(vectorB); info() << "||b||=" << normeb; // tpetraAlg.dump(matrixA,"MatrixA.txt") ; // tpetraAlg.dump(vectorB,"vectorB.txt") ; // tpetraAlg.dump(vectorBB,"vectorBB.txt") ; // tpetraAlg.dump(vectorX,"vectorX.txt") ; }*/ #endif if (options()->unitRhs()) { Alien::LocalVectorWriter v(vectorBB); for (Integer i = 0; i < v.size(); ++i) v[i] = 1.; } if (options()->zeroRhs()) { Alien::LocalVectorWriter v(vectorB); for (Integer i = 0; i < v.size(); ++i) v[i] = 0.; } /////////////////////////////////////////////////////////////////////////// // // RESOLUTION // if(options()->alienCoreSolver.size()>0) { { Alien::LocalVectorReader reader(vectorBB); Alien::LocalVectorWriter vb(vectorB); Alien::LocalVectorWriter vx(vectorX); for (Integer i = 0; i < m_vdist.localSize(); ++i) { vx[i] = 0.; vb[i] = reader[i]; } } typedef Alien::SimpleCSRInternalLinearAlgebra AlgebraType ; typedef typename AlgebraType::BackEndType BackEndType ; typedef Alien::Iteration<AlgebraType> StopCriteriaType ; typedef Alien::CG<AlgebraType> SolverType ; AlgebraType alg ; auto const& true_A = matrixA.impl()->get<Alien::BackEnd::tag::simplecsr>() ; auto const& true_b = vectorB.impl()->get<Alien::BackEnd::tag::simplecsr>() ; auto& true_x = vectorX.impl()->get<Alien::BackEnd::tag::simplecsr>(true) ; auto const& opt = options()->alienCoreSolver[0] ; int output_level = opt->outputLevel() ; int max_iteration = opt->maxIter() ; double tol = opt->tol() ; auto solver_opt = opt->solver() ; auto precond_opt = opt->preconditioner() ; auto backend = opt->backend() ; auto asynch = opt->asynch() ; // clang-format off auto run = [&](auto& alg) { typedef typename boost::remove_reference<decltype(alg)>::type AlgebraType ; typedef typename AlgebraType::BackEndType BackEndType ; typedef Alien::Iteration<AlgebraType> StopCriteriaType ; auto const& true_A = matrixA.impl()->get<BackEndType>() ; auto const& true_b = vectorB.impl()->get<BackEndType>() ; auto& true_x = vectorX.impl()->get<BackEndType>(true) ; StopCriteriaType stop_criteria{alg,true_b,tol,max_iteration,output_level>0?traceMng():nullptr} ; switch(solver_opt) { case AlienCoreSolverOptionTypes::CG: { typedef Alien::CG<AlgebraType> SolverType ; SolverType solver{alg,traceMng()} ; solver.setOutputLevel(output_level) ; switch(precond_opt) { case AlienCoreSolverOptionTypes::ChebyshevPoly: { info()<<"CHEBYSHEV PRECONDITIONER"; double polynom_factor = opt->polyFactor() ; int polynom_order = opt->polyOrder() ; int polynom_factor_max_iter = opt->polyFactorMaxIter() ; typedef Alien::ChebyshevPreconditioner<AlgebraType,true> PrecondType ; PrecondType precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,traceMng()} ; precond.setOutputLevel(output_level) ; precond.init() ; Timer::Sentry ts(&psolve_timer); if(asynch==0) solver.solve(precond,stop_criteria,true_A,true_b,true_x) ; else solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ; } break; case AlienCoreSolverOptionTypes::NeumannPoly: { info()<<"NEUMANN PRECONDITIONER"; double polynom_factor = opt->polyFactor() ; int polynom_order = opt->polyOrder() ; int polynom_factor_max_iter = opt->polyFactorMaxIter() ; typedef Alien::NeumannPolyPreconditioner<AlgebraType> PrecondType ; PrecondType precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,traceMng()} ; precond.init() ; Timer::Sentry ts(&psolve_timer); if(asynch==0) solver.solve(precond,stop_criteria,true_A,true_b,true_x) ; else solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ; } case AlienCoreSolverOptionTypes::Diag: default: { info()<<"DIAG PRECONDITIONER"; typedef Alien::DiagPreconditioner<AlgebraType> PrecondType ; PrecondType precond{alg,true_A} ; precond.init() ; Timer::Sentry ts(&psolve_timer); if(asynch==0) solver.solve(precond,stop_criteria,true_A,true_b,true_x) ; else solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ; } break ; } } break ; case AlienCoreSolverOptionTypes::BCGS: { typedef Alien::BiCGStab<AlgebraType> SolverType ; SolverType solver{alg,traceMng()} ; solver.setOutputLevel(output_level) ; switch(precond_opt) { case AlienCoreSolverOptionTypes::ChebyshevPoly: { info()<<"CHEBYSHEV PRECONDITIONER"; double polynom_factor = opt->polyFactor() ; int polynom_order = opt->polyOrder() ; int polynom_factor_max_iter = opt->polyFactorMaxIter() ; typedef Alien::ChebyshevPreconditioner<AlgebraType,true> PrecondType ; PrecondType precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,traceMng()} ; precond.setOutputLevel(output_level) ; precond.init() ; Timer::Sentry ts(&psolve_timer); if(asynch==0) solver.solve(precond,stop_criteria,true_A,true_b,true_x) ; else solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ; } break ; case AlienCoreSolverOptionTypes::NeumannPoly: { info()<<"NEUMANN PRECONDITIONER"; double polynom_factor = opt->polyFactor() ; int polynom_order = opt->polyOrder() ; int polynom_factor_max_iter = opt->polyFactorMaxIter() ; typedef Alien::NeumannPolyPreconditioner<AlgebraType> PrecondType ; PrecondType precond{alg,true_A,polynom_factor,polynom_order,polynom_factor_max_iter,traceMng()} ; precond.init() ; Timer::Sentry ts(&psolve_timer); if(asynch==0) solver.solve(precond,stop_criteria,true_A,true_b,true_x) ; else solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ; } break ; case AlienCoreSolverOptionTypes::ILU0: { info()<<"ILU0 PRECONDITIONER"; typedef Alien::ILU0Preconditioner<AlgebraType> PrecondType ; PrecondType precond{alg,true_A,traceMng()} ; precond.init() ; Timer::Sentry ts(&psolve_timer); if(asynch==0) solver.solve(precond,stop_criteria,true_A,true_b,true_x) ; else solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ; } break ; case AlienCoreSolverOptionTypes::FILU0: { info()<<"FILU0 PRECONDITIONER"; typedef Alien::FILU0Preconditioner<AlgebraType> PrecondType ; PrecondType precond{alg,true_A,traceMng()} ; precond.setParameter("nb-factor-iter",opt->filuFactorNiter()) ; precond.setParameter("nb-solver-iter",opt->filuSolverNiter()) ; precond.setParameter("tol", opt->filuTol()) ; precond.init() ; Timer::Sentry ts(&psolve_timer); if(asynch==0) solver.solve(precond,stop_criteria,true_A,true_b,true_x) ; else solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ; } break ; case AlienCoreSolverOptionTypes::Diag: default: { info()<<"DIAG PRECONDITIONER"; typedef Alien::DiagPreconditioner<AlgebraType> PrecondType ; PrecondType precond{alg,true_A} ; precond.init() ; Timer::Sentry ts(&psolve_timer); if(asynch==0) solver.solve(precond,stop_criteria,true_A,true_b,true_x) ; else solver.solve2(precond,stop_criteria,true_A,true_b,true_x) ; } break ; } } break ; default : fatal()<<"unknown solver"; } if(stop_criteria.getStatus()) { info()<<"Solver has converged"; info()<<"Nb iterations : "<<stop_criteria(); info()<<"Criteria value : "<<stop_criteria.getValue(); } else { info()<<"Solver convergence failed"; } } ; // clang-format on switch(backend) { case AlienCoreSolverOptionTypes::SimpleCSR: { Alien::SimpleCSRInternalLinearAlgebra alg; run(alg); } break ; case AlienCoreSolverOptionTypes::SYCL: { #ifdef ALIEN_USE_SYCL Alien::SYCLInternalLinearAlgebra alg; alg.setDotAlgo(vm["dot-algo"].as<int>()); run(alg); #else fatal() << "SYCL BackEnd not available"; #endif } break ; default: fatal() << "SYCL BackEnd not available"; break ; } } else { Alien::ILinearSolver* solver = options()->linearSolver(); solver->init(); #ifdef ALIEN_USE_TRILINOS if(solver->getBackEndName().contains("tpetraserial")) { auto& mat = matrixA.impl()->get<Alien::BackEnd::tag::tpetraserial>(false) ; mat.setMatrixCoordinate(coordX,coordY,coordZ) ; } #ifdef KOKKOS_ENABLE_OPENMP if(solver->getBackEndName().contains("tpetraomp")) { auto& mat = matrixA.impl()->get<Alien::BackEnd::tag::tpetraomp>(false) ; mat.setMatrixCoordinate(coordX,coordY,coordZ) ; } #endif #ifdef KOKKOS_ENABLE_THREADS if(solver->getBackEndName().contains("tpetrapth")) { auto& mat = matrixA.impl()->get<Alien::BackEnd::tag::tpetrapth>(false) ; mat.setMatrixCoordinate(coordX,coordY,coordZ) ; } #endif #ifdef KOKKOS_ENABLE_CUDA if(solver->getBackEndName().contains("tpetracuda")) { auto& mat = matrixA.impl()->get<Alien::BackEnd::tag::tpetracuda>(true) ; mat->setCoordinate(coordX,coordY,coordZ) ; } #endif #endif if (not solver->hasParallelSupport() and m_parallel_mng->commSize() > 1) { info() << "Current solver has not a parallel support for solving linear system : " "skip it"; } else { Integer nb_resolutions = options()->nbResolutions(); for (Integer i = 0; i < nb_resolutions; ++i) { if (i > 0) // i=0, matrix allready filled { Timer::Sentry ts(&pbuild_timer); Alien::ProfiledMatrixBuilder builder( matrixA, Alien::ProfiledMatrixOptions::eResetValues); ENUMERATE_ITEMPAIR(Cell, Cell, icell, cell_cell_connection) { const Cell& cell = *icell; double diag = dii(cell); Integer i = allUIndex[cell.localId()]; builder(i, i) += diag; ENUMERATE_SUB_ITEM(Cell, isubcell, icell) { const Cell& subcell = *isubcell; double off_diag = fij(cell, subcell); builder(i, i) += off_diag; Integer j = allUIndex[subcell.localId()]; builder(i, j) -= off_diag; } } if (options()->sigma() > 0.) { m_sigma = options()->sigma(); auto xCmax = Real3{ 0.25, 0.25, 0.25 }; auto xCmin = Real3{ 0.75, 0.75, 0.55 }; ENUMERATE_ITEMPAIR(Cell, Cell, icell, all_cell_cell_connection) { const Cell& cell = *icell; Real3 xC = m_cell_center[icell]; Real3 xDmax = xC - xCmax; Real3 xDmin = xC - xCmin; m_s[cell] = 0; if (xDmax.abs() < options()->epsilon()) { m_s[cell] = 1.; Integer i = allUIndex[cell.localId()]; info() << "MATRIX TRANSFO SIGMAMAX " << i; if (cell.isOwn()) builder(i, i) = m_sigma; ENUMERATE_SUB_ITEM(Cell, isubcell, icell) { const Cell& subcell = *isubcell; if (subcell.isOwn()) { Integer j = allUIndex[subcell.localId()]; builder(j, i) = 0.; } } } if (xDmin.abs() < options()->epsilon()) { m_s[cell] = -1.; Integer i = allUIndex[cell.localId()]; info() << "MATRIX TRANSFO SIGMA MIN" << i; if (cell.isOwn()) builder(i, i) = 1. / m_sigma; ENUMERATE_SUB_ITEM(Cell, isubcell, icell) { const Cell& subcell = *isubcell; if (subcell.isOwn()) { Integer j = allUIndex[subcell.localId()]; builder(j, i) = 0.; } } } } } builder.finalize(); } // Rรฉinitialisation de vectorX // if(i>0) // i=0, vector allready filled { Alien::LocalVectorReader reader(vectorBB); Alien::LocalVectorWriter vb(vectorB); Alien::LocalVectorWriter vx(vectorX); for (Integer i = 0; i < m_vdist.localSize(); ++i) { vx[i] = 0.; vb[i] = reader[i]; } } if(i==0) { Alien::MatrixMarketSystemWriter matrix_exporter("AlienBenchMatrixA.mtx",m_parallel_mng->messagePassingMng()) ; matrix_exporter.dump(matrixA) ; Alien::MatrixMarketSystemWriter vector_exporter("AlienBenchVectorB.mtx",m_parallel_mng->messagePassingMng()) ; vector_exporter.dump(vectorB) ; } Timer::Sentry ts(&psolve_timer); solver->solve(matrixA, vectorB, vectorX); } Alien::SolverStatus status = solver->getStatus(); if (status.succeeded) { info()<<"RESOLUTION SUCCEED"; Alien::VectorReader reader(vectorX); ENUMERATE_CELL (icell, areaU.own()) { const Integer iIndex = allUIndex[icell->localId()]; m_x[icell] = reader[iIndex]; } SimpleCSRLinearAlgebra alg; Alien::Vector vectorR(m_vdist); alg.mult(matrixA, vectorX, vectorR); alg.axpy(-1., vectorB, vectorR); Real res = alg.norm2(vectorR); info() << "RES : " << res; } else info()<<"SOLVER FAILED"; solver->getSolverStat().print(Universe().traceMng(), status, "Linear Solver : "); } solver->end(); } if (options()->redistribution() && m_parallel_mng->commSize() > 1) { info() << "Test REDISTRIBUTION"; { Alien::LocalVectorWriter v(vectorX); for (Integer i = 0; i < v.size(); ++i) v[i] = 0; } Alien::Vector vectorR(m_vdist); bool keep_proc = false; if (m_parallel_mng->commRank() == 0) keep_proc = true; rbuild_timer.start(); auto small_comm = Arccore::MessagePassing::mpSplit(m_parallel_mng->messagePassingMng(), keep_proc); Alien::Redistributor redist(matrixA.distribution().globalRowSize(), m_parallel_mng->messagePassingMng(), small_comm ); Alien::RedistributedMatrix Aa(matrixA, redist); Alien::RedistributedVector bb(vectorB, redist); Alien::RedistributedVector xx(vectorX, redist); Alien::RedistributedVector rr(vectorR, redist); rbuild_timer.stop(); if (keep_proc) { auto solver = options()->linearSolver(); // solver->updateParallelMng(Aa.distribution().parallelMng()); solver->init(); { Timer::Sentry ts(&rsolve_timer); solver->solve(Aa, bb, xx); } Alien::SimpleCSRLinearAlgebra alg; alg.mult(Aa, xx, rr); alg.axpy(-1., bb, rr); Real res = alg.norm2(rr); info() << "REDISTRIBUTION RES : " << res; } } info() << "==================================================="; info() << "BENCH INFO :"; info() << " PBUILD :" << pbuild_timer.totalTime(); info() << " PSOLVE :" << psolve_timer.totalTime(); info() << " RBUILD :" << rbuild_timer.totalTime(); info() << " RSOLVE :" << rsolve_timer.totalTime(); info() << "==================================================="; subDomain()->timeLoopMng()->stopComputeLoop(true); } /*---------------------------------------------------------------------------*/ Real AlienBenchModule::funcn(Real3 p) const { return p.x * p.x * p.y; } Real AlienBenchModule::funck(Real3 p) const { #define PI 3.14159265358979323846264 if (m_homogeneous) return m_off_diag_coeff; else return std::exp(-m_alpha * 0.5 * (1 + std::sin(2 * PI * p.x / m_lambdax)) * (1 + std::sin(2 * PI * p.y / m_lambday))); } Real AlienBenchModule::dii(const Cell& ci) const { return m_diag_coeff; } Real AlienBenchModule::fij(const Cell& ci, const Cell& cj) const { if (ci == cj) return dii(ci); else { Real3 xi = m_cell_center[ci]; Real3 xj = m_cell_center[cj]; Real3 xij = xi + xj; xij /= 2.; return funck(xij); } } /*---------------------------------------------------------------------------*/ ARCANE_REGISTER_MODULE_ALIENBENCH(AlienBenchModule);
35.539586
128
0.543252
[ "mesh", "vector" ]
41145b235fdfd8f9805550aafa52adba33c5739f
8,071
cpp
C++
tests/report/host/tcbinfo.cpp
vlaza/openenclave
02ae4e48c9d3b9678cb860e2af7c2319bb043679
[ "MIT" ]
null
null
null
tests/report/host/tcbinfo.cpp
vlaza/openenclave
02ae4e48c9d3b9678cb860e2af7c2319bb043679
[ "MIT" ]
null
null
null
tests/report/host/tcbinfo.cpp
vlaza/openenclave
02ae4e48c9d3b9678cb860e2af7c2319bb043679
[ "MIT" ]
1
2021-08-17T15:37:36.000Z
2021-08-17T15:37:36.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifdef OE_USE_LIBSGX #include <openenclave/host.h> #include <openenclave/internal/aesm.h> #include <openenclave/internal/datetime.h> #include <openenclave/internal/error.h> #include <openenclave/internal/hexdump.h> #include <openenclave/internal/tests.h> #include <openenclave/internal/utils.h> #include <fstream> #include <streambuf> #include <vector> #include "../../../common/sgx/tcbinfo.h" #include "../../../host/sgx/quote.h" #include "tests_u.h" #define SKIP_RETURN_CODE 2 std::vector<uint8_t> FileToBytes(const char* path) { std::ifstream f(path, std::ios::binary); std::vector<uint8_t> bytes = std::vector<uint8_t>( std::istreambuf_iterator<char>(f), std::istreambuf_iterator<char>()); if (bytes.empty()) { printf("File %s not found\n", path); exit(1); } // Explicitly add null character so that the bytes can be printed out // safely as a string if needed. bytes.push_back('\0'); return bytes; } void AssertParsedValues(oe_parsed_tcb_info_t& parsed_info) { OE_TEST(parsed_info.version == 1); oe_datetime_t expected_issue_date = {2018, 6, 6, 10, 12, 17}; OE_TEST( oe_datetime_compare(&parsed_info.issue_date, &expected_issue_date) == 0); uint8_t expected_fm_spc[6] = {0x00, 0x90, 0x6E, 0xA1, 0x00, 0x00}; OE_TEST( memcmp(parsed_info.fmspc, expected_fm_spc, sizeof(expected_fm_spc)) == 0); const uint8_t expected_signature[] = { 0x62, 0xd1, 0x81, 0xc4, 0xba, 0x86, 0x32, 0x13, 0xb8, 0x25, 0xd1, 0xc0, 0xb6, 0x6b, 0x92, 0xa3, 0xdb, 0xdb, 0x27, 0xb8, 0xff, 0x7c, 0x72, 0x50, 0xcb, 0x2b, 0x2a, 0xb8, 0x7a, 0x8f, 0x90, 0xd5, 0xe5, 0xa1, 0x41, 0x69, 0x14, 0x36, 0x9d, 0x8f, 0x82, 0xc5, 0x6c, 0xd3, 0xd8, 0x75, 0xca, 0xa5, 0x4a, 0xe4, 0xb9, 0x17, 0xca, 0xf4, 0xaf, 0x7a, 0x93, 0xde, 0xc5, 0x20, 0x67, 0xcb, 0xfd, 0x7b}; OE_TEST( memcmp( parsed_info.signature, expected_signature, sizeof(expected_signature)) == 0); } void TestVerifyTCBInfo( oe_enclave_t* enclave, oe_tcb_level_t* platform_tcb_level, oe_result_t expected) { std::vector<uint8_t> tcbInfo = FileToBytes("./data/tcbInfo.json"); oe_parsed_tcb_info_t parsed_info = {0}; oe_result_t ecall_result = OE_FAILURE; // Contains nextUpdate field. memset(&parsed_info, 0, sizeof(parsed_info)); platform_tcb_level->status = OE_TCB_LEVEL_STATUS_UNKNOWN; OE_TEST( test_verify_tcb_info( enclave, &ecall_result, (const char*)&tcbInfo[0], platform_tcb_level, &parsed_info) == OE_OK); OE_TEST(ecall_result == expected); AssertParsedValues(parsed_info); oe_datetime_t nextUpdate = {2019, 6, 6, 10, 12, 17}; OE_TEST(oe_datetime_compare(&parsed_info.next_update, &nextUpdate) == 0); } void TestVerifyTCBInfo(oe_enclave_t* enclave) { oe_tcb_level_t platform_tcb_level = { {4, 4, 2, 4, 1, 128, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, 8, OE_TCB_LEVEL_STATUS_UNKNOWN}; // ./data/tcbInfo.json contains 4 tcb levels. // The first level with pce svn = 5 is up to date. // The second level with pce svn = 4 needs configuration. // The third level with pce svn = 3 is out of date. // The fourth level with pce svn = 2 is revoked. // Set platform pce svn to 8 and assert that // the determined status is up to date. platform_tcb_level.status = OE_TCB_LEVEL_STATUS_UNKNOWN; platform_tcb_level.pce_svn = 8; TestVerifyTCBInfo(enclave, &platform_tcb_level, OE_OK); OE_TEST(platform_tcb_level.status == OE_TCB_LEVEL_STATUS_UP_TO_DATE); printf("UptoDate TCB Level determination test passed.\n"); // Set platform pce svn to 4 and assert that // the determined status is configuration needed. platform_tcb_level.status = OE_TCB_LEVEL_STATUS_UNKNOWN; platform_tcb_level.pce_svn = 4; TestVerifyTCBInfo(enclave, &platform_tcb_level, OE_TCB_LEVEL_INVALID); OE_TEST( platform_tcb_level.status == OE_TCB_LEVEL_STATUS_CONFIGURATION_NEEDED); printf("ConfigurationNeeded TCB Level determination test passed.\n"); // Set platform pce svn to 3 and assert that // the determined status is out of date. platform_tcb_level.status = OE_TCB_LEVEL_STATUS_UNKNOWN; platform_tcb_level.pce_svn = 3; TestVerifyTCBInfo(enclave, &platform_tcb_level, OE_TCB_LEVEL_INVALID); OE_TEST(platform_tcb_level.status == OE_TCB_LEVEL_STATUS_OUT_OF_DATE); printf("OutOfDate TCB Level determination test passed.\n"); // Set platform pce svn to 2 and assert that // the determined status is revoked. platform_tcb_level.status = OE_TCB_LEVEL_STATUS_UNKNOWN; platform_tcb_level.pce_svn = 2; TestVerifyTCBInfo(enclave, &platform_tcb_level, OE_TCB_LEVEL_INVALID); OE_TEST(platform_tcb_level.status == OE_TCB_LEVEL_STATUS_REVOKED); printf("OutOfDate TCB Level determination test passed.\n"); // Set each of the fields to a value not listed in the json and // test that the determined status is OE_TCB_LEVEL_INVALID for (uint32_t i = 0; i < OE_COUNTOF(platform_tcb_level.sgx_tcb_comp_svn); ++i) { platform_tcb_level.status = OE_TCB_LEVEL_STATUS_UNKNOWN; platform_tcb_level.sgx_tcb_comp_svn[i] = 0; TestVerifyTCBInfo(enclave, &platform_tcb_level, OE_TCB_LEVEL_INVALID); OE_TEST(platform_tcb_level.status == OE_TCB_LEVEL_STATUS_UNKNOWN); platform_tcb_level.sgx_tcb_comp_svn[i] = 1; } printf("Unknown TCB Level determination test passed.\n"); printf("TestVerifyTCBInfo: Positive Tests passed\n"); const char* negative_files[] = { // In the following files, a property in corresponding level has been // capitalized. JSON is case sensitive and therefore schema validation // should fail. "./data/tcbInfoNegativePropertyMissingLevel0.json", "./data/tcbInfoNegativePropertyMissingLevel1.json", "./data/tcbInfoNegativePropertyMissingLevel2.json", "./data/tcbInfoNegativePropertyMissingLevel3.json", // In the following files, a property in corresponding level has wrong // type. "./data/tcbInfoNegativePropertyWrongTypeLevel0.json", "./data/tcbInfoNegativePropertyWrongTypeLevel1.json", "./data/tcbInfoNegativePropertyWrongTypeLevel2.json", "./data/tcbInfoNegativePropertyWrongTypeLevel3.json", // Comp Svn greater than uint8_t "./data/tcbInfoNegativeCompSvn.json", // pce Svn greater than uint16_t "./data/tcbInfoNegativePceSvn.json", // Invalid issueDate field. "./data/tcbInfoNegativeInvalidIssueDate.json", // Invalid nextUpdate field. "./data/tcbInfoNegativeInvalidNextUpdate.json", // Missing nextUpdate field. "./data/tcbInfoNegativeMissingNextUpdate.json", // Signature != 64 bytes "./data/tcbInfoNegativeSignature.json", // Unsupported JSON constructs "./data/tcbInfoNegativeStringEscape.json", "./data/tcbInfoNegativeIntegerOverflow.json", "./data/tcbInfoNegativeIntegerWithSign.json", "./data/tcbInfoNegativeFloat.json", }; for (size_t i = 0; i < sizeof(negative_files) / sizeof(negative_files[0]); ++i) { std::vector<uint8_t> tcbInfo = FileToBytes(negative_files[i]); oe_parsed_tcb_info_t parsed_info = {0}; oe_tcb_level_t platform_tcb_level = {{0}}; oe_result_t ecall_result = OE_FAILURE; OE_TEST( test_verify_tcb_info( enclave, &ecall_result, (const char*)&tcbInfo[0], &platform_tcb_level, &parsed_info) == OE_OK); OE_TEST(ecall_result == OE_JSON_INFO_PARSE_ERROR); printf( "TestVerifyTCBInfo: Negative Test %s passed\n", negative_files[i]); } } #endif
37.193548
79
0.677859
[ "vector" ]
41177bffcfbe3d15a3ea977890f2e630ef209957
26,100
cpp
C++
src/jbmc/jbmc_parse_options.cpp
jeannielynnmoulton/cbmc
1d4af6d88ec960677170049a8a89a9166b952996
[ "BSD-4-Clause" ]
null
null
null
src/jbmc/jbmc_parse_options.cpp
jeannielynnmoulton/cbmc
1d4af6d88ec960677170049a8a89a9166b952996
[ "BSD-4-Clause" ]
1
2019-02-05T16:18:25.000Z
2019-02-05T16:18:25.000Z
src/jbmc/jbmc_parse_options.cpp
jeannielynnmoulton/cbmc
1d4af6d88ec960677170049a8a89a9166b952996
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: JBMC Command Line Option Processing Author: Daniel Kroening, kroening@kroening.com \*******************************************************************/ /// \file /// JBMC Command Line Option Processing #include "jbmc_parse_options.h" #include <fstream> #include <cstdlib> // exit() #include <iostream> #include <memory> #include <util/string2int.h> #include <util/config.h> #include <util/language.h> #include <util/unicode.h> #include <util/memory_info.h> #include <util/invariant.h> #include <ansi-c/ansi_c_language.h> #include <goto-programs/convert_nondet.h> #include <goto-programs/lazy_goto_model.h> #include <goto-programs/instrument_preconditions.h> #include <goto-programs/goto_convert_functions.h> #include <goto-programs/goto_inline.h> #include <goto-programs/loop_ids.h> #include <goto-programs/remove_virtual_functions.h> #include <goto-programs/remove_instanceof.h> #include <goto-programs/remove_returns.h> #include <goto-programs/remove_exceptions.h> #include <goto-programs/remove_asm.h> #include <goto-programs/remove_unused_functions.h> #include <goto-programs/remove_skip.h> #include <goto-programs/remove_static_init_loops.h> #include <goto-programs/replace_java_nondet.h> #include <goto-programs/set_properties.h> #include <goto-programs/show_goto_functions.h> #include <goto-programs/show_symbol_table.h> #include <goto-programs/show_properties.h> #include <goto-programs/remove_java_new.h> #include <goto-symex/adjust_float_expressions.h> #include <goto-instrument/full_slicer.h> #include <goto-instrument/nondet_static.h> #include <goto-instrument/cover.h> #include <pointer-analysis/add_failed_symbols.h> #include <langapi/mode.h> #include <java_bytecode/java_bytecode_language.h> #include <cbmc/cbmc_solvers.h> #include <cbmc/bmc.h> #include <cbmc/version.h> jbmc_parse_optionst::jbmc_parse_optionst(int argc, const char **argv): parse_options_baset(JBMC_OPTIONS, argc, argv), messaget(ui_message_handler), ui_message_handler(cmdline, "JBMC " CBMC_VERSION) { } ::jbmc_parse_optionst::jbmc_parse_optionst( int argc, const char **argv, const std::string &extra_options): parse_options_baset(JBMC_OPTIONS+extra_options, argc, argv), messaget(ui_message_handler), ui_message_handler(cmdline, "JBMC " CBMC_VERSION) { } void jbmc_parse_optionst::eval_verbosity() { // this is our default verbosity unsigned int v=messaget::M_STATISTICS; if(cmdline.isset("verbosity")) { v=unsafe_string2unsigned(cmdline.get_value("verbosity")); if(v>10) v=10; } ui_message_handler.set_verbosity(v); } void jbmc_parse_optionst::get_command_line_options(optionst &options) { if(config.set(cmdline)) { usage_error(); exit(1); // should contemplate EX_USAGE from sysexits.h } if(cmdline.isset("program-only")) options.set_option("program-only", true); if(cmdline.isset("show-vcc")) options.set_option("show-vcc", true); if(cmdline.isset("cover")) parse_cover_options(cmdline, options); if(cmdline.isset("no-simplify")) options.set_option("simplify", false); else options.set_option("simplify", true); if(cmdline.isset("stop-on-fail") || cmdline.isset("dimacs") || cmdline.isset("outfile")) options.set_option("stop-on-fail", true); else options.set_option("stop-on-fail", false); if(cmdline.isset("trace") || cmdline.isset("stop-on-fail")) options.set_option("trace", true); if(cmdline.isset("localize-faults")) options.set_option("localize-faults", true); if(cmdline.isset("localize-faults-method")) { options.set_option( "localize-faults-method", cmdline.get_value("localize-faults-method")); } if(cmdline.isset("unwind")) options.set_option("unwind", cmdline.get_value("unwind")); if(cmdline.isset("depth")) options.set_option("depth", cmdline.get_value("depth")); if(cmdline.isset("debug-level")) options.set_option("debug-level", cmdline.get_value("debug-level")); if(cmdline.isset("slice-by-trace")) options.set_option("slice-by-trace", cmdline.get_value("slice-by-trace")); if(cmdline.isset("unwindset")) options.set_option("unwindset", cmdline.get_value("unwindset")); // constant propagation if(cmdline.isset("no-propagation")) options.set_option("propagation", false); else options.set_option("propagation", true); // all checks supported by goto_check PARSE_OPTIONS_GOTO_CHECK(cmdline, options); // unwind loops in java enum static initialization if(cmdline.isset("java-unwind-enum-static")) options.set_option("java-unwind-enum-static", true); // check assertions if(cmdline.isset("no-assertions")) options.set_option("assertions", false); else options.set_option("assertions", true); // use assumptions if(cmdline.isset("no-assumptions")) options.set_option("assumptions", false); else options.set_option("assumptions", true); // magic error label if(cmdline.isset("error-label")) options.set_option("error-label", cmdline.get_values("error-label")); // generate unwinding assertions if(cmdline.isset("cover")) options.set_option("unwinding-assertions", false); else { options.set_option( "unwinding-assertions", cmdline.isset("unwinding-assertions")); } // generate unwinding assumptions otherwise options.set_option( "partial-loops", cmdline.isset("partial-loops")); if(options.get_bool_option("partial-loops") && options.get_bool_option("unwinding-assertions")) { error() << "--partial-loops and --unwinding-assertions " << "must not be given together" << eom; exit(1); // should contemplate EX_USAGE from sysexits.h } // remove unused equations options.set_option( "slice-formula", cmdline.isset("slice-formula")); // simplify if conditions and branches if(cmdline.isset("no-simplify-if")) options.set_option("simplify-if", false); else options.set_option("simplify-if", true); if(cmdline.isset("arrays-uf-always")) options.set_option("arrays-uf", "always"); else if(cmdline.isset("arrays-uf-never")) options.set_option("arrays-uf", "never"); else options.set_option("arrays-uf", "auto"); if(cmdline.isset("dimacs")) options.set_option("dimacs", true); if(cmdline.isset("refine-arrays")) { options.set_option("refine", true); options.set_option("refine-arrays", true); } if(cmdline.isset("refine-arithmetic")) { options.set_option("refine", true); options.set_option("refine-arithmetic", true); } if(cmdline.isset("refine")) { options.set_option("refine", true); options.set_option("refine-arrays", true); options.set_option("refine-arithmetic", true); } if(cmdline.isset("refine-strings")) { options.set_option("refine-strings", true); options.set_option("string-printable", cmdline.isset("string-printable")); if(cmdline.isset("string-max-length")) options.set_option( "string-max-length", cmdline.get_value("string-max-length")); } if(cmdline.isset("max-node-refinement")) options.set_option( "max-node-refinement", cmdline.get_value("max-node-refinement")); // SMT Options bool version_set=false; if(cmdline.isset("smt1")) { options.set_option("smt1", true); options.set_option("smt2", false); version_set=true; } if(cmdline.isset("smt2")) { // If both are given, smt2 takes precedence options.set_option("smt1", false); options.set_option("smt2", true); version_set=true; } if(cmdline.isset("fpa")) options.set_option("fpa", true); bool solver_set=false; if(cmdline.isset("boolector")) { options.set_option("boolector", true), solver_set=true; if(!version_set) options.set_option("smt2", true), version_set=true; } if(cmdline.isset("mathsat")) { options.set_option("mathsat", true), solver_set=true; if(!version_set) options.set_option("smt2", true), version_set=true; } if(cmdline.isset("cvc3")) { options.set_option("cvc3", true), solver_set=true; if(!version_set) options.set_option("smt1", true), version_set=true; } if(cmdline.isset("cvc4")) { options.set_option("cvc4", true), solver_set=true; if(!version_set) options.set_option("smt2", true), version_set=true; } if(cmdline.isset("yices")) { options.set_option("yices", true), solver_set=true; if(!version_set) options.set_option("smt2", true), version_set=true; } if(cmdline.isset("z3")) { options.set_option("z3", true), solver_set=true; if(!version_set) options.set_option("smt2", true), version_set=true; } if(cmdline.isset("opensmt")) { options.set_option("opensmt", true), solver_set=true; if(!version_set) options.set_option("smt1", true), version_set=true; } if(version_set && !solver_set) { if(cmdline.isset("outfile")) { // outfile and no solver should give standard compliant SMT-LIB options.set_option("generic", true), solver_set=true; } else { if(options.get_bool_option("smt1")) { options.set_option("boolector", true), solver_set=true; } else { INVARIANT(options.get_bool_option("smt2"), "smt2 set"); options.set_option("z3", true), solver_set=true; } } } // Either have solver and standard version set, or neither. INVARIANT(version_set==solver_set, "solver and version set"); if(cmdline.isset("beautify")) options.set_option("beautify", true); if(cmdline.isset("no-sat-preprocessor")) options.set_option("sat-preprocessor", false); else options.set_option("sat-preprocessor", true); options.set_option( "pretty-names", !cmdline.isset("no-pretty-names")); if(cmdline.isset("outfile")) options.set_option("outfile", cmdline.get_value("outfile")); if(cmdline.isset("graphml-witness")) { options.set_option("graphml-witness", cmdline.get_value("graphml-witness")); options.set_option("stop-on-fail", true); options.set_option("trace", true); } if(cmdline.isset("symex-coverage-report")) options.set_option( "symex-coverage-report", cmdline.get_value("symex-coverage-report")); PARSE_OPTIONS_GOTO_TRACE(cmdline, options); } /// invoke main modules int jbmc_parse_optionst::doit() { if(cmdline.isset("version")) { std::cout << CBMC_VERSION << '\n'; return 0; // should contemplate EX_OK from sysexits.h } // // command line options // optionst options; try { get_command_line_options(options); } catch(const char *error_msg) { error() << error_msg << eom; return 6; // should contemplate EX_SOFTWARE from sysexits.h } catch(const std::string &error_msg) { error() << error_msg << eom; return 6; // should contemplate EX_SOFTWARE from sysexits.h } eval_verbosity(); // // Print a banner // status() << "JBMC version " CBMC_VERSION " " << sizeof(void *)*8 << "-bit " << config.this_architecture() << " " << config.this_operating_system() << eom; register_language(new_ansi_c_language); register_language(new_java_bytecode_language); if(cmdline.isset("show-parse-tree")) { if(cmdline.args.size()!=1) { error() << "Please give exactly one source file" << eom; return 6; } std::string filename=cmdline.args[0]; #ifdef _MSC_VER std::ifstream infile(widen(filename)); #else std::ifstream infile(filename); #endif if(!infile) { error() << "failed to open input file `" << filename << "'" << eom; return 6; } std::unique_ptr<languaget> language= get_language_from_filename(filename); if(language==nullptr) { error() << "failed to figure out type of file `" << filename << "'" << eom; return 6; } language->get_language_options(cmdline); language->set_message_handler(get_message_handler()); status() << "Parsing " << filename << eom; if(language->parse(infile, filename)) { error() << "PARSING ERROR" << eom; return 6; } language->show_parse(std::cout); return 0; } std::unique_ptr<goto_modelt> goto_model_ptr; int get_goto_program_ret=get_goto_program(goto_model_ptr, options); if(get_goto_program_ret!=-1) return get_goto_program_ret; goto_modelt &goto_model = *goto_model_ptr; if(cmdline.isset("show-properties")) { show_properties(goto_model, ui_message_handler.get_ui()); return 0; // should contemplate EX_OK from sysexits.h } if(set_properties(goto_model)) return 7; // should contemplate EX_USAGE from sysexits.h // unwinds <clinit> loops to number of enum elements // side effect: add this as explicit unwind to unwind set if(options.get_bool_option("java-unwind-enum-static")) remove_static_init_loops(goto_model, options, get_message_handler()); // get solver cbmc_solverst jbmc_solvers( options, goto_model.symbol_table, get_message_handler()); jbmc_solvers.set_ui(ui_message_handler.get_ui()); std::unique_ptr<cbmc_solverst::solvert> jbmc_solver; try { jbmc_solver=jbmc_solvers.get_solver(); } catch(const char *error_msg) { error() << error_msg << eom; return 1; // should contemplate EX_SOFTWARE from sysexits.h } prop_convt &prop_conv=jbmc_solver->prop_conv(); bmct bmc( options, goto_model.symbol_table, get_message_handler(), prop_conv); // do actual BMC return do_bmc(bmc, goto_model); } bool jbmc_parse_optionst::set_properties(goto_modelt &goto_model) { try { if(cmdline.isset("property")) ::set_properties(goto_model, cmdline.get_values("property")); } catch(const char *e) { error() << e << eom; return true; } catch(const std::string &e) { error() << e << eom; return true; } catch(int) { return true; } return false; } int jbmc_parse_optionst::get_goto_program( std::unique_ptr<goto_modelt> &goto_model, const optionst &options) { if(cmdline.args.empty()) { error() << "Please provide a program to verify" << eom; return 6; } try { lazy_goto_modelt lazy_goto_model=lazy_goto_modelt::from_handler_object( *this, options, get_message_handler()); lazy_goto_model.initialize(cmdline); status() << "Generating GOTO Program" << messaget::eom; lazy_goto_model.load_all_functions(); // Show the symbol table before process_goto_functions mangles return // values, etc if(cmdline.isset("show-symbol-table")) { show_symbol_table( lazy_goto_model.symbol_table, ui_message_handler.get_ui()); return 0; } // Move the model out of the local lazy_goto_model // and into the caller's goto_model goto_model=lazy_goto_modelt::process_whole_model_and_freeze( std::move(lazy_goto_model)); if(goto_model == nullptr) return 6; // show it? if(cmdline.isset("show-loops")) { show_loop_ids(ui_message_handler.get_ui(), *goto_model); return 0; } // show it? if( cmdline.isset("show-goto-functions") || cmdline.isset("list-goto-functions")) { show_goto_functions( *goto_model, get_message_handler(), ui_message_handler.get_ui(), cmdline.isset("list-goto-functions")); return 0; } status() << config.object_bits_info() << eom; } catch(const char *e) { error() << e << eom; return 6; } catch(const std::string &e) { error() << e << eom; return 6; } catch(int) { return 6; } catch(const std::bad_alloc &) { error() << "Out of memory" << eom; return 6; } return -1; // no error, continue } void jbmc_parse_optionst::process_goto_function( goto_model_functiont &function) { symbol_tablet &symbol_table = function.get_symbol_table(); goto_functionst::goto_functiont &goto_function = function.get_goto_function(); try { // Remove inline assembler; this needs to happen before // adding the library. remove_asm(goto_function, symbol_table); // Removal of RTTI inspection: remove_instanceof(goto_function, symbol_table); // Java virtual functions -> explicit dispatch tables: remove_virtual_functions(function); } catch(const char *e) { error() << e << eom; throw; } catch(const std::string &e) { error() << e << eom; throw; } catch(const std::bad_alloc &) { error() << "Out of memory" << eom; throw; } } bool jbmc_parse_optionst::process_goto_functions( goto_modelt &goto_model, const optionst &options) { try { remove_java_new(goto_model, get_message_handler()); status() << "Removal of virtual functions" << eom; // remove catch and throw (introduces instanceof but request it is removed) remove_exceptions( goto_model, remove_exceptions_typest::REMOVE_ADDED_INSTANCEOF); // instrument library preconditions instrument_preconditions(goto_model); // remove returns, gcc vectors, complex remove_returns(goto_model); // Similar removal of java nondet statements: // TODO Should really get this from java_bytecode_language somehow, but we // don't have an instance of that here. object_factory_parameterst factory_params; factory_params.max_nondet_array_length= cmdline.isset("java-max-input-array-length") ? std::stoul(cmdline.get_value("java-max-input-array-length")) : MAX_NONDET_ARRAY_LENGTH_DEFAULT; factory_params.max_nondet_string_length= cmdline.isset("string-max-input-length") ? std::stoul(cmdline.get_value("string-max-input-length")) : MAX_NONDET_STRING_LENGTH; factory_params.max_nondet_tree_depth= cmdline.isset("java-max-input-tree-depth") ? std::stoul(cmdline.get_value("java-max-input-tree-depth")) : MAX_NONDET_TREE_DEPTH; replace_java_nondet(goto_model); convert_nondet( goto_model, get_message_handler(), factory_params); // add generic checks status() << "Generic Property Instrumentation" << eom; goto_check(options, goto_model); // checks don't know about adjusted float expressions adjust_float_expressions(goto_model); // ignore default/user-specified initialization // of variables with static lifetime if(cmdline.isset("nondet-static")) { status() << "Adding nondeterministic initialization " "of static/global variables" << eom; nondet_static(goto_model); } // add failed symbols // needs to be done before pointer analysis add_failed_symbols(goto_model.symbol_table); // recalculate numbers, etc. goto_model.goto_functions.update(); if(cmdline.isset("drop-unused-functions")) { // Entry point will have been set before and function pointers removed status() << "Removing unused functions" << eom; remove_unused_functions(goto_model, get_message_handler()); } // remove skips such that trivial GOTOs are deleted and not considered // for coverage annotation: remove_skip(goto_model); // instrument cover goals if(cmdline.isset("cover")) { if(instrument_cover_goals(options, goto_model, get_message_handler())) return true; } // label the assertions // This must be done after adding assertions and // before using the argument of the "property" option. // Do not re-label after using the property slicer because // this would cause the property identifiers to change. label_properties(goto_model); // full slice? if(cmdline.isset("full-slice")) { status() << "Performing a full slice" << eom; if(cmdline.isset("property")) property_slicer(goto_model, cmdline.get_values("property")); else full_slicer(goto_model); } // remove any skips introduced since coverage instrumentation remove_skip(goto_model); goto_model.goto_functions.update(); } catch(const char *e) { error() << e << eom; return true; } catch(const std::string &e) { error() << e << eom; return true; } catch(int) { return true; } catch(const std::bad_alloc &) { error() << "Out of memory" << eom; return true; } return false; } /// invoke main modules int jbmc_parse_optionst::do_bmc(bmct &bmc, goto_modelt &goto_model) { bmc.set_ui(ui_message_handler.get_ui()); int result=6; // do actual BMC switch(bmc.run(goto_model.goto_functions)) { case safety_checkert::resultt::SAFE: result=0; break; case safety_checkert::resultt::UNSAFE: result=10; break; case safety_checkert::resultt::ERROR: result=6; break; } // let's log some more statistics debug() << "Memory consumption:" << messaget::endl; memory_info(debug()); debug() << eom; return result; } /// display command line help void jbmc_parse_optionst::help() { std::cout << "\n" "* * JBMC " CBMC_VERSION " - Copyright (C) 2001-2017 "; std::cout << "(" << (sizeof(void *)*8) << "-bit version)"; std::cout << " * *\n"; std::cout << "* * Daniel Kroening, Edmund Clarke * *\n" "* * Carnegie Mellon University, Computer Science Department * *\n" "* * kroening@kroening.com * *\n" "\n" "Usage: Purpose:\n" "\n" " jbmc [-?] [-h] [--help] show help\n" " jbmc class name of class to be checked\n" "\n" "Analysis options:\n" " --show-properties show the properties, but don't run analysis\n" // NOLINT(*) " --symex-coverage-report f generate a Cobertura XML coverage report in f\n" // NOLINT(*) " --property id only check one specific property\n" " --stop-on-fail stop analysis once a failed property is detected\n" // NOLINT(*) " --trace give a counterexample trace for failed properties\n" //NOLINT(*) "\n" HELP_FUNCTIONS "\n" "Program representations:\n" " --show-parse-tree show parse tree\n" " --show-symbol-table show symbol table\n" HELP_SHOW_GOTO_FUNCTIONS " --drop-unused-functions drop functions trivially unreachable from main function\n" // NOLINT(*) "\n" "Program instrumentation options:\n" HELP_GOTO_CHECK " --no-assertions ignore user assertions\n" " --no-assumptions ignore user assumptions\n" " --error-label label check that label is unreachable\n" " --cover CC create test-suite with coverage criterion CC\n" // NOLINT(*) " --mm MM memory consistency model for concurrent programs\n" // NOLINT(*) "\n" "Java Bytecode frontend options:\n" " --classpath dir/jar set the classpath\n" " --main-class class-name set the name of the main class\n" JAVA_BYTECODE_LANGUAGE_OPTIONS_HELP // This one is handled by jbmc_parse_options not by the Java frontend, // hence its presence here: " --java-unwind-enum-static try to unwind loops in static initialization of enums\n" // NOLINT(*) "\n" "BMC options:\n" " --program-only only show program expression\n" " --show-loops show the loops in the program\n" " --depth nr limit search depth\n" " --unwind nr unwind nr times\n" " --unwindset L:B,... unwind loop L with a bound of B\n" " (use --show-loops to get the loop IDs)\n" " --show-vcc show the verification conditions\n" " --slice-formula remove assignments unrelated to property\n" " --unwinding-assertions generate unwinding assertions\n" " --partial-loops permit paths with partial loops\n" " --no-pretty-names do not simplify identifiers\n" " --graphml-witness filename write the witness in GraphML format to filename\n" // NOLINT(*) "\n" "Backend options:\n" " --object-bits n number of bits used for object addresses\n" " --dimacs generate CNF in DIMACS format\n" " --beautify beautify the counterexample (greedy heuristic)\n" // NOLINT(*) " --localize-faults localize faults (experimental)\n" " --smt1 use default SMT1 solver (obsolete)\n" " --smt2 use default SMT2 solver (Z3)\n" " --boolector use Boolector\n" " --mathsat use MathSAT\n" " --cvc4 use CVC4\n" " --yices use Yices\n" " --z3 use Z3\n" " --refine use refinement procedure (experimental)\n" " --refine-strings use string refinement (experimental)\n" " --string-printable add constraint that strings are printable (experimental)\n" // NOLINT(*) " --string-max-length add constraint on the length of strings\n" // NOLINT(*) " --string-max-input-length add constraint on the length of input strings\n" // NOLINT(*) " --outfile filename output formula to given file\n" " --arrays-uf-never never turn arrays into uninterpreted functions\n" // NOLINT(*) " --arrays-uf-always always turn arrays into uninterpreted functions\n" // NOLINT(*) "\n" "Other options:\n" " --version show version and exit\n" " --xml-ui use XML-formatted output\n" " --json-ui use JSON-formatted output\n" HELP_GOTO_TRACE " --verbosity # verbosity level\n" "\n"; }
27.914439
107
0.646245
[ "object", "model" ]
411bfa0858535134b5cf051e91d85311c5da8ba6
38,793
cc
C++
test/cctest/test-js-weak-refs.cc
ibraheemdev/able-script
5a5eaf12b9c410f0cd83ca05e42c9a608c9814f1
[ "BSD-3-Clause" ]
1
2021-05-05T11:52:49.000Z
2021-05-05T11:52:49.000Z
test/cctest/test-js-weak-refs.cc
libaoheng/v8
ed73693de815988a27ead2216acd7ab9955d9e92
[ "BSD-3-Clause" ]
11
2019-10-15T23:03:57.000Z
2020-06-14T16:10:12.000Z
test/cctest/test-js-weak-refs.cc
libaoheng/v8
ed73693de815988a27ead2216acd7ab9955d9e92
[ "BSD-3-Clause" ]
7
2019-07-04T14:23:54.000Z
2020-04-27T08:52:51.000Z
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/execution/isolate.h" #include "src/execution/microtask-queue.h" #include "src/handles/handles-inl.h" #include "src/heap/factory-inl.h" #include "src/heap/heap-inl.h" #include "src/objects/js-objects.h" #include "src/objects/js-weak-refs-inl.h" #include "test/cctest/cctest.h" #include "test/cctest/heap/heap-utils.h" namespace v8 { namespace internal { namespace { Handle<JSFinalizationRegistry> ConstructJSFinalizationRegistry( Isolate* isolate) { Factory* factory = isolate->factory(); Handle<String> finalization_registry_name = factory->NewStringFromStaticChars("FinalizationRegistry"); Handle<Object> global = handle(isolate->native_context()->global_object(), isolate); Handle<JSFunction> finalization_registry_fun = Handle<JSFunction>::cast( Object::GetProperty(isolate, global, finalization_registry_name) .ToHandleChecked()); auto finalization_registry = Handle<JSFinalizationRegistry>::cast( JSObject::New(finalization_registry_fun, finalization_registry_fun, Handle<AllocationSite>::null()) .ToHandleChecked()); #ifdef VERIFY_HEAP finalization_registry->JSFinalizationRegistryVerify(isolate); #endif // VERIFY_HEAP return finalization_registry; } Handle<JSWeakRef> ConstructJSWeakRef(Handle<JSReceiver> target, Isolate* isolate) { Factory* factory = isolate->factory(); Handle<String> weak_ref_name = factory->WeakRef_string(); Handle<Object> global = handle(isolate->native_context()->global_object(), isolate); Handle<JSFunction> weak_ref_fun = Handle<JSFunction>::cast( Object::GetProperty(isolate, global, weak_ref_name).ToHandleChecked()); auto weak_ref = Handle<JSWeakRef>::cast( JSObject::New(weak_ref_fun, weak_ref_fun, Handle<AllocationSite>::null()) .ToHandleChecked()); weak_ref->set_target(*target); #ifdef VERIFY_HEAP weak_ref->JSWeakRefVerify(isolate); #endif // VERIFY_HEAP return weak_ref; } Handle<JSObject> CreateKey(const char* key_prop_value, Isolate* isolate) { Factory* factory = isolate->factory(); Handle<String> key_string = factory->NewStringFromStaticChars("key_string"); Handle<JSObject> key = isolate->factory()->NewJSObject(isolate->object_function()); JSObject::AddProperty(isolate, key, key_string, factory->NewStringFromAsciiChecked(key_prop_value), NONE); return key; } Handle<WeakCell> FinalizationRegistryRegister( Handle<JSFinalizationRegistry> finalization_registry, Handle<JSObject> target, Handle<Object> held_value, Handle<Object> unregister_token, Isolate* isolate) { Factory* factory = isolate->factory(); Handle<JSFunction> regfunc = Handle<JSFunction>::cast( Object::GetProperty(isolate, finalization_registry, factory->NewStringFromStaticChars("register")) .ToHandleChecked()); Handle<Object> args[] = {target, held_value, unregister_token}; Execution::Call(isolate, regfunc, finalization_registry, arraysize(args), args) .ToHandleChecked(); CHECK(finalization_registry->active_cells().IsWeakCell()); Handle<WeakCell> weak_cell = handle(WeakCell::cast(finalization_registry->active_cells()), isolate); #ifdef VERIFY_HEAP weak_cell->WeakCellVerify(isolate); #endif // VERIFY_HEAP return weak_cell; } Handle<WeakCell> FinalizationRegistryRegister( Handle<JSFinalizationRegistry> finalization_registry, Handle<JSObject> target, Isolate* isolate) { Handle<Object> undefined = handle(ReadOnlyRoots(isolate).undefined_value(), isolate); return FinalizationRegistryRegister(finalization_registry, target, undefined, undefined, isolate); } void NullifyWeakCell(Handle<WeakCell> weak_cell, Isolate* isolate) { auto empty_func = [](HeapObject object, ObjectSlot slot, Object target) {}; weak_cell->Nullify(isolate, empty_func); #ifdef VERIFY_HEAP weak_cell->WeakCellVerify(isolate); #endif // VERIFY_HEAP } Object PopClearedCellHoldings( Handle<JSFinalizationRegistry> finalization_registry, Isolate* isolate) { // PopClearedCell is implemented in Torque. Reproduce that implementation here // for testing. Handle<WeakCell> weak_cell = handle(WeakCell::cast(finalization_registry->cleared_cells()), isolate); DCHECK(weak_cell->prev().IsUndefined(isolate)); finalization_registry->set_cleared_cells(weak_cell->next()); weak_cell->set_next(ReadOnlyRoots(isolate).undefined_value()); if (finalization_registry->cleared_cells().IsWeakCell()) { WeakCell cleared_cells_head = WeakCell::cast(finalization_registry->cleared_cells()); DCHECK_EQ(cleared_cells_head.prev(), *weak_cell); cleared_cells_head.set_prev(ReadOnlyRoots(isolate).undefined_value()); } else { DCHECK(finalization_registry->cleared_cells().IsUndefined(isolate)); } if (!weak_cell->unregister_token().IsUndefined(isolate)) { JSFinalizationRegistry::RemoveCellFromUnregisterTokenMap( isolate, finalization_registry->ptr(), weak_cell->ptr()); } return weak_cell->holdings(); } // Usage: VerifyWeakCellChain(isolate, list_head, n, cell1, cell2, ..., celln); // verifies that list_head == cell1 and cell1, cell2, ..., celln. form a list. void VerifyWeakCellChain(Isolate* isolate, Object list_head, int n_args, ...) { CHECK_GE(n_args, 0); va_list args; va_start(args, n_args); if (n_args == 0) { // Verify empty list CHECK(list_head.IsUndefined(isolate)); } else { WeakCell current = WeakCell::cast(Object(va_arg(args, Address))); CHECK_EQ(current, list_head); CHECK(current.prev().IsUndefined(isolate)); for (int i = 1; i < n_args; i++) { WeakCell next = WeakCell::cast(Object(va_arg(args, Address))); CHECK_EQ(current.next(), next); CHECK_EQ(next.prev(), current); current = next; } CHECK(current.next().IsUndefined(isolate)); } va_end(args); } // Like VerifyWeakCellChain but verifies the chain created with key_list_prev // and key_list_next instead of prev and next. void VerifyWeakCellKeyChain(Isolate* isolate, SimpleNumberDictionary key_map, Object unregister_token, int n_args, ...) { CHECK_GE(n_args, 0); va_list args; va_start(args, n_args); Object hash = unregister_token.GetHash(); InternalIndex entry = InternalIndex::NotFound(); if (!hash.IsUndefined(isolate)) { uint32_t key = Smi::ToInt(hash); entry = key_map.FindEntry(isolate, key); } if (n_args == 0) { // Verify empty list CHECK(entry.is_not_found()); } else { CHECK(entry.is_found()); WeakCell current = WeakCell::cast(Object(va_arg(args, Address))); Object list_head = key_map.ValueAt(entry); CHECK_EQ(current, list_head); CHECK(current.key_list_prev().IsUndefined(isolate)); for (int i = 1; i < n_args; i++) { WeakCell next = WeakCell::cast(Object(va_arg(args, Address))); CHECK_EQ(current.key_list_next(), next); CHECK_EQ(next.key_list_prev(), current); current = next; } CHECK(current.key_list_next().IsUndefined(isolate)); } va_end(args); } Handle<JSWeakRef> MakeWeakRefAndKeepDuringJob(Isolate* isolate) { HandleScope inner_scope(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSWeakRef> inner_weak_ref = ConstructJSWeakRef(js_object, isolate); isolate->heap()->KeepDuringJob(js_object); return inner_scope.CloseAndEscape(inner_weak_ref); } } // namespace TEST(TestRegister) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); // Register a weak reference and verify internal data structures. Handle<WeakCell> weak_cell1 = FinalizationRegistryRegister(finalization_registry, js_object, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 1, *weak_cell1); CHECK(weak_cell1->key_list_prev().IsUndefined(isolate)); CHECK(weak_cell1->key_list_next().IsUndefined(isolate)); CHECK(finalization_registry->cleared_cells().IsUndefined(isolate)); // No key was used during registration, key-based map stays uninitialized. CHECK(finalization_registry->key_map().IsUndefined(isolate)); // Register another weak reference and verify internal data structures. Handle<WeakCell> weak_cell2 = FinalizationRegistryRegister(finalization_registry, js_object, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 2, *weak_cell2, *weak_cell1); CHECK(weak_cell2->key_list_prev().IsUndefined(isolate)); CHECK(weak_cell2->key_list_next().IsUndefined(isolate)); CHECK(finalization_registry->cleared_cells().IsUndefined(isolate)); CHECK(finalization_registry->key_map().IsUndefined(isolate)); } TEST(TestRegisterWithKey) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSObject> token1 = CreateKey("token1", isolate); Handle<JSObject> token2 = CreateKey("token2", isolate); Handle<Object> undefined = handle(ReadOnlyRoots(isolate).undefined_value(), isolate); // Register a weak reference with a key and verify internal data structures. Handle<WeakCell> weak_cell1 = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 1, *weak_cell1); VerifyWeakCellKeyChain(isolate, key_map, *token2, 0); } // Register another weak reference with a different key and verify internal // data structures. Handle<WeakCell> weak_cell2 = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token2, isolate); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 1, *weak_cell1); VerifyWeakCellKeyChain(isolate, key_map, *token2, 1, *weak_cell2); } // Register another weak reference with token1 and verify internal data // structures. Handle<WeakCell> weak_cell3 = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 2, *weak_cell3, *weak_cell1); VerifyWeakCellKeyChain(isolate, key_map, *token2, 1, *weak_cell2); } } TEST(TestWeakCellNullify1) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<WeakCell> weak_cell1 = FinalizationRegistryRegister(finalization_registry, js_object, isolate); Handle<WeakCell> weak_cell2 = FinalizationRegistryRegister(finalization_registry, js_object, isolate); // Nullify the first WeakCell and verify internal data structures. NullifyWeakCell(weak_cell1, isolate); CHECK_EQ(finalization_registry->active_cells(), *weak_cell2); CHECK(weak_cell2->prev().IsUndefined(isolate)); CHECK(weak_cell2->next().IsUndefined(isolate)); CHECK_EQ(finalization_registry->cleared_cells(), *weak_cell1); CHECK(weak_cell1->prev().IsUndefined(isolate)); CHECK(weak_cell1->next().IsUndefined(isolate)); // Nullify the second WeakCell and verify internal data structures. NullifyWeakCell(weak_cell2, isolate); CHECK(finalization_registry->active_cells().IsUndefined(isolate)); CHECK_EQ(finalization_registry->cleared_cells(), *weak_cell2); CHECK_EQ(weak_cell2->next(), *weak_cell1); CHECK(weak_cell2->prev().IsUndefined(isolate)); CHECK_EQ(weak_cell1->prev(), *weak_cell2); CHECK(weak_cell1->next().IsUndefined(isolate)); } TEST(TestWeakCellNullify2) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<WeakCell> weak_cell1 = FinalizationRegistryRegister(finalization_registry, js_object, isolate); Handle<WeakCell> weak_cell2 = FinalizationRegistryRegister(finalization_registry, js_object, isolate); // Like TestWeakCellNullify1 but nullify the WeakCells in opposite order. NullifyWeakCell(weak_cell2, isolate); CHECK_EQ(finalization_registry->active_cells(), *weak_cell1); CHECK(weak_cell1->prev().IsUndefined(isolate)); CHECK(weak_cell1->next().IsUndefined(isolate)); CHECK_EQ(finalization_registry->cleared_cells(), *weak_cell2); CHECK(weak_cell2->prev().IsUndefined(isolate)); CHECK(weak_cell2->next().IsUndefined(isolate)); NullifyWeakCell(weak_cell1, isolate); CHECK(finalization_registry->active_cells().IsUndefined(isolate)); CHECK_EQ(finalization_registry->cleared_cells(), *weak_cell1); CHECK_EQ(weak_cell1->next(), *weak_cell2); CHECK(weak_cell1->prev().IsUndefined(isolate)); CHECK_EQ(weak_cell2->prev(), *weak_cell1); CHECK(weak_cell2->next().IsUndefined(isolate)); } TEST(TestJSFinalizationRegistryPopClearedCellHoldings1) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<Object> undefined = handle(ReadOnlyRoots(isolate).undefined_value(), isolate); Handle<Object> holdings1 = factory->NewStringFromAsciiChecked("holdings1"); Handle<WeakCell> weak_cell1 = FinalizationRegistryRegister( finalization_registry, js_object, holdings1, undefined, isolate); Handle<Object> holdings2 = factory->NewStringFromAsciiChecked("holdings2"); Handle<WeakCell> weak_cell2 = FinalizationRegistryRegister( finalization_registry, js_object, holdings2, undefined, isolate); Handle<Object> holdings3 = factory->NewStringFromAsciiChecked("holdings3"); Handle<WeakCell> weak_cell3 = FinalizationRegistryRegister( finalization_registry, js_object, holdings3, undefined, isolate); NullifyWeakCell(weak_cell2, isolate); NullifyWeakCell(weak_cell3, isolate); CHECK(finalization_registry->NeedsCleanup()); Object cleared1 = PopClearedCellHoldings(finalization_registry, isolate); CHECK_EQ(cleared1, *holdings3); CHECK(weak_cell3->prev().IsUndefined(isolate)); CHECK(weak_cell3->next().IsUndefined(isolate)); CHECK(finalization_registry->NeedsCleanup()); Object cleared2 = PopClearedCellHoldings(finalization_registry, isolate); CHECK_EQ(cleared2, *holdings2); CHECK(weak_cell2->prev().IsUndefined(isolate)); CHECK(weak_cell2->next().IsUndefined(isolate)); CHECK(!finalization_registry->NeedsCleanup()); NullifyWeakCell(weak_cell1, isolate); CHECK(finalization_registry->NeedsCleanup()); Object cleared3 = PopClearedCellHoldings(finalization_registry, isolate); CHECK_EQ(cleared3, *holdings1); CHECK(weak_cell1->prev().IsUndefined(isolate)); CHECK(weak_cell1->next().IsUndefined(isolate)); CHECK(!finalization_registry->NeedsCleanup()); CHECK(finalization_registry->active_cells().IsUndefined(isolate)); CHECK(finalization_registry->cleared_cells().IsUndefined(isolate)); } TEST(TestJSFinalizationRegistryPopClearedCellHoldings2) { // Test that when all WeakCells for a key are popped, the key is removed from // the key map. CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSObject> token1 = CreateKey("token1", isolate); Handle<Object> holdings1 = factory->NewStringFromAsciiChecked("holdings1"); Handle<WeakCell> weak_cell1 = FinalizationRegistryRegister( finalization_registry, js_object, holdings1, token1, isolate); Handle<Object> holdings2 = factory->NewStringFromAsciiChecked("holdings2"); Handle<WeakCell> weak_cell2 = FinalizationRegistryRegister( finalization_registry, js_object, holdings2, token1, isolate); NullifyWeakCell(weak_cell1, isolate); NullifyWeakCell(weak_cell2, isolate); // Nullifying doesn't affect the key chains (just moves WeakCells from // active_cells to cleared_cells). { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 2, *weak_cell2, *weak_cell1); } Object cleared1 = PopClearedCellHoldings(finalization_registry, isolate); CHECK_EQ(cleared1, *holdings2); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 1, *weak_cell1); } Object cleared2 = PopClearedCellHoldings(finalization_registry, isolate); CHECK_EQ(cleared2, *holdings1); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 0); } } TEST(TestUnregisterActiveCells) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSObject> token1 = CreateKey("token1", isolate); Handle<JSObject> token2 = CreateKey("token2", isolate); Handle<Object> undefined = handle(ReadOnlyRoots(isolate).undefined_value(), isolate); Handle<WeakCell> weak_cell1a = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); Handle<WeakCell> weak_cell1b = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); Handle<WeakCell> weak_cell2a = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token2, isolate); Handle<WeakCell> weak_cell2b = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token2, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 4, *weak_cell2b, *weak_cell2a, *weak_cell1b, *weak_cell1a); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 0); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 2, *weak_cell1b, *weak_cell1a); VerifyWeakCellKeyChain(isolate, key_map, *token2, 2, *weak_cell2b, *weak_cell2a); } JSFinalizationRegistry::Unregister(finalization_registry, token1, isolate); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 0); VerifyWeakCellKeyChain(isolate, key_map, *token2, 2, *weak_cell2b, *weak_cell2a); } // Both weak_cell1a and weak_cell1b removed from active_cells. VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 2, *weak_cell2b, *weak_cell2a); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 0); } TEST(TestUnregisterActiveAndClearedCells) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSObject> token1 = CreateKey("token1", isolate); Handle<JSObject> token2 = CreateKey("token2", isolate); Handle<Object> undefined = handle(ReadOnlyRoots(isolate).undefined_value(), isolate); Handle<WeakCell> weak_cell1a = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); Handle<WeakCell> weak_cell1b = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); Handle<WeakCell> weak_cell2a = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token2, isolate); Handle<WeakCell> weak_cell2b = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token2, isolate); NullifyWeakCell(weak_cell2a, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 3, *weak_cell2b, *weak_cell1b, *weak_cell1a); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 1, *weak_cell2a); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 2, *weak_cell1b, *weak_cell1a); VerifyWeakCellKeyChain(isolate, key_map, *token2, 2, *weak_cell2b, *weak_cell2a); } JSFinalizationRegistry::Unregister(finalization_registry, token2, isolate); // Both weak_cell2a and weak_cell2b removed. VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 2, *weak_cell1b, *weak_cell1a); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 0); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 2, *weak_cell1b, *weak_cell1a); VerifyWeakCellKeyChain(isolate, key_map, *token2, 0); } } TEST(TestWeakCellUnregisterTwice) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSObject> token1 = CreateKey("token1", isolate); Handle<Object> undefined = handle(ReadOnlyRoots(isolate).undefined_value(), isolate); Handle<WeakCell> weak_cell1 = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 1, *weak_cell1); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 0); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 1, *weak_cell1); } JSFinalizationRegistry::Unregister(finalization_registry, token1, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 0); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 0); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 0); } JSFinalizationRegistry::Unregister(finalization_registry, token1, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 0); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 0); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 0); } } TEST(TestWeakCellUnregisterPopped) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); Factory* factory = isolate->factory(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSObject> token1 = CreateKey("token1", isolate); Handle<Object> holdings1 = factory->NewStringFromAsciiChecked("holdings1"); Handle<WeakCell> weak_cell1 = FinalizationRegistryRegister( finalization_registry, js_object, holdings1, token1, isolate); NullifyWeakCell(weak_cell1, isolate); CHECK(finalization_registry->NeedsCleanup()); Object cleared1 = PopClearedCellHoldings(finalization_registry, isolate); CHECK_EQ(cleared1, *holdings1); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 0); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 0); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 0); } JSFinalizationRegistry::Unregister(finalization_registry, token1, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 0); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 0); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 0); } } TEST(TestWeakCellUnregisterNonexistentKey) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> token1 = CreateKey("token1", isolate); JSFinalizationRegistry::Unregister(finalization_registry, token1, isolate); } TEST(TestJSWeakRef) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSWeakRef> weak_ref; { HandleScope inner_scope(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); // This doesn't add the target into the KeepDuringJob set. Handle<JSWeakRef> inner_weak_ref = ConstructJSWeakRef(js_object, isolate); CcTest::CollectAllGarbage(); CHECK(!inner_weak_ref->target().IsUndefined(isolate)); weak_ref = inner_scope.CloseAndEscape(inner_weak_ref); } CHECK(!weak_ref->target().IsUndefined(isolate)); CcTest::CollectAllGarbage(); CHECK(weak_ref->target().IsUndefined(isolate)); } TEST(TestJSWeakRefIncrementalMarking) { if (!FLAG_incremental_marking) { return; } ManualGCScope manual_gc_scope; CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); Heap* heap = isolate->heap(); HandleScope outer_scope(isolate); Handle<JSWeakRef> weak_ref; { HandleScope inner_scope(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); // This doesn't add the target into the KeepDuringJob set. Handle<JSWeakRef> inner_weak_ref = ConstructJSWeakRef(js_object, isolate); heap::SimulateIncrementalMarking(heap, true); CcTest::CollectAllGarbage(); CHECK(!inner_weak_ref->target().IsUndefined(isolate)); weak_ref = inner_scope.CloseAndEscape(inner_weak_ref); } CHECK(!weak_ref->target().IsUndefined(isolate)); heap::SimulateIncrementalMarking(heap, true); CcTest::CollectAllGarbage(); CHECK(weak_ref->target().IsUndefined(isolate)); } TEST(TestJSWeakRefKeepDuringJob) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSWeakRef> weak_ref = MakeWeakRefAndKeepDuringJob(isolate); CHECK(!weak_ref->target().IsUndefined(isolate)); CcTest::CollectAllGarbage(); CHECK(!weak_ref->target().IsUndefined(isolate)); // Clears the KeepDuringJob set. context->GetIsolate()->ClearKeptObjects(); CcTest::CollectAllGarbage(); CHECK(weak_ref->target().IsUndefined(isolate)); weak_ref = MakeWeakRefAndKeepDuringJob(isolate); CHECK(!weak_ref->target().IsUndefined(isolate)); CcTest::CollectAllGarbage(); CHECK(!weak_ref->target().IsUndefined(isolate)); // ClearKeptObjects should be called by PerformMicrotasksCheckpoint. CcTest::isolate()->PerformMicrotaskCheckpoint(); CcTest::CollectAllGarbage(); CHECK(weak_ref->target().IsUndefined(isolate)); weak_ref = MakeWeakRefAndKeepDuringJob(isolate); CHECK(!weak_ref->target().IsUndefined(isolate)); CcTest::CollectAllGarbage(); CHECK(!weak_ref->target().IsUndefined(isolate)); // ClearKeptObjects should be called by MicrotasksScope::PerformCheckpoint. v8::MicrotasksScope::PerformCheckpoint(CcTest::isolate()); CcTest::CollectAllGarbage(); CHECK(weak_ref->target().IsUndefined(isolate)); } TEST(TestJSWeakRefKeepDuringJobIncrementalMarking) { if (!FLAG_incremental_marking) { return; } ManualGCScope manual_gc_scope; CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); Heap* heap = isolate->heap(); HandleScope outer_scope(isolate); Handle<JSWeakRef> weak_ref = MakeWeakRefAndKeepDuringJob(isolate); CHECK(!weak_ref->target().IsUndefined(isolate)); heap::SimulateIncrementalMarking(heap, true); CcTest::CollectAllGarbage(); CHECK(!weak_ref->target().IsUndefined(isolate)); // Clears the KeepDuringJob set. context->GetIsolate()->ClearKeptObjects(); heap::SimulateIncrementalMarking(heap, true); CcTest::CollectAllGarbage(); CHECK(weak_ref->target().IsUndefined(isolate)); } TEST(TestRemoveUnregisterToken) { CcTest::InitializeVM(); LocalContext context; Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle<JSFinalizationRegistry> finalization_registry = ConstructJSFinalizationRegistry(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSObject> token1 = CreateKey("token1", isolate); Handle<JSObject> token2 = CreateKey("token2", isolate); Handle<Object> undefined = handle(ReadOnlyRoots(isolate).undefined_value(), isolate); Handle<WeakCell> weak_cell1a = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); Handle<WeakCell> weak_cell1b = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token1, isolate); Handle<WeakCell> weak_cell2a = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token2, isolate); Handle<WeakCell> weak_cell2b = FinalizationRegistryRegister( finalization_registry, js_object, undefined, token2, isolate); NullifyWeakCell(weak_cell2a, isolate); VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 3, *weak_cell2b, *weak_cell1b, *weak_cell1a); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 1, *weak_cell2a); { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 2, *weak_cell1b, *weak_cell1a); VerifyWeakCellKeyChain(isolate, key_map, *token2, 2, *weak_cell2b, *weak_cell2a); } finalization_registry->RemoveUnregisterToken( JSReceiver::cast(*token2), isolate, [undefined](WeakCell matched_cell) { matched_cell.set_unregister_token(*undefined); }, [](HeapObject, ObjectSlot, Object) {}); // Both weak_cell2a and weak_cell2b remain on the weak cell chains. VerifyWeakCellChain(isolate, finalization_registry->active_cells(), 3, *weak_cell2b, *weak_cell1b, *weak_cell1a); VerifyWeakCellChain(isolate, finalization_registry->cleared_cells(), 1, *weak_cell2a); // But both weak_cell2a and weak_cell2b are removed from the key chain. { SimpleNumberDictionary key_map = SimpleNumberDictionary::cast(finalization_registry->key_map()); VerifyWeakCellKeyChain(isolate, key_map, *token1, 2, *weak_cell1b, *weak_cell1a); VerifyWeakCellKeyChain(isolate, key_map, *token2, 0); } } TEST(JSWeakRefScavengedInWorklist) { if (!FLAG_incremental_marking || FLAG_single_generation) { return; } ManualGCScope manual_gc_scope; CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); Heap* heap = isolate->heap(); { HandleScope outer_scope(isolate); Handle<JSWeakRef> weak_ref; // Make a WeakRef that points to a target, both of which become unreachable. { HandleScope inner_scope(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSWeakRef> inner_weak_ref = ConstructJSWeakRef(js_object, isolate); CHECK(Heap::InYoungGeneration(*js_object)); CHECK(Heap::InYoungGeneration(*inner_weak_ref)); weak_ref = inner_scope.CloseAndEscape(inner_weak_ref); } // Store weak_ref in Global such that it is part of the root set when // starting incremental marking. v8::Global<Value> global_weak_ref( CcTest::isolate(), Utils::ToLocal(Handle<Object>::cast(weak_ref))); // Do marking. This puts the WeakRef above into the js_weak_refs worklist // since its target isn't marked. CHECK( heap->mark_compact_collector()->weak_objects()->js_weak_refs.IsEmpty()); heap::SimulateIncrementalMarking(heap, true); CHECK(!heap->mark_compact_collector() ->weak_objects() ->js_weak_refs.IsEmpty()); } // Now collect both weak_ref and its target. The worklist should be empty. CcTest::CollectGarbage(NEW_SPACE); CHECK(heap->mark_compact_collector()->weak_objects()->js_weak_refs.IsEmpty()); // The mark-compactor shouldn't see zapped WeakRefs in the worklist. CcTest::CollectAllGarbage(); } TEST(JSWeakRefTenuredInWorklist) { if (!FLAG_incremental_marking || FLAG_single_generation) { return; } ManualGCScope manual_gc_scope; CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); Heap* heap = isolate->heap(); HandleScope outer_scope(isolate); Handle<JSWeakRef> weak_ref; // Make a WeakRef that points to a target. The target becomes unreachable. { HandleScope inner_scope(isolate); Handle<JSObject> js_object = isolate->factory()->NewJSObject(isolate->object_function()); Handle<JSWeakRef> inner_weak_ref = ConstructJSWeakRef(js_object, isolate); CHECK(Heap::InYoungGeneration(*js_object)); CHECK(Heap::InYoungGeneration(*inner_weak_ref)); weak_ref = inner_scope.CloseAndEscape(inner_weak_ref); } // Store weak_ref such that it is part of the root set when starting // incremental marking. v8::Global<Value> global_weak_ref( CcTest::isolate(), Utils::ToLocal(Handle<Object>::cast(weak_ref))); JSWeakRef old_weak_ref_location = *weak_ref; // Do marking. This puts the WeakRef above into the js_weak_refs worklist // since its target isn't marked. CHECK(heap->mark_compact_collector()->weak_objects()->js_weak_refs.IsEmpty()); heap::SimulateIncrementalMarking(heap, true); CHECK( !heap->mark_compact_collector()->weak_objects()->js_weak_refs.IsEmpty()); // Now collect weak_ref's target. We still have a Handle to weak_ref, so it is // moved and remains on the worklist. CcTest::CollectGarbage(NEW_SPACE); JSWeakRef new_weak_ref_location = *weak_ref; CHECK_NE(old_weak_ref_location, new_weak_ref_location); CHECK( !heap->mark_compact_collector()->weak_objects()->js_weak_refs.IsEmpty()); // The mark-compactor should see the moved WeakRef in the worklist. CcTest::CollectAllGarbage(); CHECK(heap->mark_compact_collector()->weak_objects()->js_weak_refs.IsEmpty()); CHECK(weak_ref->target().IsUndefined(isolate)); } TEST(UnregisterTokenHeapVerifier) { if (!FLAG_incremental_marking) return; ManualGCScope manual_gc_scope; #ifdef VERIFY_HEAP FLAG_verify_heap = true; #endif CcTest::InitializeVM(); v8::Isolate* isolate = CcTest::isolate(); Heap* heap = CcTest::heap(); v8::HandleScope outer_scope(isolate); { // Make a new FinalizationRegistry and register an object with an unregister // token that's unreachable after the IIFE returns. v8::HandleScope scope(isolate); CompileRun( "var token = {}; " "var registry = new FinalizationRegistry(function () {}); " "(function () { " " let o = {}; " " registry.register(o, {}, token); " "})();"); } // GC so the WeakCell corresponding to o is moved from the active_cells to // cleared_cells. CcTest::CollectAllGarbage(); CcTest::CollectAllGarbage(); { // Override the unregister token to make the original object collectible. v8::HandleScope scope(isolate); CompileRun("token = 0;"); } heap::SimulateIncrementalMarking(heap, true); // Pump message loop to run the finalizer task, then the incremental marking // task. The finalizer task will pop the WeakCell from the cleared list. This // should make the unregister_token slot undefined. That slot is iterated as a // custom weak pointer, so if it is not made undefined, the verifier as part // of the incremental marking task will crash. EmptyMessageQueues(isolate); } } // namespace internal } // namespace v8
38.144543
80
0.735519
[ "object" ]
411c0e58ca07f22ddca2052aa7981dcf35d78e77
1,273
cpp
C++
PyCommon/externalLibs/BaseLib/motion/Retarget_JH/PmQm/qmSphericalHS.cpp
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
4
2018-05-14T07:27:59.000Z
2021-12-21T04:39:21.000Z
PyCommon/externalLibs/BaseLib/motion/Retarget_JH/PmQm/qmSphericalHS.cpp
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
null
null
null
PyCommon/externalLibs/BaseLib/motion/Retarget_JH/PmQm/qmSphericalHS.cpp
hpgit/HumanFoot
f9a1a341b7c43747bddcd5584b8c98a0d1ac2973
[ "Apache-2.0" ]
3
2018-01-03T06:09:21.000Z
2021-07-26T15:13:14.000Z
#include "MATHCLASS/mathclass.h" #include "qmSphericalHS.h" using namespace jhm; int QmSphericalHS::inclusion( quater const& q ) { m_real d = 2.0*ln(q * orientation.inverse()).length(); return d << angle_bound; } int QmSphericalHS::intersection( QmGeodesic const&, quater* ) { return -1; } vector QmSphericalHS::gradient( quater const& q ) { return vector(0,0,0); } m_real QmSphericalHS::distance( quater const& q ) { m_real d = 2*ln(q * orientation.inverse()).length(); return angle_bound.distance( d ); } quater QmSphericalHS::nearest( quater const& q ) { vector v = 2*ln(q * orientation.inverse()); if ( v.length() << angle_bound ) return q; return exp( angle_bound.end_pt() * normalize(v) / 2. ) * orientation; } void QmSphericalHS::write( std::ostream& os ) { os << (*this); } std::ostream& operator<<( std::ostream& os, QmSphericalHS const& h ) { os << "#S( " << h.getOrientation() << " , " << h.getAngleBound() << " )"; return os; } std::istream& operator>>( std::istream& is, QmSphericalHS& h ) { quater q; interval i; char buf[100]; is >> buf >> q >> buf >> i >> buf; h.setOrientation( q ); h.setAngleBound( i ); return is; }
17.438356
78
0.595444
[ "vector" ]
411c9e086e3a879273055bf98de9702c1f908b8f
2,780
cpp
C++
lintcode/629.minimum-spanning-tree.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
177
2017-08-21T08:57:43.000Z
2020-06-22T03:44:22.000Z
lintcode/629.minimum-spanning-tree.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
2
2018-09-06T13:39:12.000Z
2019-06-03T02:54:45.000Z
lintcode/629.minimum-spanning-tree.cpp
geemaple/algorithm
68bc5032e1ee52c22ef2f2e608053484c487af54
[ "MIT" ]
23
2017-08-23T06:01:28.000Z
2020-04-20T03:17:36.000Z
/** * Definition for a Connection. * class Connection { * public: * string city1, city2; * int cost; * Connection(string& city1, string& city2, int cost) { * this->city1 = city1; * this->city2 = city2; * this->cost = cost; * } */ class UnionFind { vector<int> graph; int size; public: UnionFind(int n) { graph.resize(n); size = n; for(int i = 0; i < n; ++i) { graph[i] = i; } } int find(int node) { if (graph[node] == node) { return node; } graph[node] = find(graph[node]); return graph[node]; } bool query(int a, int b) { return find(a) == find(b); } void connect(int a, int b) { int root_a = find(a); int root_b = find(b); if (root_a != root_b) { graph[root_a] = root_b; size--; } } bool allConnected() { return size == 1; } }; class Solution { public: /** * @param connections given a list of connections include two cities and cost * @return a list of connections from results */ vector<Connection> lowestCost(vector<Connection>& connections) { // Write your code here //sort according to cost auto comp = [](Connection& x, Connection& y){ if (x.cost != y.cost){ return x.cost < y.cost; } else if(x.city1 != y.city1) { return x.city1 < y.city1; } else { return x.city2 < y.city2; } }; sort(connections.begin(), connections.end(), comp); // map city int count = 0; int size = connections.size(); unordered_map<string, int> cityMap; for(int i = 0; i < size; ++i) { Connection conn = connections[i]; if (cityMap.count(conn.city1) == 0) { cityMap[conn.city1] = count++; } if (cityMap.count(conn.city2) == 0) { cityMap[conn.city2] = count++; } } UnionFind uf(count); vector<Connection> res; for(int i = 0; i < size; ++i) { Connection conn = connections[i]; int city1 = cityMap[conn.city1]; int city2 = cityMap[conn.city2]; if(!uf.query(city1, city2)) { uf.connect(city1, city2); res.push_back(conn); } } return uf.allConnected() ? res: vector<Connection>(); } };
22.419355
81
0.441007
[ "vector" ]
4121742fc5a0ecf12913852e14a74313b09e6aa0
9,865
cpp
C++
lib/src/sai_redis_route.cpp
AmitKaushik7/sonic-sairedis
59e530a485bbe419f30779fe5f7058ff5bbaade8
[ "Apache-2.0" ]
null
null
null
lib/src/sai_redis_route.cpp
AmitKaushik7/sonic-sairedis
59e530a485bbe419f30779fe5f7058ff5bbaade8
[ "Apache-2.0" ]
1
2020-12-05T11:28:49.000Z
2020-12-05T11:28:49.000Z
lib/src/sai_redis_route.cpp
AmitKaushik7/sonic-sairedis
59e530a485bbe419f30779fe5f7058ff5bbaade8
[ "Apache-2.0" ]
null
null
null
#include "sai_redis.h" #include "sairedis.h" #include "meta/sai_serialize.h" #include "meta/saiattributelist.h" sai_status_t redis_dummy_create_route_entry( _In_ const sai_route_entry_t *route_entry, _In_ uint32_t attr_count, _In_ const sai_attribute_t *attr_list) { SWSS_LOG_ENTER(); /* * Since we are using validation for each route in bulk operations, we * can't execute actual CREATE, we need to do dummy create and then introduce * internal bulk_create operation that will only touch redis db only once. * So we are returning success here. */ return SAI_STATUS_SUCCESS; } sai_status_t sai_bulk_create_route_entry( _In_ uint32_t object_count, _In_ const sai_route_entry_t *route_entry, _In_ const uint32_t *attr_count, _In_ const sai_attribute_t **attr_list, _In_ sai_bulk_op_error_mode_t mode, _Out_ sai_status_t *object_statuses) { std::lock_guard<std::mutex> lock(g_apimutex); SWSS_LOG_ENTER(); if (object_count < 1) { SWSS_LOG_ERROR("expected at least 1 object to create"); return SAI_STATUS_INVALID_PARAMETER; } if (route_entry == NULL) { SWSS_LOG_ERROR("route_entry is NULL"); return SAI_STATUS_INVALID_PARAMETER; } if (attr_count == NULL) { SWSS_LOG_ERROR("attr_count is NULL"); return SAI_STATUS_INVALID_PARAMETER; } if (attr_list == NULL) { SWSS_LOG_ERROR("attr_list is NULL"); return SAI_STATUS_INVALID_PARAMETER; } switch (mode) { case SAI_BULK_OP_ERROR_MODE_STOP_ON_ERROR: case SAI_BULK_OP_ERROR_MODE_IGNORE_ERROR: // ok break; default: SWSS_LOG_ERROR("invalid bulk operation mode %d", mode); return SAI_STATUS_INVALID_PARAMETER; } if (object_statuses == NULL) { SWSS_LOG_ERROR("object_statuses is NULL"); return SAI_STATUS_INVALID_PARAMETER; } std::vector<std::string> serialized_object_ids; for (uint32_t idx = 0; idx < object_count; ++idx) { /* * At the beginning set all statuses to not executed. */ object_statuses[idx] = SAI_STATUS_NOT_EXECUTED; serialized_object_ids.push_back( sai_serialize_route_entry(route_entry[idx])); } for (uint32_t idx = 0; idx < object_count; ++idx) { sai_status_t status = meta_sai_create_route_entry( &route_entry[idx], attr_count[idx], attr_list[idx], &redis_dummy_create_route_entry); object_statuses[idx] = status; if (status != SAI_STATUS_SUCCESS) { // TODO add attr id and value SWSS_LOG_ERROR("failed on index %u: %s", idx, serialized_object_ids[idx].c_str()); if (mode == SAI_BULK_OP_ERROR_MODE_STOP_ON_ERROR) { SWSS_LOG_NOTICE("stop on error since previous operation failed"); break; } } } /* * TODO: we need to record operation type */ return internal_redis_bulk_generic_create( SAI_OBJECT_TYPE_ROUTE_ENTRY, serialized_object_ids, attr_count, attr_list, object_statuses); } sai_status_t redis_dummy_remove_route_entry( _In_ const sai_route_entry_t *route_entry) { SWSS_LOG_ENTER(); /* * Since we are using validation for each route in bulk operations, we * can't execute actual REMOVE, we need to do dummy remove and then introduce * internal bulk_remove operation that will only touch redis db only once. * So we are returning success here. */ return SAI_STATUS_SUCCESS; } sai_status_t sai_bulk_remove_route_entry( _In_ uint32_t object_count, _In_ const sai_route_entry_t *route_entry, _In_ sai_bulk_op_error_mode_t mode, _Out_ sai_status_t *object_statuses) { std::lock_guard<std::mutex> lock(g_apimutex); SWSS_LOG_ENTER(); if (object_count < 1) { SWSS_LOG_ERROR("expected at least 1 object to create"); return SAI_STATUS_INVALID_PARAMETER; } if (route_entry == NULL) { SWSS_LOG_ERROR("route_entry is NULL"); return SAI_STATUS_INVALID_PARAMETER; } switch (mode) { case SAI_BULK_OP_ERROR_MODE_STOP_ON_ERROR: case SAI_BULK_OP_ERROR_MODE_IGNORE_ERROR: // ok break; default: SWSS_LOG_ERROR("invalid bulk operation mode %d", mode); return SAI_STATUS_INVALID_PARAMETER; } if (object_statuses == NULL) { SWSS_LOG_ERROR("object_statuses is NULL"); return SAI_STATUS_INVALID_PARAMETER; } std::vector<std::string> serialized_object_ids; for (uint32_t idx = 0; idx < object_count; ++idx) { /* * At the beginning set all statuses to not executed. */ object_statuses[idx] = SAI_STATUS_NOT_EXECUTED; serialized_object_ids.push_back( sai_serialize_route_entry(route_entry[idx])); } for (uint32_t idx = 0; idx < object_count; ++idx) { sai_status_t status = meta_sai_remove_route_entry( &route_entry[idx], &redis_dummy_remove_route_entry); object_statuses[idx] = status; if (status != SAI_STATUS_SUCCESS) { // TODO add attr id and value SWSS_LOG_ERROR("failed on index %u: %s", idx, serialized_object_ids[idx].c_str()); if (mode == SAI_BULK_OP_ERROR_MODE_STOP_ON_ERROR) { SWSS_LOG_NOTICE("stop on error since previous operation failed"); break; } } } return internal_redis_bulk_generic_remove(SAI_OBJECT_TYPE_ROUTE_ENTRY, serialized_object_ids, object_statuses); } sai_status_t redis_dummy_set_route_entry( _In_ const sai_route_entry_t* unicast_route_entry, _In_ const sai_attribute_t *attr) { SWSS_LOG_ENTER(); /* * Since we are using validation for each route in bulk operations, we * can't execute actual SET, we need to do dummy set and then introduce * internal bulk_set operation that will only touch redis db only once. * So we are returning success here. */ return SAI_STATUS_SUCCESS; } sai_status_t sai_bulk_set_route_entry_attribute( _In_ uint32_t object_count, _In_ const sai_route_entry_t *route_entry, _In_ const sai_attribute_t *attr_list, _In_ sai_bulk_op_error_mode_t mode, _Out_ sai_status_t *object_statuses) { std::lock_guard<std::mutex> lock(g_apimutex); SWSS_LOG_ENTER(); if (object_count < 1) { SWSS_LOG_ERROR("expected at least 1 object to set"); return SAI_STATUS_INVALID_PARAMETER; } if (route_entry == NULL) { SWSS_LOG_ERROR("route_entry is NULL"); return SAI_STATUS_INVALID_PARAMETER; } if (attr_list == NULL) { SWSS_LOG_ERROR("attr_list is NULL"); return SAI_STATUS_INVALID_PARAMETER; } switch (mode) { case SAI_BULK_OP_ERROR_MODE_STOP_ON_ERROR: case SAI_BULK_OP_ERROR_MODE_IGNORE_ERROR: // ok break; default: SWSS_LOG_ERROR("invalid bulk operation mode %d", mode); return SAI_STATUS_INVALID_PARAMETER; } if (object_statuses == NULL) { SWSS_LOG_ERROR("object_statuses is NULL"); return SAI_STATUS_INVALID_PARAMETER; } std::vector<std::string> serialized_object_ids; for (uint32_t idx = 0; idx < object_count; ++idx) { /* * At the beginning set all statuses to not executed. */ object_statuses[idx] = SAI_STATUS_NOT_EXECUTED; serialized_object_ids.push_back( sai_serialize_route_entry(route_entry[idx])); } for (uint32_t idx = 0; idx < object_count; ++idx) { sai_status_t status = meta_sai_set_route_entry( &route_entry[idx], &attr_list[idx], &redis_dummy_set_route_entry); object_statuses[idx] = status; if (status != SAI_STATUS_SUCCESS) { // TODO add attr id and value SWSS_LOG_ERROR("failed on index %u: %s", idx, serialized_object_ids[idx].c_str()); if (mode == SAI_BULK_OP_ERROR_MODE_STOP_ON_ERROR) { SWSS_LOG_NOTICE("stop on error since previous operation failed"); break; } } } /* * TODO: we need to record operation type */ return internal_redis_bulk_generic_set( SAI_OBJECT_TYPE_ROUTE_ENTRY, serialized_object_ids, attr_list, object_statuses); } sai_status_t sai_bulk_get_route_entry_attribute( _In_ uint32_t object_count, _In_ const sai_route_entry_t *route_entry, _In_ const uint32_t *attr_count, _Inout_ sai_attribute_t **attr_list, _In_ sai_bulk_op_error_mode_t mode, _Out_ sai_status_t *object_statuses) { std::lock_guard<std::mutex> lock(g_apimutex); SWSS_LOG_ENTER(); return SAI_STATUS_NOT_IMPLEMENTED; } REDIS_GENERIC_QUAD_ENTRY(ROUTE_ENTRY,route_entry); const sai_route_api_t redis_route_api = { REDIS_GENERIC_QUAD_API(route_entry) sai_bulk_create_route_entry, sai_bulk_remove_route_entry, sai_bulk_set_route_entry_attribute, sai_bulk_get_route_entry_attribute, };
25.690104
115
0.621997
[ "object", "vector" ]
41236e2469a47f17ca29ed12479fb0ea3ecb435d
6,936
cpp
C++
src/GuiBase/Viewer/Gizmo/RotateGizmo.cpp
hoshiryu/Radium-Engine
2bc3c475a8fb1948dad84d1278bf4d61258f3cda
[ "Apache-2.0" ]
1
2021-02-03T17:47:04.000Z
2021-02-03T17:47:04.000Z
src/GuiBase/Viewer/Gizmo/RotateGizmo.cpp
hoshiryu/Radium-Engine
2bc3c475a8fb1948dad84d1278bf4d61258f3cda
[ "Apache-2.0" ]
null
null
null
src/GuiBase/Viewer/Gizmo/RotateGizmo.cpp
hoshiryu/Radium-Engine
2bc3c475a8fb1948dad84d1278bf4d61258f3cda
[ "Apache-2.0" ]
null
null
null
#include <GuiBase/Viewer/Gizmo/RotateGizmo.hpp> #include <Core/Containers/VectorArray.hpp> #include <Core/Geometry/MeshPrimitives.hpp> #include <Core/Utils/Color.hpp> #include <Engine/Renderer/Camera/Camera.hpp> #include <Engine/Renderer/Mesh/Mesh.hpp> #include <Engine/Renderer/RenderObject/RenderObject.hpp> #include <Engine/Renderer/RenderTechnique/RenderTechnique.hpp> namespace Ra { namespace Gui { RotateGizmo::RotateGizmo( Engine::Component* c, const Core::Transform& worldTo, const Core::Transform& t, Mode mode ) : Gizmo( c, worldTo, t, mode ), m_initialPix( Core::Vector2::Zero() ), m_selectedAxis( -1 ) { constexpr Scalar torusOutRadius = .1_ra; constexpr Scalar torusAspectRatio = .08_ra; // For x,y,z for ( uint i = 0; i < 3; ++i ) { Core::Geometry::TriangleMesh torus = Core::Geometry::makeParametricTorus<32>( torusOutRadius, torusAspectRatio * torusOutRadius ); // Transform the torus from z-axis to axis i. auto& data = torus.verticesWithLock(); for ( auto& v : data ) { v = .5_ra * v; if ( i < 2 ) { std::swap( v[2], v[i] ); } } torus.verticesUnlock(); auto mesh = std::shared_ptr<Engine::Mesh>( new Engine::Mesh( "Gizmo Torus" ) ); mesh->loadGeometry( std::move( torus ) ); auto torusDrawable = new Engine::RenderObject( "Gizmo Torus", m_comp, Engine::RenderObjectType::UI ); auto rt = std::shared_ptr<Engine::RenderTechnique>( makeRenderTechnique( i ) ); torusDrawable->setRenderTechnique( rt ); torusDrawable->setMesh( mesh ); addRenderObject( torusDrawable ); } updateTransform( mode, m_worldTo, m_transform ); } void RotateGizmo::updateTransform( Gizmo::Mode mode, const Core::Transform& worldTo, const Core::Transform& t ) { m_mode = mode; m_worldTo = worldTo; m_transform = t; Core::Transform displayTransform = Core::Transform::Identity(); displayTransform.translate( m_transform.translation() ); if ( m_mode == LOCAL ) { Core::Matrix3 R = m_transform.rotation(); R.col( 0 ).normalize(); R.col( 1 ).normalize(); R.col( 2 ).normalize(); displayTransform.rotate( R ); } for ( auto ro : ros() ) { ro->setLocalTransform( m_worldTo * displayTransform ); } } void RotateGizmo::selectConstraint( int drawableIdx ) { // deselect previously selected axis if ( m_selectedAxis != -1 ) { getControler( m_selectedAxis )->clearState(); m_selectedAxis = -1; } // Return if no component is selected if ( drawableIdx < 0 ) { return; } // update the state of the selected component auto found = std::find_if( ros().cbegin(), ros().cend(), [drawableIdx]( const auto& ro ) { return ro->getIndex() == Core::Utils::Index( drawableIdx ); } ); if ( found != ros().cend() ) { m_selectedAxis = int( std::distance( ros().cbegin(), found ) ); getControler( m_selectedAxis )->setState(); } } Core::Transform RotateGizmo::mouseMove( const Engine::Camera& cam, const Core::Vector2& nextXY, bool stepped, bool /*whole*/ ) { static const Scalar step = Ra::Core::Math::Pi / 10_ra; if ( m_selectedAxis == -1 ) return m_transform; // Decompose the current transform's linear part into rotation and scale Core::Matrix3 rotationMat; Core::Matrix3 scaleMat; m_transform.computeRotationScaling( &rotationMat, &scaleMat ); // Get gizmo center and rotation axis const Core::Vector3 origin = m_transform.translation(); Core::Vector3 rotationAxis = Core::Vector3::Unit( m_selectedAxis ); if ( m_mode == LOCAL ) { rotationAxis = rotationMat * rotationAxis; } rotationAxis.normalize(); const Core::Vector3 originW = m_worldTo * origin; const Core::Vector3 rotationAxisW = m_worldTo * rotationAxis; // Initialize rotation if ( !m_start ) { m_start = true; m_totalAngle = 0; m_initialRot = rotationMat; } // Project the clicked points against the plane defined by the rotation circles. std::vector<Scalar> hits1, hits2; Core::Vector3 originalHit, currentHit; bool hit1 = findPointOnPlane( cam, originW, rotationAxisW, m_initialPix, originalHit, hits1 ); bool hit2 = findPointOnPlane( cam, originW, rotationAxisW, nextXY, currentHit, hits2 ); // Compute the rotation angle Scalar angle; // standard check + guard against precision issues if ( hit1 && hit2 && hits1[0] > .2_ra && hits2[0] > .2_ra ) { // Do the calculations relative to the circle center. originalHit -= originW; currentHit -= originW; // Get the angle between the two vectors with the correct sign // (since we already know our current rotation axis). auto c = originalHit.cross( currentHit ); Scalar d = originalHit.dot( currentHit ); angle = Core::Math::sign( c.dot( rotationAxisW ) ) * std::atan2( c.norm(), d ); } else { // Rotation plane is orthogonal to the image plane Core::Vector2 dir = ( cam.project( originW + rotationAxisW ) - cam.project( originW ) ).normalized(); if ( std::abs( dir( 0 ) ) < 1e-3_ra ) { dir << 1, 0; } else if ( std::abs( dir( 1 ) ) < 1e-3_ra ) { dir << 0, 1; } else { dir = Core::Vector2( dir( 1 ), -dir( 0 ) ); } Scalar diag = std::min( cam.getWidth(), cam.getHeight() ); angle = dir.dot( ( nextXY - m_initialPix ) ) * 8_ra / diag; } if ( std::isnan( angle ) ) { angle = 0_ra; } // Apply rotation Core::Vector2 nextXY_ = nextXY; if ( stepped ) { angle = int( angle / step ) * step; if ( Core::Math::areApproxEqual( angle, 0_ra ) ) { nextXY_ = m_initialPix; } if ( !m_stepped ) { Scalar diff = m_totalAngle - int( m_totalAngle / step ) * step; angle -= diff; } } m_stepped = stepped; m_totalAngle += angle; if ( !Core::Math::areApproxEqual( angle, 0_ra ) ) { auto newRot = Core::AngleAxis( angle, rotationAxis ) * rotationMat; m_transform.fromPositionOrientationScale( origin, newRot, scaleMat.diagonal() ); } m_initialPix = nextXY_; return m_transform; } void RotateGizmo::setInitialState( const Engine::Camera& /*cam*/, const Core::Vector2& initialXY ) { m_initialPix = initialXY; m_start = false; m_stepped = false; } } // namespace Gui } // namespace Ra
36.505263
100
0.589821
[ "mesh", "geometry", "vector", "transform" ]
41240560a2573d4b82af13710c7b341f721a013a
5,785
cxx
C++
src/libxml/xpath.cxx
CyrilOleynik/xmlwrapp
ae8072ca5f1619535b56bea8f36464f5629f7871
[ "BSD-3-Clause" ]
27
2015-07-06T06:42:57.000Z
2022-02-04T01:21:55.000Z
src/libxml/xpath.cxx
CyrilOleynik/xmlwrapp
ae8072ca5f1619535b56bea8f36464f5629f7871
[ "BSD-3-Clause" ]
44
2015-04-02T15:04:08.000Z
2021-07-25T16:15:20.000Z
src/libxml/xpath.cxx
CyrilOleynik/xmlwrapp
ae8072ca5f1619535b56bea8f36464f5629f7871
[ "BSD-3-Clause" ]
8
2015-01-21T04:25:52.000Z
2022-03-26T03:50:41.000Z
/* * Copyright (C) 2011 Jonas Weber (mail@jonasw.de) * 2013 Vaclav Slavik <vslavik@gmail.com> * All Rights Reserved * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name of the Author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ // xmlwrapp includes #include "xmlwrapp/xpath.h" #include "xmlwrapp/document.h" #include "xmlwrapp/node.h" #include "errors_impl.h" #include "node_iterator.h" #include "utility.h" // libxml includes #include <libxml/xmlversion.h> #include <libxml/tree.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #include <map> using namespace xml::impl; namespace { // xmlXPathNodeEval was introduced in 2.9.1, use a helper reimplementation // with older versions: #if LIBXML_VERSION < 20901 xmlXPathObjectPtr xmlXPathNodeEval(xmlNodePtr node, const xmlChar *str, xmlXPathContextPtr ctx) { ctx->node = node; return xmlXPathEval(str, ctx); } #endif // LIBXML_VERSION < 20901 } // anonymous namespace namespace xml { namespace impl { // Function for iterating over a libxml nodeset. // Takes ownership of the path object passed to it class nodeset_next_functor : public impl::iter_advance_functor { public: explicit nodeset_next_functor(xmlXPathObjectPtr pathobj) { // TODO: This isn't efficient, it would be better if node_iterator was // able to use a functor that remembers the index. const int length = pathobj->nodesetval->nodeNr; const xmlNodePtr *table = pathobj->nodesetval->nodeTab; for ( int i = 0; i < length-1; i++ ) m_next[table[i]] = table[i+1]; } virtual xmlNodePtr operator()(xmlNodePtr node) const { const NextNodeMap::const_iterator i = m_next.find(node); if ( i == m_next.end() ) return NULL; else return i->second; } private: typedef std::map<xmlNodePtr, xmlNodePtr> NextNodeMap; NextNodeMap m_next; }; // Need the wrapper with C++ linkage as extern "C" xmlXPathFreeObject itself // can't be used as xml_scoped_ptr template parameter. inline void wrap_xmlXPathFreeObject(xmlXPathObjectPtr ptr) { xmlXPathFreeObject(ptr); } struct xpath_context_impl { explicit xpath_context_impl(const document& doc) : doc_(doc) { ctxt_ = xmlXPathNewContext(static_cast<xmlDocPtr>(doc.get_doc_data_read_only())); } ~xpath_context_impl() { if (ctxt_) xmlXPathFreeContext(ctxt_); } template<typename NodesView> NodesView evaluate(const std::string& expr, node& n, error_handler& on_error) { xmlNodePtr xmlnode = reinterpret_cast<xmlNodePtr>(n.get_node_data()); if ( xmlnode->doc != ctxt_->doc ) { throw xml::exception("node doesn't belong to context's document"); } impl::global_errors_collector err; xml_scoped_ptr<xmlXPathObjectPtr, wrap_xmlXPathFreeObject> nsptr( xmlXPathNodeEval(xmlnode, xml_string(expr), ctxt_)); err.replay(on_error); if ( !nsptr ) return NodesView(); if ( xmlXPathNodeSetIsEmpty(nsptr->nodesetval) ) return NodesView(); return NodesView(nsptr->nodesetval->nodeTab[0], new nodeset_next_functor(nsptr)); } const document& doc_; xmlXPathContextPtr ctxt_; private: // non-copyable xpath_context_impl(const xpath_context_impl&); xpath_context_impl& operator=(const xpath_context_impl&); }; } // namespace impl xpath_context::xpath_context(const document& doc) { pimpl_ = new impl::xpath_context_impl(doc); } xpath_context::~xpath_context() { delete pimpl_; } void xpath_context::register_namespace(const std::string& prefix, const std::string& href) { xmlXPathRegisterNs(pimpl_->ctxt_, xml_string(prefix), xml_string(href)); } const_nodes_view xpath_context::evaluate(const std::string& expr, error_handler& on_error) { return evaluate(expr, const_cast<document&>(pimpl_->doc_).get_root_node(), on_error); } const_nodes_view xpath_context::evaluate(const std::string& expr, const node& n, error_handler& on_error) { return pimpl_->evaluate<const_nodes_view>(expr, const_cast<node&>(n), on_error); } nodes_view xpath_context::evaluate(const std::string& expr, node& n, error_handler& on_error) { return pimpl_->evaluate<nodes_view>(expr, n, on_error); } } // namespace xml
29.666667
105
0.705618
[ "object" ]
4124dc8b59e6df3cf213689aa105e22eec1e10f0
4,269
cpp
C++
cpp/until20/thread/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
2
2021-04-26T16:37:38.000Z
2022-03-15T01:26:19.000Z
cpp/until20/thread/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
null
null
null
cpp/until20/thread/main.cpp
lonelyhentai/workspace
2a996af58d6b9be5d608ed040267398bcf72403b
[ "MIT" ]
1
2022-03-15T01:26:23.000Z
2022-03-15T01:26:23.000Z
#include <iostream> #include <thread> #include <mutex> #include <future> #include <chrono> #include <queue> #include <condition_variable> #include <atomic> #define let const auto int main() { { std::thread t([]() { std::cout << "hello world." << std::endl; }); t.join(); } { int32_t v = 1; let critical_section = [&v](const int32_t change_v) { static std::mutex mtx; std::lock_guard<std::mutex> lock(mtx); v = change_v; }; std::thread t1(critical_section, 2); std::thread t2(critical_section, 3); t1.join(); t2.join(); std::cout << v << std::endl; } { int32_t v = 1; let critical_section = [&v](const int32_t change_v) { static std::mutex mtx; std::unique_lock<std::mutex> lock(mtx); v = change_v; std::cout << v << std::endl; lock.unlock(); lock.lock(); v += 1; std::cout << v << std::endl; }; std::thread t1(critical_section, 2), t2(critical_section, 3); t1.join(); t2.join(); std::cout << v << std::endl; } { std::packaged_task<int()> task([]() { return 7; }); std::future<int> result = task.get_future(); std::thread(std::move(task)).detach(); std::cout << "waiting..."; result.wait(); std::cout << "done!" << std::endl << "future result is" << result.get() << std::endl; } { auto produced_nums = std::queue<int32_t>(); std::mutex mtx; std::condition_variable cv; bool notified = false; bool stop = false; let producer = [&]() { for (int32_t i = 0; ; i++) { std::this_thread::sleep_for(std::chrono::milliseconds(90)); std::unique_lock<std::mutex> lock(mtx); std::cout << "producing " << i << std::endl; produced_nums.push(i); notified = true; if (i >= 10) { stop = true; cv.notify_all(); break; } cv.notify_all(); } std::cout << "producer stop" << std::endl; }; let consumer = [&]() { while(true) { std::unique_lock<std::mutex> lock(mtx); while(!notified) { cv.wait(lock); } lock.unlock(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); lock.lock(); while(!produced_nums.empty()) { std::cout << "consuming " << produced_nums.front() << std::endl; produced_nums.pop(); } notified = false; if (stop) { std::cout << "consumer stop" << std::endl; return; } } }; std::thread p(producer); std::thread cs[2]; for(int i=0;i<2;i++) { cs[i] = std::thread(consumer); } p.join(); for(int i=0;i<2;i++) { cs[i].join(); } } { struct A { float x; int y; long long z; }; std::atomic<A> a; std::cout << std::boolalpha << a.is_lock_free() << std::endl; } { auto counter = std::atomic<int>{ 1 }; auto vt = std::vector<std::thread>{}; for(int32_t i = 0; i < 100; i++) { vt.emplace_back([&]() { counter.fetch_add(1, std::memory_order_relaxed); }); } for(auto &t: vt) { t.join(); } std::cout << "current counter" << counter << std::endl; } { auto ptr = std::atomic<int*>(nullptr); int v; std::thread producer([&]() { int* p = new int(42); v = 1024; ptr.store(p, std::memory_order_release); }); std::thread consumer([&]() { int* p; while (!(p = ptr.load(std::memory_order_consume))); std::cout << "p: " << *p << std::endl; std::cout << "v: " << v << std::endl; }); producer.join(); consumer.join(); } { auto v = std::vector<int>{}; auto flag = std::atomic<int>{ 0 }; std::thread release([&] { v.push_back(42); flag.store(1, std::memory_order_release); }); std::thread acqrel([&]() { int expected = 1; while(!flag.compare_exchange_strong(expected, 2, std::memory_order_acq_rel)) { expected = 1; } }); std::thread acquire([&]() { while (flag.load(std::memory_order_acquire) < 2); std::cout << v.at(0) << std::endl; }); release.join(); acqrel.join(); acquire.join(); } { std::atomic<int> counter = { 0 }; std::vector<std::thread> vt; for(int i = 0; i < 100; ++ i) { vt.emplace_back([&] { counter.fetch_add(1, std::memory_order_seq_cst); }); } for(auto & t: vt) { t.join(); } std::cout << "current counter:" << counter << std::endl; } return 0; }
19.763889
87
0.54884
[ "vector" ]
4130a7ff6301ece7c99d0ea4ec5d11f9168261b0
28,613
cpp
C++
tools/animator/src/animator.cpp
anteins/Blunted2
284a1fb59805914af1ee0dc763ff022fb088a922
[ "Unlicense" ]
null
null
null
tools/animator/src/animator.cpp
anteins/Blunted2
284a1fb59805914af1ee0dc763ff022fb088a922
[ "Unlicense" ]
null
null
null
tools/animator/src/animator.cpp
anteins/Blunted2
284a1fb59805914af1ee0dc763ff022fb088a922
[ "Unlicense" ]
null
null
null
// written by bastiaan konings schuiling 2008 - 2014 // this work is public domain. the code is undocumented, scruffy, untested, and should generally not be used for anything important. // i do not offer support, so don't ask. to be used for inspiration :) #include "animator.hpp" #include "managers/usereventmanager.hpp" #include "managers/resourcemanagerpool.hpp" #include "scene/objects/geometry.hpp" #include "scene/objectfactory.hpp" #include "utils/objectloader.hpp" #include "gui/gui.hpp" #include "blunted.hpp" Animator::Animator(boost::shared_ptr<Scene2D> scene2D, boost::shared_ptr<Scene3D> scene3D, GuiInterface *guiInterface) : scene2D(scene2D), scene3D(scene3D), guiInterface(guiInterface) { camera = static_pointer_cast<Camera>(ObjectFactory::GetInstance().CreateObject("camera", e_ObjectType_Camera)); scene3D->CreateSystemObjects(camera); ObjectLoader loader; objectNode = boost::intrusive_ptr<Node>(new Node("the world!")); objectNode->AddNode(loader.LoadObject(scene3D, "media/objects/studio/studio.object")); // debug pilon boost::intrusive_ptr < Resource<GeometryData> > geometry = ResourceManagerPool::GetInstance().GetManager<GeometryData>(e_ResourceType_GeometryData)->Fetch("media/objects/helpers/green.ase", true); greenPilon = static_pointer_cast<Geometry>(ObjectFactory::GetInstance().CreateObject("greenPilon", e_ObjectType_Geometry)); scene3D->CreateSystemObjects(greenPilon); greenPilon->SetGeometryData(geometry); greenPilon->SetLocalMode(e_LocalMode_Absolute); scene3D->AddObject(greenPilon); geometry = ResourceManagerPool::GetInstance().GetManager<GeometryData>(e_ResourceType_GeometryData)->Fetch("media/objects/helpers/blue.ase", true); bluePilon = static_pointer_cast<Geometry>(ObjectFactory::GetInstance().CreateObject("bluePilon", e_ObjectType_Geometry)); scene3D->CreateSystemObjects(bluePilon); bluePilon->SetGeometryData(geometry); bluePilon->SetLocalMode(e_LocalMode_Absolute); scene3D->AddObject(bluePilon); camera->Init(); Quaternion rot; rot.SetAngleAxis(0.42 * pi, Vector3(1, 0, 0)); camera->SetRotation(rot); camera->SetPosition(Vector3(0, -4, 1)); camera->SetFOV(44); camera->SetCapping(0.2, 120.0); cameraNode = boost::intrusive_ptr<Node>(new Node("camera")); cameraNode->AddObject(camera); objectNode->AddNode(cameraNode); playerNode = loader.LoadObject(scene3D, "./media/objects/players/player.object"); playerNode->SetName("player"); playerNode->SetPosition(Vector3(0, 0, 0)); objectNode->AddNode(playerNode); FillNodeMap(playerNode, nodeMap); ballNode = loader.LoadObject(scene3D, "./media/objects/balls/generic.object"); ballNode->SetName("ball"); objectNode->AddNode(ballNode); currentDir = "./media/animations"; //rot.SetAngleAxis(-0.3 * pi, Vector3(0, 0, 1)); //objectNode->SetRotation(rot); scene3D->AddNode(objectNode); // interface /* GuiButton *button = new GuiButton(scene2D, "testButton", 0, 0, 20, 5, "test!"); guiInterface->AddView(button); button = new GuiButton(scene2D, "testButton2", 0, 5, 20, 10, "ook een test.."); guiInterface->AddView(button); button = new GuiButton(scene2D, "testButton3", 0, 10, 20, 15, "jawohl dat ist"); guiInterface->AddView(button); */ GuiButton *button = new GuiButton(scene2D, "button_load", 0, 0, 20, 5, "Load animation"); guiInterface->AddView(button); button = new GuiButton(scene2D, "button_save", 0, 5, 20, 10, "Save animation"); guiInterface->AddView(button); timeline = new GuiTimeline(scene2D, "motionTimeline", 0, 75, 100, 100); guiInterface->AddView(timeline); //playerNode->PrintTree(); animation = new Animation; timeline->AddPart("player", "player"); managedNodes.insert(std::pair < std::string, boost::intrusive_ptr<Node> >("player", playerNode)); Vector3 position = playerNode->GetPosition(); // initial position animation->SetKeyFrame("player", 0, Quaternion(QUATERNION_IDENTITY), position); AddNodeToTimeline(playerNode, timeline); boost::shared_ptr<FootballAnimationExtension> extension(new FootballAnimationExtension(animation)); animation->AddExtension("football", extension); timeline->AddPart("ball", "ball"); //animation->GetExtension("football")->SetKeyFrame(0, Vector3(0), Vector3(0), 1.0); timelineIndex = new GuiCaption(scene2D, "caption_timelineIndex", 90, 0, 100, 10, "0/0"); guiInterface->AddView(timelineIndex); debugValues1 = new GuiCaption(scene2D, "caption_debugValues1", 80, 10, 100, 15, ""); guiInterface->AddView(debugValues1); debugValues2 = new GuiCaption(scene2D, "caption_debugValues2", 80, 15, 100, 20, ""); guiInterface->AddView(debugValues2); debugValues3 = new GuiCaption(scene2D, "caption_debugValues3", 80, 20, 100, 25, ""); guiInterface->AddView(debugValues3); // ๅฝ“ๅ‰ๅŠจ็”ปๅๅญ— caption_animName = new GuiCaption(scene2D, "caption_animName", 0, 0, 100, 5, ""); guiInterface->AddView(caption_animName); studioRot = 0; play = false; currentPlayFrame = 0; PopulateTimeline(animation, timeline); currentFile = "untitled.anim"; caption_animName->Set(currentFile); counter = 0; } Animator::~Animator() { delete animation; scene3D->DeleteObject(greenPilon); scene3D->DeleteObject(bluePilon); scene3D->DeleteNode(objectNode); camera.reset(); objectNode.reset(); playerNode.reset(); scene2D.reset(); scene3D.reset(); } Vector3 GetFrontOfFootOffset(float velocity) { Vector3 ffo = Vector3(0, -0.2, 0); // basic ffo ffo += Vector3(0, -velocity / 35.0, 0); return ffo; } void Animator::FillNodeMap(boost::intrusive_ptr<Node> targetNode, std::map < const std::string, boost::intrusive_ptr<Node> > &nodeMap) { nodeMap.insert(std::pair < std::string, boost::intrusive_ptr<Node> >(targetNode->GetName(), targetNode)); std::vector < boost::intrusive_ptr<Node> > gatherNodes; targetNode->GetNodes(gatherNodes); for (int i = 0; i < (signed int)gatherNodes.size(); i++) { FillNodeMap(gatherNodes.at(i), nodeMap); } } void Animator::AddNodeToTimeline(boost::intrusive_ptr<Node> node, GuiTimeline *timeline) { std::vector < boost::intrusive_ptr<Node> > nodes; node->GetNodes(nodes); for (int i = 0; i < (signed int)nodes.size(); i++) { timeline->AddPart(nodes.at(i)->GetName(), nodes.at(i)->GetName()); managedNodes.insert(std::pair < std::string, boost::intrusive_ptr<Node> >(nodes.at(i)->GetName(), nodes.at(i))); Vector3 position = nodes.at(i)->GetPosition(); // initial position Vector3 angles; // initial angles if (nodes.at(i)->GetName() == "left_shoulder") angles.Set(0.1, -0.25, -0.15); if (nodes.at(i)->GetName() == "right_shoulder") angles.Set(0.1, 0.25, 0.15); if (nodes.at(i)->GetName() == "left_elbow") angles.Set(-0.2, 0.0, 0.0); if (nodes.at(i)->GetName() == "right_elbow") angles.Set(-0.2, -0.0, 0.0); if (nodes.at(i)->GetName() == "left_thigh") angles.Set(-0.06, -0.04, 0); if (nodes.at(i)->GetName() == "right_thigh") angles.Set(-0.06, 0.04, 0); if (nodes.at(i)->GetName() == "left_knee") angles.Set(0.18, 0, 0); if (nodes.at(i)->GetName() == "right_knee") angles.Set(0.18, 0, 0); if (nodes.at(i)->GetName() == "left_ankle") angles.Set(-0.12, 0, 0); if (nodes.at(i)->GetName() == "right_ankle") angles.Set(-0.12, 0, 0); Quaternion rotX, rotY, rotZ, quat; rotX.SetAngleAxis(angles.coords[0], Vector3(1, 0, 0)); rotY.SetAngleAxis(angles.coords[1], Vector3(0, 1, 0)); rotZ.SetAngleAxis(angles.coords[2], Vector3(0, 0, 1)); quat = rotX * rotY * rotZ; animation->SetKeyFrame(nodes.at(i)->GetName(), 0, quat, position); AddNodeToTimeline(nodes.at(i), timeline); } } void Animator::PopulateTimeline(Animation *animation, GuiTimeline *timeline) { std::vector<NodeAnimation*> &nodeAnimations = animation->GetNodeAnimations(); // iterate nodes int animSize = nodeAnimations.size(); for (int i = 0; i < animSize; i++) { NodeAnimation *nodeAnimation = nodeAnimations.at(i); std::map<int, KeyFrame>::iterator animIter = nodeAnimation->animation.begin(); while (animIter != nodeAnimation->animation.end()) { timeline->EnableKeyFrame(nodeAnimations.at(i)->nodeName, animIter->first); animIter++; } } int i = animSize; std::map < std::string, boost::shared_ptr<AnimationExtension> >::iterator extensionIter = animation->GetExtensions().begin(); while (extensionIter != animation->GetExtensions().end()) { //extensionIter->second->PopulateTimeline(i, timeline); //void FootballAnimationExtension::PopulateTimeline(int part, GuiTimeline *timeline) { std::map<int, FootballKeyFrame>::iterator animIter = boost::static_pointer_cast<FootballAnimationExtension>(extensionIter->second)->GetAnimation().begin(); while (animIter != boost::static_pointer_cast<FootballAnimationExtension>(extensionIter->second)->GetAnimation().end()) { timeline->EnableKeyFrame(i, animIter->first); animIter++; } extensionIter++; i++; } timeline->Redraw(); } //! // adds touches around main touch // debug: adds touches around main touch void AddExtraTouches(Animation* animation, boost::intrusive_ptr<Node> playerNode, const std::list < boost::intrusive_ptr<Object> > &bodyParts, const std::map < const std::string, boost::intrusive_ptr<Node> > &nodeMap) { Vector3 animBallPos; int animTouchFrame; bool isTouch = boost::static_pointer_cast<FootballAnimationExtension>(animation->GetExtension("football"))->GetFirstTouch(animBallPos, animTouchFrame); if (isTouch) { // find out what body part the balltouchpos is closest to animation->Apply(nodeMap, animTouchFrame, 0, false); boost::intrusive_ptr<Object> closestBodyPart = (*bodyParts.begin()); float closestDistance = 100; Vector3 toBallVector = Vector3(0); std::list < boost::intrusive_ptr<Object> > ::const_iterator iter = bodyParts.begin(); while (iter != bodyParts.end()) { float distance = (animBallPos - (*iter)->GetDerivedPosition()).GetLength(); if (distance < closestDistance) { closestDistance = distance; closestBodyPart = *iter; toBallVector = animBallPos - (*iter)->GetDerivedPosition(); } iter++; } //printf("closest: %s\n", closestBodyPart->GetName().c_str()); float heightCheat = 1.0; if (animBallPos.coords[2] > 0.8) heightCheat = 1.6; int range_pre = int(round(2.f * heightCheat)); int range_post = int(round(4.f * heightCheat)); if (animation->GetVariable("type") == "trap" || animation->GetVariable("type") == "interfere") { range_pre = int(round(4.f * heightCheat)); range_post = int(round(4.f * heightCheat)); } else if (animation->GetVariable("type") == "deflect") { range_pre = int(round(4.f * heightCheat)); range_post = int(round(6.f * heightCheat)); } else if (animation->GetVariable("type") == "sliding") { range_pre = int(round(6.f * heightCheat)); range_post = int(round(6.f * heightCheat)); } else if (animation->GetVariable("type") == "ballcontrol") { range_pre = int(round(2.f * heightCheat)); range_post = int(round(6.f * heightCheat)); } //range_pre *= 0.6; int frameOffset = 4; // correct for animation smoothing: player limbs always seem to be late at ballposition otherwise if (animTouchFrame + frameOffset - range_pre <= animation->GetFrameCount()) { boost::static_pointer_cast<FootballAnimationExtension>(animation->GetExtension("football"))->DeleteKeyFrame(animTouchFrame); } for (int i = animTouchFrame - range_pre; i < animTouchFrame + range_post + 1; i += 2) { if (i >= 0 && /*i != animTouchFrame &&*/ i < animation->GetFrameCount() - frameOffset - 1) { // set animation to this frame animation->Apply(nodeMap, i, 0, false); // find new ball position, based on the closest body part's position in this frame Vector3 position = closestBodyPart->GetDerivedPosition() + toBallVector; Vector3 origBodyPos = nodeMap.find("player")->second->GetDerivedPosition(); animation->Apply(nodeMap, i + frameOffset, 0, false); Vector3 futureBodyPos = nodeMap.find("player")->second->GetDerivedPosition(); //origBodyPos.Print(); Vector3 diff2D = (futureBodyPos - origBodyPos).Get2D(); Quaternion orientation; //Vector3 position = animBallPos + (animBallPos.Get2D() * (-animTouchFrame + i) * 0.05); boost::static_pointer_cast<FootballAnimationExtension>(animation->GetExtension("football"))->SetKeyFrame(i + frameOffset, orientation, position + diff2D, 0); } } } } void Animator::GetPhase() { } void Animator::ProcessPhase() { std::string partName; int currentFrame; bool isKeyFrame; timeline->GetLocation(partName, currentFrame, isKeyFrame); //test->SetPosition(Vector3(1, -0.01, 0.47)); bool newMessage = true; while (newMessage) { GuiSignal signal = guiInterface->signalQueue.GetMessage(newMessage); if (newMessage) { printf("Get Message: %s\n", signal.sender->GetName().c_str()); if (signal.sender->GetName() == "button_save" && signal.key == SDLK_RETURN) { saveDialog = new GuiFileDialog(scene2D, "dialog_save", 30, 10, 70, 90, currentDir, currentFile.substr(currentFile.find_last_of("/") + 1, std::string::npos)); guiInterface->AddView(saveDialog); guiInterface->SetFocussedView(saveDialog); } else if (signal.sender->GetName() == "dialog_save_CancelButton" && signal.key == SDLK_RETURN) { guiInterface->DeleteView(saveDialog); saveDialog = 0; } else if (signal.sender->GetName() == "dialog_save_OkayButton" && signal.key == SDLK_RETURN) { currentFile = saveDialog->GetFilename(); currentDir = saveDialog->GetDirectory(); //printf("loading %s\n", currentFile.c_str()); animation->Save(currentFile); guiInterface->DeleteView(saveDialog); saveDialog = 0; } else if (signal.sender->GetName() == "button_load" && signal.key == SDLK_RETURN) { loadDialog = new GuiFileDialog(scene2D, "dialog_load", 30, 10, 70, 90, currentDir, currentFile.substr(currentFile.find_last_of("/") + 1, std::string::npos)); guiInterface->AddView(loadDialog); guiInterface->SetFocussedView(loadDialog); } else if (signal.sender->GetName() == "dialog_load_CancelButton" && signal.key == SDLK_RETURN) { guiInterface->DeleteView(loadDialog); loadDialog = 0; } else if (signal.sender->GetName() == "dialog_load_OkayButton" && signal.key == SDLK_RETURN) { currentFile = loadDialog->GetFilename(); currentDir = loadDialog->GetDirectory(); //printf("loading %s\n", currentFile.c_str()); animation->Reset(); delete animation; animation = new Animation; boost::shared_ptr<FootballAnimationExtension> extension(new FootballAnimationExtension(animation)); animation->AddExtension("football", extension); animation->Load(currentFile); //animation->ConvertToStartFacingForwardIfIdle(); //animation->ConvertAngles(); //animation->Invert(); /* // debug std::list < boost::intrusive_ptr<Object> > bodyParts; playerNode->GetObjects(e_ObjectType_Geometry, bodyParts, true); std::map < const std::string, boost::intrusive_ptr<Node> > nodeMap; FillNodeMap(playerNode, nodeMap); AddExtraTouches(animation, playerNode, bodyParts, nodeMap); //! */ timeline->ClearKeys(); PopulateTimeline(animation, timeline); //animation->Hax(); printf("angle: %f\n", animation->GetOutgoingAngle()); printf("body angle: %f\n", animation->GetOutgoingBodyAngle()); float velocity = animation->GetIncomingMovement().GetLength(); std::string mode; if (velocity < 1.8) mode = "idle"; else if (velocity >= 1.8 && velocity < 4.2) mode = "dribble"; else if (velocity >= 4.2 && velocity < 6.0) mode = "walk"; else if (velocity >= 6.0) mode = "sprint"; printf("%s - ", mode.c_str()); velocity = animation->GetOutgoingMovement().GetLength(); if (velocity < 1.8) mode = "idle"; else if (velocity >= 1.8 && velocity < 4.2) mode = "dribble"; else if (velocity >= 4.2 && velocity < 6.0) mode = "walk"; else if (velocity >= 6.0) mode = "sprint"; printf("%s\n", mode.c_str()); guiInterface->DeleteView(loadDialog); loadDialog = 0; } else if (signal.sender->GetName() == "motionTimeline") { if (signal.key == SDLK_INSERT) { // insert new frame (move all keyframes from this frame on to the 'right') printf("shifting..\n"); animation->Shift(currentFrame, +1); timeline->ClearKeys(); PopulateTimeline(animation, timeline); } if (signal.key == SDLK_BACKSPACE) { // insert new frame (move all keyframes from this frame on to the 'left', erasing current keyframes) printf("shifting..\n"); animation->Shift(currentFrame, -1); timeline->ClearKeys(); PopulateTimeline(animation, timeline); } // is this a normal node? if (managedNodes.find(partName) != managedNodes.end()) { if (signal.key == SDLK_DELETE && isKeyFrame && currentFrame != 0) { static_cast<GuiTimeline*>(signal.sender)->ToggleKeyFrame(); animation->DeleteKeyFrame(partName, currentFrame); } if (signal.key == SDLK_F4) { animation->Hax(); } if (signal.key == SDLK_q || signal.key == SDLK_w || signal.key == SDLK_a || signal.key == SDLK_s || signal.key == SDLK_z || signal.key == SDLK_x || signal.key == SDLK_e || signal.key == SDLK_d || signal.key == SDLK_c || signal.key == SDLK_i || signal.key == SDLK_k || signal.key == SDLK_j || signal.key == SDLK_l || signal.key == SDLK_u || signal.key == SDLK_o || signal.key == SDLK_0) { Quaternion orientation; Vector3 rotationAngles, position; int adaptedCurrentFrame = currentFrame; if (adaptedCurrentFrame > animation->GetFrameCount() - 1) adaptedCurrentFrame = animation->GetFrameCount() - 1; animation->GetKeyFrame(partName, adaptedCurrentFrame, orientation, position); orientation.GetAngles(rotationAngles.coords[0], rotationAngles.coords[1], rotationAngles.coords[2]); if (!isKeyFrame) { static_cast<GuiTimeline*>(signal.sender)->ToggleKeyFrame(); //position = managedNodes.find(partName)->second->GetPosition(); } float rotStep = pi * 0.01; if (signal.key == SDLK_q) rotationAngles.coords[0] -= rotStep; if (signal.key == SDLK_e) rotationAngles.coords[0] += rotStep; if (signal.key == SDLK_w) rotationAngles.coords[0] = 0; if (signal.key == SDLK_a) rotationAngles.coords[1] -= rotStep; if (signal.key == SDLK_d) rotationAngles.coords[1] += rotStep; if (signal.key == SDLK_s) rotationAngles.coords[1] = 0; if (signal.key == SDLK_z) rotationAngles.coords[2] -= rotStep; if (signal.key == SDLK_c) rotationAngles.coords[2] += rotStep; if (signal.key == SDLK_x) rotationAngles.coords[2] = 0; if (signal.key == SDLK_j) position.coords[0] += 0.02; if (signal.key == SDLK_l) position.coords[0] -= 0.02; if (signal.key == SDLK_i) position.coords[1] -= 0.02; if (signal.key == SDLK_k) position.coords[1] += 0.02; if (signal.key == SDLK_u) position.coords[2] -= 0.01; if (signal.key == SDLK_o) position.coords[2] += 0.01; if (signal.key == SDLK_0) position.Set(0, 0, 0); Quaternion rotX, rotY, rotZ, quat; rotX.SetAngleAxis(rotationAngles.coords[0], Vector3(1, 0, 0)); rotY.SetAngleAxis(rotationAngles.coords[1], Vector3(0, 1, 0)); rotZ.SetAngleAxis(rotationAngles.coords[2], Vector3(0, 0, 1)); quat = rotX * rotY * rotZ; animation->SetKeyFrame(partName, currentFrame, quat, position); float velocity = animation->GetIncomingMovement().GetLength(); std::string mode; if (velocity < 1.8) mode = "idle"; else if (velocity >= 1.8 && velocity < 4.2) mode = "dribble"; else if (velocity >= 4.2 && velocity < 6.0) mode = "walk"; else if (velocity >= 6.0) mode = "sprint"; float diff = 0; if (mode == "idle") diff = velocity - idleVelocity; if (mode == "dribble") diff = velocity - dribbleVelocity; if (mode == "walk") diff = velocity - walkVelocity; if (mode == "sprint") diff = velocity - sprintVelocity; printf("%s (%f) - ", mode.c_str(), diff); velocity = animation->GetOutgoingMovement().GetLength(); if (velocity < 1.8) mode = "idle"; else if (velocity >= 1.8 && velocity < 4.2) mode = "dribble"; else if (velocity >= 4.2 && velocity < 6.0) mode = "walk"; else if (velocity >= 6.0) mode = "sprint"; if (mode == "idle") diff = velocity - idleVelocity; if (mode == "dribble") diff = velocity - dribbleVelocity; if (mode == "walk") diff = velocity - walkVelocity; if (mode == "sprint") diff = velocity - sprintVelocity; printf("%s (%f)\n", mode.c_str(), diff); //animation->GetOutgoingDirection().Print(); } // then what is it? a football extension maybe? } else { if (signal.key == SDLK_DELETE && isKeyFrame) { static_cast<GuiTimeline*>(signal.sender)->ToggleKeyFrame(); animation->GetExtension("football")->DeleteKeyFrame(currentFrame); } if (signal.key == SDLK_i || signal.key == SDLK_k || signal.key == SDLK_j || signal.key == SDLK_l || signal.key == SDLK_u || signal.key == SDLK_o || signal.key == SDLK_0) { Quaternion tmp; Vector3 position; float power; animation->GetExtension("football")->GetKeyFrame(currentFrame, tmp, position, power); if (!isKeyFrame) { static_cast<GuiTimeline*>(signal.sender)->ToggleKeyFrame(); //position = managedNodes.find(partName)->second->GetPosition(); position.coords[2] = 0.11; } float rotStep = pi * 0.01; if (signal.key == SDLK_j) position.coords[0] += 0.01; if (signal.key == SDLK_l) position.coords[0] -= 0.01; if (signal.key == SDLK_i) position.coords[1] -= 0.01; if (signal.key == SDLK_k) position.coords[1] += 0.01; if (signal.key == SDLK_u) position.coords[2] -= 0.01; if (signal.key == SDLK_o) position.coords[2] += 0.01; if (signal.key == SDLK_0) position.Set(0, 0, 0.11); animation->GetExtension("football")->SetKeyFrame(currentFrame, tmp, position, power); } } if (signal.key == SDLK_SPACE) { if (!play) play = true; else play = false; } } else if (signal.sender->GetName() == "dialog_load" && signal.key == SDLK_ESCAPE) { currentFile = loadDialog->GetFilename(); currentDir = loadDialog->GetDirectory(); //printf("loading %s\n", currentFile.c_str()); animation->Reset(); delete animation; animation = new Animation; boost::shared_ptr<FootballAnimationExtension> extension(new FootballAnimationExtension(animation)); animation->AddExtension("football", extension); animation->Load(currentFile); //animation->ConvertToStartFacingForwardIfIdle(); //animation->ConvertAngles(); //animation->Invert(); /* // debug std::list < boost::intrusive_ptr<Object> > bodyParts; playerNode->GetObjects(e_ObjectType_Geometry, bodyParts, true); std::map < const std::string, boost::intrusive_ptr<Node> > nodeMap; FillNodeMap(playerNode, nodeMap); AddExtraTouches(animation, playerNode, bodyParts, nodeMap); //! */ timeline->ClearKeys(); PopulateTimeline(animation, timeline); //animation->Hax(); printf("angle: %f\n", animation->GetOutgoingAngle()); printf("body angle: %f\n", animation->GetOutgoingBodyAngle()); float velocity = animation->GetIncomingMovement().GetLength(); std::string mode; if (velocity < 1.8) mode = "idle"; else if (velocity >= 1.8 && velocity < 4.2) mode = "dribble"; else if (velocity >= 4.2 && velocity < 6.0) mode = "walk"; else if (velocity >= 6.0) mode = "sprint"; printf("%s - ", mode.c_str()); velocity = animation->GetOutgoingMovement().GetLength(); if (velocity < 1.8) mode = "idle"; else if (velocity >= 1.8 && velocity < 4.2) mode = "dribble"; else if (velocity >= 4.2 && velocity < 6.0) mode = "walk"; else if (velocity >= 6.0) mode = "sprint"; printf("%s\n", mode.c_str()); guiInterface->DeleteView(loadDialog); loadDialog = 0; } } } Quaternion orientation; Vector3 position; float power; if (managedNodes.find(partName) != managedNodes.end()) { animation->GetKeyFrame(partName, currentFrame, orientation, position); if (partName != "player") position = managedNodes.find(partName)->second->GetDerivedPosition(); } else { animation->GetExtension("football")->GetKeyFrame(currentFrame, orientation, position, power); } Vector3 rotationAngles; orientation.GetAngles(rotationAngles.coords[0], rotationAngles.coords[1], rotationAngles.coords[2]); debugValues1->Set("rot: " + int_to_str(360 * rotationAngles.coords[0] / (pi * 2)) + ", " + int_to_str(360 * rotationAngles.coords[1] / (pi * 2)) + ", " + int_to_str(360 * rotationAngles.coords[2] / (pi * 2))); debugValues2->Set("pos: " + real_to_str(position.coords[0]).substr(0, 5) + ", " + real_to_str(position.coords[1]).substr(0, 5) + ", " + real_to_str(position.coords[2]).substr(0, 5)); debugValues3->Set("outgoing rot: " + int_to_str(int(round(animation->GetOutgoingAngle() / (2 * pi) * 360)))); caption_animName->Set(currentFile); Vector3 ballPosition; Quaternion tmp; if (!play) { int adaptedCurrentFrame = currentFrame; if (adaptedCurrentFrame > animation->GetFrameCount() - 1) adaptedCurrentFrame = animation->GetFrameCount() - 1; animation->Apply(nodeMap, adaptedCurrentFrame, 0, false, 1.0f, Vector(0), 0); timelineIndex->Set(int_to_str(currentFrame) + "/" + int_to_str(timeline->GetFrameCount())); animation->GetExtension("football")->GetKeyFrame(currentFrame, tmp, ballPosition, power); //counter = 0; } else { animation->Apply(nodeMap, currentPlayFrame, 0, false); /*if (is_odd(counter)) */currentPlayFrame++; counter++; int frameCount = timeline->GetFrameCount(); if (currentPlayFrame >= frameCount - 1) currentPlayFrame = 0; timelineIndex->Set(int_to_str(currentPlayFrame) + "/" + int_to_str(timeline->GetFrameCount())); animation->GetExtension("football")->GetKeyFrame(currentPlayFrame, tmp, ballPosition, power); } float velocity = animation->GetIncomingVelocity(); greenPilon->SetPosition(GetFrontOfFootOffset(velocity)); ballNode->GetObject("genericball")->SetPosition(ballPosition); if (ballPosition != Vector3(0)) { Vector3 ballDir; if (animation->GetVariable("incomingballdirection") != "") ballDir = GetVectorFromString(animation->GetVariable("incomingballdirection")) * -1.0; if (ballDir.GetLength() == 0) if (animation->GetVariable("balldirection") != "") ballDir = GetVectorFromString(animation->GetVariable("balldirection")); if (ballDir.GetLength() != 0) bluePilon->SetPosition(ballPosition + ballDir); } // ้ผ ๆ ‡ๆ—‹่ฝฌ้•œๅคด // studioRot += UserEventManager::GetInstance().GetMouseRelativePos().coords[0] / 100.0; studioRot = 0.5f; // printf("studioRot: %f\n", studioRot); Quaternion rot; rot.SetAngleAxis(studioRot, Vector3(0, 0, 1)); cameraNode->SetRotation(rot); cameraNode->SetPosition(playerNode->GetPosition().Get2D() + Vector3(0, 0, 0.65)); // camera->SetPosition(Vector3(0, -3.4, 1.8 - 0.74) + playerNode->GetPosition()); } void Animator::PutPhase() { }
41.408104
219
0.645056
[ "geometry", "object", "vector" ]
4132615e8abdd63c3006b38f02d66a86fd601723
6,332
cpp
C++
cdb/src/v20170320/model/DescribeDBInstanceConfigResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
cdb/src/v20170320/model/DescribeDBInstanceConfigResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
cdb/src/v20170320/model/DescribeDBInstanceConfigResponse.cpp
sinjoywong/tencentcloud-sdk-cpp
1b931d20956a90b15a6720f924e5c69f8786f9f4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/cdb/v20170320/model/DescribeDBInstanceConfigResponse.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Cdb::V20170320::Model; using namespace std; DescribeDBInstanceConfigResponse::DescribeDBInstanceConfigResponse() : m_protectModeHasBeenSet(false), m_deployModeHasBeenSet(false), m_zoneHasBeenSet(false), m_slaveConfigHasBeenSet(false), m_backupConfigHasBeenSet(false), m_switchedHasBeenSet(false) { } CoreInternalOutcome DescribeDBInstanceConfigResponse::Deserialize(const string &payload) { rapidjson::Document d; d.Parse(payload.c_str()); if (d.HasParseError() || !d.IsObject()) { return CoreInternalOutcome(Error("response not json format")); } if (!d.HasMember("Response") || !d["Response"].IsObject()) { return CoreInternalOutcome(Error("response `Response` is null or not object")); } rapidjson::Value &rsp = d["Response"]; if (!rsp.HasMember("RequestId") || !rsp["RequestId"].IsString()) { return CoreInternalOutcome(Error("response `Response.RequestId` is null or not string")); } string requestId(rsp["RequestId"].GetString()); SetRequestId(requestId); if (rsp.HasMember("Error")) { if (!rsp["Error"].IsObject() || !rsp["Error"].HasMember("Code") || !rsp["Error"]["Code"].IsString() || !rsp["Error"].HasMember("Message") || !rsp["Error"]["Message"].IsString()) { return CoreInternalOutcome(Error("response `Response.Error` format error").SetRequestId(requestId)); } string errorCode(rsp["Error"]["Code"].GetString()); string errorMsg(rsp["Error"]["Message"].GetString()); return CoreInternalOutcome(Error(errorCode, errorMsg).SetRequestId(requestId)); } if (rsp.HasMember("ProtectMode") && !rsp["ProtectMode"].IsNull()) { if (!rsp["ProtectMode"].IsInt64()) { return CoreInternalOutcome(Error("response `ProtectMode` IsInt64=false incorrectly").SetRequestId(requestId)); } m_protectMode = rsp["ProtectMode"].GetInt64(); m_protectModeHasBeenSet = true; } if (rsp.HasMember("DeployMode") && !rsp["DeployMode"].IsNull()) { if (!rsp["DeployMode"].IsInt64()) { return CoreInternalOutcome(Error("response `DeployMode` IsInt64=false incorrectly").SetRequestId(requestId)); } m_deployMode = rsp["DeployMode"].GetInt64(); m_deployModeHasBeenSet = true; } if (rsp.HasMember("Zone") && !rsp["Zone"].IsNull()) { if (!rsp["Zone"].IsString()) { return CoreInternalOutcome(Error("response `Zone` IsString=false incorrectly").SetRequestId(requestId)); } m_zone = string(rsp["Zone"].GetString()); m_zoneHasBeenSet = true; } if (rsp.HasMember("SlaveConfig") && !rsp["SlaveConfig"].IsNull()) { if (!rsp["SlaveConfig"].IsObject()) { return CoreInternalOutcome(Error("response `SlaveConfig` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_slaveConfig.Deserialize(rsp["SlaveConfig"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_slaveConfigHasBeenSet = true; } if (rsp.HasMember("BackupConfig") && !rsp["BackupConfig"].IsNull()) { if (!rsp["BackupConfig"].IsObject()) { return CoreInternalOutcome(Error("response `BackupConfig` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_backupConfig.Deserialize(rsp["BackupConfig"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_backupConfigHasBeenSet = true; } if (rsp.HasMember("Switched") && !rsp["Switched"].IsNull()) { if (!rsp["Switched"].IsBool()) { return CoreInternalOutcome(Error("response `Switched` IsBool=false incorrectly").SetRequestId(requestId)); } m_switched = rsp["Switched"].GetBool(); m_switchedHasBeenSet = true; } return CoreInternalOutcome(true); } int64_t DescribeDBInstanceConfigResponse::GetProtectMode() const { return m_protectMode; } bool DescribeDBInstanceConfigResponse::ProtectModeHasBeenSet() const { return m_protectModeHasBeenSet; } int64_t DescribeDBInstanceConfigResponse::GetDeployMode() const { return m_deployMode; } bool DescribeDBInstanceConfigResponse::DeployModeHasBeenSet() const { return m_deployModeHasBeenSet; } string DescribeDBInstanceConfigResponse::GetZone() const { return m_zone; } bool DescribeDBInstanceConfigResponse::ZoneHasBeenSet() const { return m_zoneHasBeenSet; } SlaveConfig DescribeDBInstanceConfigResponse::GetSlaveConfig() const { return m_slaveConfig; } bool DescribeDBInstanceConfigResponse::SlaveConfigHasBeenSet() const { return m_slaveConfigHasBeenSet; } BackupConfig DescribeDBInstanceConfigResponse::GetBackupConfig() const { return m_backupConfig; } bool DescribeDBInstanceConfigResponse::BackupConfigHasBeenSet() const { return m_backupConfigHasBeenSet; } bool DescribeDBInstanceConfigResponse::GetSwitched() const { return m_switched; } bool DescribeDBInstanceConfigResponse::SwitchedHasBeenSet() const { return m_switchedHasBeenSet; }
30.152381
122
0.67909
[ "object", "model" ]
413449dc87b490672a9d046a3da2b7f1d92924d9
18,968
cpp
C++
src/surfrecon.cpp
gnayuy/surfrecon
9fee6d905ed80fc991a924332da09adf7a32c672
[ "BSD-3-Clause" ]
2
2017-04-20T04:40:33.000Z
2021-02-03T07:30:01.000Z
src/surfrecon.cpp
gnayuy/surfrecon
9fee6d905ed80fc991a924332da09adf7a32c672
[ "BSD-3-Clause" ]
1
2016-08-02T21:10:52.000Z
2022-03-28T08:28:54.000Z
src/surfrecon.cpp
gnayuy/surfrecon
9fee6d905ed80fc991a924332da09adf7a32c672
[ "BSD-3-Clause" ]
1
2017-05-22T01:16:34.000Z
2017-05-22T01:16:34.000Z
// surfrecon: to reconstruct a surface from a point cloud and voxelization // Yang Yu (gnayuy@gmail.com) // #include "surfrecon.h" // Surf::Surf() { } Surf::~Surf() { } void Surf::setPoints(VoxelSet pointcloud) { points.clear(); for(int i=0; i<pointcloud.size(); i++) { points.push_back(Point(pointcloud[i].x, pointcloud[i].y, pointcloud[i].z)); } } /* * as for A=B assigning the value of a point to another */ void Surf::assign(Vertex *to, Vertex *from) { to->x = from->x; to->y = from->y; to->z = from->z; } /* * A+B when B is implicitly a Vector3d ({x,y,z}) */ void Surf::addTo(Vertex *result, Vertex *v, double x, double y, double z) { result->x = v->x + x; result->y = v->y + y; result->z = v->z + z; } /* * A-B when B is implicitly a Vector3d ({x,y,z}) */ void Surf::subtractFrom(Vertex *result, Vertex *v, double x, double y, double z) { result->x = v->x - x; result->y = v->y - y; result->z = v->z - z; } /* * A+B */ void Surf::add(Vertex *result, Vertex *v1, Vertex *v2) { addTo(result, v1, v2->x, v2->y, v2->z); } /* * A-B */ void Surf::subtract(Vertex *result, Vertex *v1, Vertex *v2) { subtractFrom(result, v1, v2->x, v2->y, v2->z); } /* * C={x,y,z}=AxB| x=u2v3-u3v2, y=u3v1-u1v3, z=u1v2-u2v1 */ void Surf::crossProduct(Vertex *result, Vertex *v1, Vertex *v2) { result->x = v1->y*v2->z - v2->y*v1->z; result->y = v2->x*v1->z - v1->x*v2->z; result->z = v1->x*v2->y - v1->y*v2->x; } /* * C=A.B=u1v1+u2v2+u3v3 */ double Surf::dotProduct(Vertex *v1, Vertex *v2) { return v1->x*v2->x + v1->y*v2->y + v1->z*v2->z; } /* * scaling a Vector3d or Point3d */ void Surf::product(Vertex *result, double s, Vertex *v) { result->x = s*v->x; result->y = s*v->y; result->z = s*v->z; } /* * Euclidean distance(i.e. Sqrt(x2+y2+z2)) */ double Surf::distance(Vertex *v1, Vertex *v2) { return sqrt((v1->x-v2->x)*(v1->x-v2->x) + (v1->y-v2->y)*(v1->y-v2->y) + (v1->z-v2->z)*(v1->z-v2->z)); } /* * the bounding box is defined as a tuple(of Point3d,Point3d) respectively minimum and * maximum corners of the boundingbox. Haveing min corner means having min values for X, * Y and Z intervals and having max corner means having max values for X,Y and Z intervals. * This module finds the min and max values in x, y and z */ void Surf::getRBoundingBox(Vertex *vertices, unsigned int nVertices, Vertex *min, Vertex *max) { unsigned int currentVertex = 0; assign(min, &vertices[0]); assign(max, &vertices[0]); for (currentVertex = 1; currentVertex < nVertices; ++currentVertex) { if (vertices[currentVertex].x < min->x) min->x = vertices[currentVertex].x; if (vertices[currentVertex].x > max->x) max->x = vertices[currentVertex].x; if (vertices[currentVertex].y < min->y) min->y = vertices[currentVertex].y; if (vertices[currentVertex].y > max->y) max->y = vertices[currentVertex].y; if (vertices[currentVertex].z < min->z) min->z = vertices[currentVertex].z; if (vertices[currentVertex].z > max->z) max->z = vertices[currentVertex].z; } } void Surf::centerOfVoxel_(int x, int y, int z, Vertex *rMin, Vertex *vSize, Vertex *voxelCenter) { voxelCenter->x = rMin->x + ((double)x)*vSize->x + 0.5*vSize->x; voxelCenter->y = rMin->y + ((double)y)*vSize->y + 0.5*vSize->y; voxelCenter->z = rMin->z + ((double)z)*vSize->z + 0.5*vSize->z; } /* * embeds a voxel defined as {i,j,k} (three integers in Z3) in R3 as a Point3d, which * is a {x,y,z} or a point with three "double"s */ void Surf::centerOfVoxel(Voxel *voxel, Vertex *rMin, Vertex *vSize, Vertex *voxelCenter) { voxelCenter->x = rMin->x + ((double)voxel->x)*vSize->x + 0.5*vSize->x; voxelCenter->y = rMin->y + ((double)voxel->y)*vSize->y + 0.5*vSize->y; voxelCenter->z = rMin->z + ((double)voxel->z)*vSize->z + 0.5*vSize->z; } double Surf::distancePointSegment(LineSegment *l, Vertex *p) { Vertex p0, p1, v, w; assign(&p0, &l->start); assign(&p1, &l->end); subtract(&v, &l->end, &p0); subtract(&w, p, &p0); double c1 = dotProduct(&w, &v); /* the point is at the left side of the line segment {p0,p1} so it is closest to p0 */ if (c1 <= 0) return distance(p, &p0); double c2 = dotProduct(&v, &v); /* the point is at the right side of the line segment {p0,p1} so it is closest to p1 */ if (c2 <= c1) return distance(p, &p1); double b = c1/c2; Vertex b_v, pb; product(&b_v, b, &v); /* Pb = P0 + b * V; the point on the line segment closest to the point in question */ add(&pb, &p0, &b_v); return distance(p, &pb); } double Surf::distancePointTriangle(Face *f, Vertex *p) { Vertex o, u, v; assign(&o, f->p1); subtract(&u, f->p2, &o); subtract(&v, f->p3, &o); /* considers a parametric equation for every point on the plane corresponding to the triangle (face) as P(s,t) */ Vertex w; subtract(&w, p, &o); /* here computes five double values to be used throughout the function */ double uu = dotProduct(&u, &u); double vv = dotProduct(&v, &v); double uv = dotProduct(&u, &v); double wu = dotProduct(&w, &u); double wv = dotProduct(&w, &v); /* * the determinant is actually the size of the cross product of two edges * of the triangle. If the determinant is 0 then the triangle is degenerate * as its area is zero (because the two edges are paralell) */ double det = abs(uv*uv-uu*vv); if (det > 0) { double s = -(uv*wv-vv*wu); double t = -(uv*wu-uu*wv); /* t \R2| \ | \| |\ | \R1 R3|R0\ __|___\_____s R4|R5 \R6 */ if (s + t <= det) { if (s < 0) { if (t < 0) { /* Region4, distance to V0 */ return distance(f->p1, p); } else { /* Region3, distance to line(V0,V2) */ LineSegment l; assign(&l.start, f->p1); assign(&l.end, f->p3); return distancePointSegment(&l, p); } } else if (t < 0) { /* Region5, distance to line(V0,V1) */ LineSegment l; assign(&l.start, f->p1); assign(&l.end, f->p2); return distancePointSegment(&l, p); } else { /* Region0, distance to point(s,t) */ s /= det; t /= det; Vertex vertex, s_u, t_v; product(&s_u, s, &u); product(&t_v, t, &v); add(&vertex, &o, &s_u); add(&vertex, &vertex, &t_v); return distance(&vertex, p); } } else { if (s < 0) { /* Region2, distance to V2 */ return distance(f->p3, p); } else if (t < 0) { /* Region6, distance to V1 */ return distance(f->p2, p); } else { /* Region1, distance to line(V1,V2) */ LineSegment l; assign(&l.start, f->p2); assign(&l.end, f->p3); return distancePointSegment(&l, p); } } } else { return DBL_MAX; } } /* * returns 1 on success and 0 on failure; success means that the distance of * the point to one of the triangles of the mesh is smaller than half of the * length(norm) of the VSize vector (the longest diagon of a voxel cube) */ int Surf::isNear(int num_threads, Face **mesh, unsigned int nTriangles, Vertex *voxelCenter, Vertex *vSize) { int res = 0; unsigned int currentTriangle = 0; double threshold = 0.5*sqrt(vSize->x*vSize->x + vSize->y*vSize->y + vSize->z*vSize->z); for (currentTriangle = 0; currentTriangle < nTriangles; ++currentTriangle) { if (distancePointTriangle(mesh[currentTriangle], voxelCenter) <= threshold) { res = 1; break; } } return res; } /* * using the parametric equation of a point as P(s,t) in reference to two edges of a triangle * we find out if the intersection of a point and the plane corresponding to the triangle lies within the triangle; * this would correspond to s and t belonging to [0,1] and s+t,=1 */ int Surf::intersectsTriangleLine(Face *f, LineSegment *l) { Vertex o, u, v, n; assign(&o, f->p1); subtract(&u, f->p2, &o); subtract(&v, f->p3, &o); crossProduct(&n, &u, &v); Vertex ps, pe; assign(&ps, &l->start); assign(&pe, &l->end); Vertex o_ps, pe_ps; subtract(&o_ps, &o, &ps); double nomin = dotProduct(&o_ps, &n); subtract(&pe_ps, &pe, &ps); double denom = dotProduct(&n, &pe_ps); if (denom != 0) { double alpha = nomin/denom; Vertex scaled_pe_ps, p, w; product(&scaled_pe_ps, alpha, &pe_ps); add(&p, &ps, &scaled_pe_ps); subtract(&w, &p, &o); double uu = dotProduct(&u, &u); double vv = dotProduct(&v, &v); double uv = dotProduct(&u, &v); double wu = dotProduct(&w, &u); double wv = dotProduct(&w, &v); double stdenom = uv*uv-uu*vv; double s = (uv*wv-vv*wu)/stdenom; double t = (uv*wu-uu*wv)/stdenom; Vertex point, s_u, t_v; product(&s_u, s, &u); product(&t_v, t, &v); add(&point, &o, &s_u); add(&point, &point, &t_v); if (s >= 0 && t >= 0 && s + t <= 1) { return 1; } else { return 0; } } else { return 0; } } /* * using the function triangle line intersection we iterate over all triangular faces of a mesh */ int Surf::intersectsMeshLine(Face **mesh, unsigned int nTriangles, LineSegment *l) { unsigned int currentTriangle = 0; for (currentTriangle = 0; currentTriangle < nTriangles; ++currentTriangle) { if (intersectsTriangleLine(mesh[currentTriangle], l)) return 1; } return 0; } /* * we intersect a "connectivity target"(Laine, 2013) for 26-connected results; this is a 3D * crosshair composed of 6 lines. If intersection is not null then the voxel should be included */ int Surf::intersectsMesh26(Face **mesh, unsigned int nTriangles, Vertex *voxelCenter, Vertex *vSize) { LineSegment testLine; assign(&testLine.start, voxelCenter); assign(&testLine.end, voxelCenter); testLine.end.x += 0.5*vSize->x; if (intersectsMeshLine(mesh, nTriangles, &testLine)) return 1; assign(&testLine.end, voxelCenter); testLine.end.y += 0.5*vSize->y; if (intersectsMeshLine(mesh, nTriangles, &testLine)) return 1; assign(&testLine.end, voxelCenter); testLine.end.z += 0.5*vSize->z; if (intersectsMeshLine(mesh, nTriangles, &testLine)) return 1; assign(&testLine.end, voxelCenter); testLine.end.x -= 0.5*vSize->x; if (intersectsMeshLine(mesh, nTriangles, &testLine)) return 1; assign(&testLine.end, voxelCenter); testLine.end.y -= 0.5*vSize->y; if (intersectsMeshLine(mesh, nTriangles, &testLine)) return 1; assign(&testLine.end, voxelCenter); testLine.end.z -= 0.5*vSize->z; if (intersectsMeshLine(mesh, nTriangles, &testLine)) return 1; return 0; } /* * we intersect a "connectivity target"(Laine, 2013) for 6-connected results with the mesh in * question; this is a the outline of a voxel cube composed of 12 lines. If intersection is not * null then the voxel should be included */ int Surf::intersectsMesh6(Face **mesh, unsigned int nTriangles, Vertex *voxelCenter, Vertex *vSize) { unsigned int currentEdge = 0; Vertex vertices[8]; LineSegment edges[12]; Vertex halfSize; halfSize.x = 0.5*vSize->x; halfSize.y = 0.5*vSize->y; halfSize.z = 0.5*vSize->z; addTo(&vertices[0], voxelCenter, +halfSize.x, +halfSize.y, +halfSize.z); addTo(&vertices[1], voxelCenter, -halfSize.x, +halfSize.y, +halfSize.z); addTo(&vertices[2], voxelCenter, -halfSize.x, -halfSize.y, +halfSize.z); addTo(&vertices[3], voxelCenter, +halfSize.x, -halfSize.y, +halfSize.z); addTo(&vertices[4], voxelCenter, -halfSize.x, -halfSize.y, -halfSize.z); addTo(&vertices[5], voxelCenter, +halfSize.x, -halfSize.y, -halfSize.z); addTo(&vertices[6], voxelCenter, +halfSize.x, +halfSize.y, -halfSize.z); addTo(&vertices[7], voxelCenter, -halfSize.x, +halfSize.y, -halfSize.z); assign(&edges[0].start, &vertices[0]); assign(&edges[0].end, &vertices[1]); assign(&edges[1].start, &vertices[1]); assign(&edges[1].end, &vertices[2]); assign(&edges[2].start, &vertices[2]); assign(&edges[2].end, &vertices[3]); assign(&edges[3].start, &vertices[3]); assign(&edges[3].end, &vertices[0]); assign(&edges[4].start, &vertices[0]); assign(&edges[4].end, &vertices[6]); assign(&edges[5].start, &vertices[6]); assign(&edges[5].end, &vertices[5]); assign(&edges[6].start, &vertices[5]); assign(&edges[6].end, &vertices[4]); assign(&edges[7].start, &vertices[4]); assign(&edges[7].end, &vertices[7]); assign(&edges[8].start, &vertices[5]); assign(&edges[8].end, &vertices[3]); assign(&edges[9].start, &vertices[4]); assign(&edges[9].end, &vertices[2]); assign(&edges[10].start, &vertices[1]); assign(&edges[10].end, &vertices[7]); assign(&edges[11].start, &vertices[6]); assign(&edges[11].end, &vertices[7]); for (currentEdge = 0; currentEdge < 12; ++currentEdge) { if (intersectsMeshLine(mesh, nTriangles, &edges[currentEdge])) return 1; } return 0; } // Zlatanova's 3D raster engine int Surf::voxelizeMesh(VoxelSet &voxels, Vertex *vertices, unsigned int nVertices, Face **mesh, unsigned int nTriangles, Vertex *vSize, int co, int num_threads) { Vertex rMin, rMax; Voxel vMax; // Bounding box already in Z3 getRBoundingBox(vertices, nVertices, &rMin, &rMax); rMin.x = floor(rMin.x); rMin.y = floor(rMin.y); rMin.z = floor(rMin.z); vMax.x = (unsigned int)ceil((rMax.x-rMin.x)/vSize->x); vMax.y = (unsigned int)ceil((rMax.y-rMin.y)/vSize->y); vMax.z = (unsigned int)ceil((rMax.z-rMin.z)/vSize->z); // Go voxel by voxel, in the bounding box of the mesh. note that // if the mesh is big it will slow down the whole process. It is // better to put in many small mesh objects that one big mesh object int x, y, z; int i=0; voxels.clear(); #ifdef Use_OpenMP omp_set_num_threads(num_threads); #pragma omp parallel for private(x, y, z) #endif for (x = 0; x <= vMax.x; ++x) { for (y = 0; y <= vMax.y; ++y) { for (z = 0; z <= vMax.z; ++z) { Vertex voxelCenter; centerOfVoxel_(x, y, z, &rMin, vSize, &voxelCenter); // Check nearness int inTarget = 1; if (!isNear(num_threads, mesh, nTriangles, &voxelCenter, vSize)) inTarget = 0; // Check intersection if (inTarget) { if (co == 26) { inTarget = intersectsMesh26(mesh, nTriangles, &voxelCenter, vSize); } else if (co == 6) { inTarget = intersectsMesh6(mesh, nTriangles, &voxelCenter, vSize); } else { printf("connectivity target undefined!"); inTarget = 0; } } // if (inTarget) { voxels.push_back(VoxelType(voxelCenter.x, voxelCenter.y, voxelCenter.z)); } } } } return 0; } // surfrecon func void Surf::surfrecon(VoxelSet pcIn, VoxelSet &voxelOut, int co, int num_threads) { // init setPoints(pcIn); // Timer t; t.start(); // CGAL's implementation of scale space surface reconstrcution // Digne, Julie, et al. "Scale space meshing of raw data point sets." // Computer Graphics Forum. Vol. 30. No. 6. Blackwell Publishing Ltd, 2011. // Reconstruction reconstruct( 10, 200 ); reconstruct.reconstruct_surface( points.begin(), points.end(), 4, false, // Do not separate shells true // Force manifold output ); std::cerr << " Surface reconstruction done in " << t.time() << " sec." << std::endl; // faces.clear(); for( Triple_iterator it = reconstruct.surface_begin( ); it != reconstruct.surface_end( ); ++it ) { int c=0; Voxel v; for (auto i:*it) { switch (c++) { case 0: v.x = i; break; case 1: v.y = i; break; case 2: v.z = i; break; default: break; } } faces.push_back(v); } // int nVertices = points.size(), nTriangles = faces.size(), v=0, f=0; Vertex *vertices = NULL; Face *mesh = NULL; try { vertices = new Vertex [nVertices]; mesh = new Face [nTriangles]; } catch (...) { cout<<"Fail to allocate memory for Vertices and Faces."<<endl; return; } Face **mesh_ptr = NULL; try { mesh_ptr = new Face* [nTriangles]; } catch (...) { cout<<"Fail to allocate memory for Vertices and Faces."<<endl; return; } for(long i=0; i<nVertices; i++) { vertices[i].x = points[i].x(); vertices[i].y = points[i].y(); vertices[i].z = points[i].z(); } for(long i=0; i<nTriangles; i++) { mesh[i].p1 = &vertices[faces[i].x]; mesh[i].p2 = &vertices[faces[i].y]; mesh[i].p3 = &vertices[faces[i].z]; mesh_ptr[i] = &mesh[i]; } Vertex vSize; vSize.x = 1.0; vSize.y = 1.0; vSize.z = 1.0; // t.reset(); if (voxelizeMesh(voxelOut, vertices, nVertices, mesh_ptr, nTriangles, &vSize, co, num_threads)) { if(mesh_ptr) {delete []mesh_ptr; mesh_ptr=NULL;} if(mesh) {delete []mesh; mesh=NULL;} if(vertices) {delete []vertices; vertices=NULL;} cout << "Fail to execute voxelization."<<endl; return; } cout<<" Convert mesh "<<nTriangles<<" triangles to "<<voxelOut.size()<<" voxels in "<< t.time() << " sec." <<endl; // return; }
32.873484
160
0.549557
[ "mesh", "object", "vector", "3d" ]
413b4ae3d16098984095e8ca9257e0db2f3e3339
4,668
cpp
C++
src/client/client_engine.cpp
BinaryDrag0n/open-builder
9222a476661123d044fd6df4ad2f63a6e33c72e5
[ "MIT" ]
null
null
null
src/client/client_engine.cpp
BinaryDrag0n/open-builder
9222a476661123d044fd6df4ad2f63a6e33c72e5
[ "MIT" ]
null
null
null
src/client/client_engine.cpp
BinaryDrag0n/open-builder
9222a476661123d044fd6df4ad2f63a6e33c72e5
[ "MIT" ]
null
null
null
#include "client_engine.h" #include "client_config.h" #include "client_state_controller.h" #include "game.h" #include "gl/framebuffer.h" #include "gl/gl_errors.h" #include "gl/primitive.h" #include "gl/vertex_array.h" #include "gui/gui_system.h" #include "gui/widget/label_widget.h" #include "input/input_state.h" #include "lua/client_lua_api.h" #include "lua/client_lua_callback.h" #include "renderer/chunk_renderer.h" #include "renderer/gui_renderer.h" #include "window.h" #include <SFML/System/Clock.hpp> #include <common/lua/script_engine.h> #include <glad/glad.h> namespace { struct FPSCounter final { sf::Clock timer; float frameTime = 0; float frameCount = 0; void update() { frameCount++; if (timer.getElapsedTime() > sf::seconds(0.25)) { auto time = timer.getElapsedTime(); frameTime = time.asMilliseconds() / frameCount; timer.restart(); frameCount = 0; } } }; // } // namespace void runClientEngine() { // Window/ OpenGL context setup sf::Window window; if (!createWindowInitOpengl(window)) { return; // EngineStatus::GLInitError; } // Client engine stuff ClientStateController control; FPSCounter fps; sf::Clock gameTimer; // Input Keyboard keyboard; InputState inputState; // Init Lua lua ScriptEngine scriptEngine; ClientLuaCallbacks callbacks; // Gui gui::GuiSystem gui; GuiRenderer guiRenderer; // Init all the lua api stuff callbacks.initCallbacks(scriptEngine); luaInitGuiWidgetApi(scriptEngine); luaInitInputApi(scriptEngine, window, inputState); luaInitClientControlApi(scriptEngine, control); luaInitGuiApi(scriptEngine, gui, &guiRenderer); // Run the lua file to init the client engine scriptEngine.runLuaFile("game/client/main.lua"); callbacks.onClientStartup(); Game game; //============================================================= // Temp render stuff for testing gl::Framebuffer guiRenderTarget; gl::Framebuffer worldRenderTarget; gl::Shader screenShader; gl::VertexArray screenVAO = makeScreenQuadVertexArray(); guiRenderTarget.create(static_cast<unsigned>(GUI_WIDTH), static_cast<unsigned>(GUI_HEIGHT)); worldRenderTarget.create(ClientConfig::get().windowWidth, ClientConfig::get().windowHeight); screenShader.create("minimal", "minimal"); bool isRunning = true; // Main loop of the client code while (isRunning) { sf::Event event; while (window.pollEvent(event)) { if (window.hasFocus()) { keyboard.update(event); gui.handleEvent(event); } switch (event.type) { case sf::Event::Closed: isRunning = false; break; case sf::Event::KeyReleased: callbacks.onKeyboardKeyReleased(event.key.code); break; case sf::Event::MouseButtonReleased: game.onMouseRelease(event.mouseButton.button); break; default: break; } } // Input game.input(window, keyboard, inputState); // Update game.update(gameTimer.restart().asSeconds()); gui.update(); //============================================================= // Render // glEnable(GL_DEPTH_TEST); // World worldRenderTarget.bind(); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); game.render(); // GUI guiRenderTarget.bind(); glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); gui.render(guiRenderer); // Buffer to window gl::unbindFramebuffers(ClientConfig::get().windowWidth, ClientConfig::get().windowHeight); glDisable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT); auto drawable = screenVAO.getDrawable(); drawable.bind(); screenShader.bind(); worldRenderTarget.bindTexture(); drawable.draw(); glEnable(GL_BLEND); guiRenderTarget.bindTexture(); drawable.draw(); window.display(); glDisable(GL_BLEND); //======================================================================= fps.update(); isRunning = control.executeAction(game, callbacks); } window.close(); }
27.298246
81
0.569623
[ "render" ]
413ba7532406e32a43a90d5bf501c73122b5447b
10,715
hpp
C++
HugeCTR/include/tensor2.hpp
Chunshuizhao/HugeCTR
085b2e8ad2abaee5578e7bf43b8394d0b8473b58
[ "Apache-2.0" ]
null
null
null
HugeCTR/include/tensor2.hpp
Chunshuizhao/HugeCTR
085b2e8ad2abaee5578e7bf43b8394d0b8473b58
[ "Apache-2.0" ]
null
null
null
HugeCTR/include/tensor2.hpp
Chunshuizhao/HugeCTR
085b2e8ad2abaee5578e7bf43b8394d0b8473b58
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2021, NVIDIA CORPORATION. * * 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. */ #pragma once #include <common.hpp> #include <memory> #include <numeric> #include <vector> namespace HugeCTR { enum class TensorScalarType { None, Void, Float32, Float16, Int64, UInt64, Int32, UInt32, Size_t }; namespace { inline size_t get_num_elements_from_dimensions(const std::vector<size_t> &dimensions) { size_t elements = 1; for (size_t dim : dimensions) { elements *= dim; } return elements; } inline void *forward_void_pointer(void *ptr, size_t offset) { return reinterpret_cast<unsigned char *>(ptr) + offset; } template <typename T> struct TensorScalarSizeFunc { static size_t get_element_size() { return sizeof(T); } }; template <> struct TensorScalarSizeFunc<void> { static size_t get_element_size() { return 1ul; } }; template <typename T> struct TensorScalarTypeFunc {}; template <> struct TensorScalarTypeFunc<float> { static TensorScalarType get_type() { return TensorScalarType::Float32; } }; template <> struct TensorScalarTypeFunc<__half> { static TensorScalarType get_type() { return TensorScalarType::Float16; } }; template <> struct TensorScalarTypeFunc<size_t> { static TensorScalarType get_type() { return TensorScalarType::Size_t; } }; template <> struct TensorScalarTypeFunc<long long> { static TensorScalarType get_type() { return TensorScalarType::Int64; } }; template <> struct TensorScalarTypeFunc<unsigned int> { static TensorScalarType get_type() { return TensorScalarType::UInt32; } }; } // namespace class TensorBuffer2 { public: virtual ~TensorBuffer2() {} virtual bool allocated() const = 0; virtual void *get_ptr() = 0; }; class TensorBag2 { template <typename T> friend class Tensor2; std::vector<size_t> dimensions_; std::shared_ptr<TensorBuffer2> buffer_; TensorScalarType scalar_type_; TensorBag2(const std::vector<size_t> dimensions, const std::shared_ptr<TensorBuffer2> &buffer, TensorScalarType scalar_type) : dimensions_(dimensions), buffer_(buffer), scalar_type_(scalar_type) {} public: TensorBag2() : scalar_type_(TensorScalarType::None) {} const std::vector<size_t> &get_dimensions() const { return dimensions_; } void *get_ptr() { return buffer_->get_ptr(); } }; using TensorBags2 = std::vector<TensorBag2>; template <typename T> class Tensor2 { std::vector<size_t> dimensions_; size_t num_elements_; std::shared_ptr<TensorBuffer2> buffer_; public: static Tensor2 stretch_from(const TensorBag2 &bag) { if (bag.scalar_type_ != TensorScalarTypeFunc<T>::get_type()) { CK_THROW_(Error_t::WrongInput, "Inconsistent tensor type"); } return Tensor2(bag.dimensions_, bag.buffer_); } Tensor2() : num_elements_(0) {} Tensor2(Tensor2 const &other) = default; Tensor2 &operator=(Tensor2 const &other) = default; Tensor2(Tensor2 &&other) = default; Tensor2 &operator=(Tensor2 &&other) = default; Tensor2(const std::vector<size_t> &dimensions, const std::shared_ptr<TensorBuffer2> &buffer) : dimensions_(dimensions), num_elements_(get_num_elements_from_dimensions(dimensions)), buffer_(buffer) {} TensorBag2 shrink() const { return TensorBag2(dimensions_, buffer_, TensorScalarTypeFunc<T>::get_type()); } bool allocated() const { return buffer_ && buffer_->allocated(); } const std::vector<size_t> &get_dimensions() const { return dimensions_; } size_t get_num_elements() const { return num_elements_; } size_t get_size_in_bytes() const { return num_elements_ * TensorScalarSizeFunc<T>::get_element_size(); } void set_buffer(const std::shared_ptr<TensorBuffer2> &buffer) { buffer_ = buffer; } std::shared_ptr<TensorBuffer2> get_buffer() const { return buffer_; } const T *get_ptr() const { return reinterpret_cast<const T *>(buffer_->get_ptr()); } T *get_ptr() { return reinterpret_cast<T *>(buffer_->get_ptr()); } void reset_shape(const std::vector<size_t> &new_dimensions) { try { size_t new_num_elements = get_num_elements_from_dimensions(new_dimensions); if (new_num_elements > num_elements_) { CK_THROW_(Error_t::WrongInput, "new dimensions out of memory"); } dimensions_ = new_dimensions; num_elements_ = new_num_elements; } catch (const std::runtime_error &rt_err) { std::cerr << rt_err.what() << std::endl; } } }; template <typename T> using Tensors2 = std::vector<Tensor2<T>>; template <typename T> Tensors2<T> bags_to_tensors(const std::vector<TensorBag2> &bags) { Tensors2<T> tensors; for (const auto &bag : bags) { tensors.push_back(Tensor2<T>::stretch_from(bag)); } return tensors; } template <typename T> std::vector<TensorBag2> tensors_to_bags(const Tensors2<T> &tensors) { std::vector<TensorBag2> bags; for (const auto &tensor : tensors) { bags.push_back(tensor.shrink()); } return bags; } class SparseTensorBag { template <typename T> friend class SparseTensor; std::vector<size_t> dimensions_; std::shared_ptr<TensorBuffer2> value_buffer_; std::shared_ptr<TensorBuffer2> rowoffset_buffer_; std::shared_ptr<size_t> nnz_; size_t rowoffset_count_; TensorScalarType scalar_type_; SparseTensorBag(const std::vector<size_t> &dimensions, const std::shared_ptr<TensorBuffer2> &value_buffer, const std::shared_ptr<TensorBuffer2> &rowoffset_buffer, const std::shared_ptr<size_t> &nnz, const size_t rowoffset_count, TensorScalarType scalar_type) : dimensions_(dimensions), value_buffer_(value_buffer), rowoffset_buffer_(rowoffset_buffer), nnz_(nnz), rowoffset_count_(rowoffset_count), scalar_type_(scalar_type) {} public: SparseTensorBag() : scalar_type_(TensorScalarType::None) {} const std::vector<size_t> &get_dimensions() const { return dimensions_; } }; template <typename T> class SparseTensor { std::vector<size_t> dimensions_; std::shared_ptr<TensorBuffer2> value_buffer_; std::shared_ptr<TensorBuffer2> rowoffset_buffer_; std::shared_ptr<size_t> nnz_; // maybe size_t for FixedLengthSparseTensor size_t rowoffset_count_; public: SparseTensor() {} SparseTensor(const std::vector<size_t> &dimensions, const std::shared_ptr<TensorBuffer2> &value_buffer, const std::shared_ptr<TensorBuffer2> &rowoffset_buffer, const std::shared_ptr<size_t> &nnz, const size_t rowoffset_count) : dimensions_(dimensions), value_buffer_(value_buffer), rowoffset_buffer_(rowoffset_buffer), nnz_(nnz), rowoffset_count_(rowoffset_count) {} SparseTensor(const Tensor2<T> &value_tensor, const Tensor2<T> &rowoffset_tensor, const std::shared_ptr<size_t> nnz) : dimensions_(value_tensor.get_dimensions()), value_buffer_(value_tensor.get_buffer()), rowoffset_buffer_(rowoffset_tensor.get_buffer()), nnz_(nnz), rowoffset_count_(rowoffset_tensor.get_num_elements()) {} static SparseTensor stretch_from(const SparseTensorBag &bag) { if (bag.scalar_type_ != TensorScalarTypeFunc<T>::get_type()) { CK_THROW_(Error_t::WrongInput, "Inconsistent sparse tensor type"); } return SparseTensor(bag.dimensions_, bag.value_buffer_, bag.rowoffset_buffer_, bag.nnz_, bag.rowoffset_count_); } SparseTensorBag shrink() const { return SparseTensorBag(dimensions_, value_buffer_, rowoffset_buffer_, nnz_, rowoffset_count_, TensorScalarTypeFunc<T>::get_type()); } T *get_value_ptr() { return reinterpret_cast<T *>(value_buffer_->get_ptr()); } const T *get_value_ptr() const { return reinterpret_cast<const T *>(value_buffer_->get_ptr()); } Tensor2<T> get_value_tensor() const { return Tensor2<T>(dimensions_, value_buffer_); } T *get_rowoffset_ptr() { return reinterpret_cast<T *>(rowoffset_buffer_->get_ptr()); } const T *get_rowoffset_ptr() const { return reinterpret_cast<const T *>(rowoffset_buffer_->get_ptr()); } Tensor2<T> get_rowoffset_tensor() const { return Tensor2<T>({rowoffset_count_}, rowoffset_buffer_); } const std::vector<size_t> &get_dimensions() const { return dimensions_; } size_t max_nnz() const { return get_num_elements_from_dimensions(dimensions_); } size_t nnz() const { return *nnz_; } std::shared_ptr<size_t> get_nnz_ptr() { return nnz_; } size_t rowoffset_count() const { return rowoffset_count_; } }; template <typename T> using SparseTensors = std::vector<SparseTensor<T>>; template <typename T> class CSR; namespace sparse_tensor_helper { namespace cuda { template <typename T> void copy_async(SparseTensor<T> &dst, const SparseTensor<T> &src, cudaMemcpyKind kind, cudaStream_t stream) { CK_CUDA_THROW_(cudaMemcpyAsync(dst.get_value_ptr(), src.get_value_ptr(), src.nnz() * sizeof(T), kind, stream)); CK_CUDA_THROW_(cudaMemcpyAsync(dst.get_rowoffset_ptr(), src.get_rowoffset_ptr(), src.rowoffset_count() * sizeof(T), kind, stream)); *dst.get_nnz_ptr() = src.nnz(); } template <typename T> void copy_async(SparseTensor<T> &dst, const CSR<T> &src, cudaStream_t stream) { CK_CUDA_THROW_(cudaMemcpyAsync(dst.get_value_ptr(), src.get_value_tensor().get_ptr(), src.get_num_values() * sizeof(T), cudaMemcpyHostToDevice, stream)); CK_CUDA_THROW_(cudaMemcpyAsync(dst.get_rowoffset_ptr(), src.get_row_offset_tensor().get_ptr(), src.get_row_offset_tensor().get_size_in_bytes(), cudaMemcpyHostToDevice, stream)); *dst.get_nnz_ptr() = src.get_num_values(); } } // namespace cuda namespace cpu { template <typename T> void copy(SparseTensor<T> &dst, const SparseTensor<T> &src) { memcpy(dst.get_value_ptr(), src.get_value_ptr(), src.nnz() * sizeof(T)); memcpy(dst.get_rowoffset_ptr(), src.get_rowoffset_ptr(), src.rowoffset_count() * sizeof(T)); *dst.get_nnz_ptr() = src.nnz(); } } // namespace cpu } // namespace sparse_tensor_helper } // namespace HugeCTR
32.371601
100
0.706486
[ "vector" ]
4140670e8030cbd2479d44269630aff45de7572a
5,879
cpp
C++
Simple_Matrix/Source.cpp
RemusRomulus/Simple-Matrix
7cf94470551fd3c0ef10b11211e388b46b725977
[ "CC0-1.0" ]
null
null
null
Simple_Matrix/Source.cpp
RemusRomulus/Simple-Matrix
7cf94470551fd3c0ef10b11211e388b46b725977
[ "CC0-1.0" ]
null
null
null
Simple_Matrix/Source.cpp
RemusRomulus/Simple-Matrix
7cf94470551fd3c0ef10b11211e388b46b725977
[ "CC0-1.0" ]
null
null
null
#include <iomanip> #include <vector> #include <cmath> #include <iostream> // 0 1 2 3 // 4 5 6 7 // 8 9 10 11 // 12 13 14 15 // This Deals with strictly square matrices template <typename T> class Matrix { public: Matrix() { data = { 0 }; } Matrix(std::vector<T> &rhs) : data(rhs) { data = rhs; if (!this->size_dim()) { this->clear(); std::cout << "::ERROR:: Matrix<T> cannot initialize with non-square matrix\n"; } } Matrix(T in) { this->data.push_back(in); this->size_dim(); } ~Matrix() { data.clear(); } Matrix & operator=(const Matrix &rhs) { this->data = rhs.data; this->dim = rhs.dim; } void print() { std::cout << "-----\nMatrix Data\n-----\n"; std::cout << "-- Matrix Dim: " << this->dim << "\n-----\n"; long long counter = 1; for (auto &&e : this->data) { std::cout <<std::setprecision(6) << e << ", "; if (counter % dim == 0) std::cout << "\n"; counter++; } std::cout << "-----\n\n"; } void print_corners() { std::cout << "-----\nMatrix Data: Corners\n-----\n"; std::cout << "-- Matrix Dim: " << this->dim << "\n-----\n"; std::cout << std::setprecision(6) << this->data[0] << " -- " << this->data[dim - 1] << "\n"; std::cout << "| |\n"; std::cout << std::setprecision(6) << this->data[dim * dim - dim] << " -- " << this->data[dim*dim - 1] << "\n\n"; } void transpose() { unsigned int size_mtx = unsigned int(this->data.size()); if (size_mtx > 1) { std::vector<T> tmp_vect(dim, 0); for (unsigned int i = 0; i < size_mtx - dim - 1; i += dim + 1) { for (unsigned int j = 0; j < dim; j++) { //Keeps the array index in bounds if (i + dim * j > size_mtx) continue; //std::cout << "i: " << i << ", j: " << j << ", i + j: " << i+j << ", i + dim * j: " << i + dim*j << "\n"; tmp_vect[j] = this->data[i + dim * j]; this->data[i + dim * j] = this->data[i + j]; this->data[i + j] = tmp_vect[j]; } } } } inline void clear() { this->data.clear(); dim = 0; } private: inline bool size_dim() { bool OUT = false; this->dim = unsigned int(std::sqrt(this->data.size())); if (dim * dim == data.size()) OUT = true; // no else statement since OUT is initialized as false return OUT; } std::vector<T> data; unsigned int dim; }; template<> class Matrix<char> { public: Matrix(...) { std::cout << "::ERROR:: Matrix can't initialize with type <CHAR>.\n"; } void print() { std::cout << "-----\nMatrix Data\n-----\n"; std::cout << "-- Matrix Dim: " << 0 << "\n-----\n"; std::cout << "-----\n\n"; } void print_corners() { std::cout << "-----\nMatrix Data: Corners\n-----\n"; std::cout << "-- Matrix Dim: " << 0 << "\n-----\n"; std::cout << "-----\n\n"; } private: // data and dim attributes are not included, to ensure that an improperly created class // will not accidentally be put to use in production code later }; template <> class Matrix<std::string> { public: Matrix(...) { std::cout << "::ERROR:: Matrix can't initialize with type <STD::STRING>.\n"; } void print() { std::cout << "-----\nMatrix Data\n-----\n"; std::cout << "-- Matrix Dim: " << 0 << "\n-----\n"; std::cout << "-----\n\n"; } void print_corners() { std::cout << "-----\nMatrix Data: Corners\n-----\n"; std::cout << "-- Matrix Dim: " << 0 << "\n-----\n"; std::cout << "-----\n\n"; } private: // data and dim attributes are not included, to ensure that an improperly created class // will not accidentally be put to use in production code later }; int main() { //Check floats std::cout << "\n............\n Check FLOATs\n"; std::vector<float> mtx_array = { 1.0f, 2.0f, 3.3f, 4.4f, 5.5f, \ 6.6f, 7.7f, 8.8f, 9.9f, 10.1f, \ 11.4f, 12.2f, 13.3f, 14.4f, 15.5f, \ 16.6f }; Matrix<float> mtx(mtx_array); mtx.print(); mtx.print_corners(); mtx.transpose(); mtx.print(); mtx.print_corners(); //Check single double std::cout << "\n............\n Check Single DOUBLE\n"; Matrix<double> mtx_single_double(34.0004); mtx_single_double.print(); mtx_single_double.transpose(); mtx_single_double.print(); //Check Non Square list std::cout << "\n............\n Check NON Square MTX\n"; std::vector<double> mtx_double_array = {97.346335, 872.982734, 98.2398235, -.0293982, -29083.2352}; Matrix<double> mtx_double(mtx_double_array); mtx_double.print(); mtx_double.transpose(); mtx_double.print(); //Check Single item std::cout << "\n............\n Check Single Item\n"; Matrix<int> mtx_single(235); mtx_single.print(); mtx_single.transpose(); mtx_single.print(); //Testing Copy Operator std::cout << "\n............\n Check Copy Operator\n"; Matrix<float> mtx_float_2 = mtx; mtx_float_2.print(); //Check Ints std::cout << "\n............\n Check INTs\n"; std::vector<int> int_mtx_array = { 1, 2, 3, 4, 5, 6, \ 7, 8, 9, 10, 11, 12, \ 13, 14, 15, 16, 17, 18, \ 19, 20, 21, 22, 23, 24, \ 25, 26, 27, 28, 29, 30, \ 31, 32, 33, 34, 35, 36 }; Matrix<int> mtx_int(int_mtx_array); mtx_int.print(); mtx_int.transpose(); mtx_int.print(); //Check Large Squares of LONG LONG std::cout << "\n............\n Check LONG LONGs\n"; std::vector<long long> double_long_array(1000 * 1000, 0); long long count = 0; for (auto &&e : double_long_array) e = count++; Matrix<long long> mtx_long_long(double_long_array); mtx_long_long.print_corners(); mtx_long_long.transpose(); mtx_long_long.print_corners(); // Ensuring that trying to instantiate a Matrix<char> will fail with defined message Matrix<char> mtx_char; Matrix<char> mtx_char_2('g'); Matrix<std::string> mtx_str; Matrix<std::string> mtx_str_2("foo"); // Just using this to keep the output window open long enough to visually check the results char tmp; std::cin >> tmp; return 0; }
22.611538
114
0.565232
[ "vector" ]
4140d9a044f339b5a18862e2be2336334aa230d3
5,474
cpp
C++
03_Tutorial/T02_XMCocos2D-CookBook/Source/Recipes/Ch2_DPad.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2017-08-03T07:15:00.000Z
2018-06-18T10:32:53.000Z
03_Tutorial/T02_XMCocos2D-CookBook/Source/Recipes/Ch2_DPad.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
null
null
null
03_Tutorial/T02_XMCocos2D-CookBook/Source/Recipes/Ch2_DPad.cpp
mcodegeeks/OpenKODE-Framework
d4382d781da7f488a0e7667362a89e8e389468dd
[ "MIT" ]
2
2019-03-04T22:57:42.000Z
2020-03-06T01:32:26.000Z
/* -------------------------------------------------------------------------- * * File Ch2_DPad.cpp * Ported By Young-Hwan Mun * Contact xmsoft77@gmail.com * * Created By Nate Burba * Contact Cocos2dCookbook@gmail.com * * -------------------------------------------------------------------------- * * Copyright (c) 2010-2013 XMSoft. * Copyright (c) 2011 COCOS2D COOKBOOK. All rights reserved. * * -------------------------------------------------------------------------- * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library in the file COPYING.LIB; * if not, write to the Free Software Foundation, Inc., * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA * * -------------------------------------------------------------------------- */ #include "Precompiled.h" #include "Ch2_DPad.h" #include "Libraries/SimpleAnimObject.h" #include "Libraries/DPad.h" KDbool Ch2_DPad::init ( KDvoid ) { if ( !Recipe::init ( ) ) { return KD_FALSE; } // Add gunman sprites CCSpriteFrameCache* pCache = CCSpriteFrameCache::sharedSpriteFrameCache ( ); pCache->addSpriteFramesWithFile ( "gunman.plist" ); // Initialize gunman m_pGunman = SimpleAnimObject::createWithSpriteFrame ( pCache->spriteFrameByName ( "gunman_stand_down.png" ) ); m_pGunman->setPosition ( ccp ( 240, 160 ) ); this->addChild ( m_pGunman ); m_nGunmanDirection = DOWN; // Initialize message m_pMessage->setString ( "DPad Vector:" ); // Initialize DPad pCache->addSpriteFramesWithFile ( "dpad_buttons.plist" ); m_pDPad = DPad::create ( ); m_pDPad->setPosition ( ccp ( 100, 100 ) ); this->addChild ( m_pDPad ); this->schedule ( schedule_selector ( Ch2_DPad::step ) ); return KD_TRUE; } KDvoid Ch2_DPad::step ( KDfloat fDelta ) { CCPoint tPressedVector = m_pDPad->getPressedVector ( ); KDint nDirection = m_pDPad->getDirection ( ); // Tell the user our DPad vector m_pMessage->setString ( ccszf ( "DPad Vector:%f %f", tPressedVector.x, tPressedVector.y ) ); KDbool bResetAnimation = KD_FALSE; // We reset the animation if the gunman changes direction if ( nDirection != NO_DIRECTION ) { if ( m_nGunmanDirection != nDirection ) { bResetAnimation = KD_TRUE; m_nGunmanDirection = nDirection; } } CCPoint tGunmanVelocity = m_pGunman->getVelocity ( ); if ( tGunmanVelocity.x != tPressedVector.x * 2 || tGunmanVelocity.y != tPressedVector.y * 2 ) { m_pGunman->setVelocity ( ccp ( tPressedVector.x * 2, tPressedVector.y * 2 ) ); bResetAnimation = KD_TRUE; } // Update gunman position m_pGunman->update ( fDelta ); // Re-animate if necessary if ( bResetAnimation ) { this->animateGunman ( ); } } KDvoid Ch2_DPad::animateGunman ( KDvoid ) { CCSpriteFrameCache* pCache = CCSpriteFrameCache::sharedSpriteFrameCache ( ); // Animate our gunman CCAnimation* pAnimation = CCAnimation::create ( ); pAnimation->setDelayPerUnit ( 0.15f ); const KDchar* szDirection; KDbool bFlipX = KD_FALSE; KDbool bMoving = KD_TRUE; CCPoint tVelocity = m_pGunman->getVelocity ( ); if ( tVelocity.x == 0 && tVelocity.y == 0 ) { bMoving = KD_FALSE; } switch ( m_nGunmanDirection ) { case LEFT : szDirection = "right"; bFlipX = KD_TRUE; break; case UP_LEFT : szDirection = "up_right"; bFlipX = KD_TRUE; break; case UP : szDirection = "up"; break; case UP_RIGHT : szDirection = "up_right"; break; case RIGHT : szDirection = "right"; break; case DOWN_RIGHT : szDirection = "down_right"; break; case DOWN : szDirection = "down"; break; case DOWN_LEFT : szDirection = "down_right"; bFlipX = KD_TRUE; break; } // Our simple running loop if ( bMoving ) { pAnimation->addSpriteFrame ( pCache->spriteFrameByName ( ccszf ( "gunman_run_%s_01.png", szDirection ) ) ); pAnimation->addSpriteFrame ( pCache->spriteFrameByName ( ccszf ( "gunman_stand_%s.png" , szDirection ) ) ); pAnimation->addSpriteFrame ( pCache->spriteFrameByName ( ccszf ( "gunman_run_%s_02.png", szDirection ) ) ); pAnimation->addSpriteFrame ( pCache->spriteFrameByName ( ccszf ( "gunman_stand_%s.png" , szDirection ) ) ); } else { pAnimation->addSpriteFrame ( pCache->spriteFrameByName ( ccszf ( "gunman_stand_%s.png" , szDirection ) ) ); } m_pGunman->setFlipX ( bFlipX ); m_pGunman->stopAllActions ( ); m_pGunman->runAction ( CCRepeatForever::create ( CCAnimate::create ( pAnimation ) ) ); } KDvoid Ch2_DPad::ccTouchesBegan ( CCSet* pTouches, CCEvent* pEvent ) { m_pDPad->ccTouchesBegan ( pTouches, pEvent ); } KDvoid Ch2_DPad::ccTouchesMoved ( CCSet* pTouches, CCEvent* pEvent ) { m_pDPad->ccTouchesMoved ( pTouches, pEvent ); } KDvoid Ch2_DPad::ccTouchesEnded ( CCSet* pTouches, CCEvent* pEvent ) { m_pDPad->ccTouchesEnded ( pTouches, pEvent ); }
32.390533
111
0.643223
[ "vector" ]
414206afca9790b88c4e1499c12d1f33604d4029
5,154
cpp
C++
source/backend/vulkan/execution/VulkanDeconvolutionDepthwise.cpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
3
2019-12-27T01:10:32.000Z
2021-05-14T08:10:40.000Z
source/backend/vulkan/execution/VulkanDeconvolutionDepthwise.cpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
10
2019-07-04T01:40:13.000Z
2019-10-30T02:38:42.000Z
source/backend/vulkan/execution/VulkanDeconvolutionDepthwise.cpp
stephehuang/MNN
e8d9ee89aca3e8247745fb89b338eca2ad9b583d
[ "Apache-2.0" ]
1
2019-12-06T06:53:51.000Z
2019-12-06T06:53:51.000Z
// // VulkanDeconvolutionDepthwise.cpp // MNN // // Created by MNN on 2019/01/31. // Copyright ยฉ 2018, Alibaba Group Holding Limited // #include "backend/vulkan/execution/VulkanDeconvolutionDepthwise.hpp" #include "core/Macro.h" namespace MNN { VulkanDeconvolutionDepthwise::VulkanDeconvolutionDepthwise(Backend* bn, const Convolution2D* conv) : VulkanBasicExecution(bn) { mConvCommonOption = conv->common(); auto vkBn = (VulkanBackend*)bn; int outputC4 = UP_DIV(mConvCommonOption->outputCount(), 4); mBias = std::make_shared<VulkanImage>(vkBn->getMemoryPool(), false, std::vector<int>{outputC4, 1}); { auto biasBuffer = std::make_shared<VulkanBuffer>(vkBn->getMemoryPool(), false, outputC4 * 4 * sizeof(float)); auto biasPtr = biasBuffer->map(); ::memset(biasPtr, 0, outputC4 * 4 * sizeof(float)); ::memcpy(biasPtr, conv->bias()->data(), conv->bias()->size() * sizeof(float)); biasBuffer->unmap(); vkBn->copyBufferToImage(biasBuffer.get(), mBias.get()); } mConvParam = std::make_shared<VulkanBuffer>(vkBn->getMemoryPool(), false, sizeof(VulkanConvolutionCommon::ConvolutionParameter), nullptr, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT); int kh = mConvCommonOption->kernelY(); int kw = mConvCommonOption->kernelX(); int co = mConvCommonOption->outputCount(); int coC4 = UP_DIV(co, 4); mKernel = std::make_shared<VulkanImage>(vkBn->getMemoryPool(), false, std::vector<int>{kw * kh, coC4}); const int alignedWeightSize = kh * kw * ALIGN_UP4(co); auto tempWeightBuffer = std::make_shared<VulkanBuffer>(vkBn->getMemoryPool(), false, alignedWeightSize * sizeof(float)); auto tempReorderWeight = (float*)tempWeightBuffer->map(); ::memset(tempReorderWeight, 0, alignedWeightSize * sizeof(float)); auto tempWeight = conv->weight()->data(); for (int b = 0; b < co; ++b) { int b_4 = b / 4; float* dst_b = tempReorderWeight + b_4 * 4 * kw * kh; int mx = b % 4; for (int y = 0; y < kh; ++y) { float* dst_y = dst_b + y * kw * 4; for (int x = 0; x < kw; ++x) { float* dst_x = dst_y + x * 4; dst_x[mx] = tempWeight[x + y * kw + b * kw * kh]; } } } tempWeightBuffer->unmap(); vkBn->copyBufferToImage(tempWeightBuffer.get(), mKernel.get()); mSampler = vkBn->getCommonSampler(); std::vector<VkDescriptorType> types{ VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, }; std::string macro = VulkanConvolutionCommon::getPostTreatMacro(mConvCommonOption); mPipeline = vkBn->getPipeline("glsl_deconvolutionDepthwise_" + macro + "comp", types); mPipelineSet.reset(mPipeline->createSet()); mLocalSize[0] = 8; mLocalSize[1] = 8; mLocalSize[2] = 1; } ErrorCode VulkanDeconvolutionDepthwise::onEncode(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, const VulkanCommandPool::Buffer* cmdBuffer) { auto src = inputs[0]; auto dst = outputs[0]; const int ocDiv4 = UP_DIV(dst->channel(), 4); auto common = mConvCommonOption; { auto convCons = reinterpret_cast<VulkanConvolutionCommon::ConvolutionParameter*>(mConvParam->map()); VulkanDeconvolution::writeConvolutionConst(convCons, common, src, dst); mConvParam->unmap(); } mPipelineSet->writeImage((VkImageView)dst->deviceId(), mSampler->get(), VK_IMAGE_LAYOUT_GENERAL, 0); mPipelineSet->writeImage((VkImageView)src->deviceId(), mSampler->get(), VK_IMAGE_LAYOUT_GENERAL, 1); mPipelineSet->writeImage(mKernel->view(), mSampler->get(), VK_IMAGE_LAYOUT_GENERAL, 2); mPipelineSet->writeImage(mBias->view(), mSampler->get(), VK_IMAGE_LAYOUT_GENERAL, 3); mPipelineSet->writeBuffer(mConvParam->buffer(), 4, mConvParam->size()); mPipeline->bind(cmdBuffer->get(), mPipelineSet->get()); vkCmdDispatch(cmdBuffer->get(), UP_DIV(dst->width(), mLocalSize[0]), UP_DIV(dst->height(), mLocalSize[1]), UP_DIV(ocDiv4, mLocalSize[2])); return NO_ERROR; } class VulkanDeconvolutionDepthwiseCreator : public VulkanBackend::Creator { public: virtual VulkanBasicExecution* onCreate(const std::vector<Tensor*>& inputs, const std::vector<Tensor*>& outputs, const MNN::Op* op, Backend* backend) const override { if (inputs.size() > 1) { return nullptr; } return new VulkanDeconvolutionDepthwise(backend, op->main_as_Convolution2D()); } }; static bool gResistor = []() { VulkanBackend::addCreator(OpType_DeconvolutionDepthwise, new VulkanDeconvolutionDepthwiseCreator); return true; }(); } // namespace MNN
45.210526
134
0.635041
[ "vector" ]
414a6af6f32ec8de26422ff19cd08e6ab5fb5b72
7,328
cpp
C++
Cpp/SDK/BP_EnemyScalingSpawn_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
1
2020-08-15T08:31:55.000Z
2020-08-15T08:31:55.000Z
Cpp/SDK/BP_EnemyScalingSpawn_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
2
2020-08-15T08:43:56.000Z
2021-01-15T05:04:48.000Z
Cpp/SDK/BP_EnemyScalingSpawn_functions.cpp
MrManiak/Squad-SDK
742feb5991ae43d6f0cedd2d6b32b949923ca4f9
[ "Apache-2.0" ]
2
2020-08-10T12:05:42.000Z
2021-02-12T19:56:10.000Z
// Name: S, Version: b #include "../SDK.h" #ifdef _MSC_VER #pragma pack(push, 0x01) #endif /*!!HELPER_DEF!!*/ /*!!DEFINE!!*/ namespace UFT { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- // Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.IsSameTeam // (Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // class UObject* Object (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor) bool ABP_EnemyScalingSpawn_C::IsSameTeam(class UObject* Object) { static auto fn = UObject::FindObject<UFunction>("Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.IsSameTeam"); ABP_EnemyScalingSpawn_C_IsSameTeam_Params params; params.Object = Object; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.OnEnemiesInRadiusChanged // (Public, BlueprintCallable, BlueprintEvent) void ABP_EnemyScalingSpawn_C::OnEnemiesInRadiusChanged() { static auto fn = UObject::FindObject<UFunction>("Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.OnEnemiesInRadiusChanged"); ABP_EnemyScalingSpawn_C_OnEnemiesInRadiusChanged_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.GetRespawnDelay // (Event, Public, HasOutParms, BlueprintCallable, BlueprintEvent) // Parameters: // float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash) float ABP_EnemyScalingSpawn_C::GetRespawnDelay() { static auto fn = UObject::FindObject<UFunction>("Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.GetRespawnDelay"); ABP_EnemyScalingSpawn_C_GetRespawnDelay_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; return params.ReturnValue; } // Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.BndEvt__EnemyDetectionRadius_K2Node_ComponentBoundEvent_327_ComponentBeginOverlapSignature__DelegateSignature // (HasOutParms, BlueprintEvent) // Parameters: // class UPrimitiveComponent* OverlappedComponent (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // class AActor* OtherActor (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // class UPrimitiveComponent* OtherComp (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // int OtherBodyIndex (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // bool bFromSweep (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor) // struct FHitResult SweepResult (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData, NoDestructor, ContainsInstancedReference) void ABP_EnemyScalingSpawn_C::BndEvt__EnemyDetectionRadius_K2Node_ComponentBoundEvent_327_ComponentBeginOverlapSignature__DelegateSignature(class UPrimitiveComponent* OverlappedComponent, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int OtherBodyIndex, bool bFromSweep, const struct FHitResult& SweepResult) { static auto fn = UObject::FindObject<UFunction>("Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.BndEvt__EnemyDetectionRadius_K2Node_ComponentBoundEvent_327_ComponentBeginOverlapSignature__DelegateSignature"); ABP_EnemyScalingSpawn_C_BndEvt__EnemyDetectionRadius_K2Node_ComponentBoundEvent_327_ComponentBeginOverlapSignature__DelegateSignature_Params params; params.OverlappedComponent = OverlappedComponent; params.OtherActor = OtherActor; params.OtherComp = OtherComp; params.OtherBodyIndex = OtherBodyIndex; params.bFromSweep = bFromSweep; params.SweepResult = SweepResult; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.BndEvt__EnemyDetectionRadius_K2Node_ComponentBoundEvent_351_ComponentEndOverlapSignature__DelegateSignature // (BlueprintEvent) // Parameters: // class UPrimitiveComponent* OverlappedComponent (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // class AActor* OtherActor (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // class UPrimitiveComponent* OtherComp (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData, NoDestructor, HasGetValueTypeHash) // int OtherBodyIndex (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void ABP_EnemyScalingSpawn_C::BndEvt__EnemyDetectionRadius_K2Node_ComponentBoundEvent_351_ComponentEndOverlapSignature__DelegateSignature(class UPrimitiveComponent* OverlappedComponent, class AActor* OtherActor, class UPrimitiveComponent* OtherComp, int OtherBodyIndex) { static auto fn = UObject::FindObject<UFunction>("Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.BndEvt__EnemyDetectionRadius_K2Node_ComponentBoundEvent_351_ComponentEndOverlapSignature__DelegateSignature"); ABP_EnemyScalingSpawn_C_BndEvt__EnemyDetectionRadius_K2Node_ComponentBoundEvent_351_ComponentEndOverlapSignature__DelegateSignature_Params params; params.OverlappedComponent = OverlappedComponent; params.OtherActor = OtherActor; params.OtherComp = OtherComp; params.OtherBodyIndex = OtherBodyIndex; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.ExecuteUbergraph_BP_EnemyScalingSpawn // (Final, HasDefaults) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash) void ABP_EnemyScalingSpawn_C::ExecuteUbergraph_BP_EnemyScalingSpawn(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function BP_EnemyScalingSpawn.BP_EnemyScalingSpawn_C.ExecuteUbergraph_BP_EnemyScalingSpawn"); ABP_EnemyScalingSpawn_C_ExecuteUbergraph_BP_EnemyScalingSpawn_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
47.277419
326
0.768968
[ "object" ]
414e82c6aff19a4081cc10ecc02963ad394de84e
2,122
cpp
C++
src/Kmer_Bias.cpp
waltno/ArchR
e4d72c1b79abf7541ea10d4711c81626bf36f09e
[ "MIT" ]
214
2020-04-22T19:09:20.000Z
2022-03-31T09:50:49.000Z
src/Kmer_Bias.cpp
waltno/ArchR
e4d72c1b79abf7541ea10d4711c81626bf36f09e
[ "MIT" ]
741
2020-04-22T23:57:03.000Z
2022-03-31T15:36:07.000Z
src/Kmer_Bias.cpp
waltno/ArchR
e4d72c1b79abf7541ea10d4711c81626bf36f09e
[ "MIT" ]
83
2020-04-23T19:29:01.000Z
2022-03-25T18:00:14.000Z
#include <Rcpp.h> using namespace Rcpp; using namespace std; // [[Rcpp::export]] IntegerVector kmerIdxCpp(const std::string& str, const int window, const int n, CharacterVector &kmer){ CharacterVector result( window ); for ( int j = 0; j < window; j++ ){ result[j] = str.substr( j, n ); } IntegerVector out = match( result , kmer ); return out; } // [[Rcpp::export]] IntegerMatrix kmerPositionFrequencyCpp(StringVector &string_vector, IntegerVector &strand_vector, const int window, const int w, CharacterVector &kmer){ // Initialize Matrix IntegerMatrix out = IntegerMatrix(kmer.size(),window); rownames(out) = kmer; // Get Constants int n = string_vector.size(); std::string str_i; //Simple Vector for Storing matches IntegerVector m(window); for(int i=0; i<n; i++){ str_i = string_vector[i]; // Match Kmer over window m = kmerIdxCpp(str_i,window,w,kmer); for(int j = 0; j < window; j++){ if(!IntegerVector::is_na(m[j])){ if(strand_vector[i] == 2){ // Minus Stranded out( m[j] - 1, window - j - 1) = out( m[j] - 1, window - j - 1) + 1; }else{ // Other / Plus Stranded out( m[j] - 1, j) = out( m[j] - 1, j) + 1; } } } } return out; } // [[Rcpp::export]] IntegerMatrix kmerIDFrequencyCpp(StringVector &string_vector, IntegerVector &id_vector, const int n_id, const int window, const int w, CharacterVector &kmer){ // Initialize Matrix IntegerMatrix out = IntegerMatrix(kmer.size() , n_id); rownames(out) = kmer; // Get Constants int n = string_vector.size(); std::string str_i; int id_i; //Simple Vector for Storing matches IntegerVector m(window); for(int i = 0; i < n; i++){ str_i = string_vector[i]; id_i = id_vector[i]; // Match Kmer over window m = kmerIdxCpp(str_i, window, w, kmer); // Add Matched Value if not NA ie containing an N for(int j = 0; j < window; j++){ if(!IntegerVector::is_na(m[j])){ out(m[j] - 1, id_i - 1) = out(m[j] - 1, id_i - 1) + 1; } } } return out; }
21.434343
158
0.604147
[ "vector" ]
a991bcb36ce19fc45245b6f812f57a207b8796be
454
cpp
C++
kattis_done/datum.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
5
2019-03-17T01:33:19.000Z
2021-06-25T09:50:45.000Z
kattis_done/datum.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
kattis_done/datum.cpp
heiseish/Competitive-Programming
e4dd4db83c38e8837914562bc84bc8c102e68e34
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { time_t rawtime; int d, m; cin >> d >> m; vector<string> dd { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; struct tm * t; time ( &rawtime ); t = localtime ( &rawtime ); t->tm_year = 2009 - 1900; t->tm_mon = m - 1; t->tm_mday = d; mktime(t); cout << dd[t->tm_wday] << endl; return 0; }
23.894737
63
0.506608
[ "vector" ]
a99668dcf48694cd5e7622df61c631c5501c9509
10,529
cpp
C++
android/library/WhirlyGlobeLib/src/BillboardManager.cpp
freebird-airlines/WhirlyGlobe
3e1dd7cf27654558caeb1c5a2c8616bc1a3dbbb4
[ "Apache-2.0" ]
2
2019-05-16T18:52:21.000Z
2020-10-10T14:08:53.000Z
android/library/WhirlyGlobeLib/src/BillboardManager.cpp
freebird-airlines/WhirlyGlobe
3e1dd7cf27654558caeb1c5a2c8616bc1a3dbbb4
[ "Apache-2.0" ]
null
null
null
android/library/WhirlyGlobeLib/src/BillboardManager.cpp
freebird-airlines/WhirlyGlobe
3e1dd7cf27654558caeb1c5a2c8616bc1a3dbbb4
[ "Apache-2.0" ]
1
2020-10-22T12:09:24.000Z
2020-10-22T12:09:24.000Z
/* * BillboardManager.cpp * WhirlyGlobeLib * * Created by jmnavarro * Copyright 2011-2016 mousebird consulting * * 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 "BillboardManager.h" #include "WhirlyKitLog.h" using namespace Eigen; namespace WhirlyKit { SingleBillboardPoly::SingleBillboardPoly() : color(255,255,255,255), texId(EmptyIdentity) { } BillboardInfo::BillboardInfo() : billboardId(EmptyIdentity), color(RGBAColor()), zBufferRead(false), zBufferWrite(false) { } Billboard::Billboard() : center(Point3d(0,0,0)), size(Point2d(0,0)), isSelectable(false), selectID(EmptyIdentity) { } BillboardSceneRep::BillboardSceneRep() { } BillboardSceneRep::BillboardSceneRep(SimpleIdentity inId) : Identifiable(inId) { } BillboardSceneRep::~BillboardSceneRep() { } void BillboardSceneRep::clearContents(SelectionManager *selectManager,ChangeSet &changes,TimeInterval when) { for (const auto it: drawIDs){ changes.push_back(new RemDrawableReq(it,when)); } if (selectManager && !selectIDs.empty()){ selectManager->removeSelectables(selectIDs); } } BillboardDrawableBuilder::BillboardDrawableBuilder(Scene *scene,ChangeSet &changes,BillboardSceneRep *sceneRep,BillboardInfo *billInfo,SimpleIdentity billboardProgram,SimpleIdentity texId) : scene(scene), changes(changes), sceneRep(sceneRep), billInfo(billInfo), drawable(NULL), billboardProgram(billboardProgram), texId(texId) { } BillboardDrawableBuilder::~BillboardDrawableBuilder() { flush(); } void BillboardDrawableBuilder::addBillboard(Point3d center, const Point2dVector &pts, const std::vector<WhirlyKit::TexCoord> &texCoords, const WhirlyKit::RGBAColor *inColor, const SingleVertexAttributeSet &vertAttrs) { if (pts.size() != 4) { // NSLog(@"Only expecting 4 point polygons in BillboardDrawableBuilder"); return; } CoordSystemDisplayAdapter *coordAdapter = scene->getCoordAdapter(); // Get the drawable ready if (!drawable || !drawable->compareVertexAttributes(vertAttrs) || (drawable->getNumPoints()+4 > MaxDrawablePoints) || (drawable->getNumTris()+2 > MaxDrawableTriangles)) { if (drawable) flush(); drawable = new BillboardDrawable(); // drawMbr.reset(); drawable->setType(GL_TRIANGLES); billInfo->setupBasicDrawable(drawable); drawable->setProgram(billboardProgram); drawable->setTexId(0,texId); drawable->setRequestZBuffer(billInfo->zBufferRead); drawable->setWriteZBuffer(billInfo->zBufferWrite); drawable->setDrawPriority(billInfo->drawPriority); if (!vertAttrs.empty()) { SingleVertexAttributeInfoSet vertInfoSet; VertexAttributeSetConvert(vertAttrs,vertInfoSet); drawable->setVertexAttributes(vertInfoSet); } // drawable->setForceZBufferOn(true); } RGBAColor color = (inColor ? *inColor : billInfo->color); Point3d centerOnSphere = center; double len = sqrt(centerOnSphere.x()*centerOnSphere.x() + centerOnSphere.y()*centerOnSphere.y() + centerOnSphere.z()*centerOnSphere.z()); if (len != 0.0) centerOnSphere /= len; // Normal is straight up Point3d localPt = coordAdapter->displayToLocal(centerOnSphere); Point3d axisY = coordAdapter->normalForLocal(localPt); int startPoint = drawable->getNumPoints(); for (unsigned int ii=0;ii<4;ii++) { drawable->addPoint(center); drawable->addOffset(Point3d(pts[ii].x(),pts[ii].y(),0.0)); drawable->addTexCoord(0,texCoords[ii]); drawable->addNormal(axisY); drawable->addColor(color); if (!vertAttrs.empty()) drawable->addVertexAttributes(vertAttrs); } drawable->addTriangle(BasicDrawable::Triangle(startPoint+0,startPoint+1,startPoint+2)); drawable->addTriangle(BasicDrawable::Triangle(startPoint+0,startPoint+2,startPoint+3)); } void BillboardDrawableBuilder::flush() { if (drawable) { if (drawable->getNumPoints() > 0) { // drawable->setLocalMbr(drawMbr); sceneRep->drawIDs.insert(drawable->getId()); // TODO Port (fade isn't supported yet) // if (billInfo.fade > 0.0) // { // TimeInterval curTime = CFAbsoluteTimeGetCurrent(); // drawable->setFade(curTime, curTime+billInfo.fade); // } changes.push_back(new AddDrawableReq(drawable)); } else delete drawable; drawable = NULL; } } BillboardManager::BillboardManager() { pthread_mutex_init(&billLock, NULL); } BillboardManager::~BillboardManager() { pthread_mutex_destroy(&billLock); for (BillboardSceneRepSet::iterator it = sceneReps.begin(); it != sceneReps.end(); ++it) delete *it; sceneReps.clear(); } typedef std::map<SimpleIdentity,BillboardDrawableBuilder *> BuilderMap; /// Add billboards for display SimpleIdentity BillboardManager::addBillboards(std::vector<Billboard*> billboards,BillboardInfo *billboardInfo,SimpleIdentity billShader,ChangeSet &changes) { SelectionManager *selectManager = (SelectionManager *)scene->getManager(kWKSelectionManager); BillboardSceneRep *sceneRep = new BillboardSceneRep(); sceneRep->fade = billboardInfo->fade; CoordSystemDisplayAdapter *coordAdapter = scene->getCoordAdapter(); // One builder per texture BuilderMap drawBuilders; // Work through the billboards, constructing as we go for (Billboard *billboard : billboards) { // Work through the individual polygons for (const SingleBillboardPoly &billPoly : billboard->polys) { BuilderMap::iterator it = drawBuilders.find(billPoly.texId); BillboardDrawableBuilder *drawBuilder = NULL; // Need a new one if (it == drawBuilders.end()) { drawBuilder = new BillboardDrawableBuilder(scene,changes,sceneRep,billboardInfo,billShader,billPoly.texId); drawBuilders[billPoly.texId] = drawBuilder; } else drawBuilder = it->second; drawBuilder->addBillboard(billboard->center, billPoly.pts, billPoly.texCoords, &billPoly.color, billPoly.vertexAttrs); } // While we're at it, let's add this to the selection layer if (selectManager && billboard->isSelectable) { // If the marker doesn't already have an ID, it needs one if (!billboard->selectID) billboard->selectID = Identifiable::genId(); sceneRep->selectIDs.insert(billboard->selectID); // Normal is straight up Point3d localPt = coordAdapter->displayToLocal(billboard->center); Point3d axisY = coordAdapter->normalForLocal(localPt); selectManager->addSelectableBillboard(billboard->selectID, billboard->center, axisY, billboard->size, billboardInfo->minVis, billboardInfo->maxVis, billboardInfo->enable); } } // Flush out the changes and tear down the builders for (BuilderMap::iterator it = drawBuilders.begin(); it != drawBuilders.end(); ++it) { BillboardDrawableBuilder *drawBuilder = it->second; drawBuilder->flush(); delete drawBuilder; } drawBuilders.clear(); SimpleIdentity billID = sceneRep->getId(); pthread_mutex_lock(&billLock); sceneReps.insert(sceneRep); pthread_mutex_unlock(&billLock); return billID; } void BillboardManager::enableBillboards(SimpleIDSet &billIDs,bool enable,ChangeSet &changes) { SelectionManager *selectManager = (SelectionManager *)scene->getManager(kWKSelectionManager); pthread_mutex_lock(&billLock); for (SimpleIDSet::iterator bit = billIDs.begin();bit != billIDs.end();++bit) { BillboardSceneRep dummyRep(*bit); BillboardSceneRepSet::iterator it = sceneReps.find(&dummyRep); if (it != sceneReps.end()) { BillboardSceneRep *billRep = *it; for (SimpleIDSet::iterator dit = billRep->drawIDs.begin(); dit != billRep->drawIDs.end(); ++dit) changes.push_back(new OnOffChangeRequest((*dit), enable)); if (selectManager && !billRep->selectIDs.empty()) selectManager->enableSelectables(billRep->selectIDs, enable); } } pthread_mutex_unlock(&billLock); } /// Remove a group of billboards named by the given ID void BillboardManager::removeBillboards(SimpleIDSet &billIDs,ChangeSet &changes) { SelectionManager *selectManager = (SelectionManager *)scene->getManager(kWKSelectionManager); pthread_mutex_lock(&billLock); TimeInterval curTime = TimeGetCurrent(); for (SimpleIDSet::iterator bit = billIDs.begin();bit != billIDs.end();++bit) { BillboardSceneRep dummyRep(*bit); BillboardSceneRepSet::iterator it = sceneReps.find(&dummyRep); if (it != sceneReps.end()) { BillboardSceneRep *sceneRep = *it; TimeInterval removeTime = 0.0; if (sceneRep->fade > 0.0) { for (SimpleIDSet::iterator it = sceneRep->drawIDs.begin(); it != sceneRep->drawIDs.end(); ++it) changes.push_back(new FadeChangeRequest(*it, curTime, curTime+sceneRep->fade)); removeTime = curTime + sceneRep->fade; } sceneRep->clearContents(selectManager,changes,removeTime); sceneReps.erase(it); delete sceneRep; } } pthread_mutex_unlock(&billLock); } }
33.110063
216
0.645265
[ "vector" ]
a9968ea848851e05d21d07f4a396d25da9c5cd93
916
cpp
C++
Data_structures/Priority Queue/Argus.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
3
2017-08-12T06:09:39.000Z
2018-09-16T02:31:27.000Z
Data_structures/Priority Queue/Argus.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
Data_structures/Priority Queue/Argus.cpp
satvik007/uva
72a763f7ed46a34abfcf23891300d68581adeb44
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; typedef vector <int> vi; typedef pair<int, int> ii; class satvik { public: bool operator() (ii a, ii b) { if(a.second > b.second) return true; if(a.second == b.second && a.first > b.first) return true; return false; } }; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); //freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); priority_queue <ii, vector <ii> , satvik> a; vector <int> b(3001); string line; int n1, n2; while(cin >> line){ if(line == "#") break; cin >> n1 >> n2; b[n1] = n2; ii temp = {n1, n2}; a.push(temp); } int n; cin >> n; while(n--){ cout << a.top().first << "\n"; ii temp = a.top(); a.pop(); temp.second += b[temp.first]; a.push(temp); } return 0; }
21.302326
66
0.498908
[ "vector" ]
a99b970afafe04312cd7c28098c5e68a2fc4aab5
3,011
cpp
C++
training/Codeforces/123D.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
training/Codeforces/123D.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
training/Codeforces/123D.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
// written at 19:27 on 18 Mar 2017 #include <bits/stdc++.h> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".ans", "w", stdout); #define resetfile() freopen("/dev/tty", "r", stdin); freopen("/dev/tty", "w", stdout); system("more " filename".ans"); #define rep(i, j, k) for (int i = j; i < k; ++i) #define irep(i, j, k) for (int i = j - 1; i >= k; --i) using namespace std; template <typename T> inline T sqr(T a) { return a * a;}; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const ll LLINF = LLONG_MAX; const int MAX_N = 1e5 + 10; string S; int n, k; int lcp[MAX_N], sa[MAX_N]; int rnk[MAX_N], tmp[MAX_N]; bool compare_sa(int i, int j) { if (rnk[i] != rnk[j]) return rnk[i] < rnk[j]; else { int ri = i + k <= n? rnk[i + k] : -1; int rj = j + k <= n? rnk[j + k] : -1; return ri < rj; } } void construct_sa(string S, int *sa) { n = S.length(); for (int i = 0; i <= n; i++) { sa[i] = i; rnk[i] = i < n? S[i] : -1; } for (k = 1; k <= n; k *= 2) { sort(sa, sa + n + 1, compare_sa); tmp[sa[0]] = 0; for (int i = 1; i <= n; i++) tmp[sa[i]] = tmp[sa[i - 1]] + (compare_sa(sa[i - 1], sa[i]) ? 1 : 0); memcpy(rnk, tmp, sizeof(int) * (n + 1)); } } void construct_lcp(string S, int *sa, int *lcp) { for (int i = 0; i <= n; i++) rnk[sa[i]] = i; int h = 0; lcp[0] = 0; for (int i = 0; i < n; i++) { int j = sa[rnk[i] - 1]; if (h > 0) h--; for (; j + h < n && i + h < n; h++) if (S[j + h] != S[i + h]) break; lcp[rnk[i] - 1] = h; } } inline ll cnt(ll n) { return n * (n + 1) / 2; } int main() { cin >> S; construct_sa(S, sa); construct_lcp(S, sa, lcp); // for (int i = 0; i <= n; i++) // cout << S.substr(sa[i]) << endl; // for (int i = 0; i <= n; i++) // cout << sa[i] << " "; // cout << endl; // for (int i = 0; i <= n; i++) // cout << lcp[i] << " "; // cout << endl; vector<pair<Pii, int> > v; // height, len, id; ll ans = 0; for (int i = 1; i <= n + 1; i++) { while (!v.empty() && v.back().first.second > lcp[i - 1]) { auto &end = v.back(); if (end.first.first < lcp[i - 1]) { ans += (end.first.second - lcp[i - 1]) * cnt(i - end.second); end.first.second = lcp[i - 1]; } else { ans += (end.first.second - end.first.first) * cnt(i - end.second); v.pop_back(); } } v.push_back({{lcp[i - 1], n - sa[i]}, i}); } cout << ans << endl; return 0; }
28.40566
118
0.473265
[ "vector" ]
a9ab9562edddf4fa4ff5d1f5bc9e2b454ee17df4
21,864
cpp
C++
TowerDefense/Intermediate/Plugins/NativizedAssets/Windows/Game/Intermediate/Build/Win64/UE4/Inc/NativizedAssets/EnemyDamagePopup__pf3166771619.gen.cpp
Samuel-Rubin621/CS498
ab045b5bd888e0a0a61faccc11ed8f8a56e8219e
[ "CC0-1.0" ]
null
null
null
TowerDefense/Intermediate/Plugins/NativizedAssets/Windows/Game/Intermediate/Build/Win64/UE4/Inc/NativizedAssets/EnemyDamagePopup__pf3166771619.gen.cpp
Samuel-Rubin621/CS498
ab045b5bd888e0a0a61faccc11ed8f8a56e8219e
[ "CC0-1.0" ]
null
null
null
TowerDefense/Intermediate/Plugins/NativizedAssets/Windows/Game/Intermediate/Build/Win64/UE4/Inc/NativizedAssets/EnemyDamagePopup__pf3166771619.gen.cpp
Samuel-Rubin621/CS498
ab045b5bd888e0a0a61faccc11ed8f8a56e8219e
[ "CC0-1.0" ]
null
null
null
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "NativizedAssets/Public/EnemyDamagePopup__pf3166771619.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeEnemyDamagePopup__pf3166771619() {} // Cross Module References NATIVIZEDASSETS_API UClass* Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_NoRegister(); NATIVIZEDASSETS_API UClass* Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619(); UMG_API UClass* Z_Construct_UClass_UUserWidget(); SLATECORE_API UScriptStruct* Z_Construct_UScriptStruct_FGeometry(); UMG_API UClass* Z_Construct_UClass_UWidgetAnimation_NoRegister(); TOWERDEFENSE_API UClass* Z_Construct_UClass_ADefaultEnemy_NoRegister(); COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FVector2D(); // End Cross Module References DEFINE_FUNCTION(UEnemyDamagePopup_C__pf3166771619::execbpf__Construct__pf) { P_FINISH; P_NATIVE_BEGIN; P_THIS->bpf__Construct__pf(); P_NATIVE_END; } DEFINE_FUNCTION(UEnemyDamagePopup_C__pf3166771619::execbpf__Tick__pf) { P_GET_STRUCT(FGeometry,Z_Param_bpp__MyGeometry__pf); P_GET_PROPERTY(FFloatProperty,Z_Param_bpp__InDeltaTime__pf); P_FINISH; P_NATIVE_BEGIN; P_THIS->bpf__Tick__pf(Z_Param_bpp__MyGeometry__pf,Z_Param_bpp__InDeltaTime__pf); P_NATIVE_END; } static FName NAME_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf = FName(TEXT("Construct")); void UEnemyDamagePopup_C__pf3166771619::eventbpf__Construct__pf() { ProcessEvent(FindFunctionChecked(NAME_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf),NULL); } static FName NAME_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf = FName(TEXT("Tick")); void UEnemyDamagePopup_C__pf3166771619::eventbpf__Tick__pf(FGeometry bpp__MyGeometry__pf, float bpp__InDeltaTime__pf) { EnemyDamagePopup_C__pf3166771619_eventbpf__Tick__pf_Parms Parms; Parms.bpp__MyGeometry__pf=bpp__MyGeometry__pf; Parms.bpp__InDeltaTime__pf=bpp__InDeltaTime__pf; ProcessEvent(FindFunctionChecked(NAME_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf),&Parms); } void UEnemyDamagePopup_C__pf3166771619::StaticRegisterNativesUEnemyDamagePopup_C__pf3166771619() { UClass* Class = UEnemyDamagePopup_C__pf3166771619::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "Construct", &UEnemyDamagePopup_C__pf3166771619::execbpf__Construct__pf }, { "Tick", &UEnemyDamagePopup_C__pf3166771619::execbpf__Tick__pf }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf_Statics { #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf_Statics::Function_MetaDataParams[] = { { "Category", "User Interface" }, { "Comment", "/**t * Called after the underlying slate widget is constructed. Depending on how the slate object is usedt * this event may be called multiple times due to adding and removing from the hierarchy.t * If you need a true called-once-when-created event, use OnInitialized.t */" }, { "CppFromBpEvent", "" }, { "Keywords", "Begin Play" }, { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "OverrideNativeName", "Construct" }, { "ToolTip", "Called after the underlying slate widget is constructed. Depending on how the slate object is usedthis event may be called multiple times due to adding and removing from the hierarchy.If you need a true called-once-when-created event, use OnInitialized." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619, nullptr, "Construct", nullptr, nullptr, 0, nullptr, 0, RF_Public|RF_Transient, (EFunctionFlags)0x00020C08, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf() { UObject* Outer = Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619(); UFunction* ReturnFunction = static_cast<UFunction*>(StaticFindObjectFast( UFunction::StaticClass(), Outer, "Construct" )); if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics { static const UE4CodeGen_Private::FStructPropertyParams NewProp_bpp__MyGeometry__pf; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_bpp__InDeltaTime__pf; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::NewProp_bpp__MyGeometry__pf = { "bpp__MyGeometry__pf", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient, 1, STRUCT_OFFSET(EnemyDamagePopup_C__pf3166771619_eventbpf__Tick__pf_Parms, bpp__MyGeometry__pf), Z_Construct_UScriptStruct_FGeometry, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::NewProp_bpp__InDeltaTime__pf = { "bpp__InDeltaTime__pf", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient, 1, STRUCT_OFFSET(EnemyDamagePopup_C__pf3166771619_eventbpf__Tick__pf_Parms, bpp__InDeltaTime__pf), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::NewProp_bpp__MyGeometry__pf, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::NewProp_bpp__InDeltaTime__pf, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::Function_MetaDataParams[] = { { "Category", "User Interface" }, { "Comment", "/**t * Ticks this widget. Override in derived classes, but always call the parent implementation.t *t * @param MyGeometry The space allotted for this widgett * @param InDeltaTime Real time passed since last tickt */" }, { "CppFromBpEvent", "" }, { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "OverrideNativeName", "Tick" }, { "ToolTip", "Ticks this widget. Override in derived classes, but always call the parent implementation.@param MyGeometry The space allotted for this widget@param InDeltaTime Real time passed since last tick" }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619, nullptr, "Tick", nullptr, nullptr, sizeof(EnemyDamagePopup_C__pf3166771619_eventbpf__Tick__pf_Parms), Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::PropPointers), RF_Public|RF_Transient, (EFunctionFlags)0x00020C08, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf() { UObject* Outer = Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619(); UFunction* ReturnFunction = static_cast<UFunction*>(StaticFindObjectFast( UFunction::StaticClass(), Outer, "Tick" )); if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_NoRegister() { return UEnemyDamagePopup_C__pf3166771619::StaticClass(); } struct Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bpv__MoveAndFadeText__pf_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_bpv__MoveAndFadeText__pf; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bpv__Enemy__pf_MetaData[]; #endif static const UE4CodeGen_Private::FObjectPropertyParams NewProp_bpv__Enemy__pf; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_bpv__AnimationLength__pf_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_bpv__AnimationLength__pf; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_b0l__K2Node_Event_MyGeometry__pf_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_b0l__K2Node_Event_MyGeometry__pf; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_b0l__K2Node_Event_InDeltaTime__pf_MetaData[]; #endif static const UE4CodeGen_Private::FFloatPropertyParams NewProp_b0l__K2Node_Event_InDeltaTime__pf; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam NewProp_b0l__CallFunc_ProjectWorldLocationToScreen_ScreenLocation__pf_MetaData[]; #endif static const UE4CodeGen_Private::FStructPropertyParams NewProp_b0l__CallFunc_ProjectWorldLocationToScreen_ScreenLocation__pf; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UUserWidget, }; const FClassFunctionLinkInfo Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::FuncInfo[] = { { &Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Construct__pf, "Construct" }, // 4292805443 { &Z_Construct_UFunction_UEnemyDamagePopup_C__pf3166771619_bpf__Tick__pf, "Tick" }, // 2712144819 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::Class_MetaDataParams[] = { { "BlueprintType", "true" }, { "IncludePath", "EnemyDamagePopup__pf3166771619.h" }, { "IsBlueprintBase", "true" }, { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "ObjectInitializerConstructorDeclared", "" }, { "OverrideNativeName", "EnemyDamagePopup_C" }, { "ReplaceConverted", "/Game/UserInterface/EnemyDamagePopup.EnemyDamagePopup_C" }, }; #endif #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__MoveAndFadeText__pf_MetaData[] = { { "Category", "Animations" }, { "DisplayName", "MoveAndFadeText" }, { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "OverrideNativeName", "MoveAndFadeText" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__MoveAndFadeText__pf = { "MoveAndFadeText", nullptr, (EPropertyFlags)0x0010000000002014, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UEnemyDamagePopup_C__pf3166771619, bpv__MoveAndFadeText__pf), Z_Construct_UClass_UWidgetAnimation_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__MoveAndFadeText__pf_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__MoveAndFadeText__pf_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__Enemy__pf_MetaData[] = { { "Category", "Default" }, { "DisplayName", "Enemy" }, { "ExposeOnSpawn", "true" }, { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "MultiLine", "true" }, { "OverrideNativeName", "Enemy" }, }; #endif const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__Enemy__pf = { "Enemy", nullptr, (EPropertyFlags)0x0011000000000805, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UEnemyDamagePopup_C__pf3166771619, bpv__Enemy__pf), Z_Construct_UClass_ADefaultEnemy_NoRegister, METADATA_PARAMS(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__Enemy__pf_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__Enemy__pf_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__AnimationLength__pf_MetaData[] = { { "Category", "Default" }, { "DisplayName", "Animation Length" }, { "ExposeOnSpawn", "true" }, { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "MultiLine", "true" }, { "OverrideNativeName", "AnimationLength" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__AnimationLength__pf = { "AnimationLength", nullptr, (EPropertyFlags)0x0011000000000005, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UEnemyDamagePopup_C__pf3166771619, bpv__AnimationLength__pf), METADATA_PARAMS(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__AnimationLength__pf_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__AnimationLength__pf_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_MyGeometry__pf_MetaData[] = { { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "OverrideNativeName", "K2Node_Event_MyGeometry" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_MyGeometry__pf = { "K2Node_Event_MyGeometry", nullptr, (EPropertyFlags)0x0010000000202000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UEnemyDamagePopup_C__pf3166771619, b0l__K2Node_Event_MyGeometry__pf), Z_Construct_UScriptStruct_FGeometry, METADATA_PARAMS(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_MyGeometry__pf_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_MyGeometry__pf_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_InDeltaTime__pf_MetaData[] = { { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "OverrideNativeName", "K2Node_Event_InDeltaTime" }, }; #endif const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_InDeltaTime__pf = { "K2Node_Event_InDeltaTime", nullptr, (EPropertyFlags)0x0010000000202000, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UEnemyDamagePopup_C__pf3166771619, b0l__K2Node_Event_InDeltaTime__pf), METADATA_PARAMS(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_InDeltaTime__pf_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_InDeltaTime__pf_MetaData)) }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__CallFunc_ProjectWorldLocationToScreen_ScreenLocation__pf_MetaData[] = { { "ModuleRelativePath", "Public/EnemyDamagePopup__pf3166771619.h" }, { "OverrideNativeName", "CallFunc_ProjectWorldLocationToScreen_ScreenLocation" }, }; #endif const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__CallFunc_ProjectWorldLocationToScreen_ScreenLocation__pf = { "CallFunc_ProjectWorldLocationToScreen_ScreenLocation", nullptr, (EPropertyFlags)0x0010000000202000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(UEnemyDamagePopup_C__pf3166771619, b0l__CallFunc_ProjectWorldLocationToScreen_ScreenLocation__pf), Z_Construct_UScriptStruct_FVector2D, METADATA_PARAMS(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__CallFunc_ProjectWorldLocationToScreen_ScreenLocation__pf_MetaData, UE_ARRAY_COUNT(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__CallFunc_ProjectWorldLocationToScreen_ScreenLocation__pf_MetaData)) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__MoveAndFadeText__pf, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__Enemy__pf, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_bpv__AnimationLength__pf, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_MyGeometry__pf, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__K2Node_Event_InDeltaTime__pf, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::NewProp_b0l__CallFunc_ProjectWorldLocationToScreen_ScreenLocation__pf, }; const FCppClassTypeInfoStatic Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UEnemyDamagePopup_C__pf3166771619>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::ClassParams = { &UEnemyDamagePopup_C__pf3166771619::StaticClass, "Engine", &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::PropPointers, nullptr, UE_ARRAY_COUNT(DependentSingletons), UE_ARRAY_COUNT(FuncInfo), UE_ARRAY_COUNT(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::PropPointers), 0, 0x00A010A0u, METADATA_PARAMS(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619() { UPackage* OuterPackage = FindOrConstructDynamicTypePackage(TEXT("/Game/UserInterface/EnemyDamagePopup")); UClass* OuterClass = Cast<UClass>(StaticFindObjectFast(UClass::StaticClass(), OuterPackage, TEXT("EnemyDamagePopup_C"))); if (!OuterClass || !(OuterClass->ClassFlags & CLASS_Constructed)) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619_Statics::ClassParams); } return OuterClass; } IMPLEMENT_DYNAMIC_CLASS(UEnemyDamagePopup_C__pf3166771619, TEXT("EnemyDamagePopup_C"), 1199789601); template<> NATIVIZEDASSETS_API UClass* StaticClass<UEnemyDamagePopup_C__pf3166771619>() { return UEnemyDamagePopup_C__pf3166771619::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UEnemyDamagePopup_C__pf3166771619(Z_Construct_UClass_UEnemyDamagePopup_C__pf3166771619, &UEnemyDamagePopup_C__pf3166771619::StaticClass, TEXT("/Game/UserInterface/EnemyDamagePopup"), TEXT("EnemyDamagePopup_C"), true, TEXT("/Game/UserInterface/EnemyDamagePopup"), TEXT("/Game/UserInterface/EnemyDamagePopup.EnemyDamagePopup_C"), nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UEnemyDamagePopup_C__pf3166771619); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
76.985915
844
0.853
[ "object" ]
a9ae070245d9572921ffeda3c6fc1e4f985e7817
3,096
cpp
C++
visr_bear/pythonwrappers/dynamic_renderer.cpp
ebu/bear
0e4c4f33dfaea9b7c64991515177eb2099887a5a
[ "Apache-2.0" ]
14
2022-02-01T16:28:53.000Z
2022-02-11T11:24:59.000Z
visr_bear/pythonwrappers/dynamic_renderer.cpp
ebu/bear
0e4c4f33dfaea9b7c64991515177eb2099887a5a
[ "Apache-2.0" ]
1
2022-03-03T06:49:47.000Z
2022-03-15T13:10:43.000Z
visr_bear/pythonwrappers/dynamic_renderer.cpp
ebu/bear
0e4c4f33dfaea9b7c64991515177eb2099887a5a
[ "Apache-2.0" ]
null
null
null
#include "dynamic_renderer.hpp" #include <pybind11/numpy.h> #include <pybind11/pybind11.h> #include "array_conversion.hpp" #include "boost_variant.hpp" #include "config_impl.hpp" namespace bear { namespace python { namespace py = pybind11; void export_dynamic_renderer(pybind11::module &m) { using namespace ear; struct RendererWrapper : public DynamicRenderer { RendererWrapper(size_t block_size, size_t max_size) : DynamicRenderer(block_size, max_size), block_size(block_size) { } size_t block_size; }; py::class_<RendererWrapper>(m, "DynamicRenderer") .def(py::init<size_t, size_t>()) .def("set_config", &RendererWrapper::set_config) .def("set_config_blocking", &RendererWrapper::set_config_blocking) // pybind11 exception translation only applies to exceptions currently // being thrown, so this is the easiest way to wrap get_error .def("throw_error", [](RendererWrapper &r) { std::exception_ptr e = r.get_error(); if (e) std::rethrow_exception(e); }) .def("is_running", &RendererWrapper::is_running) .def("add_objects_block", &RendererWrapper::add_objects_block) .def("add_direct_speakers_block", &RendererWrapper::add_direct_speakers_block) .def("add_hoa_block", &RendererWrapper::add_hoa_block) .def( "process", [](RendererWrapper &r, py::array_t<float, 0> objects_input, py::array_t<float, 0> direct_speakers_input, py::array_t<float, 0> hoa_input, py::array_t<float, 0> output) { std::vector<float *> objects_input_ptrs = py_array_to_pointers_var(objects_input, r.block_size, "objects_input"); std::vector<float *> direct_speakers_input_ptrs = py_array_to_pointers_var(direct_speakers_input, r.block_size, "direct_speakers_input"); std::vector<float *> hoa_input_ptrs = py_array_to_pointers_var(hoa_input, r.block_size, "hoa_input"); std::vector<float *> output_ptrs = py_array_to_pointers(output, 2, r.block_size, "output"); r.process(objects_input_ptrs.size(), objects_input_ptrs.data(), direct_speakers_input_ptrs.size(), direct_speakers_input_ptrs.data(), hoa_input_ptrs.size(), hoa_input_ptrs.data(), output_ptrs.data()); }, py::arg("objects_input").noconvert(true), py::arg("direct_speakers_input").noconvert(true), py::arg("hoa_input").noconvert(true), py::arg("output").noconvert(true)) .def("get_block_start_time", &RendererWrapper::get_block_start_time) .def("set_block_start_time", &RendererWrapper::set_block_start_time) .def("set_listener", &RendererWrapper::set_listener); ; } } // namespace python } // namespace bear
40.207792
105
0.617571
[ "vector" ]
a9b7687d40fb3b5bf5e36eeccbc530ac404ef842
6,574
cc
C++
examples/kuka_iiwa_arm/kuka_torque_controller.cc
Brian-Acosta/dairlib
88da55d6e4378b93a787f3587d08b8a60f2f03f0
[ "BSD-3-Clause" ]
32
2019-04-15T03:10:26.000Z
2022-03-28T17:27:03.000Z
examples/kuka_iiwa_arm/kuka_torque_controller.cc
Brian-Acosta/dairlib
88da55d6e4378b93a787f3587d08b8a60f2f03f0
[ "BSD-3-Clause" ]
157
2019-02-21T03:13:57.000Z
2022-03-09T19:13:59.000Z
examples/kuka_iiwa_arm/kuka_torque_controller.cc
Brian-Acosta/dairlib
88da55d6e4378b93a787f3587d08b8a60f2f03f0
[ "BSD-3-Clause" ]
22
2019-03-02T22:31:42.000Z
2022-03-10T21:28:50.000Z
// A rewrite of Drake's kuka_torque_controller updated with a MultiBodyPlant. #include <utility> #include <vector> #include "drake/systems/controllers/inverse_dynamics.h" #include "drake/systems/controllers/pid_controller.h" #include "drake/systems/framework/diagram_builder.h" #include "drake/systems/framework/leaf_system.h" #include "drake/systems/primitives/adder.h" #include "drake/systems/primitives/constant_vector_source.h" #include "drake/systems/primitives/pass_through.h" #include "drake/multibody/plant/multibody_plant.h" #include "examples/kuka_iiwa_arm/kuka_torque_controller.h" namespace dairlib { namespace systems { using drake::systems::kVectorValued; using drake::systems::Adder; using drake::systems::BasicVector; using drake::systems::Context; using drake::systems::DiagramBuilder; using drake::systems::LeafSystem; using drake::systems::PassThrough; using drake::systems::controllers::InverseDynamics; using drake::systems::controllers::PidController; using drake::multibody::MultibodyPlant; using drake::VectorX; template <typename T> class StateDependentDamper : public LeafSystem<T> { public: StateDependentDamper(const MultibodyPlant<T>& plant, const VectorX<double>& stiffness, const VectorX<double>& damping_ratio) : plant_(plant), stiffness_(stiffness), damping_ratio_(damping_ratio) { const int num_q = plant_.num_positions(); const int num_v = plant_.num_velocities(); const int num_x = num_q + num_v; DRAKE_DEMAND(stiffness.size() == num_v); DRAKE_DEMAND(damping_ratio.size() == num_v); this->DeclareInputPort("x", kVectorValued, num_x); this->DeclareVectorOutputPort("u", BasicVector<T>(num_v), &StateDependentDamper<T>::CalcTorque); } private: const MultibodyPlant<T>& plant_; const VectorX<double> stiffness_; const VectorX<double> damping_ratio_; /** * Computes joint level damping forces by computing the damping ratio for each * joint independently as if all other joints were fixed. Note that the * effective inertia of a joint, when all of the other joints are fixed, is * given by the corresponding diagonal entry of the mass matrix. The critical * damping gain for the i-th joint is given by 2*sqrt(M(i,i)*stiffness(i)). */ void CalcTorque(const Context<T>& context, BasicVector<T>* torque) const { Eigen::VectorXd x = this->EvalVectorInput(context, 0)->get_value(); Eigen::VectorXd q = x.head(plant_.num_positions()); Eigen::VectorXd v = x.tail(plant_.num_velocities()); // Compute critical damping gains and scale by damping ratio. Use Eigen // arrays (rather than matrices) for elementwise multiplication. Eigen::MatrixXd H(plant_.num_positions(), plant_.num_positions()); std::unique_ptr<Context<double>> plant_context = plant_.CreateDefaultContext(); plant_.CalcMassMatrix(*plant_context.get(), &H); Eigen::ArrayXd temp = H.diagonal().array() * stiffness_.array(); Eigen::ArrayXd damping_gains = 2 * temp.sqrt(); damping_gains *= damping_ratio_.array(); // Compute damping torque. torque->get_mutable_value() = -(damping_gains * v.array()).matrix(); } }; template <typename T> void KukaTorqueController<T>::SetUp(const VectorX<double>& stiffness, const VectorX<double>& damping_ratio) { DiagramBuilder<T> builder; const MultibodyPlant<T>& plant = *robot_for_control_; DRAKE_DEMAND(plant.num_positions() == stiffness.size()); DRAKE_DEMAND(plant.num_positions() == damping_ratio.size()); const int dim = plant.num_positions(); /* torque_in ---------------------------- | (q, v) ------>|Gravity Comp|------+---> torque_out | /| --->|Damping|---------- | | | --->| Virtual Spring |--- (q*, v*) ------>|PID with kd=ki=0| */ // Redirects estimated state input into PID and gravity compensation. auto pass_through = builder.template AddSystem<PassThrough<T>>(2 * dim); // Add gravity compensator. auto gravity_comp = builder.template AddSystem<InverseDynamics<T>>( &plant, InverseDynamics<T>::kGravityCompensation); // Adds virtual springs. Eigen::VectorXd kd(dim); Eigen::VectorXd ki(dim); Eigen::VectorXd kp(dim); kd.setZero(); ki.setZero(); kp.setZero(); auto spring = builder.template AddSystem<PidController<T>>(kp, kd, ki); // Adds virtual damper. auto damper = builder.template AddSystem<StateDependentDamper<T>>( plant, stiffness, damping_ratio); // Adds an adder to sum the gravity compensation, spring, damper, and // feedforward torque. auto adder = builder.template AddSystem<Adder<T>>(4, dim); // Connects the estimated state to the gravity compensator. builder.Connect(pass_through->get_output_port(), gravity_comp->get_input_port_estimated_state()); // Connects the estimated state to the spring. builder.Connect(pass_through->get_output_port(), spring->get_input_port_estimated_state()); // Connects the estimated state to the damper. builder.Connect(pass_through->get_output_port(), damper->get_input_port(0)); // Connects the gravity compensation, spring, and damper torques to the adder. builder.Connect(gravity_comp->get_output_port_force(), adder->get_input_port(1)); builder.Connect(spring->get_output_port(0), adder->get_input_port(2)); builder.Connect(damper->get_output_port(0), adder->get_input_port(3)); // Exposes the estimated state port. input_port_index_estimated_state_ = builder.ExportInput(pass_through->get_input_port()); // Exposes the desired state port. input_port_index_desired_state_ = builder.ExportInput(spring->get_input_port_desired_state()); // Exposes the commanded torque port. input_port_index_commanded_torque_ = builder.ExportInput(adder->get_input_port(0)); // Exposes controller output. output_port_index_control_ = builder.ExportOutput(adder->get_output_port()); builder.BuildInto(this); } template <typename T> KukaTorqueController<T>::KukaTorqueController( std::unique_ptr<drake::multibody::MultibodyPlant<T>> plant, const VectorX<double>& stiffness, const VectorX<double>& damping) { robot_for_control_ = std::move(plant); SetUp(stiffness, damping); } template class dairlib::systems::KukaTorqueController<double>; } // namespace systems } // namespace dairlib
37.352273
97
0.69927
[ "vector" ]