hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 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 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6dbc9d8dd22509ff4db27d2772ea5578edde8380 | 218,510 | cpp | C++ | Extern/include/DirectXMath/SHMath/DirectXSH.cpp | waruqi/SakuraEngine | 443c5c2dcd25e83bf2e69756530754f41a277a40 | [
"MIT"
] | null | null | null | Extern/include/DirectXMath/SHMath/DirectXSH.cpp | waruqi/SakuraEngine | 443c5c2dcd25e83bf2e69756530754f41a277a40 | [
"MIT"
] | null | null | null | Extern/include/DirectXMath/SHMath/DirectXSH.cpp | waruqi/SakuraEngine | 443c5c2dcd25e83bf2e69756530754f41a277a40 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------------
// DirectXSH.cpp -- C++ Spherical Harmonics Math Library
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/p/?LinkId=262885
//-------------------------------------------------------------------------------------
#pragma warning( disable : 4619 4456 )
// C4619 #pragma warning warnings
// C4456 declaration hides previous local declaration
#ifdef __clang__
#pragma clang diagnostic ignored "-Wold-style-cast"
#pragma clang diagnostic ignored "-Wshadow"
#pragma clang diagnostic ignored "-Wunused-const-variable"
#pragma clang diagnostic ignored "-Wunused-function"
#endif
#include "DirectXSH.h"
#include <cassert>
using namespace DirectX;
namespace
{
#ifdef _PREFAST_
#pragma prefast(disable:246, "generated code by maple (nested const variable definitions)")
#endif
const float fExtraNormFac[XM_SH_MAXORDER] = { 2.0f*sqrtf(XM_PI), 2.0f / 3.0f*sqrtf(3.0f*XM_PI), 2.0f / 5.0f*sqrtf(5.0f*XM_PI), 2.0f / 7.0f*sqrtf(7.0f*XM_PI), 2.0f / 3.0f*sqrtf(XM_PI), 2.0f / 11.0f*sqrtf(11.0f*XM_PI) };
// computes the integral of a constant function over a solid angular
// extent. No error checking - only used internaly. This function
// only returns the Yl0 coefficients, since the rest are zero for
// circularly symmetric functions.
const float ComputeCapInt_t1 = sqrtf(0.3141593E1f);
const float ComputeCapInt_t5 = sqrtf(3.0f);
const float ComputeCapInt_t11 = sqrtf(5.0f);
const float ComputeCapInt_t18 = sqrtf(7.0f);
const float ComputeCapInt_t32 = sqrtf(11.0f);
inline void ComputeCapInt(const size_t order, float angle, float *pR)
{
const float t2 = cosf(angle);
const float t3 = ComputeCapInt_t1*t2;
const float t7 = sinf(angle);
const float t8 = t7*t7;
pR[0] = -t3 + ComputeCapInt_t1;
pR[1] = ComputeCapInt_t5*ComputeCapInt_t1*t8 / 2.0f;
if (order > 2)
{
const float t13 = t2*t2;
pR[2] = -ComputeCapInt_t11*ComputeCapInt_t1*t2*(t13 - 1.0f) / 2.0f;
if (order > 3)
{
const float t19 = ComputeCapInt_t18*ComputeCapInt_t1;
const float t20 = t13*t13;
pR[3] = -5.0f / 8.0f*t19*t20 + 3.0f / 4.0f*t19*t13 - t19 / 8.0f;
if (order > 4)
{
pR[4] = -3.0f / 8.0f*t3*(7.0f*t20 - 10.0f*t13 + 3.0f);
if (order > 5)
{
const float t33 = ComputeCapInt_t32*ComputeCapInt_t1;
pR[5] = -21.0f / 16.0f*t33*t20*t13 + 35.0f / 16.0f*t33*t20 - 15.0f / 16.0f*t33*t13 + t33 / 16.0f;
}
}
}
}
}
// input pF only consists of Yl0 values, normalizes coefficients for directional
// lights.
inline float CosWtInt(const size_t order)
{
const float fCW0 = 0.25f;
const float fCW1 = 0.5f;
const float fCW2 = 5.0f / 16.0f;
//const float fCW3 = 0.0f;
const float fCW4 = -3.0f / 32.0f;
//const float fCW5 = 0.0f;
// order has to be at least linear...
float fRet = fCW0 + fCW1;
if (order > 2) fRet += fCW2;
if (order > 4) fRet += fCW4;
// odd degrees >= 3 evaluate to zero integrated against cosine...
return fRet;
}
const float SHEvalHemisphereLight_fSqrtPi = sqrtf(XM_PI);
const float SHEvalHemisphereLight_fSqrtPi3 = sqrtf(XM_PI / 3.0f);
typedef float REAL;
#define CONSTANT(x) (x ## f)
// routine generated programmatically for evaluating SH basis for degree 1
// inputs (x,y,z) are a point on the sphere (i.e., must be unit length)
// output is vector b with SH basis evaluated at (x,y,z).
//
inline void sh_eval_basis_1(REAL x, REAL y, REAL z, REAL b[4])
{
/* m=0 */
// l=0
const REAL p_0_0 = CONSTANT(0.282094791773878140);
b[0] = p_0_0; // l=0,m=0
// l=1
const REAL p_1_0 = CONSTANT(0.488602511902919920)*z;
b[2] = p_1_0; // l=1,m=0
/* m=1 */
const REAL s1 = y;
const REAL c1 = x;
// l=1
const REAL p_1_1 = CONSTANT(-0.488602511902919920);
b[1] = p_1_1*s1; // l=1,m=-1
b[3] = p_1_1*c1; // l=1,m=+1
}
// routine generated programmatically for evaluating SH basis for degree 2
// inputs (x,y,z) are a point on the sphere (i.e., must be unit length)
// output is vector b with SH basis evaluated at (x,y,z).
//
inline void sh_eval_basis_2(REAL x, REAL y, REAL z, REAL b[9])
{
const REAL z2 = z*z;
/* m=0 */
// l=0
const REAL p_0_0 = CONSTANT(0.282094791773878140);
b[0] = p_0_0; // l=0,m=0
// l=1
const REAL p_1_0 = CONSTANT(0.488602511902919920)*z;
b[2] = p_1_0; // l=1,m=0
// l=2
const REAL p_2_0 = CONSTANT(0.946174695757560080)*z2 + CONSTANT(-0.315391565252520050);
b[6] = p_2_0; // l=2,m=0
/* m=1 */
const REAL s1 = y;
const REAL c1 = x;
// l=1
const REAL p_1_1 = CONSTANT(-0.488602511902919920);
b[1] = p_1_1*s1; // l=1,m=-1
b[3] = p_1_1*c1; // l=1,m=+1
// l=2
const REAL p_2_1 = CONSTANT(-1.092548430592079200)*z;
b[5] = p_2_1*s1; // l=2,m=-1
b[7] = p_2_1*c1; // l=2,m=+1
/* m=2 */
const REAL s2 = x*s1 + y*c1;
const REAL c2 = x*c1 - y*s1;
// l=2
const REAL p_2_2 = CONSTANT(0.546274215296039590);
b[4] = p_2_2*s2; // l=2,m=-2
b[8] = p_2_2*c2; // l=2,m=+2
}
// routine generated programmatically for evaluating SH basis for degree 3
// inputs (x,y,z) are a point on the sphere (i.e., must be unit length)
// output is vector b with SH basis evaluated at (x,y,z).
//
void sh_eval_basis_3(REAL x, REAL y, REAL z, REAL b[16])
{
const REAL z2 = z*z;
/* m=0 */
// l=0
const REAL p_0_0 = CONSTANT(0.282094791773878140);
b[0] = p_0_0; // l=0,m=0
// l=1
const REAL p_1_0 = CONSTANT(0.488602511902919920)*z;
b[2] = p_1_0; // l=1,m=0
// l=2
const REAL p_2_0 = CONSTANT(0.946174695757560080)*z2 + CONSTANT(-0.315391565252520050);
b[6] = p_2_0; // l=2,m=0
// l=3
const REAL p_3_0 = z*(CONSTANT(1.865881662950577000)*z2 + CONSTANT(-1.119528997770346200));
b[12] = p_3_0; // l=3,m=0
/* m=1 */
const REAL s1 = y;
const REAL c1 = x;
// l=1
const REAL p_1_1 = CONSTANT(-0.488602511902919920);
b[1] = p_1_1*s1; // l=1,m=-1
b[3] = p_1_1*c1; // l=1,m=+1
// l=2
const REAL p_2_1 = CONSTANT(-1.092548430592079200)*z;
b[5] = p_2_1*s1; // l=2,m=-1
b[7] = p_2_1*c1; // l=2,m=+1
// l=3
const REAL p_3_1 = CONSTANT(-2.285228997322328800)*z2 + CONSTANT(0.457045799464465770);
b[11] = p_3_1*s1; // l=3,m=-1
b[13] = p_3_1*c1; // l=3,m=+1
/* m=2 */
const REAL s2 = x*s1 + y*c1;
const REAL c2 = x*c1 - y*s1;
// l=2
const REAL p_2_2 = CONSTANT(0.546274215296039590);
b[4] = p_2_2*s2; // l=2,m=-2
b[8] = p_2_2*c2; // l=2,m=+2
// l=3
const REAL p_3_2 = CONSTANT(1.445305721320277100)*z;
b[10] = p_3_2*s2; // l=3,m=-2
b[14] = p_3_2*c2; // l=3,m=+2
/* m=3 */
const REAL s3 = x*s2 + y*c2;
const REAL c3 = x*c2 - y*s2;
// l=3
const REAL p_3_3 = CONSTANT(-0.590043589926643520);
b[9] = p_3_3*s3; // l=3,m=-3
b[15] = p_3_3*c3; // l=3,m=+3
}
// routine generated programmatically for evaluating SH basis for degree 4
// inputs (x,y,z) are a point on the sphere (i.e., must be unit length)
// output is vector b with SH basis evaluated at (x,y,z).
//
void sh_eval_basis_4(REAL x, REAL y, REAL z, REAL b[25])
{
const REAL z2 = z*z;
/* m=0 */
// l=0
const REAL p_0_0 = CONSTANT(0.282094791773878140);
b[0] = p_0_0; // l=0,m=0
// l=1
const REAL p_1_0 = CONSTANT(0.488602511902919920)*z;
b[2] = p_1_0; // l=1,m=0
// l=2
const REAL p_2_0 = CONSTANT(0.946174695757560080)*z2 + CONSTANT(-0.315391565252520050);
b[6] = p_2_0; // l=2,m=0
// l=3
const REAL p_3_0 = z*(CONSTANT(1.865881662950577000)*z2 + CONSTANT(-1.119528997770346200));
b[12] = p_3_0; // l=3,m=0
// l=4
const REAL p_4_0 = CONSTANT(1.984313483298443000)*z*p_3_0 + CONSTANT(-1.006230589874905300)*p_2_0;
b[20] = p_4_0; // l=4,m=0
/* m=1 */
const REAL s1 = y;
const REAL c1 = x;
// l=1
const REAL p_1_1 = CONSTANT(-0.488602511902919920);
b[1] = p_1_1*s1; // l=1,m=-1
b[3] = p_1_1*c1; // l=1,m=+1
// l=2
const REAL p_2_1 = CONSTANT(-1.092548430592079200)*z;
b[5] = p_2_1*s1; // l=2,m=-1
b[7] = p_2_1*c1; // l=2,m=+1
// l=3
const REAL p_3_1 = CONSTANT(-2.285228997322328800)*z2 + CONSTANT(0.457045799464465770);
b[11] = p_3_1*s1; // l=3,m=-1
b[13] = p_3_1*c1; // l=3,m=+1
// l=4
const REAL p_4_1 = z*(CONSTANT(-4.683325804901024000)*z2 + CONSTANT(2.007139630671867200));
b[19] = p_4_1*s1; // l=4,m=-1
b[21] = p_4_1*c1; // l=4,m=+1
/* m=2 */
const REAL s2 = x*s1 + y*c1;
const REAL c2 = x*c1 - y*s1;
// l=2
const REAL p_2_2 = CONSTANT(0.546274215296039590);
b[4] = p_2_2*s2; // l=2,m=-2
b[8] = p_2_2*c2; // l=2,m=+2
// l=3
const REAL p_3_2 = CONSTANT(1.445305721320277100)*z;
b[10] = p_3_2*s2; // l=3,m=-2
b[14] = p_3_2*c2; // l=3,m=+2
// l=4
const REAL p_4_2 = CONSTANT(3.311611435151459800)*z2 + CONSTANT(-0.473087347878779980);
b[18] = p_4_2*s2; // l=4,m=-2
b[22] = p_4_2*c2; // l=4,m=+2
/* m=3 */
const REAL s3 = x*s2 + y*c2;
const REAL c3 = x*c2 - y*s2;
// l=3
const REAL p_3_3 = CONSTANT(-0.590043589926643520);
b[9] = p_3_3*s3; // l=3,m=-3
b[15] = p_3_3*c3; // l=3,m=+3
// l=4
const REAL p_4_3 = CONSTANT(-1.770130769779930200)*z;
b[17] = p_4_3*s3; // l=4,m=-3
b[23] = p_4_3*c3; // l=4,m=+3
/* m=4 */
const REAL s4 = x*s3 + y*c3;
const REAL c4 = x*c3 - y*s3;
// l=4
const REAL p_4_4 = CONSTANT(0.625835735449176030);
b[16] = p_4_4*s4; // l=4,m=-4
b[24] = p_4_4*c4; // l=4,m=+4
}
// routine generated programmatically for evaluating SH basis for degree 5
// inputs (x,y,z) are a point on the sphere (i.e., must be unit length)
// output is vector b with SH basis evaluated at (x,y,z).
//
void sh_eval_basis_5(REAL x, REAL y, REAL z, REAL b[36])
{
const REAL z2 = z*z;
/* m=0 */
// l=0
const REAL p_0_0 = CONSTANT(0.282094791773878140);
b[0] = p_0_0; // l=0,m=0
// l=1
const REAL p_1_0 = CONSTANT(0.488602511902919920)*z;
b[2] = p_1_0; // l=1,m=0
// l=2
const REAL p_2_0 = CONSTANT(0.946174695757560080)*z2 + CONSTANT(-0.315391565252520050);
b[6] = p_2_0; // l=2,m=0
// l=3
const REAL p_3_0 = z*(CONSTANT(1.865881662950577000)*z2 + CONSTANT(-1.119528997770346200));
b[12] = p_3_0; // l=3,m=0
// l=4
const REAL p_4_0 = CONSTANT(1.984313483298443000)*z*p_3_0 + CONSTANT(-1.006230589874905300)*p_2_0;
b[20] = p_4_0; // l=4,m=0
// l=5
const REAL p_5_0 = CONSTANT(1.989974874213239700)*z*p_4_0 + CONSTANT(-1.002853072844814000)*p_3_0;
b[30] = p_5_0; // l=5,m=0
/* m=1 */
const REAL s1 = y;
const REAL c1 = x;
// l=1
const REAL p_1_1 = CONSTANT(-0.488602511902919920);
b[1] = p_1_1*s1; // l=1,m=-1
b[3] = p_1_1*c1; // l=1,m=+1
// l=2
const REAL p_2_1 = CONSTANT(-1.092548430592079200)*z;
b[5] = p_2_1*s1; // l=2,m=-1
b[7] = p_2_1*c1; // l=2,m=+1
// l=3
const REAL p_3_1 = CONSTANT(-2.285228997322328800)*z2 + CONSTANT(0.457045799464465770);
b[11] = p_3_1*s1; // l=3,m=-1
b[13] = p_3_1*c1; // l=3,m=+1
// l=4
const REAL p_4_1 = z*(CONSTANT(-4.683325804901024000)*z2 + CONSTANT(2.007139630671867200));
b[19] = p_4_1*s1; // l=4,m=-1
b[21] = p_4_1*c1; // l=4,m=+1
// l=5
const REAL p_5_1 = CONSTANT(2.031009601158990200)*z*p_4_1 + CONSTANT(-0.991031208965114650)*p_3_1;
b[29] = p_5_1*s1; // l=5,m=-1
b[31] = p_5_1*c1; // l=5,m=+1
/* m=2 */
const REAL s2 = x*s1 + y*c1;
const REAL c2 = x*c1 - y*s1;
// l=2
const REAL p_2_2 = CONSTANT(0.546274215296039590);
b[4] = p_2_2*s2; // l=2,m=-2
b[8] = p_2_2*c2; // l=2,m=+2
// l=3
const REAL p_3_2 = CONSTANT(1.445305721320277100)*z;
b[10] = p_3_2*s2; // l=3,m=-2
b[14] = p_3_2*c2; // l=3,m=+2
// l=4
const REAL p_4_2 = CONSTANT(3.311611435151459800)*z2 + CONSTANT(-0.473087347878779980);
b[18] = p_4_2*s2; // l=4,m=-2
b[22] = p_4_2*c2; // l=4,m=+2
// l=5
const REAL p_5_2 = z*(CONSTANT(7.190305177459987500)*z2 + CONSTANT(-2.396768392486662100));
b[28] = p_5_2*s2; // l=5,m=-2
b[32] = p_5_2*c2; // l=5,m=+2
/* m=3 */
const REAL s3 = x*s2 + y*c2;
const REAL c3 = x*c2 - y*s2;
// l=3
const REAL p_3_3 = CONSTANT(-0.590043589926643520);
b[9] = p_3_3*s3; // l=3,m=-3
b[15] = p_3_3*c3; // l=3,m=+3
// l=4
const REAL p_4_3 = CONSTANT(-1.770130769779930200)*z;
b[17] = p_4_3*s3; // l=4,m=-3
b[23] = p_4_3*c3; // l=4,m=+3
// l=5
const REAL p_5_3 = CONSTANT(-4.403144694917253700)*z2 + CONSTANT(0.489238299435250430);
b[27] = p_5_3*s3; // l=5,m=-3
b[33] = p_5_3*c3; // l=5,m=+3
/* m=4 */
const REAL s4 = x*s3 + y*c3;
const REAL c4 = x*c3 - y*s3;
// l=4
const REAL p_4_4 = CONSTANT(0.625835735449176030);
b[16] = p_4_4*s4; // l=4,m=-4
b[24] = p_4_4*c4; // l=4,m=+4
// l=5
const REAL p_5_4 = CONSTANT(2.075662314881041100)*z;
b[26] = p_5_4*s4; // l=5,m=-4
b[34] = p_5_4*c4; // l=5,m=+4
/* m=5 */
const REAL s5 = x*s4 + y*c4;
const REAL c5 = x*c4 - y*s4;
// l=5
const REAL p_5_5 = CONSTANT(-0.656382056840170150);
b[25] = p_5_5*s5; // l=5,m=-5
b[35] = p_5_5*c5; // l=5,m=+5
}
const REAL M_PIjs = (REAL)(4.0*atan(1.0));
const REAL maxang = (REAL)(M_PIjs / 2);
const int NSH0 = 1;
const int NSH1 = 4;
const int NSH2 = 9;
const int NSH3 = 16;
const int NSH4 = 25;
const int NSH5 = 36;
const int NSH6 = 49;
const int NSH7 = 64;
const int NSH8 = 81;
const int NSH9 = 100;
const int NL0 = 1;
const int NL1 = 3;
const int NL2 = 5;
const int NL3 = 7;
const int NL4 = 9;
const int NL5 = 11;
const int NL6 = 13;
const int NL7 = 15;
const int NL8 = 17;
const int NL9 = 19;
inline void rot(REAL ct, REAL st, REAL x, REAL y, REAL &xout, REAL &yout)
{
xout = x*ct - y*st;
yout = y*ct + x*st;
}
inline void rot_inv(REAL ct, REAL st, REAL x, REAL y, REAL &xout, REAL &yout)
{
xout = x*ct + y*st;
yout = y*ct - x*st;
}
inline void rot_1(REAL ct, REAL st, REAL ctm[1], REAL stm[1])
{
ctm[0] = ct;
stm[0] = st;
}
inline void rot_2(REAL ct, REAL st, REAL ctm[2], REAL stm[2])
{
REAL ct2 = CONSTANT(2.0)*ct;
ctm[0] = ct;
stm[0] = st;
ctm[1] = ct2*ct - CONSTANT(1.0);
stm[1] = ct2*st;
}
inline void rot_3(REAL ct, REAL st, REAL ctm[3], REAL stm[3])
{
REAL ct2 = CONSTANT(2.0)*ct;
ctm[0] = ct;
stm[0] = st;
ctm[1] = ct2*ct - CONSTANT(1.0);
stm[1] = ct2*st;
ctm[2] = ct2*ctm[1] - ct;
stm[2] = ct2*stm[1] - st;
}
inline void rot_4(REAL ct, REAL st, REAL ctm[4], REAL stm[4])
{
REAL ct2 = CONSTANT(2.0)*ct;
ctm[0] = ct;
stm[0] = st;
ctm[1] = ct2*ct - CONSTANT(1.0);
stm[1] = ct2*st;
ctm[2] = ct2*ctm[1] - ct;
stm[2] = ct2*stm[1] - st;
ctm[3] = ct2*ctm[2] - ctm[1];
stm[3] = ct2*stm[2] - stm[1];
}
inline void rot_5(REAL ct, REAL st, REAL ctm[5], REAL stm[5])
{
REAL ct2 = CONSTANT(2.0)*ct;
ctm[0] = ct;
stm[0] = st;
ctm[1] = ct2*ct - CONSTANT(1.0);
stm[1] = ct2*st;
ctm[2] = ct2*ctm[1] - ct;
stm[2] = ct2*stm[1] - st;
ctm[3] = ct2*ctm[2] - ctm[1];
stm[3] = ct2*stm[2] - stm[1];
ctm[4] = ct2*ctm[3] - ctm[2];
stm[4] = ct2*stm[3] - stm[2];
}
inline void sh_rotz_1(REAL ctm[1], REAL stm[1], REAL y[NL1], REAL yr[NL1])
{
yr[1] = y[1];
rot_inv(ctm[0], stm[0], y[0], y[2], yr[0], yr[2]);
}
inline void sh_rotz_2(REAL ctm[2], REAL stm[2], REAL y[NL2], REAL yr[NL2])
{
yr[2] = y[2];
rot_inv(ctm[0], stm[0], y[1], y[3], yr[1], yr[3]);
rot_inv(ctm[1], stm[1], y[0], y[4], yr[0], yr[4]);
}
inline void sh_rotz_3(REAL ctm[3], REAL stm[3], REAL y[NL3], REAL yr[NL3])
{
yr[3] = y[3];
rot_inv(ctm[0], stm[0], y[2], y[4], yr[2], yr[4]);
rot_inv(ctm[1], stm[1], y[1], y[5], yr[1], yr[5]);
rot_inv(ctm[2], stm[2], y[0], y[6], yr[0], yr[6]);
}
inline void sh_rotz_4(REAL ctm[4], REAL stm[4], REAL y[NL4], REAL yr[NL4])
{
yr[4] = y[4];
rot_inv(ctm[0], stm[0], y[3], y[5], yr[3], yr[5]);
rot_inv(ctm[1], stm[1], y[2], y[6], yr[2], yr[6]);
rot_inv(ctm[2], stm[2], y[1], y[7], yr[1], yr[7]);
rot_inv(ctm[3], stm[3], y[0], y[8], yr[0], yr[8]);
}
inline void sh_rotz_5(REAL ctm[5], REAL stm[5], REAL y[NL5], REAL yr[NL5])
{
yr[5] = y[5];
rot_inv(ctm[0], stm[0], y[4], y[6], yr[4], yr[6]);
rot_inv(ctm[1], stm[1], y[3], y[7], yr[3], yr[7]);
rot_inv(ctm[2], stm[2], y[2], y[8], yr[2], yr[8]);
rot_inv(ctm[3], stm[3], y[1], y[9], yr[1], yr[9]);
rot_inv(ctm[4], stm[4], y[0], y[10], yr[0], yr[10]);
}
// rotation code generated programmatically by rotatex (2000x4000 samples, eps=1e-008)
const REAL fx_1_001 = (REAL)(sqrt(1.0) / 1.0); // 1
const REAL fx_1_002 = (REAL)(-sqrt(1.0) / 1.0); // -1.00000030843
inline void sh_rotx90_1(REAL y[], REAL yr[])
{
yr[0] = fx_1_001*y[1];
yr[1] = fx_1_002*y[0];
yr[2] = fx_1_001*y[2];
};
inline void sh_rotx90_inv_1(REAL y[], REAL yr[])
{
yr[0] = fx_1_002*y[1];
yr[1] = fx_1_001*y[0];
yr[2] = fx_1_001*y[2];
}
const REAL fx_2_001 = (REAL)(sqrt(4.0) / 2.0); // 1
const REAL fx_2_002 = (REAL)(-sqrt(4.0) / 2.0); // -1
const REAL fx_2_003 = (REAL)(-sqrt(1.0) / 2.0); // -0.500000257021
const REAL fx_2_004 = (REAL)(-sqrt(3.0) / 2.0); // -0.866025848959
const REAL fx_2_005 = (REAL)(sqrt(1.0) / 2.0); // 0.5
inline void sh_rotx90_2(REAL y[], REAL yr[])
{
yr[0] = fx_2_001*y[3];
yr[1] = fx_2_002*y[1];
yr[2] = fx_2_003*y[2] + fx_2_004*y[4];
yr[3] = fx_2_002*y[0];
yr[4] = fx_2_004*y[2] + fx_2_005*y[4];
};
inline void sh_rotx90_inv_2(REAL y[], REAL yr[])
{
yr[0] = fx_2_002*y[3];
yr[1] = fx_2_002*y[1];
yr[2] = fx_2_003*y[2] + fx_2_004*y[4];
yr[3] = fx_2_001*y[0];
yr[4] = fx_2_004*y[2] + fx_2_005*y[4];
}
const REAL fx_3_001 = (REAL)(-sqrt(10.0) / 4.0); // -0.790569415042
const REAL fx_3_002 = (REAL)(sqrt(6.0) / 4.0); // 0.612372435696
const REAL fx_3_003 = (REAL)(-sqrt(16.0) / 4.0); // -1
const REAL fx_3_004 = (REAL)(-sqrt(6.0) / 4.0); // -0.612372435695
const REAL fx_3_005 = (REAL)(-sqrt(1.0) / 4.0); // -0.25
const REAL fx_3_006 = (REAL)(-sqrt(15.0) / 4.0); // -0.968245836551
const REAL fx_3_007 = (REAL)(sqrt(1.0) / 4.0); // 0.25
const REAL fx_3_008 = (REAL)(sqrt(10.0) / 4.0); // 0.790569983984
inline void sh_rotx90_3(REAL y[], REAL yr[])
{
yr[0] = fx_3_001*y[3] + fx_3_002*y[5];
yr[1] = fx_3_003*y[1];
yr[2] = fx_3_004*y[3] + fx_3_001*y[5];
yr[3] = fx_3_008*y[0] + fx_3_002*y[2];
yr[4] = fx_3_005*y[4] + fx_3_006*y[6];
yr[5] = fx_3_004*y[0] - fx_3_001*y[2];
yr[6] = fx_3_006*y[4] + fx_3_007*y[6];
};
inline void sh_rotx90_inv_3(REAL y[], REAL yr[])
{
yr[0] = fx_3_008*y[3] + fx_3_004*y[5];
yr[1] = fx_3_003*y[1];
yr[2] = fx_3_002*y[3] - fx_3_001*y[5];
yr[3] = fx_3_001*y[0] + fx_3_004*y[2];
yr[4] = fx_3_005*y[4] + fx_3_006*y[6];
yr[5] = fx_3_002*y[0] + fx_3_001*y[2];
yr[6] = fx_3_006*y[4] + fx_3_007*y[6];
}
const REAL fx_4_001 = (REAL)(-sqrt(56.0) / 8.0); // -0.935414346694
const REAL fx_4_002 = (REAL)(sqrt(8.0) / 8.0); // 0.353553390593
const REAL fx_4_003 = (REAL)(-sqrt(36.0) / 8.0); // -0.75
const REAL fx_4_004 = (REAL)(sqrt(28.0) / 8.0); // 0.661437827766
const REAL fx_4_005 = (REAL)(-sqrt(8.0) / 8.0); // -0.353553390593
const REAL fx_4_006 = (REAL)(sqrt(36.0) / 8.0); // 0.749999999999
const REAL fx_4_007 = (REAL)(sqrt(9.0) / 8.0); // 0.37500034698
const REAL fx_4_008 = (REAL)(sqrt(20.0) / 8.0); // 0.559017511622
const REAL fx_4_009 = (REAL)(sqrt(35.0) / 8.0); // 0.739510657141
const REAL fx_4_010 = (REAL)(sqrt(16.0) / 8.0); // 0.5
const REAL fx_4_011 = (REAL)(-sqrt(28.0) / 8.0); // -0.661437827766
const REAL fx_4_012 = (REAL)(sqrt(1.0) / 8.0); // 0.125
const REAL fx_4_013 = (REAL)(sqrt(56.0) / 8.0); // 0.935414346692
inline void sh_rotx90_4(REAL y[], REAL yr[])
{
yr[0] = fx_4_001*y[5] + fx_4_002*y[7];
yr[1] = fx_4_003*y[1] + fx_4_004*y[3];
yr[2] = fx_4_005*y[5] + fx_4_001*y[7];
yr[3] = fx_4_004*y[1] + fx_4_006*y[3];
yr[4] = fx_4_007*y[4] + fx_4_008*y[6] + fx_4_009*y[8];
yr[5] = fx_4_013*y[0] + fx_4_002*y[2];
yr[6] = fx_4_008*y[4] + fx_4_010*y[6] + fx_4_011*y[8];
yr[7] = fx_4_005*y[0] - fx_4_001*y[2];
yr[8] = fx_4_009*y[4] + fx_4_011*y[6] + fx_4_012*y[8];
};
inline void sh_rotx90_inv_4(REAL y[], REAL yr[])
{
yr[0] = fx_4_013*y[5] + fx_4_005*y[7];
yr[1] = fx_4_003*y[1] + fx_4_004*y[3];
yr[2] = fx_4_002*y[5] - fx_4_001*y[7];
yr[3] = fx_4_004*y[1] + fx_4_006*y[3];
yr[4] = fx_4_007*y[4] + fx_4_008*y[6] + fx_4_009*y[8];
yr[5] = fx_4_001*y[0] + fx_4_005*y[2];
yr[6] = fx_4_008*y[4] + fx_4_010*y[6] + fx_4_011*y[8];
yr[7] = fx_4_002*y[0] + fx_4_001*y[2];
yr[8] = fx_4_009*y[4] + fx_4_011*y[6] + fx_4_012*y[8];
}
const REAL fx_5_001 = (REAL)(sqrt(126.0) / 16.0); // 0.70156076002
const REAL fx_5_002 = (REAL)(-sqrt(120.0) / 16.0); // -0.684653196882
const REAL fx_5_003 = (REAL)(sqrt(10.0) / 16.0); // 0.197642353761
const REAL fx_5_004 = (REAL)(-sqrt(64.0) / 16.0); // -0.5
const REAL fx_5_005 = (REAL)(sqrt(192.0) / 16.0); // 0.866025403784
const REAL fx_5_006 = (REAL)(sqrt(70.0) / 16.0); // 0.522912516584
const REAL fx_5_007 = (REAL)(sqrt(24.0) / 16.0); // 0.306186217848
const REAL fx_5_008 = (REAL)(-sqrt(162.0) / 16.0); // -0.795495128835
const REAL fx_5_009 = (REAL)(sqrt(64.0) / 16.0); // 0.5
const REAL fx_5_010 = (REAL)(sqrt(60.0) / 16.0); // 0.484122918274
const REAL fx_5_011 = (REAL)(sqrt(112.0) / 16.0); // 0.661437827763
const REAL fx_5_012 = (REAL)(sqrt(84.0) / 16.0); // 0.572821961867
const REAL fx_5_013 = (REAL)(sqrt(4.0) / 16.0); // 0.125
const REAL fx_5_014 = (REAL)(sqrt(42.0) / 16.0); // 0.405046293649
const REAL fx_5_015 = (REAL)(sqrt(210.0) / 16.0); // 0.905711046633
const REAL fx_5_016 = (REAL)(sqrt(169.0) / 16.0); // 0.8125
const REAL fx_5_017 = (REAL)(-sqrt(45.0) / 16.0); // -0.419262745781
const REAL fx_5_018 = (REAL)(sqrt(1.0) / 16.0); // 0.0625
const REAL fx_5_019 = (REAL)(-sqrt(126.0) / 16.0); // -0.701561553415
const REAL fx_5_020 = (REAL)(sqrt(120.0) / 16.0); // 0.684653196881
const REAL fx_5_021 = (REAL)(-sqrt(10.0) / 16.0); // -0.197642353761
const REAL fx_5_022 = (REAL)(-sqrt(70.0) / 16.0); // -0.522913107945
const REAL fx_5_023 = (REAL)(-sqrt(60.0) / 16.0); // -0.48412346577
inline void sh_rotx90_5(REAL y[], REAL yr[])
{
yr[0] = fx_5_001*y[5] + fx_5_002*y[7] + fx_5_003*y[9];
yr[1] = fx_5_004*y[1] + fx_5_005*y[3];
yr[2] = fx_5_006*y[5] + fx_5_007*y[7] + fx_5_008*y[9];
yr[3] = fx_5_005*y[1] + fx_5_009*y[3];
yr[4] = fx_5_010*y[5] + fx_5_011*y[7] + fx_5_012*y[9];
yr[5] = fx_5_019*y[0] + fx_5_022*y[2] + fx_5_023*y[4];
yr[6] = fx_5_013*y[6] + fx_5_014*y[8] + fx_5_015*y[10];
yr[7] = fx_5_020*y[0] - fx_5_007*y[2] - fx_5_011*y[4];
yr[8] = fx_5_014*y[6] + fx_5_016*y[8] + fx_5_017*y[10];
yr[9] = fx_5_021*y[0] - fx_5_008*y[2] - fx_5_012*y[4];
yr[10] = fx_5_015*y[6] + fx_5_017*y[8] + fx_5_018*y[10];
};
inline void sh_rotx90_inv_5(REAL y[], REAL yr[])
{
yr[0] = fx_5_019*y[5] + fx_5_020*y[7] + fx_5_021*y[9];
yr[1] = fx_5_004*y[1] + fx_5_005*y[3];
yr[2] = fx_5_022*y[5] - fx_5_007*y[7] - fx_5_008*y[9];
yr[3] = fx_5_005*y[1] + fx_5_009*y[3];
yr[4] = fx_5_023*y[5] - fx_5_011*y[7] - fx_5_012*y[9];
yr[5] = fx_5_001*y[0] + fx_5_006*y[2] + fx_5_010*y[4];
yr[6] = fx_5_013*y[6] + fx_5_014*y[8] + fx_5_015*y[10];
yr[7] = fx_5_002*y[0] + fx_5_007*y[2] + fx_5_011*y[4];
yr[8] = fx_5_014*y[6] + fx_5_016*y[8] + fx_5_017*y[10];
yr[9] = fx_5_003*y[0] + fx_5_008*y[2] + fx_5_012*y[4];
yr[10] = fx_5_015*y[6] + fx_5_017*y[8] + fx_5_018*y[10];
}
inline void sh_rot_1(REAL m[3 * 3], REAL y[NL1], REAL yr[NL1])
{
REAL yr0 = m[4] * y[0] - m[5] * y[1] + m[3] * y[2];
REAL yr1 = m[8] * y[1] - m[7] * y[0] - m[6] * y[2];
REAL yr2 = m[1] * y[0] - m[2] * y[1] + m[0] * y[2];
yr[0] = yr0;
yr[1] = yr1;
yr[2] = yr2;
}
inline void sh_roty_1(REAL ctm[1], REAL stm[1], REAL y[NL1], REAL yr[NL1])
{
yr[0] = y[0];
rot_inv(ctm[0], stm[0], y[1], y[2], yr[1], yr[2]);
}
inline void sh_roty_2(REAL ctm[2], REAL stm[2], REAL y[NL2], REAL yr[NL2])
{
REAL ytmp[NL2];
sh_rotx90_2(y, yr);
sh_rotz_2(ctm, stm, yr, ytmp);
sh_rotx90_inv_2(ytmp, yr);
}
inline void sh_roty_3(REAL ctm[3], REAL stm[3], REAL y[NL3], REAL yr[NL3])
{
REAL ytmp[NL3];
sh_rotx90_3(y, yr);
sh_rotz_3(ctm, stm, yr, ytmp);
sh_rotx90_inv_3(ytmp, yr);
}
inline void sh_roty_4(REAL ctm[4], REAL stm[4], REAL y[NL4], REAL yr[NL4])
{
REAL ytmp[NL4];
sh_rotx90_4(y, yr);
sh_rotz_4(ctm, stm, yr, ytmp);
sh_rotx90_inv_4(ytmp, yr);
}
inline void sh_roty_5(REAL ctm[5], REAL stm[5], REAL y[NL5], REAL yr[NL5])
{
REAL ytmp[NL5];
sh_rotx90_5(y, yr);
sh_rotz_5(ctm, stm, yr, ytmp);
sh_rotx90_inv_5(ytmp, yr);
}
#define ROT_TOL CONSTANT(1e-4)
/*
Finds cosine,sine pairs for zyz rotation (i.e. rotation R_z2 R_y R_z1 v).
The rotation is one which maps mx to (1,0,0) and mz to (0,0,1).
*/
inline void zyz(REAL m[3 * 3], REAL &zc1, REAL &zs1, REAL &yc, REAL &ys, REAL &zc2, REAL &zs2)
{
REAL cz = m[8];
// rotate so that (cx,cy,0) aligns to (1,0,0)
REAL cxylen = (REAL)sqrtf(1.0f - cz*cz);
if (cxylen >= ROT_TOL)
{
// if above is a NaN, will do the correct thing
yc = cz;
ys = cxylen;
REAL len67inv = 1.0f / sqrtf(m[6] * m[6] + m[7] * m[7]);
zc1 = -m[6] * len67inv;
zs1 = m[7] * len67inv;
REAL len25inv = 1.0f / sqrtf(m[2] * m[2] + m[5] * m[5]);
zc2 = m[2] * len25inv;
zs2 = m[5] * len25inv;
}
else { // m[6],m[7],m[8] already aligned to (0,0,1)
zc1 = 1.0; zs1 = 0.0; // identity
yc = cz; ys = 0.0; // identity
zc2 = m[0] * cz; zs2 = -m[1]; // align x axis (mx[0],mx[1],0) to (1,0,0)
}
}
inline void sh_rotzyz_2(REAL zc1m[2], REAL zs1m[2], REAL ycm[2], REAL ysm[2], REAL zc2m[2], REAL zs2m[2], REAL y[NL2], REAL yr[NL2])
{
REAL ytmp[NL2];
sh_rotz_2(zc1m, zs1m, y, yr);
sh_roty_2(ycm, ysm, yr, ytmp);
sh_rotz_2(zc2m, zs2m, ytmp, yr);
}
inline void sh_rotzyz_3(REAL zc1m[3], REAL zs1m[3], REAL ycm[3], REAL ysm[3], REAL zc2m[3], REAL zs2m[3], REAL y[NL3], REAL yr[NL3])
{
REAL ytmp[NL3];
sh_rotz_3(zc1m, zs1m, y, yr);
sh_roty_3(ycm, ysm, yr, ytmp);
sh_rotz_3(zc2m, zs2m, ytmp, yr);
}
inline void sh_rotzyz_4(REAL zc1m[4], REAL zs1m[4], REAL ycm[4], REAL ysm[4], REAL zc2m[4], REAL zs2m[4], REAL y[NL4], REAL yr[NL4])
{
REAL ytmp[NL4];
sh_rotz_4(zc1m, zs1m, y, yr);
sh_roty_4(ycm, ysm, yr, ytmp);
sh_rotz_4(zc2m, zs2m, ytmp, yr);
}
inline void sh_rotzyz_5(REAL zc1m[5], REAL zs1m[5], REAL ycm[5], REAL ysm[5], REAL zc2m[5], REAL zs2m[5], REAL y[NL5], REAL yr[NL5])
{
REAL ytmp[NL5];
sh_rotz_5(zc1m, zs1m, y, yr);
sh_roty_5(ycm, ysm, yr, ytmp);
sh_rotz_5(zc2m, zs2m, ytmp, yr);
}
inline void sh3_rot(REAL m[3 * 3], REAL zc1, REAL zs1, REAL yc, REAL ys, REAL zc2, REAL zs2, REAL y[NSH3], REAL yr[NSH3])
{
REAL zc1m[3], zs1m[3];
rot_3(zc1, zs1, zc1m, zs1m);
REAL ycm[3], ysm[3];
rot_3(yc, ys, ycm, ysm);
REAL zc2m[3], zs2m[3];
rot_3(zc2, zs2, zc2m, zs2m);
yr[0] = y[0];
sh_rot_1(m, y + NSH0, yr + NSH0);
sh_rotzyz_2(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH1, yr + NSH1);
sh_rotzyz_3(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH2, yr + NSH2);
}
inline void sh4_rot(REAL m[3 * 3], REAL zc1, REAL zs1, REAL yc, REAL ys, REAL zc2, REAL zs2, REAL y[NSH4], REAL yr[NSH4])
{
REAL zc1m[4], zs1m[4];
rot_4(zc1, zs1, zc1m, zs1m);
REAL ycm[4], ysm[4];
rot_4(yc, ys, ycm, ysm);
REAL zc2m[4], zs2m[4];
rot_4(zc2, zs2, zc2m, zs2m);
yr[0] = y[0];
sh_rot_1(m, y + NSH0, yr + NSH0);
sh_rotzyz_2(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH1, yr + NSH1);
sh_rotzyz_3(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH2, yr + NSH2);
sh_rotzyz_4(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH3, yr + NSH3);
}
inline void sh5_rot(REAL m[3 * 3], REAL zc1, REAL zs1, REAL yc, REAL ys, REAL zc2, REAL zs2, REAL y[NSH5], REAL yr[NSH5])
{
REAL zc1m[5], zs1m[5];
rot_5(zc1, zs1, zc1m, zs1m);
REAL ycm[5], ysm[5];
rot_5(yc, ys, ycm, ysm);
REAL zc2m[5], zs2m[5];
rot_5(zc2, zs2, zc2m, zs2m);
yr[0] = y[0];
sh_rot_1(m, y + NSH0, yr + NSH0);
sh_rotzyz_2(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH1, yr + NSH1);
sh_rotzyz_3(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH2, yr + NSH2);
sh_rotzyz_4(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH3, yr + NSH3);
sh_rotzyz_5(zc1m, zs1m, ycm, ysm, zc2m, zs2m, y + NSH4, yr + NSH4);
}
inline void sh1_rot(REAL m[3 * 3], REAL y[NSH1], REAL yr[NSH1])
{
yr[0] = y[0];
sh_rot_1(m, y + NSH0, yr + NSH0);
}
inline void sh3_rot(REAL m[3 * 3], REAL y[NSH3], REAL yr[NSH3])
{
REAL zc1, zs1, yc, ys, zc2, zs2;
zyz(m, zc1, zs1, yc, ys, zc2, zs2);
sh3_rot(m, zc1, zs1, yc, ys, zc2, zs2, y, yr);
}
inline void sh4_rot(REAL m[3 * 3], REAL y[NSH4], REAL yr[NSH4])
{
REAL zc1, zs1, yc, ys, zc2, zs2;
zyz(m, zc1, zs1, yc, ys, zc2, zs2);
sh4_rot(m, zc1, zs1, yc, ys, zc2, zs2, y, yr);
}
inline void sh5_rot(REAL m[3 * 3], REAL y[NSH5], REAL yr[NSH5])
{
REAL zc1, zs1, yc, ys, zc2, zs2;
zyz(m, zc1, zs1, yc, ys, zc2, zs2);
sh5_rot(m, zc1, zs1, yc, ys, zc2, zs2, y, yr);
}
// simple matrix vector multiply for a square matrix (only used by ZRotation)
inline void SimpMatMul(size_t dim, const float *matrix, const float *input, float *result)
{
for (size_t iR = 0; iR < dim; ++iR)
{
result[iR + 0] = matrix[iR*dim + 0] * input[0];
for (size_t iC = 1; iC < dim; ++iC)
{
result[iR] += matrix[iR*dim + iC] * input[iC];
}
}
}
}; // anonymous namespace
//-------------------------------------------------------------------------------------
// Evaluates the Spherical Harmonic basis functions
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb205448.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* XM_CALLCONV DirectX::XMSHEvalDirection(
float *result,
size_t order,
FXMVECTOR dir) noexcept
{
if (!result)
return nullptr;
XMFLOAT4A dv;
XMStoreFloat4A(&dv, dir);
const float fX = dv.x;
const float fY = dv.y;
const float fZ = dv.z;
switch (order)
{
case 2:
sh_eval_basis_1(fX, fY, fZ, result);
break;
case 3:
sh_eval_basis_2(fX, fY, fZ, result);
break;
case 4:
sh_eval_basis_3(fX, fY, fZ, result);
break;
case 5:
sh_eval_basis_4(fX, fY, fZ, result);
break;
case 6:
sh_eval_basis_5(fX, fY, fZ, result);
break;
default:
assert(order < XM_SH_MINORDER || order > XM_SH_MAXORDER);
return nullptr;
}
return result;
}
//-------------------------------------------------------------------------------------
// Rotates SH vector by a rotation matrix
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb204992.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* XM_CALLCONV DirectX::XMSHRotate(
float *result,
size_t order,
FXMMATRIX rotMatrix,
const float *input) noexcept
{
if (!result || !input)
return nullptr;
if (result == input)
return nullptr;
XMFLOAT3X3 mat;
XMStoreFloat3x3(&mat, rotMatrix);
float mRot[3 * 3];
const float r00 = mRot[0 * 3 + 0] = mat._11;
const float r10 = mRot[1 * 3 + 0] = mat._12;
const float r20 = mRot[2 * 3 + 0] = mat._13;
const float r01 = mRot[0 * 3 + 1] = mat._21;
const float r11 = mRot[1 * 3 + 1] = mat._22;
const float r21 = mRot[2 * 3 + 1] = mat._23;
const float r02 = mRot[0 * 3 + 2] = mat._31;
const float r12 = mRot[1 * 3 + 2] = mat._32;
const float r22 = mRot[2 * 3 + 2] = mat._33;
result[0] = input[0]; // rotate the constant term
switch (order)
{
case 2:
{
// do linear by hand...
result[1] = r11*input[1] - r12*input[2] + r10*input[3];
result[2] = -r21*input[1] + r22*input[2] - r20*input[3];
result[3] = r01*input[1] - r02*input[2] + r00*input[3];
}
break;
case 3:
{
float R[25];
// do linear by hand...
result[1] = r11*input[1] - r12*input[2] + r10*input[3];
result[2] = -r21*input[1] + r22*input[2] - r20*input[3];
result[3] = r01*input[1] - r02*input[2] + r00*input[3];
// direct code for quadratics is faster than ZYZ reccurence relations
const float t41 = r01 * r00;
const float t43 = r11 * r10;
const float t48 = r11 * r12;
const float t50 = r01 * r02;
const float t55 = r02 * r02;
const float t57 = r22 * r22;
const float t58 = r12 * r12;
const float t61 = r00 * r02;
const float t63 = r10 * r12;
const float t68 = r10 * r10;
const float t70 = r01 * r01;
const float t72 = r11 * r11;
const float t74 = r00 * r00;
const float t76 = r21 * r21;
const float t78 = r20 * r20;
const float v173 = 0.1732050808e1f;
const float v577 = 0.5773502693e0f;
const float v115 = 0.1154700539e1f;
const float v288 = 0.2886751347e0f;
const float v866 = 0.8660254040e0f;
R[0] = r11 * r00 + r01 * r10;
R[1] = -r01 * r12 - r11 * r02;
R[2] = v173 * r02 * r12;
R[3] = -r10 * r02 - r00 * r12;
R[4] = r00 * r10 - r01 * r11;
R[5] = -r11 * r20 - r21 * r10;
R[6] = r11 * r22 + r21 * r12;
R[7] = -v173 * r22 * r12;
R[8] = r20 * r12 + r10 * r22;
R[9] = -r10 * r20 + r11 * r21;
R[10] = -v577* (t41 + t43) + v115 * r21 * r20;
R[11] = v577* (t48 + t50) - v115 * r21 * r22;
R[12] = -0.5000000000e0f * (t55 + t58) + t57;
R[13] = v577 * (t61 + t63) - v115 * r20 * r22;
R[14] = v288 * (t70 - t68 + t72 - t74) - v577 * (t76 - t78);
R[15] = -r01 * r20 - r21 * r00;
R[16] = r01 * r22 + r21 * r02;
R[17] = -v173 * r22 * r02;
R[18] = r00 * r22 + r20 * r02;
R[19] = -r00 * r20 + r01 * r21;
R[20] = t41 - t43;
R[21] = -t50 + t48;
R[22] = v866 * (t55 - t58);
R[23] = t63 - t61;
R[24] = 0.5000000000e0f *(t74 - t68 - t70 + t72);
// blow the matrix multiply out by hand, looping is ineficient on a P4...
for (unsigned int iR = 0; iR < 5; iR++)
{
const unsigned int uBase = iR * 5;
result[4 + iR] = R[uBase + 0] * input[4] + R[uBase + 1] * input[5] + R[uBase + 2] * input[6] + R[uBase + 3] * input[7] + R[uBase + 4] * input[8];
}
}
break;
case 4:
sh3_rot(mRot, const_cast<float *>(input), result);
break;
case 5:
sh4_rot(mRot, const_cast<float *>(input), result);
break;
case 6:
sh5_rot(mRot, const_cast<float *>(input), result);
break;
default:
assert(order < XM_SH_MINORDER || order > XM_SH_MAXORDER);
return nullptr;
}
return result;
}
//-------------------------------------------------------------------------------------
// Rotates the SH vector in the Z axis by an angle
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb205461.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHRotateZ(
float *result,
size_t order,
float angle,
const float *input) noexcept
{
if (!result || !input)
return nullptr;
if (result == input)
return nullptr;
if (order < XM_SH_MINORDER || order > XM_SH_MAXORDER)
return nullptr;
float R[(2 * (XM_SH_MAXORDER - 1) + 1)*(2 * (XM_SH_MAXORDER - 1) + 1)]; // used to store rotation matrices...
// these are actually very sparse matrices, most of the entries are zero's...
const float ca = cosf(angle);
const float sa = sinf(angle);
const float t1 = ca;
const float t2 = sa;
R[0] = t1;
R[1] = 0.0f;
R[2] = t2;
R[3] = 0.0f;
R[4] = 1.0f;
R[5] = 0.0f;
R[6] = -t2;
R[7] = 0.0f;
R[8] = t1;
result[0] = input[0];
SimpMatMul(3, R, input + 1, result + 1);
if (order > 2)
{
for (int j = 0; j < 5 * 5; j++) R[j] = 0.0f;
const float t1 = sa;
const float t2 = t1*t1;
const float t3 = ca;
const float t4 = t3*t3;
const float t5 = -t2 + t4;
const float t7 = 2.0f*t3*t1;
R[0] = t5;
R[4] = t7;
R[6] = t3;
R[8] = t1;
R[12] = 1.0f;
R[16] = -t1;
R[18] = t3;
R[20] = -t7;
R[24] = t5;
SimpMatMul(5, R, input + 4, result + 4); // un-roll matrix/vector multiply
if (order > 3)
{
for (int j = 0; j < 7 * 7; j++) R[j] = 0.0f;
const float t1 = ca;
const float t2 = t1*t1;
const float t4 = sa;
const float t5 = t4*t4;
const float t8 = t2*t1 - 3.0f*t1*t5;
const float t12 = 3.0f*t4*t2 - t5*t4;
const float t13 = -t5 + t2;
const float t15 = 2.0f*t1*t4;
R[0] = t8;
R[6] = t12;
R[8] = t13;
R[12] = t15;
R[16] = t1;
R[18] = t4;
R[24] = 1.0f;
R[30] = -t4;
R[32] = t1;
R[36] = -t15;
R[40] = t13;
R[42] = -t12;
R[48] = t8;
SimpMatMul(7, R, input + 9, result + 9);
if (order > 4)
{
for (int j = 0; j <= 9 * 9; j++) R[j] = 0.0f;
const float t1 = ca;
const float t2 = t1*t1;
const float t3 = t2*t2;
const float t4 = sa;
const float t5 = t4*t4;
const float t6 = t5*t5;
const float t9 = t3 + t6 - 6.0f*t5*t2;
const float t10 = t5*t4;
const float t12 = t2*t1;
const float t14 = -t10*t1 + t4*t12;
const float t17 = t12 - 3.0f*t1*t5;
const float t20 = 3.0f*t4*t2 - t10;
const float t21 = -t5 + t2;
const float t23 = 2.0f*t1*t4;
R[0] = t9;
R[8] = 4.0f*t14;
R[10] = t17;
R[16] = t20;
R[20] = t21;
R[24] = t23;
R[30] = t1;
R[32] = t4;
R[40] = 1.0f;
R[48] = -t4;
R[50] = t1;
R[56] = -t23;
R[60] = t21;
R[64] = -t20;
R[70] = t17;
R[72] = -4.0f*t14;
R[80] = t9;
SimpMatMul(9, R, input + 16, result + 16);
if (order > 5)
{
for (int j = 0; j < 11 * 11; j++) R[j] = 0.0f;
const float t1 = ca;
const float t2 = sa;
const float t3 = t2*t2;
const float t4 = t3*t3;
const float t7 = t1*t1;
const float t8 = t7*t1;
const float t11 = t7*t7;
const float t13 = 5.0f*t1*t4 - 10.0f*t3*t8 + t11*t1;
const float t14 = t3*t2;
const float t20 = -10.0f*t14*t7 + 5.0f*t2*t11 + t4*t2;
const float t23 = t11 + t4 - 6.0f*t3*t7;
const float t26 = -t14*t1 + t2*t8;
const float t29 = t8 - 3.0f*t1*t3;
const float t32 = 3.0f*t2*t7 - t14;
const float t33 = -t3 + t7;
const float t35 = 2.0f*t1*t2;
R[0] = t13;
R[10] = t20;
R[12] = t23;
R[20] = 4.0f*t26;
R[24] = t29;
R[30] = t32;
R[36] = t33;
R[40] = t35;
R[48] = t1;
R[50] = t2;
R[60] = 1.0f;
R[70] = -t2;
R[72] = t1;
R[80] = -t35;
R[84] = t33;
R[90] = -t32;
R[96] = t29;
R[100] = -4.0f*t26;
R[108] = t23;
R[110] = -t20;
R[120] = t13;
SimpMatMul(11, R, input + 25, result + 25);
}
}
}
}
return result;
}
//-------------------------------------------------------------------------------------
// Adds two SH vectors, result[i] = inputA[i] + inputB[i];
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb205438.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHAdd(
float *result,
size_t order,
const float *inputA,
const float *inputB) noexcept
{
if (!result || !inputA || !inputB)
return nullptr;
const size_t numcoeff = order*order;
for (size_t i = 0; i < numcoeff; ++i)
{
result[i] = inputA[i] + inputB[i];
}
return result;
}
//-------------------------------------------------------------------------------------
// Scales a SH vector, result[i] = input[i] * scale;
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb204994.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHScale(
float *result,
size_t order,
const float *input,
float scale) noexcept
{
if (!result || !input)
return nullptr;
const size_t numcoeff = order*order;
for (size_t i = 0; i < numcoeff; ++i)
{
result[i] = scale * input[i];
}
return result;
}
//-------------------------------------------------------------------------------------
// Computes the dot product of two SH vectors
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb205446.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float DirectX::XMSHDot(
size_t order,
const float *inputA,
const float *inputB) noexcept
{
if (!inputA || !inputB)
return 0.f;
float result = inputA[0] * inputB[0];
const size_t numcoeff = order*order;
for (size_t i = 1; i < numcoeff; ++i)
{
result += inputA[i] * inputB[i];
}
return result;
}
//-------------------------------------------------------------------------------------
// Computes the product of two functions represented using SH (f and g), where:
// result[i] = int(y_i(s) * f(s) * g(s)), where y_i(s) is the ith SH basis
// function, f(s) and g(s) are SH functions (sum_i(y_i(s)*c_i)). The order O
// determines the lengths of the arrays, where there should always be O^2
// coefficients. In general the product of two SH functions of order O generates
// and SH function of order 2*O - 1, but we truncate the result. This means
// that the product commutes (f*g == g*f) but doesn't associate
// (f*(g*h) != (f*g)*h.
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHMultiply(
float *result,
size_t order,
const float *inputF,
const float *inputG) noexcept
{
switch (order)
{
case 2:
return XMSHMultiply2(result, inputF, inputG);
case 3:
return XMSHMultiply3(result, inputF, inputG);
case 4:
return XMSHMultiply4(result, inputF, inputG);
case 5:
return XMSHMultiply5(result, inputF, inputG);
case 6:
return XMSHMultiply6(result, inputF, inputG);
default:
assert(order < XM_SH_MINORDER || order > XM_SH_MAXORDER);
return nullptr;
}
}
//-------------------------------------------------------------------------------------
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb205454.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHMultiply2(
float *y,
const float *f,
const float *g) noexcept
{
if (!y || !f || !g)
return nullptr;
REAL tf, tg, t;
// [0,0]: 0,
y[0] = CONSTANT(0.282094792935999980)*f[0] * g[0];
// [1,1]: 0,
tf = CONSTANT(0.282094791773000010)*f[0];
tg = CONSTANT(0.282094791773000010)*g[0];
y[1] = tf*g[1] + tg*f[1];
t = f[1] * g[1];
y[0] += CONSTANT(0.282094791773000010)*t;
// [2,2]: 0,
tf = CONSTANT(0.282094795249000000)*f[0];
tg = CONSTANT(0.282094795249000000)*g[0];
y[2] = tf*g[2] + tg*f[2];
t = f[2] * g[2];
y[0] += CONSTANT(0.282094795249000000)*t;
// [3,3]: 0,
tf = CONSTANT(0.282094791773000010)*f[0];
tg = CONSTANT(0.282094791773000010)*g[0];
y[3] = tf*g[3] + tg*f[3];
t = f[3] * g[3];
y[0] += CONSTANT(0.282094791773000010)*t;
// multiply count=20
return y;
}
//-------------------------------------------------------------------------------------
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb232906.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHMultiply3(
float *y,
const float *f,
const float *g) noexcept
{
if (!y || !f || !g)
return nullptr;
REAL tf, tg, t;
// [0,0]: 0,
y[0] = CONSTANT(0.282094792935999980)*f[0] * g[0];
// [1,1]: 0,6,8,
tf = CONSTANT(0.282094791773000010)*f[0] + CONSTANT(-0.126156626101000010)*f[6] + CONSTANT(-0.218509686119999990)*f[8];
tg = CONSTANT(0.282094791773000010)*g[0] + CONSTANT(-0.126156626101000010)*g[6] + CONSTANT(-0.218509686119999990)*g[8];
y[1] = tf*g[1] + tg*f[1];
t = f[1] * g[1];
y[0] += CONSTANT(0.282094791773000010)*t;
y[6] = CONSTANT(-0.126156626101000010)*t;
y[8] = CONSTANT(-0.218509686119999990)*t;
// [1,2]: 5,
tf = CONSTANT(0.218509686118000010)*f[5];
tg = CONSTANT(0.218509686118000010)*g[5];
y[1] += tf*g[2] + tg*f[2];
y[2] = tf*g[1] + tg*f[1];
t = f[1] * g[2] + f[2] * g[1];
y[5] = CONSTANT(0.218509686118000010)*t;
// [1,3]: 4,
tf = CONSTANT(0.218509686114999990)*f[4];
tg = CONSTANT(0.218509686114999990)*g[4];
y[1] += tf*g[3] + tg*f[3];
y[3] = tf*g[1] + tg*f[1];
t = f[1] * g[3] + f[3] * g[1];
y[4] = CONSTANT(0.218509686114999990)*t;
// [2,2]: 0,6,
tf = CONSTANT(0.282094795249000000)*f[0] + CONSTANT(0.252313259986999990)*f[6];
tg = CONSTANT(0.282094795249000000)*g[0] + CONSTANT(0.252313259986999990)*g[6];
y[2] += tf*g[2] + tg*f[2];
t = f[2] * g[2];
y[0] += CONSTANT(0.282094795249000000)*t;
y[6] += CONSTANT(0.252313259986999990)*t;
// [2,3]: 7,
tf = CONSTANT(0.218509686118000010)*f[7];
tg = CONSTANT(0.218509686118000010)*g[7];
y[2] += tf*g[3] + tg*f[3];
y[3] += tf*g[2] + tg*f[2];
t = f[2] * g[3] + f[3] * g[2];
y[7] = CONSTANT(0.218509686118000010)*t;
// [3,3]: 0,6,8,
tf = CONSTANT(0.282094791773000010)*f[0] + CONSTANT(-0.126156626101000010)*f[6] + CONSTANT(0.218509686119999990)*f[8];
tg = CONSTANT(0.282094791773000010)*g[0] + CONSTANT(-0.126156626101000010)*g[6] + CONSTANT(0.218509686119999990)*g[8];
y[3] += tf*g[3] + tg*f[3];
t = f[3] * g[3];
y[0] += CONSTANT(0.282094791773000010)*t;
y[6] += CONSTANT(-0.126156626101000010)*t;
y[8] += CONSTANT(0.218509686119999990)*t;
// [4,4]: 0,6,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.180223751576000010)*f[6];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.180223751576000010)*g[6];
y[4] += tf*g[4] + tg*f[4];
t = f[4] * g[4];
y[0] += CONSTANT(0.282094791770000020)*t;
y[6] += CONSTANT(-0.180223751576000010)*t;
// [4,5]: 7,
tf = CONSTANT(0.156078347226000000)*f[7];
tg = CONSTANT(0.156078347226000000)*g[7];
y[4] += tf*g[5] + tg*f[5];
y[5] += tf*g[4] + tg*f[4];
t = f[4] * g[5] + f[5] * g[4];
y[7] += CONSTANT(0.156078347226000000)*t;
// [5,5]: 0,6,8,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.090111875786499998)*f[6] + CONSTANT(-0.156078347227999990)*f[8];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.090111875786499998)*g[6] + CONSTANT(-0.156078347227999990)*g[8];
y[5] += tf*g[5] + tg*f[5];
t = f[5] * g[5];
y[0] += CONSTANT(0.282094791773999990)*t;
y[6] += CONSTANT(0.090111875786499998)*t;
y[8] += CONSTANT(-0.156078347227999990)*t;
// [6,6]: 0,6,
tf = CONSTANT(0.282094797560000000)*f[0];
tg = CONSTANT(0.282094797560000000)*g[0];
y[6] += tf*g[6] + tg*f[6];
t = f[6] * g[6];
y[0] += CONSTANT(0.282094797560000000)*t;
y[6] += CONSTANT(0.180223764527000010)*t;
// [7,7]: 0,6,8,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.090111875786499998)*f[6] + CONSTANT(0.156078347227999990)*f[8];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.090111875786499998)*g[6] + CONSTANT(0.156078347227999990)*g[8];
y[7] += tf*g[7] + tg*f[7];
t = f[7] * g[7];
y[0] += CONSTANT(0.282094791773999990)*t;
y[6] += CONSTANT(0.090111875786499998)*t;
y[8] += CONSTANT(0.156078347227999990)*t;
// [8,8]: 0,6,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.180223751576000010)*f[6];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.180223751576000010)*g[6];
y[8] += tf*g[8] + tg*f[8];
t = f[8] * g[8];
y[0] += CONSTANT(0.282094791770000020)*t;
y[6] += CONSTANT(-0.180223751576000010)*t;
// multiply count=120
return y;
}
//-------------------------------------------------------------------------------------
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb232907.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHMultiply4(
float *y,
const float *f,
const float *g) noexcept
{
if (!y || !f || !g)
return nullptr;
REAL tf, tg, t;
// [0,0]: 0,
y[0] = CONSTANT(0.282094792935999980)*f[0] * g[0];
// [1,1]: 0,6,8,
tf = CONSTANT(0.282094791773000010)*f[0] + CONSTANT(-0.126156626101000010)*f[6] + CONSTANT(-0.218509686119999990)*f[8];
tg = CONSTANT(0.282094791773000010)*g[0] + CONSTANT(-0.126156626101000010)*g[6] + CONSTANT(-0.218509686119999990)*g[8];
y[1] = tf*g[1] + tg*f[1];
t = f[1] * g[1];
y[0] += CONSTANT(0.282094791773000010)*t;
y[6] = CONSTANT(-0.126156626101000010)*t;
y[8] = CONSTANT(-0.218509686119999990)*t;
// [1,4]: 3,13,15,
tf = CONSTANT(0.218509686114999990)*f[3] + CONSTANT(-0.058399170082300000)*f[13] + CONSTANT(-0.226179013157999990)*f[15];
tg = CONSTANT(0.218509686114999990)*g[3] + CONSTANT(-0.058399170082300000)*g[13] + CONSTANT(-0.226179013157999990)*g[15];
y[1] += tf*g[4] + tg*f[4];
y[4] = tf*g[1] + tg*f[1];
t = f[1] * g[4] + f[4] * g[1];
y[3] = CONSTANT(0.218509686114999990)*t;
y[13] = CONSTANT(-0.058399170082300000)*t;
y[15] = CONSTANT(-0.226179013157999990)*t;
// [1,5]: 2,12,14,
tf = CONSTANT(0.218509686118000010)*f[2] + CONSTANT(-0.143048168103000000)*f[12] + CONSTANT(-0.184674390923000000)*f[14];
tg = CONSTANT(0.218509686118000010)*g[2] + CONSTANT(-0.143048168103000000)*g[12] + CONSTANT(-0.184674390923000000)*g[14];
y[1] += tf*g[5] + tg*f[5];
y[5] = tf*g[1] + tg*f[1];
t = f[1] * g[5] + f[5] * g[1];
y[2] = CONSTANT(0.218509686118000010)*t;
y[12] = CONSTANT(-0.143048168103000000)*t;
y[14] = CONSTANT(-0.184674390923000000)*t;
// [1,6]: 11,
tf = CONSTANT(0.202300659402999990)*f[11];
tg = CONSTANT(0.202300659402999990)*g[11];
y[1] += tf*g[6] + tg*f[6];
y[6] += tf*g[1] + tg*f[1];
t = f[1] * g[6] + f[6] * g[1];
y[11] = CONSTANT(0.202300659402999990)*t;
// [1,8]: 9,11,
tf = CONSTANT(0.226179013155000000)*f[9] + CONSTANT(0.058399170081799998)*f[11];
tg = CONSTANT(0.226179013155000000)*g[9] + CONSTANT(0.058399170081799998)*g[11];
y[1] += tf*g[8] + tg*f[8];
y[8] += tf*g[1] + tg*f[1];
t = f[1] * g[8] + f[8] * g[1];
y[9] = CONSTANT(0.226179013155000000)*t;
y[11] += CONSTANT(0.058399170081799998)*t;
// [2,2]: 0,6,
tf = CONSTANT(0.282094795249000000)*f[0] + CONSTANT(0.252313259986999990)*f[6];
tg = CONSTANT(0.282094795249000000)*g[0] + CONSTANT(0.252313259986999990)*g[6];
y[2] += tf*g[2] + tg*f[2];
t = f[2] * g[2];
y[0] += CONSTANT(0.282094795249000000)*t;
y[6] += CONSTANT(0.252313259986999990)*t;
// [2,6]: 12,
tf = CONSTANT(0.247766706973999990)*f[12];
tg = CONSTANT(0.247766706973999990)*g[12];
y[2] += tf*g[6] + tg*f[6];
y[6] += tf*g[2] + tg*f[2];
t = f[2] * g[6] + f[6] * g[2];
y[12] += CONSTANT(0.247766706973999990)*t;
// [3,3]: 0,6,8,
tf = CONSTANT(0.282094791773000010)*f[0] + CONSTANT(-0.126156626101000010)*f[6] + CONSTANT(0.218509686119999990)*f[8];
tg = CONSTANT(0.282094791773000010)*g[0] + CONSTANT(-0.126156626101000010)*g[6] + CONSTANT(0.218509686119999990)*g[8];
y[3] += tf*g[3] + tg*f[3];
t = f[3] * g[3];
y[0] += CONSTANT(0.282094791773000010)*t;
y[6] += CONSTANT(-0.126156626101000010)*t;
y[8] += CONSTANT(0.218509686119999990)*t;
// [3,6]: 13,
tf = CONSTANT(0.202300659402999990)*f[13];
tg = CONSTANT(0.202300659402999990)*g[13];
y[3] += tf*g[6] + tg*f[6];
y[6] += tf*g[3] + tg*f[3];
t = f[3] * g[6] + f[6] * g[3];
y[13] += CONSTANT(0.202300659402999990)*t;
// [3,7]: 2,12,14,
tf = CONSTANT(0.218509686118000010)*f[2] + CONSTANT(-0.143048168103000000)*f[12] + CONSTANT(0.184674390923000000)*f[14];
tg = CONSTANT(0.218509686118000010)*g[2] + CONSTANT(-0.143048168103000000)*g[12] + CONSTANT(0.184674390923000000)*g[14];
y[3] += tf*g[7] + tg*f[7];
y[7] = tf*g[3] + tg*f[3];
t = f[3] * g[7] + f[7] * g[3];
y[2] += CONSTANT(0.218509686118000010)*t;
y[12] += CONSTANT(-0.143048168103000000)*t;
y[14] += CONSTANT(0.184674390923000000)*t;
// [3,8]: 13,15,
tf = CONSTANT(-0.058399170081799998)*f[13] + CONSTANT(0.226179013155000000)*f[15];
tg = CONSTANT(-0.058399170081799998)*g[13] + CONSTANT(0.226179013155000000)*g[15];
y[3] += tf*g[8] + tg*f[8];
y[8] += tf*g[3] + tg*f[3];
t = f[3] * g[8] + f[8] * g[3];
y[13] += CONSTANT(-0.058399170081799998)*t;
y[15] += CONSTANT(0.226179013155000000)*t;
// [4,4]: 0,6,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.180223751576000010)*f[6];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.180223751576000010)*g[6];
y[4] += tf*g[4] + tg*f[4];
t = f[4] * g[4];
y[0] += CONSTANT(0.282094791770000020)*t;
y[6] += CONSTANT(-0.180223751576000010)*t;
// [4,5]: 7,
tf = CONSTANT(0.156078347226000000)*f[7];
tg = CONSTANT(0.156078347226000000)*g[7];
y[4] += tf*g[5] + tg*f[5];
y[5] += tf*g[4] + tg*f[4];
t = f[4] * g[5] + f[5] * g[4];
y[7] += CONSTANT(0.156078347226000000)*t;
// [4,9]: 3,13,
tf = CONSTANT(0.226179013157999990)*f[3] + CONSTANT(-0.094031597258400004)*f[13];
tg = CONSTANT(0.226179013157999990)*g[3] + CONSTANT(-0.094031597258400004)*g[13];
y[4] += tf*g[9] + tg*f[9];
y[9] += tf*g[4] + tg*f[4];
t = f[4] * g[9] + f[9] * g[4];
y[3] += CONSTANT(0.226179013157999990)*t;
y[13] += CONSTANT(-0.094031597258400004)*t;
// [4,10]: 2,12,
tf = CONSTANT(0.184674390919999990)*f[2] + CONSTANT(-0.188063194517999990)*f[12];
tg = CONSTANT(0.184674390919999990)*g[2] + CONSTANT(-0.188063194517999990)*g[12];
y[4] += tf*g[10] + tg*f[10];
y[10] = tf*g[4] + tg*f[4];
t = f[4] * g[10] + f[10] * g[4];
y[2] += CONSTANT(0.184674390919999990)*t;
y[12] += CONSTANT(-0.188063194517999990)*t;
// [4,11]: 3,13,15,
tf = CONSTANT(-0.058399170082300000)*f[3] + CONSTANT(0.145673124078000010)*f[13] + CONSTANT(0.094031597258400004)*f[15];
tg = CONSTANT(-0.058399170082300000)*g[3] + CONSTANT(0.145673124078000010)*g[13] + CONSTANT(0.094031597258400004)*g[15];
y[4] += tf*g[11] + tg*f[11];
y[11] += tf*g[4] + tg*f[4];
t = f[4] * g[11] + f[11] * g[4];
y[3] += CONSTANT(-0.058399170082300000)*t;
y[13] += CONSTANT(0.145673124078000010)*t;
y[15] += CONSTANT(0.094031597258400004)*t;
// [5,5]: 0,6,8,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.090111875786499998)*f[6] + CONSTANT(-0.156078347227999990)*f[8];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.090111875786499998)*g[6] + CONSTANT(-0.156078347227999990)*g[8];
y[5] += tf*g[5] + tg*f[5];
t = f[5] * g[5];
y[0] += CONSTANT(0.282094791773999990)*t;
y[6] += CONSTANT(0.090111875786499998)*t;
y[8] += CONSTANT(-0.156078347227999990)*t;
// [5,9]: 14,
tf = CONSTANT(0.148677009677999990)*f[14];
tg = CONSTANT(0.148677009677999990)*g[14];
y[5] += tf*g[9] + tg*f[9];
y[9] += tf*g[5] + tg*f[5];
t = f[5] * g[9] + f[9] * g[5];
y[14] += CONSTANT(0.148677009677999990)*t;
// [5,10]: 3,13,15,
tf = CONSTANT(0.184674390919999990)*f[3] + CONSTANT(0.115164716490000000)*f[13] + CONSTANT(-0.148677009678999990)*f[15];
tg = CONSTANT(0.184674390919999990)*g[3] + CONSTANT(0.115164716490000000)*g[13] + CONSTANT(-0.148677009678999990)*g[15];
y[5] += tf*g[10] + tg*f[10];
y[10] += tf*g[5] + tg*f[5];
t = f[5] * g[10] + f[10] * g[5];
y[3] += CONSTANT(0.184674390919999990)*t;
y[13] += CONSTANT(0.115164716490000000)*t;
y[15] += CONSTANT(-0.148677009678999990)*t;
// [5,11]: 2,12,14,
tf = CONSTANT(0.233596680327000010)*f[2] + CONSTANT(0.059470803871800003)*f[12] + CONSTANT(-0.115164716491000000)*f[14];
tg = CONSTANT(0.233596680327000010)*g[2] + CONSTANT(0.059470803871800003)*g[12] + CONSTANT(-0.115164716491000000)*g[14];
y[5] += tf*g[11] + tg*f[11];
y[11] += tf*g[5] + tg*f[5];
t = f[5] * g[11] + f[11] * g[5];
y[2] += CONSTANT(0.233596680327000010)*t;
y[12] += CONSTANT(0.059470803871800003)*t;
y[14] += CONSTANT(-0.115164716491000000)*t;
// [6,6]: 0,6,
tf = CONSTANT(0.282094797560000000)*f[0];
tg = CONSTANT(0.282094797560000000)*g[0];
y[6] += tf*g[6] + tg*f[6];
t = f[6] * g[6];
y[0] += CONSTANT(0.282094797560000000)*t;
y[6] += CONSTANT(0.180223764527000010)*t;
// [7,7]: 6,0,8,
tf = CONSTANT(0.090111875786499998)*f[6] + CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.156078347227999990)*f[8];
tg = CONSTANT(0.090111875786499998)*g[6] + CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.156078347227999990)*g[8];
y[7] += tf*g[7] + tg*f[7];
t = f[7] * g[7];
y[6] += CONSTANT(0.090111875786499998)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
y[8] += CONSTANT(0.156078347227999990)*t;
// [7,10]: 9,1,11,
tf = CONSTANT(0.148677009678999990)*f[9] + CONSTANT(0.184674390919999990)*f[1] + CONSTANT(0.115164716490000000)*f[11];
tg = CONSTANT(0.148677009678999990)*g[9] + CONSTANT(0.184674390919999990)*g[1] + CONSTANT(0.115164716490000000)*g[11];
y[7] += tf*g[10] + tg*f[10];
y[10] += tf*g[7] + tg*f[7];
t = f[7] * g[10] + f[10] * g[7];
y[9] += CONSTANT(0.148677009678999990)*t;
y[1] += CONSTANT(0.184674390919999990)*t;
y[11] += CONSTANT(0.115164716490000000)*t;
// [7,13]: 12,2,14,
tf = CONSTANT(0.059470803871800003)*f[12] + CONSTANT(0.233596680327000010)*f[2] + CONSTANT(0.115164716491000000)*f[14];
tg = CONSTANT(0.059470803871800003)*g[12] + CONSTANT(0.233596680327000010)*g[2] + CONSTANT(0.115164716491000000)*g[14];
y[7] += tf*g[13] + tg*f[13];
y[13] += tf*g[7] + tg*f[7];
t = f[7] * g[13] + f[13] * g[7];
y[12] += CONSTANT(0.059470803871800003)*t;
y[2] += CONSTANT(0.233596680327000010)*t;
y[14] += CONSTANT(0.115164716491000000)*t;
// [7,14]: 15,
tf = CONSTANT(0.148677009677999990)*f[15];
tg = CONSTANT(0.148677009677999990)*g[15];
y[7] += tf*g[14] + tg*f[14];
y[14] += tf*g[7] + tg*f[7];
t = f[7] * g[14] + f[14] * g[7];
y[15] += CONSTANT(0.148677009677999990)*t;
// [8,8]: 0,6,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.180223751576000010)*f[6];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.180223751576000010)*g[6];
y[8] += tf*g[8] + tg*f[8];
t = f[8] * g[8];
y[0] += CONSTANT(0.282094791770000020)*t;
y[6] += CONSTANT(-0.180223751576000010)*t;
// [8,9]: 11,
tf = CONSTANT(-0.094031597259499999)*f[11];
tg = CONSTANT(-0.094031597259499999)*g[11];
y[8] += tf*g[9] + tg*f[9];
y[9] += tf*g[8] + tg*f[8];
t = f[8] * g[9] + f[9] * g[8];
y[11] += CONSTANT(-0.094031597259499999)*t;
// [8,13]: 15,
tf = CONSTANT(-0.094031597259499999)*f[15];
tg = CONSTANT(-0.094031597259499999)*g[15];
y[8] += tf*g[13] + tg*f[13];
y[13] += tf*g[8] + tg*f[8];
t = f[8] * g[13] + f[13] * g[8];
y[15] += CONSTANT(-0.094031597259499999)*t;
// [8,14]: 2,12,
tf = CONSTANT(0.184674390919999990)*f[2] + CONSTANT(-0.188063194517999990)*f[12];
tg = CONSTANT(0.184674390919999990)*g[2] + CONSTANT(-0.188063194517999990)*g[12];
y[8] += tf*g[14] + tg*f[14];
y[14] += tf*g[8] + tg*f[8];
t = f[8] * g[14] + f[14] * g[8];
y[2] += CONSTANT(0.184674390919999990)*t;
y[12] += CONSTANT(-0.188063194517999990)*t;
// [9,9]: 6,0,
tf = CONSTANT(-0.210261043508000010)*f[6] + CONSTANT(0.282094791766999970)*f[0];
tg = CONSTANT(-0.210261043508000010)*g[6] + CONSTANT(0.282094791766999970)*g[0];
y[9] += tf*g[9] + tg*f[9];
t = f[9] * g[9];
y[6] += CONSTANT(-0.210261043508000010)*t;
y[0] += CONSTANT(0.282094791766999970)*t;
// [10,10]: 0,
tf = CONSTANT(0.282094791771999980)*f[0];
tg = CONSTANT(0.282094791771999980)*g[0];
y[10] += tf*g[10] + tg*f[10];
t = f[10] * g[10];
y[0] += CONSTANT(0.282094791771999980)*t;
// [11,11]: 0,6,8,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.126156626101000010)*f[6] + CONSTANT(-0.145673124078999990)*f[8];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.126156626101000010)*g[6] + CONSTANT(-0.145673124078999990)*g[8];
y[11] += tf*g[11] + tg*f[11];
t = f[11] * g[11];
y[0] += CONSTANT(0.282094791773999990)*t;
y[6] += CONSTANT(0.126156626101000010)*t;
y[8] += CONSTANT(-0.145673124078999990)*t;
// [12,12]: 0,6,
tf = CONSTANT(0.282094799871999980)*f[0] + CONSTANT(0.168208852954000010)*f[6];
tg = CONSTANT(0.282094799871999980)*g[0] + CONSTANT(0.168208852954000010)*g[6];
y[12] += tf*g[12] + tg*f[12];
t = f[12] * g[12];
y[0] += CONSTANT(0.282094799871999980)*t;
y[6] += CONSTANT(0.168208852954000010)*t;
// [13,13]: 0,8,6,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.145673124078999990)*f[8] + CONSTANT(0.126156626101000010)*f[6];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.145673124078999990)*g[8] + CONSTANT(0.126156626101000010)*g[6];
y[13] += tf*g[13] + tg*f[13];
t = f[13] * g[13];
y[0] += CONSTANT(0.282094791773999990)*t;
y[8] += CONSTANT(0.145673124078999990)*t;
y[6] += CONSTANT(0.126156626101000010)*t;
// [14,14]: 0,
tf = CONSTANT(0.282094791771999980)*f[0];
tg = CONSTANT(0.282094791771999980)*g[0];
y[14] += tf*g[14] + tg*f[14];
t = f[14] * g[14];
y[0] += CONSTANT(0.282094791771999980)*t;
// [15,15]: 0,6,
tf = CONSTANT(0.282094791766999970)*f[0] + CONSTANT(-0.210261043508000010)*f[6];
tg = CONSTANT(0.282094791766999970)*g[0] + CONSTANT(-0.210261043508000010)*g[6];
y[15] += tf*g[15] + tg*f[15];
t = f[15] * g[15];
y[0] += CONSTANT(0.282094791766999970)*t;
y[6] += CONSTANT(-0.210261043508000010)*t;
// multiply count=399
return y;
}
//-------------------------------------------------------------------------------------
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb232908.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHMultiply5(
float *y,
const float *f,
const float *g) noexcept
{
if (!y || !f || !g)
return nullptr;
REAL tf, tg, t;
// [0,0]: 0,
y[0] = CONSTANT(0.282094792935999980)*f[0] * g[0];
// [1,1]: 0,6,8,
tf = CONSTANT(0.282094791773000010)*f[0] + CONSTANT(-0.126156626101000010)*f[6] + CONSTANT(-0.218509686119999990)*f[8];
tg = CONSTANT(0.282094791773000010)*g[0] + CONSTANT(-0.126156626101000010)*g[6] + CONSTANT(-0.218509686119999990)*g[8];
y[1] = tf*g[1] + tg*f[1];
t = f[1] * g[1];
y[0] += CONSTANT(0.282094791773000010)*t;
y[6] = CONSTANT(-0.126156626101000010)*t;
y[8] = CONSTANT(-0.218509686119999990)*t;
// [1,4]: 3,13,15,
tf = CONSTANT(0.218509686114999990)*f[3] + CONSTANT(-0.058399170082300000)*f[13] + CONSTANT(-0.226179013157999990)*f[15];
tg = CONSTANT(0.218509686114999990)*g[3] + CONSTANT(-0.058399170082300000)*g[13] + CONSTANT(-0.226179013157999990)*g[15];
y[1] += tf*g[4] + tg*f[4];
y[4] = tf*g[1] + tg*f[1];
t = f[1] * g[4] + f[4] * g[1];
y[3] = CONSTANT(0.218509686114999990)*t;
y[13] = CONSTANT(-0.058399170082300000)*t;
y[15] = CONSTANT(-0.226179013157999990)*t;
// [1,5]: 2,12,14,
tf = CONSTANT(0.218509686118000010)*f[2] + CONSTANT(-0.143048168103000000)*f[12] + CONSTANT(-0.184674390923000000)*f[14];
tg = CONSTANT(0.218509686118000010)*g[2] + CONSTANT(-0.143048168103000000)*g[12] + CONSTANT(-0.184674390923000000)*g[14];
y[1] += tf*g[5] + tg*f[5];
y[5] = tf*g[1] + tg*f[1];
t = f[1] * g[5] + f[5] * g[1];
y[2] = CONSTANT(0.218509686118000010)*t;
y[12] = CONSTANT(-0.143048168103000000)*t;
y[14] = CONSTANT(-0.184674390923000000)*t;
// [1,9]: 8,22,24,
tf = CONSTANT(0.226179013155000000)*f[8] + CONSTANT(-0.043528171378199997)*f[22] + CONSTANT(-0.230329432978999990)*f[24];
tg = CONSTANT(0.226179013155000000)*g[8] + CONSTANT(-0.043528171378199997)*g[22] + CONSTANT(-0.230329432978999990)*g[24];
y[1] += tf*g[9] + tg*f[9];
y[9] = tf*g[1] + tg*f[1];
t = f[1] * g[9] + f[9] * g[1];
y[8] += CONSTANT(0.226179013155000000)*t;
y[22] = CONSTANT(-0.043528171378199997)*t;
y[24] = CONSTANT(-0.230329432978999990)*t;
// [1,10]: 7,21,23,
tf = CONSTANT(0.184674390919999990)*f[7] + CONSTANT(-0.075393004386799994)*f[21] + CONSTANT(-0.199471140200000010)*f[23];
tg = CONSTANT(0.184674390919999990)*g[7] + CONSTANT(-0.075393004386799994)*g[21] + CONSTANT(-0.199471140200000010)*g[23];
y[1] += tf*g[10] + tg*f[10];
y[10] = tf*g[1] + tg*f[1];
t = f[1] * g[10] + f[10] * g[1];
y[7] = CONSTANT(0.184674390919999990)*t;
y[21] = CONSTANT(-0.075393004386799994)*t;
y[23] = CONSTANT(-0.199471140200000010)*t;
// [1,11]: 6,8,20,22,
tf = CONSTANT(0.202300659402999990)*f[6] + CONSTANT(0.058399170081799998)*f[8] + CONSTANT(-0.150786008773000000)*f[20] + CONSTANT(-0.168583882836999990)*f[22];
tg = CONSTANT(0.202300659402999990)*g[6] + CONSTANT(0.058399170081799998)*g[8] + CONSTANT(-0.150786008773000000)*g[20] + CONSTANT(-0.168583882836999990)*g[22];
y[1] += tf*g[11] + tg*f[11];
y[11] = tf*g[1] + tg*f[1];
t = f[1] * g[11] + f[11] * g[1];
y[6] += CONSTANT(0.202300659402999990)*t;
y[8] += CONSTANT(0.058399170081799998)*t;
y[20] = CONSTANT(-0.150786008773000000)*t;
y[22] += CONSTANT(-0.168583882836999990)*t;
// [1,12]: 19,
tf = CONSTANT(0.194663900273000010)*f[19];
tg = CONSTANT(0.194663900273000010)*g[19];
y[1] += tf*g[12] + tg*f[12];
y[12] += tf*g[1] + tg*f[1];
t = f[1] * g[12] + f[12] * g[1];
y[19] = CONSTANT(0.194663900273000010)*t;
// [1,13]: 18,
tf = CONSTANT(0.168583882834000000)*f[18];
tg = CONSTANT(0.168583882834000000)*g[18];
y[1] += tf*g[13] + tg*f[13];
y[13] += tf*g[1] + tg*f[1];
t = f[1] * g[13] + f[13] * g[1];
y[18] = CONSTANT(0.168583882834000000)*t;
// [1,14]: 17,19,
tf = CONSTANT(0.199471140196999990)*f[17] + CONSTANT(0.075393004386399995)*f[19];
tg = CONSTANT(0.199471140196999990)*g[17] + CONSTANT(0.075393004386399995)*g[19];
y[1] += tf*g[14] + tg*f[14];
y[14] += tf*g[1] + tg*f[1];
t = f[1] * g[14] + f[14] * g[1];
y[17] = CONSTANT(0.199471140196999990)*t;
y[19] += CONSTANT(0.075393004386399995)*t;
// [1,15]: 16,18,
tf = CONSTANT(0.230329432973999990)*f[16] + CONSTANT(0.043528171377799997)*f[18];
tg = CONSTANT(0.230329432973999990)*g[16] + CONSTANT(0.043528171377799997)*g[18];
y[1] += tf*g[15] + tg*f[15];
y[15] += tf*g[1] + tg*f[1];
t = f[1] * g[15] + f[15] * g[1];
y[16] = CONSTANT(0.230329432973999990)*t;
y[18] += CONSTANT(0.043528171377799997)*t;
// [2,2]: 0,6,
tf = CONSTANT(0.282094795249000000)*f[0] + CONSTANT(0.252313259986999990)*f[6];
tg = CONSTANT(0.282094795249000000)*g[0] + CONSTANT(0.252313259986999990)*g[6];
y[2] += tf*g[2] + tg*f[2];
t = f[2] * g[2];
y[0] += CONSTANT(0.282094795249000000)*t;
y[6] += CONSTANT(0.252313259986999990)*t;
// [2,10]: 4,18,
tf = CONSTANT(0.184674390919999990)*f[4] + CONSTANT(0.213243618621000000)*f[18];
tg = CONSTANT(0.184674390919999990)*g[4] + CONSTANT(0.213243618621000000)*g[18];
y[2] += tf*g[10] + tg*f[10];
y[10] += tf*g[2] + tg*f[2];
t = f[2] * g[10] + f[10] * g[2];
y[4] += CONSTANT(0.184674390919999990)*t;
y[18] += CONSTANT(0.213243618621000000)*t;
// [2,12]: 6,20,
tf = CONSTANT(0.247766706973999990)*f[6] + CONSTANT(0.246232537174000010)*f[20];
tg = CONSTANT(0.247766706973999990)*g[6] + CONSTANT(0.246232537174000010)*g[20];
y[2] += tf*g[12] + tg*f[12];
y[12] += tf*g[2] + tg*f[2];
t = f[2] * g[12] + f[12] * g[2];
y[6] += CONSTANT(0.247766706973999990)*t;
y[20] += CONSTANT(0.246232537174000010)*t;
// [2,14]: 8,22,
tf = CONSTANT(0.184674390919999990)*f[8] + CONSTANT(0.213243618621000000)*f[22];
tg = CONSTANT(0.184674390919999990)*g[8] + CONSTANT(0.213243618621000000)*g[22];
y[2] += tf*g[14] + tg*f[14];
y[14] += tf*g[2] + tg*f[2];
t = f[2] * g[14] + f[14] * g[2];
y[8] += CONSTANT(0.184674390919999990)*t;
y[22] += CONSTANT(0.213243618621000000)*t;
// [3,3]: 0,6,8,
tf = CONSTANT(0.282094791773000010)*f[0] + CONSTANT(-0.126156626101000010)*f[6] + CONSTANT(0.218509686119999990)*f[8];
tg = CONSTANT(0.282094791773000010)*g[0] + CONSTANT(-0.126156626101000010)*g[6] + CONSTANT(0.218509686119999990)*g[8];
y[3] += tf*g[3] + tg*f[3];
t = f[3] * g[3];
y[0] += CONSTANT(0.282094791773000010)*t;
y[6] += CONSTANT(-0.126156626101000010)*t;
y[8] += CONSTANT(0.218509686119999990)*t;
// [3,7]: 2,12,14,
tf = CONSTANT(0.218509686118000010)*f[2] + CONSTANT(-0.143048168103000000)*f[12] + CONSTANT(0.184674390923000000)*f[14];
tg = CONSTANT(0.218509686118000010)*g[2] + CONSTANT(-0.143048168103000000)*g[12] + CONSTANT(0.184674390923000000)*g[14];
y[3] += tf*g[7] + tg*f[7];
y[7] += tf*g[3] + tg*f[3];
t = f[3] * g[7] + f[7] * g[3];
y[2] += CONSTANT(0.218509686118000010)*t;
y[12] += CONSTANT(-0.143048168103000000)*t;
y[14] += CONSTANT(0.184674390923000000)*t;
// [3,9]: 4,16,18,
tf = CONSTANT(0.226179013157999990)*f[4] + CONSTANT(0.230329432973999990)*f[16] + CONSTANT(-0.043528171377799997)*f[18];
tg = CONSTANT(0.226179013157999990)*g[4] + CONSTANT(0.230329432973999990)*g[16] + CONSTANT(-0.043528171377799997)*g[18];
y[3] += tf*g[9] + tg*f[9];
y[9] += tf*g[3] + tg*f[3];
t = f[3] * g[9] + f[9] * g[3];
y[4] += CONSTANT(0.226179013157999990)*t;
y[16] += CONSTANT(0.230329432973999990)*t;
y[18] += CONSTANT(-0.043528171377799997)*t;
// [3,10]: 5,17,19,
tf = CONSTANT(0.184674390919999990)*f[5] + CONSTANT(0.199471140200000010)*f[17] + CONSTANT(-0.075393004386799994)*f[19];
tg = CONSTANT(0.184674390919999990)*g[5] + CONSTANT(0.199471140200000010)*g[17] + CONSTANT(-0.075393004386799994)*g[19];
y[3] += tf*g[10] + tg*f[10];
y[10] += tf*g[3] + tg*f[3];
t = f[3] * g[10] + f[10] * g[3];
y[5] += CONSTANT(0.184674390919999990)*t;
y[17] += CONSTANT(0.199471140200000010)*t;
y[19] += CONSTANT(-0.075393004386799994)*t;
// [3,12]: 21,
tf = CONSTANT(0.194663900273000010)*f[21];
tg = CONSTANT(0.194663900273000010)*g[21];
y[3] += tf*g[12] + tg*f[12];
y[12] += tf*g[3] + tg*f[3];
t = f[3] * g[12] + f[12] * g[3];
y[21] += CONSTANT(0.194663900273000010)*t;
// [3,13]: 8,6,20,22,
tf = CONSTANT(-0.058399170081799998)*f[8] + CONSTANT(0.202300659402999990)*f[6] + CONSTANT(-0.150786008773000000)*f[20] + CONSTANT(0.168583882836999990)*f[22];
tg = CONSTANT(-0.058399170081799998)*g[8] + CONSTANT(0.202300659402999990)*g[6] + CONSTANT(-0.150786008773000000)*g[20] + CONSTANT(0.168583882836999990)*g[22];
y[3] += tf*g[13] + tg*f[13];
y[13] += tf*g[3] + tg*f[3];
t = f[3] * g[13] + f[13] * g[3];
y[8] += CONSTANT(-0.058399170081799998)*t;
y[6] += CONSTANT(0.202300659402999990)*t;
y[20] += CONSTANT(-0.150786008773000000)*t;
y[22] += CONSTANT(0.168583882836999990)*t;
// [3,14]: 21,23,
tf = CONSTANT(-0.075393004386399995)*f[21] + CONSTANT(0.199471140196999990)*f[23];
tg = CONSTANT(-0.075393004386399995)*g[21] + CONSTANT(0.199471140196999990)*g[23];
y[3] += tf*g[14] + tg*f[14];
y[14] += tf*g[3] + tg*f[3];
t = f[3] * g[14] + f[14] * g[3];
y[21] += CONSTANT(-0.075393004386399995)*t;
y[23] += CONSTANT(0.199471140196999990)*t;
// [3,15]: 8,22,24,
tf = CONSTANT(0.226179013155000000)*f[8] + CONSTANT(-0.043528171378199997)*f[22] + CONSTANT(0.230329432978999990)*f[24];
tg = CONSTANT(0.226179013155000000)*g[8] + CONSTANT(-0.043528171378199997)*g[22] + CONSTANT(0.230329432978999990)*g[24];
y[3] += tf*g[15] + tg*f[15];
y[15] += tf*g[3] + tg*f[3];
t = f[3] * g[15] + f[15] * g[3];
y[8] += CONSTANT(0.226179013155000000)*t;
y[22] += CONSTANT(-0.043528171378199997)*t;
y[24] += CONSTANT(0.230329432978999990)*t;
// [4,4]: 0,6,20,24,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.180223751576000010)*f[6] + CONSTANT(0.040299255967500003)*f[20] + CONSTANT(-0.238413613505999990)*f[24];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.180223751576000010)*g[6] + CONSTANT(0.040299255967500003)*g[20] + CONSTANT(-0.238413613505999990)*g[24];
y[4] += tf*g[4] + tg*f[4];
t = f[4] * g[4];
y[0] += CONSTANT(0.282094791770000020)*t;
y[6] += CONSTANT(-0.180223751576000010)*t;
y[20] += CONSTANT(0.040299255967500003)*t;
y[24] += CONSTANT(-0.238413613505999990)*t;
// [4,5]: 7,21,23,
tf = CONSTANT(0.156078347226000000)*f[7] + CONSTANT(-0.063718718434399996)*f[21] + CONSTANT(-0.168583882835000000)*f[23];
tg = CONSTANT(0.156078347226000000)*g[7] + CONSTANT(-0.063718718434399996)*g[21] + CONSTANT(-0.168583882835000000)*g[23];
y[4] += tf*g[5] + tg*f[5];
y[5] += tf*g[4] + tg*f[4];
t = f[4] * g[5] + f[5] * g[4];
y[7] += CONSTANT(0.156078347226000000)*t;
y[21] += CONSTANT(-0.063718718434399996)*t;
y[23] += CONSTANT(-0.168583882835000000)*t;
// [4,11]: 3,13,15,
tf = CONSTANT(-0.058399170082300000)*f[3] + CONSTANT(0.145673124078000010)*f[13] + CONSTANT(0.094031597258400004)*f[15];
tg = CONSTANT(-0.058399170082300000)*g[3] + CONSTANT(0.145673124078000010)*g[13] + CONSTANT(0.094031597258400004)*g[15];
y[4] += tf*g[11] + tg*f[11];
y[11] += tf*g[4] + tg*f[4];
t = f[4] * g[11] + f[11] * g[4];
y[3] += CONSTANT(-0.058399170082300000)*t;
y[13] += CONSTANT(0.145673124078000010)*t;
y[15] += CONSTANT(0.094031597258400004)*t;
// [4,16]: 8,22,
tf = CONSTANT(0.238413613494000000)*f[8] + CONSTANT(-0.075080816693699995)*f[22];
tg = CONSTANT(0.238413613494000000)*g[8] + CONSTANT(-0.075080816693699995)*g[22];
y[4] += tf*g[16] + tg*f[16];
y[16] += tf*g[4] + tg*f[4];
t = f[4] * g[16] + f[16] * g[4];
y[8] += CONSTANT(0.238413613494000000)*t;
y[22] += CONSTANT(-0.075080816693699995)*t;
// [4,18]: 6,20,24,
tf = CONSTANT(0.156078347226000000)*f[6] + CONSTANT(-0.190364615029000010)*f[20] + CONSTANT(0.075080816691500005)*f[24];
tg = CONSTANT(0.156078347226000000)*g[6] + CONSTANT(-0.190364615029000010)*g[20] + CONSTANT(0.075080816691500005)*g[24];
y[4] += tf*g[18] + tg*f[18];
y[18] += tf*g[4] + tg*f[4];
t = f[4] * g[18] + f[18] * g[4];
y[6] += CONSTANT(0.156078347226000000)*t;
y[20] += CONSTANT(-0.190364615029000010)*t;
y[24] += CONSTANT(0.075080816691500005)*t;
// [4,19]: 7,21,23,
tf = CONSTANT(-0.063718718434399996)*f[7] + CONSTANT(0.141889406569999990)*f[21] + CONSTANT(0.112621225039000000)*f[23];
tg = CONSTANT(-0.063718718434399996)*g[7] + CONSTANT(0.141889406569999990)*g[21] + CONSTANT(0.112621225039000000)*g[23];
y[4] += tf*g[19] + tg*f[19];
y[19] += tf*g[4] + tg*f[4];
t = f[4] * g[19] + f[19] * g[4];
y[7] += CONSTANT(-0.063718718434399996)*t;
y[21] += CONSTANT(0.141889406569999990)*t;
y[23] += CONSTANT(0.112621225039000000)*t;
// [5,5]: 0,6,8,20,22,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.090111875786499998)*f[6] + CONSTANT(-0.156078347227999990)*f[8] + CONSTANT(-0.161197023870999990)*f[20] + CONSTANT(-0.180223751574000000)*f[22];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.090111875786499998)*g[6] + CONSTANT(-0.156078347227999990)*g[8] + CONSTANT(-0.161197023870999990)*g[20] + CONSTANT(-0.180223751574000000)*g[22];
y[5] += tf*g[5] + tg*f[5];
t = f[5] * g[5];
y[0] += CONSTANT(0.282094791773999990)*t;
y[6] += CONSTANT(0.090111875786499998)*t;
y[8] += CONSTANT(-0.156078347227999990)*t;
y[20] += CONSTANT(-0.161197023870999990)*t;
y[22] += CONSTANT(-0.180223751574000000)*t;
// [5,11]: 2,12,14,
tf = CONSTANT(0.233596680327000010)*f[2] + CONSTANT(0.059470803871800003)*f[12] + CONSTANT(-0.115164716491000000)*f[14];
tg = CONSTANT(0.233596680327000010)*g[2] + CONSTANT(0.059470803871800003)*g[12] + CONSTANT(-0.115164716491000000)*g[14];
y[5] += tf*g[11] + tg*f[11];
y[11] += tf*g[5] + tg*f[5];
t = f[5] * g[11] + f[11] * g[5];
y[2] += CONSTANT(0.233596680327000010)*t;
y[12] += CONSTANT(0.059470803871800003)*t;
y[14] += CONSTANT(-0.115164716491000000)*t;
// [5,17]: 8,22,24,
tf = CONSTANT(0.168583882832999990)*f[8] + CONSTANT(0.132725386548000010)*f[22] + CONSTANT(-0.140463346189000000)*f[24];
tg = CONSTANT(0.168583882832999990)*g[8] + CONSTANT(0.132725386548000010)*g[22] + CONSTANT(-0.140463346189000000)*g[24];
y[5] += tf*g[17] + tg*f[17];
y[17] += tf*g[5] + tg*f[5];
t = f[5] * g[17] + f[17] * g[5];
y[8] += CONSTANT(0.168583882832999990)*t;
y[22] += CONSTANT(0.132725386548000010)*t;
y[24] += CONSTANT(-0.140463346189000000)*t;
// [5,18]: 7,21,23,
tf = CONSTANT(0.180223751571000010)*f[7] + CONSTANT(0.090297865407399994)*f[21] + CONSTANT(-0.132725386549000010)*f[23];
tg = CONSTANT(0.180223751571000010)*g[7] + CONSTANT(0.090297865407399994)*g[21] + CONSTANT(-0.132725386549000010)*g[23];
y[5] += tf*g[18] + tg*f[18];
y[18] += tf*g[5] + tg*f[5];
t = f[5] * g[18] + f[18] * g[5];
y[7] += CONSTANT(0.180223751571000010)*t;
y[21] += CONSTANT(0.090297865407399994)*t;
y[23] += CONSTANT(-0.132725386549000010)*t;
// [5,19]: 6,8,20,22,
tf = CONSTANT(0.220728115440999990)*f[6] + CONSTANT(0.063718718433900007)*f[8] + CONSTANT(0.044869370061299998)*f[20] + CONSTANT(-0.090297865408399999)*f[22];
tg = CONSTANT(0.220728115440999990)*g[6] + CONSTANT(0.063718718433900007)*g[8] + CONSTANT(0.044869370061299998)*g[20] + CONSTANT(-0.090297865408399999)*g[22];
y[5] += tf*g[19] + tg*f[19];
y[19] += tf*g[5] + tg*f[5];
t = f[5] * g[19] + f[19] * g[5];
y[6] += CONSTANT(0.220728115440999990)*t;
y[8] += CONSTANT(0.063718718433900007)*t;
y[20] += CONSTANT(0.044869370061299998)*t;
y[22] += CONSTANT(-0.090297865408399999)*t;
// [6,6]: 0,6,20,
tf = CONSTANT(0.282094797560000000)*f[0] + CONSTANT(0.241795553185999990)*f[20];
tg = CONSTANT(0.282094797560000000)*g[0] + CONSTANT(0.241795553185999990)*g[20];
y[6] += tf*g[6] + tg*f[6];
t = f[6] * g[6];
y[0] += CONSTANT(0.282094797560000000)*t;
y[6] += CONSTANT(0.180223764527000010)*t;
y[20] += CONSTANT(0.241795553185999990)*t;
// [7,7]: 6,0,8,20,22,
tf = CONSTANT(0.090111875786499998)*f[6] + CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.156078347227999990)*f[8] + CONSTANT(-0.161197023870999990)*f[20] + CONSTANT(0.180223751574000000)*f[22];
tg = CONSTANT(0.090111875786499998)*g[6] + CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.156078347227999990)*g[8] + CONSTANT(-0.161197023870999990)*g[20] + CONSTANT(0.180223751574000000)*g[22];
y[7] += tf*g[7] + tg*f[7];
t = f[7] * g[7];
y[6] += CONSTANT(0.090111875786499998)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
y[8] += CONSTANT(0.156078347227999990)*t;
y[20] += CONSTANT(-0.161197023870999990)*t;
y[22] += CONSTANT(0.180223751574000000)*t;
// [7,13]: 12,2,14,
tf = CONSTANT(0.059470803871800003)*f[12] + CONSTANT(0.233596680327000010)*f[2] + CONSTANT(0.115164716491000000)*f[14];
tg = CONSTANT(0.059470803871800003)*g[12] + CONSTANT(0.233596680327000010)*g[2] + CONSTANT(0.115164716491000000)*g[14];
y[7] += tf*g[13] + tg*f[13];
y[13] += tf*g[7] + tg*f[7];
t = f[7] * g[13] + f[13] * g[7];
y[12] += CONSTANT(0.059470803871800003)*t;
y[2] += CONSTANT(0.233596680327000010)*t;
y[14] += CONSTANT(0.115164716491000000)*t;
// [7,17]: 16,4,18,
tf = CONSTANT(0.140463346187999990)*f[16] + CONSTANT(0.168583882835000000)*f[4] + CONSTANT(0.132725386549000010)*f[18];
tg = CONSTANT(0.140463346187999990)*g[16] + CONSTANT(0.168583882835000000)*g[4] + CONSTANT(0.132725386549000010)*g[18];
y[7] += tf*g[17] + tg*f[17];
y[17] += tf*g[7] + tg*f[7];
t = f[7] * g[17] + f[17] * g[7];
y[16] += CONSTANT(0.140463346187999990)*t;
y[4] += CONSTANT(0.168583882835000000)*t;
y[18] += CONSTANT(0.132725386549000010)*t;
// [7,21]: 8,20,6,22,
tf = CONSTANT(-0.063718718433900007)*f[8] + CONSTANT(0.044869370061299998)*f[20] + CONSTANT(0.220728115440999990)*f[6] + CONSTANT(0.090297865408399999)*f[22];
tg = CONSTANT(-0.063718718433900007)*g[8] + CONSTANT(0.044869370061299998)*g[20] + CONSTANT(0.220728115440999990)*g[6] + CONSTANT(0.090297865408399999)*g[22];
y[7] += tf*g[21] + tg*f[21];
y[21] += tf*g[7] + tg*f[7];
t = f[7] * g[21] + f[21] * g[7];
y[8] += CONSTANT(-0.063718718433900007)*t;
y[20] += CONSTANT(0.044869370061299998)*t;
y[6] += CONSTANT(0.220728115440999990)*t;
y[22] += CONSTANT(0.090297865408399999)*t;
// [7,23]: 8,22,24,
tf = CONSTANT(0.168583882832999990)*f[8] + CONSTANT(0.132725386548000010)*f[22] + CONSTANT(0.140463346189000000)*f[24];
tg = CONSTANT(0.168583882832999990)*g[8] + CONSTANT(0.132725386548000010)*g[22] + CONSTANT(0.140463346189000000)*g[24];
y[7] += tf*g[23] + tg*f[23];
y[23] += tf*g[7] + tg*f[7];
t = f[7] * g[23] + f[23] * g[7];
y[8] += CONSTANT(0.168583882832999990)*t;
y[22] += CONSTANT(0.132725386548000010)*t;
y[24] += CONSTANT(0.140463346189000000)*t;
// [8,8]: 0,6,20,24,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.180223751576000010)*f[6] + CONSTANT(0.040299255967500003)*f[20] + CONSTANT(0.238413613505999990)*f[24];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.180223751576000010)*g[6] + CONSTANT(0.040299255967500003)*g[20] + CONSTANT(0.238413613505999990)*g[24];
y[8] += tf*g[8] + tg*f[8];
t = f[8] * g[8];
y[0] += CONSTANT(0.282094791770000020)*t;
y[6] += CONSTANT(-0.180223751576000010)*t;
y[20] += CONSTANT(0.040299255967500003)*t;
y[24] += CONSTANT(0.238413613505999990)*t;
// [8,22]: 6,20,24,
tf = CONSTANT(0.156078347226000000)*f[6] + CONSTANT(-0.190364615029000010)*f[20] + CONSTANT(-0.075080816691500005)*f[24];
tg = CONSTANT(0.156078347226000000)*g[6] + CONSTANT(-0.190364615029000010)*g[20] + CONSTANT(-0.075080816691500005)*g[24];
y[8] += tf*g[22] + tg*f[22];
y[22] += tf*g[8] + tg*f[8];
t = f[8] * g[22] + f[22] * g[8];
y[6] += CONSTANT(0.156078347226000000)*t;
y[20] += CONSTANT(-0.190364615029000010)*t;
y[24] += CONSTANT(-0.075080816691500005)*t;
// [9,9]: 6,0,20,
tf = CONSTANT(-0.210261043508000010)*f[6] + CONSTANT(0.282094791766999970)*f[0] + CONSTANT(0.076934943209800002)*f[20];
tg = CONSTANT(-0.210261043508000010)*g[6] + CONSTANT(0.282094791766999970)*g[0] + CONSTANT(0.076934943209800002)*g[20];
y[9] += tf*g[9] + tg*f[9];
t = f[9] * g[9];
y[6] += CONSTANT(-0.210261043508000010)*t;
y[0] += CONSTANT(0.282094791766999970)*t;
y[20] += CONSTANT(0.076934943209800002)*t;
// [9,10]: 7,21,
tf = CONSTANT(0.148677009678999990)*f[7] + CONSTANT(-0.099322584599600000)*f[21];
tg = CONSTANT(0.148677009678999990)*g[7] + CONSTANT(-0.099322584599600000)*g[21];
y[9] += tf*g[10] + tg*f[10];
y[10] += tf*g[9] + tg*f[9];
t = f[9] * g[10] + f[10] * g[9];
y[7] += CONSTANT(0.148677009678999990)*t;
y[21] += CONSTANT(-0.099322584599600000)*t;
// [9,11]: 8,22,24,
tf = CONSTANT(-0.094031597259499999)*f[8] + CONSTANT(0.133255230518000010)*f[22] + CONSTANT(0.117520066950999990)*f[24];
tg = CONSTANT(-0.094031597259499999)*g[8] + CONSTANT(0.133255230518000010)*g[22] + CONSTANT(0.117520066950999990)*g[24];
y[9] += tf*g[11] + tg*f[11];
y[11] += tf*g[9] + tg*f[9];
t = f[9] * g[11] + f[11] * g[9];
y[8] += CONSTANT(-0.094031597259499999)*t;
y[22] += CONSTANT(0.133255230518000010)*t;
y[24] += CONSTANT(0.117520066950999990)*t;
// [9,13]: 4,16,18,
tf = CONSTANT(-0.094031597258400004)*f[4] + CONSTANT(-0.117520066953000000)*f[16] + CONSTANT(0.133255230519000010)*f[18];
tg = CONSTANT(-0.094031597258400004)*g[4] + CONSTANT(-0.117520066953000000)*g[16] + CONSTANT(0.133255230519000010)*g[18];
y[9] += tf*g[13] + tg*f[13];
y[13] += tf*g[9] + tg*f[9];
t = f[9] * g[13] + f[13] * g[9];
y[4] += CONSTANT(-0.094031597258400004)*t;
y[16] += CONSTANT(-0.117520066953000000)*t;
y[18] += CONSTANT(0.133255230519000010)*t;
// [9,14]: 5,19,
tf = CONSTANT(0.148677009677999990)*f[5] + CONSTANT(-0.099322584600699995)*f[19];
tg = CONSTANT(0.148677009677999990)*g[5] + CONSTANT(-0.099322584600699995)*g[19];
y[9] += tf*g[14] + tg*f[14];
y[14] += tf*g[9] + tg*f[9];
t = f[9] * g[14] + f[14] * g[9];
y[5] += CONSTANT(0.148677009677999990)*t;
y[19] += CONSTANT(-0.099322584600699995)*t;
// [9,17]: 2,12,
tf = CONSTANT(0.162867503964999990)*f[2] + CONSTANT(-0.203550726872999990)*f[12];
tg = CONSTANT(0.162867503964999990)*g[2] + CONSTANT(-0.203550726872999990)*g[12];
y[9] += tf*g[17] + tg*f[17];
y[17] += tf*g[9] + tg*f[9];
t = f[9] * g[17] + f[17] * g[9];
y[2] += CONSTANT(0.162867503964999990)*t;
y[12] += CONSTANT(-0.203550726872999990)*t;
// [10,10]: 0,20,24,
tf = CONSTANT(0.282094791771999980)*f[0] + CONSTANT(-0.179514867494000000)*f[20] + CONSTANT(-0.151717754049000010)*f[24];
tg = CONSTANT(0.282094791771999980)*g[0] + CONSTANT(-0.179514867494000000)*g[20] + CONSTANT(-0.151717754049000010)*g[24];
y[10] += tf*g[10] + tg*f[10];
t = f[10] * g[10];
y[0] += CONSTANT(0.282094791771999980)*t;
y[20] += CONSTANT(-0.179514867494000000)*t;
y[24] += CONSTANT(-0.151717754049000010)*t;
// [10,11]: 7,21,23,
tf = CONSTANT(0.115164716490000000)*f[7] + CONSTANT(0.102579924281000000)*f[21] + CONSTANT(-0.067850242288900006)*f[23];
tg = CONSTANT(0.115164716490000000)*g[7] + CONSTANT(0.102579924281000000)*g[21] + CONSTANT(-0.067850242288900006)*g[23];
y[10] += tf*g[11] + tg*f[11];
y[11] += tf*g[10] + tg*f[10];
t = f[10] * g[11] + f[11] * g[10];
y[7] += CONSTANT(0.115164716490000000)*t;
y[21] += CONSTANT(0.102579924281000000)*t;
y[23] += CONSTANT(-0.067850242288900006)*t;
// [10,12]: 4,18,
tf = CONSTANT(-0.188063194517999990)*f[4] + CONSTANT(-0.044418410173299998)*f[18];
tg = CONSTANT(-0.188063194517999990)*g[4] + CONSTANT(-0.044418410173299998)*g[18];
y[10] += tf*g[12] + tg*f[12];
y[12] += tf*g[10] + tg*f[10];
t = f[10] * g[12] + f[12] * g[10];
y[4] += CONSTANT(-0.188063194517999990)*t;
y[18] += CONSTANT(-0.044418410173299998)*t;
// [10,13]: 5,17,19,
tf = CONSTANT(0.115164716490000000)*f[5] + CONSTANT(0.067850242288900006)*f[17] + CONSTANT(0.102579924281000000)*f[19];
tg = CONSTANT(0.115164716490000000)*g[5] + CONSTANT(0.067850242288900006)*g[17] + CONSTANT(0.102579924281000000)*g[19];
y[10] += tf*g[13] + tg*f[13];
y[13] += tf*g[10] + tg*f[10];
t = f[10] * g[13] + f[13] * g[10];
y[5] += CONSTANT(0.115164716490000000)*t;
y[17] += CONSTANT(0.067850242288900006)*t;
y[19] += CONSTANT(0.102579924281000000)*t;
// [10,14]: 16,
tf = CONSTANT(0.151717754044999990)*f[16];
tg = CONSTANT(0.151717754044999990)*g[16];
y[10] += tf*g[14] + tg*f[14];
y[14] += tf*g[10] + tg*f[10];
t = f[10] * g[14] + f[14] * g[10];
y[16] += CONSTANT(0.151717754044999990)*t;
// [10,15]: 5,19,
tf = CONSTANT(-0.148677009678999990)*f[5] + CONSTANT(0.099322584599600000)*f[19];
tg = CONSTANT(-0.148677009678999990)*g[5] + CONSTANT(0.099322584599600000)*g[19];
y[10] += tf*g[15] + tg*f[15];
y[15] += tf*g[10] + tg*f[10];
t = f[10] * g[15] + f[15] * g[10];
y[5] += CONSTANT(-0.148677009678999990)*t;
y[19] += CONSTANT(0.099322584599600000)*t;
// [11,11]: 0,6,8,20,22,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.126156626101000010)*f[6] + CONSTANT(-0.145673124078999990)*f[8] + CONSTANT(0.025644981070299999)*f[20] + CONSTANT(-0.114687841910000000)*f[22];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.126156626101000010)*g[6] + CONSTANT(-0.145673124078999990)*g[8] + CONSTANT(0.025644981070299999)*g[20] + CONSTANT(-0.114687841910000000)*g[22];
y[11] += tf*g[11] + tg*f[11];
t = f[11] * g[11];
y[0] += CONSTANT(0.282094791773999990)*t;
y[6] += CONSTANT(0.126156626101000010)*t;
y[8] += CONSTANT(-0.145673124078999990)*t;
y[20] += CONSTANT(0.025644981070299999)*t;
y[22] += CONSTANT(-0.114687841910000000)*t;
// [11,14]: 17,
tf = CONSTANT(0.067850242288500007)*f[17];
tg = CONSTANT(0.067850242288500007)*g[17];
y[11] += tf*g[14] + tg*f[14];
y[14] += tf*g[11] + tg*f[11];
t = f[11] * g[14] + f[14] * g[11];
y[17] += CONSTANT(0.067850242288500007)*t;
// [11,15]: 16,
tf = CONSTANT(-0.117520066953000000)*f[16];
tg = CONSTANT(-0.117520066953000000)*g[16];
y[11] += tf*g[15] + tg*f[15];
y[15] += tf*g[11] + tg*f[11];
t = f[11] * g[15] + f[15] * g[11];
y[16] += CONSTANT(-0.117520066953000000)*t;
// [11,18]: 3,13,15,
tf = CONSTANT(0.168583882834000000)*f[3] + CONSTANT(0.114687841909000000)*f[13] + CONSTANT(-0.133255230519000010)*f[15];
tg = CONSTANT(0.168583882834000000)*g[3] + CONSTANT(0.114687841909000000)*g[13] + CONSTANT(-0.133255230519000010)*g[15];
y[11] += tf*g[18] + tg*f[18];
y[18] += tf*g[11] + tg*f[11];
t = f[11] * g[18] + f[18] * g[11];
y[3] += CONSTANT(0.168583882834000000)*t;
y[13] += CONSTANT(0.114687841909000000)*t;
y[15] += CONSTANT(-0.133255230519000010)*t;
// [11,19]: 2,14,12,
tf = CONSTANT(0.238413613504000000)*f[2] + CONSTANT(-0.102579924282000000)*f[14] + CONSTANT(0.099322584599300004)*f[12];
tg = CONSTANT(0.238413613504000000)*g[2] + CONSTANT(-0.102579924282000000)*g[14] + CONSTANT(0.099322584599300004)*g[12];
y[11] += tf*g[19] + tg*f[19];
y[19] += tf*g[11] + tg*f[11];
t = f[11] * g[19] + f[19] * g[11];
y[2] += CONSTANT(0.238413613504000000)*t;
y[14] += CONSTANT(-0.102579924282000000)*t;
y[12] += CONSTANT(0.099322584599300004)*t;
// [12,12]: 0,6,20,
tf = CONSTANT(0.282094799871999980)*f[0] + CONSTANT(0.168208852954000010)*f[6] + CONSTANT(0.153869910786000010)*f[20];
tg = CONSTANT(0.282094799871999980)*g[0] + CONSTANT(0.168208852954000010)*g[6] + CONSTANT(0.153869910786000010)*g[20];
y[12] += tf*g[12] + tg*f[12];
t = f[12] * g[12];
y[0] += CONSTANT(0.282094799871999980)*t;
y[6] += CONSTANT(0.168208852954000010)*t;
y[20] += CONSTANT(0.153869910786000010)*t;
// [12,14]: 8,22,
tf = CONSTANT(-0.188063194517999990)*f[8] + CONSTANT(-0.044418410173299998)*f[22];
tg = CONSTANT(-0.188063194517999990)*g[8] + CONSTANT(-0.044418410173299998)*g[22];
y[12] += tf*g[14] + tg*f[14];
y[14] += tf*g[12] + tg*f[12];
t = f[12] * g[14] + f[14] * g[12];
y[8] += CONSTANT(-0.188063194517999990)*t;
y[22] += CONSTANT(-0.044418410173299998)*t;
// [13,13]: 0,8,6,20,22,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.145673124078999990)*f[8] + CONSTANT(0.126156626101000010)*f[6] + CONSTANT(0.025644981070299999)*f[20] + CONSTANT(0.114687841910000000)*f[22];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.145673124078999990)*g[8] + CONSTANT(0.126156626101000010)*g[6] + CONSTANT(0.025644981070299999)*g[20] + CONSTANT(0.114687841910000000)*g[22];
y[13] += tf*g[13] + tg*f[13];
t = f[13] * g[13];
y[0] += CONSTANT(0.282094791773999990)*t;
y[8] += CONSTANT(0.145673124078999990)*t;
y[6] += CONSTANT(0.126156626101000010)*t;
y[20] += CONSTANT(0.025644981070299999)*t;
y[22] += CONSTANT(0.114687841910000000)*t;
// [13,14]: 23,
tf = CONSTANT(0.067850242288500007)*f[23];
tg = CONSTANT(0.067850242288500007)*g[23];
y[13] += tf*g[14] + tg*f[14];
y[14] += tf*g[13] + tg*f[13];
t = f[13] * g[14] + f[14] * g[13];
y[23] += CONSTANT(0.067850242288500007)*t;
// [13,15]: 8,22,24,
tf = CONSTANT(-0.094031597259499999)*f[8] + CONSTANT(0.133255230518000010)*f[22] + CONSTANT(-0.117520066950999990)*f[24];
tg = CONSTANT(-0.094031597259499999)*g[8] + CONSTANT(0.133255230518000010)*g[22] + CONSTANT(-0.117520066950999990)*g[24];
y[13] += tf*g[15] + tg*f[15];
y[15] += tf*g[13] + tg*f[13];
t = f[13] * g[15] + f[15] * g[13];
y[8] += CONSTANT(-0.094031597259499999)*t;
y[22] += CONSTANT(0.133255230518000010)*t;
y[24] += CONSTANT(-0.117520066950999990)*t;
// [13,21]: 2,12,14,
tf = CONSTANT(0.238413613504000000)*f[2] + CONSTANT(0.099322584599300004)*f[12] + CONSTANT(0.102579924282000000)*f[14];
tg = CONSTANT(0.238413613504000000)*g[2] + CONSTANT(0.099322584599300004)*g[12] + CONSTANT(0.102579924282000000)*g[14];
y[13] += tf*g[21] + tg*f[21];
y[21] += tf*g[13] + tg*f[13];
t = f[13] * g[21] + f[21] * g[13];
y[2] += CONSTANT(0.238413613504000000)*t;
y[12] += CONSTANT(0.099322584599300004)*t;
y[14] += CONSTANT(0.102579924282000000)*t;
// [14,14]: 0,20,24,
tf = CONSTANT(0.282094791771999980)*f[0] + CONSTANT(-0.179514867494000000)*f[20] + CONSTANT(0.151717754049000010)*f[24];
tg = CONSTANT(0.282094791771999980)*g[0] + CONSTANT(-0.179514867494000000)*g[20] + CONSTANT(0.151717754049000010)*g[24];
y[14] += tf*g[14] + tg*f[14];
t = f[14] * g[14];
y[0] += CONSTANT(0.282094791771999980)*t;
y[20] += CONSTANT(-0.179514867494000000)*t;
y[24] += CONSTANT(0.151717754049000010)*t;
// [14,15]: 7,21,
tf = CONSTANT(0.148677009677999990)*f[7] + CONSTANT(-0.099322584600699995)*f[21];
tg = CONSTANT(0.148677009677999990)*g[7] + CONSTANT(-0.099322584600699995)*g[21];
y[14] += tf*g[15] + tg*f[15];
y[15] += tf*g[14] + tg*f[14];
t = f[14] * g[15] + f[15] * g[14];
y[7] += CONSTANT(0.148677009677999990)*t;
y[21] += CONSTANT(-0.099322584600699995)*t;
// [15,15]: 0,6,20,
tf = CONSTANT(0.282094791766999970)*f[0] + CONSTANT(-0.210261043508000010)*f[6] + CONSTANT(0.076934943209800002)*f[20];
tg = CONSTANT(0.282094791766999970)*g[0] + CONSTANT(-0.210261043508000010)*g[6] + CONSTANT(0.076934943209800002)*g[20];
y[15] += tf*g[15] + tg*f[15];
t = f[15] * g[15];
y[0] += CONSTANT(0.282094791766999970)*t;
y[6] += CONSTANT(-0.210261043508000010)*t;
y[20] += CONSTANT(0.076934943209800002)*t;
// [15,23]: 12,2,
tf = CONSTANT(-0.203550726872999990)*f[12] + CONSTANT(0.162867503964999990)*f[2];
tg = CONSTANT(-0.203550726872999990)*g[12] + CONSTANT(0.162867503964999990)*g[2];
y[15] += tf*g[23] + tg*f[23];
y[23] += tf*g[15] + tg*f[15];
t = f[15] * g[23] + f[23] * g[15];
y[12] += CONSTANT(-0.203550726872999990)*t;
y[2] += CONSTANT(0.162867503964999990)*t;
// [16,16]: 0,6,20,
tf = CONSTANT(0.282094791763999990)*f[0] + CONSTANT(-0.229375683829000000)*f[6] + CONSTANT(0.106525305981000000)*f[20];
tg = CONSTANT(0.282094791763999990)*g[0] + CONSTANT(-0.229375683829000000)*g[6] + CONSTANT(0.106525305981000000)*g[20];
y[16] += tf*g[16] + tg*f[16];
t = f[16] * g[16];
y[0] += CONSTANT(0.282094791763999990)*t;
y[6] += CONSTANT(-0.229375683829000000)*t;
y[20] += CONSTANT(0.106525305981000000)*t;
// [16,18]: 8,22,
tf = CONSTANT(-0.075080816693699995)*f[8] + CONSTANT(0.135045473380000000)*f[22];
tg = CONSTANT(-0.075080816693699995)*g[8] + CONSTANT(0.135045473380000000)*g[22];
y[16] += tf*g[18] + tg*f[18];
y[18] += tf*g[16] + tg*f[16];
t = f[16] * g[18] + f[18] * g[16];
y[8] += CONSTANT(-0.075080816693699995)*t;
y[22] += CONSTANT(0.135045473380000000)*t;
// [16,23]: 19,5,
tf = CONSTANT(-0.119098912754999990)*f[19] + CONSTANT(0.140463346187999990)*f[5];
tg = CONSTANT(-0.119098912754999990)*g[19] + CONSTANT(0.140463346187999990)*g[5];
y[16] += tf*g[23] + tg*f[23];
y[23] += tf*g[16] + tg*f[16];
t = f[16] * g[23] + f[23] * g[16];
y[19] += CONSTANT(-0.119098912754999990)*t;
y[5] += CONSTANT(0.140463346187999990)*t;
// [17,17]: 0,6,20,
tf = CONSTANT(0.282094791768999990)*f[0] + CONSTANT(-0.057343920955899998)*f[6] + CONSTANT(-0.159787958979000000)*f[20];
tg = CONSTANT(0.282094791768999990)*g[0] + CONSTANT(-0.057343920955899998)*g[6] + CONSTANT(-0.159787958979000000)*g[20];
y[17] += tf*g[17] + tg*f[17];
t = f[17] * g[17];
y[0] += CONSTANT(0.282094791768999990)*t;
y[6] += CONSTANT(-0.057343920955899998)*t;
y[20] += CONSTANT(-0.159787958979000000)*t;
// [17,19]: 8,22,24,
tf = CONSTANT(-0.112621225039000000)*f[8] + CONSTANT(0.045015157794100001)*f[22] + CONSTANT(0.119098912753000000)*f[24];
tg = CONSTANT(-0.112621225039000000)*g[8] + CONSTANT(0.045015157794100001)*g[22] + CONSTANT(0.119098912753000000)*g[24];
y[17] += tf*g[19] + tg*f[19];
y[19] += tf*g[17] + tg*f[17];
t = f[17] * g[19] + f[19] * g[17];
y[8] += CONSTANT(-0.112621225039000000)*t;
y[22] += CONSTANT(0.045015157794100001)*t;
y[24] += CONSTANT(0.119098912753000000)*t;
// [17,21]: 16,4,18,
tf = CONSTANT(-0.119098912754999990)*f[16] + CONSTANT(-0.112621225039000000)*f[4] + CONSTANT(0.045015157794399997)*f[18];
tg = CONSTANT(-0.119098912754999990)*g[16] + CONSTANT(-0.112621225039000000)*g[4] + CONSTANT(0.045015157794399997)*g[18];
y[17] += tf*g[21] + tg*f[21];
y[21] += tf*g[17] + tg*f[17];
t = f[17] * g[21] + f[21] * g[17];
y[16] += CONSTANT(-0.119098912754999990)*t;
y[4] += CONSTANT(-0.112621225039000000)*t;
y[18] += CONSTANT(0.045015157794399997)*t;
// [18,18]: 6,0,20,24,
tf = CONSTANT(0.065535909662600006)*f[6] + CONSTANT(0.282094791771999980)*f[0] + CONSTANT(-0.083698454702400005)*f[20] + CONSTANT(-0.135045473384000000)*f[24];
tg = CONSTANT(0.065535909662600006)*g[6] + CONSTANT(0.282094791771999980)*g[0] + CONSTANT(-0.083698454702400005)*g[20] + CONSTANT(-0.135045473384000000)*g[24];
y[18] += tf*g[18] + tg*f[18];
t = f[18] * g[18];
y[6] += CONSTANT(0.065535909662600006)*t;
y[0] += CONSTANT(0.282094791771999980)*t;
y[20] += CONSTANT(-0.083698454702400005)*t;
y[24] += CONSTANT(-0.135045473384000000)*t;
// [18,19]: 7,21,23,
tf = CONSTANT(0.090297865407399994)*f[7] + CONSTANT(0.102084782359000000)*f[21] + CONSTANT(-0.045015157794399997)*f[23];
tg = CONSTANT(0.090297865407399994)*g[7] + CONSTANT(0.102084782359000000)*g[21] + CONSTANT(-0.045015157794399997)*g[23];
y[18] += tf*g[19] + tg*f[19];
y[19] += tf*g[18] + tg*f[18];
t = f[18] * g[19] + f[19] * g[18];
y[7] += CONSTANT(0.090297865407399994)*t;
y[21] += CONSTANT(0.102084782359000000)*t;
y[23] += CONSTANT(-0.045015157794399997)*t;
// [19,19]: 6,8,0,20,22,
tf = CONSTANT(0.139263808033999990)*f[6] + CONSTANT(-0.141889406570999990)*f[8] + CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.068480553847200004)*f[20] + CONSTANT(-0.102084782360000000)*f[22];
tg = CONSTANT(0.139263808033999990)*g[6] + CONSTANT(-0.141889406570999990)*g[8] + CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.068480553847200004)*g[20] + CONSTANT(-0.102084782360000000)*g[22];
y[19] += tf*g[19] + tg*f[19];
t = f[19] * g[19];
y[6] += CONSTANT(0.139263808033999990)*t;
y[8] += CONSTANT(-0.141889406570999990)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
y[20] += CONSTANT(0.068480553847200004)*t;
y[22] += CONSTANT(-0.102084782360000000)*t;
// [20,20]: 6,0,20,
tf = CONSTANT(0.163839797503000010)*f[6] + CONSTANT(0.282094802232000010)*f[0];
tg = CONSTANT(0.163839797503000010)*g[6] + CONSTANT(0.282094802232000010)*g[0];
y[20] += tf*g[20] + tg*f[20];
t = f[20] * g[20];
y[6] += CONSTANT(0.163839797503000010)*t;
y[0] += CONSTANT(0.282094802232000010)*t;
y[20] += CONSTANT(0.136961139005999990)*t;
// [21,21]: 6,20,0,8,22,
tf = CONSTANT(0.139263808033999990)*f[6] + CONSTANT(0.068480553847200004)*f[20] + CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.141889406570999990)*f[8] + CONSTANT(0.102084782360000000)*f[22];
tg = CONSTANT(0.139263808033999990)*g[6] + CONSTANT(0.068480553847200004)*g[20] + CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.141889406570999990)*g[8] + CONSTANT(0.102084782360000000)*g[22];
y[21] += tf*g[21] + tg*f[21];
t = f[21] * g[21];
y[6] += CONSTANT(0.139263808033999990)*t;
y[20] += CONSTANT(0.068480553847200004)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
y[8] += CONSTANT(0.141889406570999990)*t;
y[22] += CONSTANT(0.102084782360000000)*t;
// [21,23]: 8,22,24,
tf = CONSTANT(-0.112621225039000000)*f[8] + CONSTANT(0.045015157794100001)*f[22] + CONSTANT(-0.119098912753000000)*f[24];
tg = CONSTANT(-0.112621225039000000)*g[8] + CONSTANT(0.045015157794100001)*g[22] + CONSTANT(-0.119098912753000000)*g[24];
y[21] += tf*g[23] + tg*f[23];
y[23] += tf*g[21] + tg*f[21];
t = f[21] * g[23] + f[23] * g[21];
y[8] += CONSTANT(-0.112621225039000000)*t;
y[22] += CONSTANT(0.045015157794100001)*t;
y[24] += CONSTANT(-0.119098912753000000)*t;
// [22,22]: 6,20,0,24,
tf = CONSTANT(0.065535909662600006)*f[6] + CONSTANT(-0.083698454702400005)*f[20] + CONSTANT(0.282094791771999980)*f[0] + CONSTANT(0.135045473384000000)*f[24];
tg = CONSTANT(0.065535909662600006)*g[6] + CONSTANT(-0.083698454702400005)*g[20] + CONSTANT(0.282094791771999980)*g[0] + CONSTANT(0.135045473384000000)*g[24];
y[22] += tf*g[22] + tg*f[22];
t = f[22] * g[22];
y[6] += CONSTANT(0.065535909662600006)*t;
y[20] += CONSTANT(-0.083698454702400005)*t;
y[0] += CONSTANT(0.282094791771999980)*t;
y[24] += CONSTANT(0.135045473384000000)*t;
// [23,23]: 6,20,0,
tf = CONSTANT(-0.057343920955899998)*f[6] + CONSTANT(-0.159787958979000000)*f[20] + CONSTANT(0.282094791768999990)*f[0];
tg = CONSTANT(-0.057343920955899998)*g[6] + CONSTANT(-0.159787958979000000)*g[20] + CONSTANT(0.282094791768999990)*g[0];
y[23] += tf*g[23] + tg*f[23];
t = f[23] * g[23];
y[6] += CONSTANT(-0.057343920955899998)*t;
y[20] += CONSTANT(-0.159787958979000000)*t;
y[0] += CONSTANT(0.282094791768999990)*t;
// [24,24]: 6,0,20,
tf = CONSTANT(-0.229375683829000000)*f[6] + CONSTANT(0.282094791763999990)*f[0] + CONSTANT(0.106525305981000000)*f[20];
tg = CONSTANT(-0.229375683829000000)*g[6] + CONSTANT(0.282094791763999990)*g[0] + CONSTANT(0.106525305981000000)*g[20];
y[24] += tf*g[24] + tg*f[24];
t = f[24] * g[24];
y[6] += CONSTANT(-0.229375683829000000)*t;
y[0] += CONSTANT(0.282094791763999990)*t;
y[20] += CONSTANT(0.106525305981000000)*t;
// multiply count=1135
return y;
}
//-------------------------------------------------------------------------------------
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb232909.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
float* DirectX::XMSHMultiply6(
float *y,
const float *f,
const float *g) noexcept
{
if (!y || !f || !g)
return nullptr;
REAL tf, tg, t;
// [0,0]: 0,
y[0] = CONSTANT(0.282094792935999980)*f[0] * g[0];
// [1,1]: 0,6,8,
tf = CONSTANT(0.282094791773000010)*f[0] + CONSTANT(-0.126156626101000010)*f[6] + CONSTANT(-0.218509686119999990)*f[8];
tg = CONSTANT(0.282094791773000010)*g[0] + CONSTANT(-0.126156626101000010)*g[6] + CONSTANT(-0.218509686119999990)*g[8];
y[1] = tf*g[1] + tg*f[1];
t = f[1] * g[1];
y[0] += CONSTANT(0.282094791773000010)*t;
y[6] = CONSTANT(-0.126156626101000010)*t;
y[8] = CONSTANT(-0.218509686119999990)*t;
// [1,4]: 3,13,15,
tf = CONSTANT(0.218509686114999990)*f[3] + CONSTANT(-0.058399170082300000)*f[13] + CONSTANT(-0.226179013157999990)*f[15];
tg = CONSTANT(0.218509686114999990)*g[3] + CONSTANT(-0.058399170082300000)*g[13] + CONSTANT(-0.226179013157999990)*g[15];
y[1] += tf*g[4] + tg*f[4];
y[4] = tf*g[1] + tg*f[1];
t = f[1] * g[4] + f[4] * g[1];
y[3] = CONSTANT(0.218509686114999990)*t;
y[13] = CONSTANT(-0.058399170082300000)*t;
y[15] = CONSTANT(-0.226179013157999990)*t;
// [1,5]: 2,12,
tf = CONSTANT(0.218509686118000010)*f[2] + CONSTANT(-0.143048168103000000)*f[12];
tg = CONSTANT(0.218509686118000010)*g[2] + CONSTANT(-0.143048168103000000)*g[12];
y[1] += tf*g[5] + tg*f[5];
y[5] = tf*g[1] + tg*f[1];
t = f[1] * g[5] + f[5] * g[1];
y[2] = CONSTANT(0.218509686118000010)*t;
y[12] = CONSTANT(-0.143048168103000000)*t;
// [1,11]: 6,8,20,22,
tf = CONSTANT(0.202300659402999990)*f[6] + CONSTANT(0.058399170081799998)*f[8] + CONSTANT(-0.150786008773000000)*f[20] + CONSTANT(-0.168583882836999990)*f[22];
tg = CONSTANT(0.202300659402999990)*g[6] + CONSTANT(0.058399170081799998)*g[8] + CONSTANT(-0.150786008773000000)*g[20] + CONSTANT(-0.168583882836999990)*g[22];
y[1] += tf*g[11] + tg*f[11];
y[11] = tf*g[1] + tg*f[1];
t = f[1] * g[11] + f[11] * g[1];
y[6] += CONSTANT(0.202300659402999990)*t;
y[8] += CONSTANT(0.058399170081799998)*t;
y[20] = CONSTANT(-0.150786008773000000)*t;
y[22] = CONSTANT(-0.168583882836999990)*t;
// [1,16]: 15,33,35,
tf = CONSTANT(0.230329432973999990)*f[15] + CONSTANT(-0.034723468517399998)*f[33] + CONSTANT(-0.232932108051999990)*f[35];
tg = CONSTANT(0.230329432973999990)*g[15] + CONSTANT(-0.034723468517399998)*g[33] + CONSTANT(-0.232932108051999990)*g[35];
y[1] += tf*g[16] + tg*f[16];
y[16] = tf*g[1] + tg*f[1];
t = f[1] * g[16] + f[16] * g[1];
y[15] += CONSTANT(0.230329432973999990)*t;
y[33] = CONSTANT(-0.034723468517399998)*t;
y[35] = CONSTANT(-0.232932108051999990)*t;
// [1,18]: 15,13,31,33,
tf = CONSTANT(0.043528171377799997)*f[15] + CONSTANT(0.168583882834000000)*f[13] + CONSTANT(-0.085054779966799998)*f[31] + CONSTANT(-0.183739324705999990)*f[33];
tg = CONSTANT(0.043528171377799997)*g[15] + CONSTANT(0.168583882834000000)*g[13] + CONSTANT(-0.085054779966799998)*g[31] + CONSTANT(-0.183739324705999990)*g[33];
y[1] += tf*g[18] + tg*f[18];
y[18] = tf*g[1] + tg*f[1];
t = f[1] * g[18] + f[18] * g[1];
y[15] += CONSTANT(0.043528171377799997)*t;
y[13] += CONSTANT(0.168583882834000000)*t;
y[31] = CONSTANT(-0.085054779966799998)*t;
y[33] += CONSTANT(-0.183739324705999990)*t;
// [1,19]: 14,12,30,32,
tf = CONSTANT(0.075393004386399995)*f[14] + CONSTANT(0.194663900273000010)*f[12] + CONSTANT(-0.155288072037000010)*f[30] + CONSTANT(-0.159122922869999990)*f[32];
tg = CONSTANT(0.075393004386399995)*g[14] + CONSTANT(0.194663900273000010)*g[12] + CONSTANT(-0.155288072037000010)*g[30] + CONSTANT(-0.159122922869999990)*g[32];
y[1] += tf*g[19] + tg*f[19];
y[19] = tf*g[1] + tg*f[1];
t = f[1] * g[19] + f[19] * g[1];
y[14] = CONSTANT(0.075393004386399995)*t;
y[12] += CONSTANT(0.194663900273000010)*t;
y[30] = CONSTANT(-0.155288072037000010)*t;
y[32] = CONSTANT(-0.159122922869999990)*t;
// [1,24]: 9,25,27,
tf = CONSTANT(-0.230329432978999990)*f[9] + CONSTANT(0.232932108049000000)*f[25] + CONSTANT(0.034723468517100002)*f[27];
tg = CONSTANT(-0.230329432978999990)*g[9] + CONSTANT(0.232932108049000000)*g[25] + CONSTANT(0.034723468517100002)*g[27];
y[1] += tf*g[24] + tg*f[24];
y[24] = tf*g[1] + tg*f[1];
t = f[1] * g[24] + f[24] * g[1];
y[9] = CONSTANT(-0.230329432978999990)*t;
y[25] = CONSTANT(0.232932108049000000)*t;
y[27] = CONSTANT(0.034723468517100002)*t;
// [1,29]: 22,20,
tf = CONSTANT(0.085054779965999999)*f[22] + CONSTANT(0.190188269815000010)*f[20];
tg = CONSTANT(0.085054779965999999)*g[22] + CONSTANT(0.190188269815000010)*g[20];
y[1] += tf*g[29] + tg*f[29];
y[29] = tf*g[1] + tg*f[1];
t = f[1] * g[29] + f[29] * g[1];
y[22] += CONSTANT(0.085054779965999999)*t;
y[20] += CONSTANT(0.190188269815000010)*t;
// [2,2]: 0,6,
tf = CONSTANT(0.282094795249000000)*f[0] + CONSTANT(0.252313259986999990)*f[6];
tg = CONSTANT(0.282094795249000000)*g[0] + CONSTANT(0.252313259986999990)*g[6];
y[2] += tf*g[2] + tg*f[2];
t = f[2] * g[2];
y[0] += CONSTANT(0.282094795249000000)*t;
y[6] += CONSTANT(0.252313259986999990)*t;
// [2,12]: 6,20,
tf = CONSTANT(0.247766706973999990)*f[6] + CONSTANT(0.246232537174000010)*f[20];
tg = CONSTANT(0.247766706973999990)*g[6] + CONSTANT(0.246232537174000010)*g[20];
y[2] += tf*g[12] + tg*f[12];
y[12] += tf*g[2] + tg*f[2];
t = f[2] * g[12] + f[12] * g[2];
y[6] += CONSTANT(0.247766706973999990)*t;
y[20] += CONSTANT(0.246232537174000010)*t;
// [2,20]: 30,
tf = CONSTANT(0.245532020560000010)*f[30];
tg = CONSTANT(0.245532020560000010)*g[30];
y[2] += tf*g[20] + tg*f[20];
y[20] += tf*g[2] + tg*f[2];
t = f[2] * g[20] + f[20] * g[2];
y[30] += CONSTANT(0.245532020560000010)*t;
// [3,3]: 0,6,8,
tf = CONSTANT(0.282094791773000010)*f[0] + CONSTANT(-0.126156626101000010)*f[6] + CONSTANT(0.218509686119999990)*f[8];
tg = CONSTANT(0.282094791773000010)*g[0] + CONSTANT(-0.126156626101000010)*g[6] + CONSTANT(0.218509686119999990)*g[8];
y[3] += tf*g[3] + tg*f[3];
t = f[3] * g[3];
y[0] += CONSTANT(0.282094791773000010)*t;
y[6] += CONSTANT(-0.126156626101000010)*t;
y[8] += CONSTANT(0.218509686119999990)*t;
// [3,7]: 2,12,
tf = CONSTANT(0.218509686118000010)*f[2] + CONSTANT(-0.143048168103000000)*f[12];
tg = CONSTANT(0.218509686118000010)*g[2] + CONSTANT(-0.143048168103000000)*g[12];
y[3] += tf*g[7] + tg*f[7];
y[7] = tf*g[3] + tg*f[3];
t = f[3] * g[7] + f[7] * g[3];
y[2] += CONSTANT(0.218509686118000010)*t;
y[12] += CONSTANT(-0.143048168103000000)*t;
// [3,13]: 8,6,20,22,
tf = CONSTANT(-0.058399170081799998)*f[8] + CONSTANT(0.202300659402999990)*f[6] + CONSTANT(-0.150786008773000000)*f[20] + CONSTANT(0.168583882836999990)*f[22];
tg = CONSTANT(-0.058399170081799998)*g[8] + CONSTANT(0.202300659402999990)*g[6] + CONSTANT(-0.150786008773000000)*g[20] + CONSTANT(0.168583882836999990)*g[22];
y[3] += tf*g[13] + tg*f[13];
y[13] += tf*g[3] + tg*f[3];
t = f[3] * g[13] + f[13] * g[3];
y[8] += CONSTANT(-0.058399170081799998)*t;
y[6] += CONSTANT(0.202300659402999990)*t;
y[20] += CONSTANT(-0.150786008773000000)*t;
y[22] += CONSTANT(0.168583882836999990)*t;
// [3,16]: 9,25,27,
tf = CONSTANT(0.230329432973999990)*f[9] + CONSTANT(0.232932108051999990)*f[25] + CONSTANT(-0.034723468517399998)*f[27];
tg = CONSTANT(0.230329432973999990)*g[9] + CONSTANT(0.232932108051999990)*g[25] + CONSTANT(-0.034723468517399998)*g[27];
y[3] += tf*g[16] + tg*f[16];
y[16] += tf*g[3] + tg*f[3];
t = f[3] * g[16] + f[16] * g[3];
y[9] += CONSTANT(0.230329432973999990)*t;
y[25] += CONSTANT(0.232932108051999990)*t;
y[27] += CONSTANT(-0.034723468517399998)*t;
// [3,21]: 12,14,30,32,
tf = CONSTANT(0.194663900273000010)*f[12] + CONSTANT(-0.075393004386399995)*f[14] + CONSTANT(-0.155288072037000010)*f[30] + CONSTANT(0.159122922869999990)*f[32];
tg = CONSTANT(0.194663900273000010)*g[12] + CONSTANT(-0.075393004386399995)*g[14] + CONSTANT(-0.155288072037000010)*g[30] + CONSTANT(0.159122922869999990)*g[32];
y[3] += tf*g[21] + tg*f[21];
y[21] = tf*g[3] + tg*f[3];
t = f[3] * g[21] + f[21] * g[3];
y[12] += CONSTANT(0.194663900273000010)*t;
y[14] += CONSTANT(-0.075393004386399995)*t;
y[30] += CONSTANT(-0.155288072037000010)*t;
y[32] += CONSTANT(0.159122922869999990)*t;
// [3,24]: 15,33,35,
tf = CONSTANT(0.230329432978999990)*f[15] + CONSTANT(-0.034723468517100002)*f[33] + CONSTANT(0.232932108049000000)*f[35];
tg = CONSTANT(0.230329432978999990)*g[15] + CONSTANT(-0.034723468517100002)*g[33] + CONSTANT(0.232932108049000000)*g[35];
y[3] += tf*g[24] + tg*f[24];
y[24] += tf*g[3] + tg*f[3];
t = f[3] * g[24] + f[24] * g[3];
y[15] += CONSTANT(0.230329432978999990)*t;
y[33] += CONSTANT(-0.034723468517100002)*t;
y[35] += CONSTANT(0.232932108049000000)*t;
// [3,31]: 20,22,
tf = CONSTANT(0.190188269815000010)*f[20] + CONSTANT(-0.085054779965999999)*f[22];
tg = CONSTANT(0.190188269815000010)*g[20] + CONSTANT(-0.085054779965999999)*g[22];
y[3] += tf*g[31] + tg*f[31];
y[31] += tf*g[3] + tg*f[3];
t = f[3] * g[31] + f[31] * g[3];
y[20] += CONSTANT(0.190188269815000010)*t;
y[22] += CONSTANT(-0.085054779965999999)*t;
// [4,4]: 0,6,20,24,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.180223751576000010)*f[6] + CONSTANT(0.040299255967500003)*f[20] + CONSTANT(-0.238413613505999990)*f[24];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.180223751576000010)*g[6] + CONSTANT(0.040299255967500003)*g[20] + CONSTANT(-0.238413613505999990)*g[24];
y[4] += tf*g[4] + tg*f[4];
t = f[4] * g[4];
y[0] += CONSTANT(0.282094791770000020)*t;
y[6] += CONSTANT(-0.180223751576000010)*t;
y[20] += CONSTANT(0.040299255967500003)*t;
y[24] += CONSTANT(-0.238413613505999990)*t;
// [4,5]: 7,21,23,
tf = CONSTANT(0.156078347226000000)*f[7] + CONSTANT(-0.063718718434399996)*f[21] + CONSTANT(-0.168583882835000000)*f[23];
tg = CONSTANT(0.156078347226000000)*g[7] + CONSTANT(-0.063718718434399996)*g[21] + CONSTANT(-0.168583882835000000)*g[23];
y[4] += tf*g[5] + tg*f[5];
y[5] += tf*g[4] + tg*f[4];
t = f[4] * g[5] + f[5] * g[4];
y[7] += CONSTANT(0.156078347226000000)*t;
y[21] += CONSTANT(-0.063718718434399996)*t;
y[23] = CONSTANT(-0.168583882835000000)*t;
// [4,9]: 3,13,31,35,
tf = CONSTANT(0.226179013157999990)*f[3] + CONSTANT(-0.094031597258400004)*f[13] + CONSTANT(0.016943317729299998)*f[31] + CONSTANT(-0.245532000542000000)*f[35];
tg = CONSTANT(0.226179013157999990)*g[3] + CONSTANT(-0.094031597258400004)*g[13] + CONSTANT(0.016943317729299998)*g[31] + CONSTANT(-0.245532000542000000)*g[35];
y[4] += tf*g[9] + tg*f[9];
y[9] += tf*g[4] + tg*f[4];
t = f[4] * g[9] + f[9] * g[4];
y[3] += CONSTANT(0.226179013157999990)*t;
y[13] += CONSTANT(-0.094031597258400004)*t;
y[31] += CONSTANT(0.016943317729299998)*t;
y[35] += CONSTANT(-0.245532000542000000)*t;
// [4,10]: 2,12,30,34,
tf = CONSTANT(0.184674390919999990)*f[2] + CONSTANT(-0.188063194517999990)*f[12] + CONSTANT(0.053579475144400000)*f[30] + CONSTANT(-0.190188269816000010)*f[34];
tg = CONSTANT(0.184674390919999990)*g[2] + CONSTANT(-0.188063194517999990)*g[12] + CONSTANT(0.053579475144400000)*g[30] + CONSTANT(-0.190188269816000010)*g[34];
y[4] += tf*g[10] + tg*f[10];
y[10] = tf*g[4] + tg*f[4];
t = f[4] * g[10] + f[10] * g[4];
y[2] += CONSTANT(0.184674390919999990)*t;
y[12] += CONSTANT(-0.188063194517999990)*t;
y[30] += CONSTANT(0.053579475144400000)*t;
y[34] = CONSTANT(-0.190188269816000010)*t;
// [4,11]: 3,13,15,31,33,
tf = CONSTANT(-0.058399170082300000)*f[3] + CONSTANT(0.145673124078000010)*f[13] + CONSTANT(0.094031597258400004)*f[15] + CONSTANT(-0.065621187395699998)*f[31] + CONSTANT(-0.141757966610000010)*f[33];
tg = CONSTANT(-0.058399170082300000)*g[3] + CONSTANT(0.145673124078000010)*g[13] + CONSTANT(0.094031597258400004)*g[15] + CONSTANT(-0.065621187395699998)*g[31] + CONSTANT(-0.141757966610000010)*g[33];
y[4] += tf*g[11] + tg*f[11];
y[11] += tf*g[4] + tg*f[4];
t = f[4] * g[11] + f[11] * g[4];
y[3] += CONSTANT(-0.058399170082300000)*t;
y[13] += CONSTANT(0.145673124078000010)*t;
y[15] += CONSTANT(0.094031597258400004)*t;
y[31] += CONSTANT(-0.065621187395699998)*t;
y[33] += CONSTANT(-0.141757966610000010)*t;
// [4,16]: 8,22,
tf = CONSTANT(0.238413613494000000)*f[8] + CONSTANT(-0.075080816693699995)*f[22];
tg = CONSTANT(0.238413613494000000)*g[8] + CONSTANT(-0.075080816693699995)*g[22];
y[4] += tf*g[16] + tg*f[16];
y[16] += tf*g[4] + tg*f[4];
t = f[4] * g[16] + f[16] * g[4];
y[8] += CONSTANT(0.238413613494000000)*t;
y[22] += CONSTANT(-0.075080816693699995)*t;
// [4,18]: 6,20,24,
tf = CONSTANT(0.156078347226000000)*f[6] + CONSTANT(-0.190364615029000010)*f[20] + CONSTANT(0.075080816691500005)*f[24];
tg = CONSTANT(0.156078347226000000)*g[6] + CONSTANT(-0.190364615029000010)*g[20] + CONSTANT(0.075080816691500005)*g[24];
y[4] += tf*g[18] + tg*f[18];
y[18] += tf*g[4] + tg*f[4];
t = f[4] * g[18] + f[18] * g[4];
y[6] += CONSTANT(0.156078347226000000)*t;
y[20] += CONSTANT(-0.190364615029000010)*t;
y[24] += CONSTANT(0.075080816691500005)*t;
// [4,19]: 7,21,23,
tf = CONSTANT(-0.063718718434399996)*f[7] + CONSTANT(0.141889406569999990)*f[21] + CONSTANT(0.112621225039000000)*f[23];
tg = CONSTANT(-0.063718718434399996)*g[7] + CONSTANT(0.141889406569999990)*g[21] + CONSTANT(0.112621225039000000)*g[23];
y[4] += tf*g[19] + tg*f[19];
y[19] += tf*g[4] + tg*f[4];
t = f[4] * g[19] + f[19] * g[4];
y[7] += CONSTANT(-0.063718718434399996)*t;
y[21] += CONSTANT(0.141889406569999990)*t;
y[23] += CONSTANT(0.112621225039000000)*t;
// [4,25]: 15,33,
tf = CONSTANT(0.245532000542000000)*f[15] + CONSTANT(-0.062641347680800000)*f[33];
tg = CONSTANT(0.245532000542000000)*g[15] + CONSTANT(-0.062641347680800000)*g[33];
y[4] += tf*g[25] + tg*f[25];
y[25] += tf*g[4] + tg*f[4];
t = f[4] * g[25] + f[25] * g[4];
y[15] += CONSTANT(0.245532000542000000)*t;
y[33] += CONSTANT(-0.062641347680800000)*t;
// [4,26]: 14,32,
tf = CONSTANT(0.190188269806999990)*f[14] + CONSTANT(-0.097043558542400002)*f[32];
tg = CONSTANT(0.190188269806999990)*g[14] + CONSTANT(-0.097043558542400002)*g[32];
y[4] += tf*g[26] + tg*f[26];
y[26] = tf*g[4] + tg*f[4];
t = f[4] * g[26] + f[26] * g[4];
y[14] += CONSTANT(0.190188269806999990)*t;
y[32] += CONSTANT(-0.097043558542400002)*t;
// [4,27]: 13,31,35,
tf = CONSTANT(0.141757966610000010)*f[13] + CONSTANT(-0.121034582549000000)*f[31] + CONSTANT(0.062641347680800000)*f[35];
tg = CONSTANT(0.141757966610000010)*g[13] + CONSTANT(-0.121034582549000000)*g[31] + CONSTANT(0.062641347680800000)*g[35];
y[4] += tf*g[27] + tg*f[27];
y[27] += tf*g[4] + tg*f[4];
t = f[4] * g[27] + f[27] * g[4];
y[13] += CONSTANT(0.141757966610000010)*t;
y[31] += CONSTANT(-0.121034582549000000)*t;
y[35] += CONSTANT(0.062641347680800000)*t;
// [4,28]: 12,30,34,
tf = CONSTANT(0.141757966609000000)*f[12] + CONSTANT(-0.191372478254000000)*f[30] + CONSTANT(0.097043558538899996)*f[34];
tg = CONSTANT(0.141757966609000000)*g[12] + CONSTANT(-0.191372478254000000)*g[30] + CONSTANT(0.097043558538899996)*g[34];
y[4] += tf*g[28] + tg*f[28];
y[28] = tf*g[4] + tg*f[4];
t = f[4] * g[28] + f[28] * g[4];
y[12] += CONSTANT(0.141757966609000000)*t;
y[30] += CONSTANT(-0.191372478254000000)*t;
y[34] += CONSTANT(0.097043558538899996)*t;
// [4,29]: 13,15,31,33,
tf = CONSTANT(-0.065621187395699998)*f[13] + CONSTANT(-0.016943317729299998)*f[15] + CONSTANT(0.140070311613999990)*f[31] + CONSTANT(0.121034582549000000)*f[33];
tg = CONSTANT(-0.065621187395699998)*g[13] + CONSTANT(-0.016943317729299998)*g[15] + CONSTANT(0.140070311613999990)*g[31] + CONSTANT(0.121034582549000000)*g[33];
y[4] += tf*g[29] + tg*f[29];
y[29] += tf*g[4] + tg*f[4];
t = f[4] * g[29] + f[29] * g[4];
y[13] += CONSTANT(-0.065621187395699998)*t;
y[15] += CONSTANT(-0.016943317729299998)*t;
y[31] += CONSTANT(0.140070311613999990)*t;
y[33] += CONSTANT(0.121034582549000000)*t;
// [5,5]: 0,6,8,20,22,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.090111875786499998)*f[6] + CONSTANT(-0.156078347227999990)*f[8] + CONSTANT(-0.161197023870999990)*f[20] + CONSTANT(-0.180223751574000000)*f[22];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.090111875786499998)*g[6] + CONSTANT(-0.156078347227999990)*g[8] + CONSTANT(-0.161197023870999990)*g[20] + CONSTANT(-0.180223751574000000)*g[22];
y[5] += tf*g[5] + tg*f[5];
t = f[5] * g[5];
y[0] += CONSTANT(0.282094791773999990)*t;
y[6] += CONSTANT(0.090111875786499998)*t;
y[8] += CONSTANT(-0.156078347227999990)*t;
y[20] += CONSTANT(-0.161197023870999990)*t;
y[22] += CONSTANT(-0.180223751574000000)*t;
// [5,10]: 3,13,15,31,33,
tf = CONSTANT(0.184674390919999990)*f[3] + CONSTANT(0.115164716490000000)*f[13] + CONSTANT(-0.148677009678999990)*f[15] + CONSTANT(-0.083004965974099995)*f[31] + CONSTANT(-0.179311220383999990)*f[33];
tg = CONSTANT(0.184674390919999990)*g[3] + CONSTANT(0.115164716490000000)*g[13] + CONSTANT(-0.148677009678999990)*g[15] + CONSTANT(-0.083004965974099995)*g[31] + CONSTANT(-0.179311220383999990)*g[33];
y[5] += tf*g[10] + tg*f[10];
y[10] += tf*g[5] + tg*f[5];
t = f[5] * g[10] + f[10] * g[5];
y[3] += CONSTANT(0.184674390919999990)*t;
y[13] += CONSTANT(0.115164716490000000)*t;
y[15] += CONSTANT(-0.148677009678999990)*t;
y[31] += CONSTANT(-0.083004965974099995)*t;
y[33] += CONSTANT(-0.179311220383999990)*t;
// [5,11]: 2,12,14,30,32,
tf = CONSTANT(0.233596680327000010)*f[2] + CONSTANT(0.059470803871800003)*f[12] + CONSTANT(-0.115164716491000000)*f[14] + CONSTANT(-0.169433177294000010)*f[30] + CONSTANT(-0.173617342585000000)*f[32];
tg = CONSTANT(0.233596680327000010)*g[2] + CONSTANT(0.059470803871800003)*g[12] + CONSTANT(-0.115164716491000000)*g[14] + CONSTANT(-0.169433177294000010)*g[30] + CONSTANT(-0.173617342585000000)*g[32];
y[5] += tf*g[11] + tg*f[11];
y[11] += tf*g[5] + tg*f[5];
t = f[5] * g[11] + f[11] * g[5];
y[2] += CONSTANT(0.233596680327000010)*t;
y[12] += CONSTANT(0.059470803871800003)*t;
y[14] += CONSTANT(-0.115164716491000000)*t;
y[30] += CONSTANT(-0.169433177294000010)*t;
y[32] += CONSTANT(-0.173617342585000000)*t;
// [5,14]: 9,1,27,29,
tf = CONSTANT(0.148677009677999990)*f[9] + CONSTANT(-0.184674390923000000)*f[1] + CONSTANT(0.179311220382000010)*f[27] + CONSTANT(0.083004965973399999)*f[29];
tg = CONSTANT(0.148677009677999990)*g[9] + CONSTANT(-0.184674390923000000)*g[1] + CONSTANT(0.179311220382000010)*g[27] + CONSTANT(0.083004965973399999)*g[29];
y[5] += tf*g[14] + tg*f[14];
y[14] += tf*g[5] + tg*f[5];
t = f[5] * g[14] + f[14] * g[5];
y[9] += CONSTANT(0.148677009677999990)*t;
y[1] += CONSTANT(-0.184674390923000000)*t;
y[27] += CONSTANT(0.179311220382000010)*t;
y[29] += CONSTANT(0.083004965973399999)*t;
// [5,17]: 8,22,24,
tf = CONSTANT(0.168583882832999990)*f[8] + CONSTANT(0.132725386548000010)*f[22] + CONSTANT(-0.140463346189000000)*f[24];
tg = CONSTANT(0.168583882832999990)*g[8] + CONSTANT(0.132725386548000010)*g[22] + CONSTANT(-0.140463346189000000)*g[24];
y[5] += tf*g[17] + tg*f[17];
y[17] = tf*g[5] + tg*f[5];
t = f[5] * g[17] + f[17] * g[5];
y[8] += CONSTANT(0.168583882832999990)*t;
y[22] += CONSTANT(0.132725386548000010)*t;
y[24] += CONSTANT(-0.140463346189000000)*t;
// [5,18]: 7,21,23,
tf = CONSTANT(0.180223751571000010)*f[7] + CONSTANT(0.090297865407399994)*f[21] + CONSTANT(-0.132725386549000010)*f[23];
tg = CONSTANT(0.180223751571000010)*g[7] + CONSTANT(0.090297865407399994)*g[21] + CONSTANT(-0.132725386549000010)*g[23];
y[5] += tf*g[18] + tg*f[18];
y[18] += tf*g[5] + tg*f[5];
t = f[5] * g[18] + f[18] * g[5];
y[7] += CONSTANT(0.180223751571000010)*t;
y[21] += CONSTANT(0.090297865407399994)*t;
y[23] += CONSTANT(-0.132725386549000010)*t;
// [5,19]: 6,8,20,22,
tf = CONSTANT(0.220728115440999990)*f[6] + CONSTANT(0.063718718433900007)*f[8] + CONSTANT(0.044869370061299998)*f[20] + CONSTANT(-0.090297865408399999)*f[22];
tg = CONSTANT(0.220728115440999990)*g[6] + CONSTANT(0.063718718433900007)*g[8] + CONSTANT(0.044869370061299998)*g[20] + CONSTANT(-0.090297865408399999)*g[22];
y[5] += tf*g[19] + tg*f[19];
y[19] += tf*g[5] + tg*f[5];
t = f[5] * g[19] + f[19] * g[5];
y[6] += CONSTANT(0.220728115440999990)*t;
y[8] += CONSTANT(0.063718718433900007)*t;
y[20] += CONSTANT(0.044869370061299998)*t;
y[22] += CONSTANT(-0.090297865408399999)*t;
// [5,26]: 15,33,35,
tf = CONSTANT(0.155288072035000000)*f[15] + CONSTANT(0.138662534056999990)*f[33] + CONSTANT(-0.132882365179999990)*f[35];
tg = CONSTANT(0.155288072035000000)*g[15] + CONSTANT(0.138662534056999990)*g[33] + CONSTANT(-0.132882365179999990)*g[35];
y[5] += tf*g[26] + tg*f[26];
y[26] += tf*g[5] + tg*f[5];
t = f[5] * g[26] + f[26] * g[5];
y[15] += CONSTANT(0.155288072035000000)*t;
y[33] += CONSTANT(0.138662534056999990)*t;
y[35] += CONSTANT(-0.132882365179999990)*t;
// [5,28]: 15,13,31,33,
tf = CONSTANT(0.044827805096399997)*f[15] + CONSTANT(0.173617342584000000)*f[13] + CONSTANT(0.074118242118699995)*f[31] + CONSTANT(-0.114366930522000000)*f[33];
tg = CONSTANT(0.044827805096399997)*g[15] + CONSTANT(0.173617342584000000)*g[13] + CONSTANT(0.074118242118699995)*g[31] + CONSTANT(-0.114366930522000000)*g[33];
y[5] += tf*g[28] + tg*f[28];
y[28] += tf*g[5] + tg*f[5];
t = f[5] * g[28] + f[28] * g[5];
y[15] += CONSTANT(0.044827805096399997)*t;
y[13] += CONSTANT(0.173617342584000000)*t;
y[31] += CONSTANT(0.074118242118699995)*t;
y[33] += CONSTANT(-0.114366930522000000)*t;
// [5,29]: 12,30,32,
tf = CONSTANT(0.214317900578999990)*f[12] + CONSTANT(0.036165998945399999)*f[30] + CONSTANT(-0.074118242119099995)*f[32];
tg = CONSTANT(0.214317900578999990)*g[12] + CONSTANT(0.036165998945399999)*g[30] + CONSTANT(-0.074118242119099995)*g[32];
y[5] += tf*g[29] + tg*f[29];
y[29] += tf*g[5] + tg*f[5];
t = f[5] * g[29] + f[29] * g[5];
y[12] += CONSTANT(0.214317900578999990)*t;
y[30] += CONSTANT(0.036165998945399999)*t;
y[32] += CONSTANT(-0.074118242119099995)*t;
// [5,32]: 9,27,
tf = CONSTANT(-0.044827805096799997)*f[9] + CONSTANT(0.114366930522000000)*f[27];
tg = CONSTANT(-0.044827805096799997)*g[9] + CONSTANT(0.114366930522000000)*g[27];
y[5] += tf*g[32] + tg*f[32];
y[32] += tf*g[5] + tg*f[5];
t = f[5] * g[32] + f[32] * g[5];
y[9] += CONSTANT(-0.044827805096799997)*t;
y[27] += CONSTANT(0.114366930522000000)*t;
// [5,34]: 9,27,25,
tf = CONSTANT(-0.155288072036000010)*f[9] + CONSTANT(-0.138662534059000000)*f[27] + CONSTANT(0.132882365179000010)*f[25];
tg = CONSTANT(-0.155288072036000010)*g[9] + CONSTANT(-0.138662534059000000)*g[27] + CONSTANT(0.132882365179000010)*g[25];
y[5] += tf*g[34] + tg*f[34];
y[34] += tf*g[5] + tg*f[5];
t = f[5] * g[34] + f[34] * g[5];
y[9] += CONSTANT(-0.155288072036000010)*t;
y[27] += CONSTANT(-0.138662534059000000)*t;
y[25] += CONSTANT(0.132882365179000010)*t;
// [6,6]: 0,6,20,
tf = CONSTANT(0.282094797560000000)*f[0] + CONSTANT(0.241795553185999990)*f[20];
tg = CONSTANT(0.282094797560000000)*g[0] + CONSTANT(0.241795553185999990)*g[20];
y[6] += tf*g[6] + tg*f[6];
t = f[6] * g[6];
y[0] += CONSTANT(0.282094797560000000)*t;
y[6] += CONSTANT(0.180223764527000010)*t;
y[20] += CONSTANT(0.241795553185999990)*t;
// [7,7]: 6,0,8,20,22,
tf = CONSTANT(0.090111875786499998)*f[6] + CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.156078347227999990)*f[8] + CONSTANT(-0.161197023870999990)*f[20] + CONSTANT(0.180223751574000000)*f[22];
tg = CONSTANT(0.090111875786499998)*g[6] + CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.156078347227999990)*g[8] + CONSTANT(-0.161197023870999990)*g[20] + CONSTANT(0.180223751574000000)*g[22];
y[7] += tf*g[7] + tg*f[7];
t = f[7] * g[7];
y[6] += CONSTANT(0.090111875786499998)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
y[8] += CONSTANT(0.156078347227999990)*t;
y[20] += CONSTANT(-0.161197023870999990)*t;
y[22] += CONSTANT(0.180223751574000000)*t;
// [7,10]: 9,1,11,27,29,
tf = CONSTANT(0.148677009678999990)*f[9] + CONSTANT(0.184674390919999990)*f[1] + CONSTANT(0.115164716490000000)*f[11] + CONSTANT(0.179311220383999990)*f[27] + CONSTANT(-0.083004965974099995)*f[29];
tg = CONSTANT(0.148677009678999990)*g[9] + CONSTANT(0.184674390919999990)*g[1] + CONSTANT(0.115164716490000000)*g[11] + CONSTANT(0.179311220383999990)*g[27] + CONSTANT(-0.083004965974099995)*g[29];
y[7] += tf*g[10] + tg*f[10];
y[10] += tf*g[7] + tg*f[7];
t = f[7] * g[10] + f[10] * g[7];
y[9] += CONSTANT(0.148677009678999990)*t;
y[1] += CONSTANT(0.184674390919999990)*t;
y[11] += CONSTANT(0.115164716490000000)*t;
y[27] += CONSTANT(0.179311220383999990)*t;
y[29] += CONSTANT(-0.083004965974099995)*t;
// [7,13]: 12,2,14,30,32,
tf = CONSTANT(0.059470803871800003)*f[12] + CONSTANT(0.233596680327000010)*f[2] + CONSTANT(0.115164716491000000)*f[14] + CONSTANT(-0.169433177294000010)*f[30] + CONSTANT(0.173617342585000000)*f[32];
tg = CONSTANT(0.059470803871800003)*g[12] + CONSTANT(0.233596680327000010)*g[2] + CONSTANT(0.115164716491000000)*g[14] + CONSTANT(-0.169433177294000010)*g[30] + CONSTANT(0.173617342585000000)*g[32];
y[7] += tf*g[13] + tg*f[13];
y[13] += tf*g[7] + tg*f[7];
t = f[7] * g[13] + f[13] * g[7];
y[12] += CONSTANT(0.059470803871800003)*t;
y[2] += CONSTANT(0.233596680327000010)*t;
y[14] += CONSTANT(0.115164716491000000)*t;
y[30] += CONSTANT(-0.169433177294000010)*t;
y[32] += CONSTANT(0.173617342585000000)*t;
// [7,14]: 3,15,31,33,
tf = CONSTANT(0.184674390923000000)*f[3] + CONSTANT(0.148677009677999990)*f[15] + CONSTANT(-0.083004965973399999)*f[31] + CONSTANT(0.179311220382000010)*f[33];
tg = CONSTANT(0.184674390923000000)*g[3] + CONSTANT(0.148677009677999990)*g[15] + CONSTANT(-0.083004965973399999)*g[31] + CONSTANT(0.179311220382000010)*g[33];
y[7] += tf*g[14] + tg*f[14];
y[14] += tf*g[7] + tg*f[7];
t = f[7] * g[14] + f[14] * g[7];
y[3] += CONSTANT(0.184674390923000000)*t;
y[15] += CONSTANT(0.148677009677999990)*t;
y[31] += CONSTANT(-0.083004965973399999)*t;
y[33] += CONSTANT(0.179311220382000010)*t;
// [7,17]: 16,4,18,
tf = CONSTANT(0.140463346187999990)*f[16] + CONSTANT(0.168583882835000000)*f[4] + CONSTANT(0.132725386549000010)*f[18];
tg = CONSTANT(0.140463346187999990)*g[16] + CONSTANT(0.168583882835000000)*g[4] + CONSTANT(0.132725386549000010)*g[18];
y[7] += tf*g[17] + tg*f[17];
y[17] += tf*g[7] + tg*f[7];
t = f[7] * g[17] + f[17] * g[7];
y[16] += CONSTANT(0.140463346187999990)*t;
y[4] += CONSTANT(0.168583882835000000)*t;
y[18] += CONSTANT(0.132725386549000010)*t;
// [7,21]: 8,20,6,22,
tf = CONSTANT(-0.063718718433900007)*f[8] + CONSTANT(0.044869370061299998)*f[20] + CONSTANT(0.220728115440999990)*f[6] + CONSTANT(0.090297865408399999)*f[22];
tg = CONSTANT(-0.063718718433900007)*g[8] + CONSTANT(0.044869370061299998)*g[20] + CONSTANT(0.220728115440999990)*g[6] + CONSTANT(0.090297865408399999)*g[22];
y[7] += tf*g[21] + tg*f[21];
y[21] += tf*g[7] + tg*f[7];
t = f[7] * g[21] + f[21] * g[7];
y[8] += CONSTANT(-0.063718718433900007)*t;
y[20] += CONSTANT(0.044869370061299998)*t;
y[6] += CONSTANT(0.220728115440999990)*t;
y[22] += CONSTANT(0.090297865408399999)*t;
// [7,23]: 8,22,24,
tf = CONSTANT(0.168583882832999990)*f[8] + CONSTANT(0.132725386548000010)*f[22] + CONSTANT(0.140463346189000000)*f[24];
tg = CONSTANT(0.168583882832999990)*g[8] + CONSTANT(0.132725386548000010)*g[22] + CONSTANT(0.140463346189000000)*g[24];
y[7] += tf*g[23] + tg*f[23];
y[23] += tf*g[7] + tg*f[7];
t = f[7] * g[23] + f[23] * g[7];
y[8] += CONSTANT(0.168583882832999990)*t;
y[22] += CONSTANT(0.132725386548000010)*t;
y[24] += CONSTANT(0.140463346189000000)*t;
// [7,26]: 9,25,27,
tf = CONSTANT(0.155288072035000000)*f[9] + CONSTANT(0.132882365179999990)*f[25] + CONSTANT(0.138662534056999990)*f[27];
tg = CONSTANT(0.155288072035000000)*g[9] + CONSTANT(0.132882365179999990)*g[25] + CONSTANT(0.138662534056999990)*g[27];
y[7] += tf*g[26] + tg*f[26];
y[26] += tf*g[7] + tg*f[7];
t = f[7] * g[26] + f[26] * g[7];
y[9] += CONSTANT(0.155288072035000000)*t;
y[25] += CONSTANT(0.132882365179999990)*t;
y[27] += CONSTANT(0.138662534056999990)*t;
// [7,28]: 27,11,9,29,
tf = CONSTANT(0.114366930522000000)*f[27] + CONSTANT(0.173617342584000000)*f[11] + CONSTANT(-0.044827805096399997)*f[9] + CONSTANT(0.074118242118699995)*f[29];
tg = CONSTANT(0.114366930522000000)*g[27] + CONSTANT(0.173617342584000000)*g[11] + CONSTANT(-0.044827805096399997)*g[9] + CONSTANT(0.074118242118699995)*g[29];
y[7] += tf*g[28] + tg*f[28];
y[28] += tf*g[7] + tg*f[7];
t = f[7] * g[28] + f[28] * g[7];
y[27] += CONSTANT(0.114366930522000000)*t;
y[11] += CONSTANT(0.173617342584000000)*t;
y[9] += CONSTANT(-0.044827805096399997)*t;
y[29] += CONSTANT(0.074118242118699995)*t;
// [7,31]: 30,12,32,
tf = CONSTANT(0.036165998945399999)*f[30] + CONSTANT(0.214317900578999990)*f[12] + CONSTANT(0.074118242119099995)*f[32];
tg = CONSTANT(0.036165998945399999)*g[30] + CONSTANT(0.214317900578999990)*g[12] + CONSTANT(0.074118242119099995)*g[32];
y[7] += tf*g[31] + tg*f[31];
y[31] += tf*g[7] + tg*f[7];
t = f[7] * g[31] + f[31] * g[7];
y[30] += CONSTANT(0.036165998945399999)*t;
y[12] += CONSTANT(0.214317900578999990)*t;
y[32] += CONSTANT(0.074118242119099995)*t;
// [7,32]: 15,33,
tf = CONSTANT(-0.044827805096799997)*f[15] + CONSTANT(0.114366930522000000)*f[33];
tg = CONSTANT(-0.044827805096799997)*g[15] + CONSTANT(0.114366930522000000)*g[33];
y[7] += tf*g[32] + tg*f[32];
y[32] += tf*g[7] + tg*f[7];
t = f[7] * g[32] + f[32] * g[7];
y[15] += CONSTANT(-0.044827805096799997)*t;
y[33] += CONSTANT(0.114366930522000000)*t;
// [7,34]: 15,33,35,
tf = CONSTANT(0.155288072036000010)*f[15] + CONSTANT(0.138662534059000000)*f[33] + CONSTANT(0.132882365179000010)*f[35];
tg = CONSTANT(0.155288072036000010)*g[15] + CONSTANT(0.138662534059000000)*g[33] + CONSTANT(0.132882365179000010)*g[35];
y[7] += tf*g[34] + tg*f[34];
y[34] += tf*g[7] + tg*f[7];
t = f[7] * g[34] + f[34] * g[7];
y[15] += CONSTANT(0.155288072036000010)*t;
y[33] += CONSTANT(0.138662534059000000)*t;
y[35] += CONSTANT(0.132882365179000010)*t;
// [8,8]: 0,6,20,24,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.180223751576000010)*f[6] + CONSTANT(0.040299255967500003)*f[20] + CONSTANT(0.238413613505999990)*f[24];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.180223751576000010)*g[6] + CONSTANT(0.040299255967500003)*g[20] + CONSTANT(0.238413613505999990)*g[24];
y[8] += tf*g[8] + tg*f[8];
t = f[8] * g[8];
y[0] += CONSTANT(0.282094791770000020)*t;
y[6] += CONSTANT(-0.180223751576000010)*t;
y[20] += CONSTANT(0.040299255967500003)*t;
y[24] += CONSTANT(0.238413613505999990)*t;
// [8,9]: 1,11,25,29,
tf = CONSTANT(0.226179013155000000)*f[1] + CONSTANT(-0.094031597259499999)*f[11] + CONSTANT(0.245532000541000000)*f[25] + CONSTANT(0.016943317729199998)*f[29];
tg = CONSTANT(0.226179013155000000)*g[1] + CONSTANT(-0.094031597259499999)*g[11] + CONSTANT(0.245532000541000000)*g[25] + CONSTANT(0.016943317729199998)*g[29];
y[8] += tf*g[9] + tg*f[9];
y[9] += tf*g[8] + tg*f[8];
t = f[8] * g[9] + f[9] * g[8];
y[1] += CONSTANT(0.226179013155000000)*t;
y[11] += CONSTANT(-0.094031597259499999)*t;
y[25] += CONSTANT(0.245532000541000000)*t;
y[29] += CONSTANT(0.016943317729199998)*t;
// [8,14]: 2,12,30,34,
tf = CONSTANT(0.184674390919999990)*f[2] + CONSTANT(-0.188063194517999990)*f[12] + CONSTANT(0.053579475144400000)*f[30] + CONSTANT(0.190188269816000010)*f[34];
tg = CONSTANT(0.184674390919999990)*g[2] + CONSTANT(-0.188063194517999990)*g[12] + CONSTANT(0.053579475144400000)*g[30] + CONSTANT(0.190188269816000010)*g[34];
y[8] += tf*g[14] + tg*f[14];
y[14] += tf*g[8] + tg*f[8];
t = f[8] * g[14] + f[14] * g[8];
y[2] += CONSTANT(0.184674390919999990)*t;
y[12] += CONSTANT(-0.188063194517999990)*t;
y[30] += CONSTANT(0.053579475144400000)*t;
y[34] += CONSTANT(0.190188269816000010)*t;
// [8,15]: 13,3,31,35,
tf = CONSTANT(-0.094031597259499999)*f[13] + CONSTANT(0.226179013155000000)*f[3] + CONSTANT(0.016943317729199998)*f[31] + CONSTANT(0.245532000541000000)*f[35];
tg = CONSTANT(-0.094031597259499999)*g[13] + CONSTANT(0.226179013155000000)*g[3] + CONSTANT(0.016943317729199998)*g[31] + CONSTANT(0.245532000541000000)*g[35];
y[8] += tf*g[15] + tg*f[15];
y[15] += tf*g[8] + tg*f[8];
t = f[8] * g[15] + f[15] * g[8];
y[13] += CONSTANT(-0.094031597259499999)*t;
y[3] += CONSTANT(0.226179013155000000)*t;
y[31] += CONSTANT(0.016943317729199998)*t;
y[35] += CONSTANT(0.245532000541000000)*t;
// [8,22]: 6,20,24,
tf = CONSTANT(0.156078347226000000)*f[6] + CONSTANT(-0.190364615029000010)*f[20] + CONSTANT(-0.075080816691500005)*f[24];
tg = CONSTANT(0.156078347226000000)*g[6] + CONSTANT(-0.190364615029000010)*g[20] + CONSTANT(-0.075080816691500005)*g[24];
y[8] += tf*g[22] + tg*f[22];
y[22] += tf*g[8] + tg*f[8];
t = f[8] * g[22] + f[22] * g[8];
y[6] += CONSTANT(0.156078347226000000)*t;
y[20] += CONSTANT(-0.190364615029000010)*t;
y[24] += CONSTANT(-0.075080816691500005)*t;
// [8,26]: 10,28,
tf = CONSTANT(0.190188269806999990)*f[10] + CONSTANT(-0.097043558542400002)*f[28];
tg = CONSTANT(0.190188269806999990)*g[10] + CONSTANT(-0.097043558542400002)*g[28];
y[8] += tf*g[26] + tg*f[26];
y[26] += tf*g[8] + tg*f[8];
t = f[8] * g[26] + f[26] * g[8];
y[10] += CONSTANT(0.190188269806999990)*t;
y[28] += CONSTANT(-0.097043558542400002)*t;
// [8,27]: 25,11,29,
tf = CONSTANT(-0.062641347680800000)*f[25] + CONSTANT(0.141757966609000000)*f[11] + CONSTANT(-0.121034582550000010)*f[29];
tg = CONSTANT(-0.062641347680800000)*g[25] + CONSTANT(0.141757966609000000)*g[11] + CONSTANT(-0.121034582550000010)*g[29];
y[8] += tf*g[27] + tg*f[27];
y[27] += tf*g[8] + tg*f[8];
t = f[8] * g[27] + f[27] * g[8];
y[25] += CONSTANT(-0.062641347680800000)*t;
y[11] += CONSTANT(0.141757966609000000)*t;
y[29] += CONSTANT(-0.121034582550000010)*t;
// [8,32]: 30,12,34,
tf = CONSTANT(-0.191372478254000000)*f[30] + CONSTANT(0.141757966609000000)*f[12] + CONSTANT(-0.097043558538899996)*f[34];
tg = CONSTANT(-0.191372478254000000)*g[30] + CONSTANT(0.141757966609000000)*g[12] + CONSTANT(-0.097043558538899996)*g[34];
y[8] += tf*g[32] + tg*f[32];
y[32] += tf*g[8] + tg*f[8];
t = f[8] * g[32] + f[32] * g[8];
y[30] += CONSTANT(-0.191372478254000000)*t;
y[12] += CONSTANT(0.141757966609000000)*t;
y[34] += CONSTANT(-0.097043558538899996)*t;
// [8,33]: 13,31,35,
tf = CONSTANT(0.141757966609000000)*f[13] + CONSTANT(-0.121034582550000010)*f[31] + CONSTANT(-0.062641347680800000)*f[35];
tg = CONSTANT(0.141757966609000000)*g[13] + CONSTANT(-0.121034582550000010)*g[31] + CONSTANT(-0.062641347680800000)*g[35];
y[8] += tf*g[33] + tg*f[33];
y[33] += tf*g[8] + tg*f[8];
t = f[8] * g[33] + f[33] * g[8];
y[13] += CONSTANT(0.141757966609000000)*t;
y[31] += CONSTANT(-0.121034582550000010)*t;
y[35] += CONSTANT(-0.062641347680800000)*t;
// [9,9]: 6,0,20,
tf = CONSTANT(-0.210261043508000010)*f[6] + CONSTANT(0.282094791766999970)*f[0] + CONSTANT(0.076934943209800002)*f[20];
tg = CONSTANT(-0.210261043508000010)*g[6] + CONSTANT(0.282094791766999970)*g[0] + CONSTANT(0.076934943209800002)*g[20];
y[9] += tf*g[9] + tg*f[9];
t = f[9] * g[9];
y[6] += CONSTANT(-0.210261043508000010)*t;
y[0] += CONSTANT(0.282094791766999970)*t;
y[20] += CONSTANT(0.076934943209800002)*t;
// [9,17]: 2,12,30,
tf = CONSTANT(0.162867503964999990)*f[2] + CONSTANT(-0.203550726872999990)*f[12] + CONSTANT(0.098140130728100003)*f[30];
tg = CONSTANT(0.162867503964999990)*g[2] + CONSTANT(-0.203550726872999990)*g[12] + CONSTANT(0.098140130728100003)*g[30];
y[9] += tf*g[17] + tg*f[17];
y[17] += tf*g[9] + tg*f[9];
t = f[9] * g[17] + f[17] * g[9];
y[2] += CONSTANT(0.162867503964999990)*t;
y[12] += CONSTANT(-0.203550726872999990)*t;
y[30] += CONSTANT(0.098140130728100003)*t;
// [9,18]: 3,13,31,35,
tf = CONSTANT(-0.043528171377799997)*f[3] + CONSTANT(0.133255230519000010)*f[13] + CONSTANT(-0.101584686310000010)*f[31] + CONSTANT(0.098140130731999994)*f[35];
tg = CONSTANT(-0.043528171377799997)*g[3] + CONSTANT(0.133255230519000010)*g[13] + CONSTANT(-0.101584686310000010)*g[31] + CONSTANT(0.098140130731999994)*g[35];
y[9] += tf*g[18] + tg*f[18];
y[18] += tf*g[9] + tg*f[9];
t = f[9] * g[18] + f[18] * g[9];
y[3] += CONSTANT(-0.043528171377799997)*t;
y[13] += CONSTANT(0.133255230519000010)*t;
y[31] += CONSTANT(-0.101584686310000010)*t;
y[35] += CONSTANT(0.098140130731999994)*t;
// [9,19]: 14,32,34,
tf = CONSTANT(-0.099322584600699995)*f[14] + CONSTANT(0.126698363970000010)*f[32] + CONSTANT(0.131668802180999990)*f[34];
tg = CONSTANT(-0.099322584600699995)*g[14] + CONSTANT(0.126698363970000010)*g[32] + CONSTANT(0.131668802180999990)*g[34];
y[9] += tf*g[19] + tg*f[19];
y[19] += tf*g[9] + tg*f[9];
t = f[9] * g[19] + f[19] * g[9];
y[14] += CONSTANT(-0.099322584600699995)*t;
y[32] += CONSTANT(0.126698363970000010)*t;
y[34] += CONSTANT(0.131668802180999990)*t;
// [9,22]: 1,11,25,29,
tf = CONSTANT(-0.043528171378199997)*f[1] + CONSTANT(0.133255230518000010)*f[11] + CONSTANT(-0.098140130732499997)*f[25] + CONSTANT(-0.101584686311000000)*f[29];
tg = CONSTANT(-0.043528171378199997)*g[1] + CONSTANT(0.133255230518000010)*g[11] + CONSTANT(-0.098140130732499997)*g[25] + CONSTANT(-0.101584686311000000)*g[29];
y[9] += tf*g[22] + tg*f[22];
y[22] += tf*g[9] + tg*f[9];
t = f[9] * g[22] + f[22] * g[9];
y[1] += CONSTANT(-0.043528171378199997)*t;
y[11] += CONSTANT(0.133255230518000010)*t;
y[25] += CONSTANT(-0.098140130732499997)*t;
y[29] += CONSTANT(-0.101584686311000000)*t;
// [9,27]: 6,20,
tf = CONSTANT(0.126792179874999990)*f[6] + CONSTANT(-0.196280261464999990)*f[20];
tg = CONSTANT(0.126792179874999990)*g[6] + CONSTANT(-0.196280261464999990)*g[20];
y[9] += tf*g[27] + tg*f[27];
y[27] += tf*g[9] + tg*f[9];
t = f[9] * g[27] + f[27] * g[9];
y[6] += CONSTANT(0.126792179874999990)*t;
y[20] += CONSTANT(-0.196280261464999990)*t;
// [10,10]: 0,20,24,
tf = CONSTANT(0.282094791771999980)*f[0] + CONSTANT(-0.179514867494000000)*f[20] + CONSTANT(-0.151717754049000010)*f[24];
tg = CONSTANT(0.282094791771999980)*g[0] + CONSTANT(-0.179514867494000000)*g[20] + CONSTANT(-0.151717754049000010)*g[24];
y[10] += tf*g[10] + tg*f[10];
t = f[10] * g[10];
y[0] += CONSTANT(0.282094791771999980)*t;
y[20] += CONSTANT(-0.179514867494000000)*t;
y[24] += CONSTANT(-0.151717754049000010)*t;
// [10,16]: 14,32,
tf = CONSTANT(0.151717754044999990)*f[14] + CONSTANT(-0.077413979111300005)*f[32];
tg = CONSTANT(0.151717754044999990)*g[14] + CONSTANT(-0.077413979111300005)*g[32];
y[10] += tf*g[16] + tg*f[16];
y[16] += tf*g[10] + tg*f[10];
t = f[10] * g[16] + f[16] * g[10];
y[14] += CONSTANT(0.151717754044999990)*t;
y[32] += CONSTANT(-0.077413979111300005)*t;
// [10,17]: 13,3,31,35,
tf = CONSTANT(0.067850242288900006)*f[13] + CONSTANT(0.199471140200000010)*f[3] + CONSTANT(-0.113793659091000000)*f[31] + CONSTANT(-0.149911525925999990)*f[35];
tg = CONSTANT(0.067850242288900006)*g[13] + CONSTANT(0.199471140200000010)*g[3] + CONSTANT(-0.113793659091000000)*g[31] + CONSTANT(-0.149911525925999990)*g[35];
y[10] += tf*g[17] + tg*f[17];
y[17] += tf*g[10] + tg*f[10];
t = f[10] * g[17] + f[17] * g[10];
y[13] += CONSTANT(0.067850242288900006)*t;
y[3] += CONSTANT(0.199471140200000010)*t;
y[31] += CONSTANT(-0.113793659091000000)*t;
y[35] += CONSTANT(-0.149911525925999990)*t;
// [10,18]: 12,2,30,34,
tf = CONSTANT(-0.044418410173299998)*f[12] + CONSTANT(0.213243618621000000)*f[2] + CONSTANT(-0.171327458205000000)*f[30] + CONSTANT(-0.101358691177000000)*f[34];
tg = CONSTANT(-0.044418410173299998)*g[12] + CONSTANT(0.213243618621000000)*g[2] + CONSTANT(-0.171327458205000000)*g[30] + CONSTANT(-0.101358691177000000)*g[34];
y[10] += tf*g[18] + tg*f[18];
y[18] += tf*g[10] + tg*f[10];
t = f[10] * g[18] + f[18] * g[10];
y[12] += CONSTANT(-0.044418410173299998)*t;
y[2] += CONSTANT(0.213243618621000000)*t;
y[30] += CONSTANT(-0.171327458205000000)*t;
y[34] += CONSTANT(-0.101358691177000000)*t;
// [10,19]: 3,15,13,31,33,
tf = CONSTANT(-0.075393004386799994)*f[3] + CONSTANT(0.099322584599600000)*f[15] + CONSTANT(0.102579924281000000)*f[13] + CONSTANT(0.097749909976500002)*f[31] + CONSTANT(-0.025339672794100002)*f[33];
tg = CONSTANT(-0.075393004386799994)*g[3] + CONSTANT(0.099322584599600000)*g[15] + CONSTANT(0.102579924281000000)*g[13] + CONSTANT(0.097749909976500002)*g[31] + CONSTANT(-0.025339672794100002)*g[33];
y[10] += tf*g[19] + tg*f[19];
y[19] += tf*g[10] + tg*f[10];
t = f[10] * g[19] + f[19] * g[10];
y[3] += CONSTANT(-0.075393004386799994)*t;
y[15] += CONSTANT(0.099322584599600000)*t;
y[13] += CONSTANT(0.102579924281000000)*t;
y[31] += CONSTANT(0.097749909976500002)*t;
y[33] += CONSTANT(-0.025339672794100002)*t;
// [10,21]: 11,1,9,27,29,
tf = CONSTANT(0.102579924281000000)*f[11] + CONSTANT(-0.075393004386799994)*f[1] + CONSTANT(-0.099322584599600000)*f[9] + CONSTANT(0.025339672794100002)*f[27] + CONSTANT(0.097749909976500002)*f[29];
tg = CONSTANT(0.102579924281000000)*g[11] + CONSTANT(-0.075393004386799994)*g[1] + CONSTANT(-0.099322584599600000)*g[9] + CONSTANT(0.025339672794100002)*g[27] + CONSTANT(0.097749909976500002)*g[29];
y[10] += tf*g[21] + tg*f[21];
y[21] += tf*g[10] + tg*f[10];
t = f[10] * g[21] + f[21] * g[10];
y[11] += CONSTANT(0.102579924281000000)*t;
y[1] += CONSTANT(-0.075393004386799994)*t;
y[9] += CONSTANT(-0.099322584599600000)*t;
y[27] += CONSTANT(0.025339672794100002)*t;
y[29] += CONSTANT(0.097749909976500002)*t;
// [10,23]: 11,1,25,29,
tf = CONSTANT(-0.067850242288900006)*f[11] + CONSTANT(-0.199471140200000010)*f[1] + CONSTANT(0.149911525925999990)*f[25] + CONSTANT(0.113793659091000000)*f[29];
tg = CONSTANT(-0.067850242288900006)*g[11] + CONSTANT(-0.199471140200000010)*g[1] + CONSTANT(0.149911525925999990)*g[25] + CONSTANT(0.113793659091000000)*g[29];
y[10] += tf*g[23] + tg*f[23];
y[23] += tf*g[10] + tg*f[10];
t = f[10] * g[23] + f[23] * g[10];
y[11] += CONSTANT(-0.067850242288900006)*t;
y[1] += CONSTANT(-0.199471140200000010)*t;
y[25] += CONSTANT(0.149911525925999990)*t;
y[29] += CONSTANT(0.113793659091000000)*t;
// [10,28]: 6,20,24,
tf = CONSTANT(0.190188269814000000)*f[6] + CONSTANT(-0.065426753820500005)*f[20] + CONSTANT(0.077413979109600004)*f[24];
tg = CONSTANT(0.190188269814000000)*g[6] + CONSTANT(-0.065426753820500005)*g[20] + CONSTANT(0.077413979109600004)*g[24];
y[10] += tf*g[28] + tg*f[28];
y[28] += tf*g[10] + tg*f[10];
t = f[10] * g[28] + f[28] * g[10];
y[6] += CONSTANT(0.190188269814000000)*t;
y[20] += CONSTANT(-0.065426753820500005)*t;
y[24] += CONSTANT(0.077413979109600004)*t;
// [11,11]: 0,6,8,20,22,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.126156626101000010)*f[6] + CONSTANT(-0.145673124078999990)*f[8] + CONSTANT(0.025644981070299999)*f[20] + CONSTANT(-0.114687841910000000)*f[22];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.126156626101000010)*g[6] + CONSTANT(-0.145673124078999990)*g[8] + CONSTANT(0.025644981070299999)*g[20] + CONSTANT(-0.114687841910000000)*g[22];
y[11] += tf*g[11] + tg*f[11];
t = f[11] * g[11];
y[0] += CONSTANT(0.282094791773999990)*t;
y[6] += CONSTANT(0.126156626101000010)*t;
y[8] += CONSTANT(-0.145673124078999990)*t;
y[20] += CONSTANT(0.025644981070299999)*t;
y[22] += CONSTANT(-0.114687841910000000)*t;
// [11,16]: 15,33,35,
tf = CONSTANT(-0.117520066953000000)*f[15] + CONSTANT(0.119929220739999990)*f[33] + CONSTANT(0.134084945035999990)*f[35];
tg = CONSTANT(-0.117520066953000000)*g[15] + CONSTANT(0.119929220739999990)*g[33] + CONSTANT(0.134084945035999990)*g[35];
y[11] += tf*g[16] + tg*f[16];
y[16] += tf*g[11] + tg*f[11];
t = f[11] * g[16] + f[16] * g[11];
y[15] += CONSTANT(-0.117520066953000000)*t;
y[33] += CONSTANT(0.119929220739999990)*t;
y[35] += CONSTANT(0.134084945035999990)*t;
// [11,18]: 3,13,15,31,33,
tf = CONSTANT(0.168583882834000000)*f[3] + CONSTANT(0.114687841909000000)*f[13] + CONSTANT(-0.133255230519000010)*f[15] + CONSTANT(0.075189952564900006)*f[31] + CONSTANT(-0.101990215611000000)*f[33];
tg = CONSTANT(0.168583882834000000)*g[3] + CONSTANT(0.114687841909000000)*g[13] + CONSTANT(-0.133255230519000010)*g[15] + CONSTANT(0.075189952564900006)*g[31] + CONSTANT(-0.101990215611000000)*g[33];
y[11] += tf*g[18] + tg*f[18];
y[18] += tf*g[11] + tg*f[11];
t = f[11] * g[18] + f[18] * g[11];
y[3] += CONSTANT(0.168583882834000000)*t;
y[13] += CONSTANT(0.114687841909000000)*t;
y[15] += CONSTANT(-0.133255230519000010)*t;
y[31] += CONSTANT(0.075189952564900006)*t;
y[33] += CONSTANT(-0.101990215611000000)*t;
// [11,19]: 2,14,12,30,32,
tf = CONSTANT(0.238413613504000000)*f[2] + CONSTANT(-0.102579924282000000)*f[14] + CONSTANT(0.099322584599300004)*f[12] + CONSTANT(0.009577496073830001)*f[30] + CONSTANT(-0.104682806112000000)*f[32];
tg = CONSTANT(0.238413613504000000)*g[2] + CONSTANT(-0.102579924282000000)*g[14] + CONSTANT(0.099322584599300004)*g[12] + CONSTANT(0.009577496073830001)*g[30] + CONSTANT(-0.104682806112000000)*g[32];
y[11] += tf*g[19] + tg*f[19];
y[19] += tf*g[11] + tg*f[11];
t = f[11] * g[19] + f[19] * g[11];
y[2] += CONSTANT(0.238413613504000000)*t;
y[14] += CONSTANT(-0.102579924282000000)*t;
y[12] += CONSTANT(0.099322584599300004)*t;
y[30] += CONSTANT(0.009577496073830001)*t;
y[32] += CONSTANT(-0.104682806112000000)*t;
// [11,24]: 9,25,27,
tf = CONSTANT(0.117520066950999990)*f[9] + CONSTANT(-0.134084945037000000)*f[25] + CONSTANT(-0.119929220742000010)*f[27];
tg = CONSTANT(0.117520066950999990)*g[9] + CONSTANT(-0.134084945037000000)*g[25] + CONSTANT(-0.119929220742000010)*g[27];
y[11] += tf*g[24] + tg*f[24];
y[24] += tf*g[11] + tg*f[11];
t = f[11] * g[24] + f[24] * g[11];
y[9] += CONSTANT(0.117520066950999990)*t;
y[25] += CONSTANT(-0.134084945037000000)*t;
y[27] += CONSTANT(-0.119929220742000010)*t;
// [11,29]: 6,20,22,8,
tf = CONSTANT(0.227318461243000010)*f[6] + CONSTANT(0.086019920779800002)*f[20] + CONSTANT(-0.075189952565200002)*f[22] + CONSTANT(0.065621187395299999)*f[8];
tg = CONSTANT(0.227318461243000010)*g[6] + CONSTANT(0.086019920779800002)*g[20] + CONSTANT(-0.075189952565200002)*g[22] + CONSTANT(0.065621187395299999)*g[8];
y[11] += tf*g[29] + tg*f[29];
y[29] += tf*g[11] + tg*f[11];
t = f[11] * g[29] + f[29] * g[11];
y[6] += CONSTANT(0.227318461243000010)*t;
y[20] += CONSTANT(0.086019920779800002)*t;
y[22] += CONSTANT(-0.075189952565200002)*t;
y[8] += CONSTANT(0.065621187395299999)*t;
// [12,12]: 0,6,20,
tf = CONSTANT(0.282094799871999980)*f[0] + CONSTANT(0.168208852954000010)*f[6] + CONSTANT(0.153869910786000010)*f[20];
tg = CONSTANT(0.282094799871999980)*g[0] + CONSTANT(0.168208852954000010)*g[6] + CONSTANT(0.153869910786000010)*g[20];
y[12] += tf*g[12] + tg*f[12];
t = f[12] * g[12];
y[0] += CONSTANT(0.282094799871999980)*t;
y[6] += CONSTANT(0.168208852954000010)*t;
y[20] += CONSTANT(0.153869910786000010)*t;
// [12,30]: 20,6,
tf = CONSTANT(0.148373961712999990)*f[20] + CONSTANT(0.239614719999000000)*f[6];
tg = CONSTANT(0.148373961712999990)*g[20] + CONSTANT(0.239614719999000000)*g[6];
y[12] += tf*g[30] + tg*f[30];
y[30] += tf*g[12] + tg*f[12];
t = f[12] * g[30] + f[30] * g[12];
y[20] += CONSTANT(0.148373961712999990)*t;
y[6] += CONSTANT(0.239614719999000000)*t;
// [13,13]: 0,8,6,20,22,
tf = CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.145673124078999990)*f[8] + CONSTANT(0.126156626101000010)*f[6] + CONSTANT(0.025644981070299999)*f[20] + CONSTANT(0.114687841910000000)*f[22];
tg = CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.145673124078999990)*g[8] + CONSTANT(0.126156626101000010)*g[6] + CONSTANT(0.025644981070299999)*g[20] + CONSTANT(0.114687841910000000)*g[22];
y[13] += tf*g[13] + tg*f[13];
t = f[13] * g[13];
y[0] += CONSTANT(0.282094791773999990)*t;
y[8] += CONSTANT(0.145673124078999990)*t;
y[6] += CONSTANT(0.126156626101000010)*t;
y[20] += CONSTANT(0.025644981070299999)*t;
y[22] += CONSTANT(0.114687841910000000)*t;
// [13,16]: 9,25,27,
tf = CONSTANT(-0.117520066953000000)*f[9] + CONSTANT(-0.134084945035999990)*f[25] + CONSTANT(0.119929220739999990)*f[27];
tg = CONSTANT(-0.117520066953000000)*g[9] + CONSTANT(-0.134084945035999990)*g[25] + CONSTANT(0.119929220739999990)*g[27];
y[13] += tf*g[16] + tg*f[16];
y[16] += tf*g[13] + tg*f[13];
t = f[13] * g[16] + f[16] * g[13];
y[9] += CONSTANT(-0.117520066953000000)*t;
y[25] += CONSTANT(-0.134084945035999990)*t;
y[27] += CONSTANT(0.119929220739999990)*t;
// [13,21]: 2,12,14,30,32,
tf = CONSTANT(0.238413613504000000)*f[2] + CONSTANT(0.099322584599300004)*f[12] + CONSTANT(0.102579924282000000)*f[14] + CONSTANT(0.009577496073830001)*f[30] + CONSTANT(0.104682806112000000)*f[32];
tg = CONSTANT(0.238413613504000000)*g[2] + CONSTANT(0.099322584599300004)*g[12] + CONSTANT(0.102579924282000000)*g[14] + CONSTANT(0.009577496073830001)*g[30] + CONSTANT(0.104682806112000000)*g[32];
y[13] += tf*g[21] + tg*f[21];
y[21] += tf*g[13] + tg*f[13];
t = f[13] * g[21] + f[21] * g[13];
y[2] += CONSTANT(0.238413613504000000)*t;
y[12] += CONSTANT(0.099322584599300004)*t;
y[14] += CONSTANT(0.102579924282000000)*t;
y[30] += CONSTANT(0.009577496073830001)*t;
y[32] += CONSTANT(0.104682806112000000)*t;
// [13,24]: 15,33,35,
tf = CONSTANT(-0.117520066950999990)*f[15] + CONSTANT(0.119929220742000010)*f[33] + CONSTANT(-0.134084945037000000)*f[35];
tg = CONSTANT(-0.117520066950999990)*g[15] + CONSTANT(0.119929220742000010)*g[33] + CONSTANT(-0.134084945037000000)*g[35];
y[13] += tf*g[24] + tg*f[24];
y[24] += tf*g[13] + tg*f[13];
t = f[13] * g[24] + f[24] * g[13];
y[15] += CONSTANT(-0.117520066950999990)*t;
y[33] += CONSTANT(0.119929220742000010)*t;
y[35] += CONSTANT(-0.134084945037000000)*t;
// [13,31]: 6,22,20,8,
tf = CONSTANT(0.227318461243000010)*f[6] + CONSTANT(0.075189952565200002)*f[22] + CONSTANT(0.086019920779800002)*f[20] + CONSTANT(-0.065621187395299999)*f[8];
tg = CONSTANT(0.227318461243000010)*g[6] + CONSTANT(0.075189952565200002)*g[22] + CONSTANT(0.086019920779800002)*g[20] + CONSTANT(-0.065621187395299999)*g[8];
y[13] += tf*g[31] + tg*f[31];
y[31] += tf*g[13] + tg*f[13];
t = f[13] * g[31] + f[31] * g[13];
y[6] += CONSTANT(0.227318461243000010)*t;
y[22] += CONSTANT(0.075189952565200002)*t;
y[20] += CONSTANT(0.086019920779800002)*t;
y[8] += CONSTANT(-0.065621187395299999)*t;
// [14,14]: 0,20,24,
tf = CONSTANT(0.282094791771999980)*f[0] + CONSTANT(-0.179514867494000000)*f[20] + CONSTANT(0.151717754049000010)*f[24];
tg = CONSTANT(0.282094791771999980)*g[0] + CONSTANT(-0.179514867494000000)*g[20] + CONSTANT(0.151717754049000010)*g[24];
y[14] += tf*g[14] + tg*f[14];
t = f[14] * g[14];
y[0] += CONSTANT(0.282094791771999980)*t;
y[20] += CONSTANT(-0.179514867494000000)*t;
y[24] += CONSTANT(0.151717754049000010)*t;
// [14,17]: 11,1,25,29,
tf = CONSTANT(0.067850242288500007)*f[11] + CONSTANT(0.199471140196999990)*f[1] + CONSTANT(0.149911525925999990)*f[25] + CONSTANT(-0.113793659092000000)*f[29];
tg = CONSTANT(0.067850242288500007)*g[11] + CONSTANT(0.199471140196999990)*g[1] + CONSTANT(0.149911525925999990)*g[25] + CONSTANT(-0.113793659092000000)*g[29];
y[14] += tf*g[17] + tg*f[17];
y[17] += tf*g[14] + tg*f[14];
t = f[14] * g[17] + f[17] * g[14];
y[11] += CONSTANT(0.067850242288500007)*t;
y[1] += CONSTANT(0.199471140196999990)*t;
y[25] += CONSTANT(0.149911525925999990)*t;
y[29] += CONSTANT(-0.113793659092000000)*t;
// [14,22]: 12,2,30,34,
tf = CONSTANT(-0.044418410173299998)*f[12] + CONSTANT(0.213243618621000000)*f[2] + CONSTANT(-0.171327458205000000)*f[30] + CONSTANT(0.101358691177000000)*f[34];
tg = CONSTANT(-0.044418410173299998)*g[12] + CONSTANT(0.213243618621000000)*g[2] + CONSTANT(-0.171327458205000000)*g[30] + CONSTANT(0.101358691177000000)*g[34];
y[14] += tf*g[22] + tg*f[22];
y[22] += tf*g[14] + tg*f[14];
t = f[14] * g[22] + f[22] * g[14];
y[12] += CONSTANT(-0.044418410173299998)*t;
y[2] += CONSTANT(0.213243618621000000)*t;
y[30] += CONSTANT(-0.171327458205000000)*t;
y[34] += CONSTANT(0.101358691177000000)*t;
// [14,23]: 13,3,31,35,
tf = CONSTANT(0.067850242288500007)*f[13] + CONSTANT(0.199471140196999990)*f[3] + CONSTANT(-0.113793659092000000)*f[31] + CONSTANT(0.149911525925999990)*f[35];
tg = CONSTANT(0.067850242288500007)*g[13] + CONSTANT(0.199471140196999990)*g[3] + CONSTANT(-0.113793659092000000)*g[31] + CONSTANT(0.149911525925999990)*g[35];
y[14] += tf*g[23] + tg*f[23];
y[23] += tf*g[14] + tg*f[14];
t = f[14] * g[23] + f[23] * g[14];
y[13] += CONSTANT(0.067850242288500007)*t;
y[3] += CONSTANT(0.199471140196999990)*t;
y[31] += CONSTANT(-0.113793659092000000)*t;
y[35] += CONSTANT(0.149911525925999990)*t;
// [14,32]: 20,6,24,
tf = CONSTANT(-0.065426753820500005)*f[20] + CONSTANT(0.190188269814000000)*f[6] + CONSTANT(-0.077413979109600004)*f[24];
tg = CONSTANT(-0.065426753820500005)*g[20] + CONSTANT(0.190188269814000000)*g[6] + CONSTANT(-0.077413979109600004)*g[24];
y[14] += tf*g[32] + tg*f[32];
y[32] += tf*g[14] + tg*f[14];
t = f[14] * g[32] + f[32] * g[14];
y[20] += CONSTANT(-0.065426753820500005)*t;
y[6] += CONSTANT(0.190188269814000000)*t;
y[24] += CONSTANT(-0.077413979109600004)*t;
// [15,15]: 0,6,20,
tf = CONSTANT(0.282094791766999970)*f[0] + CONSTANT(-0.210261043508000010)*f[6] + CONSTANT(0.076934943209800002)*f[20];
tg = CONSTANT(0.282094791766999970)*g[0] + CONSTANT(-0.210261043508000010)*g[6] + CONSTANT(0.076934943209800002)*g[20];
y[15] += tf*g[15] + tg*f[15];
t = f[15] * g[15];
y[0] += CONSTANT(0.282094791766999970)*t;
y[6] += CONSTANT(-0.210261043508000010)*t;
y[20] += CONSTANT(0.076934943209800002)*t;
// [15,21]: 14,32,34,
tf = CONSTANT(-0.099322584600699995)*f[14] + CONSTANT(0.126698363970000010)*f[32] + CONSTANT(-0.131668802180999990)*f[34];
tg = CONSTANT(-0.099322584600699995)*g[14] + CONSTANT(0.126698363970000010)*g[32] + CONSTANT(-0.131668802180999990)*g[34];
y[15] += tf*g[21] + tg*f[21];
y[21] += tf*g[15] + tg*f[15];
t = f[15] * g[21] + f[21] * g[15];
y[14] += CONSTANT(-0.099322584600699995)*t;
y[32] += CONSTANT(0.126698363970000010)*t;
y[34] += CONSTANT(-0.131668802180999990)*t;
// [15,22]: 13,3,31,35,
tf = CONSTANT(0.133255230518000010)*f[13] + CONSTANT(-0.043528171378199997)*f[3] + CONSTANT(-0.101584686311000000)*f[31] + CONSTANT(-0.098140130732499997)*f[35];
tg = CONSTANT(0.133255230518000010)*g[13] + CONSTANT(-0.043528171378199997)*g[3] + CONSTANT(-0.101584686311000000)*g[31] + CONSTANT(-0.098140130732499997)*g[35];
y[15] += tf*g[22] + tg*f[22];
y[22] += tf*g[15] + tg*f[15];
t = f[15] * g[22] + f[22] * g[15];
y[13] += CONSTANT(0.133255230518000010)*t;
y[3] += CONSTANT(-0.043528171378199997)*t;
y[31] += CONSTANT(-0.101584686311000000)*t;
y[35] += CONSTANT(-0.098140130732499997)*t;
// [15,23]: 12,2,30,
tf = CONSTANT(-0.203550726872999990)*f[12] + CONSTANT(0.162867503964999990)*f[2] + CONSTANT(0.098140130728100003)*f[30];
tg = CONSTANT(-0.203550726872999990)*g[12] + CONSTANT(0.162867503964999990)*g[2] + CONSTANT(0.098140130728100003)*g[30];
y[15] += tf*g[23] + tg*f[23];
y[23] += tf*g[15] + tg*f[15];
t = f[15] * g[23] + f[23] * g[15];
y[12] += CONSTANT(-0.203550726872999990)*t;
y[2] += CONSTANT(0.162867503964999990)*t;
y[30] += CONSTANT(0.098140130728100003)*t;
// [15,33]: 6,20,
tf = CONSTANT(0.126792179874999990)*f[6] + CONSTANT(-0.196280261464999990)*f[20];
tg = CONSTANT(0.126792179874999990)*g[6] + CONSTANT(-0.196280261464999990)*g[20];
y[15] += tf*g[33] + tg*f[33];
y[33] += tf*g[15] + tg*f[15];
t = f[15] * g[33] + f[33] * g[15];
y[6] += CONSTANT(0.126792179874999990)*t;
y[20] += CONSTANT(-0.196280261464999990)*t;
// [16,16]: 0,6,20,
tf = CONSTANT(0.282094791763999990)*f[0] + CONSTANT(-0.229375683829000000)*f[6] + CONSTANT(0.106525305981000000)*f[20];
tg = CONSTANT(0.282094791763999990)*g[0] + CONSTANT(-0.229375683829000000)*g[6] + CONSTANT(0.106525305981000000)*g[20];
y[16] += tf*g[16] + tg*f[16];
t = f[16] * g[16];
y[0] += CONSTANT(0.282094791763999990)*t;
y[6] += CONSTANT(-0.229375683829000000)*t;
y[20] += CONSTANT(0.106525305981000000)*t;
// [16,18]: 8,22,
tf = CONSTANT(-0.075080816693699995)*f[8] + CONSTANT(0.135045473380000000)*f[22];
tg = CONSTANT(-0.075080816693699995)*g[8] + CONSTANT(0.135045473380000000)*g[22];
y[16] += tf*g[18] + tg*f[18];
y[18] += tf*g[16] + tg*f[16];
t = f[16] * g[18] + f[18] * g[16];
y[8] += CONSTANT(-0.075080816693699995)*t;
y[22] += CONSTANT(0.135045473380000000)*t;
// [16,23]: 19,5,
tf = CONSTANT(-0.119098912754999990)*f[19] + CONSTANT(0.140463346187999990)*f[5];
tg = CONSTANT(-0.119098912754999990)*g[19] + CONSTANT(0.140463346187999990)*g[5];
y[16] += tf*g[23] + tg*f[23];
y[23] += tf*g[16] + tg*f[16];
t = f[16] * g[23] + f[23] * g[16];
y[19] += CONSTANT(-0.119098912754999990)*t;
y[5] += CONSTANT(0.140463346187999990)*t;
// [16,26]: 12,2,30,
tf = CONSTANT(-0.207723503645000000)*f[12] + CONSTANT(0.147319200325000010)*f[2] + CONSTANT(0.130197596199999990)*f[30];
tg = CONSTANT(-0.207723503645000000)*g[12] + CONSTANT(0.147319200325000010)*g[2] + CONSTANT(0.130197596199999990)*g[30];
y[16] += tf*g[26] + tg*f[26];
y[26] += tf*g[16] + tg*f[16];
t = f[16] * g[26] + f[26] * g[16];
y[12] += CONSTANT(-0.207723503645000000)*t;
y[2] += CONSTANT(0.147319200325000010)*t;
y[30] += CONSTANT(0.130197596199999990)*t;
// [16,28]: 14,32,
tf = CONSTANT(-0.077413979111300005)*f[14] + CONSTANT(0.128376561115000010)*f[32];
tg = CONSTANT(-0.077413979111300005)*g[14] + CONSTANT(0.128376561115000010)*g[32];
y[16] += tf*g[28] + tg*f[28];
y[28] += tf*g[16] + tg*f[16];
t = f[16] * g[28] + f[28] * g[16];
y[14] += CONSTANT(-0.077413979111300005)*t;
y[32] += CONSTANT(0.128376561115000010)*t;
// [16,29]: 15,33,35,
tf = CONSTANT(0.035835708931099997)*f[15] + CONSTANT(-0.118853600623999990)*f[33] + CONSTANT(-0.053152946071899999)*f[35];
tg = CONSTANT(0.035835708931099997)*g[15] + CONSTANT(-0.118853600623999990)*g[33] + CONSTANT(-0.053152946071899999)*g[35];
y[16] += tf*g[29] + tg*f[29];
y[29] += tf*g[16] + tg*f[16];
t = f[16] * g[29] + f[29] * g[16];
y[15] += CONSTANT(0.035835708931099997)*t;
y[33] += CONSTANT(-0.118853600623999990)*t;
y[35] += CONSTANT(-0.053152946071899999)*t;
// [16,31]: 27,9,25,
tf = CONSTANT(-0.118853600623999990)*f[27] + CONSTANT(0.035835708931099997)*f[9] + CONSTANT(0.053152946071899999)*f[25];
tg = CONSTANT(-0.118853600623999990)*g[27] + CONSTANT(0.035835708931099997)*g[9] + CONSTANT(0.053152946071899999)*g[25];
y[16] += tf*g[31] + tg*f[31];
y[31] += tf*g[16] + tg*f[16];
t = f[16] * g[31] + f[31] * g[16];
y[27] += CONSTANT(-0.118853600623999990)*t;
y[9] += CONSTANT(0.035835708931099997)*t;
y[25] += CONSTANT(0.053152946071899999)*t;
// [17,17]: 0,6,20,
tf = CONSTANT(0.282094791768999990)*f[0] + CONSTANT(-0.057343920955899998)*f[6] + CONSTANT(-0.159787958979000000)*f[20];
tg = CONSTANT(0.282094791768999990)*g[0] + CONSTANT(-0.057343920955899998)*g[6] + CONSTANT(-0.159787958979000000)*g[20];
y[17] += tf*g[17] + tg*f[17];
t = f[17] * g[17];
y[0] += CONSTANT(0.282094791768999990)*t;
y[6] += CONSTANT(-0.057343920955899998)*t;
y[20] += CONSTANT(-0.159787958979000000)*t;
// [17,19]: 8,22,24,
tf = CONSTANT(-0.112621225039000000)*f[8] + CONSTANT(0.045015157794100001)*f[22] + CONSTANT(0.119098912753000000)*f[24];
tg = CONSTANT(-0.112621225039000000)*g[8] + CONSTANT(0.045015157794100001)*g[22] + CONSTANT(0.119098912753000000)*g[24];
y[17] += tf*g[19] + tg*f[19];
y[19] += tf*g[17] + tg*f[17];
t = f[17] * g[19] + f[19] * g[17];
y[8] += CONSTANT(-0.112621225039000000)*t;
y[22] += CONSTANT(0.045015157794100001)*t;
y[24] += CONSTANT(0.119098912753000000)*t;
// [17,21]: 16,4,18,
tf = CONSTANT(-0.119098912754999990)*f[16] + CONSTANT(-0.112621225039000000)*f[4] + CONSTANT(0.045015157794399997)*f[18];
tg = CONSTANT(-0.119098912754999990)*g[16] + CONSTANT(-0.112621225039000000)*g[4] + CONSTANT(0.045015157794399997)*g[18];
y[17] += tf*g[21] + tg*f[21];
y[21] += tf*g[17] + tg*f[17];
t = f[17] * g[21] + f[21] * g[17];
y[16] += CONSTANT(-0.119098912754999990)*t;
y[4] += CONSTANT(-0.112621225039000000)*t;
y[18] += CONSTANT(0.045015157794399997)*t;
// [17,26]: 3,13,31,
tf = CONSTANT(0.208340811096000000)*f[3] + CONSTANT(0.029982305185199998)*f[13] + CONSTANT(-0.118853600623999990)*f[31];
tg = CONSTANT(0.208340811096000000)*g[3] + CONSTANT(0.029982305185199998)*g[13] + CONSTANT(-0.118853600623999990)*g[31];
y[17] += tf*g[26] + tg*f[26];
y[26] += tf*g[17] + tg*f[17];
t = f[17] * g[26] + f[26] * g[17];
y[3] += CONSTANT(0.208340811096000000)*t;
y[13] += CONSTANT(0.029982305185199998)*t;
y[31] += CONSTANT(-0.118853600623999990)*t;
// [17,27]: 12,2,30,
tf = CONSTANT(-0.103861751821000010)*f[12] + CONSTANT(0.196425600433000000)*f[2] + CONSTANT(-0.130197596204999990)*f[30];
tg = CONSTANT(-0.103861751821000010)*g[12] + CONSTANT(0.196425600433000000)*g[2] + CONSTANT(-0.130197596204999990)*g[30];
y[17] += tf*g[27] + tg*f[27];
y[27] += tf*g[17] + tg*f[17];
t = f[17] * g[27] + f[27] * g[17];
y[12] += CONSTANT(-0.103861751821000010)*t;
y[2] += CONSTANT(0.196425600433000000)*t;
y[30] += CONSTANT(-0.130197596204999990)*t;
// [17,28]: 13,3,31,35,
tf = CONSTANT(0.121172043789000000)*f[13] + CONSTANT(-0.060142811686500000)*f[3] + CONSTANT(0.034310079156700000)*f[31] + CONSTANT(0.099440056652200001)*f[35];
tg = CONSTANT(0.121172043789000000)*g[13] + CONSTANT(-0.060142811686500000)*g[3] + CONSTANT(0.034310079156700000)*g[31] + CONSTANT(0.099440056652200001)*g[35];
y[17] += tf*g[28] + tg*f[28];
y[28] += tf*g[17] + tg*f[17];
t = f[17] * g[28] + f[28] * g[17];
y[13] += CONSTANT(0.121172043789000000)*t;
y[3] += CONSTANT(-0.060142811686500000)*t;
y[31] += CONSTANT(0.034310079156700000)*t;
y[35] += CONSTANT(0.099440056652200001)*t;
// [17,32]: 11,1,25,29,
tf = CONSTANT(0.121172043788000010)*f[11] + CONSTANT(-0.060142811686900000)*f[1] + CONSTANT(-0.099440056652700004)*f[25] + CONSTANT(0.034310079156599997)*f[29];
tg = CONSTANT(0.121172043788000010)*g[11] + CONSTANT(-0.060142811686900000)*g[1] + CONSTANT(-0.099440056652700004)*g[25] + CONSTANT(0.034310079156599997)*g[29];
y[17] += tf*g[32] + tg*f[32];
y[32] += tf*g[17] + tg*f[17];
t = f[17] * g[32] + f[32] * g[17];
y[11] += CONSTANT(0.121172043788000010)*t;
y[1] += CONSTANT(-0.060142811686900000)*t;
y[25] += CONSTANT(-0.099440056652700004)*t;
y[29] += CONSTANT(0.034310079156599997)*t;
// [17,34]: 29,11,1,
tf = CONSTANT(0.118853600623000000)*f[29] + CONSTANT(-0.029982305185400002)*f[11] + CONSTANT(-0.208340811100000000)*f[1];
tg = CONSTANT(0.118853600623000000)*g[29] + CONSTANT(-0.029982305185400002)*g[11] + CONSTANT(-0.208340811100000000)*g[1];
y[17] += tf*g[34] + tg*f[34];
y[34] += tf*g[17] + tg*f[17];
t = f[17] * g[34] + f[34] * g[17];
y[29] += CONSTANT(0.118853600623000000)*t;
y[11] += CONSTANT(-0.029982305185400002)*t;
y[1] += CONSTANT(-0.208340811100000000)*t;
// [18,18]: 6,0,20,24,
tf = CONSTANT(0.065535909662600006)*f[6] + CONSTANT(0.282094791771999980)*f[0] + CONSTANT(-0.083698454702400005)*f[20] + CONSTANT(-0.135045473384000000)*f[24];
tg = CONSTANT(0.065535909662600006)*g[6] + CONSTANT(0.282094791771999980)*g[0] + CONSTANT(-0.083698454702400005)*g[20] + CONSTANT(-0.135045473384000000)*g[24];
y[18] += tf*g[18] + tg*f[18];
t = f[18] * g[18];
y[6] += CONSTANT(0.065535909662600006)*t;
y[0] += CONSTANT(0.282094791771999980)*t;
y[20] += CONSTANT(-0.083698454702400005)*t;
y[24] += CONSTANT(-0.135045473384000000)*t;
// [18,19]: 7,21,23,
tf = CONSTANT(0.090297865407399994)*f[7] + CONSTANT(0.102084782359000000)*f[21] + CONSTANT(-0.045015157794399997)*f[23];
tg = CONSTANT(0.090297865407399994)*g[7] + CONSTANT(0.102084782359000000)*g[21] + CONSTANT(-0.045015157794399997)*g[23];
y[18] += tf*g[19] + tg*f[19];
y[19] += tf*g[18] + tg*f[18];
t = f[18] * g[19] + f[19] * g[18];
y[7] += CONSTANT(0.090297865407399994)*t;
y[21] += CONSTANT(0.102084782359000000)*t;
y[23] += CONSTANT(-0.045015157794399997)*t;
// [18,25]: 15,33,
tf = CONSTANT(-0.098140130731999994)*f[15] + CONSTANT(0.130197596202000000)*f[33];
tg = CONSTANT(-0.098140130731999994)*g[15] + CONSTANT(0.130197596202000000)*g[33];
y[18] += tf*g[25] + tg*f[25];
y[25] += tf*g[18] + tg*f[18];
t = f[18] * g[25] + f[25] * g[18];
y[15] += CONSTANT(-0.098140130731999994)*t;
y[33] += CONSTANT(0.130197596202000000)*t;
// [18,26]: 14,32,
tf = CONSTANT(0.101358691174000000)*f[14] + CONSTANT(0.084042186965900004)*f[32];
tg = CONSTANT(0.101358691174000000)*g[14] + CONSTANT(0.084042186965900004)*g[32];
y[18] += tf*g[26] + tg*f[26];
y[26] += tf*g[18] + tg*f[18];
t = f[18] * g[26] + f[26] * g[18];
y[14] += CONSTANT(0.101358691174000000)*t;
y[32] += CONSTANT(0.084042186965900004)*t;
// [18,27]: 13,3,35,
tf = CONSTANT(0.101990215611000000)*f[13] + CONSTANT(0.183739324705999990)*f[3] + CONSTANT(-0.130197596202000000)*f[35];
tg = CONSTANT(0.101990215611000000)*g[13] + CONSTANT(0.183739324705999990)*g[3] + CONSTANT(-0.130197596202000000)*g[35];
y[18] += tf*g[27] + tg*f[27];
y[27] += tf*g[18] + tg*f[18];
t = f[18] * g[27] + f[27] * g[18];
y[13] += CONSTANT(0.101990215611000000)*t;
y[3] += CONSTANT(0.183739324705999990)*t;
y[35] += CONSTANT(-0.130197596202000000)*t;
// [18,28]: 2,12,30,34,
tf = CONSTANT(0.225033795606000010)*f[2] + CONSTANT(0.022664492358099999)*f[12] + CONSTANT(-0.099440056651100006)*f[30] + CONSTANT(-0.084042186968800003)*f[34];
tg = CONSTANT(0.225033795606000010)*g[2] + CONSTANT(0.022664492358099999)*g[12] + CONSTANT(-0.099440056651100006)*g[30] + CONSTANT(-0.084042186968800003)*g[34];
y[18] += tf*g[28] + tg*f[28];
y[28] += tf*g[18] + tg*f[18];
t = f[18] * g[28] + f[28] * g[18];
y[2] += CONSTANT(0.225033795606000010)*t;
y[12] += CONSTANT(0.022664492358099999)*t;
y[30] += CONSTANT(-0.099440056651100006)*t;
y[34] += CONSTANT(-0.084042186968800003)*t;
// [18,29]: 3,13,15,31,
tf = CONSTANT(-0.085054779966799998)*f[3] + CONSTANT(0.075189952564900006)*f[13] + CONSTANT(0.101584686310000010)*f[15] + CONSTANT(0.097043558538999999)*f[31];
tg = CONSTANT(-0.085054779966799998)*g[3] + CONSTANT(0.075189952564900006)*g[13] + CONSTANT(0.101584686310000010)*g[15] + CONSTANT(0.097043558538999999)*g[31];
y[18] += tf*g[29] + tg*f[29];
y[29] += tf*g[18] + tg*f[18];
t = f[18] * g[29] + f[29] * g[18];
y[3] += CONSTANT(-0.085054779966799998)*t;
y[13] += CONSTANT(0.075189952564900006)*t;
y[15] += CONSTANT(0.101584686310000010)*t;
y[31] += CONSTANT(0.097043558538999999)*t;
// [19,19]: 6,8,0,20,22,
tf = CONSTANT(0.139263808033999990)*f[6] + CONSTANT(-0.141889406570999990)*f[8] + CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.068480553847200004)*f[20] + CONSTANT(-0.102084782360000000)*f[22];
tg = CONSTANT(0.139263808033999990)*g[6] + CONSTANT(-0.141889406570999990)*g[8] + CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.068480553847200004)*g[20] + CONSTANT(-0.102084782360000000)*g[22];
y[19] += tf*g[19] + tg*f[19];
t = f[19] * g[19];
y[6] += CONSTANT(0.139263808033999990)*t;
y[8] += CONSTANT(-0.141889406570999990)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
y[20] += CONSTANT(0.068480553847200004)*t;
y[22] += CONSTANT(-0.102084782360000000)*t;
// [19,25]: 34,
tf = CONSTANT(-0.130197596205999990)*f[34];
tg = CONSTANT(-0.130197596205999990)*g[34];
y[19] += tf*g[25] + tg*f[25];
y[25] += tf*g[19] + tg*f[19];
t = f[19] * g[25] + f[25] * g[19];
y[34] += CONSTANT(-0.130197596205999990)*t;
// [19,26]: 15,35,
tf = CONSTANT(-0.131668802182000000)*f[15] + CONSTANT(0.130197596204999990)*f[35];
tg = CONSTANT(-0.131668802182000000)*g[15] + CONSTANT(0.130197596204999990)*g[35];
y[19] += tf*g[26] + tg*f[26];
y[26] += tf*g[19] + tg*f[19];
t = f[19] * g[26] + f[26] * g[19];
y[15] += CONSTANT(-0.131668802182000000)*t;
y[35] += CONSTANT(0.130197596204999990)*t;
// [19,27]: 14,32,
tf = CONSTANT(0.025339672793899998)*f[14] + CONSTANT(0.084042186967699994)*f[32];
tg = CONSTANT(0.025339672793899998)*g[14] + CONSTANT(0.084042186967699994)*g[32];
y[19] += tf*g[27] + tg*f[27];
y[27] += tf*g[19] + tg*f[19];
t = f[19] * g[27] + f[27] * g[19];
y[14] += CONSTANT(0.025339672793899998)*t;
y[32] += CONSTANT(0.084042186967699994)*t;
// [19,28]: 13,3,15,31,33,
tf = CONSTANT(0.104682806111000000)*f[13] + CONSTANT(0.159122922869999990)*f[3] + CONSTANT(-0.126698363970000010)*f[15] + CONSTANT(0.090775936911399999)*f[31] + CONSTANT(-0.084042186968400004)*f[33];
tg = CONSTANT(0.104682806111000000)*g[13] + CONSTANT(0.159122922869999990)*g[3] + CONSTANT(-0.126698363970000010)*g[15] + CONSTANT(0.090775936911399999)*g[31] + CONSTANT(-0.084042186968400004)*g[33];
y[19] += tf*g[28] + tg*f[28];
y[28] += tf*g[19] + tg*f[19];
t = f[19] * g[28] + f[28] * g[19];
y[13] += CONSTANT(0.104682806111000000)*t;
y[3] += CONSTANT(0.159122922869999990)*t;
y[15] += CONSTANT(-0.126698363970000010)*t;
y[31] += CONSTANT(0.090775936911399999)*t;
y[33] += CONSTANT(-0.084042186968400004)*t;
// [19,29]: 12,14,2,30,32,
tf = CONSTANT(0.115089467124000010)*f[12] + CONSTANT(-0.097749909977199997)*f[14] + CONSTANT(0.240571246744999990)*f[2] + CONSTANT(0.053152946072499999)*f[30] + CONSTANT(-0.090775936912099994)*f[32];
tg = CONSTANT(0.115089467124000010)*g[12] + CONSTANT(-0.097749909977199997)*g[14] + CONSTANT(0.240571246744999990)*g[2] + CONSTANT(0.053152946072499999)*g[30] + CONSTANT(-0.090775936912099994)*g[32];
y[19] += tf*g[29] + tg*f[29];
y[29] += tf*g[19] + tg*f[19];
t = f[19] * g[29] + f[29] * g[19];
y[12] += CONSTANT(0.115089467124000010)*t;
y[14] += CONSTANT(-0.097749909977199997)*t;
y[2] += CONSTANT(0.240571246744999990)*t;
y[30] += CONSTANT(0.053152946072499999)*t;
y[32] += CONSTANT(-0.090775936912099994)*t;
// [20,20]: 6,0,20,
tf = CONSTANT(0.163839797503000010)*f[6] + CONSTANT(0.282094802232000010)*f[0];
tg = CONSTANT(0.163839797503000010)*g[6] + CONSTANT(0.282094802232000010)*g[0];
y[20] += tf*g[20] + tg*f[20];
t = f[20] * g[20];
y[6] += CONSTANT(0.163839797503000010)*t;
y[0] += CONSTANT(0.282094802232000010)*t;
y[20] += CONSTANT(0.136961139005999990)*t;
// [21,21]: 6,20,0,8,22,
tf = CONSTANT(0.139263808033999990)*f[6] + CONSTANT(0.068480553847200004)*f[20] + CONSTANT(0.282094791773999990)*f[0] + CONSTANT(0.141889406570999990)*f[8] + CONSTANT(0.102084782360000000)*f[22];
tg = CONSTANT(0.139263808033999990)*g[6] + CONSTANT(0.068480553847200004)*g[20] + CONSTANT(0.282094791773999990)*g[0] + CONSTANT(0.141889406570999990)*g[8] + CONSTANT(0.102084782360000000)*g[22];
y[21] += tf*g[21] + tg*f[21];
t = f[21] * g[21];
y[6] += CONSTANT(0.139263808033999990)*t;
y[20] += CONSTANT(0.068480553847200004)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
y[8] += CONSTANT(0.141889406570999990)*t;
y[22] += CONSTANT(0.102084782360000000)*t;
// [21,23]: 8,22,24,
tf = CONSTANT(-0.112621225039000000)*f[8] + CONSTANT(0.045015157794100001)*f[22] + CONSTANT(-0.119098912753000000)*f[24];
tg = CONSTANT(-0.112621225039000000)*g[8] + CONSTANT(0.045015157794100001)*g[22] + CONSTANT(-0.119098912753000000)*g[24];
y[21] += tf*g[23] + tg*f[23];
y[23] += tf*g[21] + tg*f[21];
t = f[21] * g[23] + f[23] * g[21];
y[8] += CONSTANT(-0.112621225039000000)*t;
y[22] += CONSTANT(0.045015157794100001)*t;
y[24] += CONSTANT(-0.119098912753000000)*t;
// [21,26]: 9,25,
tf = CONSTANT(-0.131668802182000000)*f[9] + CONSTANT(-0.130197596204999990)*f[25];
tg = CONSTANT(-0.131668802182000000)*g[9] + CONSTANT(-0.130197596204999990)*g[25];
y[21] += tf*g[26] + tg*f[26];
y[26] += tf*g[21] + tg*f[21];
t = f[21] * g[26] + f[26] * g[21];
y[9] += CONSTANT(-0.131668802182000000)*t;
y[25] += CONSTANT(-0.130197596204999990)*t;
// [21,28]: 27,1,11,9,29,
tf = CONSTANT(0.084042186968400004)*f[27] + CONSTANT(0.159122922869999990)*f[1] + CONSTANT(0.104682806111000000)*f[11] + CONSTANT(0.126698363970000010)*f[9] + CONSTANT(0.090775936911399999)*f[29];
tg = CONSTANT(0.084042186968400004)*g[27] + CONSTANT(0.159122922869999990)*g[1] + CONSTANT(0.104682806111000000)*g[11] + CONSTANT(0.126698363970000010)*g[9] + CONSTANT(0.090775936911399999)*g[29];
y[21] += tf*g[28] + tg*f[28];
y[28] += tf*g[21] + tg*f[21];
t = f[21] * g[28] + f[28] * g[21];
y[27] += CONSTANT(0.084042186968400004)*t;
y[1] += CONSTANT(0.159122922869999990)*t;
y[11] += CONSTANT(0.104682806111000000)*t;
y[9] += CONSTANT(0.126698363970000010)*t;
y[29] += CONSTANT(0.090775936911399999)*t;
// [21,31]: 14,2,30,12,32,
tf = CONSTANT(0.097749909977199997)*f[14] + CONSTANT(0.240571246744999990)*f[2] + CONSTANT(0.053152946072499999)*f[30] + CONSTANT(0.115089467124000010)*f[12] + CONSTANT(0.090775936912099994)*f[32];
tg = CONSTANT(0.097749909977199997)*g[14] + CONSTANT(0.240571246744999990)*g[2] + CONSTANT(0.053152946072499999)*g[30] + CONSTANT(0.115089467124000010)*g[12] + CONSTANT(0.090775936912099994)*g[32];
y[21] += tf*g[31] + tg*f[31];
y[31] += tf*g[21] + tg*f[21];
t = f[21] * g[31] + f[31] * g[21];
y[14] += CONSTANT(0.097749909977199997)*t;
y[2] += CONSTANT(0.240571246744999990)*t;
y[30] += CONSTANT(0.053152946072499999)*t;
y[12] += CONSTANT(0.115089467124000010)*t;
y[32] += CONSTANT(0.090775936912099994)*t;
// [21,33]: 32,14,
tf = CONSTANT(0.084042186967699994)*f[32] + CONSTANT(0.025339672793899998)*f[14];
tg = CONSTANT(0.084042186967699994)*g[32] + CONSTANT(0.025339672793899998)*g[14];
y[21] += tf*g[33] + tg*f[33];
y[33] += tf*g[21] + tg*f[21];
t = f[21] * g[33] + f[33] * g[21];
y[32] += CONSTANT(0.084042186967699994)*t;
y[14] += CONSTANT(0.025339672793899998)*t;
// [21,34]: 35,
tf = CONSTANT(-0.130197596205999990)*f[35];
tg = CONSTANT(-0.130197596205999990)*g[35];
y[21] += tf*g[34] + tg*f[34];
y[34] += tf*g[21] + tg*f[21];
t = f[21] * g[34] + f[34] * g[21];
y[35] += CONSTANT(-0.130197596205999990)*t;
// [22,22]: 6,20,0,24,
tf = CONSTANT(0.065535909662600006)*f[6] + CONSTANT(-0.083698454702400005)*f[20] + CONSTANT(0.282094791771999980)*f[0] + CONSTANT(0.135045473384000000)*f[24];
tg = CONSTANT(0.065535909662600006)*g[6] + CONSTANT(-0.083698454702400005)*g[20] + CONSTANT(0.282094791771999980)*g[0] + CONSTANT(0.135045473384000000)*g[24];
y[22] += tf*g[22] + tg*f[22];
t = f[22] * g[22];
y[6] += CONSTANT(0.065535909662600006)*t;
y[20] += CONSTANT(-0.083698454702400005)*t;
y[0] += CONSTANT(0.282094791771999980)*t;
y[24] += CONSTANT(0.135045473384000000)*t;
// [22,26]: 10,28,
tf = CONSTANT(0.101358691174000000)*f[10] + CONSTANT(0.084042186965900004)*f[28];
tg = CONSTANT(0.101358691174000000)*g[10] + CONSTANT(0.084042186965900004)*g[28];
y[22] += tf*g[26] + tg*f[26];
y[26] += tf*g[22] + tg*f[22];
t = f[22] * g[26] + f[26] * g[22];
y[10] += CONSTANT(0.101358691174000000)*t;
y[28] += CONSTANT(0.084042186965900004)*t;
// [22,27]: 1,11,25,
tf = CONSTANT(0.183739324704000010)*f[1] + CONSTANT(0.101990215611000000)*f[11] + CONSTANT(0.130197596200999990)*f[25];
tg = CONSTANT(0.183739324704000010)*g[1] + CONSTANT(0.101990215611000000)*g[11] + CONSTANT(0.130197596200999990)*g[25];
y[22] += tf*g[27] + tg*f[27];
y[27] += tf*g[22] + tg*f[22];
t = f[22] * g[27] + f[27] * g[22];
y[1] += CONSTANT(0.183739324704000010)*t;
y[11] += CONSTANT(0.101990215611000000)*t;
y[25] += CONSTANT(0.130197596200999990)*t;
// [22,32]: 2,30,12,34,
tf = CONSTANT(0.225033795606000010)*f[2] + CONSTANT(-0.099440056651100006)*f[30] + CONSTANT(0.022664492358099999)*f[12] + CONSTANT(0.084042186968800003)*f[34];
tg = CONSTANT(0.225033795606000010)*g[2] + CONSTANT(-0.099440056651100006)*g[30] + CONSTANT(0.022664492358099999)*g[12] + CONSTANT(0.084042186968800003)*g[34];
y[22] += tf*g[32] + tg*f[32];
y[32] += tf*g[22] + tg*f[22];
t = f[22] * g[32] + f[32] * g[22];
y[2] += CONSTANT(0.225033795606000010)*t;
y[30] += CONSTANT(-0.099440056651100006)*t;
y[12] += CONSTANT(0.022664492358099999)*t;
y[34] += CONSTANT(0.084042186968800003)*t;
// [22,33]: 3,13,35,
tf = CONSTANT(0.183739324704000010)*f[3] + CONSTANT(0.101990215611000000)*f[13] + CONSTANT(0.130197596200999990)*f[35];
tg = CONSTANT(0.183739324704000010)*g[3] + CONSTANT(0.101990215611000000)*g[13] + CONSTANT(0.130197596200999990)*g[35];
y[22] += tf*g[33] + tg*f[33];
y[33] += tf*g[22] + tg*f[22];
t = f[22] * g[33] + f[33] * g[22];
y[3] += CONSTANT(0.183739324704000010)*t;
y[13] += CONSTANT(0.101990215611000000)*t;
y[35] += CONSTANT(0.130197596200999990)*t;
// [23,23]: 6,20,0,
tf = CONSTANT(-0.057343920955899998)*f[6] + CONSTANT(-0.159787958979000000)*f[20] + CONSTANT(0.282094791768999990)*f[0];
tg = CONSTANT(-0.057343920955899998)*g[6] + CONSTANT(-0.159787958979000000)*g[20] + CONSTANT(0.282094791768999990)*g[0];
y[23] += tf*g[23] + tg*f[23];
t = f[23] * g[23];
y[6] += CONSTANT(-0.057343920955899998)*t;
y[20] += CONSTANT(-0.159787958979000000)*t;
y[0] += CONSTANT(0.282094791768999990)*t;
// [23,26]: 1,11,29,
tf = CONSTANT(0.208340811096000000)*f[1] + CONSTANT(0.029982305185199998)*f[11] + CONSTANT(-0.118853600623999990)*f[29];
tg = CONSTANT(0.208340811096000000)*g[1] + CONSTANT(0.029982305185199998)*g[11] + CONSTANT(-0.118853600623999990)*g[29];
y[23] += tf*g[26] + tg*f[26];
y[26] += tf*g[23] + tg*f[23];
t = f[23] * g[26] + f[26] * g[23];
y[1] += CONSTANT(0.208340811096000000)*t;
y[11] += CONSTANT(0.029982305185199998)*t;
y[29] += CONSTANT(-0.118853600623999990)*t;
// [23,28]: 25,11,1,29,
tf = CONSTANT(-0.099440056652200001)*f[25] + CONSTANT(-0.121172043789000000)*f[11] + CONSTANT(0.060142811686500000)*f[1] + CONSTANT(-0.034310079156700000)*f[29];
tg = CONSTANT(-0.099440056652200001)*g[25] + CONSTANT(-0.121172043789000000)*g[11] + CONSTANT(0.060142811686500000)*g[1] + CONSTANT(-0.034310079156700000)*g[29];
y[23] += tf*g[28] + tg*f[28];
y[28] += tf*g[23] + tg*f[23];
t = f[23] * g[28] + f[28] * g[23];
y[25] += CONSTANT(-0.099440056652200001)*t;
y[11] += CONSTANT(-0.121172043789000000)*t;
y[1] += CONSTANT(0.060142811686500000)*t;
y[29] += CONSTANT(-0.034310079156700000)*t;
// [23,32]: 31,13,3,35,
tf = CONSTANT(0.034310079156599997)*f[31] + CONSTANT(0.121172043788000010)*f[13] + CONSTANT(-0.060142811686900000)*f[3] + CONSTANT(-0.099440056652700004)*f[35];
tg = CONSTANT(0.034310079156599997)*g[31] + CONSTANT(0.121172043788000010)*g[13] + CONSTANT(-0.060142811686900000)*g[3] + CONSTANT(-0.099440056652700004)*g[35];
y[23] += tf*g[32] + tg*f[32];
y[32] += tf*g[23] + tg*f[23];
t = f[23] * g[32] + f[32] * g[23];
y[31] += CONSTANT(0.034310079156599997)*t;
y[13] += CONSTANT(0.121172043788000010)*t;
y[3] += CONSTANT(-0.060142811686900000)*t;
y[35] += CONSTANT(-0.099440056652700004)*t;
// [23,33]: 2,30,12,
tf = CONSTANT(0.196425600433000000)*f[2] + CONSTANT(-0.130197596204999990)*f[30] + CONSTANT(-0.103861751821000010)*f[12];
tg = CONSTANT(0.196425600433000000)*g[2] + CONSTANT(-0.130197596204999990)*g[30] + CONSTANT(-0.103861751821000010)*g[12];
y[23] += tf*g[33] + tg*f[33];
y[33] += tf*g[23] + tg*f[23];
t = f[23] * g[33] + f[33] * g[23];
y[2] += CONSTANT(0.196425600433000000)*t;
y[30] += CONSTANT(-0.130197596204999990)*t;
y[12] += CONSTANT(-0.103861751821000010)*t;
// [23,34]: 3,13,31,
tf = CONSTANT(0.208340811100000000)*f[3] + CONSTANT(0.029982305185400002)*f[13] + CONSTANT(-0.118853600623000000)*f[31];
tg = CONSTANT(0.208340811100000000)*g[3] + CONSTANT(0.029982305185400002)*g[13] + CONSTANT(-0.118853600623000000)*g[31];
y[23] += tf*g[34] + tg*f[34];
y[34] += tf*g[23] + tg*f[23];
t = f[23] * g[34] + f[34] * g[23];
y[3] += CONSTANT(0.208340811100000000)*t;
y[13] += CONSTANT(0.029982305185400002)*t;
y[31] += CONSTANT(-0.118853600623000000)*t;
// [24,24]: 6,0,20,
tf = CONSTANT(-0.229375683829000000)*f[6] + CONSTANT(0.282094791763999990)*f[0] + CONSTANT(0.106525305981000000)*f[20];
tg = CONSTANT(-0.229375683829000000)*g[6] + CONSTANT(0.282094791763999990)*g[0] + CONSTANT(0.106525305981000000)*g[20];
y[24] += tf*g[24] + tg*f[24];
t = f[24] * g[24];
y[6] += CONSTANT(-0.229375683829000000)*t;
y[0] += CONSTANT(0.282094791763999990)*t;
y[20] += CONSTANT(0.106525305981000000)*t;
// [24,29]: 9,27,25,
tf = CONSTANT(-0.035835708931400000)*f[9] + CONSTANT(0.118853600623000000)*f[27] + CONSTANT(0.053152946071199997)*f[25];
tg = CONSTANT(-0.035835708931400000)*g[9] + CONSTANT(0.118853600623000000)*g[27] + CONSTANT(0.053152946071199997)*g[25];
y[24] += tf*g[29] + tg*f[29];
y[29] += tf*g[24] + tg*f[24];
t = f[24] * g[29] + f[29] * g[24];
y[9] += CONSTANT(-0.035835708931400000)*t;
y[27] += CONSTANT(0.118853600623000000)*t;
y[25] += CONSTANT(0.053152946071199997)*t;
// [24,31]: 15,33,35,
tf = CONSTANT(0.035835708931400000)*f[15] + CONSTANT(-0.118853600623000000)*f[33] + CONSTANT(0.053152946071199997)*f[35];
tg = CONSTANT(0.035835708931400000)*g[15] + CONSTANT(-0.118853600623000000)*g[33] + CONSTANT(0.053152946071199997)*g[35];
y[24] += tf*g[31] + tg*f[31];
y[31] += tf*g[24] + tg*f[24];
t = f[24] * g[31] + f[31] * g[24];
y[15] += CONSTANT(0.035835708931400000)*t;
y[33] += CONSTANT(-0.118853600623000000)*t;
y[35] += CONSTANT(0.053152946071199997)*t;
// [24,34]: 12,30,2,
tf = CONSTANT(-0.207723503645000000)*f[12] + CONSTANT(0.130197596199999990)*f[30] + CONSTANT(0.147319200325000010)*f[2];
tg = CONSTANT(-0.207723503645000000)*g[12] + CONSTANT(0.130197596199999990)*g[30] + CONSTANT(0.147319200325000010)*g[2];
y[24] += tf*g[34] + tg*f[34];
y[34] += tf*g[24] + tg*f[24];
t = f[24] * g[34] + f[34] * g[24];
y[12] += CONSTANT(-0.207723503645000000)*t;
y[30] += CONSTANT(0.130197596199999990)*t;
y[2] += CONSTANT(0.147319200325000010)*t;
// [25,25]: 0,6,20,
tf = CONSTANT(0.282094791761999970)*f[0] + CONSTANT(-0.242608896358999990)*f[6] + CONSTANT(0.130197596198000000)*f[20];
tg = CONSTANT(0.282094791761999970)*g[0] + CONSTANT(-0.242608896358999990)*g[6] + CONSTANT(0.130197596198000000)*g[20];
y[25] += tf*g[25] + tg*f[25];
t = f[25] * g[25];
y[0] += CONSTANT(0.282094791761999970)*t;
y[6] += CONSTANT(-0.242608896358999990)*t;
y[20] += CONSTANT(0.130197596198000000)*t;
// [26,26]: 6,20,0,
tf = CONSTANT(-0.097043558542400002)*f[6] + CONSTANT(-0.130197596207000000)*f[20] + CONSTANT(0.282094791766000000)*f[0];
tg = CONSTANT(-0.097043558542400002)*g[6] + CONSTANT(-0.130197596207000000)*g[20] + CONSTANT(0.282094791766000000)*g[0];
y[26] += tf*g[26] + tg*f[26];
t = f[26] * g[26];
y[6] += CONSTANT(-0.097043558542400002)*t;
y[20] += CONSTANT(-0.130197596207000000)*t;
y[0] += CONSTANT(0.282094791766000000)*t;
// [27,27]: 0,20,6,
tf = CONSTANT(0.282094791770000020)*f[0] + CONSTANT(-0.130197596204999990)*f[20] + CONSTANT(0.016173926423100001)*f[6];
tg = CONSTANT(0.282094791770000020)*g[0] + CONSTANT(-0.130197596204999990)*g[20] + CONSTANT(0.016173926423100001)*g[6];
y[27] += tf*g[27] + tg*f[27];
t = f[27] * g[27];
y[0] += CONSTANT(0.282094791770000020)*t;
y[20] += CONSTANT(-0.130197596204999990)*t;
y[6] += CONSTANT(0.016173926423100001)*t;
// [28,28]: 6,0,20,24,
tf = CONSTANT(0.097043558538800007)*f[6] + CONSTANT(0.282094791771999980)*f[0] + CONSTANT(-0.021699599367299999)*f[20] + CONSTANT(-0.128376561118000000)*f[24];
tg = CONSTANT(0.097043558538800007)*g[6] + CONSTANT(0.282094791771999980)*g[0] + CONSTANT(-0.021699599367299999)*g[20] + CONSTANT(-0.128376561118000000)*g[24];
y[28] += tf*g[28] + tg*f[28];
t = f[28] * g[28];
y[6] += CONSTANT(0.097043558538800007)*t;
y[0] += CONSTANT(0.282094791771999980)*t;
y[20] += CONSTANT(-0.021699599367299999)*t;
y[24] += CONSTANT(-0.128376561118000000)*t;
// [29,29]: 20,6,0,22,8,
tf = CONSTANT(0.086798397468799998)*f[20] + CONSTANT(0.145565337808999990)*f[6] + CONSTANT(0.282094791773999990)*f[0] + CONSTANT(-0.097043558539500002)*f[22] + CONSTANT(-0.140070311615000000)*f[8];
tg = CONSTANT(0.086798397468799998)*g[20] + CONSTANT(0.145565337808999990)*g[6] + CONSTANT(0.282094791773999990)*g[0] + CONSTANT(-0.097043558539500002)*g[22] + CONSTANT(-0.140070311615000000)*g[8];
y[29] += tf*g[29] + tg*f[29];
t = f[29] * g[29];
y[20] += CONSTANT(0.086798397468799998)*t;
y[6] += CONSTANT(0.145565337808999990)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
y[22] += CONSTANT(-0.097043558539500002)*t;
y[8] += CONSTANT(-0.140070311615000000)*t;
// [30,30]: 0,20,6,
tf = CONSTANT(0.282094804531000000)*f[0] + CONSTANT(0.130197634486000000)*f[20] + CONSTANT(0.161739292769000010)*f[6];
tg = CONSTANT(0.282094804531000000)*g[0] + CONSTANT(0.130197634486000000)*g[20] + CONSTANT(0.161739292769000010)*g[6];
y[30] += tf*g[30] + tg*f[30];
t = f[30] * g[30];
y[0] += CONSTANT(0.282094804531000000)*t;
y[20] += CONSTANT(0.130197634486000000)*t;
y[6] += CONSTANT(0.161739292769000010)*t;
// [31,31]: 6,8,20,22,0,
tf = CONSTANT(0.145565337808999990)*f[6] + CONSTANT(0.140070311615000000)*f[8] + CONSTANT(0.086798397468799998)*f[20] + CONSTANT(0.097043558539500002)*f[22] + CONSTANT(0.282094791773999990)*f[0];
tg = CONSTANT(0.145565337808999990)*g[6] + CONSTANT(0.140070311615000000)*g[8] + CONSTANT(0.086798397468799998)*g[20] + CONSTANT(0.097043558539500002)*g[22] + CONSTANT(0.282094791773999990)*g[0];
y[31] += tf*g[31] + tg*f[31];
t = f[31] * g[31];
y[6] += CONSTANT(0.145565337808999990)*t;
y[8] += CONSTANT(0.140070311615000000)*t;
y[20] += CONSTANT(0.086798397468799998)*t;
y[22] += CONSTANT(0.097043558539500002)*t;
y[0] += CONSTANT(0.282094791773999990)*t;
// [32,32]: 0,24,20,6,
tf = CONSTANT(0.282094791771999980)*f[0] + CONSTANT(0.128376561118000000)*f[24] + CONSTANT(-0.021699599367299999)*f[20] + CONSTANT(0.097043558538800007)*f[6];
tg = CONSTANT(0.282094791771999980)*g[0] + CONSTANT(0.128376561118000000)*g[24] + CONSTANT(-0.021699599367299999)*g[20] + CONSTANT(0.097043558538800007)*g[6];
y[32] += tf*g[32] + tg*f[32];
t = f[32] * g[32];
y[0] += CONSTANT(0.282094791771999980)*t;
y[24] += CONSTANT(0.128376561118000000)*t;
y[20] += CONSTANT(-0.021699599367299999)*t;
y[6] += CONSTANT(0.097043558538800007)*t;
// [33,33]: 6,20,0,
tf = CONSTANT(0.016173926423100001)*f[6] + CONSTANT(-0.130197596204999990)*f[20] + CONSTANT(0.282094791770000020)*f[0];
tg = CONSTANT(0.016173926423100001)*g[6] + CONSTANT(-0.130197596204999990)*g[20] + CONSTANT(0.282094791770000020)*g[0];
y[33] += tf*g[33] + tg*f[33];
t = f[33] * g[33];
y[6] += CONSTANT(0.016173926423100001)*t;
y[20] += CONSTANT(-0.130197596204999990)*t;
y[0] += CONSTANT(0.282094791770000020)*t;
// [34,34]: 20,6,0,
tf = CONSTANT(-0.130197596207000000)*f[20] + CONSTANT(-0.097043558542400002)*f[6] + CONSTANT(0.282094791766000000)*f[0];
tg = CONSTANT(-0.130197596207000000)*g[20] + CONSTANT(-0.097043558542400002)*g[6] + CONSTANT(0.282094791766000000)*g[0];
y[34] += tf*g[34] + tg*f[34];
t = f[34] * g[34];
y[20] += CONSTANT(-0.130197596207000000)*t;
y[6] += CONSTANT(-0.097043558542400002)*t;
y[0] += CONSTANT(0.282094791766000000)*t;
// [35,35]: 6,0,20,
tf = CONSTANT(-0.242608896358999990)*f[6] + CONSTANT(0.282094791761999970)*f[0] + CONSTANT(0.130197596198000000)*f[20];
tg = CONSTANT(-0.242608896358999990)*g[6] + CONSTANT(0.282094791761999970)*g[0] + CONSTANT(0.130197596198000000)*g[20];
y[35] += tf*g[35] + tg*f[35];
t = f[35] * g[35];
y[6] += CONSTANT(-0.242608896358999990)*t;
y[0] += CONSTANT(0.282094791761999970)*t;
y[20] += CONSTANT(0.130197596198000000)*t;
// multiply count=2527
return y;
}
//-------------------------------------------------------------------------------------
// Evaluates a directional light and returns spectral SH data. The output
// vector is computed so that if the intensity of R/G/B is unit the resulting
// exit radiance of a point directly under the light on a diffuse object with
// an albedo of 1 would be 1.0. This will compute 3 spectral samples, resultR
// has to be specified, while resultG and resultB are optional.
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb204988.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
bool XM_CALLCONV DirectX::XMSHEvalDirectionalLight(
size_t order,
FXMVECTOR dir,
FXMVECTOR color,
float *resultR,
float *resultG,
float *resultB) noexcept
{
if (!resultR)
return false;
if (order < XM_SH_MINORDER || order > XM_SH_MAXORDER)
return false;
XMFLOAT3A clr;
XMStoreFloat3A(&clr, color);
float fTmp[XM_SH_MAXORDER * XM_SH_MAXORDER];
XMSHEvalDirection(fTmp, order, dir); // evaluate the BF in this direction...
// now compute "normalization" and scale vector for each valid spectral band
const float fNorm = XM_PI / CosWtInt(order);
const size_t numcoeff = order*order;
const float fRScale = fNorm * clr.x;
for (size_t i = 0; i < numcoeff; ++i)
{
resultR[i] = fTmp[i] * fRScale;
}
if (resultG)
{
const float fGScale = fNorm * clr.y;
for (size_t i = 0; i < numcoeff; ++i)
{
resultG[i] = fTmp[i] * fGScale;
}
}
if (resultB)
{
const float fBScale = fNorm * clr.z;
for (size_t i = 0; i < numcoeff; ++i)
{
resultB[i] = fTmp[i] * fBScale;
}
}
return true;
}
//------------------------------------------------------------------------------------
// Evaluates a spherical light and returns spectral SH data. There is no
// normalization of the intensity of the light like there is for directional
// lights, care has to be taken when specifiying the intensities. This will
// compute 3 spectral samples, resultR has to be specified, while resultG and
// resultB are optional.
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb205451.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
bool XM_CALLCONV DirectX::XMSHEvalSphericalLight(
size_t order,
FXMVECTOR pos,
float radius,
FXMVECTOR color,
float *resultR,
float *resultG,
float *resultB) noexcept
{
if (!resultR)
return false;
if (radius < 0.f)
return false;
const float fDist = XMVectorGetX(XMVector3Length(pos));
// WARNING: fDist should not be < radius - otherwise light contains origin
//const float fSinConeAngle = (fDist <= radius) ? 0.99999f : radius/fDist;
const float fConeAngle = (fDist <= radius) ? (XM_PIDIV2) : asinf(radius / fDist);
XMVECTOR dir = XMVector3Normalize(pos);
float fTmpDir[XM_SH_MAXORDER* XM_SH_MAXORDER]; // rotation "vector"
float fTmpL0[XM_SH_MAXORDER];
//
// Sphere at distance fDist, the cone angle is determined by looking at the
// right triangle with one side (the hypotenuse) beind the vector from the
// origin to the center of the sphere, another side is from the origin to
// a point on the sphere whose normal is perpendicular to the given side (this
// is one of the points on the cone that is defined by the projection of the sphere
// through the origin - we want to find the angle of this cone) and the final
// side being from the center of the sphere to the point of tagency (the two
// sides conected to this are at a right angle by construction.)
// From trig we know that sin(theta) = ||opposite||/||hypotenuse||, where
// ||opposite|| = Radius, ||hypotenuse|| = fDist
// theta is the angle of the cone that subtends the sphere from the origin
//
// no default normalization is done for this case, have to be careful how
// you represent the coefficients...
const float fNewNorm = 1.0f;///(fSinConeAngle*fSinConeAngle);
ComputeCapInt(order, fConeAngle, fTmpL0);
XMFLOAT3A vd;
XMStoreFloat3(&vd, dir);
const float fX = vd.x;
const float fY = vd.y;
const float fZ = vd.z;
switch (order)
{
case 2:
sh_eval_basis_1(fX, fY, fZ, fTmpDir);
break;
case 3:
sh_eval_basis_2(fX, fY, fZ, fTmpDir);
break;
case 4:
sh_eval_basis_3(fX, fY, fZ, fTmpDir);
break;
case 5:
sh_eval_basis_4(fX, fY, fZ, fTmpDir);
break;
case 6:
sh_eval_basis_5(fX, fY, fZ, fTmpDir);
break;
default:
assert(order < XM_SH_MINORDER || order > XM_SH_MAXORDER);
return false;
}
XMFLOAT3A clr;
XMStoreFloat3A(&clr, color);
for (size_t i = 0; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * clr.x*fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j) resultR[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
if (resultG)
{
for (size_t i = 0; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * clr.y*fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j) resultG[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
}
if (resultB)
{
for (size_t i = 0; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * clr.z*fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j) resultB[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
}
return true;
}
//-------------------------------------------------------------------------------------
// Evaluates a light that is a cone of constant intensity and returns spectral
// SH data. The output vector is computed so that if the intensity of R/G/B is
// unit the resulting exit radiance of a point directly under the light oriented
// in the cone direction on a diffuse object with an albedo of 1 would be 1.0.
// This will compute 3 spectral samples, resultR has to be specified, while resultG
// and resultB are optional.
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb204986.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
bool XM_CALLCONV DirectX::XMSHEvalConeLight(
size_t order,
FXMVECTOR dir,
float radius,
FXMVECTOR color,
float *resultR,
float *resultG,
float *resultB) noexcept
{
if (!resultR)
return false;
if (radius < 0.f || radius >(XM_PI*1.00001f))
return false;
if (radius < 0.0001f)
{
// turn it into a pure directional light...
return XMSHEvalDirectionalLight(order, dir, color, resultR, resultG, resultB);
}
else
{
float fTmpL0[XM_SH_MAXORDER];
float fTmpDir[XM_SH_MAXORDER * XM_SH_MAXORDER];
const float fConeAngle = radius;
const float fAngCheck = (fConeAngle > XM_PIDIV2) ? (XM_PIDIV2) : fConeAngle;
const float fNewNorm = 1.0f / (sinf(fAngCheck)*sinf(fAngCheck));
ComputeCapInt(order, fConeAngle, fTmpL0);
XMFLOAT3A vd;
XMStoreFloat3(&vd, dir);
const float fX = vd.x;
const float fY = vd.y;
const float fZ = vd.z;
switch (order)
{
case 2:
sh_eval_basis_1(fX, fY, fZ, fTmpDir);
break;
case 3:
sh_eval_basis_2(fX, fY, fZ, fTmpDir);
break;
case 4:
sh_eval_basis_3(fX, fY, fZ, fTmpDir);
break;
case 5:
sh_eval_basis_4(fX, fY, fZ, fTmpDir);
break;
case 6:
sh_eval_basis_5(fX, fY, fZ, fTmpDir);
break;
default:
assert(order < XM_SH_MINORDER || order > XM_SH_MAXORDER);
return false;
}
XMFLOAT3A clr;
XMStoreFloat3A(&clr, color);
for (size_t i = 0; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * clr.x*fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j)
resultR[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
if (resultG)
{
for (size_t i = 0; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * clr.y*fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j)
resultG[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
}
if (resultB)
{
for (size_t i = 0; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * clr.z*fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j)
resultB[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
}
}
return true;
}
//------------------------------------------------------------------------------------
// Evaluates a light that is a linear interpolant between two colors over the
// sphere. The interpolant is linear along the axis of the two points, not
// over the surface of the sphere (ie: if the axis was (0,0,1) it is linear in
// Z, not in the azimuthal angle.) The resulting spherical lighting function
// is normalized so that a point on a perfectly diffuse surface with no
// shadowing and a normal pointed in the direction pDir would result in exit
// radiance with a value of 1 if the top color was white and the bottom color
// was black. This is a very simple model where topColor represents the intensity
// of the "sky" and bottomColor represents the intensity of the "ground".
//
// http://msdn.microsoft.com/en-us/library/windows/desktop/bb204989.aspx
//-------------------------------------------------------------------------------------
_Use_decl_annotations_
bool XM_CALLCONV DirectX::XMSHEvalHemisphereLight(
size_t order,
FXMVECTOR dir,
FXMVECTOR topColor,
FXMVECTOR bottomColor,
float *resultR,
float *resultG,
float *resultB) noexcept
{
if (!resultR)
return false;
if (order < XM_SH_MINORDER || order > XM_SH_MAXORDER)
return false;
// seperate "R/G/B colors...
float fTmpDir[XM_SH_MAXORDER * XM_SH_MAXORDER]; // rotation "vector"
float fTmpL0[XM_SH_MAXORDER];
const float fNewNorm = 3.0f / 2.0f; // normalizes things for 1 sky color, 0 ground color...
XMFLOAT3A vd;
XMStoreFloat3(&vd, dir);
const float fX = vd.x;
const float fY = vd.y;
const float fZ = vd.z;
sh_eval_basis_1(fX, fY, fZ, fTmpDir);
XMFLOAT3A clrTop;
XMStoreFloat3A(&clrTop, topColor);
XMFLOAT3A clrBottom;
XMStoreFloat3A(&clrBottom, bottomColor);
float fA = clrTop.x;
float fAvrg = (clrTop.x + clrBottom.x)*0.5f;
fTmpL0[0] = fAvrg*2.0f*SHEvalHemisphereLight_fSqrtPi;
fTmpL0[1] = (fA - fAvrg)*2.0f*SHEvalHemisphereLight_fSqrtPi3;
size_t i = 0;
for (; i < 2; ++i)
{
_Analysis_assume_(i < order);
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j) resultR[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
for (; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
for (size_t j = 0; j < cNumCoefs; ++j) resultR[cStart + j] = 0.0f;
}
if (resultG)
{
fA = clrTop.y;
fAvrg = (clrTop.y + clrBottom.y)*0.5f;
fTmpL0[0] = fAvrg*2.0f*SHEvalHemisphereLight_fSqrtPi;
fTmpL0[1] = (fA - fAvrg)*2.0f*SHEvalHemisphereLight_fSqrtPi3;
for (i = 0; i < 2; ++i)
{
_Analysis_assume_(i < order);
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j) resultG[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
for (; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
for (size_t j = 0; j < cNumCoefs; ++j) resultG[cStart + j] = 0.0f;
}
}
if (resultB)
{
fA = clrTop.z;
fAvrg = (clrTop.z + clrBottom.z)*0.5f;
fTmpL0[0] = fAvrg*2.0f*SHEvalHemisphereLight_fSqrtPi;
fTmpL0[1] = (fA - fAvrg)*2.0f*SHEvalHemisphereLight_fSqrtPi3;
for (i = 0; i < 2; ++i)
{
_Analysis_assume_(i < order);
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
const float fValUse = fTmpL0[i] * fNewNorm*fExtraNormFac[i];
for (size_t j = 0; j < cNumCoefs; ++j) resultB[cStart + j] = fTmpDir[cStart + j] * fValUse;
}
for (; i < order; ++i)
{
const size_t cNumCoefs = 2 * i + 1;
const size_t cStart = i*i;
for (size_t j = 0; j < cNumCoefs; ++j) resultB[cStart + j] = 0.0f;
}
}
return true;
}
| 44.53934 | 223 | 0.569928 | waruqi |
6dbd63f2020c5d3f1ca6df93d304ce083b4ee496 | 56,288 | cpp | C++ | test_common/harness/kernelHelpers.cpp | grey-eminence/OpenCL-CTS | a69f3ca8cf2d50d6cf81eebedfa177d03c02b00b | [
"Apache-2.0"
] | null | null | null | test_common/harness/kernelHelpers.cpp | grey-eminence/OpenCL-CTS | a69f3ca8cf2d50d6cf81eebedfa177d03c02b00b | [
"Apache-2.0"
] | null | null | null | test_common/harness/kernelHelpers.cpp | grey-eminence/OpenCL-CTS | a69f3ca8cf2d50d6cf81eebedfa177d03c02b00b | [
"Apache-2.0"
] | null | null | null | //
// Copyright (c) 2017 The Khronos Group Inc.
//
// 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 "crc32.h"
#include "kernelHelpers.h"
#include "deviceInfo.h"
#include "errorHelpers.h"
#include "imageHelpers.h"
#include "typeWrappers.h"
#include "testHarness.h"
#include "parseParameters.h"
#include <cassert>
#include <vector>
#include <string>
#include <fstream>
#include <sstream>
#include <iomanip>
#if defined(_WIN32)
std::string slash = "\\";
#else
std::string slash = "/";
#endif
static cl_int get_first_device_id(const cl_context context, cl_device_id &device);
long get_file_size(const std::string &fileName)
{
std::ifstream ifs(fileName.c_str(), std::ios::binary);
if (!ifs.good())
return 0;
// get length of file:
ifs.seekg(0, std::ios::end);
std::ios::pos_type length = ifs.tellg();
return static_cast<long>(length);
}
static std::string get_kernel_content(unsigned int numKernelLines, const char *const *kernelProgram)
{
std::string kernel;
for (size_t i = 0; i < numKernelLines; ++i)
{
std::string chunk(kernelProgram[i], 0, std::string::npos);
kernel += chunk;
}
return kernel;
}
std::string get_kernel_name(const std::string &source)
{
// Create list of kernel names
std::string kernelsList;
size_t kPos = source.find("kernel");
while (kPos != std::string::npos)
{
// check for '__kernel'
size_t pos = kPos;
if (pos >= 2 && source[pos - 1] == '_' && source[pos - 2] == '_')
pos -= 2;
//check character before 'kernel' (white space expected)
size_t wsPos = source.find_last_of(" \t\r\n", pos);
if (wsPos == std::string::npos || wsPos + 1 == pos)
{
//check character after 'kernel' (white space expected)
size_t akPos = kPos + sizeof("kernel") - 1;
wsPos = source.find_first_of(" \t\r\n", akPos);
if (!(wsPos == akPos))
{
kPos = source.find("kernel", kPos + 1);
continue;
}
bool attributeFound;
do
{
attributeFound = false;
// find '(' after kernel name name
size_t pPos = source.find("(", akPos);
if (!(pPos != std::string::npos))
continue;
// check for not empty kernel name before '('
pos = source.find_last_not_of(" \t\r\n", pPos - 1);
if (!(pos != std::string::npos && pos > akPos))
continue;
//find character before kernel name
wsPos = source.find_last_of(" \t\r\n", pos);
if (!(wsPos != std::string::npos && wsPos >= akPos))
continue;
std::string name = source.substr(wsPos + 1, pos + 1 - (wsPos + 1));
//check for kernel attribute
if (name == "__attribute__")
{
attributeFound = true;
int pCount = 1;
akPos = pPos + 1;
while (pCount > 0 && akPos != std::string::npos)
{
akPos = source.find_first_of("()", akPos + 1);
if (akPos != std::string::npos)
{
if (source[akPos] == '(')
pCount++;
else
pCount--;
}
}
}
else
{
kernelsList += name + ".";
}
} while (attributeFound);
}
kPos = source.find("kernel", kPos + 1);
}
std::ostringstream oss;
if (MAX_LEN_FOR_KERNEL_LIST > 0)
{
if (kernelsList.size() > MAX_LEN_FOR_KERNEL_LIST + 1)
{
kernelsList = kernelsList.substr(0, MAX_LEN_FOR_KERNEL_LIST + 1);
kernelsList[kernelsList.size() - 1] = '.';
kernelsList[kernelsList.size() - 1] = '.';
}
oss << kernelsList;
}
return oss.str();
}
static std::string get_offline_compilation_file_type_str(const CompilationMode compilationMode)
{
switch (compilationMode)
{
default:
assert(0 && "Invalid compilation mode");
abort();
case kOnline:
assert(0 && "Invalid compilation mode for offline compilation");
abort();
case kBinary:
return "binary";
case kSpir_v:
return "SPIR-V";
}
}
static std::string get_unique_filename_prefix(unsigned int numKernelLines,
const char *const *kernelProgram,
const char *buildOptions)
{
std::string kernel = get_kernel_content(numKernelLines, kernelProgram);
std::string kernelName = get_kernel_name(kernel);
cl_uint kernelCrc = crc32(kernel.data(), kernel.size());
std::ostringstream oss;
oss << kernelName << std::hex << std::setfill('0') << std::setw(8) << kernelCrc;
if(buildOptions) {
cl_uint bOptionsCrc = crc32(buildOptions, strlen(buildOptions));
oss << '.' << std::hex << std::setfill('0') << std::setw(8) << bOptionsCrc;
}
return oss.str();
}
static std::string
get_cl_build_options_filename_with_path(const std::string& filePath,
const std::string& fileNamePrefix) {
return filePath + slash + fileNamePrefix + ".options";
}
static std::string
get_cl_source_filename_with_path(const std::string& filePath,
const std::string& fileNamePrefix) {
return filePath + slash + fileNamePrefix + ".cl";
}
static std::string
get_binary_filename_with_path(CompilationMode mode,
cl_uint deviceAddrSpaceSize,
const std::string& filePath,
const std::string& fileNamePrefix) {
std::string binaryFilename = filePath + slash + fileNamePrefix;
if(kSpir_v == mode) {
std::ostringstream extension;
extension << ".spv" << deviceAddrSpaceSize;
binaryFilename += extension.str();
}
return binaryFilename;
}
static bool file_exist_on_disk(const std::string& filePath,
const std::string& fileName) {
std::string fileNameWithPath = filePath + slash + fileName;
bool exist = false;
std::ifstream ifs;
ifs.open(fileNameWithPath.c_str(), std::ios::binary);
if(ifs.good())
exist = true;
ifs.close();
return exist;
}
static bool should_save_kernel_source_to_disk(CompilationMode mode,
CompilationCacheMode cacheMode,
const std::string& binaryPath,
const std::string& binaryName)
{
bool saveToDisk = false;
if(cacheMode == kCacheModeDumpCl ||
(cacheMode == kCacheModeOverwrite && mode != kOnline)) {
saveToDisk = true;
}
if(cacheMode == kCacheModeCompileIfAbsent && mode != kOnline) {
saveToDisk = !file_exist_on_disk(binaryPath, binaryName);
}
return saveToDisk;
}
static int save_kernel_build_options_to_disk(const std::string& path,
const std::string& prefix,
const char *buildOptions) {
std::string filename = get_cl_build_options_filename_with_path(path, prefix);
std::ofstream ofs(filename.c_str(), std::ios::binary);
if (!ofs.good())
{
log_info("Can't save kernel build options: %s\n", filename.c_str());
return -1;
}
ofs.write(buildOptions, strlen(buildOptions));
ofs.close();
log_info("Saved kernel build options to file: %s\n", filename.c_str());
return CL_SUCCESS;
}
static int save_kernel_source_to_disk(const std::string& path,
const std::string& prefix,
const std::string& source) {
std::string filename = get_cl_source_filename_with_path(path, prefix);
std::ofstream ofs(filename.c_str(), std::ios::binary);
if (!ofs.good())
{
log_info("Can't save kernel source: %s\n", filename.c_str());
return -1;
}
ofs.write(source.c_str(), source.size());
ofs.close();
log_info("Saved kernel source to file: %s\n", filename.c_str());
return CL_SUCCESS;
}
static int save_kernel_source_and_options_to_disk(unsigned int numKernelLines,
const char *const *kernelProgram,
const char *buildOptions)
{
int error;
std::string kernel = get_kernel_content(numKernelLines, kernelProgram);
std::string kernelNamePrefix = get_unique_filename_prefix(numKernelLines,
kernelProgram,
buildOptions);
// save kernel source to disk
error = save_kernel_source_to_disk(gCompilationCachePath, kernelNamePrefix, kernel);
// save kernel build options to disk if exists
if (buildOptions != NULL)
error |= save_kernel_build_options_to_disk(gCompilationCachePath, kernelNamePrefix, buildOptions);
return error;
}
static std::string get_compilation_mode_str(const CompilationMode compilationMode)
{
switch (compilationMode)
{
default:
assert(0 && "Invalid compilation mode");
abort();
case kOnline:
return "online";
case kBinary:
return "binary";
case kSpir_v:
return "spir-v";
}
}
#ifdef KHRONOS_OFFLINE_COMPILER
static std::string get_khronos_compiler_command(const cl_uint device_address_space_size,
const bool openclCXX,
const std::string &bOptions,
const std::string &sourceFilename,
const std::string &outputFilename)
{
// Set compiler options
// Emit SPIR-V
std::string compilerOptions = " -cc1 -emit-spirv";
// <triple>: for 32 bit SPIR-V use spir-unknown-unknown, for 64 bit SPIR-V use spir64-unknown-unknown.
if(device_address_space_size == 32)
{
compilerOptions += " -triple=spir-unknown-unknown";
}
else
{
compilerOptions += " -triple=spir64-unknown-unknown";
}
// Set OpenCL C++ flag required by SPIR-V-ready clang (compiler provided by Khronos)
if(openclCXX)
{
compilerOptions = compilerOptions + " -cl-std=c++";
}
// Set correct includes
if(openclCXX)
{
compilerOptions += " -I ";
compilerOptions += STRINGIFY_VALUE(CL_LIBCLCXX_DIR);
}
else
{
compilerOptions += " -include opencl.h";
}
#ifdef KHRONOS_OFFLINE_COMPILER_OPTIONS
compilerOptions += STRINGIFY_VALUE(KHRONOS_OFFLINE_COMPILER_OPTIONS);
#endif
// Add build options passed to this function
compilerOptions += " " + bOptions;
compilerOptions +=
" " + sourceFilename +
" -o " + outputFilename;
std::string runString = STRINGIFY_VALUE(KHRONOS_OFFLINE_COMPILER) + compilerOptions;
return runString;
}
#endif // KHRONOS_OFFLINE_COMPILER
static cl_int get_cl_device_info_str(const cl_device_id device, const cl_uint device_address_space_size,
const CompilationMode compilationMode, std::string &clDeviceInfo)
{
std::string extensionsString = get_device_extensions_string(device);
std::string versionString = get_device_version_string(device);
std::ostringstream clDeviceInfoStream;
std::string file_type = get_offline_compilation_file_type_str(compilationMode);
clDeviceInfoStream << "# OpenCL device info affecting " << file_type << " offline compilation:" << std::endl
<< "CL_DEVICE_ADDRESS_BITS=" << device_address_space_size << std::endl
<< "CL_DEVICE_EXTENSIONS=\"" << extensionsString << "\"" << std::endl;
/* We only need the device's supported IL version(s) when compiling IL
* that will be loaded with clCreateProgramWithIL() */
if (compilationMode == kSpir_v)
{
std::string ilVersionString = get_device_il_version_string(device);
clDeviceInfoStream << "CL_DEVICE_IL_VERSION=\"" << ilVersionString << "\"" << std::endl;
}
clDeviceInfoStream << "CL_DEVICE_VERSION=\"" << versionString << "\"" << std::endl;
clDeviceInfoStream << "CL_DEVICE_IMAGE_SUPPORT="
<< (0 == checkForImageSupport(device)) << std::endl;
clDeviceInfoStream << "CL_DEVICE_NAME=\"" << get_device_name(device).c_str()
<< "\"" << std::endl;
clDeviceInfo = clDeviceInfoStream.str();
return CL_SUCCESS;
}
static int write_cl_device_info(const cl_device_id device, const cl_uint device_address_space_size,
const CompilationMode compilationMode, std::string &clDeviceInfoFilename)
{
std::string clDeviceInfo;
int error = get_cl_device_info_str(device, device_address_space_size, compilationMode, clDeviceInfo);
if (error != CL_SUCCESS)
{
return error;
}
cl_uint crc = crc32(clDeviceInfo.data(), clDeviceInfo.size());
/* Get the filename for the clDeviceInfo file.
* Note: the file includes the hash on its content, so it is usually unnecessary to delete it. */
std::ostringstream clDeviceInfoFilenameStream;
clDeviceInfoFilenameStream << gCompilationCachePath << slash << "clDeviceInfo-";
clDeviceInfoFilenameStream << std::hex << std::setfill('0') << std::setw(8) << crc << ".txt";
clDeviceInfoFilename = clDeviceInfoFilenameStream.str();
if ((size_t) get_file_size(clDeviceInfoFilename) == clDeviceInfo.size())
{
/* The CL device info file has already been created.
* Nothing to do. */
return 0;
}
/* The file does not exist or its length is not as expected. Create/overwrite it. */
std::ofstream ofs(clDeviceInfoFilename);
if (!ofs.good())
{
log_info("OfflineCompiler: can't create CL device info file: %s\n", clDeviceInfoFilename.c_str());
return -1;
}
ofs << clDeviceInfo;
ofs.close();
return CL_SUCCESS;
}
static std::string get_offline_compilation_command(const cl_uint device_address_space_size,
const CompilationMode compilationMode,
const std::string &bOptions,
const std::string &sourceFilename,
const std::string &outputFilename,
const std::string &clDeviceInfoFilename)
{
std::ostringstream wrapperOptions;
wrapperOptions << gCompilationProgram
<< " --mode=" << get_compilation_mode_str(compilationMode)
<< " --source=" << sourceFilename
<< " --output=" << outputFilename
<< " --cl-device-info=" << clDeviceInfoFilename;
if (bOptions != "")
{
// Add build options passed to this function
wrapperOptions << " -- " << bOptions;
}
return wrapperOptions.str();
}
static int invoke_offline_compiler(const cl_device_id device,
const cl_uint device_address_space_size,
const CompilationMode compilationMode,
const std::string &bOptions,
const std::string &sourceFilename,
const std::string &outputFilename,
const bool openclCXX)
{
std::string runString;
if (openclCXX)
{
#ifndef KHRONOS_OFFLINE_COMPILER
log_error("CL C++ compilation is not possible: KHRONOS_OFFLINE_COMPILER was not defined.\n");
return CL_INVALID_OPERATION;
#else
if (compilationMode != kSpir_v)
{
log_error("Compilation mode must be SPIR-V for Khronos compiler");
return -1;
}
runString = get_khronos_compiler_command(device_address_space_size, openclCXX, bOptions,
sourceFilename, outputFilename);
#endif
}
else
{
std::string clDeviceInfoFilename;
// See cl_offline_compiler-interface.txt for a description of the
// format of the CL device information file generated below, and
// the internal command line interface for invoking the offline
// compiler.
cl_int err = write_cl_device_info(device, device_address_space_size, compilationMode,
clDeviceInfoFilename);
if (err != CL_SUCCESS)
{
log_error("Failed writing CL device info file\n");
return err;
}
runString = get_offline_compilation_command(device_address_space_size, compilationMode, bOptions,
sourceFilename, outputFilename, clDeviceInfoFilename);
}
// execute script
log_info("Executing command: %s\n", runString.c_str());
fflush(stdout);
int returnCode = system(runString.c_str());
if (returnCode != 0)
{
log_error("ERROR: Command finished with error: 0x%x\n", returnCode);
return CL_COMPILE_PROGRAM_FAILURE;
}
return CL_SUCCESS;
}
static cl_int get_first_device_id(const cl_context context, cl_device_id &device)
{
cl_uint numDevices = 0;
cl_int error = clGetContextInfo(context, CL_CONTEXT_NUM_DEVICES, sizeof(cl_uint), &numDevices, NULL);
test_error(error, "clGetContextInfo failed getting CL_CONTEXT_NUM_DEVICES");
if (numDevices == 0)
{
log_error("ERROR: No CL devices found\n");
return -1;
}
std::vector<cl_device_id> devices(numDevices, 0);
error = clGetContextInfo(context, CL_CONTEXT_DEVICES, numDevices*sizeof(cl_device_id), &devices[0], NULL);
test_error(error, "clGetContextInfo failed getting CL_CONTEXT_DEVICES");
device = devices[0];
return CL_SUCCESS;
}
static cl_int get_device_address_bits(const cl_device_id device, cl_uint &device_address_space_size)
{
cl_int error = clGetDeviceInfo(device, CL_DEVICE_ADDRESS_BITS, sizeof(cl_uint), &device_address_space_size, NULL);
test_error(error, "Unable to obtain device address bits");
if (device_address_space_size != 32 && device_address_space_size != 64)
{
log_error("ERROR: Unexpected number of device address bits: %u\n", device_address_space_size);
return -1;
}
return CL_SUCCESS;
}
static int get_offline_compiler_output(std::ifstream &ifs,
const cl_device_id device,
cl_uint deviceAddrSpaceSize,
const bool openclCXX,
const CompilationMode compilationMode,
const std::string &bOptions,
const std::string &kernelPath,
const std::string &kernelNamePrefix)
{
std::string sourceFilename = get_cl_source_filename_with_path(kernelPath, kernelNamePrefix);
std::string outputFilename = get_binary_filename_with_path(compilationMode,
deviceAddrSpaceSize,
kernelPath,
kernelNamePrefix);
ifs.open(outputFilename.c_str(), std::ios::binary);
if(!ifs.good()) {
std::string file_type = get_offline_compilation_file_type_str(compilationMode);
if (gCompilationCacheMode == kCacheModeForceRead) {
log_info("OfflineCompiler: can't open cached %s file: %s\n",
file_type.c_str(), outputFilename.c_str());
return -1;
}
else {
int error = invoke_offline_compiler(device, deviceAddrSpaceSize, compilationMode,
bOptions, sourceFilename, outputFilename, openclCXX);
if (error != CL_SUCCESS)
return error;
// read output file
ifs.open(outputFilename.c_str(), std::ios::binary);
if (!ifs.good())
{
log_info("OfflineCompiler: can't read generated %s file: %s\n",
file_type.c_str(), outputFilename.c_str());
return -1;
}
}
}
return CL_SUCCESS;
}
static int create_single_kernel_helper_create_program_offline(cl_context context,
cl_device_id device,
cl_program *outProgram,
unsigned int numKernelLines,
const char *const *kernelProgram,
const char *buildOptions,
const bool openclCXX,
CompilationMode compilationMode)
{
if(kCacheModeDumpCl == gCompilationCacheMode) {
return -1;
}
// Get device CL_DEVICE_ADDRESS_BITS
int error;
cl_uint device_address_space_size = 0;
if (device == NULL)
{
error = get_first_device_id(context, device);
test_error(error, "Failed to get device ID for first device");
}
error = get_device_address_bits(device, device_address_space_size);
if (error != CL_SUCCESS)
return error;
// set build options
std::string bOptions;
bOptions += buildOptions ? std::string(buildOptions) : "";
std::string kernelName = get_unique_filename_prefix(numKernelLines,
kernelProgram,
buildOptions);
std::ifstream ifs;
error = get_offline_compiler_output(ifs, device, device_address_space_size, openclCXX, compilationMode, bOptions, gCompilationCachePath, kernelName);
if (error != CL_SUCCESS)
return error;
// -----------------------------------------------------------------------------------
// ------------- ONLY FOR OPENCL 22 CONFORMANCE TEST 22 DEVELOPMENT ------------------
// -----------------------------------------------------------------------------------
// Only OpenCL C++ to SPIR-V compilation
#if defined(DEVELOPMENT) && defined(ONLY_SPIRV_COMPILATION)
if(openclCXX)
{
return CL_SUCCESS;
}
#endif
ifs.seekg(0, ifs.end);
int length = ifs.tellg();
ifs.seekg(0, ifs.beg);
//treat modifiedProgram as input for clCreateProgramWithBinary
if (compilationMode == kBinary)
{
// read binary from file:
std::vector<unsigned char> modifiedKernelBuf(length);
ifs.read((char *)&modifiedKernelBuf[0], length);
ifs.close();
size_t lengths = modifiedKernelBuf.size();
const unsigned char *binaries = { &modifiedKernelBuf[0] };
log_info("offlineCompiler: clCreateProgramWithSource replaced with clCreateProgramWithBinary\n");
*outProgram = clCreateProgramWithBinary(context, 1, &device, &lengths, &binaries, NULL, &error);
if (*outProgram == NULL || error != CL_SUCCESS)
{
print_error(error, "clCreateProgramWithBinary failed");
return error;
}
}
//treat modifiedProgram as input for clCreateProgramWithIL
else if (compilationMode == kSpir_v)
{
// read spir-v from file:
std::vector<unsigned char> modifiedKernelBuf(length);
ifs.read((char *)&modifiedKernelBuf[0], length);
ifs.close();
size_t length = modifiedKernelBuf.size();
log_info("offlineCompiler: clCreateProgramWithSource replaced with clCreateProgramWithIL\n");
*outProgram = clCreateProgramWithIL(context, &modifiedKernelBuf[0], length, &error);
if (*outProgram == NULL || error != CL_SUCCESS)
{
print_error(error, "clCreateProgramWithIL failed");
return error;
}
}
return CL_SUCCESS;
}
static int create_single_kernel_helper_create_program(cl_context context,
cl_device_id device,
cl_program *outProgram,
unsigned int numKernelLines,
const char **kernelProgram,
const char *buildOptions,
const bool openclCXX,
CompilationMode compilationMode)
{
std::string filePrefix = get_unique_filename_prefix(numKernelLines,
kernelProgram,
buildOptions);
bool shouldSaveToDisk = should_save_kernel_source_to_disk(compilationMode,
gCompilationCacheMode,
gCompilationCachePath,
filePrefix);
if(shouldSaveToDisk)
{
if(CL_SUCCESS != save_kernel_source_and_options_to_disk(numKernelLines, kernelProgram, buildOptions))
{
log_error("Unable to dump kernel source to disk");
return -1;
}
}
if (compilationMode == kOnline)
{
int error = CL_SUCCESS;
/* Create the program object from source */
*outProgram = clCreateProgramWithSource(context, numKernelLines, kernelProgram, NULL, &error);
if (*outProgram == NULL || error != CL_SUCCESS)
{
print_error(error, "clCreateProgramWithSource failed");
return error;
}
return CL_SUCCESS;
}
else
{
return create_single_kernel_helper_create_program_offline(context, device, outProgram,
numKernelLines, kernelProgram,
buildOptions, openclCXX,
compilationMode);
}
}
int create_single_kernel_helper_create_program(cl_context context,
cl_program *outProgram,
unsigned int numKernelLines,
const char **kernelProgram,
const char *buildOptions,
const bool openclCXX)
{
return create_single_kernel_helper_create_program(context, NULL, outProgram,
numKernelLines, kernelProgram,
buildOptions, openclCXX,
gCompilationMode);
}
int create_single_kernel_helper_create_program_for_device(cl_context context,
cl_device_id device,
cl_program *outProgram,
unsigned int numKernelLines,
const char **kernelProgram,
const char *buildOptions,
const bool openclCXX)
{
return create_single_kernel_helper_create_program(context, device, outProgram,
numKernelLines, kernelProgram,
buildOptions, openclCXX,
gCompilationMode);
}
int create_single_kernel_helper_with_build_options(cl_context context,
cl_program *outProgram,
cl_kernel *outKernel,
unsigned int numKernelLines,
const char **kernelProgram,
const char *kernelName,
const char *buildOptions,
const bool openclCXX)
{
return create_single_kernel_helper(context, outProgram, outKernel, numKernelLines, kernelProgram, kernelName, buildOptions, openclCXX);
}
// Creates and builds OpenCL C/C++ program, and creates a kernel
int create_single_kernel_helper(cl_context context,
cl_program *outProgram,
cl_kernel *outKernel,
unsigned int numKernelLines,
const char **kernelProgram,
const char *kernelName,
const char *buildOptions,
const bool openclCXX)
{
int error;
// Create OpenCL C++ program
if(openclCXX)
{
// -----------------------------------------------------------------------------------
// ------------- ONLY FOR OPENCL 22 CONFORMANCE TEST 22 DEVELOPMENT ------------------
// -----------------------------------------------------------------------------------
// Only OpenCL C++ to SPIR-V compilation
#if defined(DEVELOPMENT) && defined(ONLY_SPIRV_COMPILATION)
// Save global variable
bool tempgCompilationCacheMode = gCompilationCacheMode;
// Force OpenCL C++ -> SPIR-V compilation on every run
gCompilationCacheMode = kCacheModeOverwrite;
#endif
error = create_openclcpp_program(
context, outProgram, numKernelLines, kernelProgram, buildOptions
);
if (error != CL_SUCCESS)
{
log_error("Create program failed: %d, line: %d\n", error, __LINE__);
return error;
}
// -----------------------------------------------------------------------------------
// ------------- ONLY FOR OPENCL 22 CONFORMANCE TEST 22 DEVELOPMENT ------------------
// -----------------------------------------------------------------------------------
#if defined(DEVELOPMENT) && defined(ONLY_SPIRV_COMPILATION)
// Restore global variables
gCompilationCacheMode = tempgCompilationCacheMode;
log_info("WARNING: KERNEL %s WAS ONLY COMPILED TO SPIR-V\n", kernelName);
return error;
#endif
}
// Create OpenCL C program
else
{
error = create_single_kernel_helper_create_program(
context, outProgram, numKernelLines, kernelProgram, buildOptions
);
if (error != CL_SUCCESS)
{
log_error("Create program failed: %d, line: %d\n", error, __LINE__);
return error;
}
}
// Remove offline-compiler-only build options
std::string newBuildOptions;
if (buildOptions != NULL)
{
newBuildOptions = buildOptions;
std::string offlineCompierOptions[] = {
"-cl-fp16-enable",
"-cl-fp64-enable",
"-cl-zero-init-local-mem-vars"
};
for(auto& s : offlineCompierOptions)
{
std::string::size_type i = newBuildOptions.find(s);
if (i != std::string::npos)
newBuildOptions.erase(i, s.length());
}
}
// Build program and create kernel
return build_program_create_kernel_helper(
context, outProgram, outKernel, numKernelLines, kernelProgram, kernelName, newBuildOptions.c_str()
);
}
// Creates OpenCL C++ program
int create_openclcpp_program(cl_context context,
cl_program *outProgram,
unsigned int numKernelLines,
const char **kernelProgram,
const char *buildOptions)
{
// Create program
return create_single_kernel_helper_create_program(
context, NULL, outProgram, numKernelLines, kernelProgram, buildOptions, true, kSpir_v
);
}
// Builds OpenCL C/C++ program and creates
int build_program_create_kernel_helper(cl_context context,
cl_program *outProgram,
cl_kernel *outKernel,
unsigned int numKernelLines,
const char **kernelProgram,
const char *kernelName,
const char *buildOptions)
{
int error;
/* Compile the program */
int buildProgramFailed = 0;
int printedSource = 0;
error = clBuildProgram(*outProgram, 0, NULL, buildOptions, NULL, NULL);
if (error != CL_SUCCESS)
{
unsigned int i;
print_error(error, "clBuildProgram failed");
buildProgramFailed = 1;
printedSource = 1;
log_error("Build options: %s\n", buildOptions);
log_error("Original source is: ------------\n");
for (i = 0; i < numKernelLines; i++)
log_error("%s", kernelProgram[i]);
}
// Verify the build status on all devices
cl_uint deviceCount = 0;
error = clGetProgramInfo(*outProgram, CL_PROGRAM_NUM_DEVICES, sizeof(deviceCount), &deviceCount, NULL);
if (error != CL_SUCCESS)
{
print_error(error, "clGetProgramInfo CL_PROGRAM_NUM_DEVICES failed");
return error;
}
if (deviceCount == 0)
{
log_error("No devices found for program.\n");
return -1;
}
cl_device_id *devices = (cl_device_id *)malloc(deviceCount * sizeof(cl_device_id));
if (NULL == devices)
return -1;
BufferOwningPtr<cl_device_id> devicesBuf(devices);
memset(devices, 0, deviceCount * sizeof(cl_device_id));
error = clGetProgramInfo(*outProgram, CL_PROGRAM_DEVICES, sizeof(cl_device_id) * deviceCount, devices, NULL);
if (error != CL_SUCCESS)
{
print_error(error, "clGetProgramInfo CL_PROGRAM_DEVICES failed");
return error;
}
cl_uint z;
bool buildFailed = false;
for (z = 0; z < deviceCount; z++)
{
char deviceName[4096] = "";
error = clGetDeviceInfo(devices[z], CL_DEVICE_NAME, sizeof(deviceName), deviceName, NULL);
if (error != CL_SUCCESS || deviceName[0] == '\0')
{
log_error("Device \"%d\" failed to return a name\n", z);
print_error(error, "clGetDeviceInfo CL_DEVICE_NAME failed");
}
cl_build_status buildStatus;
error = clGetProgramBuildInfo(*outProgram, devices[z], CL_PROGRAM_BUILD_STATUS, sizeof(buildStatus), &buildStatus, NULL);
if (error != CL_SUCCESS)
{
print_error(error, "clGetProgramBuildInfo CL_PROGRAM_BUILD_STATUS failed");
return error;
}
if (buildStatus == CL_BUILD_SUCCESS && buildProgramFailed && deviceCount == 1)
{
buildFailed = true;
log_error("clBuildProgram returned an error, but buildStatus is marked as CL_BUILD_SUCCESS.\n");
}
if (buildStatus != CL_BUILD_SUCCESS)
{
char statusString[64] = "";
if (buildStatus == (cl_build_status)CL_BUILD_SUCCESS)
sprintf(statusString, "CL_BUILD_SUCCESS");
else if (buildStatus == (cl_build_status)CL_BUILD_NONE)
sprintf(statusString, "CL_BUILD_NONE");
else if (buildStatus == (cl_build_status)CL_BUILD_ERROR)
sprintf(statusString, "CL_BUILD_ERROR");
else if (buildStatus == (cl_build_status)CL_BUILD_IN_PROGRESS)
sprintf(statusString, "CL_BUILD_IN_PROGRESS");
else
sprintf(statusString, "UNKNOWN (%d)", buildStatus);
if (buildStatus != CL_BUILD_SUCCESS)
log_error("Build not successful for device \"%s\", status: %s\n", deviceName, statusString);
size_t paramSize = 0;
error = clGetProgramBuildInfo(*outProgram, devices[z], CL_PROGRAM_BUILD_LOG, 0, NULL, ¶mSize);
if (error != CL_SUCCESS)
{
print_error(error, "clGetProgramBuildInfo CL_PROGRAM_BUILD_LOG failed");
return error;
}
std::string log;
log.resize(paramSize / sizeof(char));
error = clGetProgramBuildInfo(*outProgram, devices[z], CL_PROGRAM_BUILD_LOG, paramSize, &log[0], NULL);
if (error != CL_SUCCESS || log[0] == '\0')
{
log_error("Device %d (%s) failed to return a build log\n", z, deviceName);
if (error)
{
print_error(error, "clGetProgramBuildInfo CL_PROGRAM_BUILD_LOG failed");
return error;
}
else
{
log_error("clGetProgramBuildInfo returned an empty log.\n");
return -1;
}
}
// In this case we've already printed out the code above.
if (!printedSource)
{
unsigned int i;
log_error("Original source is: ------------\n");
for (i = 0; i < numKernelLines; i++)
log_error("%s", kernelProgram[i]);
printedSource = 1;
}
log_error("Build log for device \"%s\" is: ------------\n", deviceName);
log_error("%s\n", log.c_str());
log_error("\n----------\n");
return -1;
}
}
if (buildFailed)
{
return -1;
}
/* And create a kernel from it */
if (kernelName != NULL)
{
*outKernel = clCreateKernel(*outProgram, kernelName, &error);
if (*outKernel == NULL || error != CL_SUCCESS)
{
print_error(error, "Unable to create kernel");
return error;
}
}
return 0;
}
int get_max_allowed_work_group_size( cl_context context, cl_kernel kernel, size_t *outMaxSize, size_t *outLimits )
{
cl_device_id *devices;
size_t size, maxCommonSize = 0;
int numDevices, i, j, error;
cl_uint numDims;
size_t outSize;
size_t sizeLimit[]={1,1,1};
/* Assume fewer than 16 devices will be returned */
error = clGetContextInfo( context, CL_CONTEXT_DEVICES, 0, NULL, &outSize );
test_error( error, "Unable to obtain list of devices size for context" );
devices = (cl_device_id *)malloc(outSize);
BufferOwningPtr<cl_device_id> devicesBuf(devices);
error = clGetContextInfo( context, CL_CONTEXT_DEVICES, outSize, devices, NULL );
test_error( error, "Unable to obtain list of devices for context" );
numDevices = (int)( outSize / sizeof( cl_device_id ) );
for( i = 0; i < numDevices; i++ )
{
error = clGetDeviceInfo( devices[i], CL_DEVICE_MAX_WORK_GROUP_SIZE, sizeof( size ), &size, NULL );
test_error( error, "Unable to obtain max work group size for device" );
if( size < maxCommonSize || maxCommonSize == 0)
maxCommonSize = size;
error = clGetKernelWorkGroupInfo( kernel, devices[i], CL_KERNEL_WORK_GROUP_SIZE, sizeof( size ), &size, NULL );
test_error( error, "Unable to obtain max work group size for device and kernel combo" );
if( size < maxCommonSize || maxCommonSize == 0)
maxCommonSize = size;
error= clGetDeviceInfo( devices[i], CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof( numDims ), &numDims, NULL);
test_error( error, "clGetDeviceInfo failed for CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS");
sizeLimit[0] = 1;
error= clGetDeviceInfo( devices[i], CL_DEVICE_MAX_WORK_ITEM_SIZES, numDims*sizeof(size_t), sizeLimit, NULL);
test_error( error, "clGetDeviceInfo failed for CL_DEVICE_MAX_WORK_ITEM_SIZES");
if (outLimits != NULL)
{
if (i == 0) {
for (j=0; j<3; j++)
outLimits[j] = sizeLimit[j];
} else {
for (j=0; j<(int)numDims; j++) {
if (sizeLimit[j] < outLimits[j])
outLimits[j] = sizeLimit[j];
}
}
}
}
*outMaxSize = (unsigned int)maxCommonSize;
return 0;
}
extern int get_max_allowed_1d_work_group_size_on_device( cl_device_id device, cl_kernel kernel, size_t *outSize )
{
cl_uint maxDim;
size_t maxWgSize;
size_t *maxWgSizePerDim;
int error;
error = clGetKernelWorkGroupInfo( kernel, device, CL_KERNEL_WORK_GROUP_SIZE, sizeof( size_t ), &maxWgSize, NULL );
test_error( error, "clGetKernelWorkGroupInfo CL_KERNEL_WORK_GROUP_SIZE failed" );
error = clGetDeviceInfo( device, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS, sizeof( cl_uint ), &maxDim, NULL );
test_error( error, "clGetDeviceInfo CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS failed" );
maxWgSizePerDim = (size_t*)malloc( maxDim * sizeof( size_t ) );
if( !maxWgSizePerDim )
{
log_error( "Unable to allocate maxWgSizePerDim\n" );
return -1;
}
error = clGetDeviceInfo( device, CL_DEVICE_MAX_WORK_ITEM_SIZES, maxDim * sizeof( size_t ), maxWgSizePerDim, NULL );
if( error != CL_SUCCESS)
{
log_error( "clGetDeviceInfo CL_DEVICE_MAX_WORK_ITEM_SIZES failed\n" );
free( maxWgSizePerDim );
return error;
}
// "maxWgSize" is limited to that of the first dimension.
if( maxWgSize > maxWgSizePerDim[0] )
{
maxWgSize = maxWgSizePerDim[0];
}
free( maxWgSizePerDim );
*outSize = maxWgSize;
return 0;
}
int get_max_common_work_group_size( cl_context context, cl_kernel kernel,
size_t globalThreadSize, size_t *outMaxSize )
{
size_t sizeLimit[3];
int error = get_max_allowed_work_group_size( context, kernel, outMaxSize, sizeLimit );
if( error != 0 )
return error;
/* Now find the largest factor of globalThreadSize that is <= maxCommonSize */
/* Note for speed, we don't need to check the range of maxCommonSize, b/c once it gets to 1,
the modulo test will succeed and break the loop anyway */
for( ; ( globalThreadSize % *outMaxSize ) != 0 || (*outMaxSize > sizeLimit[0]); (*outMaxSize)-- )
;
return 0;
}
int get_max_common_2D_work_group_size( cl_context context, cl_kernel kernel,
size_t *globalThreadSizes, size_t *outMaxSizes )
{
size_t sizeLimit[3];
size_t maxSize;
int error = get_max_allowed_work_group_size( context, kernel, &maxSize, sizeLimit );
if( error != 0 )
return error;
/* Now find a set of factors, multiplied together less than maxSize, but each a factor of the global
sizes */
/* Simple case */
if( globalThreadSizes[ 0 ] * globalThreadSizes[ 1 ] <= maxSize )
{
if (globalThreadSizes[ 0 ] <= sizeLimit[0] && globalThreadSizes[ 1 ] <= sizeLimit[1]) {
outMaxSizes[ 0 ] = globalThreadSizes[ 0 ];
outMaxSizes[ 1 ] = globalThreadSizes[ 1 ];
return 0;
}
}
size_t remainingSize, sizeForThisOne;
remainingSize = maxSize;
int i, j;
for (i=0 ; i<2; i++) {
if (globalThreadSizes[i] > remainingSize)
sizeForThisOne = remainingSize;
else
sizeForThisOne = globalThreadSizes[i];
for (; (globalThreadSizes[i] % sizeForThisOne) != 0 || (sizeForThisOne > sizeLimit[i]); sizeForThisOne--) ;
outMaxSizes[i] = sizeForThisOne;
remainingSize = maxSize;
for (j=0; j<=i; j++)
remainingSize /=outMaxSizes[j];
}
return 0;
}
int get_max_common_3D_work_group_size( cl_context context, cl_kernel kernel,
size_t *globalThreadSizes, size_t *outMaxSizes )
{
size_t sizeLimit[3];
size_t maxSize;
int error = get_max_allowed_work_group_size( context, kernel, &maxSize, sizeLimit );
if( error != 0 )
return error;
/* Now find a set of factors, multiplied together less than maxSize, but each a factor of the global
sizes */
/* Simple case */
if( globalThreadSizes[ 0 ] * globalThreadSizes[ 1 ] * globalThreadSizes[ 2 ] <= maxSize )
{
if (globalThreadSizes[ 0 ] <= sizeLimit[0] && globalThreadSizes[ 1 ] <= sizeLimit[1] && globalThreadSizes[ 2 ] <= sizeLimit[2]) {
outMaxSizes[ 0 ] = globalThreadSizes[ 0 ];
outMaxSizes[ 1 ] = globalThreadSizes[ 1 ];
outMaxSizes[ 2 ] = globalThreadSizes[ 2 ];
return 0;
}
}
size_t remainingSize, sizeForThisOne;
remainingSize = maxSize;
int i, j;
for (i=0 ; i<3; i++) {
if (globalThreadSizes[i] > remainingSize)
sizeForThisOne = remainingSize;
else
sizeForThisOne = globalThreadSizes[i];
for (; (globalThreadSizes[i] % sizeForThisOne) != 0 || (sizeForThisOne > sizeLimit[i]); sizeForThisOne--) ;
outMaxSizes[i] = sizeForThisOne;
remainingSize = maxSize;
for (j=0; j<=i; j++)
remainingSize /=outMaxSizes[j];
}
return 0;
}
/* Helper to determine if a device supports an image format */
int is_image_format_supported( cl_context context, cl_mem_flags flags, cl_mem_object_type image_type, const cl_image_format *fmt )
{
cl_image_format *list;
cl_uint count = 0;
cl_int err = clGetSupportedImageFormats( context, flags, image_type, 128, NULL, &count );
if( count == 0 )
return 0;
list = (cl_image_format*) malloc( count * sizeof( cl_image_format ) );
if( NULL == list )
{
log_error( "Error: unable to allocate %ld byte buffer for image format list at %s:%d (err = %d)\n", count * sizeof( cl_image_format ), __FILE__, __LINE__, err );
return 0;
}
BufferOwningPtr<cl_image_format> listBuf(list);
cl_int error = clGetSupportedImageFormats( context, flags, image_type, count, list, NULL );
if( error )
{
log_error( "Error: failed to obtain supported image type list at %s:%d (err = %d)\n", __FILE__, __LINE__, err );
return 0;
}
// iterate looking for a match.
cl_uint i;
for( i = 0; i < count; i++ )
{
if( fmt->image_channel_data_type == list[ i ].image_channel_data_type &&
fmt->image_channel_order == list[ i ].image_channel_order )
break;
}
return ( i < count ) ? 1 : 0;
}
size_t get_pixel_bytes( const cl_image_format *fmt );
size_t get_pixel_bytes( const cl_image_format *fmt )
{
size_t chanCount;
switch( fmt->image_channel_order )
{
case CL_R:
case CL_A:
case CL_Rx:
case CL_INTENSITY:
case CL_LUMINANCE:
case CL_DEPTH:
chanCount = 1;
break;
case CL_RG:
case CL_RA:
case CL_RGx:
chanCount = 2;
break;
case CL_RGB:
case CL_RGBx:
case CL_sRGB:
case CL_sRGBx:
chanCount = 3;
break;
case CL_RGBA:
case CL_ARGB:
case CL_BGRA:
case CL_sBGRA:
case CL_sRGBA:
#ifdef CL_1RGB_APPLE
case CL_1RGB_APPLE:
#endif
#ifdef CL_BGR1_APPLE
case CL_BGR1_APPLE:
#endif
chanCount = 4;
break;
default:
log_error("Unknown channel order at %s:%d!\n", __FILE__, __LINE__ );
abort();
break;
}
switch( fmt->image_channel_data_type )
{
case CL_UNORM_SHORT_565:
case CL_UNORM_SHORT_555:
return 2;
case CL_UNORM_INT_101010:
return 4;
case CL_SNORM_INT8:
case CL_UNORM_INT8:
case CL_SIGNED_INT8:
case CL_UNSIGNED_INT8:
return chanCount;
case CL_SNORM_INT16:
case CL_UNORM_INT16:
case CL_HALF_FLOAT:
case CL_SIGNED_INT16:
case CL_UNSIGNED_INT16:
#ifdef CL_SFIXED14_APPLE
case CL_SFIXED14_APPLE:
#endif
return chanCount * 2;
case CL_SIGNED_INT32:
case CL_UNSIGNED_INT32:
case CL_FLOAT:
return chanCount * 4;
default:
log_error("Unknown channel data type at %s:%d!\n", __FILE__, __LINE__ );
abort();
}
return 0;
}
test_status verifyImageSupport( cl_device_id device )
{
int result = checkForImageSupport( device );
if( result == 0 )
{
return TEST_PASS;
}
if( result == CL_IMAGE_FORMAT_NOT_SUPPORTED )
{
log_error( "SKIPPED: Device does not supported images as required by this test!\n" );
return TEST_SKIP;
}
return TEST_FAIL;
}
int checkForImageSupport( cl_device_id device )
{
cl_uint i;
int error;
/* Check the device props to see if images are supported at all first */
error = clGetDeviceInfo( device, CL_DEVICE_IMAGE_SUPPORT, sizeof( i ), &i, NULL );
test_error( error, "Unable to query device for image support" );
if( i == 0 )
{
return CL_IMAGE_FORMAT_NOT_SUPPORTED;
}
/* So our support is good */
return 0;
}
int checkFor3DImageSupport( cl_device_id device )
{
cl_uint i;
int error;
/* Check the device props to see if images are supported at all first */
error = clGetDeviceInfo( device, CL_DEVICE_IMAGE_SUPPORT, sizeof( i ), &i, NULL );
test_error( error, "Unable to query device for image support" );
if( i == 0 )
{
return CL_IMAGE_FORMAT_NOT_SUPPORTED;
}
char profile[128];
error = clGetDeviceInfo( device, CL_DEVICE_PROFILE, sizeof(profile ), profile, NULL );
test_error( error, "Unable to query device for CL_DEVICE_PROFILE" );
if( 0 == strcmp( profile, "EMBEDDED_PROFILE" ) )
{
size_t width = -1L;
size_t height = -1L;
size_t depth = -1L;
error = clGetDeviceInfo( device, CL_DEVICE_IMAGE3D_MAX_WIDTH, sizeof(width), &width, NULL );
test_error( error, "Unable to get CL_DEVICE_IMAGE3D_MAX_WIDTH" );
error = clGetDeviceInfo( device, CL_DEVICE_IMAGE3D_MAX_HEIGHT, sizeof(height), &height, NULL );
test_error( error, "Unable to get CL_DEVICE_IMAGE3D_MAX_HEIGHT" );
error = clGetDeviceInfo( device, CL_DEVICE_IMAGE3D_MAX_DEPTH, sizeof(depth), &depth, NULL );
test_error( error, "Unable to get CL_DEVICE_IMAGE3D_MAX_DEPTH" );
if( 0 == (height | width | depth ))
return CL_IMAGE_FORMAT_NOT_SUPPORTED;
}
/* So our support is good */
return 0;
}
size_t get_min_alignment(cl_context context)
{
static cl_uint align_size = 0;
if( 0 == align_size )
{
cl_device_id * devices;
size_t devices_size = 0;
cl_uint result = 0;
cl_int error;
int i;
error = clGetContextInfo (context,
CL_CONTEXT_DEVICES,
0,
NULL,
&devices_size);
test_error_ret(error, "clGetContextInfo failed", 0);
devices = (cl_device_id*)malloc(devices_size);
if (devices == NULL) {
print_error( error, "malloc failed" );
return 0;
}
error = clGetContextInfo (context,
CL_CONTEXT_DEVICES,
devices_size,
(void*)devices,
NULL);
test_error_ret(error, "clGetContextInfo failed", 0);
for (i = 0; i < (int)(devices_size/sizeof(cl_device_id)); i++)
{
cl_uint alignment = 0;
error = clGetDeviceInfo (devices[i],
CL_DEVICE_MEM_BASE_ADDR_ALIGN,
sizeof(cl_uint),
(void*)&alignment,
NULL);
if (error == CL_SUCCESS)
{
alignment >>= 3; // convert bits to bytes
result = (alignment > result) ? alignment : result;
}
else
print_error( error, "clGetDeviceInfo failed" );
}
align_size = result;
free(devices);
}
return align_size;
}
cl_device_fp_config get_default_rounding_mode( cl_device_id device )
{
char profileStr[128] = "";
cl_device_fp_config single = 0;
int error = clGetDeviceInfo( device, CL_DEVICE_SINGLE_FP_CONFIG, sizeof( single ), &single, NULL );
if( error )
test_error_ret( error, "Unable to get device CL_DEVICE_SINGLE_FP_CONFIG", 0 );
if( single & CL_FP_ROUND_TO_NEAREST )
return CL_FP_ROUND_TO_NEAREST;
if( 0 == (single & CL_FP_ROUND_TO_ZERO) )
test_error_ret( -1, "FAILURE: device must support either CL_DEVICE_SINGLE_FP_CONFIG or CL_FP_ROUND_TO_NEAREST", 0 );
// Make sure we are an embedded device before allowing a pass
if( (error = clGetDeviceInfo( device, CL_DEVICE_PROFILE, sizeof( profileStr ), &profileStr, NULL ) ))
test_error_ret( error, "FAILURE: Unable to get CL_DEVICE_PROFILE", 0 );
if( strcmp( profileStr, "EMBEDDED_PROFILE" ) )
test_error_ret( error, "FAILURE: non-EMBEDDED_PROFILE devices must support CL_FP_ROUND_TO_NEAREST", 0 );
return CL_FP_ROUND_TO_ZERO;
}
int checkDeviceForQueueSupport( cl_device_id device, cl_command_queue_properties prop )
{
cl_command_queue_properties realProps;
cl_int error = clGetDeviceInfo( device, CL_DEVICE_QUEUE_ON_HOST_PROPERTIES, sizeof( realProps ), &realProps, NULL );
test_error_ret( error, "FAILURE: Unable to get device queue properties", 0 );
return ( realProps & prop ) ? 1 : 0;
}
int printDeviceHeader( cl_device_id device )
{
char deviceName[ 512 ], deviceVendor[ 512 ], deviceVersion[ 512 ], cLangVersion[ 512 ];
int error;
error = clGetDeviceInfo( device, CL_DEVICE_NAME, sizeof( deviceName ), deviceName, NULL );
test_error( error, "Unable to get CL_DEVICE_NAME for device" );
error = clGetDeviceInfo( device, CL_DEVICE_VENDOR, sizeof( deviceVendor ), deviceVendor, NULL );
test_error( error, "Unable to get CL_DEVICE_VENDOR for device" );
error = clGetDeviceInfo( device, CL_DEVICE_VERSION, sizeof( deviceVersion ), deviceVersion, NULL );
test_error( error, "Unable to get CL_DEVICE_VERSION for device" );
error = clGetDeviceInfo( device, CL_DEVICE_OPENCL_C_VERSION, sizeof( cLangVersion ), cLangVersion, NULL );
test_error( error, "Unable to get CL_DEVICE_OPENCL_C_VERSION for device" );
log_info("Compute Device Name = %s, Compute Device Vendor = %s, Compute Device Version = %s%s%s\n",
deviceName, deviceVendor, deviceVersion, ( error == CL_SUCCESS ) ? ", CL C Version = " : "",
( error == CL_SUCCESS ) ? cLangVersion : "" );
return CL_SUCCESS;
}
| 37.276821 | 170 | 0.568274 | grey-eminence |
6dbf6c5ee937acbe14cf2df5cab10e8cdf80ce58 | 16,728 | cpp | C++ | PhysX-3.2.4_PC_SDK_Core/Source/PhysXVehicle/src/VehicleUtilTelemetry.cpp | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | null | null | null | PhysX-3.2.4_PC_SDK_Core/Source/PhysXVehicle/src/VehicleUtilTelemetry.cpp | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | null | null | null | PhysX-3.2.4_PC_SDK_Core/Source/PhysXVehicle/src/VehicleUtilTelemetry.cpp | emlowry/AIEFramework | 8f1dd02105237e72cfe303ec4c541eea7debd1f7 | [
"MIT"
] | 3 | 2017-01-04T19:48:57.000Z | 2020-03-24T03:05:27.000Z | // This code contains NVIDIA Confidential Information and is disclosed to you
// under a form of NVIDIA software license agreement provided separately to you.
//
// Notice
// NVIDIA Corporation and its licensors retain all intellectual property and
// proprietary rights in and to this software and related documentation and
// any modifications thereto. Any use, reproduction, disclosure, or
// distribution of this software and related documentation without an express
// license agreement from NVIDIA Corporation is strictly prohibited.
//
// ALL NVIDIA DESIGN SPECIFICATIONS, CODE ARE PROVIDED "AS IS.". NVIDIA MAKES
// NO WARRANTIES, EXPRESSED, IMPLIED, STATUTORY, OR OTHERWISE WITH RESPECT TO
// THE MATERIALS, AND EXPRESSLY DISCLAIMS ALL IMPLIED WARRANTIES OF NONINFRINGEMENT,
// MERCHANTABILITY, AND FITNESS FOR A PARTICULAR PURPOSE.
//
// Information and code furnished is believed to be accurate and reliable.
// However, NVIDIA Corporation assumes no responsibility for the consequences of use of such
// information or for any infringement of patents or other rights of third parties that may
// result from its use. No license is granted by implication or otherwise under any patent
// or patent rights of NVIDIA Corporation. Details are subject to change without notice.
// This code supersedes and replaces all information previously supplied.
// NVIDIA Corporation products are not authorized for use as critical
// components in life support devices or systems without express written approval of
// NVIDIA Corporation.
//
// Copyright (c) 2008-2013 NVIDIA Corporation. All rights reserved.
// Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved.
// Copyright (c) 2001-2004 NovodeX AG. All rights reserved.
#include "PxVehicleUtilTelemetry.h"
#include "PxVehicleSDK.h"
#include "PsFoundation.h"
#include "PsUtilities.h"
#include "stdio.h"
#include "CmPhysXCommon.h"
namespace physx
{
#if PX_DEBUG_VEHICLE_ON
PxVehicleGraphDesc::PxVehicleGraphDesc()
: mPosX(PX_MAX_F32),
mPosY(PX_MAX_F32),
mSizeX(PX_MAX_F32),
mSizeY(PX_MAX_F32),
mBackgroundColor(PxVec3(PX_MAX_F32,PX_MAX_F32,PX_MAX_F32)),
mAlpha(PX_MAX_F32)
{
}
bool PxVehicleGraphDesc::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mPosX != PX_MAX_F32, "PxVehicleGraphDesc.mPosX must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mPosY != PX_MAX_F32, "PxVehicleGraphDesc.mPosY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mSizeX != PX_MAX_F32, "PxVehicleGraphDesc.mSizeX must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mSizeY != PX_MAX_F32, "PxVehicleGraphDesc.mSizeY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mBackgroundColor.x != PX_MAX_F32 && mBackgroundColor.y != PX_MAX_F32 && mBackgroundColor.z != PX_MAX_F32, "PxVehicleGraphDesc.mBackgroundColor must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mAlpha != PX_MAX_F32, "PxVehicleGraphDesc.mAlpha must be initialised", false);
return true;
}
PxVehicleGraphChannelDesc::PxVehicleGraphChannelDesc()
: mMinY(PX_MAX_F32),
mMaxY(PX_MAX_F32),
mMidY(PX_MAX_F32),
mColorLow(PxVec3(PX_MAX_F32,PX_MAX_F32,PX_MAX_F32)),
mColorHigh(PxVec3(PX_MAX_F32,PX_MAX_F32,PX_MAX_F32)),
mTitle(NULL)
{
}
bool PxVehicleGraphChannelDesc::isValid() const
{
PX_CHECK_AND_RETURN_VAL(mMinY != PX_MAX_F32, "PxVehicleGraphChannelDesc.mMinY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mMaxY != PX_MAX_F32, "PxVehicleGraphChannelDesc.mMaxY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mMidY != PX_MAX_F32, "PxVehicleGraphChannelDesc.mMidY must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mColorLow.x != PX_MAX_F32 && mColorLow.y != PX_MAX_F32 && mColorLow.z != PX_MAX_F32, "PxVehicleGraphChannelDesc.mColorLow must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mColorHigh.x != PX_MAX_F32 && mColorHigh.y != PX_MAX_F32 && mColorHigh.z != PX_MAX_F32, "PxVehicleGraphChannelDesc.mColorHigh must be initialised", false);
PX_CHECK_AND_RETURN_VAL(mTitle, "PxVehicleGraphChannelDesc.mTitle must be initialised", false);
return true;
}
PxVehicleGraph::PxVehicleGraph()
{
mBackgroundMinX=0;
mBackgroundMaxX=0;
mBackgroundMinY=0;
mBackgroundMaxY=0;
mSampleTide=0;
mBackgroundColor=PxVec3(255,255,255),
mBackgroundAlpha=1.0f;
for(PxU32 i=0;i<eMAX_NUM_CHANNELS;i++)
{
mChannelMinY[i]=0;
mChannelMaxY[i]=0;
mChannelMidY[i]=0;
mChannelColorLow[i]=PxVec3(0,0,255);
mChannelColorHigh[i]=PxVec3(255,0,0);
memset(mChannelSamples[i], 0, sizeof(PxReal)*eMAX_NUM_SAMPLES);
}
mNumChannels = 0;
PX_COMPILE_TIME_ASSERT((size_t)eMAX_NUM_CHANNELS >= (size_t)eMAX_NUM_ENGINE_CHANNELS && (size_t)eMAX_NUM_CHANNELS >= (size_t)eMAX_NUM_WHEEL_CHANNELS);
}
PxVehicleGraph::~PxVehicleGraph()
{
}
void PxVehicleGraph::setup(const PxVehicleGraphDesc& desc, const eGraphType graphType)
{
mBackgroundMinX = (desc.mPosX - 0.5f*desc.mSizeX);
mBackgroundMaxX = (desc.mPosX + 0.5f*desc.mSizeX);
mBackgroundMinY = (desc.mPosY - 0.5f*desc.mSizeY);
mBackgroundMaxY = (desc.mPosY + 0.5f*desc.mSizeY);
mBackgroundColor=desc.mBackgroundColor;
mBackgroundAlpha=desc.mAlpha;
mNumChannels = (eGRAPH_TYPE_WHEEL==graphType) ? (PxU32)eMAX_NUM_WHEEL_CHANNELS : (PxU32)eMAX_NUM_ENGINE_CHANNELS;
}
void PxVehicleGraph::setChannel(PxVehicleGraphChannelDesc& desc, const PxU32 channel)
{
PX_ASSERT(channel<eMAX_NUM_CHANNELS);
mChannelMinY[channel]=desc.mMinY;
mChannelMaxY[channel]=desc.mMaxY;
mChannelMidY[channel]=desc.mMidY;
PX_CHECK_MSG(mChannelMinY[channel]<=mChannelMidY[channel], "mChannelMinY must be less than or equal to mChannelMidY");
PX_CHECK_MSG(mChannelMidY[channel]<=mChannelMaxY[channel], "mChannelMidY must be less than or equal to mChannelMaxY");
mChannelColorLow[channel]=desc.mColorLow;
mChannelColorHigh[channel]=desc.mColorHigh;
strcpy(mChannelTitle[channel], desc.mTitle);
}
void PxVehicleGraph::clearRecordedChannelData()
{
mSampleTide=0;
for(PxU32 i=0;i<eMAX_NUM_CHANNELS;i++)
{
memset(mChannelSamples[i], 0, sizeof(PxReal)*eMAX_NUM_SAMPLES);
}
}
void PxVehicleGraph::updateTimeSlice(const PxReal* const samples)
{
mSampleTide++;
mSampleTide=mSampleTide%eMAX_NUM_SAMPLES;
for(PxU32 i=0;i<mNumChannels;i++)
{
mChannelSamples[i][mSampleTide]=PxClamp(samples[i],mChannelMinY[i],mChannelMaxY[i]);
}
}
void PxVehicleGraph::computeGraphChannel(const PxU32 channel, PxReal* xy, PxVec3* colors, char* title) const
{
PX_ASSERT(channel<mNumChannels);
const PxReal sizeX=mBackgroundMaxX-mBackgroundMinX;
const PxReal sizeY=mBackgroundMaxY-mBackgroundMinY;
for(PxU32 i=0;i<PxVehicleGraph::eMAX_NUM_SAMPLES;i++)
{
const PxU32 index=(mSampleTide+1+i)%PxVehicleGraph::eMAX_NUM_SAMPLES;
xy[2*i+0]=mBackgroundMinX+sizeX*i/((PxReal)(PxVehicleGraph::eMAX_NUM_SAMPLES));
const PxReal y=(mChannelSamples[channel][index]-mChannelMinY[channel])/(mChannelMaxY[channel]-mChannelMinY[channel]);
xy[2*i+1]=mBackgroundMinY+sizeY*y;
colors[i]=mChannelSamples[channel][index]<mChannelMidY[channel] ? mChannelColorLow[channel] : mChannelColorHigh[channel];
}
strcpy(title,mChannelTitle[channel]);
}
void PxVehicleGraph::setupEngineGraph
(const PxF32 sizeX, const PxF32 sizeY, const PxF32 posX, const PxF32 posY,
const PxVec3& backgoundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow)
{
PxVehicleGraphDesc desc;
desc.mSizeX=sizeX;
desc.mSizeY=sizeY;
desc.mPosX=posX;
desc.mPosY=posY;
desc.mBackgroundColor=backgoundColor;
desc.mAlpha=0.5f;
setup(desc,PxVehicleGraph::eGRAPH_TYPE_ENGINE);
//Engine revs
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=800.0f;
desc2.mMidY=400.0f;
char title[64];
sprintf(title, "engineRevs");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_ENGINE_REVS);
}
//Engine torque
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1000.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "engineDriveTorque");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_ENGINE_DRIVE_TORQUE);
}
//Clutch slip
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-200.0f;
desc2.mMaxY=200.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "clutchSlip");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_CLUTCH_SLIP);
}
//Accel control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "accel");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_ACCEL_CONTROL);
}
//Brake control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "brake/tank brake left");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_BRAKE_CONTROL);
}
//HandBrake control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "handbrake/tank brake right");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_HANDBRAKE_CONTROL);
}
//Steer control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-1.1f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "steerLeft/tank thrust left");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_STEER_LEFT_CONTROL);
}
//Steer control
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-1.1f;
desc2.mMaxY=1.1f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "steerRight/tank thrust right");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_STEER_RIGHT_CONTROL);
}
//Gear
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-4.f;
desc2.mMaxY=20.f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "gearRatio");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_GEAR_RATIO);
}
}
void PxVehicleGraph::setupWheelGraph
(const PxF32 sizeX, const PxF32 sizeY, const PxF32 posX, const PxF32 posY,
const PxVec3& backgoundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow)
{
PxVehicleGraphDesc desc;
desc.mSizeX=sizeX;
desc.mSizeY=sizeY;
desc.mPosX=posX;
desc.mPosY=posY;
desc.mBackgroundColor=backgoundColor;
desc.mAlpha=0.5f;
setup(desc,PxVehicleGraph::eGRAPH_TYPE_WHEEL);
//Jounce data channel
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-0.2f;
desc2.mMaxY=0.4f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "suspJounce");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_JOUNCE);
}
//Jounce susp force channel
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=20000.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "suspForce");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_SUSPFORCE);
}
//Tire load channel.
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=20000.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "tireLoad");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_TIRELOAD);
}
//Normalised tire load channel.
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=3.0f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "normTireLoad");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_NORMALIZED_TIRELOAD);
}
//Wheel omega channel
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-50.0f;
desc2.mMaxY=250.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "wheelOmega");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_WHEEL_OMEGA);
}
//Tire friction
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=1.1f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "friction");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_TIRE_FRICTION);
}
//Tire long slip
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-0.2f;
desc2.mMaxY=0.2f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "tireLongSlip");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_TIRE_LONG_SLIP);
}
//Normalised tire long force
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=2.0f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "normTireLongForce");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_NORM_TIRE_LONG_FORCE);
}
//Tire lat slip
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=-1.0f;
desc2.mMaxY=1.0f;
desc2.mMidY=0.0f;
char title[64];
sprintf(title, "tireLatSlip");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_TIRE_LAT_SLIP);
}
//Normalised tire lat force
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=2.0f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "normTireLatForce");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_NORM_TIRE_LAT_FORCE);
}
//Normalized aligning moment
{
PxVehicleGraphChannelDesc desc2;
desc2.mColorHigh=lineColorHigh;
desc2.mColorLow=lineColorLow;
desc2.mMinY=0.0f;
desc2.mMaxY=2.0f;
desc2.mMidY=1.0f;
char title[64];
sprintf(title, "normTireAlignMoment");
desc2.mTitle=title;
setChannel(desc2,PxVehicleGraph::eCHANNEL_NORM_TIRE_ALIGNING_MOMENT);
}
}
PxVehicleTelemetryData* physx::PxVehicleTelemetryData::allocate(const PxU32 numWheels)
{
//Work out the byte size required.
PxU32 size = sizeof(PxVehicleTelemetryData);
size += sizeof(PxVehicleGraph); //engine graph
size += sizeof(PxVehicleGraph)*numWheels; //wheel graphs
size += sizeof(PxVec3)*numWheels; //tire force app points
size += sizeof(PxVec3)*numWheels; //susp force app points
//Allocate the memory.
PxVehicleTelemetryData* vehTelData=(PxVehicleTelemetryData*)PX_ALLOC(size, PX_DEBUG_EXP("PxVehicleNWTelemetryData"));
//Patch up the pointers.
PxU8* ptr = (PxU8*)vehTelData + sizeof(PxVehicleTelemetryData);
vehTelData->mEngineGraph = (PxVehicleGraph*)ptr;
ptr += sizeof(PxVehicleGraph);
vehTelData->mWheelGraphs = (PxVehicleGraph*)ptr;
ptr += sizeof(PxVehicleGraph)*numWheels;
vehTelData->mSuspforceAppPoints = (PxVec3*)ptr;
ptr += sizeof(PxVec3)*numWheels;
vehTelData->mTireforceAppPoints = (PxVec3*)ptr;
ptr += sizeof(PxVec3)*numWheels;
//Set the number of wheels in each structure that needs it.
vehTelData->mNumActiveWheels=numWheels;
//Finished.
return vehTelData;
}
void PxVehicleTelemetryData::free()
{
PX_FREE(this);
}
void physx::PxVehicleTelemetryData::setup
(const PxF32 graphSizeX, const PxF32 graphSizeY,
const PxF32 engineGraphPosX, const PxF32 engineGraphPosY,
const PxF32* const wheelGraphPosX, const PxF32* const wheelGraphPosY,
const PxVec3& backgroundColor, const PxVec3& lineColorHigh, const PxVec3& lineColorLow)
{
mEngineGraph->setupEngineGraph
(graphSizeX, graphSizeY, engineGraphPosX, engineGraphPosY,
backgroundColor, lineColorHigh, lineColorLow);
const PxU32 numActiveWheels=mNumActiveWheels;
for(PxU32 k=0;k<numActiveWheels;k++)
{
mWheelGraphs[k].setupWheelGraph
(graphSizeX, graphSizeY, wheelGraphPosX[k], wheelGraphPosY[k],
backgroundColor, lineColorHigh, lineColorLow);
mTireforceAppPoints[k]=PxVec3(0,0,0);
mSuspforceAppPoints[k]=PxVec3(0,0,0);
}
}
void physx::PxVehicleTelemetryData::clear()
{
mEngineGraph->clearRecordedChannelData();
const PxU32 numActiveWheels=mNumActiveWheels;
for(PxU32 k=0;k<numActiveWheels;k++)
{
mWheelGraphs[k].clearRecordedChannelData();
mTireforceAppPoints[k]=PxVec3(0,0,0);
mSuspforceAppPoints[k]=PxVec3(0,0,0);
}
}
#endif //PX_DEBUG_VEHICLE_ON
} //physx
| 29.712256 | 197 | 0.768472 | emlowry |
6dc1a8199499ee8c92a8148cb62899af2b4c3cbc | 12,963 | cpp | C++ | src/alns/PALNS-CVRP/Route.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | src/alns/PALNS-CVRP/Route.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | src/alns/PALNS-CVRP/Route.cpp | alberto-santini/cvrp-decomposition | 854d2b5b7cdd51fe4ab46acac7d88dbc7e5bfb88 | [
"MIT"
] | null | null | null | // @@@ Notice! the savings algorithm assumes symmetric costs!
#include "Route.h"
// From SRP-Utils
#include "Utils.h"
#include "VectorUtils.h"
Route::Route(const CVRPInstance& instance) : m_pInstance(&instance), m_pMatDists(&(instance.getDists())) {
int iN = instance.getN();
m_vecRoute.push_back(0);
m_vecRoute.push_back(iN + 1);
m_iLoad = 0;
m_dCost = m_pMatDists->getElement(0, iN + 1);
m_dDuration = m_pMatDists->getElement(0, iN + 1);
m_dToleranceEps = 1E-7;
}
/***********************************************************************
* bool Route::removeCustomer(int iPos)
*
* remove the customer at position <iPos>
*
* --- input parameters ---
* iPos : The position of the customer to remove
* iPos = 0 is invalid (position 0 is occupied by the depot).
* --- output parameters ---
* --- return value ---
***********************************************************************/
void Route::removeCustomer(int iPos) {
#ifdef _DEBUG
if(iPos <= 0 || iPos >= (int)m_vecRoute.size() - 1)
error("Route::removeCustomer(...)", "remove position out of range ");
#endif
int iCustId = m_vecRoute[iPos];
double inc = m_pMatDists->getElement(m_vecRoute[iPos - 1], m_vecRoute[iPos + 1]) - m_pMatDists->getElement(m_vecRoute[iPos - 1], iCustId) -
m_pMatDists->getElement(iCustId, m_vecRoute[iPos + 1]);
m_dCost += inc;
m_iLoad -= m_pInstance->getDemand(iCustId);
m_dDuration += inc;
m_dDuration -= m_pInstance->getServiceTime(iCustId);
m_vecRoute.erase(m_vecRoute.begin() + iPos);
}
// Go through the route and removes customers if vecIsCustRemoved[id] == true
// where <id> is the id of the customer. The method returns the number of customers removed.
void Route::removeCustomers(const vector<bool>& vecIsCustRemoved, vector<int>& vecRemovedCusts) {
vecRemovedCusts.clear();
assert((int)vecIsCustRemoved.size() >= (m_pInstance->getN() + 1));
vector<int> vecNewRoute(m_vecRoute.size());
vecNewRoute[0] = 0;
int iOrigIdx, iNewIdx = 1;
// Don't look at the last element in the route (it's the end depot).
int iOrigLastIdx = (int)m_vecRoute.size() - 1;
// dDelta : change in distance.
double dDelta = 0;
int iServTimeDelta = 0;
for(iOrigIdx = 1; iOrigIdx < iOrigLastIdx; ++iOrigIdx) {
// If the customer at position <iOrigIdx> hasn't been removed, then
// copy it to the new route.
if(!vecIsCustRemoved[m_vecRoute[iOrigIdx]]) {
vecNewRoute[iNewIdx] = m_vecRoute[iOrigIdx];
++iNewIdx;
} else {
// Customer is removed. Update delta and load.
int iCustId = m_vecRoute[iOrigIdx];
dDelta += m_pMatDists->getElement(vecNewRoute[iNewIdx - 1], m_vecRoute[iOrigIdx + 1]) - m_pMatDists->getElement(vecNewRoute[iNewIdx - 1], iCustId) -
m_pMatDists->getElement(iCustId, m_vecRoute[iOrigIdx + 1]);
m_iLoad -= m_pInstance->getDemand(iCustId);
iServTimeDelta -= m_pInstance->getServiceTime(iCustId);
vecRemovedCusts.push_back(iCustId);
}
}
m_dCost += dDelta;
m_dDuration += dDelta + iServTimeDelta;
vecNewRoute[iNewIdx] = m_pInstance->getN() + 1;
++iNewIdx;
// Shrink the new vector.
vecNewRoute.resize(iNewIdx);
m_vecRoute.swap(vecNewRoute);
}
void Route::removeSequence(int iStartPos, int iNToRemove) {
double dDeltaDist = 0;
int iServTimeDelta = 0;
int iDeltaLoad = 0;
int i;
for(i = 0; i < iNToRemove; ++i) {
int iPos = iStartPos + i;
dDeltaDist -= m_pMatDists->getElement(m_vecRoute[iPos - 1], m_vecRoute[iPos]);
iServTimeDelta -= m_pInstance->getServiceTime(m_vecRoute[iPos]);
iDeltaLoad -= m_pInstance->getDemand(m_vecRoute[iPos]);
}
dDeltaDist -= m_pMatDists->getElement(m_vecRoute[iStartPos + iNToRemove - 1], m_vecRoute[iStartPos + iNToRemove]);
dDeltaDist += m_pMatDists->getElement(m_vecRoute[iStartPos - 1], m_vecRoute[iStartPos + iNToRemove]);
m_dCost += dDeltaDist;
m_iLoad += iDeltaLoad;
m_dDuration += dDeltaDist + iServTimeDelta;
m_vecRoute.erase(m_vecRoute.begin() + iStartPos, m_vecRoute.begin() + (iStartPos + iNToRemove));
}
void Route::concatRoute(const Route& otherRoute) {
// cout << "concatRoute" << endl;
int iN = m_pInstance->getN();
double saving = m_pMatDists->getElement(getLastCustomer(), otherRoute.getFirstCustomer()) - m_pMatDists->getElement(getLastCustomer(), iN + 1) -
m_pMatDists->getElement(0, otherRoute.getFirstCustomer());
m_dCost += otherRoute.getCost() + saving;
m_iLoad += otherRoute.getLoad();
m_dDuration += otherRoute.getDuration() + saving;
m_vecRoute.insert(m_vecRoute.begin() + size() - 1, otherRoute.m_vecRoute.begin() + 1, otherRoute.m_vecRoute.begin() + otherRoute.size() - 1);
}
// concatenate <otherRoute> to this route, inversing the order of <otherRoute>
void Route::concatRouteInv(const Route& otherRoute) {
// cout << "concatRouteInv" << endl;
int iN = m_pInstance->getN();
double saving = m_pMatDists->getElement(getLastCustomer(), otherRoute.getLastCustomer()) - m_pMatDists->getElement(getLastCustomer(), iN + 1) -
m_pMatDists->getElement(otherRoute.getLastCustomer(), iN + 1);
m_dCost += otherRoute.getCost() + saving;
m_iLoad += otherRoute.getLoad();
m_dDuration += otherRoute.getDuration() + saving;
int i;
m_vecRoute.pop_back();
for(i = otherRoute.size() - 2; i > 0; i--)
m_vecRoute.push_back(otherRoute.getNodeId(i));
m_vecRoute.push_back(iN + 1);
}
// concatenate <otherRoute> to this route, inversing the order of <this> route
void Route::concatRouteInvThis(const Route& otherRoute) {
// cout << "concatRouteInvThis" << endl;
int iN = m_pInstance->getN();
double saving = m_pMatDists->getElement(getFirstCustomer(), otherRoute.getFirstCustomer()) - m_pMatDists->getElement(0, getFirstCustomer()) -
m_pMatDists->getElement(0, otherRoute.getFirstCustomer());
m_dCost += otherRoute.getCost() + saving;
m_iLoad += otherRoute.getLoad();
m_dDuration += otherRoute.getDuration() + saving;
reverse(m_vecRoute.begin(), m_vecRoute.end());
// Now the first node on m_vecRoute is n+1 and the last node is 0. Correct this:
m_vecRoute.front() = 0;
m_vecRoute.back() = iN + 1;
m_vecRoute.insert(m_vecRoute.begin() + size() - 1, otherRoute.m_vecRoute.begin() + 1, otherRoute.m_vecRoute.begin() + otherRoute.size() - 1);
}
void Route::consCalc() {
int iPos, iNodeId;
int iMaxPos = (int)m_vecRoute.size();
assert(iMaxPos >= 2);
double dDist = 0;
int iServTime = 0;
int iLoad = 0;
for(iPos = 1; iPos < iMaxPos; iPos++) {
iNodeId = m_vecRoute[iPos];
dDist += m_pMatDists->getElement(m_vecRoute[iPos - 1], iNodeId);
iServTime += m_pInstance->getServiceTime(iNodeId);
iLoad += m_pInstance->getDemand(iNodeId);
}
if(iLoad > m_pInstance->getMaxLoad()) {
assert(false);
error("Route::consCalc()", "Load is violated");
}
if(dDist + iServTime > m_pInstance->getMaxDuration())
error("Route::consCalc()", "Duration is violated");
if(iLoad != m_iLoad)
error("Route::consCalc()", "Calculated (" + int2String(iLoad) + ") and stored load (" + int2String(m_iLoad) + ") mismatch!");
if(fabs(dDist - m_dCost) > m_dToleranceEps) {
assert(false);
error("Route::consCalc()", "Calculated and stored cost mismatch!");
}
if(fabs(dDist + iServTime - m_dDuration) > m_dToleranceEps)
error("Route::consCalc()", "Calculated and stored duration mismatch!");
// Use the calculated distance. It is most precise (it's the result of the fewest number
// of calculations).
m_dCost = dDist;
m_dDuration = dDist + iServTime;
}
// Perform two opt local search on the route. Return true iff the route was improved.
// The method only works for symmetric distances.
bool Route::twoOpt(double dImproveEps) {
#ifndef BATCH_MODE
consCalc();
#endif
int i, j, iBestI, iBestJ;
int iRouteLength = (int)m_vecRoute.size();
bool bImproved = false;
bool bImprovedThisIter;
do {
bImprovedThisIter = false;
double dBestDelta = DBL_MAX;
// i indexes the first edge to remove. We are removing the edge (m_vecRoute[i-1], m_vecRoute[i]), that is
// the edge between the (i-1)'th and i'th node in the tour. As the last node in the tour is node
// iRouteLength-1 and there has to be one edge between the two edges removed the last edge in the tour that
// can be the "first edge" is the joining the (iRouteLength-4)'th and (iRouteLength-3)'th nodes as the
// second edge will joing ((iRouteLength-2)'th and (iRouteLength-1)'th
for(i = 1; i <= iRouteLength - 3; i++) {
// i indexes the second edge to remove. We are removing the edge between the (j-1)'th and j'th node in the tour.
for(j = i + 2; j <= iRouteLength - 1; j++) {
double dDelta = -m_pMatDists->getElement(m_vecRoute[i - 1], m_vecRoute[i]) - m_pMatDists->getElement(m_vecRoute[j - 1], m_vecRoute[j]) +
m_pMatDists->getElement(m_vecRoute[i - 1], m_vecRoute[j - 1]) + m_pMatDists->getElement(m_vecRoute[i], m_vecRoute[j]);
// DISTANCE MATRIX NOT SYMMETRIC => NEED THIS:
for(auto k = i; k < j - 1; ++k) {
dDelta -= m_pMatDists->getElement(m_vecRoute[k], m_vecRoute[k + 1]);
dDelta += m_pMatDists->getElement(m_vecRoute[k + 1], m_vecRoute[k]);
}
if(dDelta < dBestDelta) {
dBestDelta = dDelta;
iBestI = i;
iBestJ = j;
}
}
}
if(dBestDelta < -dImproveEps) {
#ifndef BATCH_MODE
consCalc();
#endif
bImproved = true;
bImprovedThisIter = true;
do2optMove(iBestI, iBestJ);
#ifndef BATCH_MODE
consCalc();
#endif
}
} while(bImprovedThisIter);
return bImproved;
}
void Route::do2optMove(int i, int j) {
assert(i < j);
double dDelta = -m_pMatDists->getElement(m_vecRoute[i - 1], m_vecRoute[i]) - m_pMatDists->getElement(m_vecRoute[j - 1], m_vecRoute[j]) +
m_pMatDists->getElement(m_vecRoute[i - 1], m_vecRoute[j - 1]) + m_pMatDists->getElement(m_vecRoute[i], m_vecRoute[j]);
// DISTANCE MATRIX NOT SYMMETRIC => NEED THIS:
for(auto k = i; k < j - 1; ++k) {
dDelta -= m_pMatDists->getElement(m_vecRoute[k], m_vecRoute[k + 1]);
dDelta += m_pMatDists->getElement(m_vecRoute[k + 1], m_vecRoute[k]);
}
m_dCost += dDelta;
m_dDuration += dDelta;
// Update the route. All that the 2 opt move does is reversing the segment
// (r[i], r[i+1], ... r[j-1]) where r[i] is the node at position i in the route.
reverse(m_vecRoute.begin() + i, m_vecRoute.begin() + j);
}
// Set the nodes of this route to be the nodes of <vecNodes>
void Route::setNodes(const vector<int>& vecNodes) {
assert(vecNodes.size() >= 2);
assert(vecNodes.front() == 0);
assert(vecNodes.back() == m_pInstance->getN() + 1);
m_vecRoute.assign(vecNodes.begin(), vecNodes.end());
int iPos, iNodeId;
int iMaxPos = (int)m_vecRoute.size();
double dDist = 0;
int iServTime = 0;
m_iLoad = 0;
for(iPos = 1; iPos < iMaxPos; iPos++) {
iNodeId = m_vecRoute[iPos];
dDist += m_pMatDists->getElement(m_vecRoute[iPos - 1], iNodeId);
iServTime += m_pInstance->getServiceTime(iNodeId);
m_iLoad += m_pInstance->getDemand(iNodeId);
}
m_dCost = dDist;
m_dDuration = dDist + iServTime;
}
// Set the customers of this route to be those of <vecCustomers>
// (the method is similar to <setNodes(...)>, but in the method below <vecCustomers> should not contain the start and end depot).
void Route::setCustomers(const vector<int>& vecCustomers) {
assert(vecCustomers.front() != 0);
assert(vecCustomers.back() != m_pInstance->getN() + 1);
m_vecRoute.clear();
m_vecRoute.push_back(0);
m_vecRoute.insert(m_vecRoute.end(), vecCustomers.begin(), vecCustomers.end());
m_vecRoute.push_back(m_pInstance->getN() + 1);
consCalc();
}
ostream& operator<<(ostream& os, const Route& route) {
os << "{ ";
outputVector(os, route.m_vecRoute);
os << " }, cost: " << route.getCost() << ", load: " << route.getLoad() << ", duration: " << route.getDuration();
return os;
}
| 41.816129 | 161 | 0.615598 | alberto-santini |
6dc3373eeb34c612a0dee9fdc4fdfaba467f453a | 15,190 | cpp | C++ | level_zero/tools/test/unit_tests/sources/sysman/frequency/linux/test_zes_frequency.cpp | Acidburn0zzz/compute-runtime | 79ba0ff1f963c80aec47384728d3733995a0e09c | [
"MIT"
] | 1 | 2020-09-03T17:10:38.000Z | 2020-09-03T17:10:38.000Z | level_zero/tools/test/unit_tests/sources/sysman/frequency/linux/test_zes_frequency.cpp | Acidburn0zzz/compute-runtime | 79ba0ff1f963c80aec47384728d3733995a0e09c | [
"MIT"
] | null | null | null | level_zero/tools/test/unit_tests/sources/sysman/frequency/linux/test_zes_frequency.cpp | Acidburn0zzz/compute-runtime | 79ba0ff1f963c80aec47384728d3733995a0e09c | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "level_zero/tools/test/unit_tests/sources/sysman/linux/mock_sysman_fixture.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "mock_sysfs_frequency.h"
#include <cmath>
using ::testing::Invoke;
namespace L0 {
namespace ult {
constexpr double minFreq = 300.0;
constexpr double maxFreq = 1100.0;
constexpr double step = 100.0 / 6;
constexpr double request = 300.0;
constexpr double tdp = 1100.0;
constexpr double actual = 300.0;
constexpr double efficient = 300.0;
constexpr double maxVal = 1100.0;
constexpr double minVal = 300.0;
constexpr uint32_t numClocks = static_cast<uint32_t>((maxFreq - minFreq) / step) + 1;
constexpr uint32_t handleComponentCount = 1u;
class SysmanDeviceFrequencyFixture : public SysmanDeviceFixture {
protected:
std::unique_ptr<Mock<FrequencySysfsAccess>> pSysfsAccess;
SysfsAccess *pSysfsAccessOld = nullptr;
void SetUp() override {
SysmanDeviceFixture::SetUp();
pSysfsAccessOld = pLinuxSysmanImp->pSysfsAccess;
pSysfsAccess = std::make_unique<NiceMock<Mock<FrequencySysfsAccess>>>();
pLinuxSysmanImp->pSysfsAccess = pSysfsAccess.get();
pSysfsAccess->setVal(minFreqFile, minFreq);
pSysfsAccess->setVal(maxFreqFile, maxFreq);
pSysfsAccess->setVal(requestFreqFile, request);
pSysfsAccess->setVal(tdpFreqFile, tdp);
pSysfsAccess->setVal(actualFreqFile, actual);
pSysfsAccess->setVal(efficientFreqFile, efficient);
pSysfsAccess->setVal(maxValFreqFile, maxVal);
pSysfsAccess->setVal(minValFreqFile, minVal);
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::getVal));
ON_CALL(*pSysfsAccess.get(), write(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::setVal));
// delete handles created in initial SysmanDeviceHandleContext::init() call
for (auto handle : pSysmanDeviceImp->pFrequencyHandleContext->handleList) {
delete handle;
}
pSysmanDeviceImp->pFrequencyHandleContext->handleList.clear();
pSysmanDeviceImp->pFrequencyHandleContext->init();
}
void TearDown() override {
SysmanDeviceFixture::TearDown();
pLinuxSysmanImp->pSysfsAccess = pSysfsAccessOld;
}
double clockValue(const double calculatedClock) {
// i915 specific. frequency step is a fraction
// However, the i915 represents all clock
// rates as integer values. So clocks are
// rounded to the nearest integer.
uint32_t actualClock = static_cast<uint32_t>(calculatedClock + 0.5);
return static_cast<double>(actualClock);
}
std::vector<zes_freq_handle_t> get_freq_handles(uint32_t count) {
std::vector<zes_freq_handle_t> handles(count, nullptr);
EXPECT_EQ(zesDeviceEnumFrequencyDomains(device->toHandle(), &count, handles.data()), ZE_RESULT_SUCCESS);
return handles;
}
};
TEST_F(SysmanDeviceFrequencyFixture, GivenComponentCountZeroWhenEnumeratingFrequencyHandlesThenNonZeroCountIsReturnedAndCallSucceds) {
uint32_t count = 0U;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesDeviceEnumFrequencyDomains(device->toHandle(), &count, nullptr));
EXPECT_EQ(count, handleComponentCount);
uint32_t testCount = count + 1;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesDeviceEnumFrequencyDomains(device->toHandle(), &testCount, nullptr));
EXPECT_EQ(count, testCount);
auto handles = get_freq_handles(count);
for (auto handle : handles) {
EXPECT_NE(handle, nullptr);
}
}
TEST_F(SysmanDeviceFrequencyFixture, GivenComponentCountZeroAndValidPtrWhenEnumeratingFrequencyHandlesThenNonZeroCountAndNoHandlesAreReturnedAndCallSucceds) {
uint32_t count = 0U;
zes_freq_handle_t handle = static_cast<zes_freq_handle_t>(0UL);
EXPECT_EQ(ZE_RESULT_SUCCESS, zesDeviceEnumFrequencyDomains(device->toHandle(), &count, &handle));
EXPECT_EQ(count, handleComponentCount);
EXPECT_EQ(handle, static_cast<zes_freq_handle_t>(0UL));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenActualComponentCountTwoWhenTryingToGetOneComponentOnlyThenOneComponentIsReturnedAndCountUpdated) {
auto pFrequencyHandleContextTest = std::make_unique<FrequencyHandleContext>(pOsSysman);
pFrequencyHandleContextTest->handleList.push_back(new FrequencyImp(pOsSysman));
pFrequencyHandleContextTest->handleList.push_back(new FrequencyImp(pOsSysman));
uint32_t count = 1;
std::vector<zes_freq_handle_t> phFrequency(count, nullptr);
EXPECT_EQ(ZE_RESULT_SUCCESS, pFrequencyHandleContextTest->frequencyGet(&count, phFrequency.data()));
EXPECT_EQ(count, 1u);
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyHandleWhenCallingzesFrequencyGetPropertiesThenSuccessIsReturned) {
auto handles = get_freq_handles(handleComponentCount);
for (auto handle : handles) {
EXPECT_NE(handle, nullptr);
zes_freq_properties_t properties;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencyGetProperties(handle, &properties));
EXPECT_EQ(ZES_STRUCTURE_TYPE_FREQ_PROPERTIES, properties.stype);
EXPECT_EQ(nullptr, properties.pNext);
EXPECT_EQ(ZES_FREQ_DOMAIN_GPU, properties.type);
EXPECT_FALSE(properties.onSubdevice);
EXPECT_DOUBLE_EQ(maxFreq, properties.max);
EXPECT_DOUBLE_EQ(minFreq, properties.min);
EXPECT_TRUE(properties.canControl);
}
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyHandleAndZeroCountWhenCallingzesFrequencyGetAvailableClocksThenCallSucceeds) {
auto handles = get_freq_handles(handleComponentCount);
for (auto handle : handles) {
EXPECT_NE(handle, nullptr);
uint32_t count = 0;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencyGetAvailableClocks(handle, &count, nullptr));
EXPECT_EQ(numClocks, count);
}
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyHandleAndCorrectCountWhenCallingzesFrequencyGetAvailableClocksThenCallSucceeds) {
auto handles = get_freq_handles(handleComponentCount);
for (auto handle : handles) {
uint32_t count = 0;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencyGetAvailableClocks(handle, &count, nullptr));
EXPECT_EQ(numClocks, count);
double *clocks = new double[count];
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencyGetAvailableClocks(handle, &count, clocks));
EXPECT_EQ(numClocks, count);
for (uint32_t i = 0; i < count; i++) {
EXPECT_DOUBLE_EQ(clockValue(minFreq + (step * i)), clocks[i]);
}
delete[] clocks;
}
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidateFrequencyGetRangeWhengetMaxFailsThenFrequencyGetRangeCallShouldFail) {
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::getValReturnError));
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_range_t limit = {};
EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pFrequencyImp->frequencyGetRange(&limit));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyHandleWhenCallingzesFrequencyGetRangeThenVerifyzesFrequencyGetRangeTestCallSucceeds) {
auto handles = get_freq_handles(handleComponentCount);
for (auto handle : handles) {
zes_freq_range_t limits;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencyGetRange(handle, &limits));
EXPECT_DOUBLE_EQ(minFreq, limits.min);
EXPECT_DOUBLE_EQ(maxFreq, limits.max);
}
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyLimitsWhenCallingFrequencySetRangeForFailures1ThenAPIExitsGracefully) {
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_range_t limits = {};
// Verify that Max must be within range.
limits.min = minFreq;
limits.max = 600.0;
ON_CALL(*pSysfsAccess.get(), write(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::setValMinReturnError));
EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pFrequencyImp->frequencySetRange(&limits));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyLimitsWhenCallingFrequencySetRangeForFailures2ThenAPIExitsGracefully) {
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_range_t limits = {};
// Verify that Max must be within range.
limits.min = 900.0;
limits.max = maxFreq;
ON_CALL(*pSysfsAccess.get(), write(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::setValMaxReturnError));
EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pFrequencyImp->frequencySetRange(&limits));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyHandleWhenCallingzesFrequencySetRangeThenVerifyzesFrequencySetRangeTest1CallSucceeds) {
auto handles = get_freq_handles(handleComponentCount);
for (auto handle : handles) {
const double startingMin = 900.0;
const double newMax = 600.0;
zes_freq_range_t limits;
pSysfsAccess->setVal(minFreqFile, startingMin);
// If the new Max value is less than the old Min
// value, the new Min must be set before the new Max
limits.min = minFreq;
limits.max = newMax;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencySetRange(handle, &limits));
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencyGetRange(handle, &limits));
EXPECT_DOUBLE_EQ(minFreq, limits.min);
EXPECT_DOUBLE_EQ(newMax, limits.max);
}
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyHandleWhenCallingzesFrequencySetRangeThenVerifyzesFrequencySetRangeTest2CallSucceeds) {
auto handles = get_freq_handles(handleComponentCount);
for (auto handle : handles) {
const double startingMax = 600.0;
const double newMin = 900.0;
zes_freq_range_t limits;
pSysfsAccess->setVal(maxFreqFile, startingMax);
// If the new Min value is greater than the old Max
// value, the new Max must be set before the new Min
limits.min = newMin;
limits.max = maxFreq;
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencySetRange(handle, &limits));
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencyGetRange(handle, &limits));
EXPECT_DOUBLE_EQ(newMin, limits.min);
EXPECT_DOUBLE_EQ(maxFreq, limits.max);
}
}
TEST_F(SysmanDeviceFrequencyFixture, GivenInvalidFrequencyLimitsWhenCallingFrequencySetRangeThenVerifyFrequencySetRangeTest1ReturnsError) {
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_range_t limits;
// Verify that Max must be within range.
limits.min = minFreq;
limits.max = clockValue(maxFreq + step);
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, pFrequencyImp->frequencySetRange(&limits));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenInvalidFrequencyLimitsWhenCallingFrequencySetRangeThenVerifyFrequencySetRangeTest2ReturnsError) {
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_range_t limits;
// Verify that Min must be within range.
limits.min = clockValue(minFreq - step);
limits.max = maxFreq;
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, pFrequencyImp->frequencySetRange(&limits));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenInvalidFrequencyLimitsWhenCallingFrequencySetRangeThenVerifyFrequencySetRangeTest3ReturnsError) {
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_range_t limits;
// Verify that values must be multiples of step.
limits.min = clockValue(minFreq + (step * 0.5));
limits.max = maxFreq;
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, pFrequencyImp->frequencySetRange(&limits));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenInvalidFrequencyLimitsWhenCallingFrequencySetRangeThenVerifyFrequencySetRangeTest4ReturnsError) {
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_range_t limits;
// Verify that Max must be greater than min range.
limits.min = clockValue(maxFreq + step);
limits.max = minFreq;
EXPECT_EQ(ZE_RESULT_ERROR_INVALID_ARGUMENT, pFrequencyImp->frequencySetRange(&limits));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidFrequencyHandleWhenCallingzesFrequencyGetStateThenVerifyzesFrequencyGetStateTestCallSucceeds) {
auto handles = get_freq_handles(handleComponentCount);
for (auto handle : handles) {
const double testRequestValue = 450.0;
const double testTdpValue = 1200.0;
const double testEfficientValue = 400.0;
const double testActualValue = 550.0;
zes_freq_state_t state;
pSysfsAccess->setVal(requestFreqFile, testRequestValue);
pSysfsAccess->setVal(tdpFreqFile, testTdpValue);
pSysfsAccess->setVal(actualFreqFile, testActualValue);
pSysfsAccess->setVal(efficientFreqFile, testEfficientValue);
EXPECT_EQ(ZE_RESULT_SUCCESS, zesFrequencyGetState(handle, &state));
EXPECT_DOUBLE_EQ(testRequestValue, state.request);
EXPECT_DOUBLE_EQ(testTdpValue, state.tdp);
EXPECT_DOUBLE_EQ(testEfficientValue, state.efficient);
EXPECT_DOUBLE_EQ(testActualValue, state.actual);
EXPECT_EQ(0u, state.throttleReasons);
EXPECT_EQ(nullptr, state.pNext);
EXPECT_EQ(ZES_STRUCTURE_TYPE_FREQ_STATE, state.stype);
EXPECT_LE(state.currentVoltage, 0);
}
}
TEST_F(SysmanDeviceFrequencyFixture, GivenValidStatePointerWhenValidatingfrequencyGetStateForFailuresThenAPIExitsGracefully) {
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_state_t state = {};
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::getValRequestReturnError));
EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pFrequencyImp->frequencyGetState(&state));
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::getValTdpReturnError));
EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pFrequencyImp->frequencyGetState(&state));
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::getValEfficientReturnError));
EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pFrequencyImp->frequencyGetState(&state));
ON_CALL(*pSysfsAccess.get(), read(_, _))
.WillByDefault(::testing::Invoke(pSysfsAccess.get(), &Mock<FrequencySysfsAccess>::getValActualReturnError));
EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pFrequencyImp->frequencyGetState(&state));
}
TEST_F(SysmanDeviceFrequencyFixture, GivenThrottleTimeStructPointerWhenCallingfrequencyGetThrottleTimeThenUnsupportedIsReturned) {
auto pFrequencyImp = std::make_unique<FrequencyImp>(pOsSysman);
zes_freq_throttle_time_t throttleTime = {};
EXPECT_EQ(ZE_RESULT_ERROR_UNSUPPORTED_FEATURE, pFrequencyImp->frequencyGetThrottleTime(&throttleTime));
}
} // namespace ult
} // namespace L0
| 44.80826 | 158 | 0.751876 | Acidburn0zzz |
6dc4aef7f7b2ee6ba5efc22d2683853ade1ebc0b | 3,411 | hpp | C++ | include/utils/for_each.hpp | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 65 | 2020-12-07T01:15:41.000Z | 2022-03-28T01:17:33.000Z | include/utils/for_each.hpp | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 1 | 2021-04-08T13:20:39.000Z | 2021-04-09T00:37:02.000Z | include/utils/for_each.hpp | fengwang/ceras | 15d10e8909ded656f45201aecc45b8eefe961b2d | [
"BSD-3-Clause"
] | 7 | 2021-01-07T08:52:39.000Z | 2022-03-08T13:04:37.000Z | #ifndef FOR_EACH_HPP_INCLUDED_DSPOJSADLK111111111111111111111983UY4KAJSLFLKJFDIF
#define FOR_EACH_HPP_INCLUDED_DSPOJSADLK111111111111111111111983UY4KAJSLFLKJFDIF
#include "../includes.hpp"
#include "./range.hpp"
#include "./parallel.hpp"
namespace ceras
{
namespace// anonymous namespace
{
template < std::size_t Index, typename Type, typename... Types >
struct extract_type_forward
{
typedef typename extract_type_forward < Index - 1, Types... >::result_type result_type;
};
template < typename Type, typename... Types >
struct extract_type_forward< 1, Type, Types... >
{
typedef Type result_type;
};
template < typename Type, typename... Types >
struct extract_type_forward< 0, Type, Types... >
{
struct index_parameter_for_extract_type_forwrod_should_not_be_0;
typedef index_parameter_for_extract_type_forwrod_should_not_be_0 result_type;
};
template < std::size_t Index, typename... Types >
struct extract_type_backward
{
typedef typename extract_type_forward <sizeof...( Types ) - Index + 1, Types...>::result_type result_type;
};
template < std::size_t Index, typename... Types >
struct extract_type
{
typedef typename extract_type_forward< Index, Types... >::result_type result_type;
};
template < typename Function, typename InputIterator1, typename... InputIteratorn >
constexpr Function _for_each_n( Function f, std::size_t n, InputIterator1 begin1, InputIteratorn... beginn )
{
//for ( auto idx : range( n ) ) f( *(begin1+idx), *(beginn+idx)... );
auto const& func = [&]( std::uint_least64_t idx )
{
f( *(begin1+idx), *(beginn+idx)... );
};
parallel( func, 0UL, n );
return f;
}
template < typename Function, typename InputIterator1, typename... InputIteratorn >
constexpr Function _for_each( Function f, InputIterator1 begin1, InputIterator1 end1, InputIteratorn... beginn )
{
return _for_each_n( f, std::distance( begin1, end1 ), begin1, beginn... );
}
struct dummy { };
template < typename... Types_N >
struct for_each_impl_with_dummy
{
typedef typename extract_type_backward< 1, Types_N... >::result_type return_type;
template < typename Predict, typename... Types >
constexpr Predict impl( Predict p, dummy, Types... types ) const
{
return _for_each( p, types... );
}
template < typename S, typename... Types >
constexpr return_type impl( S s, Types... types ) const
{
return impl( types..., s );
}
};
}//anonymous namespace
template < typename... Types >
constexpr typename extract_type_backward< 1, Types... >::result_type for_each( Types... types ) // Types are simple enough to pass by value
{
static_assert( sizeof...( types ) > 2, "f::for_each requires at least 3 arguments" );
return for_each_impl_with_dummy< Types... >().impl( types..., dummy{} );
}
}//namespace ceras
#endif//FOR_EACH_HPP_INCLUDED_DSPOJSADLK111111111111111111111983UY4KAJSLFLKJFDIF
| 36.677419 | 143 | 0.61243 | fengwang |
6dc5b8583cf7a282574ac4c5797c9933b8ca818d | 261 | hpp | C++ | core/Exception.hpp | longzuo/SimpleKeyValueDb | ac5ba1184f3ce273ba9a0b1160c091de9902c0f6 | [
"MIT"
] | 1 | 2019-05-25T11:17:21.000Z | 2019-05-25T11:17:21.000Z | core/Exception.hpp | longzuo/SimpleKeyValueDb | ac5ba1184f3ce273ba9a0b1160c091de9902c0f6 | [
"MIT"
] | null | null | null | core/Exception.hpp | longzuo/SimpleKeyValueDb | ac5ba1184f3ce273ba9a0b1160c091de9902c0f6 | [
"MIT"
] | null | null | null | #ifndef SDB_EXCEPTIONS_HPP
#define SDB_EXCEPTIONS_HPP
#include <stdexcept>
namespace SDB {
class SdbException : public std::runtime_error {
public:
explicit SdbException(const std::string& msg) : std::runtime_error(msg) {}
};
} // namespace SDB
#endif | 21.75 | 78 | 0.743295 | longzuo |
6dc7afd1a16cfe3173f8d3880eb3ebec649c7b69 | 246 | hpp | C++ | openbmc_modules/phosphor-pid-control/notimpl/writeonly.hpp | Eyerunmyden/HWMgmt-MegaRAC-OpenEdition | 72b03e9fc6e2a13184f1c57b8045b616db9b0a6d | [
"Apache-2.0",
"MIT"
] | 14 | 2021-11-04T07:47:37.000Z | 2022-03-21T10:10:30.000Z | notimpl/writeonly.hpp | quanta-bmc/phosphor-pid-control | bc5a76b7bcf578e0a7718635279a97d28e39d434 | [
"Apache-2.0"
] | null | null | null | notimpl/writeonly.hpp | quanta-bmc/phosphor-pid-control | bc5a76b7bcf578e0a7718635279a97d28e39d434 | [
"Apache-2.0"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | /* Interface that implements an exception throwing write method. */
#pragma once
#include "interfaces.hpp"
class WriteOnly : public ReadInterface
{
public:
WriteOnly() : ReadInterface()
{
}
ReadReturn read(void) override;
};
| 16.4 | 67 | 0.691057 | Eyerunmyden |
6dcb24e72c474a1f85ff67f1563500db6cb00701 | 2,225 | cpp | C++ | core/warp_solver/RigidSolver.cpp | mihaibujanca/surfelwarp | 3b424f912b2a90412ad781940b071520825c3030 | [
"BSD-3-Clause"
] | null | null | null | core/warp_solver/RigidSolver.cpp | mihaibujanca/surfelwarp | 3b424f912b2a90412ad781940b071520825c3030 | [
"BSD-3-Clause"
] | null | null | null | core/warp_solver/RigidSolver.cpp | mihaibujanca/surfelwarp | 3b424f912b2a90412ad781940b071520825c3030 | [
"BSD-3-Clause"
] | 1 | 2020-07-15T05:54:31.000Z | 2020-07-15T05:54:31.000Z | //
// Created by wei on 5/22/18.
//
#include "common/ConfigParser.h"
#include "core/warp_solver/RigidSolver.h"
#include <Eigen/Eigen>
surfelwarp::RigidSolver::RigidSolver() {
//Init the intrisic for projection
const auto& config = ConfigParser::Instance();
m_project_intrinsic = config.rgb_intrinsic_clip();
m_image_rows = config.clip_image_rows();
m_image_cols = config.clip_image_cols();
//Init the world2camera
m_curr_world2camera = mat34::identity();
//Allocate the buffer
allocateReduceBuffer();
}
surfelwarp::RigidSolver::~RigidSolver() {
}
void surfelwarp::RigidSolver::SetInputMaps(
const surfelwarp::Renderer::SolverMaps &solver_maps,
const surfelwarp::CameraObservation &observation,
const mat34& init_world2camera
) {
m_solver_maps.live_vertex_map = solver_maps.warp_vertex_map;
m_solver_maps.live_normal_map = solver_maps.warp_normal_map;
m_observation.vertex_map = observation.vertex_config_map;
m_observation.normal_map = observation.normal_radius_map;
m_curr_world2camera = init_world2camera;
}
surfelwarp::mat34 surfelwarp::RigidSolver::Solve(int max_iters, cudaStream_t stream) {
//The solver iteration
for(int i = 0; i < max_iters; i++) {
rigidSolveDeviceIteration(stream);
rigidSolveHostIterationSync(stream);
}
//The updated world2camera
return m_curr_world2camera;
}
void surfelwarp::RigidSolver::rigidSolveHostIterationSync(cudaStream_t stream) {
//Sync before using the data
cudaSafeCall(cudaStreamSynchronize(stream));
//Load the hsot array
const auto& host_array = m_reduced_matrix_vector.HostArray();
//Load the data into Eigen
auto shift = 0;
#pragma unroll
for (int i = 0; i < 6; i++) {
for (int j = i; j < 6; j++) {
const float value = host_array[shift++];
JtJ_(i, j) = value;
JtJ_(j, i) = value;
}
}
for (int i = 0; i < 6; i++) {
const float value = host_array[shift++];
JtErr_[i] = value;
}
//Solve it
Eigen::Matrix<float, 6, 1> x = JtJ_.llt().solve(JtErr_).cast<float>();
//Update the se3
const float3 twist_rot = make_float3(x(0), x(1), x(2));
const float3 twist_trans = make_float3(x(3), x(4), x(5));
const mat34 se3_update(twist_rot, twist_trans);
m_curr_world2camera = se3_update * m_curr_world2camera;
} | 26.807229 | 86 | 0.733483 | mihaibujanca |
6dccb0d7047c5a5772619ebf60854152024447fc | 5,499 | cpp | C++ | jni/RTKLIB/app/winapp/strsvr/svroptdlg.cpp | wjw164833/RtkGpsForPad | c9fb10c0bc56cfa473582088dbc673c6da2d31be | [
"BSD-2-Clause"
] | 2 | 2021-11-06T07:23:27.000Z | 2021-11-07T14:29:21.000Z | jni/RTKLIB/app/winapp/strsvr/svroptdlg.cpp | wjw164833/RtkGpsForPad | c9fb10c0bc56cfa473582088dbc673c6da2d31be | [
"BSD-2-Clause"
] | null | null | null | jni/RTKLIB/app/winapp/strsvr/svroptdlg.cpp | wjw164833/RtkGpsForPad | c9fb10c0bc56cfa473582088dbc673c6da2d31be | [
"BSD-2-Clause"
] | 2 | 2021-11-06T01:11:33.000Z | 2021-11-06T07:23:31.000Z | //---------------------------------------------------------------------------
#include <vcl.h>
#include <FileCtrl.hpp>
#pragma hdrstop
#include "rtklib.h"
#include "refdlg.h"
#include "svroptdlg.h"
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TSvrOptDialog *SvrOptDialog;
//---------------------------------------------------------------------------
static double str2dbl(AnsiString str)
{
double val=0.0;
sscanf(str.c_str(),"%lf",&val);
return val;
}
//---------------------------------------------------------------------------
__fastcall TSvrOptDialog::TSvrOptDialog(TComponent* Owner)
: TForm(Owner)
{
}
//---------------------------------------------------------------------------
void __fastcall TSvrOptDialog::FormShow(TObject *Sender)
{
double pos[3];
AnsiString s;
DataTimeout->Text=s.sprintf("%d",SvrOpt[0]);
ConnectInterval->Text=s.sprintf("%d",SvrOpt[1]);
AvePeriodRate->Text=s.sprintf("%d",SvrOpt[2]);
SvrBuffSize->Text=s.sprintf("%d",SvrOpt[3]);
SvrCycle->Text=s.sprintf("%d",SvrOpt[4]);
ProgBarR->Text=s.sprintf("%d",ProgBarRange);
RelayMsg->ItemIndex=RelayBack;
NmeaCycle->Text=s.sprintf("%d",SvrOpt[5]);
FileSwapMarginE->Text=s.sprintf("%d",FileSwapMargin);
if (norm(AntPos,3)>0.0) {
ecef2pos(AntPos,pos);
AntPos1->Text=s.sprintf("%.8f",pos[0]*R2D);
AntPos2->Text=s.sprintf("%.8f",pos[1]*R2D);
AntPos3->Text=s.sprintf("%.3f",pos[2]);
}
else {
AntPos1->Text="0.00000000";
AntPos2->Text="0.00000000";
AntPos3->Text="0.000";
}
TraceLevelS->ItemIndex=TraceLevel;
NmeaReqT->Checked=NmeaReq;
LocalDir->Text=LocalDirectory;
ProxyAddr->Text=ProxyAddress;
StationId->Text=s.sprintf("%d",StaId);
StaInfoSel->Checked=StaSel;
AntInfo->Text=AntType;
RcvInfo->Text=RcvType;
AntOff1->Text=s.sprintf("%.4f",AntOff[0]);
AntOff2->Text=s.sprintf("%.4f",AntOff[1]);
AntOff3->Text=s.sprintf("%.4f",AntOff[2]);
LogFileF->Text=LogFile;
UpdateEnable();
}
//---------------------------------------------------------------------------
void __fastcall TSvrOptDialog::BtnOkClick(TObject *Sender)
{
double pos[3];
SvrOpt[0]=DataTimeout->Text.ToInt();
SvrOpt[1]=ConnectInterval->Text.ToInt();
SvrOpt[2]=AvePeriodRate->Text.ToInt();
SvrOpt[3]=SvrBuffSize->Text.ToInt();
SvrOpt[4]=SvrCycle->Text.ToInt();
SvrOpt[5]=NmeaCycle->Text.ToInt();
ProgBarRange=ProgBarR->Text.ToInt();
FileSwapMargin=FileSwapMarginE->Text.ToInt();
RelayBack=RelayMsg->ItemIndex;
pos[0]=str2dbl(AntPos1->Text)*D2R;
pos[1]=str2dbl(AntPos2->Text)*D2R;
pos[2]=str2dbl(AntPos3->Text);
if (norm(pos,3)>0.0) {
pos2ecef(pos,AntPos);
}
else {
for (int i=0;i<3;i++) AntPos[i]=0.0;
}
TraceLevel=TraceLevelS->ItemIndex;
NmeaReq=NmeaReqT->Checked;
LocalDirectory=LocalDir->Text;
ProxyAddress=ProxyAddr->Text;
StaId=(int)str2dbl(StationId->Text);
StaSel=StaInfoSel->Checked;
AntType=AntInfo->Text;
RcvType=RcvInfo->Text;
AntOff[0]=str2dbl(AntOff1->Text);
AntOff[1]=str2dbl(AntOff2->Text);
AntOff[2]=str2dbl(AntOff3->Text);
LogFile=LogFileF->Text;
}
//---------------------------------------------------------------------------
void __fastcall TSvrOptDialog::BtnPosClick(TObject *Sender)
{
AnsiString s;
RefDialog->RovPos[0]=str2dbl(AntPos1->Text);
RefDialog->RovPos[1]=str2dbl(AntPos2->Text);
RefDialog->RovPos[2]=str2dbl(AntPos3->Text);
RefDialog->BtnLoad->Enabled=true;
RefDialog->StaPosFile=StaPosFile;
RefDialog->Opt=1;
if (RefDialog->ShowModal()!=mrOk) return;
AntPos1->Text=s.sprintf("%.8f",RefDialog->Pos[0]);
AntPos2->Text=s.sprintf("%.8f",RefDialog->Pos[1]);
AntPos3->Text=s.sprintf("%.3f",RefDialog->Pos[2]);
StaPosFile=RefDialog->StaPosFile;
}
//---------------------------------------------------------------------------
void __fastcall TSvrOptDialog::BtnLocalDirClick(TObject *Sender)
{
#ifdef TCPP
AnsiString dir=LocalDir->Text;
if (!SelectDirectory("Local Directory","",dir)) return;
LocalDir->Text=dir;
#else
UnicodeString dir=LocalDir->Text;
TSelectDirExtOpts opt=TSelectDirExtOpts()<<sdNewUI<<sdNewFolder;
if (!SelectDirectory(L"Local Directory",L"",dir,opt)) return;
LocalDir->Text=dir;
#endif
}
//---------------------------------------------------------------------------
void __fastcall TSvrOptDialog::UpdateEnable(void)
{
NmeaCycle->Enabled=NmeaReqT->Checked;
StationId->Enabled=StaInfoSel->Checked;
AntPos1->Enabled=StaInfoSel->Checked||NmeaReqT->Checked;
AntPos2->Enabled=StaInfoSel->Checked||NmeaReqT->Checked;
AntPos3->Enabled=StaInfoSel->Checked||NmeaReqT->Checked;
BtnPos ->Enabled=StaInfoSel->Checked||NmeaReqT->Checked;
AntOff1->Enabled=StaInfoSel->Checked;
AntOff2->Enabled=StaInfoSel->Checked;
AntOff3->Enabled=StaInfoSel->Checked;
AntInfo->Enabled=StaInfoSel->Checked;
RcvInfo->Enabled=StaInfoSel->Checked;
}
//---------------------------------------------------------------------------
void __fastcall TSvrOptDialog::NmeaReqTClick(TObject *Sender)
{
UpdateEnable();
}
//---------------------------------------------------------------------------
void __fastcall TSvrOptDialog::StaInfoSelClick(TObject *Sender)
{
UpdateEnable();
}
//---------------------------------------------------------------------------
void __fastcall TSvrOptDialog::BtnLogFileClick(TObject *Sender)
{
OpenDialog->Title="Log File";
OpenDialog->FileName=LogFileF->Text;
if (!OpenDialog->Execute()) return;
LogFileF->Text=OpenDialog->FileName;
}
//---------------------------------------------------------------------------
| 33.530488 | 77 | 0.595017 | wjw164833 |
6dcd27fd6d1d7b27d44446d5a470885605270609 | 1,561 | cc | C++ | chrome/browser/android/signin/signin_bridge.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | chrome/browser/android/signin/signin_bridge.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/android/signin/signin_bridge.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/android/signin/signin_bridge.h"
#include "base/android/jni_android.h"
#include "base/android/jni_string.h"
#include "base/android/scoped_java_ref.h"
#include "chrome/android/chrome_jni_headers/SigninBridge_jni.h"
#include "ui/android/window_android.h"
using base::android::JavaParamRef;
// static
void SigninBridge::LaunchSigninActivity(
ui::WindowAndroid* window,
signin_metrics::AccessPoint access_point) {
if (window) {
Java_SigninBridge_launchSigninActivity(base::android::AttachCurrentThread(),
window->GetJavaObject(),
static_cast<int>(access_point));
}
}
void SigninBridge::OpenAccountManagementScreen(
ui::WindowAndroid* window,
signin::GAIAServiceType service_type) {
DCHECK(window);
JNIEnv* env = base::android::AttachCurrentThread();
Java_SigninBridge_openAccountManagementScreen(env, window->GetJavaObject(),
static_cast<int>(service_type));
}
void SigninBridge::OpenAccountPickerBottomSheet(
ui::WindowAndroid* window,
const std::string& continue_url) {
DCHECK(window);
JNIEnv* env = base::android::AttachCurrentThread();
Java_SigninBridge_openAccountPickerBottomSheet(
env, window->GetJavaObject(),
base::android::ConvertUTF8ToJavaString(env, continue_url));
}
| 35.477273 | 80 | 0.704676 | zealoussnow |
6dcf9957d8485f31f9bdd11b7d3b47c283043e7d | 1,574 | hpp | C++ | include/pique/data/grid.hpp | daboyuka/PIQUE | d0e2ba4cc47aaeaf364b3c76339306e1795adb5e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/pique/data/grid.hpp | daboyuka/PIQUE | d0e2ba4cc47aaeaf364b3c76339306e1795adb5e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | include/pique/data/grid.hpp | daboyuka/PIQUE | d0e2ba4cc47aaeaf364b3c76339306e1795adb5e | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | /*
* Copyright 2015 David A. Boyuka II
*
* 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.
*/
/*
* grid.hpp
*
* Created on: Jan 24, 2014
* Author: David A. Boyuka II
*/
#ifndef GRID_HPP_
#define GRID_HPP_
#include <boost/smart_ptr.hpp>
class Grid : public std::vector< uint64_t > {
public:
enum class Linearization { ROW_MAJOR_ORDER, Z_ORDER, MORTON_ORDER = Z_ORDER /* alias */, };
public:
using ParentType = std::vector< uint64_t >;
Grid(Linearization lin = Linearization::ROW_MAJOR_ORDER) : ParentType(), lin(lin) {}
Grid(std::vector< uint64_t > &&dims, Linearization lin = Linearization::ROW_MAJOR_ORDER) : ParentType(std::move(dims)), lin(lin) {}
Grid(std::initializer_list< uint64_t > &&dims) : ParentType(std::move(dims)), lin(Linearization::ROW_MAJOR_ORDER) {}
Linearization get_linearization() const { return lin; }
uint64_t get_npoints() const {
uint64_t count = 1;
for (uint64_t dim : *this)
count *= dim;
return count;
}
private:
Linearization lin;
};
#endif /* GRID_HPP_ */
| 29.698113 | 135 | 0.691868 | daboyuka |
6dd12f37c7e32ea04ee35dd4e712e20a5e481085 | 3,554 | hpp | C++ | src/Generator/Polar/Generator_polar.hpp | aff3ct/polar_decoder_gen | 7d02025aa62bbef58b88f8fca65f5ee9ed86727e | [
"MIT"
] | 8 | 2018-03-14T22:17:16.000Z | 2021-05-31T23:29:03.000Z | src/Generator/Polar/Generator_polar.hpp | aff3ct/polar_decoder_gen | 7d02025aa62bbef58b88f8fca65f5ee9ed86727e | [
"MIT"
] | 1 | 2017-09-30T01:02:23.000Z | 2018-03-16T09:01:33.000Z | src/Generator/Polar/Generator_polar.hpp | aff3ct/polar_decoder_gen | 7d02025aa62bbef58b88f8fca65f5ee9ed86727e | [
"MIT"
] | 2 | 2019-09-16T08:30:13.000Z | 2019-12-17T02:15:34.000Z | #ifndef GENERATOR_POLAR_SYS_
#define GENERATOR_POLAR_SYS_
#include <map>
#include <vector>
#include <mipp.h>
#include <aff3ct.hpp>
#include "../Generator.hpp"
namespace aff3ct
{
namespace generator
{
class Generator_polar : public Generator
{
protected:
const int K; // k bits input
const int N; // n bits input
const int m; // graph depth
const float snr;
const std::vector<bool>& frozen_bits;
const std::vector<tools::Pattern_polar_i*> &patterns;
const tools::Pattern_polar_i &pattern_rate0;
const tools::Pattern_polar_i &pattern_rate1;
tools::Pattern_polar_parser parser;
std::string mother_class_name;
std::string MOTHER_CLASS_NAME;
std::string fbits_name;
std::ostream &dec_stream;
std::ostream &short_dec_stream;
std::ostream &graph_stream;
std::ostream &short_graph_stream;
std::string tab;
const int inlining_level;
std::vector<std::vector<int>> stats;
std::map<std::string, int> subtree_occurences;
std::map<std::string, int> subtree_occurences_cpy;
std::map<std::string, std::string> subtree_nodes;
unsigned n_nodes_before_compression;
unsigned n_nodes_after_compression;
const bool enable_short_decoder;
public:
Generator_polar(const int& K,
const int& N,
const float& snr,
const std::vector<bool>& frozen_bits,
const std::vector<tools::Pattern_polar_i*> &patterns,
const int idx_r0,
const int idx_r1,
std::string mother_class_name,
std::string MOTHER_CLASS_NAME,
std::ostream &dec_stream = std::cout,
std::ostream &short_dec_stream = std::cout,
std::ostream &graph_stream = std::cout,
std::ostream &short_graph_stream = std::cout,
const bool enable_short_decoder = true);
virtual ~Generator_polar();
void generate();
std::string get_class_name();
unsigned long get_n_generated_nodes ( int graph_depth = -1) const;
unsigned long get_n_generated_nodes_by_pattern(std::size_t pattern_hash, int graph_depth = -1) const;
protected:
virtual void generate_header(const std::string mother_class_name,
const std::vector<bool> &frozen_bits,
const std::string fbits_name,
std::ostream &stream) = 0;
virtual void generate_class_header(const std::string class_name,
const std::string fbits_name,
std::ostream &stream1,
std::ostream &stream2) = 0;
virtual void generate_class_footer( std::ostream &stream) = 0;
virtual void generate_footer ( std::ostream &stream) = 0;
virtual void recursive_generate_decoder (const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream) = 0;
virtual void recursive_generate_short_decoder(const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream) = 0;
private:
void recursive_generate_short_decoder_funcs(const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream);
void recursive_generate_graph (const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream);
void recursive_generate_short_graph (const tools::Binary_node<tools::Pattern_polar_i>* node_curr, std::ostream &stream);
};
}
}
#endif /* GENERATOR_POLAR_SYS_ */
| 35.188119 | 134 | 0.655318 | aff3ct |
6dd25a7eb3167e6380786d56bfe0fe1389550fa3 | 33,982 | cpp | C++ | cuda/cudamd/Host.cpp | vakuras/moleculardynamics | f9c6b03db7df8e429f72fa17b5ccfd98d08ee272 | [
"MIT"
] | null | null | null | cuda/cudamd/Host.cpp | vakuras/moleculardynamics | f9c6b03db7df8e429f72fa17b5ccfd98d08ee272 | [
"MIT"
] | null | null | null | cuda/cudamd/Host.cpp | vakuras/moleculardynamics | f9c6b03db7df8e429f72fa17b5ccfd98d08ee272 | [
"MIT"
] | null | null | null | ///
/// Host Implementation
///
/// Molecular Dynamics Simulation on GPU
///
/// Written by Vadim Kuras. 2009-2010.
///
#include "Host.h"
///
/// Simulation main host function
///
int hostMain(CUdevice device, char * module_path, configuration * config)
{
real4 * posArray; //positions (host)
real3 * velocityArray; //velocity (host)
bool * flag; //box hit flag (host)
int * ljList = NULL; //lennard jones neigbor list pointer
int * mbList = NULL; //many body neigbor list pointer
listSettings lj; //lennard jones neigbor list settings
listSettings mb; //many body neigbor list settings
float highestVelocity; //heighest velocity
int timesteps; //timestep counter
int ljNextBuild; //on which timestep to call the build of the lennard jones list
int mbNextBuild; //on which timestep to call the build of the many body list
float boxSize=pow((float)(config->LennardJonesParticles + config->ManyBodyParticles),1.0f/3.0f)*52.8f; //box size
float boxSizeList; //box size for the neighbor lists
int buckets; //bucket count for the neighbor list
bool fallbackmb = false; //fallback from tpp to bpp for many body
bool fallbacklj = false; //fallback from tpp to bpp for lennard jones
vector<results> resultVec; //results vector
vector<float*> posVec; //position vector for animation
vector<float*> velVec; //velocity vector for animation
#ifdef USECUDADEBUG
float * informationMemory; //information memory pointer
CUdeviceptr devInformation; //information memory pointer for cuda
//vibLJ, vibMB, kinetic, temperature, centerOfMass, momentum
const int informationSize = sizeof(float)+sizeof(float)+sizeof(float)+sizeof(float)+sizeof(float3)+sizeof(real3);
#endif
//device variables
CUdeviceptr devPosArray; //positions cuda pointer
CUdeviceptr devVelocityArray; //velocity cuda pointer
CUdeviceptr devAAccArray; //acceleration cuda pointer
CUdeviceptr devForceArray; //force cuda pointer
CUdeviceptr devBAccArray; //b-acc cuda pointer
CUdeviceptr devCAccArray; //c-acc cuda pointer
CUdeviceptr devMemAlloc; //device block-shared memory pointer
CUdeviceptr devFlag; //device box-hit-flag
CUcontext context; //device context
CUmodule module; //cude module (.ptx file)
//function pointers from module:
#ifdef USECUDADEBUG
CUfunction performCalculations;
CUfunction calculatePotentional;
#endif
CUfunction correct;
CUfunction predict;
CUfunction lennardJonesForces;
CUfunction lennardJonesForcesBPP;
CUfunction manyBodyForces1;
CUfunction manyBodyForces2;
CUfunction manyBodyForcesBPP1;
CUfunction manyBodyForcesBPP2;
CUfunction calculateAccelerations;
//textures for neighbor lists
CUarray devLjList = NULL;
CUarray devMbList = NULL;
CUtexref devLjTexRef = NULL;
CUtexref devMbTexRef = NULL;
//function build helpers - for use by consts defined in Host.h (CUDA_DEF_SET, CUDA_RESET_OFFSET... and so)
void * ptr;
int offset;
unsigned int val;
float fval;
int nlsoffset; //neighbor list 'largest list size' byte offset in the byte array of the force calculation functions
//block configuration
int BlocksPerGrid = config->CudaBlocks;
int ThreadsPerBlocks = (config->LennardJonesParticles + config->ManyBodyParticles)/BlocksPerGrid + ((config->LennardJonesParticles + config->ManyBodyParticles)%BlocksPerGrid == 0 ? 0:1);
int mbThreadsPerBlocks = config->ManyBodyParticles/BlocksPerGrid + (config->ManyBodyParticles%BlocksPerGrid == 0 ? 0:1);
//time-measure events
CUevent start;
CUevent stop;
float elapsedTime;
config->energyLoss = sqrt(config->energyLoss); //fix energy loss
//create context
CU_SAFE_CALL(cuCtxCreate(&context, 0, device));
//load module
CU_SAFE_CALL(cuModuleLoad(&module, module_path));
//get functions
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuModuleGetFunction(&performCalculations, module, "performCalculations"));
CU_SAFE_CALL(cuModuleGetFunction(&calculatePotentional, module, "calculatePotentional"));
#endif
CU_SAFE_CALL(cuModuleGetFunction(&predict, module, "predict"));
CU_SAFE_CALL(cuModuleGetFunction(&correct, module, "correct"));
CU_SAFE_CALL(cuModuleGetFunction(&calculateAccelerations, module, "calculateAccelerations"));
if (config->useLennardJones) //if using lennard jones
{
CU_SAFE_CALL(cuModuleGetFunction(&lennardJonesForcesBPP, module, "lennardJonesForcesBPP"));
CU_SAFE_CALL(cuModuleGetFunction(&lennardJonesForces, module, "lennardJonesForces"));
}
if (config->useManyBody) //if using many body
{
CU_SAFE_CALL(cuModuleGetFunction(&manyBodyForcesBPP1, module, "manyBodyForcesBPP1"));
CU_SAFE_CALL(cuModuleGetFunction(&manyBodyForcesBPP2, module, "manyBodyForcesBPP2"));
CU_SAFE_CALL(cuModuleGetFunction(&manyBodyForces1, module, "manyBodyForces1"));
CU_SAFE_CALL(cuModuleGetFunction(&manyBodyForces2, module, "manyBodyForces2"));
CU_SAFE_CALL(cuMemAlloc(&devMemAlloc,sizeof(float2) * config->ManyBodyParticles * config->ManyBodyParticles)); //allocate memory used by many body
}
//set events
CU_SAFE_CALL(cuEventCreate(&start, CU_EVENT_DEFAULT));
CU_SAFE_CALL(cuEventCreate(&stop, CU_EVENT_DEFAULT));
//allocate memory for data on host (for future device mapping)
CU_SAFE_CALL(cuMemAllocHost((void**)&posArray, (config->LennardJonesParticles + config->ManyBodyParticles) * sizeof(real4)));
CU_SAFE_CALL(cuMemAllocHost((void**)&velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles) * sizeof(real3)));
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuMemAllocHost((void**)&informationMemory, informationSize));
#endif
CU_SAFE_CALL(cuMemAllocHost((void**)&flag, sizeof(bool)));
//allocate memory for data on device
CU_SAFE_CALL(cuMemAlloc(&devPosArray,sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devVelocityArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devAAccArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devForceArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devBAccArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemAlloc(&devCAccArray,sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuMemAlloc(&devInformation,informationSize));
#endif
CU_SAFE_CALL(cuMemAlloc(&devFlag,sizeof(bool)));
//number of buckets for list hashs
buckets = (config->LennardJonesParticles + config->ManyBodyParticles) * 3;
mb.nlargestsize = lj.nlargestsize = 0;
if (config->useLennardJones) //set lennard jones list settings
{
lj.maxnlmove = ((config->LennardJonesRS) - (config->LennardJonesRCUT)) * 0.5f;
lj.maxnlmovesq = pow(lj.maxnlmove, 2);
lj.rcutsq = pow(config->LennardJonesRCUT,2);
lj.rcut = config->LennardJonesRCUT;
lj.rs = config->LennardJonesRS;
}
if (config->useManyBody) //set many body list settings
{
mb.maxnlmove = ((config->ManyBodyRS) - (config->ManyBodyRCUT)) * 0.5f;
mb.maxnlmovesq = pow(mb.maxnlmove, 2);
mb.rcutsq = pow(config->ManyBodyRCUT,2);
mb.rcut = config->ManyBodyRCUT;
mb.rs = config->ManyBodyRS;
}
#ifdef USECUDADEBUG
//parameter setup for performCalculations
CUDA_RESET_OFFSET; //reset offset to zero
CUDA_POINTER_ALLOC(performCalculations, devPosArray); //allocate pointer in the byte array of the function
CUDA_POINTER_ALLOC(performCalculations, devVelocityArray);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(performCalculations, val); //allocate unsigned int in the byte array of the function
CUDA_POINTER_ALLOC(performCalculations, devInformation);
CU_SAFE_CALL(cuParamSetSize( performCalculations, offset )); //set byte array size
CU_SAFE_CALL(cuFuncSetBlockShape( performCalculations, 1, 1, 1 )); //set block grid
//parameter setup for calculatePotentional
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(calculatePotentional, devPosArray);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(calculatePotentional, val);
CUDA_POINTER_ALLOC(calculatePotentional, devInformation);
CU_SAFE_CALL(cuParamSetSize( calculatePotentional, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( calculatePotentional, ThreadsPerBlocks, 1, 1 ));
#endif
//parameter setup for predict
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(predict, devPosArray);
CUDA_POINTER_ALLOC(predict, devVelocityArray);
CUDA_POINTER_ALLOC(predict, devAAccArray);
CUDA_POINTER_ALLOC(predict, devBAccArray);
CUDA_POINTER_ALLOC(predict, devCAccArray);
fval = config->DT;
CUDA_FLOAT_ALLOC(predict, fval); //allocate float in the byte array of the function
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(predict, val);
CU_SAFE_CALL(cuParamSetSize( predict, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( predict, ThreadsPerBlocks, 1, 1 ));
//parameter setup for correct
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(correct, devPosArray);
CUDA_POINTER_ALLOC(correct, devVelocityArray);
CUDA_POINTER_ALLOC(correct, devForceArray);
CUDA_POINTER_ALLOC(correct, devAAccArray);
CUDA_POINTER_ALLOC(correct, devBAccArray);
CUDA_POINTER_ALLOC(correct, devCAccArray);
fval = config->DT;
CUDA_FLOAT_ALLOC(correct, fval);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(correct, val);
fval = boxSize;
CUDA_FLOAT_ALLOC(correct, fval);
CUDA_POINTER_ALLOC(correct, devFlag);
fval = config->energyLoss;
CUDA_FLOAT_ALLOC(correct, fval);
CU_SAFE_CALL(cuParamSetSize( correct, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( correct, ThreadsPerBlocks, 1, 1 ));
//parameter setup for calculateAccelerations
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(calculateAccelerations, devPosArray);
CUDA_POINTER_ALLOC(calculateAccelerations, devForceArray);
CUDA_POINTER_ALLOC(calculateAccelerations, devAAccArray);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(calculateAccelerations, val);
CU_SAFE_CALL(cuParamSetSize( calculateAccelerations, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( calculateAccelerations, ThreadsPerBlocks, 1, 1 ));
if (config->useLennardJones)
{
//parameter setup for lennardJonesForcesBPP
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(lennardJonesForcesBPP, devPosArray);
CUDA_POINTER_ALLOC(lennardJonesForcesBPP, devForceArray);
fval = lj.rcutsq;
CUDA_FLOAT_ALLOC(lennardJonesForcesBPP, fval);
CU_SAFE_CALL(cuParamSetSize( lennardJonesForcesBPP, offset ));
//parameter setup for lennardJonesForces
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(lennardJonesForces, devPosArray);
CUDA_POINTER_ALLOC(lennardJonesForces, devForceArray);
val = 0; //temporarily
CUDA_GET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(lennardJonesForces, val);
val = (config->LennardJonesParticles + config->ManyBodyParticles);
CUDA_UINT_ALLOC(lennardJonesForces, val);
fval = lj.rcutsq;
CUDA_FLOAT_ALLOC(lennardJonesForces, fval);
CU_SAFE_CALL(cuParamSetSize( lennardJonesForces, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( lennardJonesForces, ThreadsPerBlocks, 1, 1 ));
}
if (config->useManyBody)
{
//parameter setup for manyBodyForcesBPP1
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(manyBodyForcesBPP1, devPosArray);
CUDA_POINTER_ALLOC(manyBodyForcesBPP1, devForceArray);
fval = mb.rcutsq;
CUDA_FLOAT_ALLOC(manyBodyForcesBPP1, fval);
val = config->ManyBodyParticles;
CUDA_UINT_ALLOC(manyBodyForcesBPP1, val);
CUDA_POINTER_ALLOC(manyBodyForcesBPP1, devMemAlloc);
val = config->useLennardJones;
CUDA_UINT_ALLOC(manyBodyForcesBPP1, val);
CU_SAFE_CALL(cuParamSetSize( manyBodyForcesBPP1, offset ));
//parameter setup for manyBodyForcesBPP2
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(manyBodyForcesBPP2, devPosArray);
CUDA_POINTER_ALLOC(manyBodyForcesBPP2, devForceArray);
fval = mb.rcutsq;
CUDA_FLOAT_ALLOC(manyBodyForcesBPP2, fval);
val = config->ManyBodyParticles;
CUDA_UINT_ALLOC(manyBodyForcesBPP2, val);
CUDA_POINTER_ALLOC(manyBodyForcesBPP2, devMemAlloc);
CU_SAFE_CALL(cuParamSetSize( manyBodyForcesBPP2, offset ));
//parameter setup for manyBodyForces1
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(manyBodyForces1, devPosArray);
CUDA_POINTER_ALLOC(manyBodyForces1, devForceArray);
val = 0; //temporarily
CUDA_GET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces1, val);
val = config->ManyBodyParticles;
CUDA_UINT_ALLOC(manyBodyForces1, val);
fval = mb.rcutsq;
CUDA_FLOAT_ALLOC(manyBodyForces1, fval);
CUDA_POINTER_ALLOC(manyBodyForces1, devMemAlloc);
val = config->useLennardJones;
CUDA_UINT_ALLOC(manyBodyForces1, val);
CU_SAFE_CALL(cuParamSetSize( manyBodyForces1, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForces1, mbThreadsPerBlocks, 1, 1 ));
//parameter setup for manyBodyForces2
CUDA_RESET_OFFSET;
CUDA_POINTER_ALLOC(manyBodyForces2, devPosArray);
CUDA_POINTER_ALLOC(manyBodyForces2, devForceArray);
val = 0; //temporarily
CUDA_UINT_ALLOC(manyBodyForces2, val);
val = config->ManyBodyParticles;
CUDA_UINT_ALLOC(manyBodyForces2, val);
fval = mb.rcutsq;
CUDA_FLOAT_ALLOC(manyBodyForces2, fval);
CUDA_POINTER_ALLOC(manyBodyForces2, devMemAlloc);
CU_SAFE_CALL(cuParamSetSize( manyBodyForces2, offset ));
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForces2, mbThreadsPerBlocks, 1, 1 ));
}
for(float vxcm=config->vxcmFrom; vxcm<=config->vxcmTo; vxcm+=config->vxcmStep)
{
//init
timesteps = 0;
ljNextBuild = mbNextBuild = 0;
//information
int printout = config->OutputTimesteps; //next debug output time step
int animts = config->animts; //next animation save time step
//read input file
readInput(config, (float*) posArray, (float*) velocityArray);
//push the particles outside the box into the box & vxcm
for (int id=0; id< (config->LennardJonesParticles + config->ManyBodyParticles); id++)
{
if (fabs(posArray[id].x) > (boxSize/2))
posArray[id].x = (boxSize/2) * (posArray[id].x/fabs(posArray[id].x));
if (fabs(posArray[id].y) > (boxSize/2))
posArray[id].y = (boxSize/2) * (posArray[id].y/fabs(posArray[id].y));
if (fabs(posArray[id].z) > (boxSize/2))
posArray[id].z = (boxSize/2) * (posArray[id].z/fabs(posArray[id].z));
velocityArray[id].x += vxcm;
}
//copy position & velocity to device memory
CU_SAFE_CALL(cuMemcpyHtoD(devPosArray, posArray, sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemcpyHtoD(devVelocityArray, velocityArray, sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
//zero some device memory
CU_SAFE_CALL(cuMemsetD32(devAAccArray, 0, 3 * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemsetD32(devBAccArray, 0, 3 * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemsetD32(devCAccArray, 0, 3 * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemsetD8(devFlag, 0, sizeof(bool)));
//before sim output
cout << fixed << setprecision(6); //set maximal precision for output
cout.setf(ios::fixed,ios::floatfield); //zero padding
cout << "Before Simulation [VXCM = " << vxcm << "]:" << endl;
//calculate highest velocity and boxSizeList
readyList(posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles), highestVelocity, boxSizeList);
if (config->useLennardJones)
{
//build lennard jones list
buildList(posArray, &lj, boxSizeList, buckets, highestVelocity, (config->LennardJonesParticles + config->ManyBodyParticles), ljNextBuild, 0, &ljList, config->DT, "ljTexRef", &devLjList, &devLjTexRef, &module);
//check if a fallback is to be used
fallbacklj = (lj.nlargestsize > THREADSPERBLOCK) && config->Fallback;
//set the 'largest list size' according to the new data
if (config->lennardJonesBPP && !fallbacklj)
{
if (lj.nlargestsize > 0)
{
CU_SAFE_CALL(cuFuncSetBlockShape( lennardJonesForcesBPP, lj.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( lennardJonesForcesBPP, lj.nlargestsize*sizeof(real4)));
}
}
else
{
val = lj.nlargestsize;
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(lennardJonesForces, val);
}
}
if (config->useManyBody)
{
//build many body list
buildList(posArray, &mb, boxSizeList, buckets, highestVelocity, config->ManyBodyParticles, mbNextBuild, 0, &mbList, config->DT, "mbTexRef", &devMbList, &devMbTexRef, &module);
//check if a fallback is to be used
fallbackmb = (mb.nlargestsize > THREADSPERBLOCK) && config->Fallback;
//set the 'largest list size' according to the new data
if (config->manyBodyBPP && !fallbackmb)
{
if (mb.nlargestsize>0)
{
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForcesBPP1, mb.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( manyBodyForcesBPP1, mb.nlargestsize*sizeof(real4)));
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForcesBPP2, mb.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( manyBodyForcesBPP2, mb.nlargestsize*sizeof(real4)));
}
}
else
{
val = mb.nlargestsize;
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces1, val);
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces2, val);
}
}
//perform the output function
#ifdef USECUDADEBUG
performOutput(resultVec, BlocksPerGrid, informationSize, informationMemory, devInformation, performCalculations, calculatePotentional, timesteps, config->DT, true);
#else
performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, devPosArray, devVelocityArray, timesteps, config->DT, true);
#endif
cout << endl;
if (config->animts>-1)
pushAnim(posVec, velVec, posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles));
//measure & perform
CU_SAFE_CALL(cuEventRecord(start,0));
if (config->useLennardJones && lj.nlargestsize>0) //calculate force for lennard jones
{
if (config->lennardJonesBPP && !fallbacklj) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForcesBPP, (config->LennardJonesParticles + config->ManyBodyParticles), 1));
CU_SAFE_CALL(cuCtxSynchronize()); //synchronize context
}
else //tpp
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForces, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize()); //synchronize context
}
}
if (config->useManyBody && mb.nlargestsize>0) //calculate force for many body
{
if (config->manyBodyBPP && !fallbackmb) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP1, config->ManyBodyParticles, 1)); //b-o 1
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP2, config->ManyBodyParticles, 1)); //b-o 2
CU_SAFE_CALL(cuCtxSynchronize());
}
else //tpp
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces1, BlocksPerGrid, 1)); //b-o 1
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces2, BlocksPerGrid, 1)); //b-o 2
CU_SAFE_CALL(cuCtxSynchronize());
}
}
//calculate the accelerations after the force
CU_SAFE_CALL(cuLaunchGrid(calculateAccelerations, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize());
//while not reached the timestep goal
while(timesteps<config->Timesteps)
{
if (ljNextBuild == timesteps || mbNextBuild == timesteps) //is is time to build any of the lists?
{
//copy memory from device
CU_SAFE_CALL(cuMemcpyDtoH(posArray, devPosArray, sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemcpyDtoH(velocityArray, devVelocityArray, sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
readyList(posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles), highestVelocity, boxSizeList);
if (config->useLennardJones && ljNextBuild == timesteps) //is it time to build the lj list?
{
buildList(posArray, &lj, boxSizeList, buckets, highestVelocity, (config->LennardJonesParticles + config->ManyBodyParticles), ljNextBuild, timesteps, &ljList, config->DT, "ljTexRef", &devLjList, &devLjTexRef, &module);
fallbacklj = (lj.nlargestsize > THREADSPERBLOCK) && config->Fallback; //check for fallback
//set the 'largest list size' according to the new data
if (config->lennardJonesBPP && !fallbacklj)
{
if (lj.nlargestsize > 0)
{
CU_SAFE_CALL(cuFuncSetBlockShape( lennardJonesForcesBPP, lj.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( lennardJonesForcesBPP, lj.nlargestsize*sizeof(real4)));
}
}
else
{
val = lj.nlargestsize;
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(lennardJonesForces, val);
}
}
if (config->useManyBody && mbNextBuild == timesteps) // is it time to build the mb list?
{
buildList(posArray, &mb, boxSizeList, buckets, highestVelocity, config->ManyBodyParticles, mbNextBuild, timesteps, &mbList, config->DT, "mbTexRef", &devMbList, &devMbTexRef, &module);
fallbackmb = (mb.nlargestsize > THREADSPERBLOCK) && config->Fallback; //check for fallback
//set the 'largest list size' according to the new data
if (config->manyBodyBPP && !fallbackmb)
{
if (mb.nlargestsize>0)
{
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForcesBPP1, mb.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( manyBodyForcesBPP1, mb.nlargestsize*sizeof(real4)));
CU_SAFE_CALL(cuFuncSetBlockShape( manyBodyForcesBPP2, mb.nlargestsize, 1, 1 ));
CU_SAFE_CALL(cuFuncSetSharedSize( manyBodyForcesBPP2, mb.nlargestsize*sizeof(real4)));
}
}
else
{
val = mb.nlargestsize;
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces1, val);
CUDA_SET_OFFSET(nlsoffset);
CUDA_UINT_ALLOC(manyBodyForces2, val);
}
}
}
//predict
CU_SAFE_CALL(cuLaunchGrid(predict, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
//force lj
if (config->useLennardJones && lj.nlargestsize>0)
{
if (config->lennardJonesBPP && !fallbacklj)
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForcesBPP, (config->LennardJonesParticles + config->ManyBodyParticles),1));
CU_SAFE_CALL(cuCtxSynchronize());
}
else
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForces, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
}
}
//force mb
if (config->useManyBody && mb.nlargestsize>0)
{
if (config->manyBodyBPP && !fallbackmb) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP1, config->ManyBodyParticles,1));
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP2, config->ManyBodyParticles,1));
CU_SAFE_CALL(cuCtxSynchronize());
}
else
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces1, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces2, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
}
}
//correct
CU_SAFE_CALL(cuLaunchGrid(correct, BlocksPerGrid,1));
CU_SAFE_CALL(cuCtxSynchronize());
//copy flag mem
CU_SAFE_CALL(cuMemcpyDtoH(flag, devFlag, sizeof(bool)));
if (*flag)
{
if (config->useLennardJones && lj.nlargestsize>0) //calculate force for lennard jones
{
if (config->lennardJonesBPP && !fallbacklj) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForcesBPP, (config->LennardJonesParticles + config->ManyBodyParticles), 1));
CU_SAFE_CALL(cuCtxSynchronize()); //synchronize context
}
else //tpp
{
CU_SAFE_CALL(cuLaunchGrid(lennardJonesForces, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize()); //synchronize context
}
}
if (config->useManyBody && mb.nlargestsize>0) //calculate force for many body
{
if (config->manyBodyBPP && !fallbackmb) //bpp and no fallback
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP1, config->ManyBodyParticles, 1)); //b-o 1
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForcesBPP2, config->ManyBodyParticles, 1)); //b-o 2
CU_SAFE_CALL(cuCtxSynchronize());
}
else //tpp
{
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces1, BlocksPerGrid, 1)); //b-o 1
CU_SAFE_CALL(cuCtxSynchronize());
CU_SAFE_CALL(cuLaunchGrid(manyBodyForces2, BlocksPerGrid, 1)); //b-o 2
CU_SAFE_CALL(cuCtxSynchronize());
}
}
//calculate the accelerations after the force
CU_SAFE_CALL(cuLaunchGrid(calculateAccelerations, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize());
//clear flag
CU_SAFE_CALL(cuMemsetD8(devFlag, 0, sizeof(bool)));
}
//results
if (printout==timesteps)
{
#ifdef USECUDADEBUG
performOutput(resultVec, BlocksPerGrid, informationSize, informationMemory, devInformation, performCalculations, calculatePotentional, timesteps, config->DT, config->Debug);
#else
performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, devPosArray, devVelocityArray, timesteps, config->DT, config->Debug);
#endif
printout += config->OutputTimesteps;
}
//animation
if (animts==timesteps)
{
//copy memory from device
CU_SAFE_CALL(cuMemcpyDtoH(posArray, devPosArray, sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemcpyDtoH(velocityArray, devVelocityArray, sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
pushAnim(posVec, velVec, posArray, velocityArray, (config->LennardJonesParticles + config->ManyBodyParticles));
animts += config->animts;
}
timesteps++;
}
//stop measuring
CU_SAFE_CALL(cuEventRecord(stop,0));
CU_SAFE_CALL(cuEventSynchronize(stop));
//calculate time
CU_SAFE_CALL(cuEventElapsedTime(&elapsedTime,start,stop));
//after sim output
cout << "\nAfter Simulation [VXCM = " << vxcm << "]:" << endl;
#ifdef USECUDADEBUG
performOutput(resultVec, BlocksPerGrid, informationSize, informationMemory, devInformation, performCalculations, calculatePotentional, timesteps, config->DT, true);
#else
performOutput(&resultVec, (config->LennardJonesParticles + config->ManyBodyParticles), posArray, velocityArray, devPosArray, devVelocityArray, timesteps, config->DT, true);
#endif
cout << "\nTime took: " << elapsedTime << "ms" << endl;
//copy memory from device
CU_SAFE_CALL(cuMemcpyDtoH(posArray, devPosArray, sizeof(real4) * (config->LennardJonesParticles + config->ManyBodyParticles)));
CU_SAFE_CALL(cuMemcpyDtoH(velocityArray, devVelocityArray, sizeof(real3) * (config->LennardJonesParticles + config->ManyBodyParticles)));
//write the output
writeOutput(config, (float*) posArray, (float*) velocityArray);
//output info to log & results
writeResults(resultVec, config, elapsedTime, tailResults(posArray, config->ManyBodyParticles), vxcm);
if (config->animts>-1)
writeAnimationBinaryData(posVec, velVec, config, vxcm);
flushVectors(resultVec, posVec, velVec);
}
//release lists memory
if (ljList)
{
delete [] ljList;
ljList = NULL;
}
if (mbList)
{
delete [] mbList;
mbList = NULL;
}
//free events
CU_SAFE_CALL(cuEventDestroy(start));
CU_SAFE_CALL(cuEventDestroy(stop));
//free device memory
CU_SAFE_CALL(cuMemFree(devPosArray));
CU_SAFE_CALL(cuMemFree(devVelocityArray));
CU_SAFE_CALL(cuMemFree(devAAccArray));
CU_SAFE_CALL(cuMemFree(devForceArray));
CU_SAFE_CALL(cuMemFree(devBAccArray));
CU_SAFE_CALL(cuMemFree(devCAccArray));
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuMemFree(devInformation));
#endif
CU_SAFE_CALL(cuMemFree(devFlag));
if (config->useManyBody)
CU_SAFE_CALL(cuMemFree(devMemAlloc));
//free memory
CU_SAFE_CALL(cuMemFreeHost(posArray));
CU_SAFE_CALL(cuMemFreeHost(velocityArray));
CU_SAFE_CALL(cuMemFreeHost(flag));
#ifdef USECUDADEBUG
CU_SAFE_CALL(cuMemFreeHost(informationMemory));
#endif
//drop context
CU_SAFE_CALL(cuCtxDetach(context));
//free module path
cutFree(module_path);
return EXIT_SUCCESS;
}
#ifdef USECUDADEBUG
void performOutput(vector<results> & resultVec, int BlocksPerGrid, int informationSize, float * informationMemory, CUdeviceptr & devInformation, CUfunction & performCalculations, CUfunction & calculatePotentional, int timesteps, float dt, bool print)
{
real3 cmassTmp;
real3 momentumTmp;
//reset information memory on device
CU_SAFE_CALL(cuMemsetD32(devInformation, 0, informationSize/sizeof(float)));
//kinetic, memontum an so
CU_SAFE_CALL(cuLaunchGrid(performCalculations, 1, 1));
CU_SAFE_CALL(cuCtxSynchronize());
//potentional energy calculation
CU_SAFE_CALL(cuLaunchGrid(calculatePotentional, BlocksPerGrid, 1));
CU_SAFE_CALL(cuCtxSynchronize());
//copy from device to host
CU_SAFE_CALL(cuMemcpyDtoH(informationMemory, devInformation, informationSize));
//fill results structure and push into vector
results res;
res.time = timesteps * dt;
res.ek = (double)*(informationMemory+2);
res.eu = (double)*informationMemory + (double)*(informationMemory+1);
res.e = (double)res.ek + res.eu;
res.temperature = (double)*(informationMemory+3);
cmassTmp = *(real3*)(informationMemory+4);
momentumTmp = *(real3*)(informationMemory+7);
res.centerOfMassx = (double)cmassTmp.x;
res.centerOfMassy = (double)cmassTmp.y;
res.centerOfMassz = (double)cmassTmp.z;
res.momentumx = (double)momentumTmp.x;
res.momentumy = (double)momentumTmp.y;
res.momentumz = (double)momentumTmp.z;
if (print) //debug-output
cout << "t=" << res.time
<< "\tT=" << res.temperature
<< "\tE=" << res.e
<< "\tEK=" << res.ek
<< "\tEU=" << res.eu
<< endl;
resultVec.push_back(res);
}
#else
void performOutput(vector<results> * resultVec, int NumberOfParticles, real4 * posArray, real3 * velocityArray, CUdeviceptr & devPosArray, CUdeviceptr & devVelocityArray, int timesteps, real dt, bool print)
{
CU_SAFE_CALL(cuMemcpyDtoH(posArray, devPosArray, sizeof(real4) * NumberOfParticles));
CU_SAFE_CALL(cuMemcpyDtoH(velocityArray, devVelocityArray, sizeof(real3) * NumberOfParticles));
performOutput(resultVec, NumberOfParticles, posArray, velocityArray, timesteps, dt, print);
}
#endif
///
/// Get Highest Velocity & Box Size
///
void readyList(real4 * posArray, real3 * velocityArray, int NumberOfParticles, float & highestVelocity, float & boxSize)
{
highestVelocity = 0;
boxSize = 0;
for(int i=0; i<NumberOfParticles; i++)
{
//calculate highest velocity
float velocity = sqrt(velocityArray[i].x * velocityArray[i].x + velocityArray[i].y * velocityArray[i].y + velocityArray[i].z * velocityArray[i].z);
if (velocity>highestVelocity)
highestVelocity = velocity;
//boxsize = (the particle that is far the most from 0,0,0) * 2
if (boxSize<abs(posArray[i].x))
boxSize = abs(posArray[i].x);
if (boxSize<abs(posArray[i].y))
boxSize = abs(posArray[i].y);
if (boxSize<abs(posArray[i].z))
boxSize = abs(posArray[i].z);
}
boxSize*=2; //final box size
}
///
/// Build Neighbor List
///
void buildList(real4 * posArray, listSettings * listsettings, float boxSize, int buckets, float highestVelocity, int NumberOfParticles, int & nextBuild, int currentTimestep, int ** list, float dt, char * lpTexRef, CUarray * cu_array, CUtexref * cu_texref, CUmodule * module)
{
CUDA_ARRAY_DESCRIPTOR desc;
CUDA_MEMCPY2D copyParam;
//free memory if needed
if (*list)
{
delete [] *list;
*list = NULL;
}
//build list
*list = buildNeighborList(posArray, listsettings, boxSize, buckets, NumberOfParticles);
//calculte next build time step
nextBuild = (int) ((listsettings->maxnlmove / highestVelocity) / fabs(dt));
nextBuild += currentTimestep;
//create texture
if (*cu_array)
CU_SAFE_CALL( cuArrayDestroy( *cu_array));
desc.Format = CU_AD_FORMAT_SIGNED_INT32;
desc.NumChannels = 1;
desc.Width = listsettings->nlistsize;
desc.Height = NumberOfParticles;
CU_SAFE_CALL( cuArrayCreate( cu_array, &desc ));
//set memory copy params host-to-cuda-array
memset(©Param, 0, sizeof(copyParam));
copyParam.dstMemoryType = CU_MEMORYTYPE_ARRAY;
copyParam.dstArray = *cu_array;
copyParam.srcMemoryType = CU_MEMORYTYPE_HOST;
copyParam.srcHost = *list;
copyParam.srcPitch = listsettings->nlistsize * sizeof(int);
copyParam.WidthInBytes = copyParam.srcPitch;
copyParam.Height = NumberOfParticles;
CU_SAFE_CALL(cuMemcpy2D(©Param));
//build texture
CU_SAFE_CALL(cuModuleGetTexRef(cu_texref, *module, lpTexRef));
CU_SAFE_CALL(cuTexRefSetArray(*cu_texref, *cu_array, CU_TRSA_OVERRIDE_FORMAT));
CU_SAFE_CALL(cuTexRefSetAddressMode(*cu_texref, 0, CU_TR_ADDRESS_MODE_CLAMP));
CU_SAFE_CALL(cuTexRefSetAddressMode(*cu_texref, 1, CU_TR_ADDRESS_MODE_CLAMP));
CU_SAFE_CALL(cuTexRefSetFilterMode(*cu_texref, CU_TR_FILTER_MODE_POINT));
CU_SAFE_CALL(cuTexRefSetFlags(*cu_texref, CU_TRSF_READ_AS_INTEGER));
CU_SAFE_CALL(cuTexRefSetFormat(*cu_texref, CU_AD_FORMAT_SIGNED_INT32, 1));
//free memory
if (*list)
{
delete [] *list;
*list = NULL;
}
} | 39.194925 | 275 | 0.731122 | vakuras |
6dd279a35cd5586705bac9ecb509f1606d9aba00 | 2,351 | cpp | C++ | examples/st7920_12864_8080_example.cpp | lin2010304125/rt-u8g2 | bca73e4406193e5986e0fffadc0aba2daa68bca1 | [
"CC-BY-3.0"
] | null | null | null | examples/st7920_12864_8080_example.cpp | lin2010304125/rt-u8g2 | bca73e4406193e5986e0fffadc0aba2daa68bca1 | [
"CC-BY-3.0"
] | null | null | null | examples/st7920_12864_8080_example.cpp | lin2010304125/rt-u8g2 | bca73e4406193e5986e0fffadc0aba2daa68bca1 | [
"CC-BY-3.0"
] | null | null | null | #include <rthw.h>
#include <rtthread.h>
#include <rtdevice.h>
#include <U8g2lib.h>
// You may reference Drivers/drv_gpio.c for pinout
// In u8x8.h #define U8X8_USE_PINS
#define ST7920_8080_PIN_D0 36 // PB15
#define ST7920_8080_PIN_D1 35 // PB14
#define ST7920_8080_PIN_D2 34 // PB13
#define ST7920_8080_PIN_D3 33 // PB12
#define ST7920_8080_PIN_D4 37 // PC6
#define ST7920_8080_PIN_D5 38 // PC7
#define ST7920_8080_PIN_D6 39 // PC8
#define ST7920_8080_PIN_D7 40 // PC9
#define ST7920_8080_PIN_EN 50 // PA15
#define ST7920_8080_PIN_CS U8X8_PIN_NONE
#define ST7920_8080_PIN_DC 44 // PA11
#define ST7920_8080_PIN_RST 45 // PA12
// Check https://github.com/olikraus/u8g2/wiki/u8g2setupcpp for all supported devices
static U8G2_ST7920_128X64_F_8080 u8g2(U8G2_R0,
ST7920_8080_PIN_D0,
ST7920_8080_PIN_D1,
ST7920_8080_PIN_D2,
ST7920_8080_PIN_D3,
ST7920_8080_PIN_D4,
ST7920_8080_PIN_D5,
ST7920_8080_PIN_D6,
ST7920_8080_PIN_D7,
/*enable=*/ ST7920_8080_PIN_EN,
/*cs=*/ ST7920_8080_PIN_CS,
/*dc=*/ ST7920_8080_PIN_DC,
/*reset=*/ ST7920_8080_PIN_RST);
static void u8g2_st7920_12864_8080_example(int argc,char *argv[])
{
u8g2.begin();
u8g2.clearBuffer(); // clear the internal memory
u8g2.setFont(u8g2_font_6x13_tr); // choose a suitable font
u8g2.drawStr(1, 18, "U8g2 on RT-Thread"); // write something to the internal memory
u8g2.sendBuffer(); // transfer internal memory to the display
u8g2.setFont(u8g2_font_unifont_t_symbols);
u8g2.drawGlyph(112, 56, 0x2603 );
u8g2.sendBuffer();
}
MSH_CMD_EXPORT(u8g2_st7920_12864_8080_example, st7920 12864 LCD sample);
| 47.979592 | 90 | 0.522756 | lin2010304125 |
6dd458e028538a93c0cbacb01c2acce34df18e3a | 653 | cpp | C++ | leetcode/cpp/qt_find_peak_element.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | 5 | 2016-10-29T09:28:11.000Z | 2019-10-19T23:02:48.000Z | leetcode/cpp/qt_find_peak_element.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | leetcode/cpp/qt_find_peak_element.cpp | qiaotian/CodeInterview | 294c1ba86d8ace41a121c5ada4ba4c3765ccc17d | [
"WTFPL"
] | null | null | null | // 4ms, beat 94%
class Solution {
private:
int helper(const vector<int> &num, int low, int high) {
if(low == high) return low;
int mid = (low + high)/2;
int nxt = mid + 1;
if(num[mid] > num[nxt]) {
return helper(num, low, mid);
} else {
return helper(num, nxt, high);
}
}
public:
int findPeakElement(const vector<int> &num) {
return helper(num, 0, num.size()-1);
}
};
/**
* 1st solution
* logarithmic complexity
* Consider that each local maximum is one valid peak.
* My solution is to find one local maximum with binary search.
* /
| 24.185185 | 63 | 0.54977 | qiaotian |
6dd56544fcecaecfd25b6a183cc3753589d6bcc0 | 3,474 | inl | C++ | test/bincore.inl | PredatorCZ/PreCore | 98f5896e35371d034e6477dd0ce9edeb4fd8d814 | [
"Apache-2.0"
] | 5 | 2019-10-17T15:52:38.000Z | 2021-08-10T18:57:32.000Z | test/bincore.inl | PredatorCZ/PreCore | 98f5896e35371d034e6477dd0ce9edeb4fd8d814 | [
"Apache-2.0"
] | null | null | null | test/bincore.inl | PredatorCZ/PreCore | 98f5896e35371d034e6477dd0ce9edeb4fd8d814 | [
"Apache-2.0"
] | 1 | 2021-01-31T20:37:42.000Z | 2021-01-31T20:37:42.000Z | #include "../datas/binwritter.hpp"
#include "../datas/binreader.hpp"
#include <sstream>
struct BinStr00 {
int8 v0;
bool v1;
int16 v2;
uint32 v3;
};
struct BinStr00_Fc : BinStr00 {
void Read(BinReaderRef rd) {
rd.Read(v0);
rd.Read(v3);
}
void Write(BinWritterRef wr) const {
wr.Write(v0);
wr.Write(v3);
}
};
struct BinStr00_Sw : BinStr00 {
void SwapEndian() {
FByteswapper(v2);
FByteswapper(v3);
}
};
int test_bincore_00() {
std::stringstream ss;
BinWritterRef mwr(ss);
BinStr00_Fc tst = {};
tst.v0 = 15;
tst.v1 = true;
tst.v2 = 584;
tst.v3 = 12418651;
mwr.Write(tst);
tst = {};
tst.v0 = 1;
tst.v1 = false;
tst.v2 = 2;
tst.v3 = 3;
BinReaderRef mrd(ss);
mrd.Read(tst);
TEST_EQUAL(tst.v0, 15);
TEST_EQUAL(tst.v1, false);
TEST_EQUAL(tst.v2, 2);
TEST_EQUAL(tst.v3, 12418651);
mwr.SwapEndian(true);
mwr.Write(tst);
tst.v1 = true;
tst.v2 = 3;
mrd.SwapEndian(true);
mrd.Read(tst);
TEST_EQUAL(tst.v0, 15);
TEST_EQUAL(tst.v1, true);
TEST_EQUAL(tst.v2, 3);
TEST_EQUAL(tst.v3, 12418651);
mwr.Seek(5);
mwr.Skip(-2);
TEST_EQUAL(mwr.Tell(), 3);
mrd.Seek(0);
TEST_EQUAL(mrd.Tell(), 0);
mrd.Skip(10);
TEST_EQUAL(mrd.Tell(), 10);
mrd.Skip(-3);
TEST_EQUAL(mrd.Tell(), 7);
return 0;
};
struct wtcounter {
uint8 count;
uint8 someData;
wtcounter() = default;
wtcounter(size_t cnt) : count(cnt) {}
void Read(BinReaderRef rd) {
rd.Read(count);
}
void Write(BinWritterRef wr) const {
wr.Write(count);
}
operator size_t() const {return count;}
};
int test_bincore_01() {
std::stringstream ss;
BinWritterRef mwr(ss);
std::vector<BinStr00_Fc> vec;
BinStr00_Fc tst = {};
tst.v0 = 15;
tst.v1 = true;
tst.v2 = 584;
tst.v3 = 12418651;
vec.push_back(tst);
tst.v0 = 79;
tst.v1 = false;
tst.v2 = 2100;
tst.v3 = 4248613;
vec.push_back(tst);
mwr.WriteContainerWCount<wtcounter>(vec);
vec.clear();
BinReaderRef mrd(ss);
mrd.ReadContainer<wtcounter>(vec);
TEST_EQUAL(vec.size(), 2);
TEST_EQUAL(vec[0].v0, 15);
TEST_EQUAL(vec[0].v1, false);
TEST_EQUAL(vec[0].v2, 0);
TEST_EQUAL(vec[0].v3, 12418651);
TEST_EQUAL(vec[1].v0, 79);
TEST_EQUAL(vec[1].v1, false);
TEST_EQUAL(vec[1].v2, 0);
TEST_EQUAL(vec[1].v3, 4248613);
return 0;
};
int test_bincore_02() {
std::stringstream ss;
BinWritterRef mwr(ss);
std::vector<BinStr00_Sw> vec;
BinStr00_Sw tst = {};
tst.v0 = 15;
tst.v1 = true;
tst.v2 = 584;
tst.v3 = 12418651;
vec.push_back(tst);
tst.v0 = 79;
tst.v1 = false;
tst.v2 = 2100;
tst.v3 = 4248613;
vec.push_back(tst);
mwr.WriteContainerWCount<wtcounter>(vec);
vec.clear();
BinReaderRef mrd(ss);
mrd.ReadContainer<wtcounter>(vec);
TEST_EQUAL(vec.size(), 2);
TEST_EQUAL(vec[0].v0, 15);
TEST_EQUAL(vec[0].v1, true);
TEST_EQUAL(vec[0].v2, 584);
TEST_EQUAL(vec[0].v3, 12418651);
TEST_EQUAL(vec[1].v0, 79);
TEST_EQUAL(vec[1].v1, false);
TEST_EQUAL(vec[1].v2, 2100);
TEST_EQUAL(vec[1].v3, 4248613);
mwr.SwapEndian(true);
mwr.WriteContainerWCount(vec);
mrd.SwapEndian(true);
vec.clear();
mrd.ReadContainer(vec);
TEST_EQUAL(vec.size(), 2);
TEST_EQUAL(vec[0].v0, 15);
TEST_EQUAL(vec[0].v1, true);
TEST_EQUAL(vec[0].v2, 584);
TEST_EQUAL(vec[0].v3, 12418651);
TEST_EQUAL(vec[1].v0, 79);
TEST_EQUAL(vec[1].v1, false);
TEST_EQUAL(vec[1].v2, 2100);
TEST_EQUAL(vec[1].v3, 4248613);
return 0;
};
| 16.782609 | 43 | 0.629246 | PredatorCZ |
6dd61215a03808129af6ffdebc0b22c3935b2318 | 3,694 | cc | C++ | biod/biod_metrics_test.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 5 | 2019-01-19T15:38:48.000Z | 2021-10-06T03:59:46.000Z | biod/biod_metrics_test.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | null | null | null | biod/biod_metrics_test.cc | emersion/chromiumos-platform2 | ba71ad06f7ba52e922c647a8915ff852b2d4ebbd | [
"BSD-3-Clause"
] | 1 | 2019-02-15T23:05:30.000Z | 2019-02-15T23:05:30.000Z | // Copyright 2018 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <base/macros.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <metrics/metrics_library_mock.h>
#include "biod/biod_metrics.h"
using ::testing::_;
namespace biod {
namespace {
class BiodMetricsTest : public testing::Test {
protected:
BiodMetricsTest() {
biod_metrics_.SetMetricsLibraryForTesting(
std::make_unique<MetricsLibraryMock>());
}
~BiodMetricsTest() override = default;
MetricsLibraryMock* GetMetricsLibraryMock() {
return static_cast<MetricsLibraryMock*>(
biod_metrics_.metrics_library_for_testing());
}
BiodMetrics biod_metrics_;
private:
DISALLOW_COPY_AND_ASSIGN(BiodMetricsTest);
};
TEST_F(BiodMetricsTest, SendEnrolledFingerCount) {
const int finger_count = 2;
EXPECT_CALL(*GetMetricsLibraryMock(), SendEnumToUMA(_, finger_count, _))
.Times(1);
biod_metrics_.SendEnrolledFingerCount(finger_count);
}
TEST_F(BiodMetricsTest, SendFpUnlockEnabled) {
EXPECT_CALL(*GetMetricsLibraryMock(), SendBoolToUMA(_, true)).Times(1);
EXPECT_CALL(*GetMetricsLibraryMock(), SendBoolToUMA(_, false)).Times(1);
biod_metrics_.SendFpUnlockEnabled(true);
biod_metrics_.SendFpUnlockEnabled(false);
}
TEST_F(BiodMetricsTest, SendFpLatencyStatsOnMatch) {
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpMatchDurationCapture, _, _, _, _))
.Times(1);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpMatchDurationMatcher, _, _, _, _))
.Times(1);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpMatchDurationOverall, _, _, _, _))
.Times(1);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpNoMatchDurationCapture, _, _, _, _))
.Times(0);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpNoMatchDurationMatcher, _, _, _, _))
.Times(0);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpNoMatchDurationOverall, _, _, _, _))
.Times(0);
biod_metrics_.SendFpLatencyStats(true, 0, 0, 0);
}
TEST_F(BiodMetricsTest, SendFpLatencyStatsOnNoMatch) {
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpMatchDurationCapture, _, _, _, _))
.Times(0);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpMatchDurationMatcher, _, _, _, _))
.Times(0);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpMatchDurationOverall, _, _, _, _))
.Times(0);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpNoMatchDurationCapture, _, _, _, _))
.Times(1);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpNoMatchDurationMatcher, _, _, _, _))
.Times(1);
EXPECT_CALL(*GetMetricsLibraryMock(),
SendToUMA(metrics::kFpNoMatchDurationOverall, _, _, _, _))
.Times(1);
biod_metrics_.SendFpLatencyStats(false, 0, 0, 0);
}
TEST_F(BiodMetricsTest, SendFpLatencyStatsValues) {
const int capture = 70;
const int matcher = 187;
const int overall = 223;
EXPECT_CALL(*GetMetricsLibraryMock(), SendToUMA(_, capture, _, _, _))
.Times(2);
EXPECT_CALL(*GetMetricsLibraryMock(), SendToUMA(_, matcher, _, _, _))
.Times(2);
EXPECT_CALL(*GetMetricsLibraryMock(), SendToUMA(_, overall, _, _, _))
.Times(2);
biod_metrics_.SendFpLatencyStats(true, capture, matcher, overall);
biod_metrics_.SendFpLatencyStats(false, capture, matcher, overall);
}
} // namespace
} // namespace biod
| 33.581818 | 74 | 0.700596 | emersion |
6dd835d8b2e4ceaab87e1ac475894dc2c3cead8a | 12,243 | cpp | C++ | Blech/test.cpp | Natedog2012/dll | 5fb9414a5ebddf9c37809517eaf378a26b422d61 | [
"MIT"
] | 3 | 2021-06-25T00:03:25.000Z | 2021-11-30T19:45:27.000Z | Blech/test.cpp | Natedog2012/dll | 5fb9414a5ebddf9c37809517eaf378a26b422d61 | [
"MIT"
] | null | null | null | Blech/test.cpp | Natedog2012/dll | 5fb9414a5ebddf9c37809517eaf378a26b422d61 | [
"MIT"
] | 3 | 2021-09-21T23:33:31.000Z | 2022-02-18T08:13:20.000Z | #include "Blech.h"
#define CheckOne(ID) \
if (nevent != 1) { \
printf("bad event count %d != 1\n", nevent); \
exit(1); \
} \
if (eventarray[0].id != ID) { \
printf("bad event %d != " #ID "\n", eventarray[0].id); \
exit(1); \
}
struct {
int id, nvalues;
char name[50][100];
char value[50][100];
} eventarray[20];
int nevent = 0;
void __stdcall MyEvent(unsigned long ID, void *pData, PBLECHVALUE pValues)
{
int i = 0;
printf("MyEvent(%d,%d,%X)\n", ID, pData, pValues);
eventarray[nevent].id = (int) pData;
while (pValues) {
printf("\t'%s'=>'%s'\n", pValues->Name, pValues->Value);
strcpy(eventarray[nevent].name[i], pValues->Name);
strcpy(eventarray[nevent].value[i], pValues->Value);
i++;
pValues = pValues->pNext;
}
eventarray[nevent].nvalues = i;
printf("\n");
nevent++;
}
main()
{
Blech b('#');
int j = 0, i = 0, eventid[200];
for (int x = 0; x < 2; x++) {
eventid[i++] = b.AddEvent("Text with #variable# portion", MyEvent, (void *) 0);
eventid[i++] = b.AddEvent("#*#Text with #variable# portion", MyEvent, (void *) 1);
eventid[i++] = b.AddEvent("thisshouldnevertrigger", MyEvent, (void *) 2);
eventid[i++] = b.AddEvent("#*#while stunned#*#", MyEvent, (void *) 3);
eventid[i++] = b.AddEvent("#*#has been slain#*#", MyEvent, (void *) 4);
eventid[i++] = b.AddEvent("#*#gain experience!#*#", MyEvent, (void *) 5);
eventid[i++] = b.AddEvent("#*#Insufficient mana#*#", MyEvent, (void *) 6);
eventid[i++] = b.AddEvent("[MQ2] getout", MyEvent, (void *) 7);
eventid[i++] = b.AddEvent("#*#target is out of range#*#", MyEvent, (void *) 8);
eventid[i++] = b.AddEvent("You cannot see#*#", MyEvent, (void *) 9);
eventid[i++] =
b.AddEvent("#*#Returning to home point, please wait...#*#", MyEvent, (void *) 10);
eventid[i++] = b.AddEvent("#*#you have been slain#*#", MyEvent, (void *) 11);
eventid[i++] = b.AddEvent("#*#You have entered#*#", MyEvent, (void *) 12);
eventid[i++] = b.AddEvent("The shield fades away.", MyEvent, (void *) 13);
eventid[i++] = b.AddEvent("The maelstrom dissipates.", MyEvent, (void *) 14);
eventid[i++] = b.AddEvent("You have been summoned!", MyEvent, (void *) 15);
eventid[i++] = b.AddEvent("#*# YOU for #*#", MyEvent, (void *) 16);
eventid[i++] = b.AddEvent("#*# YOU, but #*#", MyEvent, (void *) 17);
eventid[i++] = b.AddEvent("[MQ2] nuke1 #1#", MyEvent, (void *) 18);
eventid[i++] = b.AddEvent("[MQ2] nuke2 #1#", MyEvent, (void *) 19);
eventid[i++] = b.AddEvent("[MQ2] domodrod", MyEvent, (void *) 20);
eventid[i++] = b.AddEvent("[MQ2] conc", MyEvent, (void *) 21);
eventid[i++] = b.AddEvent("[MQ2] concnum #1#", MyEvent, (void *) 22);
eventid[i++] = b.AddEvent("[MQ2] myfamiliar #1#", MyEvent, (void *) 23);
eventid[i++] = b.AddEvent("[MQ2] mainnukenum #1#", MyEvent, (void *) 24);
eventid[i++] = b.AddEvent("[MQ2] endnukenum #1#", MyEvent, (void *) 25);
eventid[i++] = b.AddEvent("[MQ2] maxbuffs #1#", MyEvent, (void *) 26);
eventid[i++] = b.AddEvent("[MQ2] mobhealth #1#", MyEvent, (void *) 27);
eventid[i++] = b.AddEvent("[MQ2] staffhealth #1#", MyEvent, (void *) 28);
eventid[i++] = b.AddEvent("[MQ2] stopnuke #1#", MyEvent, (void *) 29);
eventid[i++] = b.AddEvent("[MQ2] stopnuke2 #1#", MyEvent, (void *) 30);
eventid[i++] = b.AddEvent("[MQ2] engagedistance #1#", MyEvent, (void *) 31);
eventid[i++] = b.AddEvent("[MQ2] assist", MyEvent, (void *) 32);
eventid[i++] = b.AddEvent("[MQ2] doxuzl", MyEvent, (void *) 33);
eventid[i++] = b.AddEvent("[MQ2] manarobe", MyEvent, (void *) 34);
eventid[i++] = b.AddEvent("[MQ2] xuzlperc #1#", MyEvent, (void *) 35);
eventid[i++] = b.AddEvent("[MQ2] temp", MyEvent, (void *) 36);
eventid[i++] = b.AddEvent("[MQ2] dosnare", MyEvent, (void *) 37);
eventid[i++] = b.AddEvent("[MQ2] snareperc #1#", MyEvent, (void *) 38);
eventid[i++] = b.AddEvent("[MQ2] ss", MyEvent, (void *) 39);
eventid[i++] = b.AddEvent("[MQ2] mw", MyEvent, (void *) 40);
eventid[i++] = b.AddEvent("[MQ2] timewand", MyEvent, (void *) 41);
eventid[i++] = b.AddEvent("[MQ2] epic", MyEvent, (void *) 42);
eventid[i++] = b.AddEvent("[MQ2] forceshield", MyEvent, (void *) 43);
eventid[i++] = b.AddEvent("[MQ2] autosit", MyEvent, (void *) 44);
eventid[i++] = b.AddEvent("[MQ2] som", MyEvent, (void *) 45);
eventid[i++] = b.AddEvent("[MQ2] ma #1#", MyEvent, (void *) 46);
eventid[i++] = b.AddEvent("[MQ2] sa #1#", MyEvent, (void *) 47);
eventid[i++] = b.AddEvent("[MQ2] ta #1#", MyEvent, (void *) 48);
eventid[i++] = b.AddEvent("[MQ2] cycle", MyEvent, (void *) 49);
eventid[i++] = b.AddEvent("The magical barrier fades #*#", MyEvent, (void *) 50);
eventid[i++] = b.AddEvent("The blue aura fades #*#", MyEvent, (void *) 51);
eventid[i++] = b.AddEvent("[MQ2] exclude #*#", MyEvent, (void *) 52);
eventid[i++] = b.AddEvent("[MQ2] include #*#", MyEvent, (void *) 53);
eventid[i++] = b.AddEvent("[MQ2] addmaster #*#", MyEvent, (void *) 54);
eventid[i++] = b.AddEvent("[MQ2] delmaster #*#", MyEvent, (void *) 55);
eventid[i++] = b.AddEvent("[MQ2] addjunk #*#", MyEvent, (void *) 56);
eventid[i++] = b.AddEvent("[MQ2] deljunk #*#", MyEvent, (void *) 57);
eventid[i++] = b.AddEvent("[MQ2] pause", MyEvent, (void *) 58);
eventid[i++] = b.AddEvent("[MQ2] itemset #1# #2# #3#", MyEvent, (void *) 59);
eventid[i++] = b.AddEvent("[MQ2] itembounce #1# #2#", MyEvent, (void *) 60);
eventid[i++] = b.AddEvent("[MQ2] itemcast #1#", MyEvent, (void *) 61);
eventid[i++] = b.AddEvent("[MQ2] leash#*#", MyEvent, (void *) 62);
eventid[i++] = b.AddEvent("[MQ2] autofollow#*#", MyEvent, (void *) 63);
eventid[i++] = b.AddEvent("[MQ2] stopfollow#*#", MyEvent, (void *) 64);
eventid[i++] = b.AddEvent("[MQ2] afhelp", MyEvent, (void *) 65);
eventid[i++] = b.AddEvent("[MQ2] nukepause #*#", MyEvent, (void *) 66);
eventid[i++] = b.AddEvent("[MQ2] doharvest", MyEvent, (void *) 67);
eventid[i++] = b.AddEvent("[MQ2] harvestperc #1#", MyEvent, (void *) 68);
eventid[i++] = b.AddEvent("[MQ2] medtoggle", MyEvent, (void *) 69);
eventid[i++] = b.AddEvent("[MQ2] dopreconc", MyEvent, (void *) 70);
eventid[i++] = b.AddEvent("[MQ2] dopreconcxxxxx", MyEvent, (void *) 71);
eventid[i++] = b.AddEvent("[MQ2] preconcnum #1#", MyEvent, (void *) 72);
eventid[i++] = b.AddEvent("[MQ2] tlocate #*#", MyEvent, (void *) 73);
eventid[i++] = b.AddEvent("[MQ2] getout", MyEvent, (void *) 74);
eventid[i++] = b.AddEvent("You gain#*#", MyEvent, (void *) 75);
eventid[i++] = b.AddEvent("[MQ2] SetPCRadius#*#", MyEvent, (void *) 76);
eventid[i++] = b.AddEvent("[MQ2] SetNPCRadius#*#", MyEvent, (void *) 77);
eventid[i++] = b.AddEvent("[MQ2] Autoassist#*#", MyEvent, (void *) 78);
eventid[i++] = b.AddEvent("[MQ2] AutoTargetSwitch#*#", MyEvent, (void *) 79);
eventid[i++] = b.AddEvent("[MQ2] AutoTraps#*#", MyEvent, (void *) 80);
eventid[i++] = b.AddEvent("#1# begins to cast a spell.", MyEvent, (void *) 81);
eventid[i++] = b.AddEvent("#1# hits you for #2# damage.", MyEvent, (void *) 82);
nevent = 0;
b.Feed("[MQ2] Autoassist your mom");
CheckOne(78);
nevent = 0;
b.Feed("Text with extra bits of portion");
if (nevent != 2) {
printf("bad event count %d != 2\n", nevent);
exit(1);
}
if ((eventarray[0].id != 0) && (eventarray[0].id != 1)) {
printf("wrong events triggerd %d -- not 0 or 1\n", eventarray[0].id);
exit(1);
}
nevent = 0;
b.Feed("notText with extra bits of portion");
CheckOne(1);
nevent = 0;
b.Feed("[MQ2] maxbuffs 145");
CheckOne(26);
if (eventarray[0].nvalues != 1) {
printf("bad value count %d != 1\n", eventarray[0].nvalues);
exit(1);
}
if (strcmp(eventarray[0].name[0], "1")) {
printf("bad value name '%s' != 1\n", eventarray[0].name[0]);
exit(1);
}
if (strcmp(eventarray[0].value[0], "145")) {
printf("bad value value '%s' != 145\n", eventarray[0].value[0]);
exit(1);
}
nevent = 0;
b.Feed("The magical barrier fades yourmoma");
CheckOne(50);
if (eventarray[0].nvalues != 1) {
printf("bad value count %d != 1\n", eventarray[0].nvalues);
exit(1);
}
if (strcmp(eventarray[0].name[0], "*")) {
printf("bad value name '%s' != *\n", eventarray[0].name[0]);
exit(1);
}
if (strcmp(eventarray[0].value[0], "yourmoma")) {
printf("bad value value '%s' != yourmoma\n", eventarray[0].value[0]);
exit(1);
}
nevent = 0;
b.Feed("[MQ2] afhelp");
CheckOne(65);
nevent = 0;
b.Feed("[MQ2] ma 1");
CheckOne(46);
nevent = 0;
b.Feed("You can use the ability Fellstrike Discipline again in 20 minute(s) 19 seconds.");
if (nevent != 0) {
printf("bad event count %d != 0\n", nevent);
exit(1);
}
nevent = 0;
b.Feed("[MQ2] SetPCRadius");
CheckOne(76);
nevent = 0;
b.Feed("[MQ2] SetNPCRadius");
CheckOne(77);
nevent = 0;
b.Feed("[MQ2] itemset 3 2 1");
CheckOne(59);
if (eventarray[0].nvalues != 3) {
printf("bad value count %d != 3\n", eventarray[0].nvalues);
exit(1);
}
if (strcmp(eventarray[0].name[0], "1")) {
printf("bad value name0 '%s' != 1\n", eventarray[0].name[0]);
exit(1);
}
if (strcmp(eventarray[0].value[0], "3")) {
printf("bad value value '%s' != 3\n", eventarray[0].value[0]);
exit(1);
}
if (strcmp(eventarray[0].name[1], "2")) {
printf("bad value name1 '%s' != 2\n", eventarray[0].name[1]);
exit(1);
}
if (strcmp(eventarray[0].value[1], "2")) {
printf("bad value value '%s' != 2\n", eventarray[0].value[1]);
exit(1);
}
if (strcmp(eventarray[0].name[2], "3")) {
printf("bad value name2 '%s' != 3\n", eventarray[0].name[2]);
exit(1);
}
if (strcmp(eventarray[0].value[2], "1")) {
printf("bad value value '%s' != 1\n", eventarray[0].value[2]);
exit(1);
}
nevent = 0;
b.Feed("a mob with space in name begins to cast a spell.");
CheckOne(81);
if (eventarray[0].nvalues != 1) {
printf("bad value count %d != 1\n", eventarray[0].nvalues);
exit(1);
}
if (strcmp(eventarray[0].name[0], "1")) {
printf("bad value name '%s' != 1\n", eventarray[0].name[0]);
exit(1);
}
if (strcmp(eventarray[0].value[0], "a mob with space in name")) {
printf("bad value value '%s' != 'a mob with space in name'\n", eventarray[0].value[0]);
exit(1);
}
nevent = 0;
b.Feed("a mob hits you for lots of damage.");
if (nevent != 2) {
printf("bad event count %d != 2\n", nevent);
exit(1);
}
if (strcmp(eventarray[1].name[0], "1")) {
printf("bad value name0 '%s' != 1\n", eventarray[1].name[0]);
exit(1);
}
if (strcmp(eventarray[1].value[0], "a mob")) {
printf("bad value value '%s' != a mob\n", eventarray[1].value[0]);
exit(1);
}
if (strcmp(eventarray[1].name[1], "2")) {
printf("bad value name1 '%s' != 2\n", eventarray[1].name[1]);
exit(1);
}
if (strcmp(eventarray[1].value[1], "lots of")) {
printf("bad value value '%s' != lots of\n", eventarray[1].value[1]);
exit(1);
}
nevent = 0;
b.Feed("A bat hits you for 4 damage.");
if (nevent != 2) {
printf("bad event count %d != 2\n", nevent);
exit(1);
}
if (eventarray[1].nvalues != 2) {
printf("bad value count %d != 2\n", eventarray[1].nvalues);
exit(1);
}
if (strcmp(eventarray[1].name[0], "1")) {
printf("bad value name0 '%s' != 1\n", eventarray[1].name[0]);
exit(1);
}
if (strcmp(eventarray[1].value[0], "A bat")) {
printf("bad value value '%s' != A bat\n", eventarray[1].value[0]);
exit(1);
}
if (strcmp(eventarray[1].name[1], "2")) {
printf("bad value name1 '%s' != 2\n", eventarray[1].name[1]);
exit(1);
}
if (strcmp(eventarray[1].value[1], "4")) {
printf("bad value value '%s' != 4\n", eventarray[1].value[1]);
exit(1);
}
// watch j is not initialized here
for (; j < i; j++) {
if (eventid[j]) {
if (!b.RemoveEvent(eventid[j])) {
printf("removal failed %d\n", j);
exit(1);
}
} else {
printf("no event for %d\n", j);
}
}
}
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
printf("!!!!!!!!!!!!!!! SUCCESS !!!!!!!!!!!!!!!!!!!\n");
}
| 38.140187 | 92 | 0.561545 | Natedog2012 |
6dd949923b519bb644499f87f79e451863782278 | 10,904 | cpp | C++ | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/DistributedSPOSet.cpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 55 | 2015-07-28T01:32:58.000Z | 2022-02-27T16:27:46.000Z | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/DistributedSPOSet.cpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 66 | 2015-06-15T20:38:19.000Z | 2020-08-26T00:11:43.000Z | test/performance-regression/full-apps/qmcpack/src/QMCWaveFunctions/DistributedSPOSet.cpp | JKChenFZ/hclib | 50970656ac133477c0fbe80bb674fe88a19d7177 | [
"BSD-3-Clause"
] | 26 | 2015-10-26T22:11:51.000Z | 2021-03-02T22:09:15.000Z | //////////////////////////////////////////////////////////////////
// (c) Copyright 2007- by Jeongnim Kim
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////
// National Center for Supercomputing Applications &
// Materials Computation Center
// University of Illinois, Urbana-Champaign
// Urbana, IL 61801
// e-mail: jnkim@ncsa.uiuc.edu
//
// Supported by
// National Center for Supercomputing Applications, UIUC
// Materials Computation Center, UIUC
//////////////////////////////////////////////////////////////////
// -*- C++ -*-
#include "QMCWaveFunctions/DistributedSPOSet.h"
//this will go into cmake
#define MAX_NUM_SHARED_NODES 8
#define PSI_DIM 5
namespace qmcplusplus
{
///constructor
DistributedSPOSet::DistributedSPOSet(int norbs=0)
{
setOrbitalSetSize(norbs);
}
DistributedSPOSet::~DistributedSPOSet()
{
delete_iter(SendBuffer.begin(),SendBuffer.end());
delete_iter(RecvBuffer.begin(),RecvBuffer.end());
}
void DistributedSPOSet::setCommunicator(Communicate* c)
{
if(myComm && myComm == c)
{
app_log() << " Identical communicator. Nothing to be done in ScalarEstimatorManager::setCommunicator." << endl;
return;
}
if(c)
myComm=c;
else
myComm = OHMMS::Controller;
int ncontexts=myComm->ncontexts();
Rnow.resize(OrbitalSetSize);
//divide orbitals among the processors
OrbitalCount.resize(ncontexts);
OrbitalOffset.resize(ncontexts+1);
FairDivideLow(OrbitalSetSize,ncontexts,OrbitalOffSet);
for(int i=0; i<ncontexts; i++)
OrbitalCount[i]=OrbitalOffset[i+1]-OrbitalOffset[i];
NumRemoteNodes=ncontexts-1;
if(RemoteNodes.empty())//cannot do it again
{
RemoteNodes.resize(NumRemoteNodes);
SendBuffer.resize(ncontexts,0);
RecvBuffer.resize(ncontexts,0);
for(int i=0, r=0; i<=NumRemoteNodes; i++)
{
if(i == myNodeID)
{
SendBuffer[i]=new BufferType;
RecvBuffer[i]=new BufferType;
}
else
{
RemonteNodes[r++]=i;
SendBuffer[i]=new BufferType(OrbitalCount[i]*OrbitalSetSize*PSI_DIM);
RecvBuffer[i]=new BufferType(OrbitalCount[i]*OrbitalSetSize*PSI_DIM);
}
}
}
}
void DistributedSPOSet::setOrbitalSetSize(int norbs)
{
if(norbs == OrbitalSetSize )
return;
OrbitalSetSize=norbs;
BasisSetSize=norbs;
}
void DistributedSPOSet::resetParameters(VarRegistry<RealType>& optVariables)
{
Phi->resetParameters(optVariables);
}
void DistributedSPOSet::resetTargetParticleSet(ParticleSet& P)
{
Phi->resetTargetParticleSet(P);
}
void
DistributedSPOSet::evaluate(const ParticleSet& P, int iat, ValueVector_t& psi)
{
CommunicatorTraits::mpi_request_type sendPos[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_request_type recvPsi[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_request_type sendPsi[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_status_type statusPos[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_status_type statusPsi[MAX_NUM_SHARED_NODES];
PosType pos(P[iat]);
//send the current position and start recv
for(int p=0; p<NumRemoteNodes; p++)
{
int target=RemoteNodes[p];
MPI_Isend(pos.begin(), OHMMS_DIM, MPI_DOUBLE, target, PosTag, myComm->getMPI(), &(sendPos[p]));
MPI_Irecv(RecvBuffer[target]->data(), OrbitalCount[target], target, PsiTag, myComm->getMPI(),&(recvPsi[p]));
}
ValueVector_t psiL(OrbitalCount[myNodeID]);
//do the local calculation
Phi->evaluate(pos,psiL);
std::copy(psiL.begin(),psiL.end(),psi.begin()+OrbitalOffset[myNodeID]);
//can make waitsome
int err=MPI_Waitall(NumRemoteNodes, sendPos,statusPos);
//do the calculation with the positions recv and send back the orbitals
for(int p=0; p<NumRemoteNodes; p++)
{
int target=RemoteNodes[p];
//matching recv with MPI_Isend
MPI_recv(Rnow[p].data(), OHMMS_DIM, MPI_DOUBLE, target, PosTag, myNodeID,myComm->getMPI(),&(statusPos[p]));
//calculate with a position
Phi->evaluate(Rnow[p],psiL);
//pack the message
SendBuffer[p]->rewind();
SendBuffer[p]->put(psiL.begin(),psiL.end());
//send the wavefunction matching ready-send with MPI_Irecv
MPI_Irsend(SendBuffer[p]->data(), OrbitalCount[myNodeID], MPI_DOUBLE, target, PsiTag, myComm->getMPI(), &(sendPsi[p]));
}
int nm=NumRemoteNodes;
while(nm)
{
int count =0;
int err=MPI_Testsome(NumRemoteNodes,recvPsi,&count,statusPsi);
for(int m=0; m<count; m++)
{
int source=statusPsi[m].MPI_SOURCE;
RecvBuffer[source]->rewind();
for(int t=OrbitalOffset[source]; t<OrbitalOffset[source+1]; t++)
RecvBuffer[source]->get(psi[t]);
}
nm-=count;
}
err=MPI_Waitall(NumRemoteNodes, sendPsi,statusPsi);
}
void
DistributedSPOSet::evaluate(const ParticleSet& P, int iat,
ValueVector_t& psi, GradVector_t& dpsi, ValueVector_t& d2psi)
{
CommunicatorTraits::mpi_request_type sendPos[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_request_type recvPsi[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_request_type sendPsi[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_status_type statusPos[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_status_type statusPsi[MAX_NUM_SHARED_NODES];
PosType pos(P[iat]);
//send the current position and start recv
for(int p=0; p<NumRemoteNodes; p++)
{
int target=RemoteNodes[p];
MPI_Isend(pos.data(), OHMMS_DIM, MPI_DOUBLE, target, PosTag, myComm->getMPI(), &(sendPos[p]));
MPI_Irecv(RecvBuffer[target]->data(), PSI_DIM*OrbitalCount[target], target, PsiTag, myComm->getMPI(),&(recvPsi[p]));
}
ValueVector_t psiL(OrbitalCount[myNodeID]);
GradVector_t dpsiL(OrbitalCount[myNodeID]);
ValueVector_t p2siL(OrbitalCount[myNodeID]);
//do the local calculation
Phi->evaluate(pos,psiL,dpsiL,d2psiL);
std::copy(psiL.begin(),psiL.end(),psi.begin()+OrbitalOffset[myNoodeID]);
std::copy(dpsiL.begin(),dpsiL.end(),dpsi.begin()+OrbitalOffset[myNoodeID]);
std::copy(d2psiL.begin(),d2psiL.end(),d2psi.begin()+OrbitalOffset[myNoodeID]);
int err=MPI_Waitall(NumRemoteNodes, sendPos,statusPos);
int ngd=OrbitalCount[myNodeID]*OHMMS_DIM;
//do the calculation with the positions recv and send back the orbitals
for(int p=0; p<NumRemoteNodes; p++)
{
int target=RemoteNodes[p];
//matching recv with MPI_Isend
MPI_recv(Rnow[p].data(), OHMMS_DIM, MPI_DOUBLE, target, PosTag, myNodeID,myComm->getMPI(),&(statusPos[p]));
//do the local calculation
Phi->evaluate(Rnow[p],psiL,dpsiL,d2psiL);
//pack the message
SendBuffer[p]->rewind();
for(int i=0; i<OrbitalCount[target]; i++)
{
SendBuffer[p]->put(psiL[i]);
SendBuffer[p]->put(dpsiL[i].begin(),dpsiL[i].end());
SendBuffer[p]->put(d2dpsiL[i]);
}
//send the wavefunction matching ready-send with MPI_Irecv
MPI_Irsend(SendBuffer[p]->data(), PSI_DIM*OrbitalCount[target], MPI_DOUBLE, target, PsiTag, myComm->getMPI(), &(sendPsi[p]));
}
int nm=NumRemoteNodes,count;
while(nm)
{
int err=MPI_Testsome(NumRemoteNodes,recvPsi,&count,statusPsi);
for(int m=0; m<count; m++)
{
int source=statusPsi[m].MPI_SOURCE;
RecvBuffer[source]->rewind();
for(int t=OrbitalOffset[source]; t<OrbitalOffset[source+1]; t++)
{
RecvBuffer[source]->get(psi[t]);
RecvBuffer[source]->get(dpsi[t].begin(),dpsi[t].end());
RecvBuffer[source]->get(d2psi[t]);
}
}
nm-=count;
}
err=MPI_Waitall(NumRemoteNodes, sendPsi,statusPsi);
}
void DistributedSPOSet::evaluate_notranspose(const ParticleSet& P, int first, int last,
ValueMatrix_t& logdet, GradMatrix_t& dlogdet, ValueMatrix_t& d2logdet)
{
CommunicatorTraits::mpi_request_type sendPos[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_request_type recvPsi[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_request_type sendPsi[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_status_type statusPos[MAX_NUM_SHARED_NODES];
CommunicatorTraits::mpi_status_type statusPsi[MAX_NUM_SHARED_NODES];
int nat=last-first;
vector<PosType> pos(nat);
for(int iat=first,i=0; iat<last; iat++,i++)
pos[i]=P.R[iat];
//send the current position and start recv
for(int p=0; p<NumRemoteNodes; p++)
{
int target=RemoteNodes[p];
MPI_Isend(&(pos[0][0]), nat*OHMMS_DIM, MPI_DOUBLE, target, PosTag, myComm->getMPI(), &(sendPos[p]));
MPI_Irecv(RecvBuffer[target]->data(), nat*PSI_DIM*OrbitalCount[target], target, PsiTag, myComm->getMPI(),&(recvPsi[p]));
}
ValueVector_t psiL(OrbitalCount[myNodeID]);
GradVector_t dpsiL(OrbitalCount[myNodeID]);
ValueVector_t p2siL(OrbitalCount[myNodeID]);
for(int i=0; i<nat; i++)
{
//do the local calculation
Phi->evaluate_notranspose(pos[i],psiL,dpsiL,d2psiL);
//use std::copy
for(int jc=0,j=OrbitalOffset[myNoodeID]; jc<OrbitalCount[myNodeID]; jc++,j++)
{
//logdet(j,i)=psiL[jc];
logdet(i,j)=psiL[jc];
dlogdet(i,j)=dpsiL[jc];
d2logdet(i,j)=d2psiL[jc];
}
}
int err=MPI_Waitall(NumRemoteNodes, sendPos,statusPos);
//do the calculation with the positions recv and send back the orbitals
for(int p=0; p<NumRemoteNodes; p++)
{
int target=RemoteNodes[p];
//matching recv with MPI_Isend
MPI_recv(Rnow[0].data(), nat*OHMMS_DIM, MPI_DOUBLE, target, PosTag, myComm->getMPI(),&(statusPos[p]));
//evaluate for the target node
SendBuffer[p]->rewind();
for(int i=0; i<nat; i++)
{
Phi->evaluate_notranspose(Rnow[i],psiL,dpsiL,d2psiL);
for(int j=0; j<OrbitalCount[target]; j++)
{
SendBuffer[p]->put(psiL[j]);
SendBuffer[p]->put(dpsiL[j].begin(),dpsiL[j].end());
SendBuffer[p]->put(d2dpsiL[j]);
}
}
//send the wavefunction matching ready-send with MPI_Irecv
MPI_Irsend(SendBuffer[p]->data(), nat*PSI_DIM*OrbitalCount[target], MPI_DOUBLE, target, PsiTag, myComm->getMPI(), &(sendPsi[p]));
}
int nm=NumRemoteNodes,count;
while(nm)
{
int err=MPI_Testsome(NumRemoteNodes,recvPsi,&count,statusPsi);
for(int m=0; m<count; m++)
{
int source=statusPsi[m].MPI_SOURCE;
RecvBuffer[source]->rewind();
for(int i=0; i<nat; i++)
{
for(int t=OrbitalOffset[source]; t<OrbitalOffset[source+1]; t++)
{
RecvBuffer[source]->get(logdet(i,t));
//RecvBuffer[source]->get(logdet(t,i));
RecvBuffer[source]->get(dlogdet(i,t).begin(),dlogdet(i,t).end());
RecvBuffer[source]->get(d2logdet(i,t));
}
}
}
nm-=count;
}
err=MPI_Waitall(NumRemoteNodes, sendPsi,statusPsi);
}
}
/***************************************************************************
* $RCSfile$ $Author: jnkim $
* $Revision: 1772 $ $Date: 2007-02-17 17:47:37 -0600 (Sat, 17 Feb 2007) $
* $Id: DistributedSPOSet.cpp 1772 2007-02-17 23:47:37Z jnkim $
***************************************************************************/
| 36.225914 | 133 | 0.665994 | JKChenFZ |
6dd974d999d6486106b97a0b6126262f0e5add38 | 72,627 | cc | C++ | RecoLocalCalo/CaloTowersCreator/src/CaloTowersCreationAlgo.cc | malbouis/cmssw | 16173a30d3f0c9ecc5419c474bb4d272c58b65c8 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | RecoLocalCalo/CaloTowersCreator/src/CaloTowersCreationAlgo.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | RecoLocalCalo/CaloTowersCreator/src/CaloTowersCreationAlgo.cc | gartung/cmssw | 3072dde3ce94dcd1791d778988198a44cde02162 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "CaloTowersCreationAlgo.h"
#include "Geometry/CaloTopology/interface/HcalTopology.h"
#include "Geometry/CaloTopology/interface/CaloTowerTopology.h"
#include "Geometry/CaloTopology/interface/CaloTowerConstituentsMap.h"
#include "Geometry/CaloGeometry/interface/CaloCellGeometry.h"
#include "Geometry/CaloGeometry/interface/CaloSubdetectorGeometry.h"
#include "Geometry/CaloGeometry/interface/CaloGeometry.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "Math/Interpolator.h"
#include <cmath>
//#define EDM_ML_DEBUG
CaloTowersCreationAlgo::CaloTowersCreationAlgo()
: theEBthreshold(-1000.),
theEEthreshold(-1000.),
theUseEtEBTresholdFlag(false),
theUseEtEETresholdFlag(false),
theUseSymEBTresholdFlag(false),
theUseSymEETresholdFlag(false),
theHcalThreshold(-1000.),
theHBthreshold(-1000.),
theHBthreshold1(-1000.),
theHBthreshold2(-1000.),
theHESthreshold(-1000.),
theHESthreshold1(-1000.),
theHEDthreshold(-1000.),
theHEDthreshold1(-1000.),
theHOthreshold0(-1000.),
theHOthresholdPlus1(-1000.),
theHOthresholdMinus1(-1000.),
theHOthresholdPlus2(-1000.),
theHOthresholdMinus2(-1000.),
theHF1threshold(-1000.),
theHF2threshold(-1000.),
theEBGrid(std::vector<double>(5, 10.)),
theEBWeights(std::vector<double>(5, 1.)),
theEEGrid(std::vector<double>(5, 10.)),
theEEWeights(std::vector<double>(5, 1.)),
theHBGrid(std::vector<double>(5, 10.)),
theHBWeights(std::vector<double>(5, 1.)),
theHESGrid(std::vector<double>(5, 10.)),
theHESWeights(std::vector<double>(5, 1.)),
theHEDGrid(std::vector<double>(5, 10.)),
theHEDWeights(std::vector<double>(5, 1.)),
theHOGrid(std::vector<double>(5, 10.)),
theHOWeights(std::vector<double>(5, 1.)),
theHF1Grid(std::vector<double>(5, 10.)),
theHF1Weights(std::vector<double>(5, 1.)),
theHF2Grid(std::vector<double>(5, 10.)),
theHF2Weights(std::vector<double>(5, 1.)),
theEBweight(1.),
theEEweight(1.),
theHBweight(1.),
theHESweight(1.),
theHEDweight(1.),
theHOweight(1.),
theHF1weight(1.),
theHF2weight(1.),
theEcutTower(-1000.),
theEBSumThreshold(-1000.),
theEESumThreshold(-1000.),
theEBEScale(50.),
theEEEScale(50.),
theHBEScale(50.),
theHESEScale(50.),
theHEDEScale(50.),
theHOEScale(50.),
theHF1EScale(50.),
theHF2EScale(50.),
theHcalTopology(nullptr),
theGeometry(nullptr),
theTowerConstituentsMap(nullptr),
theHcalAcceptSeverityLevel(0),
theRecoveredHcalHitsAreUsed(false),
theRecoveredEcalHitsAreUsed(false),
useRejectedHitsOnly(false),
theHcalAcceptSeverityLevelForRejectedHit(0),
useRejectedRecoveredHcalHits(0),
useRejectedRecoveredEcalHits(0),
missingHcalRescaleFactorForEcal(0.),
theHOIsUsed(true),
// (for momentum reconstruction algorithm)
theMomConstrMethod(0),
theMomHBDepth(0.),
theMomHEDepth(0.),
theMomEBDepth(0.),
theMomEEDepth(0.),
theHcalPhase(0) {}
CaloTowersCreationAlgo::CaloTowersCreationAlgo(double EBthreshold,
double EEthreshold,
bool useEtEBTreshold,
bool useEtEETreshold,
bool useSymEBTreshold,
bool useSymEETreshold,
double HcalThreshold,
double HBthreshold,
double HBthreshold1,
double HBthreshold2,
double HESthreshold,
double HESthreshold1,
double HEDthreshold,
double HEDthreshold1,
double HOthreshold0,
double HOthresholdPlus1,
double HOthresholdMinus1,
double HOthresholdPlus2,
double HOthresholdMinus2,
double HF1threshold,
double HF2threshold,
double EBweight,
double EEweight,
double HBweight,
double HESweight,
double HEDweight,
double HOweight,
double HF1weight,
double HF2weight,
double EcutTower,
double EBSumThreshold,
double EESumThreshold,
bool useHO,
// (momentum reconstruction algorithm)
int momConstrMethod,
double momHBDepth,
double momHEDepth,
double momEBDepth,
double momEEDepth,
int hcalPhase)
: theEBthreshold(EBthreshold),
theEEthreshold(EEthreshold),
theUseEtEBTresholdFlag(useEtEBTreshold),
theUseEtEETresholdFlag(useEtEETreshold),
theUseSymEBTresholdFlag(useSymEBTreshold),
theUseSymEETresholdFlag(useSymEETreshold),
theHcalThreshold(HcalThreshold),
theHBthreshold(HBthreshold),
theHBthreshold1(HBthreshold1),
theHBthreshold2(HBthreshold2),
theHESthreshold(HESthreshold),
theHESthreshold1(HESthreshold1),
theHEDthreshold(HEDthreshold),
theHEDthreshold1(HEDthreshold1),
theHOthreshold0(HOthreshold0),
theHOthresholdPlus1(HOthresholdPlus1),
theHOthresholdMinus1(HOthresholdMinus1),
theHOthresholdPlus2(HOthresholdPlus2),
theHOthresholdMinus2(HOthresholdMinus2),
theHF1threshold(HF1threshold),
theHF2threshold(HF2threshold),
theEBGrid(std::vector<double>(5, 10.)),
theEBWeights(std::vector<double>(5, 1.)),
theEEGrid(std::vector<double>(5, 10.)),
theEEWeights(std::vector<double>(5, 1.)),
theHBGrid(std::vector<double>(5, 10.)),
theHBWeights(std::vector<double>(5, 1.)),
theHESGrid(std::vector<double>(5, 10.)),
theHESWeights(std::vector<double>(5, 1.)),
theHEDGrid(std::vector<double>(5, 10.)),
theHEDWeights(std::vector<double>(5, 1.)),
theHOGrid(std::vector<double>(5, 10.)),
theHOWeights(std::vector<double>(5, 1.)),
theHF1Grid(std::vector<double>(5, 10.)),
theHF1Weights(std::vector<double>(5, 1.)),
theHF2Grid(std::vector<double>(5, 10.)),
theHF2Weights(std::vector<double>(5, 1.)),
theEBweight(EBweight),
theEEweight(EEweight),
theHBweight(HBweight),
theHESweight(HESweight),
theHEDweight(HEDweight),
theHOweight(HOweight),
theHF1weight(HF1weight),
theHF2weight(HF2weight),
theEcutTower(EcutTower),
theEBSumThreshold(EBSumThreshold),
theEESumThreshold(EESumThreshold),
theEBEScale(50.),
theEEEScale(50.),
theHBEScale(50.),
theHESEScale(50.),
theHEDEScale(50.),
theHOEScale(50.),
theHF1EScale(50.),
theHF2EScale(50.),
theHcalTopology(nullptr),
theGeometry(nullptr),
theTowerConstituentsMap(nullptr),
theHcalAcceptSeverityLevel(0),
theRecoveredHcalHitsAreUsed(false),
theRecoveredEcalHitsAreUsed(false),
useRejectedHitsOnly(false),
theHcalAcceptSeverityLevelForRejectedHit(0),
useRejectedRecoveredHcalHits(0),
useRejectedRecoveredEcalHits(0),
missingHcalRescaleFactorForEcal(0.),
theHOIsUsed(useHO),
// (momentum reconstruction algorithm)
theMomConstrMethod(momConstrMethod),
theMomHBDepth(momHBDepth),
theMomHEDepth(momHEDepth),
theMomEBDepth(momEBDepth),
theMomEEDepth(momEEDepth),
theHcalPhase(hcalPhase) {}
CaloTowersCreationAlgo::CaloTowersCreationAlgo(double EBthreshold,
double EEthreshold,
bool useEtEBTreshold,
bool useEtEETreshold,
bool useSymEBTreshold,
bool useSymEETreshold,
double HcalThreshold,
double HBthreshold,
double HBthreshold1,
double HBthreshold2,
double HESthreshold,
double HESthreshold1,
double HEDthreshold,
double HEDthreshold1,
double HOthreshold0,
double HOthresholdPlus1,
double HOthresholdMinus1,
double HOthresholdPlus2,
double HOthresholdMinus2,
double HF1threshold,
double HF2threshold,
const std::vector<double>& EBGrid,
const std::vector<double>& EBWeights,
const std::vector<double>& EEGrid,
const std::vector<double>& EEWeights,
const std::vector<double>& HBGrid,
const std::vector<double>& HBWeights,
const std::vector<double>& HESGrid,
const std::vector<double>& HESWeights,
const std::vector<double>& HEDGrid,
const std::vector<double>& HEDWeights,
const std::vector<double>& HOGrid,
const std::vector<double>& HOWeights,
const std::vector<double>& HF1Grid,
const std::vector<double>& HF1Weights,
const std::vector<double>& HF2Grid,
const std::vector<double>& HF2Weights,
double EBweight,
double EEweight,
double HBweight,
double HESweight,
double HEDweight,
double HOweight,
double HF1weight,
double HF2weight,
double EcutTower,
double EBSumThreshold,
double EESumThreshold,
bool useHO,
// (for the momentum construction algorithm)
int momConstrMethod,
double momHBDepth,
double momHEDepth,
double momEBDepth,
double momEEDepth,
int hcalPhase)
: theEBthreshold(EBthreshold),
theEEthreshold(EEthreshold),
theUseEtEBTresholdFlag(useEtEBTreshold),
theUseEtEETresholdFlag(useEtEETreshold),
theUseSymEBTresholdFlag(useSymEBTreshold),
theUseSymEETresholdFlag(useSymEETreshold),
theHcalThreshold(HcalThreshold),
theHBthreshold(HBthreshold),
theHBthreshold1(HBthreshold1),
theHBthreshold2(HBthreshold2),
theHESthreshold(HESthreshold),
theHESthreshold1(HESthreshold1),
theHEDthreshold(HEDthreshold),
theHEDthreshold1(HEDthreshold1),
theHOthreshold0(HOthreshold0),
theHOthresholdPlus1(HOthresholdPlus1),
theHOthresholdMinus1(HOthresholdMinus1),
theHOthresholdPlus2(HOthresholdPlus2),
theHOthresholdMinus2(HOthresholdMinus2),
theHF1threshold(HF1threshold),
theHF2threshold(HF2threshold),
theEBGrid(EBGrid),
theEBWeights(EBWeights),
theEEGrid(EEGrid),
theEEWeights(EEWeights),
theHBGrid(HBGrid),
theHBWeights(HBWeights),
theHESGrid(HESGrid),
theHESWeights(HESWeights),
theHEDGrid(HEDGrid),
theHEDWeights(HEDWeights),
theHOGrid(HOGrid),
theHOWeights(HOWeights),
theHF1Grid(HF1Grid),
theHF1Weights(HF1Weights),
theHF2Grid(HF2Grid),
theHF2Weights(HF2Weights),
theEBweight(EBweight),
theEEweight(EEweight),
theHBweight(HBweight),
theHESweight(HESweight),
theHEDweight(HEDweight),
theHOweight(HOweight),
theHF1weight(HF1weight),
theHF2weight(HF2weight),
theEcutTower(EcutTower),
theEBSumThreshold(EBSumThreshold),
theEESumThreshold(EESumThreshold),
theEBEScale(50.),
theEEEScale(50.),
theHBEScale(50.),
theHESEScale(50.),
theHEDEScale(50.),
theHOEScale(50.),
theHF1EScale(50.),
theHF2EScale(50.),
theHcalTopology(nullptr),
theGeometry(nullptr),
theTowerConstituentsMap(nullptr),
theHcalAcceptSeverityLevel(0),
theRecoveredHcalHitsAreUsed(false),
theRecoveredEcalHitsAreUsed(false),
useRejectedHitsOnly(false),
theHcalAcceptSeverityLevelForRejectedHit(0),
useRejectedRecoveredHcalHits(0),
useRejectedRecoveredEcalHits(0),
missingHcalRescaleFactorForEcal(0.),
theHOIsUsed(useHO),
// (momentum reconstruction algorithm)
theMomConstrMethod(momConstrMethod),
theMomHBDepth(momHBDepth),
theMomHEDepth(momHEDepth),
theMomEBDepth(momEBDepth),
theMomEEDepth(momEEDepth),
theHcalPhase(hcalPhase) {
// static int N = 0;
// std::cout << "VI Algo " << ++N << std::endl;
// nalgo=N;
}
void CaloTowersCreationAlgo::setGeometry(const CaloTowerTopology* cttopo,
const CaloTowerConstituentsMap* ctmap,
const HcalTopology* htopo,
const CaloGeometry* geo) {
theTowerTopology = cttopo;
theTowerConstituentsMap = ctmap;
theHcalTopology = htopo;
theGeometry = geo;
theTowerGeometry = geo->getSubdetectorGeometry(DetId::Calo, CaloTowerDetId::SubdetId);
//initialize ecal bad channel map
ecalBadChs.resize(theTowerTopology->sizeForDenseIndexing(), 0);
}
void CaloTowersCreationAlgo::begin() {
theTowerMap.clear();
theTowerMapSize = 0;
//hcalDropChMap.clear();
}
void CaloTowersCreationAlgo::process(const HBHERecHitCollection& hbhe) {
for (HBHERecHitCollection::const_iterator hbheItr = hbhe.begin(); hbheItr != hbhe.end(); ++hbheItr)
assignHitHcal(&(*hbheItr));
}
void CaloTowersCreationAlgo::process(const HORecHitCollection& ho) {
for (HORecHitCollection::const_iterator hoItr = ho.begin(); hoItr != ho.end(); ++hoItr)
assignHitHcal(&(*hoItr));
}
void CaloTowersCreationAlgo::process(const HFRecHitCollection& hf) {
for (HFRecHitCollection::const_iterator hfItr = hf.begin(); hfItr != hf.end(); ++hfItr)
assignHitHcal(&(*hfItr));
}
void CaloTowersCreationAlgo::process(const EcalRecHitCollection& ec) {
for (EcalRecHitCollection::const_iterator ecItr = ec.begin(); ecItr != ec.end(); ++ecItr)
assignHitEcal(&(*ecItr));
}
// this method should not be used any more as the towers in the changed format
// can not be properly rescaled with the "rescale" method.
// "rescale was replaced by "rescaleTowers"
//
void CaloTowersCreationAlgo::process(const CaloTowerCollection& ctc) {
for (CaloTowerCollection::const_iterator ctcItr = ctc.begin(); ctcItr != ctc.end(); ++ctcItr) {
rescale(&(*ctcItr));
}
}
void CaloTowersCreationAlgo::finish(CaloTowerCollection& result) {
// now copy this map into the final collection
result.reserve(theTowerMapSize);
// auto k=0U;
// if (!theEbHandle.isValid()) std::cout << "VI ebHandle not valid" << std::endl;
// if (!theEeHandle.isValid()) std::cout << "VI eeHandle not valid" << std::endl;
for (auto const& mt : theTowerMap) {
// Convert only if there is at least one constituent in the metatower.
// The check of constituents size in the coverted tower is still needed!
if (!mt.empty()) {
convert(mt.id, mt, result);
} // ++k;}
}
// assert(k==theTowerMapSize);
// std::cout << "VI TowerMap " << theTowerMapSize << " " << k << std::endl;
theTowerMap.clear(); // save the memory
theTowerMapSize = 0;
}
void CaloTowersCreationAlgo::rescaleTowers(const CaloTowerCollection& ctc, CaloTowerCollection& ctcResult) {
for (CaloTowerCollection::const_iterator ctcItr = ctc.begin(); ctcItr != ctc.end(); ++ctcItr) {
CaloTowerDetId twrId = ctcItr->id();
double newE_em = ctcItr->emEnergy();
double newE_had = ctcItr->hadEnergy();
double newE_outer = ctcItr->outerEnergy();
double threshold = 0.0; // not used: we do not change thresholds
double weight = 1.0;
// HF
if (ctcItr->ietaAbs() >= theTowerTopology->firstHFRing()) {
double E_short = 0.5 * newE_had; // from the definitions for HF
double E_long = newE_em + 0.5 * newE_had; //
// scale
E_long *= theHF1weight;
E_short *= theHF2weight;
// convert
newE_em = E_long - E_short;
newE_had = 2.0 * E_short;
}
else { // barrel/endcap
// find if its in EB, or EE; determine from first ecal constituent found
for (unsigned int iConst = 0; iConst < ctcItr->constituentsSize(); ++iConst) {
DetId constId = ctcItr->constituent(iConst);
if (constId.det() != DetId::Ecal)
continue;
getThresholdAndWeight(constId, threshold, weight);
newE_em *= weight;
break;
}
// HO
for (unsigned int iConst = 0; iConst < ctcItr->constituentsSize(); ++iConst) {
DetId constId = ctcItr->constituent(iConst);
if (constId.det() != DetId::Hcal)
continue;
if (HcalDetId(constId).subdet() != HcalOuter)
continue;
getThresholdAndWeight(constId, threshold, weight);
newE_outer *= weight;
break;
}
// HB/HE
for (unsigned int iConst = 0; iConst < ctcItr->constituentsSize(); ++iConst) {
DetId constId = ctcItr->constituent(iConst);
if (constId.det() != DetId::Hcal)
continue;
if (HcalDetId(constId).subdet() == HcalOuter)
continue;
getThresholdAndWeight(constId, threshold, weight);
newE_had *= weight;
if (ctcItr->ietaAbs() > theTowerTopology->firstHERing())
newE_outer *= weight;
break;
}
} // barrel/endcap region
// now make the new tower
double newE_hadTot =
(theHOIsUsed && twrId.ietaAbs() <= theTowerTopology->lastHORing()) ? newE_had + newE_outer : newE_had;
GlobalPoint emPoint = ctcItr->emPosition();
GlobalPoint hadPoint = ctcItr->emPosition();
double f_em = 1.0 / cosh(emPoint.eta());
double f_had = 1.0 / cosh(hadPoint.eta());
CaloTower::PolarLorentzVector towerP4;
if (ctcItr->ietaAbs() < theTowerTopology->firstHFRing()) {
if (newE_em > 0)
towerP4 += CaloTower::PolarLorentzVector(newE_em * f_em, emPoint.eta(), emPoint.phi(), 0);
if (newE_hadTot > 0)
towerP4 += CaloTower::PolarLorentzVector(newE_hadTot * f_had, hadPoint.eta(), hadPoint.phi(), 0);
} else {
double newE_tot = newE_em + newE_had;
// for HF we use common point for ecal, hcal shower positions regardless of the method
if (newE_tot > 0)
towerP4 += CaloTower::PolarLorentzVector(newE_tot * f_had, hadPoint.eta(), hadPoint.phi(), 0);
}
CaloTower rescaledTower(twrId, newE_em, newE_had, newE_outer, -1, -1, towerP4, emPoint, hadPoint);
// copy the timings, have to convert back to int, 1 unit = 0.01 ns
rescaledTower.setEcalTime(int(ctcItr->ecalTime() * 100.0 + 0.5));
rescaledTower.setHcalTime(int(ctcItr->hcalTime() * 100.0 + 0.5));
//add topology info
rescaledTower.setHcalSubdet(theTowerTopology->lastHBRing(),
theTowerTopology->lastHERing(),
theTowerTopology->lastHFRing(),
theTowerTopology->lastHORing());
std::vector<DetId> contains;
for (unsigned int iConst = 0; iConst < ctcItr->constituentsSize(); ++iConst) {
contains.push_back(ctcItr->constituent(iConst));
}
rescaledTower.addConstituents(contains);
rescaledTower.setCaloTowerStatus(ctcItr->towerStatusWord());
ctcResult.push_back(rescaledTower);
} // end of loop over towers
}
void CaloTowersCreationAlgo::assignHitHcal(const CaloRecHit* recHit) {
DetId detId = recHit->detid();
DetId detIdF(detId);
if (detId.det() == DetId::Hcal && theHcalTopology->getMergePositionFlag()) {
detIdF = theHcalTopology->idFront(HcalDetId(detId));
#ifdef EDM_ML_DEBUG
std::cout << "AssignHitHcal DetId " << HcalDetId(detId) << " Front " << HcalDetId(detIdF) << std::endl;
#endif
}
unsigned int chStatusForCT = hcalChanStatusForCaloTower(recHit);
// this is for skipping channls: mostly needed for the creation of
// bad towers from hits i the bad channel collections.
if (chStatusForCT == CaloTowersCreationAlgo::IgnoredChan)
return;
double threshold, weight;
getThresholdAndWeight(detId, threshold, weight);
double energy = recHit->energy(); // original RecHit energy is used to apply thresholds
double e = energy * weight; // energies scaled by user weight: used in energy assignments
// SPECIAL handling of tower 28 merged depths --> half into tower 28 and half into tower 29
bool merge(false);
if (detIdF.det() == DetId::Hcal && HcalDetId(detIdF).subdet() == HcalEndcap &&
(theHcalPhase == 0 || theHcalPhase == 1) &&
//HcalDetId(detId).depth()==3 &&
HcalDetId(detIdF).ietaAbs() == theHcalTopology->lastHERing() - 1) {
merge = theHcalTopology->mergedDepth29(HcalDetId(detIdF));
#ifdef EDM_ML_DEBUG
std::cout << "Merge " << HcalDetId(detIdF) << ":" << merge << std::endl;
#endif
}
if (merge) {
////////////////////////////// unsigned int chStatusForCT = hcalChanStatusForCaloTower(recHit);
// bad channels are counted regardless of energy threshold
if (chStatusForCT == CaloTowersCreationAlgo::BadChan) {
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(detId);
if (towerDetId.null())
return;
MetaTower& tower28 = find(towerDetId);
CaloTowerDetId towerDetId29(towerDetId.ieta() + towerDetId.zside(), towerDetId.iphi());
MetaTower& tower29 = find(towerDetId29);
tower28.numBadHcalCells += 1;
tower29.numBadHcalCells += 1;
}
else if (0.5 * energy >= threshold) { // not bad channel: use energy if above threshold
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(detId);
if (towerDetId.null())
return;
MetaTower& tower28 = find(towerDetId);
CaloTowerDetId towerDetId29(towerDetId.ieta() + towerDetId.zside(), towerDetId.iphi());
MetaTower& tower29 = find(towerDetId29);
if (chStatusForCT == CaloTowersCreationAlgo::RecoveredChan) {
tower28.numRecHcalCells += 1;
tower29.numRecHcalCells += 1;
} else if (chStatusForCT == CaloTowersCreationAlgo::ProblematicChan) {
tower28.numProbHcalCells += 1;
tower29.numProbHcalCells += 1;
}
// NOTE DIVIDE BY 2!!!
double e28 = 0.5 * e;
double e29 = 0.5 * e;
tower28.E_had += e28;
tower28.E += e28;
std::pair<DetId, float> mc(detId, e28);
tower28.metaConstituents.push_back(mc);
tower29.E_had += e29;
tower29.E += e29;
tower29.metaConstituents.push_back(mc);
// time info: do not use in averaging if timing error is found: need
// full set of status info to implement: use only "good" channels for now
if (chStatusForCT == CaloTowersCreationAlgo::GoodChan) {
tower28.hadSumTimeTimesE += (e28 * recHit->time());
tower28.hadSumEForTime += e28;
tower29.hadSumTimeTimesE += (e29 * recHit->time());
tower29.hadSumEForTime += e29;
}
// store the energy in layer 3 also in E_outer
tower28.E_outer += e28;
tower29.E_outer += e29;
} // not a "bad" hit
} // end of special case
else {
HcalDetId hcalDetId(detId);
/////////////////////// unsigned int chStatusForCT = hcalChanStatusForCaloTower(recHit);
if (hcalDetId.subdet() == HcalOuter) {
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(detId);
if (towerDetId.null())
return;
MetaTower& tower = find(towerDetId);
if (chStatusForCT == CaloTowersCreationAlgo::BadChan) {
if (theHOIsUsed)
tower.numBadHcalCells += 1;
}
else if (energy >= threshold) {
tower.E_outer += e; // store HO energy even if HO is not used
// add energy of the tower and/or flag if theHOIsUsed
if (theHOIsUsed) {
tower.E += e;
if (chStatusForCT == CaloTowersCreationAlgo::RecoveredChan) {
tower.numRecHcalCells += 1;
} else if (chStatusForCT == CaloTowersCreationAlgo::ProblematicChan) {
tower.numProbHcalCells += 1;
}
} // HO is used
// add HO to constituents even if it is not used: JetMET wants to keep these towers
std::pair<DetId, float> mc(detId, e);
tower.metaConstituents.push_back(mc);
} // not a bad channel, energy above threshold
} // HO hit
// HF calculates EM fraction differently
else if (hcalDetId.subdet() == HcalForward) {
if (chStatusForCT == CaloTowersCreationAlgo::BadChan) {
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(detId);
if (towerDetId.null())
return;
MetaTower& tower = find(towerDetId);
tower.numBadHcalCells += 1;
}
else if (energy >= threshold) {
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(detId);
if (towerDetId.null())
return;
MetaTower& tower = find(towerDetId);
if (hcalDetId.depth() == 1) {
// long fiber, so E_EM = E(Long) - E(Short)
tower.E_em += e;
} else {
// short fiber, EHAD = 2 * E(Short)
tower.E_em -= e;
tower.E_had += 2. * e;
}
tower.E += e;
if (chStatusForCT == CaloTowersCreationAlgo::RecoveredChan) {
tower.numRecHcalCells += 1;
} else if (chStatusForCT == CaloTowersCreationAlgo::ProblematicChan) {
tower.numProbHcalCells += 1;
}
// put the timing in HCAL -> have to check timing errors when available
// for now use only good channels
if (chStatusForCT == CaloTowersCreationAlgo::GoodChan) {
tower.hadSumTimeTimesE += (e * recHit->time());
tower.hadSumEForTime += e;
}
std::pair<DetId, float> mc(detId, e);
tower.metaConstituents.push_back(mc);
} // not a bad HF channel, energy above threshold
} // HF hit
else {
// HCAL situation normal in HB/HE
if (chStatusForCT == CaloTowersCreationAlgo::BadChan) {
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(detId);
if (towerDetId.null())
return;
MetaTower& tower = find(towerDetId);
tower.numBadHcalCells += 1;
} else if (energy >= threshold) {
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(detId);
if (towerDetId.null())
return;
MetaTower& tower = find(towerDetId);
tower.E_had += e;
tower.E += e;
if (chStatusForCT == CaloTowersCreationAlgo::RecoveredChan) {
tower.numRecHcalCells += 1;
} else if (chStatusForCT == CaloTowersCreationAlgo::ProblematicChan) {
tower.numProbHcalCells += 1;
}
// Timing information: need specific accessors
// for now use only good channels
if (chStatusForCT == CaloTowersCreationAlgo::GoodChan) {
tower.hadSumTimeTimesE += (e * recHit->time());
tower.hadSumEForTime += e;
}
// store energy in highest depth for towers 18-27 (for electron,photon ID in endcap)
// also, store energy in HE part of tower 16 (for JetMET cleanup)
HcalDetId hcalDetId(detId);
if (hcalDetId.subdet() == HcalEndcap) {
if (theHcalPhase == 0) {
if ((hcalDetId.depth() == 2 && hcalDetId.ietaAbs() >= 18 && hcalDetId.ietaAbs() < 27) ||
(hcalDetId.depth() == 3 && hcalDetId.ietaAbs() == 27) ||
(hcalDetId.depth() == 3 && hcalDetId.ietaAbs() == 16)) {
tower.E_outer += e;
}
}
//combine depths in phase0-like way
else if (theHcalPhase == 1) {
if ((hcalDetId.depth() >= 3 && hcalDetId.ietaAbs() >= 18 && hcalDetId.ietaAbs() < 26) ||
(hcalDetId.depth() >= 4 && (hcalDetId.ietaAbs() == 26 || hcalDetId.ietaAbs() == 27)) ||
(hcalDetId.depth() == 3 && hcalDetId.ietaAbs() == 17) ||
(hcalDetId.depth() == 4 && hcalDetId.ietaAbs() == 16)) {
tower.E_outer += e;
}
}
}
std::pair<DetId, float> mc(detId, e);
tower.metaConstituents.push_back(mc);
} // not a "bad" channel, energy above threshold
} // channel in HBHE (excluding twrs 28,29)
} // recHit normal case (not in HE towers 28,29)
} // end of assignHitHcal method
void CaloTowersCreationAlgo::assignHitEcal(const EcalRecHit* recHit) {
DetId detId = recHit->detid();
unsigned int chStatusForCT;
bool ecalIsBad = false;
std::tie(chStatusForCT, ecalIsBad) = ecalChanStatusForCaloTower(recHit);
// this is for skipping channls: mostly needed for the creation of
// bad towers from hits i the bad channel collections.
if (chStatusForCT == CaloTowersCreationAlgo::IgnoredChan)
return;
double threshold, weight;
getThresholdAndWeight(detId, threshold, weight);
double energy = recHit->energy(); // original RecHit energy is used to apply thresholds
double e = energy * weight; // energies scaled by user weight: used in energy assignments
///////////////////////////// unsigned int chStatusForCT = ecalChanStatusForCaloTower(recHit);
// For ECAL we count all bad channels after the metatower is complete
// Include options for symmetric thresholds and cut on Et
// for ECAL RecHits
bool passEmThreshold = false;
if (detId.subdetId() == EcalBarrel) {
if (theUseEtEBTresholdFlag)
energy /= cosh((theGeometry->getGeometry(detId)->getPosition()).eta());
if (theUseSymEBTresholdFlag)
passEmThreshold = (fabs(energy) >= threshold);
else
passEmThreshold = (energy >= threshold);
} else if (detId.subdetId() == EcalEndcap) {
if (theUseEtEETresholdFlag)
energy /= cosh((theGeometry->getGeometry(detId)->getPosition()).eta());
if (theUseSymEETresholdFlag)
passEmThreshold = (fabs(energy) >= threshold);
else
passEmThreshold = (energy >= threshold);
}
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(detId);
if (towerDetId.null())
return;
MetaTower& tower = find(towerDetId);
// count bad cells and avoid double counting with those from DB (Recovered are counted bad)
// somehow misses some
// if ( (chStatusForCT == CaloTowersCreationAlgo::BadChan) & (!ecalIsBad) ) ++tower.numBadEcalCells;
// a bit slower...
if (chStatusForCT == CaloTowersCreationAlgo::BadChan) {
auto thisEcalSevLvl = theEcalSevLvlAlgo->severityLevel(detId);
// check if the Ecal severity is ok to keep
auto sevit = std::find(theEcalSeveritiesToBeExcluded.begin(), theEcalSeveritiesToBeExcluded.end(), thisEcalSevLvl);
if (sevit == theEcalSeveritiesToBeExcluded.end())
++tower.numBadEcalCells; // notinDB
}
// if (chStatusForCT != CaloTowersCreationAlgo::BadChan && energy >= threshold) {
if (chStatusForCT != CaloTowersCreationAlgo::BadChan && passEmThreshold) {
tower.E_em += e;
tower.E += e;
if (chStatusForCT == CaloTowersCreationAlgo::RecoveredChan) {
tower.numRecEcalCells += 1;
} else if (chStatusForCT == CaloTowersCreationAlgo::ProblematicChan) {
tower.numProbEcalCells += 1;
}
// change when full status info is available
// for now use only good channels
// add e>0 check (new options allow e<0)
if (chStatusForCT == CaloTowersCreationAlgo::GoodChan && e > 0) {
tower.emSumTimeTimesE += (e * recHit->time());
tower.emSumEForTime += e; // see above
}
std::pair<DetId, float> mc(detId, e);
tower.metaConstituents.push_back(mc);
}
} // end of assignHitEcal method
// This method is not flexible enough for the new CaloTower format.
// For now make a quick compatibility "fix" : WILL NOT WORK CORRECTLY with anything
// except the default simple p4 assignment!!!
// Must be rewritten for full functionality.
void CaloTowersCreationAlgo::rescale(const CaloTower* ct) {
double threshold, weight;
CaloTowerDetId towerDetId = theTowerConstituentsMap->towerOf(ct->id());
if (towerDetId.null())
return;
MetaTower& tower = find(towerDetId);
tower.E_em = 0.;
tower.E_had = 0.;
tower.E_outer = 0.;
for (unsigned int i = 0; i < ct->constituentsSize(); i++) {
DetId detId = ct->constituent(i);
getThresholdAndWeight(detId, threshold, weight);
DetId::Detector det = detId.det();
if (det == DetId::Ecal) {
tower.E_em = ct->emEnergy() * weight;
} else {
HcalDetId hcalDetId(detId);
if (hcalDetId.subdet() == HcalForward) {
if (hcalDetId.depth() == 1)
tower.E_em = ct->emEnergy() * weight;
if (hcalDetId.depth() == 2)
tower.E_had = ct->hadEnergy() * weight;
} else if (hcalDetId.subdet() == HcalOuter) {
tower.E_outer = ct->outerEnergy() * weight;
} else {
tower.E_had = ct->hadEnergy() * weight;
}
}
tower.E = tower.E_had + tower.E_em + tower.E_outer;
// this is to be compliant with the new MetaTower setup
// used only for the default simple vector assignment
std::pair<DetId, float> mc(detId, 0);
tower.metaConstituents.push_back(mc);
}
// preserve time inforamtion
tower.emSumTimeTimesE = ct->ecalTime();
tower.hadSumTimeTimesE = ct->hcalTime();
tower.emSumEForTime = 1.0;
tower.hadSumEForTime = 1.0;
}
CaloTowersCreationAlgo::MetaTower& CaloTowersCreationAlgo::find(const CaloTowerDetId& detId) {
if (theTowerMap.empty()) {
theTowerMap.resize(theTowerTopology->sizeForDenseIndexing());
}
auto& mt = theTowerMap[theTowerTopology->denseIndex(detId)];
if (mt.empty()) {
mt.id = detId;
mt.metaConstituents.reserve(detId.ietaAbs() < theTowerTopology->firstHFRing() ? 12 : 2);
++theTowerMapSize;
}
return mt;
}
void CaloTowersCreationAlgo::convert(const CaloTowerDetId& id, const MetaTower& mt, CaloTowerCollection& collection) {
assert(id.rawId() != 0);
double ecalThres = (id.ietaAbs() <= 17) ? (theEBSumThreshold) : (theEESumThreshold);
double E = mt.E;
double E_em = mt.E_em;
double E_had = mt.E_had;
double E_outer = mt.E_outer;
// Note: E_outer is used to save HO energy OR energy in the outermost depths in endcap region
// In the methods with separate treatment of EM and HAD components:
// - HO is not used to determine direction, however HO energy is added to get "total had energy"
// => Check if the tower is within HO coverage before adding E_outer to the "total had" energy
// else the energy will be double counted
// When summing up the energy of the tower these checks are performed in the loops over RecHits
std::vector<std::pair<DetId, float> > metaContains = mt.metaConstituents;
if (id.ietaAbs() < theTowerTopology->firstHFRing() && E_em < ecalThres) { // ignore EM threshold in HF
E -= E_em;
E_em = 0;
std::vector<std::pair<DetId, float> > metaContains_noecal;
for (std::vector<std::pair<DetId, float> >::iterator i = metaContains.begin(); i != metaContains.end(); ++i)
if (i->first.det() != DetId::Ecal)
metaContains_noecal.push_back(*i);
metaContains.swap(metaContains_noecal);
}
if (id.ietaAbs() < theTowerTopology->firstHFRing() && E_had < theHcalThreshold) {
E -= E_had;
if (theHOIsUsed && id.ietaAbs() <= theTowerTopology->lastHORing())
E -= E_outer; // not subtracted before, think it should be done
E_had = 0;
E_outer = 0;
std::vector<std::pair<DetId, float> > metaContains_nohcal;
for (std::vector<std::pair<DetId, float> >::iterator i = metaContains.begin(); i != metaContains.end(); ++i)
if (i->first.det() != DetId::Hcal)
metaContains_nohcal.push_back(*i);
metaContains.swap(metaContains_nohcal);
}
if (metaContains.empty())
return;
if (missingHcalRescaleFactorForEcal > 0 && E_had == 0 && E_em > 0) {
auto match = hcalDropChMap.find(id);
if (match != hcalDropChMap.end() && match->second.second) {
E_had = missingHcalRescaleFactorForEcal * E_em;
E += E_had;
}
}
double E_had_tot = (theHOIsUsed && id.ietaAbs() <= theTowerTopology->lastHORing()) ? E_had + E_outer : E_had;
// create CaloTower using the selected algorithm
GlobalPoint emPoint, hadPoint;
// this is actually a 4D vector
Basic3DVectorF towerP4;
bool massless = true;
// float mass1=0;
float mass2 = 0;
// conditional assignment of depths for barrel/endcap
// Some additional tuning may be required in the transitional region
// 14<|iEta|<19
double momEmDepth = 0.;
double momHadDepth = 0.;
if (id.ietaAbs() <= 17) {
momHadDepth = theMomHBDepth;
momEmDepth = theMomEBDepth;
} else {
momHadDepth = theMomHEDepth;
momEmDepth = theMomEEDepth;
}
switch (theMomConstrMethod) {
// FIXME : move to simple cartesian algebra
case 0: { // Simple 4-momentum assignment
GlobalPoint p = theTowerGeometry->getGeometry(id)->getPosition();
towerP4 = p.basicVector().unit();
towerP4[3] = 1.f; // energy
towerP4 *= E;
// double pf=1.0/cosh(p.eta());
// if (E>0) towerP4 = CaloTower::PolarLorentzVector(E*pf, p.eta(), p.phi(), 0);
emPoint = p;
hadPoint = p;
} // end case 0
break;
case 1: { // separate 4-vectors for ECAL, HCAL, add to get the 4-vector of the tower (=>tower has mass!)
if (id.ietaAbs() < theTowerTopology->firstHFRing()) {
Basic3DVectorF emP4;
if (E_em > 0) {
emPoint = emShwrPos(metaContains, momEmDepth, E_em);
emP4 = emPoint.basicVector().unit();
emP4[3] = 1.f; // energy
towerP4 = emP4 * E_em;
// double emPf = 1.0/cosh(emPoint.eta());
// towerP4 += CaloTower::PolarLorentzVector(E_em*emPf, emPoint.eta(), emPoint.phi(), 0);
}
if ((E_had + E_outer) > 0) {
massless = (E_em <= 0);
hadPoint = hadShwrPos(id, momHadDepth);
auto lP4 = hadPoint.basicVector().unit();
lP4[3] = 1.f; // energy
if (!massless) {
auto diff = lP4 - emP4;
mass2 = std::sqrt(E_em * E_had_tot * diff.mag2());
}
lP4 *= E_had_tot;
towerP4 += lP4;
/*
if (!massless) {
auto p = towerP4;
double m2 = double(p[3]*p[3]) - double(p[0]*p[0])+double(p[1]*p[1])+double(p[2]*p[2]); mass1 = m2>0 ? std::sqrt(m2) : 0;
}
*/
// double hadPf = 1.0/cosh(hadPoint.eta());
// if (E_had_tot>0) {
// towerP4 += CaloTower::PolarLorentzVector(E_had_tot*hadPf, hadPoint.eta(), hadPoint.phi(), 0);
// }
}
} else { // forward detector: use the CaloTower position
GlobalPoint p = theTowerGeometry->getGeometry(id)->getPosition();
towerP4 = p.basicVector().unit();
towerP4[3] = 1.f; // energy
towerP4 *= E;
// double pf=1.0/cosh(p.eta());
// if (E>0) towerP4 = CaloTower::PolarLorentzVector(E*pf, p.eta(), p.phi(), 0); // simple momentum assignment, same position
emPoint = p;
hadPoint = p;
}
} // end case 1
break;
case 2: { // use ECAL position for the tower (when E_cal>0), else default CaloTower position (massless tower)
if (id.ietaAbs() < theTowerTopology->firstHFRing()) {
if (E_em > 0)
emPoint = emShwrLogWeightPos(metaContains, momEmDepth, E_em);
else
emPoint = theTowerGeometry->getGeometry(id)->getPosition();
towerP4 = emPoint.basicVector().unit();
towerP4[3] = 1.f; // energy
towerP4 *= E;
// double sumPf = 1.0/cosh(emPoint.eta());
/// if (E>0) towerP4 = CaloTower::PolarLorentzVector(E*sumPf, emPoint.eta(), emPoint.phi(), 0);
hadPoint = emPoint;
} else { // forward detector: use the CaloTower position
GlobalPoint p = theTowerGeometry->getGeometry(id)->getPosition();
towerP4 = p.basicVector().unit();
towerP4[3] = 1.f; // energy
towerP4 *= E;
// double pf=1.0/cosh(p.eta());
// if (E>0) towerP4 = CaloTower::PolarLorentzVector(E*pf, p.eta(), p.phi(), 0); // simple momentum assignment, same position
emPoint = p;
hadPoint = p;
}
} // end case 2
break;
} // end of decision on p4 reconstruction method
// insert in collection (remove and return if below threshold)
if UNLIKELY ((towerP4[3] == 0) & (E_outer > 0)) {
float val = theHOIsUsed ? 0 : 1E-9; // to keep backwards compatibility for theHOIsUsed == true
collection.emplace_back(id,
E_em,
E_had,
E_outer,
-1,
-1,
CaloTower::PolarLorentzVector(val, hadPoint.eta(), hadPoint.phi(), 0),
emPoint,
hadPoint);
} else {
collection.emplace_back(
id, E_em, E_had, E_outer, -1, -1, GlobalVector(towerP4), towerP4[3], mass2, emPoint, hadPoint);
}
auto& caloTower = collection.back();
// if (!massless) std::cout << "massive " << id <<' ' << mass1 <<' ' << mass2 <<' ' << caloTower.mass() << std::endl;
// std::cout << "CaloTowerVI " <<theMomConstrMethod <<' ' << id <<' '<< E_em <<' '<< E_had <<' '<< E_outer <<' '<< GlobalVector(towerP4) <<' '<< towerP4[3] <<' '<< emPoint <<' '<< hadPoint << std::endl;
//if (towerP4[3]==0) std::cout << "CaloTowerVIzero " << theEcutTower << ' ' << collection.back().eta() <<' '<< collection.back().phi() << std::endl;
if (caloTower.energy() < theEcutTower) {
collection.pop_back();
return;
}
// set the timings
float ecalTime = (mt.emSumEForTime > 0) ? mt.emSumTimeTimesE / mt.emSumEForTime : -9999;
float hcalTime = (mt.hadSumEForTime > 0) ? mt.hadSumTimeTimesE / mt.hadSumEForTime : -9999;
caloTower.setEcalTime(compactTime(ecalTime));
caloTower.setHcalTime(compactTime(hcalTime));
//add topology info
caloTower.setHcalSubdet(theTowerTopology->lastHBRing(),
theTowerTopology->lastHERing(),
theTowerTopology->lastHFRing(),
theTowerTopology->lastHORing());
// set the CaloTower status word =====================================
// Channels must be counter exclusively in the defined cathegories
// "Bad" channels (not used in energy assignment) can be flagged during
// CaloTower creation only if specified in the configuration file
unsigned int numBadHcalChan = mt.numBadHcalCells;
// unsigned int numBadEcalChan = mt.numBadEcalCells;
unsigned int numBadEcalChan = 0; //
unsigned int numRecHcalChan = mt.numRecHcalCells;
unsigned int numRecEcalChan = mt.numRecEcalCells;
unsigned int numProbHcalChan = mt.numProbHcalCells;
unsigned int numProbEcalChan = mt.numProbEcalCells;
// now add dead/off/... channels not used in RecHit reconstruction for HCAL
HcalDropChMap::iterator dropChItr = hcalDropChMap.find(id);
if (dropChItr != hcalDropChMap.end())
numBadHcalChan += dropChItr->second.first;
// for ECAL the number of all bad channels is obtained here -----------------------
/*
// old hyper slow algorithm
// get all possible constituents of the tower
std::vector<DetId> allConstituents = theTowerConstituentsMap->constituentsOf(id);
for (std::vector<DetId>::iterator ac_it=allConstituents.begin();
ac_it!=allConstituents.end(); ++ac_it) {
if (ac_it->det()!=DetId::Ecal) continue;
int thisEcalSevLvl = -999;
if (ac_it->subdetId() == EcalBarrel && theEbHandle.isValid()) {
thisEcalSevLvl = theEcalSevLvlAlgo->severityLevel( *ac_it, *theEbHandle);//, *theEcalChStatus);
}
else if (ac_it->subdetId() == EcalEndcap && theEeHandle.isValid()) {
thisEcalSevLvl = theEcalSevLvlAlgo->severityLevel( *ac_it, *theEeHandle);//, *theEcalChStatus);
}
// check if the Ecal severity is ok to keep
std::vector<int>::const_iterator sevit = std::find(theEcalSeveritiesToBeExcluded.begin(),
theEcalSeveritiesToBeExcluded.end(),
thisEcalSevLvl);
if (sevit!=theEcalSeveritiesToBeExcluded.end()) {
++numBadEcalChan;
}
}
// compare with fast version
// hcal:
int inEcals[2] = {0,0};
for (std::vector<std::pair<DetId,float> >::iterator i=metaContains.begin(); i!=metaContains.end(); ++i) {
DetId detId = i->first;
if(detId.det() == DetId::Ecal){
if( detId.subdetId()==EcalBarrel ) inEcals[0] =1;
else if( detId.subdetId()==EcalEndcap ) inEcals[1] =1;
}
}
auto numBadEcalChanNew = ecalBadChs[theTowerTopology->denseIndex(id)]+mt.numBadEcalCells; // - mt.numRecEcalCells
if (int(numBadEcalChanNew)!=int(numBadEcalChan)) {
std::cout << "VI wrong " << ((inEcals[1]==1) ? "EE" : "" ) << id << " " << numBadEcalChanNew << " " << numBadEcalChan
<< " " << mt.numBadEcalCells << " " << mt.numRecEcalCells << std::endl;
}
*/
numBadEcalChan = ecalBadChs[theTowerTopology->denseIndex(id)] + mt.numBadEcalCells; // - mt.numRecEcalCells
//--------------------------------------------------------------------------------------
caloTower.setCaloTowerStatus(
numBadHcalChan, numBadEcalChan, numRecHcalChan, numRecEcalChan, numProbHcalChan, numProbEcalChan);
double maxCellE = -999.0; // for storing the hottest cell E in the calotower
std::vector<DetId> contains;
contains.reserve(metaContains.size());
for (std::vector<std::pair<DetId, float> >::iterator i = metaContains.begin(); i != metaContains.end(); ++i) {
contains.push_back(i->first);
if (maxCellE < i->second) {
// need an extra check because of the funny towers that are empty except for the presence of an HO
// hit in the constituents (JetMET wanted them saved)
// This constituent is only used for storing the tower, but should not be concidered as a hot cell canditate for
// configurations with useHO = false
if (i->first.det() == DetId::Ecal) { // ECAL
maxCellE = i->second;
} else { // HCAL
if (HcalDetId(i->first).subdet() != HcalOuter)
maxCellE = i->second;
else if (theHOIsUsed)
maxCellE = i->second;
}
} // found higher E cell
} // loop over matacontains
caloTower.setConstituents(std::move(contains));
caloTower.setHottestCellE(maxCellE);
// std::cout << "CaloTowerVI " << nalgo << ' ' << caloTower.id() << ((inEcals[1]==1) ? "EE " : " " ) << caloTower.pt() << ' ' << caloTower.et() << ' ' << caloTower.mass() << ' '
// << caloTower.constituentsSize() <<' '<< caloTower.towerStatusWord() << std::endl;
}
void CaloTowersCreationAlgo::getThresholdAndWeight(const DetId& detId, double& threshold, double& weight) const {
DetId::Detector det = detId.det();
weight = 0; // in case the hit is not identified
if (det == DetId::Ecal) {
// may or may not be EB. We'll find out.
EcalSubdetector subdet = (EcalSubdetector)(detId.subdetId());
if (subdet == EcalBarrel) {
threshold = theEBthreshold;
weight = theEBweight;
if (weight <= 0.) {
ROOT::Math::Interpolator my(theEBGrid, theEBWeights, ROOT::Math::Interpolation::kAKIMA);
weight = my.Eval(theEBEScale);
}
} else if (subdet == EcalEndcap) {
threshold = theEEthreshold;
weight = theEEweight;
if (weight <= 0.) {
ROOT::Math::Interpolator my(theEEGrid, theEEWeights, ROOT::Math::Interpolation::kAKIMA);
weight = my.Eval(theEEEScale);
}
}
} else if (det == DetId::Hcal) {
HcalDetId hcalDetId(detId);
HcalSubdetector subdet = hcalDetId.subdet();
int depth = hcalDetId.depth();
if (subdet == HcalBarrel) {
threshold = (depth == 1) ? theHBthreshold1 : (depth == 2) ? theHBthreshold2 : theHBthreshold;
weight = theHBweight;
if (weight <= 0.) {
ROOT::Math::Interpolator my(theHBGrid, theHBWeights, ROOT::Math::Interpolation::kAKIMA);
weight = my.Eval(theHBEScale);
}
}
else if (subdet == HcalEndcap) {
// check if it's single or double tower
if (hcalDetId.ietaAbs() < theHcalTopology->firstHEDoublePhiRing()) {
threshold = (depth == 1) ? theHESthreshold1 : theHESthreshold;
weight = theHESweight;
if (weight <= 0.) {
ROOT::Math::Interpolator my(theHESGrid, theHESWeights, ROOT::Math::Interpolation::kAKIMA);
weight = my.Eval(theHESEScale);
}
} else {
threshold = (depth == 1) ? theHEDthreshold1 : theHEDthreshold;
weight = theHEDweight;
if (weight <= 0.) {
ROOT::Math::Interpolator my(theHEDGrid, theHEDWeights, ROOT::Math::Interpolation::kAKIMA);
weight = my.Eval(theHEDEScale);
}
}
}
else if (subdet == HcalOuter) {
//check if it's ring 0 or +1 or +2 or -1 or -2
if (hcalDetId.ietaAbs() <= 4)
threshold = theHOthreshold0;
else if (hcalDetId.ieta() < 0) {
// set threshold for ring -1 or -2
threshold = (hcalDetId.ietaAbs() <= 10) ? theHOthresholdMinus1 : theHOthresholdMinus2;
} else {
// set threshold for ring +1 or +2
threshold = (hcalDetId.ietaAbs() <= 10) ? theHOthresholdPlus1 : theHOthresholdPlus2;
}
weight = theHOweight;
if (weight <= 0.) {
ROOT::Math::Interpolator my(theHOGrid, theHOWeights, ROOT::Math::Interpolation::kAKIMA);
weight = my.Eval(theHOEScale);
}
}
else if (subdet == HcalForward) {
if (hcalDetId.depth() == 1) {
threshold = theHF1threshold;
weight = theHF1weight;
if (weight <= 0.) {
ROOT::Math::Interpolator my(theHF1Grid, theHF1Weights, ROOT::Math::Interpolation::kAKIMA);
weight = my.Eval(theHF1EScale);
}
} else {
threshold = theHF2threshold;
weight = theHF2weight;
if (weight <= 0.) {
ROOT::Math::Interpolator my(theHF2Grid, theHF2Weights, ROOT::Math::Interpolation::kAKIMA);
weight = my.Eval(theHF2EScale);
}
}
}
} else {
edm::LogError("CaloTowersCreationAlgo") << "Bad cell: " << det << std::endl;
}
}
void CaloTowersCreationAlgo::setEBEScale(double scale) {
if (scale > 0.00001)
*&theEBEScale = scale;
else
*&theEBEScale = 50.;
}
void CaloTowersCreationAlgo::setEEEScale(double scale) {
if (scale > 0.00001)
*&theEEEScale = scale;
else
*&theEEEScale = 50.;
}
void CaloTowersCreationAlgo::setHBEScale(double scale) {
if (scale > 0.00001)
*&theHBEScale = scale;
else
*&theHBEScale = 50.;
}
void CaloTowersCreationAlgo::setHESEScale(double scale) {
if (scale > 0.00001)
*&theHESEScale = scale;
else
*&theHESEScale = 50.;
}
void CaloTowersCreationAlgo::setHEDEScale(double scale) {
if (scale > 0.00001)
*&theHEDEScale = scale;
else
*&theHEDEScale = 50.;
}
void CaloTowersCreationAlgo::setHOEScale(double scale) {
if (scale > 0.00001)
*&theHOEScale = scale;
else
*&theHOEScale = 50.;
}
void CaloTowersCreationAlgo::setHF1EScale(double scale) {
if (scale > 0.00001)
*&theHF1EScale = scale;
else
*&theHF1EScale = 50.;
}
void CaloTowersCreationAlgo::setHF2EScale(double scale) {
if (scale > 0.00001)
*&theHF2EScale = scale;
else
*&theHF2EScale = 50.;
}
GlobalPoint CaloTowersCreationAlgo::emCrystalShwrPos(DetId detId, float fracDepth) {
auto cellGeometry = theGeometry->getGeometry(detId);
GlobalPoint point = cellGeometry->getPosition(); // face of the cell
if (fracDepth <= 0)
return point;
if (fracDepth > 1)
fracDepth = 1;
const GlobalPoint& backPoint = cellGeometry->getBackPoint();
point += fracDepth * (backPoint - point);
return point;
}
GlobalPoint CaloTowersCreationAlgo::hadSegmentShwrPos(DetId detId, float fracDepth) {
// same code as above
return emCrystalShwrPos(detId, fracDepth);
}
GlobalPoint CaloTowersCreationAlgo::hadShwrPos(const std::vector<std::pair<DetId, float> >& metaContains,
float fracDepth,
double hadE) {
// this is based on available RecHits, can lead to different actual depths if
// hits in multi-depth towers are not all there
#ifdef EDM_ML_DEBUG
std::cout << "hadShwrPos called with " << metaContains.size() << " elements and energy " << hadE << ":" << fracDepth
<< std::endl;
#endif
if (hadE <= 0)
return GlobalPoint(0, 0, 0);
double hadX = 0.0;
double hadY = 0.0;
double hadZ = 0.0;
int nConst = 0;
std::vector<std::pair<DetId, float> >::const_iterator mc_it = metaContains.begin();
for (; mc_it != metaContains.end(); ++mc_it) {
if (mc_it->first.det() != DetId::Hcal)
continue;
// do not use HO for deirection calculations for now
if (HcalDetId(mc_it->first).subdet() == HcalOuter)
continue;
++nConst;
GlobalPoint p = hadSegmentShwrPos(mc_it->first, fracDepth);
// longitudinal segmentation: do not weight by energy,
// get the geometrical position
hadX += p.x();
hadY += p.y();
hadZ += p.z();
}
return GlobalPoint(hadX / nConst, hadY / nConst, hadZ / nConst);
}
GlobalPoint CaloTowersCreationAlgo::hadShwrPos(CaloTowerDetId towerId, float fracDepth) {
// set depth using geometry of cells that are associated with the
// tower (regardless if they have non-zero energies)
// if (hadE <= 0) return GlobalPoint(0, 0, 0);
#ifdef EDM_ML_DEBUG
std::cout << "hadShwrPos " << towerId << " frac " << fracDepth << std::endl;
#endif
if (fracDepth < 0)
fracDepth = 0;
else if (fracDepth > 1)
fracDepth = 1;
GlobalPoint point(0, 0, 0);
int iEta = towerId.ieta();
int iPhi = towerId.iphi();
HcalDetId frontCellId, backCellId;
if (towerId.ietaAbs() >= theTowerTopology->firstHFRing()) {
// forward, take the geometry for long fibers
frontCellId = HcalDetId(HcalForward, towerId.zside() * theTowerTopology->convertCTtoHcal(abs(iEta)), iPhi, 1);
backCellId = HcalDetId(HcalForward, towerId.zside() * theTowerTopology->convertCTtoHcal(abs(iEta)), iPhi, 1);
} else {
//use constituents map
std::vector<DetId> items = theTowerConstituentsMap->constituentsOf(towerId);
int frontDepth = 1000;
int backDepth = -1000;
for (unsigned i = 0; i < items.size(); i++) {
if (items[i].det() != DetId::Hcal)
continue;
HcalDetId hid(items[i]);
if (hid.subdet() == HcalOuter)
continue;
if (!theHcalTopology->validHcal(hid, 2))
continue;
if (theHcalTopology->idFront(hid).depth() < frontDepth) {
frontCellId = hid;
frontDepth = theHcalTopology->idFront(hid).depth();
}
if (theHcalTopology->idBack(hid).depth() > backDepth) {
backCellId = hid;
backDepth = theHcalTopology->idBack(hid).depth();
}
}
#ifdef EDM_ML_DEBUG
std::cout << "Front " << frontCellId << " Back " << backCellId << " Depths " << frontDepth << ":" << backDepth
<< std::endl;
#endif
//fix for tower 28/29 - no tower 29 at highest depths
if (towerId.ietaAbs() == theTowerTopology->lastHERing() && (theHcalPhase == 0 || theHcalPhase == 1)) {
CaloTowerDetId towerId28(towerId.ieta() - towerId.zside(), towerId.iphi());
std::vector<DetId> items28 = theTowerConstituentsMap->constituentsOf(towerId28);
#ifdef EDM_ML_DEBUG
std::cout << towerId28 << " with " << items28.size() << " constituents:";
for (unsigned k = 0; k < items28.size(); ++k)
if (items28[k].det() == DetId::Hcal)
std::cout << " " << HcalDetId(items28[k]);
std::cout << std::endl;
#endif
for (unsigned i = 0; i < items28.size(); i++) {
if (items28[i].det() != DetId::Hcal)
continue;
HcalDetId hid(items28[i]);
if (hid.subdet() == HcalOuter)
continue;
if (theHcalTopology->idBack(hid).depth() > backDepth) {
backCellId = hid;
backDepth = theHcalTopology->idBack(hid).depth();
}
}
}
#ifdef EDM_ML_DEBUG
std::cout << "Back " << backDepth << " ID " << backCellId << std::endl;
#endif
}
point = hadShwPosFromCells(DetId(frontCellId), DetId(backCellId), fracDepth);
return point;
}
GlobalPoint CaloTowersCreationAlgo::hadShwPosFromCells(DetId frontCellId, DetId backCellId, float fracDepth) {
// uses the "front" and "back" cells
// to determine the axis. point set by the predefined depth.
HcalDetId hid1(frontCellId), hid2(backCellId);
if (theHcalTopology->getMergePositionFlag()) {
hid1 = theHcalTopology->idFront(frontCellId);
#ifdef EDM_ML_DEBUG
std::cout << "Front " << HcalDetId(frontCellId) << " " << hid1 << "\n";
#endif
hid2 = theHcalTopology->idBack(backCellId);
#ifdef EDM_ML_DEBUG
std::cout << "Back " << HcalDetId(backCellId) << " " << hid2 << "\n";
#endif
}
auto frontCellGeometry = theGeometry->getGeometry(DetId(hid1));
auto backCellGeometry = theGeometry->getGeometry(DetId(hid2));
GlobalPoint point = frontCellGeometry->getPosition();
const GlobalPoint& backPoint = backCellGeometry->getBackPoint();
point += fracDepth * (backPoint - point);
return point;
}
GlobalPoint CaloTowersCreationAlgo::emShwrPos(const std::vector<std::pair<DetId, float> >& metaContains,
float fracDepth,
double emE) {
if (emE <= 0)
return GlobalPoint(0, 0, 0);
double emX = 0.0;
double emY = 0.0;
double emZ = 0.0;
double eSum = 0;
std::vector<std::pair<DetId, float> >::const_iterator mc_it = metaContains.begin();
for (; mc_it != metaContains.end(); ++mc_it) {
if (mc_it->first.det() != DetId::Ecal)
continue;
GlobalPoint p = emCrystalShwrPos(mc_it->first, fracDepth);
double e = mc_it->second;
if (e > 0) {
emX += p.x() * e;
emY += p.y() * e;
emZ += p.z() * e;
eSum += e;
}
}
return GlobalPoint(emX / eSum, emY / eSum, emZ / eSum);
}
GlobalPoint CaloTowersCreationAlgo::emShwrLogWeightPos(const std::vector<std::pair<DetId, float> >& metaContains,
float fracDepth,
double emE) {
double emX = 0.0;
double emY = 0.0;
double emZ = 0.0;
double weight = 0;
double sumWeights = 0;
double sumEmE = 0; // add crystals with E/E_EM > 1.5%
double crystalThresh = 0.015 * emE;
std::vector<std::pair<DetId, float> >::const_iterator mc_it = metaContains.begin();
for (; mc_it != metaContains.end(); ++mc_it) {
if (mc_it->second < 0)
continue;
if (mc_it->first.det() == DetId::Ecal && mc_it->second > crystalThresh)
sumEmE += mc_it->second;
}
for (mc_it = metaContains.begin(); mc_it != metaContains.end(); ++mc_it) {
if (mc_it->first.det() != DetId::Ecal || mc_it->second < crystalThresh)
continue;
GlobalPoint p = emCrystalShwrPos(mc_it->first, fracDepth);
weight = 4.2 + log(mc_it->second / sumEmE);
sumWeights += weight;
emX += p.x() * weight;
emY += p.y() * weight;
emZ += p.z() * weight;
}
return GlobalPoint(emX / sumWeights, emY / sumWeights, emZ / sumWeights);
}
int CaloTowersCreationAlgo::compactTime(float time) {
const float timeUnit = 0.01; // discretization (ns)
if (time > 300.0)
return 30000;
if (time < -300.0)
return -30000;
return int(time / timeUnit + 0.5);
}
//========================================================
//
// Bad/anomolous cell handling
void CaloTowersCreationAlgo::makeHcalDropChMap() {
// This method fills the map of number of dead channels for the calotower,
// The key of the map is CaloTowerDetId.
// By definition these channels are not going to be in the RecHit collections.
hcalDropChMap.clear();
std::vector<DetId> allChanInStatusCont = theHcalChStatus->getAllChannels();
#ifdef EDM_ML_DEBUG
std::cout << "DropChMap with " << allChanInStatusCont.size() << " channels" << std::endl;
#endif
for (std::vector<DetId>::iterator it = allChanInStatusCont.begin(); it != allChanInStatusCont.end(); ++it) {
const uint32_t dbStatusFlag = theHcalChStatus->getValues(*it)->getValue();
if (theHcalSevLvlComputer->dropChannel(dbStatusFlag)) {
DetId id = theHcalTopology->mergedDepthDetId(HcalDetId(*it));
CaloTowerDetId twrId = theTowerConstituentsMap->towerOf(id);
hcalDropChMap[twrId].first += 1;
HcalDetId hid(*it);
// special case for tower 29: if HCAL hit is in depth 3 add to twr 29 as well
if (hid.subdet() == HcalEndcap && (theHcalPhase == 0 || theHcalPhase == 1) &&
hid.ietaAbs() == theHcalTopology->lastHERing() - 1) {
bool merge = theHcalTopology->mergedDepth29(hid);
if (merge) {
CaloTowerDetId twrId29(twrId.ieta() + twrId.zside(), twrId.iphi());
hcalDropChMap[twrId29].first += 1;
}
}
}
}
// now I know how many bad channels, but I also need to know if there's any good ones
if (missingHcalRescaleFactorForEcal > 0) {
for (auto& pair : hcalDropChMap) {
if (pair.second.first == 0)
continue; // unexpected, but just in case
int ngood = 0, nbad = 0;
for (DetId id : theTowerConstituentsMap->constituentsOf(pair.first)) {
if (id.det() != DetId::Hcal)
continue;
HcalDetId hid(id);
if (hid.subdet() != HcalBarrel && hid.subdet() != HcalEndcap)
continue;
const uint32_t dbStatusFlag = theHcalChStatus->getValues(id)->getValue();
if (dbStatusFlag == 0 || !theHcalSevLvlComputer->dropChannel(dbStatusFlag)) {
ngood += 1;
} else {
nbad += 1; // recount, since pair.second.first may include HO
}
}
if (nbad > 0 && nbad >= ngood) {
//uncomment for debug (may be useful to tune the criteria above)
//CaloTowerDetId id(pair.first);
//std::cout << "CaloTower at ieta = " << id.ieta() << ", iphi " << id.iphi() << ": set Hcal as not efficient (ngood =" << ngood << ", nbad = " << nbad << ")" << std::endl;
pair.second.second = true;
}
}
}
}
void CaloTowersCreationAlgo::makeEcalBadChs() {
// std::cout << "VI making EcalBadChs ";
// for ECAL the number of all bad channels is obtained here -----------------------
for (auto ind = 0U; ind < theTowerTopology->sizeForDenseIndexing(); ++ind) {
auto& numBadEcalChan = ecalBadChs[ind];
numBadEcalChan = 0;
auto id = theTowerTopology->detIdFromDenseIndex(ind);
// this is utterly slow... (can be optmized if really needed)
// get all possible constituents of the tower
std::vector<DetId> allConstituents = theTowerConstituentsMap->constituentsOf(id);
for (std::vector<DetId>::iterator ac_it = allConstituents.begin(); ac_it != allConstituents.end(); ++ac_it) {
if (ac_it->det() != DetId::Ecal)
continue;
auto thisEcalSevLvl = theEcalSevLvlAlgo->severityLevel(*ac_it);
// check if the Ecal severity is ok to keep
std::vector<int>::const_iterator sevit =
std::find(theEcalSeveritiesToBeExcluded.begin(), theEcalSeveritiesToBeExcluded.end(), thisEcalSevLvl);
if (sevit != theEcalSeveritiesToBeExcluded.end()) {
++numBadEcalChan;
}
}
// if (0!=numBadEcalChan) std::cout << id << ":" << numBadEcalChan << ", ";
}
/*
int tot=0;
for (auto ind=0U; ind<theTowerTopology->sizeForDenseIndexing(); ++ind) {
if (ecalBadChs[ind]!=0) ++tot;
}
std::cout << " | " << tot << std::endl;
*/
}
////// Get status of the channel contributing to the tower
unsigned int CaloTowersCreationAlgo::hcalChanStatusForCaloTower(const CaloRecHit* hit) {
HcalDetId hid(hit->detid());
DetId id = theHcalTopology->idFront(hid);
#ifdef EDM_ML_DEBUG
std::cout << "ChanStatusForCaloTower for " << hid << " to " << HcalDetId(id) << std::endl;
#endif
const uint32_t recHitFlag = hit->flags();
const uint32_t dbStatusFlag = theHcalChStatus->getValues(id)->getValue();
int severityLevel = theHcalSevLvlComputer->getSeverityLevel(id, recHitFlag, dbStatusFlag);
bool isRecovered = theHcalSevLvlComputer->recoveredRecHit(id, recHitFlag);
// For use with hits rejected in the default reconstruction
if (useRejectedHitsOnly) {
if (!isRecovered) {
if (severityLevel <= int(theHcalAcceptSeverityLevel) ||
severityLevel > int(theHcalAcceptSeverityLevelForRejectedHit))
return CaloTowersCreationAlgo::IgnoredChan;
// this hit was either already accepted or is worse than
} else {
if (theRecoveredHcalHitsAreUsed || !useRejectedRecoveredHcalHits) {
// skip recovered hits either because they were already used or because there was an explicit instruction
return CaloTowersCreationAlgo::IgnoredChan;
} else if (useRejectedRecoveredHcalHits) {
return CaloTowersCreationAlgo::RecoveredChan;
}
} // recovered channels
// clasify channels as problematic: no good hits are supposed to be present in the
// extra rechit collections
return CaloTowersCreationAlgo::ProblematicChan;
} // treatment of rejected hits
// this is for the regular reconstruction sequence
if (severityLevel == 0)
return CaloTowersCreationAlgo::GoodChan;
if (isRecovered) {
return (theRecoveredHcalHitsAreUsed) ? CaloTowersCreationAlgo::RecoveredChan : CaloTowersCreationAlgo::BadChan;
} else {
if (severityLevel > int(theHcalAcceptSeverityLevel)) {
return CaloTowersCreationAlgo::BadChan;
} else {
return CaloTowersCreationAlgo::ProblematicChan;
}
}
}
std::tuple<unsigned int, bool> CaloTowersCreationAlgo::ecalChanStatusForCaloTower(const EcalRecHit* hit) {
// const DetId id = hit->detid();
// uint16_t dbStatus = theEcalChStatus->find(id)->getStatusCode();
// uint32_t rhFlags = hit->flags();
// int severityLevel = theEcalSevLvlAlgo->severityLevel(rhFlags, dbStatus);
// The methods above will become private and cannot be usef for flagging ecal spikes.
// Use the recommended interface - we leave the parameters for spilke removal to be specified by ECAL.
// int severityLevel = 999;
EcalRecHit const& rh = *reinterpret_cast<EcalRecHit const*>(hit);
int severityLevel = theEcalSevLvlAlgo->severityLevel(rh);
// if (id.subdetId() == EcalBarrel) severityLevel = theEcalSevLvlAlgo->severityLevel( id, *theEbHandle);//, *theEcalChStatus);
// else if (id.subdetId() == EcalEndcap) severityLevel = theEcalSevLvlAlgo->severityLevel( id, *theEeHandle);//, *theEcalChStatus);
// there should be no other ECAL types used in this reconstruction
// The definition of ECAL severity levels uses categories that
// are similar to the defined for CaloTower. (However, the categorization
// for CaloTowers depends on the specified maximum acceptabel severity and therefore cannnot
// be exact correspondence between the two. ECAL has additional categories describing modes of failure.)
// This approach is different from the initial idea and from
// the implementation for HCAL. Still make the logic similar to HCAL so that one has the ability to
// exclude problematic channels as defined by ECAL.
// For definitions of ECAL severity levels see RecoLocalCalo/EcalRecAlgos/interface/EcalSeverityLevelAlgo.h
bool isBad = (severityLevel == EcalSeverityLevel::kBad);
bool isRecovered = (severityLevel == EcalSeverityLevel::kRecovered);
// check if the severity is compatible with our configuration
// This applies to the "default" tower cleaning
std::vector<int>::const_iterator sevit =
std::find(theEcalSeveritiesToBeExcluded.begin(), theEcalSeveritiesToBeExcluded.end(), severityLevel);
bool accepted = (sevit == theEcalSeveritiesToBeExcluded.end());
// For use with hits that were rejected in the regular reconstruction:
// This is for creating calotowers with lower level of cleaning by merging
// the information from the default towers and a collection of towers created from
// bad rechits
if (useRejectedHitsOnly) {
if (!isRecovered) {
if (accepted || std::find(theEcalSeveritiesToBeUsedInBadTowers.begin(),
theEcalSeveritiesToBeUsedInBadTowers.end(),
severityLevel) == theEcalSeveritiesToBeUsedInBadTowers.end())
return std::make_tuple(CaloTowersCreationAlgo::IgnoredChan, isBad);
// this hit was either already accepted, or is not eligible for inclusion
} else {
if (theRecoveredEcalHitsAreUsed || !useRejectedRecoveredEcalHits) {
// skip recovered hits either because they were already used or because there was an explicit instruction
return std::make_tuple(CaloTowersCreationAlgo::IgnoredChan, isBad);
;
} else if (useRejectedRecoveredEcalHits) {
return std::make_tuple(CaloTowersCreationAlgo::RecoveredChan, isBad);
}
} // recovered channels
// clasify channels as problematic
return std::make_tuple(CaloTowersCreationAlgo::ProblematicChan, isBad);
} // treatment of rejected hits
// for normal reconstruction
if (severityLevel == EcalSeverityLevel::kGood)
return std::make_tuple(CaloTowersCreationAlgo::GoodChan, false);
if (isRecovered) {
return std::make_tuple(
(theRecoveredEcalHitsAreUsed) ? CaloTowersCreationAlgo::RecoveredChan : CaloTowersCreationAlgo::BadChan, true);
} else {
return std::make_tuple(accepted ? CaloTowersCreationAlgo::ProblematicChan : CaloTowersCreationAlgo::BadChan, isBad);
}
}
| 38.610845 | 204 | 0.60779 | malbouis |
6dd9babda4a11fbe0588758e8ccd994a30672af8 | 3,770 | cpp | C++ | src/appleseed/foundation/platform/defaulttimers.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | 1 | 2021-04-02T10:51:57.000Z | 2021-04-02T10:51:57.000Z | src/appleseed/foundation/platform/defaulttimers.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | null | null | null | src/appleseed/foundation/platform/defaulttimers.cpp | istemi-bahceci/appleseed | 2db1041acb04bad4742cf7826ce019f0e623fe35 | [
"MIT"
] | null | null | null |
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// 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.
//
// Interface header.
#include "defaulttimers.h"
// appleseed.foundation headers.
#ifdef _WIN32
#include "foundation/platform/windows.h"
#endif
// Standard headers.
#include <ctime>
#if defined _WIN32
#include <sys/timeb.h>
#include <sys/types.h>
#elif defined __GNUC__
#include <sys/time.h>
#endif
using namespace std;
namespace foundation
{
//
// DefaultProcessorTimer class implementation.
//
DefaultProcessorTimer::DefaultProcessorTimer()
{
// Windows.
#if defined _WIN32
// Check whether QueryPerformanceCounter() is available.
LARGE_INTEGER frequency;
m_has_qpc = QueryPerformanceFrequency(&frequency) != 0;
#endif
}
uint64 DefaultProcessorTimer::frequency()
{
// Windows.
#if defined _WIN32
if (m_has_qpc)
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return static_cast<uint64>(frequency.QuadPart);
}
else
{
return static_cast<uint64>(CLOCKS_PER_SEC);
}
// Other platforms.
#else
return static_cast<uint64>(CLOCKS_PER_SEC);
#endif
}
uint64 DefaultProcessorTimer::read()
{
// Windows.
#if defined _WIN32
if (m_has_qpc)
{
LARGE_INTEGER count;
QueryPerformanceCounter(&count);
return static_cast<uint64>(count.QuadPart);
}
else
{
return static_cast<uint64>(clock());
}
// Other platforms.
#else
//
// On Linux, we might want to use clock_gettime(CLOCK_REALTIME).
//
// Andrei Alexandrescu, Writing Fast Code
// https://youtu.be/vrfYLlR8X8k?t=1973
//
return static_cast<uint64>(clock());
#endif
}
//
// DefaultWallclockTimer class implementation.
//
uint64 DefaultWallclockTimer::frequency()
{
// POSIX platforms.
#if defined __GNUC__
return 1000000;
// Windows.
#elif defined _WIN32
return 1000;
// Other platforms.
#else
return 1;
#endif
}
uint64 DefaultWallclockTimer::read()
{
// POSIX platforms.
#if defined __GNUC__
timeval tv;
gettimeofday(&tv, 0);
return static_cast<uint64>(tv.tv_sec) * 1000000 + static_cast<uint64>(tv.tv_usec);
// Windows.
#elif defined _WIN32
__timeb64 tb;
_ftime64(&tb);
return static_cast<uint64>(tb.time) * 1000 + static_cast<uint64>(tb.millitm);
// Other platforms.
#else
const time_t seconds = time(0);
return static_cast<uint64>(seconds);
#endif
}
} // namespace foundation
| 21.666667 | 86 | 0.711936 | istemi-bahceci |
6dda92928b28a08d4fd15c022d7a19a66dcf49c6 | 1,482 | cc | C++ | components/invalidation/fake_invalidation_state_tracker.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-01-25T10:18:18.000Z | 2021-01-23T15:29:56.000Z | components/invalidation/fake_invalidation_state_tracker.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | components/invalidation/fake_invalidation_state_tracker.cc | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/invalidation/fake_invalidation_state_tracker.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/location.h"
#include "base/task_runner.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer {
const int64 FakeInvalidationStateTracker::kMinVersion = kint64min;
FakeInvalidationStateTracker::FakeInvalidationStateTracker() {}
FakeInvalidationStateTracker::~FakeInvalidationStateTracker() {}
void FakeInvalidationStateTracker::ClearAndSetNewClientId(
const std::string& client_id) {
Clear();
invalidator_client_id_ = client_id;
}
std::string FakeInvalidationStateTracker::GetInvalidatorClientId() const {
return invalidator_client_id_;
}
void FakeInvalidationStateTracker::SetBootstrapData(
const std::string& data) {
bootstrap_data_ = data;
}
std::string FakeInvalidationStateTracker::GetBootstrapData() const {
return bootstrap_data_;
}
void FakeInvalidationStateTracker::SetSavedInvalidations(
const UnackedInvalidationsMap& states) {
unacked_invalidations_map_ = states;
}
UnackedInvalidationsMap
FakeInvalidationStateTracker::GetSavedInvalidations() const {
return unacked_invalidations_map_;
}
void FakeInvalidationStateTracker::Clear() {
invalidator_client_id_.clear();
bootstrap_data_.clear();
}
} // namespace syncer
| 26.464286 | 74 | 0.798246 | kjthegod |
6ddad5089bd8dc2a531736c0f047965a4d65b5ba | 4,080 | hpp | C++ | include/site.hpp | SavAct/SavWeb | 0c57ddb94df2a27d5a197cc23c481742cd85962b | [
"MIT"
] | null | null | null | include/site.hpp | SavAct/SavWeb | 0c57ddb94df2a27d5a197cc23c481742cd85962b | [
"MIT"
] | null | null | null | include/site.hpp | SavAct/SavWeb | 0c57ddb94df2a27d5a197cc23c481742cd85962b | [
"MIT"
] | null | null | null | #include "tables.hpp"
using namespace std;
using namespace eosio;
CONTRACT site : public contract {
public:
using contract::contract;
#define errorTableKey "There is no entry with this key."
#define errorOldNotMatch "Old reffered transaction doesn't match the last reffered transaction."
#define errorRefHigerOrEven "Reffered block has to be higher or even to old reffered block."
#define errorUserNotAuth "User is not authorized to perform this action."
#define errorFirstNotMatch "First reffered transaction doesn't match."
#define errorContractToManyRefs "Contract Error: There are more than two refrences."
#define errorMissingOldRef "Missing old reference."
/**
* First transaction to start the upload of a file. Additional parameters will be used to verify the files with the browser.
* @param scope Scope of the entry
* @param key Index key of the entry
* @param fname File name
* @param type Type of the file
* @param format Enryption format
* @param fsize Amount of bytes of the complete file
* @param attri Otional attributes of the file
* @param originators All originators with their share. (Prefixes define the type of a share and originator reference)
* @param resalefee This is the amount of fee which will granted to the originators by considering the share of each originator. Fee = (max value of uint16_t) / resalefee.
* @param hash The hash of the file as byte array
* @param code The first byte section of the file
*/
ACTION uploadbegin(name scope, uint64_t key, string& fname, string& type, string& format, uint32_t fsize, string& attri, string& originators, uint16_t resalefee, string& hash, string& code);
/**
* Upload the next file snipped
* @param scope Scope of the entry
* @param key Index key of the entry
* @param refs refs[0] is a reference to last transaction and refs[1] a reference to the old last transaction
* @param code The next byte section of the file
*/
ACTION uploadnext(name scope, uint64_t key, vector<Ref>& refs, string& code);
/**
* Update the references in the RAM to the very last transaction
* @param scope Scope of the entry
* @param key Index key of the entry
* @param refs refs[0] is a reference to last transaction and refs[1] a reference to the old last transaction
*/
ACTION updateref(name scope, uint64_t key, vector<Ref>& refs);
/**
* Delete an entry. This can be performed by the scope or owner of the contract
* @param scope The scope of the entry
* @param key The index key of the entry
*/
ACTION deleteentry(name scope, uint64_t key);
/**
* Delete a whole scope. This can be performed by the scope or owner of the contract
* @param scope The scope which will be deleted
*/
ACTION clearscope(name scope);
/**
* Change the index key of an entry
* @param scope The scope of the entry
* @param key The index key of the entry
* @param newkey The new index key
*/
ACTION changekey(name scope, uint64_t key, uint64_t newkey);
/**
* Functions without any checking or table entry. They are just to upload a file with a minimum need of CPU
*/
ACTION minbegin(name scope, uint64_t key, string& fname, string& type, string& format, uint32_t fsize, string& attri, string& originators, uint16_t resalefee, string& hash, string& code){}
ACTION minnext(name scope, uint64_t key, Ref& ref, string& code){}
ACTION minend(name scope, uint64_t key, Ref& ref, Ref& fref, string& code){}
/**
* Emplace the reference of an already uploaded file in a table
* @param scope Scope of the entry
* @param key Index key of the entry
* @param refs refs[0] is a reference to last transaction and refs[1] a reference to the first transaction if it differs from refs[0]
* @param attri Optional attributes of the file
*/
ACTION setref(name scope, uint64_t key, string& fname, vector<Ref> refs, string attri);
private:
};
| 44.835165 | 194 | 0.698775 | SavAct |
6ddc8b5b8ab78d0b2cf778fd67ad25399042660f | 1,716 | cpp | C++ | src/medCore/medJobManager.cpp | lcatanes/medInria-public | 5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f | [
"BSD-4-Clause"
] | 1 | 2020-11-16T13:55:45.000Z | 2020-11-16T13:55:45.000Z | src/medCore/medJobManager.cpp | lcatanes/medInria-public | 5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f | [
"BSD-4-Clause"
] | null | null | null | src/medCore/medJobManager.cpp | lcatanes/medInria-public | 5d79ce0085c11f2fb9277a06c8cf56b4258a9d9f | [
"BSD-4-Clause"
] | null | null | null | /*=========================================================================
medInria
Copyright (c) INRIA 2013 - 2014. All rights reserved.
See LICENSE.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.
=========================================================================*/
#include <medJobManager.h>
#include <medJobItem.h>
medJobManager *medJobManager::s_instance = NULL;
class medJobManagerPrivate
{
public:
QList<medJobItem*> itemList;
bool m_IsActive;
};
medJobManager *medJobManager::instance(void)
{
if(!s_instance)
s_instance = new medJobManager;
return s_instance;
}
medJobManager::medJobManager( void ) : d(new medJobManagerPrivate)
{
d->m_IsActive = true;
}
medJobManager::~medJobManager( void )
{
delete d;
d = NULL;
}
bool medJobManager::registerJobItem( medJobItem* item, QString jobName)
{
if(d->m_IsActive)
{
d->itemList.append(item);
connect(this, SIGNAL(cancel(QObject*)), item, SLOT(onCancel(QObject*)) );
emit jobRegistered(item, jobName);
return true;
}
return false;
}
bool medJobManager::unRegisterJobItem( medJobItem* item )
{
int index = d->itemList.indexOf(item);
if (index != -1)
{
disconnect(this, SIGNAL(cancel(QObject*)), item, SLOT(onCancel(QObject*)) );
d->itemList.removeAt(index);
return true;
}
return false;
}
void medJobManager::dispatchGlobalCancelEvent(bool ignoreNewJobItems)
{
if (ignoreNewJobItems)
d->m_IsActive = false;
foreach( medJobItem* item, d->itemList )
emit cancel( item );
}
| 22.285714 | 84 | 0.617133 | lcatanes |
6ddd9bd83114b46592b1024577193156d431cea1 | 11,413 | cpp | C++ | Code/toolboxes/BSR/ucm/ucm_mean_pb.cpp | corganhejijun/crisp-boundaries-win32 | 8cfea4d1e337f4b30e1e1ad873683139ee7821fb | [
"BSD-3-Clause"
] | null | null | null | Code/toolboxes/BSR/ucm/ucm_mean_pb.cpp | corganhejijun/crisp-boundaries-win32 | 8cfea4d1e337f4b30e1e1ad873683139ee7821fb | [
"BSD-3-Clause"
] | null | null | null | Code/toolboxes/BSR/ucm/ucm_mean_pb.cpp | corganhejijun/crisp-boundaries-win32 | 8cfea4d1e337f4b30e1e1ad873683139ee7821fb | [
"BSD-3-Clause"
] | null | null | null | /*
Source code for computing ultrametric contour maps based on average boundary strength, as described in :
P. Arbelaez, M. Maire, C. Fowlkes, and J. Malik. From contours to regions: An empirical evaluation. In CVPR, 2009.
Pablo Arbelaez <arbelaez@eecs.berkeley.edu>
March 2009.
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <iostream>
#include <deque>
#include <queue>
#include <vector>
#include <list>
#include <map>
using namespace std;
#include "mex.h"
/*************************************************************/
/******************************************************************************/
#ifndef Order_node_h
#define Order_node_h
class Order_node
{
public:
double energy;
int region1;
int region2;
Order_node(){ energy = 0.0; region1 = 0; region2 = 0; }
Order_node( const double& e, const int& rregion1, const int& rregion2 )
{
energy = e;
region1 = rregion1;
region2 = rregion2;
}
~Order_node(){}
// LEXICOGRAPHIC ORDER on priority queue: (energy,label)
bool operator < (const Order_node& x) const { return ( ( energy > x.energy ) ||(( energy == x.energy ) && (region1 > x.region1)) ||(( energy == x.energy ) && (region1 == x.region1)&& (region2 > x.region2))); }
};
#endif
/******************************************************************************/
#ifndef Neighbor_Region_h
#define Neighbor_Region_h
class Neighbor_Region
{
public:
double energy;
double total_pb;
double bdry_length;
Neighbor_Region()
{ energy = 0.0; total_pb = 0.0; bdry_length = 0.0; }
Neighbor_Region(const Neighbor_Region& v)
{ energy = v.energy; total_pb = v.total_pb; bdry_length = v.bdry_length; }
Neighbor_Region(const double& en, const double& tt, const double& bor )
{
energy = en;
total_pb = tt;
bdry_length = bor;
}
~Neighbor_Region(){}
};
#endif
/******************************************************************************/
#ifndef Bdry_element_h
#define Bdry_element_h
class Bdry_element
{
public:
int coord;
int cc_neigh;
Bdry_element(){}
Bdry_element(const int& c, const int& v) { coord = c; cc_neigh = v;}
Bdry_element(const Bdry_element& n) { coord = n.coord; cc_neigh = n.cc_neigh;}
~Bdry_element(){}
bool operator ==(const Bdry_element& n) const { return ( ( coord == n.coord) && ( cc_neigh == n.cc_neigh) ) ; }
// LEXICOGRAPHIC ORDER: (cc_neigh, coord)
bool operator < (const Bdry_element& n) const { return ( (cc_neigh < n.cc_neigh) || ((cc_neigh == n.cc_neigh) && ( coord < n.coord))); }
};
#endif
/******************************************************************************/
#ifndef Region_h
#define Region_h
class Region
{
public:
list<int> elements;
map<int, Neighbor_Region, less<int> > neighbors;
list<Bdry_element> boundary;
Region(){}
Region(const int& l) { elements.push_back(l); }
~Region(){}
void merge( Region& r, int* labels, const int& label, double* ucm, const double& saliency, const int& son, const int& tx );
};
void Region::merge( Region& r, int* labels, const int& label, double* ucm, const double& saliency, const int& son, const int& tx )
{
/* I. BOUNDARY */
// Ia. update father's boundary
list<Bdry_element>::iterator itrb, itrb2;
itrb = boundary.begin();
while ( itrb != boundary.end() )
{
if( labels[(*itrb).cc_neigh] == son )
{
itrb2 = itrb;
++itrb;
boundary.erase(itrb2);
}
else ++itrb;
}
int coord_contour;
// Ib. move son's boundary to father
for( itrb = r.boundary.begin(); itrb != r.boundary.end(); ++itrb )
{
if (ucm[(*itrb).coord] < saliency ) ucm[(*itrb).coord] = saliency;
if ( labels[(*itrb).cc_neigh] != label )
boundary.push_back( Bdry_element(*itrb) );
}
r.boundary.erase( r.boundary.begin(), r.boundary.end() );
/* II. ELEMENTS */
for( list<int>::iterator p = r.elements.begin(); p != r.elements.end(); ++p ) labels[*p] = label;
elements.insert( elements.begin(), r.elements.begin(), r.elements.end() );
r.elements.erase( r.elements.begin(), r.elements.end() );
/* III. NEIGHBORS */
map<int,Neighbor_Region, less<int> >::iterator itr, itr2;
// IIIa. remove inactive neighbors from father
itr = neighbors.begin();
while( itr != neighbors.end() )
{
if ( labels[(*itr).first] != (*itr).first )
{
itr2 = itr;
++itr;
neighbors.erase(itr2);
} else ++itr;
}
// IIIb. remove inactive neighbors from son y and neighbors belonging to father
itr = r.neighbors.begin();
while ( itr != r.neighbors.end() )
{
if ( ( labels[(*itr).first] != (*itr).first ) || ( labels[(*itr).first] == label ) )
{
itr2 = itr;
++itr;
r.neighbors.erase(itr2);
} else ++itr;
}
}
#endif
/*************************************************************/
void complete_contour_map(double* ucm, const int& txc, const int& tyc)
/* complete contour map by max strategy on Khalimsky space */
{
int vx[4] = { 1, 0, -1, 0 };
int vy[4] = { 0, 1, 0, -1 };
int nxp, nyp, cv;
double maximo;
for( int x = 0; x < txc; x = x + 2 ) for( int y = 0; y < tyc; y = y + 2 )
{
maximo = 0.0;
for( int v = 0; v < 4; v++ )
{
nxp = x + vx[v] ; nyp = y + vy[v]; cv = nxp + nyp * txc;
if ( (nyp >= 0) && (nyp < tyc) && (nxp < txc) && (nxp >= 0) && ( maximo < ucm[cv] ) )
maximo = ucm[cv];
}
ucm[x + y*txc] = maximo;
}
}
/***************************************************************************************************************************/
void compute_ucm
( double* local_boundaries, int* initial_partition, const int& totcc, double* ucm, const int& tx, const int& ty)
{
// I. INITIATE
int p,c;
int* labels = new int[totcc];
for(c = 0; c < totcc; c++ )
{
labels[c] = c;
}
// II. ULTRAMETRIC
Region* R = new Region[totcc];
priority_queue<Order_node, vector<Order_node>, less<Order_node> > merging_queue;
double totalPb, totalBdry, dissimilarity;
int v,px;
for( p = 0; p < (2*tx+1)*(2*ty+1); p++ ) ucm[p] = 0.0;
// INITIATE REGI0NS
for ( c = 0; c < totcc; c++ ) R[c] = Region(c);
// INITIATE UCM
int vx[4] = { 1, 0, -1, 0};
int vy[4] = { 0, 1, 0, -1};
int nxp, nyp, cnp, xp, yp, label;
for( p = 0; p < tx*ty; p++ )
{
xp = p%tx; yp = p/tx;
for( v = 0; v < 4; v++ )
{
nxp = xp + vx[v]; nyp = yp + vy[v]; cnp = nxp + nyp*tx;
if ( (nyp >= 0) && (nyp < ty) && (nxp < tx) && (nxp >= 0) && (initial_partition[cnp] != initial_partition[p]) )
R[initial_partition[p]].boundary.push_back(Bdry_element(( xp + nxp + 1 ) + ( yp + nyp + 1 )*(2*tx+1), initial_partition[cnp]));
}
}
// INITIATE merging_queue
list<Bdry_element>::iterator itrb;
for ( c = 0; c < totcc; c++ )
{
R[c].boundary.sort();
label = (*R[c].boundary.begin()).cc_neigh;
totalBdry = 0.0;
totalPb = 0.0;
for ( itrb = R[c].boundary.begin(); itrb != R[c].boundary.end(); ++itrb )
{
if ((*itrb).cc_neigh == label)
{
totalBdry++;
totalPb += local_boundaries[(*itrb).coord];
}
else
{
R[c].neighbors[label] = Neighbor_Region(totalPb/totalBdry, totalPb, totalBdry);
if( label > c ) merging_queue.push(Order_node(totalPb/totalBdry, c, label));
label = (*itrb).cc_neigh;
totalBdry = 1.0;
totalPb = local_boundaries[(*itrb).coord];
}
}
R[c].neighbors[label] = Neighbor_Region(totalPb/totalBdry, totalPb, totalBdry);
if( label > c ) merging_queue.push(Order_node(totalPb/totalBdry, c, label));
}
//MERGING
Order_node minor;
int father, son;
map<int,Neighbor_Region,less<int> >::iterator itr;
double current_energy = 0.0;
while ( !merging_queue.empty() )
{
minor = merging_queue.top(); merging_queue.pop();
if( (labels[minor.region1] == minor.region1) && (labels[minor.region2] == minor.region2) &&
(minor.energy == R[minor.region1].neighbors[minor.region2].energy) )
{
if (current_energy <= minor.energy) current_energy = minor.energy;
else
{
printf("\n ERROR : \n");
printf("\n current_energy = %f \n", current_energy);
printf("\n minor.energy = %f \n\n", minor.energy);
delete[] R; delete[] labels;
mexErrMsgTxt(" BUG: THIS IS NOT AN ULTRAMETRIC !!! ");
}
dissimilarity = R[minor.region1].neighbors[minor.region2].total_pb / R[minor.region1].neighbors[minor.region2].bdry_length ;
if (minor.region1 < minor.region2)
{ son = minor.region1; father = minor.region2; }
else
{ son = minor.region2; father = minor.region1; }
R[father].merge(R[son], labels, father, ucm, dissimilarity, son, tx);
// move and update neighbors
while ( R[son].neighbors.size() > 0 )
{
itr = R[son].neighbors.begin();
R[father].neighbors[(*itr).first].total_pb += (*itr).second.total_pb;
R[(*itr).first].neighbors[father].total_pb += (*itr).second.total_pb;
R[father].neighbors[(*itr).first].bdry_length += (*itr).second.bdry_length;
R[(*itr).first].neighbors[father].bdry_length += (*itr).second.bdry_length;
R[son].neighbors.erase(itr);
}
// update merging_queue
for (itr = R[father].neighbors.begin(); itr != R[father].neighbors.end(); ++itr )
{
dissimilarity = R[father].neighbors[(*itr).first].total_pb / R[father].neighbors[(*itr).first].bdry_length;
merging_queue.push(Order_node(dissimilarity, (*itr).first, father));
R[father].neighbors[(*itr).first].energy = dissimilarity;
R[(*itr).first].neighbors[father].energy = dissimilarity;
}
}
}
complete_contour_map(ucm, 2*tx+1, 2*ty+1 );
delete[] R; delete[] labels;
}
/*************************************************************************************************/
void mexFunction(int nlhs, mxArray *plhs[],int nrhs,const mxArray *prhs[])
{
if (nrhs != 2) mexErrMsgTxt("INPUT: (local_boundaries, initial_partition) ");
if (nlhs != 1) mexErrMsgTxt("OUTPUT: [ucm] ");
double* local_boundaries = mxGetPr(prhs[0]);
double* pi = mxGetPr(prhs[1]);
// size of original image
int fil = mxGetM(prhs[1]);
int col = mxGetN(prhs[1]);
int totcc = -1;
int* initial_partition = new int[fil*col];
for( int px = 0; px < fil*col; px++ )
{
initial_partition[px] = (int) pi[px];
if (totcc < initial_partition[px]) totcc = initial_partition[px];
}
if (totcc < 0) mexErrMsgTxt("\n ERROR : number of connected components < 0 : \n");
totcc++;
plhs[0] = mxCreateDoubleMatrix(2*fil+1, 2*col+1, mxREAL);
double* ucm = mxGetPr(plhs[0]);
compute_ucm(local_boundaries, initial_partition, totcc, ucm, fil, col);
delete[] initial_partition;
}
| 28.748111 | 210 | 0.537194 | corganhejijun |
6ddf3a01464ec973ad0b344f6a9759d7635a399a | 6,099 | inl | C++ | include/bit/math/detail/point/point2.inl | bitwizeshift/bit-math | e29d6dfe3cefecd08c3215bc4578b5903b269d86 | [
"MIT"
] | 3 | 2020-04-05T01:14:21.000Z | 2021-10-03T09:34:48.000Z | include/bit/math/detail/point/point2.inl | bitwizeshift/bit-math | e29d6dfe3cefecd08c3215bc4578b5903b269d86 | [
"MIT"
] | 1 | 2017-10-15T20:41:30.000Z | 2017-10-15T20:41:30.000Z | include/bit/math/detail/point/point2.inl | bitwizeshift/bit-math | e29d6dfe3cefecd08c3215bc4578b5903b269d86 | [
"MIT"
] | null | null | null | #ifndef BIT_MATH_DETAIL_GEOMETRY_POINT_POINT2_INL
#define BIT_MATH_DETAIL_GEOMETRY_POINT_POINT2_INL
//----------------------------------------------------------------------------
// Constructors
//----------------------------------------------------------------------------
inline constexpr bit::math::point2::point2()
noexcept
: m_data{0,0}
{
}
inline constexpr bit::math::point2::point2( value_type x, value_type y )
noexcept
: m_data{x,y}
{
}
//----------------------------------------------------------------------------
// Compound Operators
//----------------------------------------------------------------------------
template<typename T>
bit::math::point2& bit::math::point2::operator+=( const vector2<T>& rhs )
noexcept
{
for( auto i=0; i<2; ++i ) {
m_data[i] += rhs[i];
}
return (*this);
}
template<typename T>
bit::math::point2& bit::math::point2::operator-=( const vector2<T>& rhs )
noexcept
{
for( auto i=0; i<2; ++i ) {
m_data[i] -= rhs[i];
}
return (*this);
}
//----------------------------------------------------------------------------
// Observers
//----------------------------------------------------------------------------
inline constexpr bit::math::point2::reference bit::math::point2::x()
noexcept
{
return m_data[0];
}
inline constexpr bit::math::point2::const_reference bit::math::point2::x()
const noexcept
{
return m_data[0];
}
//----------------------------------------------------------------------------
inline constexpr bit::math::point2::reference bit::math::point2::y()
noexcept
{
return m_data[1];
}
inline constexpr bit::math::point2::const_reference bit::math::point2::y()
const noexcept
{
return m_data[1];
}
//----------------------------------------------------------------------------
inline constexpr bit::math::point2::pointer bit::math::point2::data()
noexcept
{
return m_data;
}
inline constexpr bit::math::point2::const_pointer bit::math::point2::data()
const noexcept
{
return m_data;
}
//----------------------------------------------------------------------------
// Modifiers
//----------------------------------------------------------------------------
inline void bit::math::point2::swap( point2& other )
noexcept
{
using std::swap;
swap(m_data[0],other.m_data[0]);
swap(m_data[1],other.m_data[1]);
}
//----------------------------------------------------------------------------
// Free Operators
//----------------------------------------------------------------------------
inline bit::math::vector2<float_t>
bit::math::operator - ( const point2& lhs, const point2& rhs )
noexcept
{
return { lhs.x() - rhs.x(), lhs.y() - rhs.y() };
}
template<typename T>
inline bit::math::point2
bit::math::operator + ( const point2& lhs, const vector2<T>& rhs )
noexcept
{
return point2(lhs)+=rhs;
}
template<typename T>
inline bit::math::point2
bit::math::operator - ( const point2& lhs, const vector2<T>& rhs )
noexcept
{
return point2(lhs)-=rhs;
}
//------------------------------------------------------------------------
// Free Functions
//------------------------------------------------------------------------
inline constexpr void bit::math::swap( point2& lhs, point2& rhs )
noexcept
{
lhs.swap(rhs);
}
inline constexpr bit::math::float_t bit::math::dot( const point2& lhs,
const point2& rhs )
noexcept
{
return lhs.x() * rhs.x() + lhs.y() * rhs.y();
}
inline constexpr bit::math::float_t bit::math::dot( const vec2& lhs,
const point2& rhs )
noexcept
{
return lhs.x() * rhs.x() + lhs.y() * rhs.y();
}
inline constexpr bit::math::float_t bit::math::dot( const point2& lhs,
const vec2& rhs )
noexcept
{
return lhs.x() * rhs.x() + lhs.y() * rhs.y();
}
//------------------------------------------------------------------------
// Comparisons
//------------------------------------------------------------------------
inline constexpr bool bit::math::operator==( const point2& lhs,
const point2& rhs )
noexcept
{
return std::tie(lhs.x(),lhs.y()) == std::tie(rhs.x(),rhs.y());
}
inline constexpr bool bit::math::operator!=( const point2& lhs,
const point2& rhs )
noexcept
{
return std::tie(lhs.x(),lhs.y()) != std::tie(rhs.x(),rhs.y());
}
inline constexpr bool bit::math::operator<=( const point2& lhs,
const point2& rhs )
noexcept
{
return std::tie(lhs.x(),lhs.y()) <= std::tie(rhs.x(),rhs.y());
}
inline constexpr bool bit::math::operator>=( const point2& lhs,
const point2& rhs )
noexcept
{
return std::tie(lhs.x(),lhs.y()) >= std::tie(rhs.x(),rhs.y());
}
inline constexpr bool bit::math::operator<( const point2& lhs,
const point2& rhs )
noexcept
{
return std::tie(lhs.x(),lhs.y()) < std::tie(rhs.x(),rhs.y());
}
inline constexpr bool bit::math::operator>( const point2& lhs,
const point2& rhs )
noexcept
{
return std::tie(lhs.x(),lhs.y()) > std::tie(rhs.x(),rhs.y());
}
//----------------------------------------------------------------------------
inline constexpr bool bit::math::almost_equal( const point2& lhs,
const point2& rhs )
noexcept
{
return almost_equal( lhs.x(), rhs.x() ) &&
almost_equal( lhs.y(), rhs.y() );
}
template<typename Arithmetic, std::enable_if_t<std::is_arithmetic<Arithmetic>::value>*>
inline constexpr bool bit::math::almost_equal( const point2& lhs,
const point2& rhs,
Arithmetic tolerance )
noexcept
{
return almost_equal( lhs.x(), rhs.x(), tolerance ) &&
almost_equal( lhs.y(), rhs.y(), tolerance );
}
#endif /* BIT_MATH_DETAIL_GEOMETRY_POINT_POINT2_INL */
| 26.517391 | 87 | 0.454173 | bitwizeshift |
6ddf5189196626421b8e6d6b3cddaae2fd0c7626 | 3,822 | cpp | C++ | src/_OOP/Shader.cpp | haxpor/lgl | d87628f2a4653c0ebc80bca24bbd244993c63d77 | [
"MIT"
] | 3 | 2020-10-29T06:22:30.000Z | 2021-05-01T14:27:31.000Z | src/_OOP/Shader.cpp | haxpor/lgl | d87628f2a4653c0ebc80bca24bbd244993c63d77 | [
"MIT"
] | null | null | null | src/_OOP/Shader.cpp | haxpor/lgl | d87628f2a4653c0ebc80bca24bbd244993c63d77 | [
"MIT"
] | null | null | null | /*
====================
Uniforms
====================
*/
#include "lgl/Base.h"
#include <cmath>
float vertices[] = {
0.5f, 0.5f, 0.0f, // top right
0.5f, -0.5f, 0.0f, // bottom right
-0.5f, -0.5f, 0.0f, // bottom left
-0.5f, 0.5f, 0.0f // top left
};
unsigned int indices[] = {
0, 1, 2, // first triangle (right)
0, 2, 3 // second triangle (left)
};
class Demo : public lgl::App
{
public:
void UserSetup() override {
// compile vertex shader
GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &VS_CODE, NULL);
glCompileShader(vertexShader);
lgl::error::PrintGLShaderErrorIfAny(vertexShader);
// compile fragment shader
GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &FS_CODE, NULL);
glCompileShader(fragmentShader);
lgl::error::PrintGLShaderErrorIfAny(fragmentShader);
// link all shaders together
shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
lgl::util::PrintGLShaderProgramErrorIfAny(shaderProgram);
// delete un-needed shader objects
// note: in fact, it will mark them for deletion after our usage of shader program is done
// they will be deleted after that
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// wrap vertex attrib configurations via VAO
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
// prepare vertex data
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); // or 3*sizeof(float) for its stride parameter
glEnableVertexAttribArray(0);
// prepare of EBO (Element Buffer Object) for indexed drawing
GLuint EBO;
glGenBuffers(1, &EBO);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
glBindVertexArray(0);
isFirstFrameWaitDone = false;
}
void UserUpdate(const double delta) override {
if (isFirstFrameWaitDone)
{
double currentTicks = glfwGetTime();
double greenValue = (std::sin(currentTicks) / 2.0f) + 0.5f;
// skip calling to glUseProgram(shaderProgram) as we wait for 1 frame
// shaderProgram by now is set to be active, so we save subsequent call from now on
glUniform4f(0, 0.0f, greenValue, 0.0f, 1.0f);
}
}
void UserRender() override {
glClear(GL_COLOR_BUFFER_BIT);
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glUseProgram(shaderProgram);
glBindVertexArray(VAO);
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
glBindVertexArray(0);
if (!isFirstFrameWaitDone)
{
isFirstFrameWaitDone = true;
}
}
private:
const char* VS_CODE = R"(#version 330 core
layout (location = 0) in vec3 aPos;
void main()
{
gl_Position = vec4(aPos, 1.0);
})";
const char* FS_CODE = R"(#version 330 core
#extension GL_ARB_explicit_uniform_location : require
out vec4 FragColor;
layout (location = 0) uniform vec4 ourColor;
void main()
{
FragColor = ourColor;
}
)";
bool isFirstFrameWaitDone;
GLuint VAO;
GLuint shaderProgram;
};
int main()
{
Demo app;
app.Setup("Shader");
app.Start();
return 0;
}
| 29.175573 | 114 | 0.615646 | haxpor |
6de17176a7b9b2b179496ef2503903bc576cc5d9 | 1,214 | cpp | C++ | src/col.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/col.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | src/col.cpp | kushaldalsania/haystack-cpp | 95997ae2bca9ea096dc7e61c000291f3ac08d9d7 | [
"AFL-3.0"
] | null | null | null | //
// Copyright (c) 2015, J2 Innovations
// Copyright (c) 2012 Brian Frank
// Licensed under the Academic Free License version 3.0
// History:
// 28 Aug 2014 Radu Racariu<radur@2inn.com> Ported to C++
// 06 Jun 2011 Brian Frank Creation
//
#include "col.hpp"
#include "str.hpp"
#include "dict.hpp"
////////////////////////////////////////////////
// Col
////////////////////////////////////////////////
using namespace haystack;
// public:
//////////////////////////////////////////////////////////////////////////
// Access
//////////////////////////////////////////////////////////////////////////
// Return programatic name of column
const std::string Col::name() const { return m_name; }
// Return display name of column which is meta.dis or name
const std::string Col::dis() const
{
const Val& dis = m_meta->get("dis");
if (dis.type() == Val::STR_TYPE)
return ((Str&)dis).value;
return m_name;
}
// Column meta-data tags
const Dict& Col::meta() const { return *m_meta; }
// Equality is name and meta
bool Col::operator== (const Col& that)
{
return m_name == that.m_name && *m_meta == *that.m_meta;
}
bool Col::operator!= (const Col& that)
{
return !(*this == that);
} | 25.829787 | 74 | 0.522241 | kushaldalsania |
6de17c3b0548814a4cfa34ad7a64798f4126af32 | 2,511 | hpp | C++ | src/tablestore/core/plainbuffer/consts.hpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | 2 | 2020-02-24T06:51:55.000Z | 2020-04-24T14:40:10.000Z | src/tablestore/core/plainbuffer/consts.hpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | null | null | null | src/tablestore/core/plainbuffer/consts.hpp | TimeExceed/aliyun-tablestore-cpp-sdk | f8d2fdf500badf70073dff4e21a5d2d7aa7d3853 | [
"BSD-3-Clause"
] | 1 | 2020-02-24T06:51:57.000Z | 2020-02-24T06:51:57.000Z | #pragma once
/*
BSD 3-Clause License
Copyright (c) 2017, Alibaba Cloud
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the 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.
*/
#ifndef TABLESTORE_CORE_PLAINBUFFER_PLAIN_BUFFER_CONSTS_HPP
#define TABLESTORE_CORE_PLAINBUFFER_PLAIN_BUFFER_CONSTS_HPP
#include <stdint.h>
namespace aliyun {
namespace tablestore {
namespace core {
namespace plainbuffer {
const uint32_t kHeader = 0x75;
enum Tag {
kTag_None = 0,
kTag_RowKey = 0x1,
kTag_RowData = 0x2,
kTag_Cell = 0x3,
kTag_CellName = 0x4,
kTag_CellValue = 0x5,
kTag_CellType = 0x6,
kTag_CellTimestamp = 0x7,
kTag_RowDeleteMarker = 0x8,
kTag_RowChecksum = 0x9,
kTag_CellChecksum = 0x0A,
};
enum CellDeleteMarker {
kCDM_DeleteAllVersions = 0x1,
kCDM_DeleteOneVersion = 0x3,
};
enum VariantType {
kVT_Integer = 0x0,
kVT_Double = 0x1,
kVT_Boolean = 0x2,
kVT_String = 0x3,
kVT_Null = 0x6,
kVT_Blob = 0x7,
kVT_InfMin = 0x9,
kVT_InfMax = 0xa,
kVT_AutoIncrement = 0xb,
};
} // namespace plainbuffer
} // namespace core
} // namespace tablestore
} // namespace aliyun
#endif
| 31 | 78 | 0.766627 | TimeExceed |
6de21abe33dd6600cebe17f5747a1ceb68bd0e4b | 9,581 | cpp | C++ | src/main.cpp | cultur98/ESP32_Vorrat | 0dba638677c32ccb46069403a71cefa2460974ad | [
"MIT"
] | null | null | null | src/main.cpp | cultur98/ESP32_Vorrat | 0dba638677c32ccb46069403a71cefa2460974ad | [
"MIT"
] | null | null | null | src/main.cpp | cultur98/ESP32_Vorrat | 0dba638677c32ccb46069403a71cefa2460974ad | [
"MIT"
] | null | null | null | #include <Arduino.h>
#include <ArduinoJson.h>
#include <Wire.h>
#include <Ticker.h>
#include <Button2.h>
#include "Config.h"
#include "vorratConfig.h"
#include "myTimer.h"
#include "wifiman.h"
#include "Logger.h"
#include "hch_stuff.h"
#include "ePaperBWR.h"
#include "lilygo.h"
#include "ota.h"
#include "deep_sleep_helper.h"
#include "batty.h"
// enable debug messages on the console
#define ARDUINOTRACE_ENABLE 1
#include "ArduinoTrace.h"
Logger myLogger;
ePaperBWR myEpaper;
Ticker watch_tick;
MyTimer myTimer;
TaskHandle_t TickTask;
int language = _GER_;
Button2 button1 = Button2(BUTTON_LAST);
Button2 button2 = Button2(BUTTON_NEXT);
Batty myBatt;
int the_page = 0;
uint32_t timer_ctr = 0;
uint32_t main_loop_ctr = 0;
int today = 0;
char time_string[MIN_STRING_LEN];
bool has_valid_config = false;
bool new_firmware = false;
bool timer_wakeup = false;
bool wasConnected = true;
bool isConnected = false;
RTC_DATA_ATTR int bootCount = 0;
touch_pad_t touchPin;
#define UP_TIMEOUT_SEC 30
#define TROUBLE_TIMEOUT_MIN 20
void watch_task() {
TRACE1();
timer_ctr++;
char uptime[80];
int up_seconds = (TICK_TASK_DELAY/1000)* timer_ctr;
hch_uptime(up_seconds, uptime);
isConnected = WiFi.isConnected();
Serial.printf("\nisConn %d | wasConn %d | valid_conf %d | timer_wake %d\n",
isConnected, wasConnected, has_valid_config, timer_wakeup);
if(up_seconds > UP_TIMEOUT_SEC)
{
if(wasConnected == true && isConnected == false && has_valid_config == true && timer_wakeup == true)
{
Serial.printf("TROUBLE detected - trying again in %d minutes\n", TROUBLE_TIMEOUT_MIN);
uint64_t wakeup_us = TROUBLE_TIMEOUT_MIN * (60 * 1000000);
esp_sleep_enable_timer_wakeup(wakeup_us);
set_deep_sleep();
}
if(wasConnected == true && isConnected == false)
{
Serial.println(F("watch_task() print AP mode"));
myEpaper.ap_mode("No access to WLAN");
set_timeout(LONG_TIMEOUT);
}
Serial.printf("WIFI was %d | is %d\n", wasConnected, isConnected);
wasConnected = isConnected;
}
uint32_t heap = esp_32_get_free_heap();
uint32_t psram = ESP.getPsramSize();
Serial.printf("NTP date %s\n", time_string);
Serial.printf("nuptime %s | min_uptime %d | %u boots\n", uptime, UP_TIMEOUT_SEC, hch_get_boot_ctr());
Serial.printf("main_loop: %u | timer %u | heap %u | psram %u\n", main_loop_ctr, timer_ctr, heap, psram);
Serial.printf("sleep in %ds\n", get_timeout_delta());
check_sleep();
}
void show_prev_screen()
{
set_timeout(MEDIUM_TIMEOUT);
Serial.println(F("UP clicked"));
if(the_page > 0)
the_page = the_page - 1;
myEpaper.print_lager_list(time_string, today, the_page, false);
set_timeout(MEDIUM_TIMEOUT);
}
void show_next_screen()
{
set_timeout(MEDIUM_TIMEOUT);
Serial.println(F("DOWN clicked"));
the_page = the_page + 1;
myEpaper.print_lager_list(time_string, today, the_page, false);
set_timeout(MEDIUM_TIMEOUT);
}
void click(Button2& btn) {
TRACE1();
if (btn == button1) {
show_prev_screen();
}
if ((btn == button2) || (btn == button2) ){
show_next_screen();
}
}
#define WAKE_UP_MINS_DELTA_MIN 30
void processWakeup()
{
int hours, mins;
char time_string[MIN_STRING_LEN];
int min_wakeup_mins = -1;
if(today <= 0)
{
Serial.printf("Time ist not defined. Cannot set wakeup!\n");
return;
}
for(int i = 0; i < WAKE_UP_TIMES; i++)
{
strcpy(time_string, vorrat_config.wakeup_time[i].c_str());
DUMP1(time_string);
int ret = sscanf(time_string, "%d:%d", &hours, &mins);
DUMP1(ret);
if(ret == 2)
{
DUMP2(hours);
DUMP2(mins);
if((hours >= 0) && (hours <= 23) && (mins >= 0) && (mins <= 59))
{
int wakeup_mins = mins + hours * 60;
DUMP2(wakeup_mins);
if (myTimer.getTimeStringShort(time_string, MIN_STRING_LEN) == true)
{
sscanf(time_string, "%d:%d", &hours, &mins);
DUMP2(hours);
DUMP2(mins);
if((hours >= 0) && (hours <= 23) && (mins >= 0) && (mins <= 59))
{
int the_mins = mins + hours * 60;
DUMP2(the_mins);
int wakeup_mins_delta = wakeup_mins - the_mins;
if(wakeup_mins_delta < 0)
{
wakeup_mins_delta = wakeup_mins_delta + 1440;
}
if(wakeup_mins_delta < WAKE_UP_MINS_DELTA_MIN)
{
wakeup_mins_delta = wakeup_mins_delta + 1440;
}
if((wakeup_mins_delta < min_wakeup_mins) || (min_wakeup_mins == -1))
{
min_wakeup_mins = wakeup_mins_delta;
DUMP1(min_wakeup_mins);
}
DUMP2(wakeup_mins_delta);
}
}
}
}
}
if(min_wakeup_mins > 0)
{
uint64_t wakeup_us = min_wakeup_mins;
wakeup_us = wakeup_us * 60 * 1000000;
esp_sleep_enable_timer_wakeup(wakeup_us);
Serial.printf("ESP will wake up in [%02d:%02d]\n", min_wakeup_mins / 60, min_wakeup_mins % 60);
}
}
bool setup_timer()
{
TRACE1();
int update_ctr = 0;
myTimer.init(vorrat_config.time_zone_offset);
while((myTimer.update() == false) && (update_ctr++ < 5))
{
Serial.print(F("Failed to get time via NTP.\n"));
Serial.printf("Trying again in %dms.\n", NTP_UPDATE_TIME);
delay(NTP_UPDATE_TIME);
}
myTimer.getTimeString(time_string, MIN_STRING_LEN);
today = myTimer.tick() / (60*60*24);
return(true);
}
bool process_list(bool new_fw)
{
TRACE1();
setup_timer();
myLogger.init();
if(vorrat_config.key.length() > 0)
{
if(myLogger.get_lager_list_server(vorrat_config.key.c_str(), vorrat_config.loc.c_str()) == true)
{
myEpaper.print_lager_list(time_string, today, the_page, new_fw);
set_timeout(SHORT_TIMEOUT);
processWakeup();
return(true);
}
}
else if((vorrat_config.googleID.length() > 0) && (vorrat_config.googleAPIkey.length() > 0))
{
if(myLogger.get_google_list(vorrat_config.googleID.c_str(), vorrat_config.googleAPIkey.c_str()) == true)
{
myEpaper.print_lager_list(time_string, today, the_page, new_fw);
set_timeout(SHORT_TIMEOUT);
processWakeup();
return(true);
}
}
processWakeup();
return(false);
}
bool setup_button_click()
{
TRACE1();
button1.setClickHandler(click);
button2.setClickHandler(click);
button1.setLongClickHandler(click);
button2.setLongClickHandler(click);
return(true);
}
void setup() {
TRACE1();
bool show_config = false;
bool ota_update = false;
bool force_ap_mode = false;
pinMode(BUTTON_WAKE, INPUT_PULLUP);
pinMode(BUTTON_LAST, INPUT_PULLUP);
pinMode(BUTTON_NEXT, INPUT_PULLUP);
ota_update = hch_init((char*)CLIENT_ID, 115200);
delay(100);
language = hch_get_lang();
bootCount++;
Serial.println("Boot number: " + String(bootCount));
// init wakeup and deep sleep behavior
timer_wakeup = init_wakeup();
set_timeout(LONG_TIMEOUT);
Serial.printf("CLIENT_ID %s\n", CLIENT_ID);
watch_tick.attach((float)(TICK_TASK_DELAY / 1000), watch_task);
Serial.printf("Button state [%d|%d|%d]\n",
digitalRead(BUTTON_WAKE), digitalRead(BUTTON_LAST),
digitalRead(BUTTON_NEXT));
if(digitalRead(BUTTON_NEXT) == LOW)
{
ota_update = true;
Serial.println(F("FIRMWARE UPDATE requested!"));
}
if( digitalRead(BUTTON_LAST) == LOW )
{
Serial.println(F("SHOW CONFIG requested!"));
show_config = true;
}
if( (digitalRead(BUTTON_LAST) == LOW) && (digitalRead(BUTTON_NEXT) == LOW) )
{
Serial.println(F("AP MODE requested!"));
force_ap_mode = true;
show_config = false;
ota_update = false;
}
has_valid_config = WiFiManager_loadConfigData();
myEpaper.init();
myBatt.init();
myBatt.test();
myBatt.read();
if(has_valid_config == false)
{
Serial.printf("Config status [%d]\n", has_valid_config);
}
new_firmware = hch_check_for_new_fw(FW_VERSION_MAJ, FW_VERSION_MIN);
DUMP1(new_firmware);
DUMP1(FW_VERSION_MAJ);
DUMP1(FW_VERSION_MIN);
if(new_firmware == true)
{
myEpaper.firmware_change(FW_VERSION_MAJ, FW_VERSION_MIN);
}
/*
if(force_ap_mode == true)
{
myEpaper.ap_mode("Button Pressed");
}
*/
wasConnected = true;
WiFiManager_init(CLIENT_ID, force_ap_mode);
bool new_online_fw = checkVersion();
if(ota_update == true)
{
hch_clear_ota_request();
if(new_online_fw == true)
{
myEpaper.show_ota_update(theVersion.new_major, theVersion.new_minor);
checkForUpdates();
Serial.println(F("New Update available\n"));
return;
}
else
{
myEpaper.show_firmware();
Serial.println(F("Firmware up to date .... continue!\n"));
}
}
setup_button_click();
TRACE1();
if(show_config == true)
{
myEpaper.show_config();
Serial.println(F("setup() long timeout"));
}
else
{
if(has_valid_config == true)
{
bool process_status = process_list(new_online_fw);
if(process_status == false)
{
char mess[MIN_STRING_LEN];
Serial.println(F("NO TABLE FOUND!"));
sprintf(mess, "[%d|%d|%d][%d|%d|%d][%d|%d|%d][%d]",
has_valid_config, new_firmware, timer_wakeup,
wasConnected, isConnected, show_config,
ota_update, force_ap_mode, new_online_fw,
process_status);
myEpaper.no_conn(mess);
}
}
else
{
Serial.println(F("NO CONFIGURATION FOUND!"));
myEpaper.config_mode();
}
}
}
void loop() {
TRACE2();
main_loop_ctr++;
WiFiManager_loop();
button1.loop();
button2.loop();
check_sleep();
}
| 26.249315 | 108 | 0.650663 | cultur98 |
6deae22ab238d88fa54b9680aacc077195ff80a5 | 633 | cpp | C++ | others/HANGOVER.cpp | stepan-krivanek/spoj | 3a91d7e666fd6af5cb2a7978dc20318077e62850 | [
"MIT"
] | null | null | null | others/HANGOVER.cpp | stepan-krivanek/spoj | 3a91d7e666fd6af5cb2a7978dc20318077e62850 | [
"MIT"
] | null | null | null | others/HANGOVER.cpp | stepan-krivanek/spoj | 3a91d7e666fd6af5cb2a7978dc20318077e62850 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
double input;
cin >> input;
double table[275];
table[0] = 0.5;
int index = 0;
while (input != 0){
int i = 0;
while (1){ //while condition not working?
if (input < table[i]){ //i++ not working?
break;
}
i++;
if (i > index){
index++;
table[index] = table[index-1] + (double)1/(index + 2);
}
}
int result = i + 1;
cout << result << " card(s)" << endl;
cin >> input;
}
return 0;
} | 21.1 | 70 | 0.406003 | stepan-krivanek |
6df0490a8e778e10fcbe5546581fa0021e1d97bc | 1,448 | cc | C++ | caffe2/operators/given_tensor_fill_op.cc | gautamkmr/caffe2 | cde7f21d1e34ec714bc08dbfab945a1ad30e92ff | [
"MIT"
] | null | null | null | caffe2/operators/given_tensor_fill_op.cc | gautamkmr/caffe2 | cde7f21d1e34ec714bc08dbfab945a1ad30e92ff | [
"MIT"
] | null | null | null | caffe2/operators/given_tensor_fill_op.cc | gautamkmr/caffe2 | cde7f21d1e34ec714bc08dbfab945a1ad30e92ff | [
"MIT"
] | 1 | 2019-11-11T03:30:00.000Z | 2019-11-11T03:30:00.000Z | #include "caffe2/operators/given_tensor_fill_op.h"
namespace caffe2 {
REGISTER_CPU_OPERATOR(GivenTensorFill, GivenTensorFillOp<float, CPUContext>);
REGISTER_CPU_OPERATOR(GivenTensorBoolFill, GivenTensorFillOp<bool, CPUContext>);
REGISTER_CPU_OPERATOR(GivenTensorIntFill, GivenTensorFillOp<int, CPUContext>);
REGISTER_CPU_OPERATOR(
GivenTensorInt64Fill,
GivenTensorFillOp<int64_t, CPUContext>);
REGISTER_CPU_OPERATOR(
GivenTensorStringFill,
GivenTensorFillOp<std::string, CPUContext>);
NO_GRADIENT(GivenTensorFill);
NO_GRADIENT(GivenTensorBoolFill);
NO_GRADIENT(GivenTensorIntFill);
NO_GRADIENT(GivenTensorInt64Fill);
OPERATOR_SCHEMA(GivenTensorFill)
.NumInputs(0, 1)
.NumOutputs(1)
.AllowInplace({{0, 0}})
.TensorInferenceFunction(FillerTensorInference);
OPERATOR_SCHEMA(GivenTensorBoolFill)
.NumInputs(0, 1)
.NumOutputs(1)
.AllowInplace({{0, 0}})
.TensorInferenceFunction(FillerTensorInference);
OPERATOR_SCHEMA(GivenTensorIntFill)
.NumInputs(0, 1)
.NumOutputs(1)
.AllowInplace({{0, 0}})
.TensorInferenceFunction(FillerTensorInference);
OPERATOR_SCHEMA(GivenTensorInt64Fill)
.NumInputs(0, 1)
.NumOutputs(1)
.AllowInplace({{0, 0}})
.TensorInferenceFunction(FillerTensorInference);
OPERATOR_SCHEMA(GivenTensorStringFill)
.NumInputs(0, 1)
.NumOutputs(1)
.AllowInplace({{0, 0}})
.TensorInferenceFunction(FillerTensorInference);
} // namespace caffe2
| 30.808511 | 80 | 0.772099 | gautamkmr |
6df1223aac31e1ad651fd2ceea8ed9c7c6707acd | 7,058 | cpp | C++ | test/src/distance_test.cpp | ericwa/vecmath | b1db3cedac39d380b4d65efc894c933c9f413030 | [
"MIT"
] | 1 | 2021-07-13T02:56:28.000Z | 2021-07-13T02:56:28.000Z | test/src/distance_test.cpp | ericwa/vecmath | b1db3cedac39d380b4d65efc894c933c9f413030 | [
"MIT"
] | null | null | null | test/src/distance_test.cpp | ericwa/vecmath | b1db3cedac39d380b4d65efc894c933c9f413030 | [
"MIT"
] | null | null | null | /*
Copyright 2010-2019 Kristian Duske
Copyright 2015-2019 Eric Wasylishen
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 <gtest/gtest.h>
#include "test_utils.h"
#include <vecmath/forward.h>
#include <vecmath/vec.h>
#include <vecmath/distance.h>
namespace vm {
TEST(distance_test, distance_ray_point) {
constexpr auto ray = ray3f(vec3f::zero(), vec3f::pos_z());
// point is behind ray
CER_ASSERT_FLOAT_EQ(0.0f, squared_distance(ray, vec3f(-1.0f, -1.0f, -1.0f)).position)
CER_ASSERT_FLOAT_EQ(3.0f, squared_distance(ray, vec3f(-1.0f, -1.0f, -1.0f)).distance)
// point is in front of ray
CER_ASSERT_FLOAT_EQ(1.0f, squared_distance(ray, vec3f(1.0f, 1.0f, 1.0f)).position)
CER_ASSERT_FLOAT_EQ(2.0f, squared_distance(ray, vec3f(1.0f, 1.0f, 1.0f)).distance)
// point is on ray
CER_ASSERT_FLOAT_EQ(1.0f, squared_distance(ray, vec3f(0.0f, 0.0f, 1.0f)).position)
CER_ASSERT_FLOAT_EQ(0.0f, squared_distance(ray, vec3f(0.0f, 0.0f, 1.0f)).distance)
}
TEST(distance_test, distance_segment_point) {
constexpr auto segment = segment3f(vec3f::zero(), vec3f::pos_z());
// point is below start
ASSERT_FLOAT_EQ(0.0f, squared_distance(segment, vec3f(-1.0f, -1.0f, -1.0f)).position);
ASSERT_FLOAT_EQ(3.0f, squared_distance(segment, vec3f(-1.0f, -1.0f, -1.0f)).distance);
// point is within segment
ASSERT_FLOAT_EQ(1.0f, squared_distance(segment, vec3f(1.0f, 1.0f, 1.0f)).position);
ASSERT_FLOAT_EQ(2.0f, squared_distance(segment, vec3f(1.0f, 1.0f, 1.0f)).distance);
// point is above end
ASSERT_FLOAT_EQ(1.0f, squared_distance(segment, vec3f(0.0f, 0.0f, 2.0f)).position);
ASSERT_FLOAT_EQ(1.0f, squared_distance(segment, vec3f(0.0f, 0.0f, 2.0f)).distance);
}
TEST(distance_test, distance_ray_segment) {
constexpr auto ray = ray3f(vec3f::zero(), vec3f::pos_z());
line_distance<float> segDist;
segDist = squared_distance(ray, segment3f(vec3f(0.0f, 0.0f, 0.0f), vec3f(0.0f, 0.0f, 1.0f)));
ASSERT_TRUE(segDist.parallel);
ASSERT_FLOAT_EQ(0.0f, segDist.distance);
segDist = squared_distance(ray, segment3f(vec3f(1.0f, 1.0f, 0.0f), vec3f(1.0f, 1.0f, 1.0f)));
ASSERT_TRUE(segDist.parallel);
ASSERT_FLOAT_EQ(2.0f, segDist.distance);
segDist = squared_distance(ray, segment3f(vec3f(1.0f, 0.0f, 0.0f), vec3f(0.0f, 1.0f, 0.0f)));
ASSERT_FALSE(segDist.parallel);
ASSERT_FLOAT_EQ(0.0f, segDist.position1);
ASSERT_FLOAT_EQ(0.5f, segDist.distance);
ASSERT_FLOAT_EQ(0.70710677f, segDist.position2);
segDist = squared_distance(ray, segment3f(vec3f(1.0f, 0.0f, 0.0f), vec3f(2.0f, -1.0f, 0.0f)));
ASSERT_FALSE(segDist.parallel);
ASSERT_FLOAT_EQ(0.0f, segDist.position1);
ASSERT_FLOAT_EQ(1.0f, segDist.distance);
ASSERT_FLOAT_EQ(0.0f, segDist.position2);
segDist = distance(ray, segment3f(vec3f(-1.0f, 1.5f, 2.0f), vec3f(+1.0f, 1.5f, 2.0f)));
ASSERT_FALSE(segDist.parallel);
ASSERT_FLOAT_EQ(2.0f, segDist.position1);
ASSERT_FLOAT_EQ(1.5f, segDist.distance);
ASSERT_FLOAT_EQ(1.0f, segDist.position2);
}
TEST(distance_test, distance_ray_ray) {
constexpr auto ray1 = ray3f(vec3f::zero(), vec3f::pos_z());
constexpr auto segDist1 = squared_distance(ray1, ray1);
CER_ASSERT_TRUE(segDist1.parallel)
CER_ASSERT_NEAR(0.0f, segDist1.distance, 0.001f)
constexpr auto segDist2 = squared_distance(ray1, ray3f(vec3f(1.0f, 1.0, 0.0f), vec3f::pos_z()));
CER_ASSERT_TRUE(segDist2.parallel)
CER_ASSERT_NEAR(2.0f, segDist2.distance, 0.001f)
constexpr auto segDist3 = squared_distance(ray1, ray3f(vec3f(1.0f, 1.0f, 0.0f), normalize_c(vec3f(1.0f, 1.0f, 1.0f))));
CER_ASSERT_FALSE(segDist3.parallel)
CER_ASSERT_NEAR(0.0f, segDist3.position1, 0.001f)
CER_ASSERT_NEAR(2.0f, segDist3.distance, 0.001f)
CER_ASSERT_NEAR(0.0f, segDist3.position2, 0.001f)
constexpr auto segDist4 = squared_distance(ray1, ray3f(vec3f(1.0f, 1.0f, 0.0f), normalize_c(vec3f(-1.0f, -1.0f, +1.0f))));
CER_ASSERT_FALSE(segDist4.parallel)
CER_ASSERT_NEAR(1.0f, segDist4.position1, 0.001f)
CER_ASSERT_NEAR(0.0f, segDist4.distance, 0.001f)
CER_ASSERT_NEAR(length(vec3f(1.0f, 1.0f, 1.0f)), segDist4.position2, 0.001f)
constexpr auto segDist5 = squared_distance(ray1, ray3f(vec3f(1.0f, 1.0f, 0.0f), normalize_c(vec3f(-1.0f, 0.0f, +1.0f))));
CER_ASSERT_FALSE(segDist5.parallel)
CER_ASSERT_NEAR(1.0f, segDist5.position1, 0.001f)
CER_ASSERT_NEAR(1.0f, segDist5.distance, 0.001f)
CER_ASSERT_NEAR(length(vec3f(1.0f, 0.0f, 1.0f)), segDist5.position2, 0.001f)
}
TEST(distance_test, distance_ray_line) {
constexpr auto ray = ray3f(vec3f::zero(), vec3f::pos_z());
constexpr auto segDist1 = squared_distance(ray, line3f(vec3f(0.0f, 0.0f, 0.0f), vec3f::pos_z()));
CER_ASSERT_TRUE(segDist1.parallel)
CER_ASSERT_FLOAT_EQ(0.0f, segDist1.distance)
constexpr auto segDist2 = squared_distance(ray, line3f(vec3f(1.0f, 1.0f, 0.0f), vec3f::pos_z()));
CER_ASSERT_TRUE(segDist2.parallel)
CER_ASSERT_FLOAT_EQ(2.0f, segDist2.distance)
constexpr auto segDist3 = squared_distance(ray, line3f(vec3f(1.0f, 0.0f, 0.0f), normalize_c(vec3f(-1.0f, 1.0f, 0.0f))));
CER_ASSERT_FALSE(segDist3.parallel)
CER_ASSERT_FLOAT_EQ(0.0f, segDist3.position1)
CER_ASSERT_FLOAT_EQ(0.5f, segDist3.distance)
CER_ASSERT_FLOAT_EQ(sqrt_c(2.0f) / 2.0f, segDist3.position2)
constexpr auto segDist4 = squared_distance(ray, line3f(vec3f(1.0f, 0.0f, 0.0f), normalize_c(vec3f(1.0f, -1.0f, 0.0f))));
CER_ASSERT_FALSE(segDist4.parallel)
CER_ASSERT_FLOAT_EQ(0.0f, segDist4.position1)
CER_ASSERT_FLOAT_EQ(0.5f, segDist4.distance)
CER_ASSERT_FLOAT_EQ(-sqrt_c(2.0f) / 2.0f, segDist4.position2)
}
}
| 48.675862 | 130 | 0.685463 | ericwa |
6df41b02c4b178a772645eac31c372d79c57d7a1 | 1,421 | cpp | C++ | Google Code Jam/2018/Round 1C/A Whole New Word.cpp | pratyaydeep/Competitive-Programming | c6ee9a492915e39b7b4c54d167a3c027a64b48b1 | [
"MIT"
] | null | null | null | Google Code Jam/2018/Round 1C/A Whole New Word.cpp | pratyaydeep/Competitive-Programming | c6ee9a492915e39b7b4c54d167a3c027a64b48b1 | [
"MIT"
] | null | null | null | Google Code Jam/2018/Round 1C/A Whole New Word.cpp | pratyaydeep/Competitive-Programming | c6ee9a492915e39b7b4c54d167a3c027a64b48b1 | [
"MIT"
] | 1 | 2021-07-19T08:39:38.000Z | 2021-07-19T08:39:38.000Z | // Problem 1: A Whole New Word
// Idea: Brute Force (just generating all strings of given characters, return the first generated string that is not found in the dictionary)
#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 5;
const int MAX_L = 20; // ~ Log N
const long long MOD = 1e9 + 7;
const long long INF = 1e18;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int,int> ii;
typedef vector<ii> vii;
typedef vector<vi> vvi;
#define LSOne(S) (S & (-S))
#define isBitSet(S, i) ((S >> i) & 1)
int N, L;
set<string> dict;
vector<set<char>> arr;
string build(string cur, int pos) {
if (pos == L) {
return (dict.find(cur) == dict.end()) ? cur : "-";
}
for (char c : arr[pos]) {
string res = build(cur + c, pos + 1);
if (res != "-") return res;
}
return "-";
}
void solve() {
cin >> N >> L;
dict.clear();
arr.clear(); arr.resize(L);
for (int i = 0; i < N; i++) {
string str; cin >> str;
dict.insert(str);
for (int j = 0; j < L; j++) {
arr[j].insert(str[j]);
}
}
cout << build("", 0) << "\n";
}
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int tc; cin >> tc;
for (int t = 1; t <= tc; t++) {
cout << "Case #" << t << ": ";
solve();
}
}
| 22.555556 | 141 | 0.532723 | pratyaydeep |
6df8b3d9ad306a18bc5943553fe6eed3a1c29df2 | 5,021 | cpp | C++ | test/parse_tree.cpp | cmargiotta/ratl | 84d76f23bbc52d3e581cfbb5e5a3dd04993e74c2 | [
"MIT"
] | null | null | null | test/parse_tree.cpp | cmargiotta/ratl | 84d76f23bbc52d3e581cfbb5e5a3dd04993e74c2 | [
"MIT"
] | null | null | null | test/parse_tree.cpp | cmargiotta/ratl | 84d76f23bbc52d3e581cfbb5e5a3dd04993e74c2 | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_ENABLE_BENCHMARKING
#include <catch2/catch.hpp>
#include <fstream>
#include <iostream>
#include <math/fraction.hpp>
#include <parser/dice.hpp>
#include <parser/math.hpp>
#include <parser/math_function.hpp>
#include <parser/regex.hpp>
SCENARIO("Regex parse tree")
{
GIVEN("A regex parser and an expression tree")
{
ratl::regex_parser parser_;
std::string parse_expr("1*2+a?[\\dA]*");
auto tree = parser_(parse_expr);
std::string parse_expr1("[1-2]+");
auto tree1 = parser_(parse_expr1);
REQUIRE(tree->to_string() == parse_expr);
REQUIRE(tree1->to_string() == parse_expr1);
WHEN("It is asked to compute")
{
THEN("It correctly interprets its language")
{
std::string expression("1222");
REQUIRE(tree->compute(expression));
expression = "22222";
REQUIRE(tree->compute(expression));
expression = "1111122222";
REQUIRE(tree->compute(expression));
expression = "122222a";
REQUIRE(tree->compute(expression));
expression = "122222a9999";
REQUIRE(tree->compute(expression));
expression = "122222aAAAA";
REQUIRE(tree->compute(expression));
expression = "122222a9AA999";
REQUIRE(tree->compute(expression));
expression = "22222aa";
REQUIRE(tree->compute(expression));
expression = "111aa";
REQUIRE(!tree->compute(expression));
expression = "111";
REQUIRE(!tree->compute(expression));
expression = "";
REQUIRE(!tree->compute(expression));
expression = "12344";
REQUIRE(tree1->compute(expression));
}
}
AND_WHEN("Two trees are merged")
{
ratl::regex_parser parser_;
std::string parse_expr("1*2+a?[\\dA]*");
auto tree = parser_(parse_expr);
std::string parse_expr1 = "[1-2]+";
auto tree1 = parser_(parse_expr1);
tree->merge(std::move(tree1));
THEN("They are correctly merged")
{
REQUIRE(tree->to_string() == ("(" + parse_expr + ")|(" + parse_expr1 + ")"));
std::string expression = "12344";
REQUIRE(tree->compute(expression));
expression = "22222aa";
REQUIRE(tree->compute(expression));
}
}
}
}
SCENARIO("Math parse tree")
{
GIVEN("A regex parser and an expression tree")
{
ratl::math_parser parser_;
WHEN("It is asked to compute")
{
THEN("It correctly interprets its expression")
{
std::string parse_expr("12+5*2");
auto tree = parser_(parse_expr);
REQUIRE(tree->to_string() == parse_expr);
REQUIRE(tree->compute() == 34);
parse_expr = "(12+5)*2";
tree = parser_(parse_expr);
REQUIRE(tree->to_string() == parse_expr);
REQUIRE(tree->compute() == 34);
parse_expr = "12+5^2";
tree = parser_(parse_expr);
REQUIRE(tree->to_string() == parse_expr);
REQUIRE(tree->compute() == 289);
}
}
}
}
SCENARIO("Math function parse tree")
{
GIVEN("A regex parser and an expression tree")
{
ratl::math_function_parser parser_;
WHEN("It is asked to compute")
{
THEN("It correctly interprets it")
{
std::string parse_expr("12/2+2+5xy");
auto tree = parser_(parse_expr);
std::unordered_map<std::string, ratl::math::fraction<int>> unknowns;
unknowns["x"] = ratl::math::fraction<int>(1, 2);
unknowns["y"] = ratl::math::fraction<int>(2, 1);
REQUIRE(tree->to_string() == "13xy");
auto result = tree->compute(unknowns);
REQUIRE(result.numerator == 13);
REQUIRE(result.denominator == 1);
}
}
}
}
SCENARIO("Dice parse tree")
{
GIVEN("A regex parser and an expression tree")
{
ratl::dice_parser parser_;
std::string parse_expr("10d6");
auto tree = parser_(parse_expr);
REQUIRE(tree->to_string() == parse_expr);
WHEN("It is asked to compute")
{
THEN("It correctly interprets its expression")
{
for (int i = 0; i < 100; ++i)
{
auto result = tree->compute();
REQUIRE(result <= 60);
REQUIRE(result >= 1);
}
}
}
}
} | 28.856322 | 93 | 0.49293 | cmargiotta |
6df8e55ef6356d1bd6e87c4f7b67cd5cec20118e | 1,788 | cpp | C++ | test/snippet/alignment/matrix/debug_matrix_trace.cpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | test/snippet/alignment/matrix/debug_matrix_trace.cpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | test/snippet/alignment/matrix/debug_matrix_trace.cpp | marehr/nomchop | a88bfb6f5d4a291a71b6b3192eeac81fdc450d43 | [
"CC-BY-4.0",
"CC0-1.0"
] | null | null | null | #include <iostream>
#include <seqan3/alphabet/nucleotide/dna4.hpp>
#include <seqan3/alignment/matrix/debug_matrix.hpp>
#include <seqan3/core/debug_stream.hpp>
#include <seqan3/range/views/to_char.hpp>
int main()
{
// using namespace seqan3;
using seqan3::detail::debug_matrix;
using seqan3::operator""_dna4;
using seqan3::operator|;
std::vector<seqan3::dna4> database = "AACCGGTT"_dna4;
std::vector<seqan3::dna4> query = "ACGT"_dna4;
auto N = seqan3::detail::trace_directions::none;
auto D = seqan3::detail::trace_directions::diagonal;
auto U = seqan3::detail::trace_directions::up;
auto L = seqan3::detail::trace_directions::left;
seqan3::detail::row_wise_matrix<seqan3::detail::trace_directions> trace_matrix
{
seqan3::detail::number_rows{5u},
seqan3::detail::number_cols{9u},
std::vector
{
N,L,L ,L ,L ,L ,L ,L,L ,
U,D,D|L,L ,L ,L ,L ,L,L ,
U,U,D ,D ,D|L,L ,L ,L,L ,
U,U,D|U,D|U,D ,D ,D|L,L,L ,
U,U,D|U,D|U,D|U,D|U,D ,D,D|L
}
};
seqan3::debug_stream << "database:\t" << database << std::endl;
seqan3::debug_stream << "query:\t\t" << query << std::endl;
seqan3::debug_stream << std::endl;
seqan3::debug_stream << "trace_matrix: " << trace_matrix.cols() << " columns and "
<< trace_matrix.rows() << " rows" << std::endl;
// Prints out the matrix in a convenient way
seqan3::debug_stream << trace_matrix << std::endl; // without sequences
seqan3::debug_stream << debug_matrix{trace_matrix, database, query} << std::endl; // with sequences
seqan3::debug_stream << seqan3::fmtflags2::utf8 << debug_matrix{trace_matrix, database, query}; // as utf8
return 0;
}
| 35.76 | 110 | 0.615213 | marehr |
6df953f7de78c5d844b7a240b350f8253e81d074 | 21,876 | cpp | C++ | catboost/cuda/cuda_util/sort.cpp | HeyLey/catboost | f472aed90604ebe727537d9d4a37147985e10ec2 | [
"Apache-2.0"
] | 6,989 | 2017-07-18T06:23:18.000Z | 2022-03-31T15:58:36.000Z | catboost/cuda/cuda_util/sort.cpp | HeyLey/catboost | f472aed90604ebe727537d9d4a37147985e10ec2 | [
"Apache-2.0"
] | 1,978 | 2017-07-18T09:17:58.000Z | 2022-03-31T14:28:43.000Z | catboost/cuda/cuda_util/sort.cpp | HeyLey/catboost | f472aed90604ebe727537d9d4a37147985e10ec2 | [
"Apache-2.0"
] | 1,228 | 2017-07-18T09:03:13.000Z | 2022-03-29T05:57:40.000Z | #include "sort.h"
#include "reorder_bins.h"
#include <catboost/cuda/cuda_lib/cuda_buffer.h>
#include <catboost/cuda/cuda_lib/cuda_kernel_buffer.h>
#include <catboost/cuda/cuda_lib/kernel.h>
#include <catboost/cuda/cuda_util/kernel/sort.cuh>
#include <catboost/cuda/cuda_util/kernel/transform.cuh>
#include <catboost/libs/helpers/exception.h>
#include <util/stream/labeled.h>
using NCudaLib::TMirrorMapping;
using NCudaLib::TSingleMapping;
using NCudaLib::TStripeMapping;
using NKernelHost::IMemoryManager;
using NKernelHost::TCudaBufferPtr;
using NKernelHost::TCudaStream;
using NKernelHost::TKernelBase;
using NKernelHost::uchar;
namespace {
template <typename T>
struct TValueConversion {
using TValue = T;
};
template <>
struct TValueConversion<char> {
using TValue = unsigned char;
};
template <>
struct TValueConversion<bool> {
using TValue = unsigned char;
};
template <>
struct TValueConversion<short> {
using TValue = unsigned short;
};
template <>
struct TValueConversion<int> {
using TValue = ui32;
};
template <>
struct TValueConversion<float> {
using TValue = ui32;
};
template <typename K, typename V>
class TRadixSortKernel: public TKernelBase<NKernel::TRadixSortContext> {
private:
TCudaBufferPtr<K> Keys;
TCudaBufferPtr<V> Values;
using TValueStorage = typename TValueConversion<V>::TValue;
bool CompareGreater;
ui32 FirstBit;
ui32 LastBit;
TCudaBufferPtr<K> TmpKeys;
TCudaBufferPtr<V> TmpValues;
public:
using TKernelContext = NKernel::TRadixSortContext;
TRadixSortKernel() = default;
TRadixSortKernel(TCudaBufferPtr<K> keys,
TCudaBufferPtr<V> values,
bool compareGreater,
ui32 firstBit = 0,
ui32 lastBit = sizeof(K) * 8)
: Keys(keys)
, Values(values)
, CompareGreater(compareGreater)
, FirstBit(firstBit)
, LastBit(lastBit)
{
}
TRadixSortKernel(TCudaBufferPtr<K> keys,
bool compareGreater,
ui32 firstBit = 0,
ui32 lastBit = sizeof(K) * 8)
: Keys(keys)
, Values(TCudaBufferPtr<V>::Nullptr())
, CompareGreater(compareGreater)
, FirstBit(firstBit)
, LastBit(lastBit)
{
}
TRadixSortKernel(TCudaBufferPtr<K> keys,
TCudaBufferPtr<V> values,
bool compareGreater,
ui32 firstBit,
ui32 lastBit,
TCudaBufferPtr<K> tmpKeys,
TCudaBufferPtr<V> tmpValues)
: Keys(keys)
, Values(values)
, CompareGreater(compareGreater)
, FirstBit(firstBit)
, LastBit(lastBit)
, TmpKeys(tmpKeys)
, TmpValues(tmpValues)
{
}
template <bool NeedOnlyTempStorage = false>
static inline void AllocateMemory(IMemoryManager& manager, ui32 size, NKernel::TRadixSortContext& context) {
if (!NeedOnlyTempStorage) {
context.TempKeys = manager.Allocate<char>(size * sizeof(K));
if (context.ValueSize) {
context.TempValues = manager.Allocate<char>(size * context.ValueSize);
}
}
context.TempStorage = manager.Allocate<char>(context.TempStorageSize);
}
inline void MakeTempKeysAndValuesPtrs(NKernel::TRadixSortContext& context) const {
CB_ENSURE(context.UseExternalBufferForTempKeysAndValues);
CB_ENSURE(TmpKeys.Size() == Keys.Size(), LabeledOutput(TmpKeys.Size(), Keys.Size()));
CB_ENSURE(TmpValues.Size() == Values.Size(), LabeledOutput(TmpValues.Size(), Values.Size()));
context.TempKeys = TmpKeys.GetData().GetRawHandleBasedPtr();
context.TempValues = TmpValues.GetData().GetRawHandleBasedPtr();
}
THolder<TKernelContext> PrepareContext(IMemoryManager& manager) const {
CB_ENSURE(Keys.Size() == Keys.ObjectCount(), LabeledOutput(Keys.Size(), Keys.ObjectCount()));
CB_ENSURE(Keys.Size() < (static_cast<ui64>(1) << 32), LabeledOutput(Keys.Size()));
const ui32 size = Keys.Size();
const ui32 valueSize = Values.Size() ? sizeof(V) : 0;
if (valueSize) {
CB_ENSURE(Values.Size() == Keys.Size());
}
auto context = MakeHolder<TKernelContext>(FirstBit, LastBit, valueSize, CompareGreater);
context->UseExternalBufferForTempKeysAndValues = TmpKeys.Size() > 0;
if (size) {
//fill temp storage size by cub
CUDA_SAFE_CALL(NKernel::RadixSort((K*)nullptr, (TValueStorage*)nullptr, size, *context, 0));
if (context->UseExternalBufferForTempKeysAndValues) {
AllocateMemory<true>(manager, size, *context);
} else {
AllocateMemory<false>(manager, size, *context);
}
}
return context;
}
void Run(const TCudaStream& stream, TKernelContext& context) const {
const ui32 size = Keys.Size();
if (size == 0) {
return;
}
if (context.UseExternalBufferForTempKeysAndValues) {
MakeTempKeysAndValuesPtrs(context);
}
//we need safecall for cub-based routines
CUDA_SAFE_CALL(NKernel::RadixSort(Keys.Get(), context.ValueSize ? (TValueStorage*)(Values.Get()) : (TValueStorage*)nullptr, size, context, stream.GetStream()));
}
Y_SAVELOAD_DEFINE(Keys, Values, CompareGreater, FirstBit, LastBit, TmpKeys, TmpValues);
};
}
// RadixSort
template <typename K, typename TMapping>
static void RadixSortImpl(TCudaBuffer<K, TMapping>& keys, bool compareGreater, ui32 stream) {
using TKernel = TRadixSortKernel<K, char>;
LaunchKernels<TKernel>(keys.NonEmptyDevices(), stream, keys, compareGreater);
}
#define Y_CATBOOST_CUDA_F_IMPL_PROXY(x) \
Y_CATBOOST_CUDA_F_IMPL x
#define Y_CATBOOST_CUDA_F_IMPL(K, TMapping) \
template <> \
void RadixSort<K, TMapping>(TCudaBuffer<K, TMapping> & keys, bool compareGreater, ui32 stream) { \
::RadixSortImpl(keys, compareGreater, stream); \
}
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, TMirrorMapping),
(ui32, TMirrorMapping),
(ui64, TMirrorMapping),
(bool, TMirrorMapping),
(float, TSingleMapping),
(ui32, TSingleMapping),
(ui64, TSingleMapping),
(bool, TSingleMapping),
(float, TStripeMapping),
(ui32, TStripeMapping),
(ui64, TStripeMapping),
(bool, TStripeMapping));
#undef Y_CATBOOST_CUDA_F_IMPL
#undef Y_CATBOOST_CUDA_F_IMPL_PROXY
// RadixSort
template <typename K, typename V, typename TMapping>
static void RadixSortImpl(
TCudaBuffer<K, TMapping>& keys,
TCudaBuffer<V, TMapping>& values,
bool compareGreater,
ui32 stream) {
using TKernel = TRadixSortKernel<K, V>;
LaunchKernels<TKernel>(keys.NonEmptyDevices(), stream, keys, values, compareGreater);
}
#define Y_CATBOOST_CUDA_F_IMPL_PROXY(x) \
Y_CATBOOST_CUDA_F_IMPL x
#define Y_CATBOOST_CUDA_F_IMPL(K, V, TMapping) \
template <> \
void RadixSort<K, V, TMapping>( \
TCudaBuffer<K, TMapping> & keys, \
TCudaBuffer<V, TMapping> & values, \
bool compareGreater, \
ui32 stream) { \
::RadixSortImpl(keys, values, compareGreater, stream); \
}
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TMirrorMapping),
(float, char, TMirrorMapping),
(float, ui16, TMirrorMapping),
(float, i16, TMirrorMapping),
(float, ui32, TMirrorMapping),
(float, i32, TMirrorMapping),
(float, float, TMirrorMapping),
(ui32, uchar, TMirrorMapping),
(ui32, char, TMirrorMapping),
(ui32, ui16, TMirrorMapping),
(ui32, i16, TMirrorMapping),
(ui32, ui32, TMirrorMapping),
(ui32, i32, TMirrorMapping),
(ui32, float, TMirrorMapping),
(ui64, i32, TMirrorMapping),
(float, uint2, TMirrorMapping),
(ui64, ui32, TMirrorMapping),
(bool, ui32, TMirrorMapping));
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TSingleMapping),
(float, char, TSingleMapping),
(float, ui16, TSingleMapping),
(float, i16, TSingleMapping),
(float, ui32, TSingleMapping),
(float, i32, TSingleMapping),
(float, float, TSingleMapping),
(ui32, uchar, TSingleMapping),
(ui32, char, TSingleMapping),
(ui32, ui16, TSingleMapping),
(ui32, i16, TSingleMapping),
(ui32, ui32, TSingleMapping),
(ui32, i32, TSingleMapping),
(ui32, float, TSingleMapping),
(ui64, i32, TSingleMapping),
(float, uint2, TSingleMapping),
(ui64, ui32, TSingleMapping),
(bool, ui32, TSingleMapping));
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TStripeMapping),
(float, char, TStripeMapping),
(float, ui16, TStripeMapping),
(float, i16, TStripeMapping),
(float, ui32, TStripeMapping),
(float, i32, TStripeMapping),
(float, float, TStripeMapping),
(ui32, uchar, TStripeMapping),
(ui32, char, TStripeMapping),
(ui32, ui16, TStripeMapping),
(ui32, i16, TStripeMapping),
(ui32, ui32, TStripeMapping),
(ui32, i32, TStripeMapping),
(ui32, float, TStripeMapping),
(ui64, i32, TStripeMapping),
(float, uint2, TStripeMapping),
(ui64, ui32, TStripeMapping),
(bool, ui32, TStripeMapping));
#undef Y_CATBOOST_CUDA_F_IMPL
#undef Y_CATBOOST_CUDA_F_IMPL_PROXY
// RadixSort
template <typename K, typename V, typename TMapping>
static void RadixSortImpl(
TCudaBuffer<K, TMapping>& keys, TCudaBuffer<V, TMapping>& values,
TCudaBuffer<K, TMapping>& tmpKeys, TCudaBuffer<V, TMapping>& tmpValues,
ui32 offset,
ui32 bits,
ui64 stream) {
using TKernel = TRadixSortKernel<K, V>;
CB_ENSURE((offset + bits) <= (sizeof(K) * 8), LabeledOutput(offset + bits, sizeof(K) + 8));
LaunchKernels<TKernel>(keys.NonEmptyDevices(), stream, keys, values, false, offset, offset + bits, tmpKeys, tmpValues);
}
#define Y_CATBOOST_CUDA_F_IMPL_PROXY(x) \
Y_CATBOOST_CUDA_F_IMPL x
#define Y_CATBOOST_CUDA_F_IMPL(K, V, TMapping) \
template <> \
void RadixSort<K, V, TMapping>( \
TCudaBuffer<K, TMapping> & keys, TCudaBuffer<V, TMapping> & values, \
TCudaBuffer<K, TMapping> & tmpKeys, TCudaBuffer<V, TMapping> & tmpValues, \
ui32 offset, \
ui32 bits, \
ui64 stream) { \
::RadixSortImpl(keys, values, tmpKeys, tmpValues, offset, bits, stream); \
}
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TMirrorMapping),
(float, char, TMirrorMapping),
(float, ui16, TMirrorMapping),
(float, i16, TMirrorMapping),
(float, ui32, TMirrorMapping),
(float, i32, TMirrorMapping),
(float, float, TMirrorMapping),
(ui32, uchar, TMirrorMapping),
(ui32, char, TMirrorMapping),
(ui32, ui16, TMirrorMapping),
(ui32, i16, TMirrorMapping),
(ui32, ui32, TMirrorMapping),
(ui32, i32, TMirrorMapping),
(ui32, float, TMirrorMapping),
(ui64, i32, TMirrorMapping),
(float, uint2, TMirrorMapping),
(ui64, ui32, TMirrorMapping),
(bool, ui32, TMirrorMapping));
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TSingleMapping),
(float, char, TSingleMapping),
(float, ui16, TSingleMapping),
(float, i16, TSingleMapping),
(float, ui32, TSingleMapping),
(float, i32, TSingleMapping),
(float, float, TSingleMapping),
(ui32, uchar, TSingleMapping),
(ui32, char, TSingleMapping),
(ui32, ui16, TSingleMapping),
(ui32, i16, TSingleMapping),
(ui32, ui32, TSingleMapping),
(ui32, i32, TSingleMapping),
(ui32, float, TSingleMapping),
(ui64, i32, TSingleMapping),
(float, uint2, TSingleMapping),
(ui64, ui32, TSingleMapping),
(bool, ui32, TSingleMapping));
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TStripeMapping),
(float, char, TStripeMapping),
(float, ui16, TStripeMapping),
(float, i16, TStripeMapping),
(float, ui32, TStripeMapping),
(float, i32, TStripeMapping),
(float, float, TStripeMapping),
(ui32, uchar, TStripeMapping),
(ui32, char, TStripeMapping),
(ui32, ui16, TStripeMapping),
(ui32, i16, TStripeMapping),
(ui32, ui32, TStripeMapping),
(ui32, i32, TStripeMapping),
(ui32, float, TStripeMapping),
(ui64, i32, TStripeMapping),
(float, uint2, TStripeMapping),
(ui64, ui32, TStripeMapping),
(bool, ui32, TStripeMapping));
#undef Y_CATBOOST_CUDA_F_IMPL
#undef Y_CATBOOST_CUDA_F_IMPL_PROXY
// RadixSort
template <typename K, typename V, typename TMapping>
static void RadixSortImpl(
TCudaBuffer<K, TMapping>& keys,
TCudaBuffer<V, TMapping>& values,
bool compareGreater,
ui32 offset,
ui32 bits,
ui32 stream) {
using TKernel = TRadixSortKernel<K, V>;
LaunchKernels<TKernel>(keys.NonEmptyDevices(), stream, keys, values, compareGreater, offset, bits);
}
#define Y_CATBOOST_CUDA_F_IMPL_PROXY(x) \
Y_CATBOOST_CUDA_F_IMPL x
#define Y_CATBOOST_CUDA_F_IMPL(K, V, TMapping) \
template <> \
void RadixSort<K, V, TMapping>( \
TCudaBuffer<K, TMapping> & keys, \
TCudaBuffer<V, TMapping> & values, \
bool compareGreater, \
ui32 offset, \
ui32 bits, \
ui32 stream) { \
::RadixSortImpl(keys, values, compareGreater, offset, bits, stream); \
}
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TMirrorMapping),
(float, char, TMirrorMapping),
(float, ui16, TMirrorMapping),
(float, i16, TMirrorMapping),
(float, ui32, TMirrorMapping),
(float, i32, TMirrorMapping),
(float, float, TMirrorMapping),
(ui32, uchar, TMirrorMapping),
(ui32, char, TMirrorMapping),
(ui32, ui16, TMirrorMapping),
(ui32, i16, TMirrorMapping),
(ui32, ui32, TMirrorMapping),
(ui32, i32, TMirrorMapping),
(ui32, float, TMirrorMapping),
(ui64, i32, TMirrorMapping),
(float, uint2, TMirrorMapping),
(ui64, ui32, TMirrorMapping),
(bool, ui32, TMirrorMapping));
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TSingleMapping),
(float, char, TSingleMapping),
(float, ui16, TSingleMapping),
(float, i16, TSingleMapping),
(float, ui32, TSingleMapping),
(float, i32, TSingleMapping),
(float, float, TSingleMapping),
(ui32, uchar, TSingleMapping),
(ui32, char, TSingleMapping),
(ui32, ui16, TSingleMapping),
(ui32, i16, TSingleMapping),
(ui32, ui32, TSingleMapping),
(ui32, i32, TSingleMapping),
(ui32, float, TSingleMapping),
(ui64, i32, TSingleMapping),
(float, uint2, TSingleMapping),
(ui64, ui32, TSingleMapping),
(bool, ui32, TSingleMapping));
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL_PROXY,
(float, uchar, TStripeMapping),
(float, char, TStripeMapping),
(float, ui16, TStripeMapping),
(float, i16, TStripeMapping),
(float, ui32, TStripeMapping),
(float, i32, TStripeMapping),
(float, float, TStripeMapping),
(ui32, uchar, TStripeMapping),
(ui32, char, TStripeMapping),
(ui32, ui16, TStripeMapping),
(ui32, i16, TStripeMapping),
(ui32, ui32, TStripeMapping),
(ui32, i32, TStripeMapping),
(ui32, float, TStripeMapping),
(ui64, i32, TStripeMapping),
(float, uint2, TStripeMapping),
(ui64, ui32, TStripeMapping),
(bool, ui32, TStripeMapping));
#undef Y_CATBOOST_CUDA_F_IMPL
#undef Y_CATBOOST_CUDA_F_IMPL_PROXY
// ReorderBins
template <typename TMapping>
static void ReorderBinsImpl(
TCudaBuffer<ui32, TMapping>& bins,
TCudaBuffer<ui32, TMapping>& indices,
ui32 offset,
ui32 bits,
ui64 stream) {
using TKernel = TRadixSortKernel<ui32, ui32>;
CB_ENSURE((offset + bits) <= (sizeof(ui32) * 8), LabeledOutput(offset + bits, sizeof(ui32) * 8));
LaunchKernels<TKernel>(bins.NonEmptyDevices(), stream, bins, indices, false, offset, offset + bits);
}
#define Y_CATBOOST_CUDA_F_IMPL(TMapping) \
template <> \
void ReorderBins<TMapping>( \
TCudaBuffer<ui32, TMapping> & bins, \
TCudaBuffer<ui32, TMapping> & indices, \
ui32 offset, \
ui32 bits, \
ui64 stream) { \
::ReorderBinsImpl(bins, indices, offset, bits, stream); \
}
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL,
TMirrorMapping,
TSingleMapping,
TStripeMapping);
#undef Y_CATBOOST_CUDA_F_IMPL
// ReorderBins
template <typename TMapping>
static void ReorderBinsImpl(
TCudaBuffer<ui32, TMapping>& bins,
TCudaBuffer<ui32, TMapping>& indices,
ui32 offset,
ui32 bits,
TCudaBuffer<ui32, TMapping>& tmpBins,
TCudaBuffer<ui32, TMapping>& tmpIndices,
ui64 stream) {
using TKernel = TRadixSortKernel<ui32, ui32>;
CB_ENSURE((offset + bits) <= (sizeof(ui32) * 8), LabeledOutput(offset + bits, sizeof(ui32) * 8));
LaunchKernels<TKernel>(bins.NonEmptyDevices(), stream, bins, indices, false, offset, offset + bits, tmpBins, tmpIndices);
}
#define Y_CATBOOST_CUDA_F_IMPL(TMapping) \
template <> \
void ReorderBins<TMapping>( \
TCudaBuffer<ui32, TMapping> & bins, \
TCudaBuffer<ui32, TMapping> & indices, \
ui32 offset, \
ui32 bits, \
TCudaBuffer<ui32, TMapping> & tmpBins, \
TCudaBuffer<ui32, TMapping> & tmpIndices, \
ui64 stream) { \
::ReorderBinsImpl(bins, indices, offset, bits, tmpBins, tmpIndices, stream); \
}
Y_MAP_ARGS(
Y_CATBOOST_CUDA_F_IMPL,
TMirrorMapping,
TSingleMapping,
TStripeMapping);
#undef Y_CATBOOST_CUDA_F_IMPL
// register kernels
namespace NCudaLib {
//TODO(noxoomo): remap on master side
REGISTER_KERNEL_TEMPLATE_2(0xAA0001, TRadixSortKernel, float, uchar);
REGISTER_KERNEL_TEMPLATE_2(0xAA0002, TRadixSortKernel, float, char);
REGISTER_KERNEL_TEMPLATE_2(0xAA0003, TRadixSortKernel, float, ui16);
REGISTER_KERNEL_TEMPLATE_2(0xAA0004, TRadixSortKernel, float, i16);
REGISTER_KERNEL_TEMPLATE_2(0xAA0005, TRadixSortKernel, float, ui32);
REGISTER_KERNEL_TEMPLATE_2(0xAA0006, TRadixSortKernel, float, i32);
REGISTER_KERNEL_TEMPLATE_2(0xAA0007, TRadixSortKernel, float, float);
REGISTER_KERNEL_TEMPLATE_2(0xAA0008, TRadixSortKernel, ui32, uchar);
REGISTER_KERNEL_TEMPLATE_2(0xAA0009, TRadixSortKernel, ui32, char);
REGISTER_KERNEL_TEMPLATE_2(0xAA0010, TRadixSortKernel, ui32, ui16);
REGISTER_KERNEL_TEMPLATE_2(0xAA0011, TRadixSortKernel, ui32, i16);
REGISTER_KERNEL_TEMPLATE_2(0xAA0012, TRadixSortKernel, ui32, ui32);
REGISTER_KERNEL_TEMPLATE_2(0xAA0013, TRadixSortKernel, ui32, i32);
REGISTER_KERNEL_TEMPLATE_2(0xAA0014, TRadixSortKernel, ui32, float);
REGISTER_KERNEL_TEMPLATE_2(0xAA0015, TRadixSortKernel, ui64, i32);
REGISTER_KERNEL_TEMPLATE_2(0xAA0016, TRadixSortKernel, float, uint2);
REGISTER_KERNEL_TEMPLATE_2(0xAA0017, TRadixSortKernel, ui64, ui32);
REGISTER_KERNEL_TEMPLATE_2(0xAA0018, TRadixSortKernel, bool, ui32);
// REGISTER_KERNEL_TEMPLATE_2(0xAA0015, TRadixSortKernel, i32, uchar);
// REGISTER_KERNEL_TEMPLATE_2(0xAA0016, TRadixSortKernel, i32, char);
// REGISTER_KERNEL_TEMPLATE_2(0xAA0017, TRadixSortKernel, i32, ui16);
// REGISTER_KERNEL_TEMPLATE_2(0xAA0018, TRadixSortKernel, i32, i16);
// REGISTER_KERNEL_TEMPLATE_2(0xAA0019, TRadixSortKernel, i32, ui32);
// REGISTER_KERNEL_TEMPLATE_2(0xAA0020, TRadixSortKernel, i32, i32);
// REGISTER_KERNEL_TEMPLATE_2(0xAA0021, TRadixSortKernel, i32, float);
}
| 37.140917 | 172 | 0.598236 | HeyLey |
6dfdf0104e6d8f0e56afba47b2b7c59c43c9e52e | 2,266 | cpp | C++ | src/ui/ControlsWidget.cpp | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 2,706 | 2018-04-05T18:28:50.000Z | 2022-03-29T16:56:59.000Z | src/ui/ControlsWidget.cpp | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 242 | 2018-04-05T22:30:42.000Z | 2022-03-19T01:55:11.000Z | src/ui/ControlsWidget.cpp | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 464 | 2018-04-05T19:10:34.000Z | 2022-03-28T13:33:32.000Z | #include "ControlsWidget.h"
#include "ui_ControlsWidget.h"
#include <QGroupBox>
#include <QKeySequenceEdit>
#include <QLabel>
ControlsWidget::ControlsWidget(const QString& platform, QWidget* parent)
: QDialog(parent)
, m_ui(new Ui::ControlsWidget) {
m_ui->setupUi(this);
m_ui->platform->setTitle(platform);
m_sections.append(m_ui->platform);
}
ControlsWidget::~ControlsWidget() {
delete m_ui;
}
void ControlsWidget::setKeys(const QStringList& keys) {
m_keyNames = keys;
for (unsigned player = 0; player < m_bindings.size(); ++player) {
for (const auto& key : m_bindings[player].keys()) {
if (!m_keyNames.contains(key)) {
m_bindings[player].remove(key);
}
}
}
}
void ControlsWidget::setBindings(const QMap<QString, int>& bindings, unsigned player) {
m_bindings[player].clear();
while (m_sections[player]->layout()->count()) {
delete m_sections[player]->layout()->takeAt(0);
}
for (const auto& key : m_keyNames) {
if (bindings.contains(key)) {
m_bindings[player][key] = bindings[key];
QKeySequenceEdit* edit = new QKeySequenceEdit(QKeySequence(bindings[key]));
QFormLayout* layout = static_cast<QFormLayout*>(m_sections[player]->layout());
layout->addRow(key, edit);
connect(edit, &QKeySequenceEdit::keySequenceChanged, [this, key, player](const QKeySequence& seq) {
m_bindings[player][key] = seq[0];
});
}
}
}
void ControlsWidget::setPlayers(unsigned players) {
m_players = players;
while (m_bindings.size() < players) {
m_bindings.append(QMap<QString, int>{});
}
while (m_bindings.size() > players) {
m_bindings.removeLast();
}
while (m_sections.size() < players) {
QGroupBox* box = new QGroupBox;
m_sections.append(box);
box->setTitle(tr("Player %1").arg(m_sections.size()));
box->setLayout(new QFormLayout);
m_ui->players->addWidget(box);
}
while (m_sections.size() > players) {
delete m_sections.takeLast();
}
}
QMap<QString, int> ControlsWidget::getBindings(unsigned player) const {
return m_bindings[player];
}
void ControlsWidget::accept() {
for (unsigned player = 0; player < m_players; ++player) {
for (const auto& key : m_keyNames) {
if (m_bindings[player].contains(key)) {
emit bindingChanged(key, m_bindings[player][key], player);
}
}
}
close();
}
| 27.301205 | 102 | 0.698147 | MatPoliquin |
a300c0ce65eb4fcf7b6443f06c01650df6ce9b8f | 21,074 | cpp | C++ | source/code/providers/MySQL_Server_Class_Provider.cpp | Bhaskers-Blu-Org2/MySQL-Provider | 211f79e98e7f34a13c4fb7c01f3aaaefc0dada63 | [
"MIT"
] | 5 | 2016-06-18T14:41:36.000Z | 2019-01-10T09:46:20.000Z | source/code/providers/MySQL_Server_Class_Provider.cpp | microsoft/MySQL-Provider | 211f79e98e7f34a13c4fb7c01f3aaaefc0dada63 | [
"MIT"
] | 5 | 2016-04-12T23:00:45.000Z | 2019-03-28T23:04:57.000Z | source/code/providers/MySQL_Server_Class_Provider.cpp | microsoft/MySQL-Provider | 211f79e98e7f34a13c4fb7c01f3aaaefc0dada63 | [
"MIT"
] | 6 | 2019-09-18T00:11:36.000Z | 2021-11-10T10:07:03.000Z | /* @migen@ */
/*
* --------------------------------- START OF LICENSE ----------------------------
*
* MySQL cimprov ver. 1.0
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the ""Software""), to deal
* in the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* ---------------------------------- END OF LICENSE -----------------------------
*/
#include <MI.h>
#include "MySQL_Server_Class_Provider.h"
#include <scxcorelib/scxcmn.h>
#include <scxcorelib/scxfile.h>
#include <scxcorelib/scxnameresolver.h>
#include <scxcorelib/stringaid.h>
#include <util/Base64Helper.h>
#include "sqlauth.h"
#include "logstartup.h"
#include "sqlbinding.h"
#include <errmsg.h>
#include <mysqld_error.h>
// Pick up specific definitions for new MySQL versions if we're on an older version
#if !defined(ER_BASE64_DECODE_ERROR)
#define ER_BASE64_DECODE_ERROR 1575
#endif
#if !defined(ER_ACCESS_DENIED_NO_PASSWORD_ERROR)
#define ER_ACCESS_DENIED_NO_PASSWORD_ERROR 1698
#endif
using namespace SCXCoreLib;
MI_BEGIN_NAMESPACE
/*----------------------------------------------------------------------------*/
/**
Find the MySQL configuration file (priority-based search algorithm)
\param[in] pBinding Binding object
\param[in] pAuth Authentication class for MySQL authentication
\returns MySQL configuraiton file path, or empty string if none found
*/
static std::string FindConfigurationFile(
util::unique_ptr<MySQL_Binding>& pBinding,
util::unique_ptr<MySQL_Authentication>& pAuth)
{
std::string configFile;
if ( pAuth->GetAutomaticUpdates() )
{
std::vector<std::string> sqlPaths;
pBinding->GetConfigurationFilePaths( sqlPaths );
for (std::vector<std::string>::const_iterator it = sqlPaths.begin(); it != sqlPaths.end(); ++it)
{
if ( SCXFile::Exists(SCXFilePath(StrFromUTF8(*it))) )
{
configFile = *it;
break;
}
}
}
return configFile;
}
/*----------------------------------------------------------------------------*/
/**
Enumerate special "failure" case of MySQL_Server class (if we're unable
to connect or authenticate to the MySQL instance from port/auth data)
\param[in] hLog LogHandle for logging purposes
\param[in] pBinding Binding object to get information about MySQL install
\param[out] inst Instance to populate (caller will post the instance)
\param[in] port Port number of MySQL server instance to connect to
\param[in] auth Authentication class for MySQL authentication
\param[in] keysOnly True if only keys should be populated, false otherwise
\param[in] sqlError MySQL error from connection/authentication failure
*/
static void EnumerateConnectionFailure(
SCXLogHandle& hLog,
util::unique_ptr<MySQL_Binding>& pBinding,
MySQL_Server_Class& inst,
unsigned int port,
util::unique_ptr<MySQL_Authentication>& pAuth,
const bool keysOnly,
unsigned int sqlError)
{
// The ProductID is the hostname:bind-address:port combination (assume no DB connection)
NameResolver nr;
std::string hostname( StrToUTF8(nr.GetHostname()) );
MySQL_AuthenticationEntry entry;
pAuth->GetEntry(port, entry);
std::string productID = hostname + ":" + entry.binding + ":" + StrToUTF8(StrFrom(port));
inst.ProductIdentifyingNumber_value( productID.c_str() );
inst.ProductName_value( "MySQL" );
inst.ProductVendor_value( "Oracle" );
inst.ProductVersion_value( "" );
inst.SystemID_value( "" );
inst.CollectionID_value( "" );
if ( !keysOnly )
{
// Try and find the configuration at a list of known locations
std::string configFile( FindConfigurationFile(pBinding, pAuth) );
if ( configFile.size() )
{
inst.ConfigurationFile_value( configFile.c_str() );
}
inst.Hostname_value( hostname.c_str() );
inst.BindAddress_value( entry.binding.c_str() );
inst.Port_value( port );
const char *pStatus;
switch (sqlError)
{
case ER_ABORTING_CONNECTION: // 1152
pStatus = "Aborted";
break;
case ER_CRASHED_ON_REPAIR: // 1195
case ER_WARN_QC_RESIZE: // 1282
case ER_INDEX_REBUILD: // 1187
pStatus = "Degraded";
break;
case ER_DBACCESS_DENIED_ERROR: // 1044
case ER_ACCESS_DENIED_ERROR: // 1045
case ER_HOST_NOT_PRIVILEGED: // 1130
case ER_SPECIFIC_ACCESS_DENIED_ERROR: // 1227
case ER_CANNOT_USER: // 1396
case ER_BASE64_DECODE_ERROR: // 1575
case ER_ACCESS_DENIED_NO_PASSWORD_ERROR: // 1698
pStatus = "Insufficient Privileges";
break;
case CR_CONNECTION_ERROR: // 2002
case CR_CONN_HOST_ERROR: // 2003
pStatus = "No Contact";
break;
case ER_SERVER_SHUTDOWN: // 1053
case ER_NORMAL_SHUTDOWN: // 1077
pStatus = "Stopping";
break;
case ER_CON_COUNT_ERROR: // 1040
case ER_OUT_OF_RESOURCES: // 1041
case ER_HOST_IS_BLOCKED: // 1129
case ER_CANT_CREATE_THREAD: // 1135
case ER_TOO_MANY_USER_CONNECTIONS: // 1203
case ER_FPARSER_TOO_BIG_FILE: // 1340
pStatus = "Stressed";
break;
case MYSQL_AUTH_EXCEPTION: // (Internal)
case MYSQL_AUTH_INVALID_ENTRY: // (Internal)
pStatus = "Authentication File in Error";
break;
default:
pStatus = "Unknown";
}
inst.OperatingStatus_value( pStatus );
}
}
/*----------------------------------------------------------------------------*/
/**
Enumerate one single instance of MySQL_Server class given inputs
Note: If we're unable to connect to MySQL for whatever reason (server down,
authentication issues, etc), then we populate the instance as a failure
using function 'EnumerateConnectionFailure'. Since SOMETHING is always
set up in the instance, the caller should always post the result.
\param[in] hLog LogHandle for logging purposes
\param[out] inst Instance to populate (caller will post the instance)
\param[in] port Port number of MySQL server instance to connect to
\param[in] auth Authentication class for MySQL authentication
\param[in] keysOnly True if only keys should be populated, false otherwise
*/
static void EnumerateOneInstance(
SCXLogHandle& hLog,
MySQL_Server_Class& inst,
unsigned int port,
util::unique_ptr<MySQL_Authentication>& pAuth,
const bool keysOnly)
{
util::unique_ptr<MySQL_Binding> pBinding( g_pFactory->GetBinding() );
std::string strValue;
// Attach to the MySQL database instance
if ( !pBinding->AttachUsingStoredCredentials(port, pAuth) )
{
std::stringstream ss;
ss << "Failure attaching to MySQL on port: " << port << ", Error "
<< pBinding->GetErrorNum() << ": " << pBinding->GetErrorText();
SCX_LOGERROR(hLog, ss.str());
EnumerateConnectionFailure(hLog, pBinding, inst, port, pAuth, keysOnly, pBinding->GetErrorNum());
return;
}
// Execute a query to get the MySQL variables
util::unique_ptr<MySQL_Query> pQuery( g_pFactory->GetQuery() );
std::map<std::string, std::string> variables;
if ( ! pQuery->ExecuteQuery("show variables") || ! pQuery->GetResults(variables) )
{
std::stringstream ss;
ss << "Failure executing query \"show variables\" against MySQL engine on port " << port
<< ", Error " << pQuery->GetErrorNum() << ": " << pQuery->GetErrorText();
SCX_LOGERROR(hLog, ss.str());
EnumerateConnectionFailure(hLog, pBinding, inst, port, pAuth, keysOnly, pQuery->GetErrorNum());
return;
}
// The ProductID is the hostname:bind-address:port combination
std::string hostname, strPort;
if ( !GetStrValue(variables, "hostname", hostname) )
{
// Populate hostname here (for MySQL 5.0 systems)
NameResolver nr;
hostname = StrToUTF8(nr.GetHostname());
}
MySQL_AuthenticationEntry entry;
pAuth->GetEntry(port, entry);
if ( !GetStrValue(variables, "port", strPort) )
{
SCX_LOGERROR(hLog, StrAppend(L"Query \"show variables\" did not return \"port\" in the result set on port ", port));
strPort = StrToUTF8(StrFrom(port));
}
std::string productID = hostname + ":" + entry.binding + ":" + strPort;
inst.ProductIdentifyingNumber_value( productID.c_str() );
inst.ProductName_value( "MySQL" );
inst.ProductVendor_value( "Oracle" );
if ( GetStrValue(variables, "version", strValue) )
{
inst.ProductVersion_value( strValue.c_str() );
}
if ( GetStrValue(variables, "server_id", strValue) )
{
inst.SystemID_value( strValue.c_str() );
}
if ( GetStrValue(variables, "version_compile_os", strValue) )
{
inst.CollectionID_value( strValue.c_str() );
}
if ( !keysOnly )
{
// Try and find the configuration at a list of known locations
std::string configFile( FindConfigurationFile(pBinding, pAuth) );
if ( configFile.size() )
{
inst.ConfigurationFile_value( configFile.c_str() );
}
if ( GetStrValue(variables, "log_error", strValue) )
{
inst.ErrorLogFile_value( strValue.c_str() );
}
inst.Hostname_value( hostname.c_str() );
inst.BindAddress_value( entry.binding.c_str() );
inst.Port_value( port );
if ( GetStrValue(variables, "socket", strValue) )
{
inst.SocketFile_value( strValue.c_str() );
}
if ( GetStrValue(variables, "datadir", strValue) )
{
inst.DataDirectory_value( strValue.c_str() );
}
inst.OperatingStatus_value( "OK" );
}
}
MySQL_Server_Class_Provider::MySQL_Server_Class_Provider(
Module* module) :
m_Module(module)
{
}
MySQL_Server_Class_Provider::~MySQL_Server_Class_Provider()
{
}
void MySQL_Server_Class_Provider::Load(
Context& context)
{
MySQL::LogStartup();
context.Post(MI_RESULT_OK);
}
void MySQL_Server_Class_Provider::Unload(
Context& context)
{
context.Post(MI_RESULT_OK);
}
void MySQL_Server_Class_Provider::EnumerateInstances(
Context& context,
const String& nameSpace,
const PropertySet& propertySet,
bool keysOnly,
const MI_Filter* filter)
{
SCXLogHandle hLog = SCXLogHandleFactory::GetLogHandle(L"mysql.provider.server");
CIM_PEX_BEGIN
{
// Get the list of ports (instances) that we want to look at
std::vector<unsigned int> portList;
util::unique_ptr<MySQL_Authentication> pAuth(g_pFactory->GetAuthentication());
pAuth->Load();
pAuth->GetPortList(portList);
for (std::vector<unsigned int>::const_iterator it = portList.begin(); it != portList.end(); ++it)
{
MySQL_Server_Class inst;
EnumerateOneInstance(hLog, inst, *it, pAuth, keysOnly);
context.Post(inst);
}
context.Post(MI_RESULT_OK);
}
CIM_PEX_END( L"MySQL_Server_Class_Provider::EnumerateInstances" , hLog );
}
void MySQL_Server_Class_Provider::GetInstance(
Context& context,
const String& nameSpace,
const MySQL_Server_Class& instanceName,
const PropertySet& propertySet)
{
SCXLogHandle hLog = SCXLogHandleFactory::GetLogHandle(L"mysql.provider.server");
CIM_PEX_BEGIN
{
// Was have a 6-part key (on Redhat, it looks like this):
// [Key] ProductIdentifyingNumber=jeffcof64-rhel6-01:127.0.0.1:3306
// [Key] ProductName=MySQL
// [Key] ProductVendor=Oracle
// [Key] ProductVersion=5.1.52
// [Key] SystemID=0
// [Key] CollectionID=redhat-linux-gnu
if ( !instanceName.ProductIdentifyingNumber_exists()
|| !instanceName.ProductName_exists()
|| !instanceName.ProductVendor_exists()
|| !instanceName.ProductVersion_exists()
|| !instanceName.SystemID_exists()
|| !instanceName.CollectionID_exists() )
{
context.Post(MI_RESULT_INVALID_PARAMETER);
return;
}
// Now compare (case insensitive for the class names, case sensitive for the others)
if ( 0 != strcasecmp("MySQL", instanceName.ProductName_value().Str())
|| 0 != strcasecmp("Oracle", instanceName.ProductVendor_value().Str()) )
{
context.Post(MI_RESULT_NOT_FOUND);
return;
}
// Save the bind-address and port from the ProductIdentifyingNumber (host:bind-address:port)
std::wstring productID( StrFromUTF8(instanceName.ProductIdentifyingNumber_value().Str()) );
std::vector<std::wstring> elements;
StrTokenize(productID, elements, L":", true, true);
if ( 3 != elements.size() || std::string::npos != elements[2].find_first_not_of(L"0123456789") )
{
context.Post(MI_RESULT_NOT_FOUND);
return;
}
std::string bindAddress( StrToUTF8(elements[1]) );
unsigned int port = StrToUInt( elements[2] );
// We have the information we need, so try and retrieve the instance
// (But validate the bind address along the way)
util::unique_ptr<MySQL_Authentication> pAuth(g_pFactory->GetAuthentication());
MySQL_AuthenticationEntry authEntry;
pAuth->Load();
pAuth->GetEntry(port, authEntry);
if ( 0 != strcasecmp(authEntry.binding.c_str(), bindAddress.c_str()) )
{
context.Post(MI_RESULT_NOT_FOUND);
return;
}
MySQL_Server_Class inst;
EnumerateOneInstance(hLog, inst, port, pAuth, false /* keysOnly */);
// Wicked ugly; the CIM standard calls for key validation, so we must as well (or unit tests fail)
// If these final values pass, then we post result; otherwise we just return a failure
// This, unfortunately, makes this class almost useless, but the standard is the standard
if ( 0 != strcasecmp(inst.ProductVersion_value().Str(), instanceName.ProductVersion_value().Str())
|| 0 != strcasecmp(inst.SystemID_value().Str(), instanceName.SystemID_value().Str())
|| 0 != strcasecmp(inst.CollectionID_value().Str(), instanceName.CollectionID_value().Str()) )
{
context.Post(MI_RESULT_NOT_FOUND);
return;
}
context.Post(inst);
context.Post(MI_RESULT_OK);
}
CIM_PEX_END( L"MySQL_Server_Class_Provider::GetInstance", hLog );
}
void MySQL_Server_Class_Provider::CreateInstance(
Context& context,
const String& nameSpace,
const MySQL_Server_Class& newInstance)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void MySQL_Server_Class_Provider::ModifyInstance(
Context& context,
const String& nameSpace,
const MySQL_Server_Class& modifiedInstance,
const PropertySet& propertySet)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void MySQL_Server_Class_Provider::DeleteInstance(
Context& context,
const String& nameSpace,
const MySQL_Server_Class& instanceName)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void MySQL_Server_Class_Provider::Invoke_UpdateCredentials(
Context& context,
const String& nameSpace,
const MySQL_Server_Class& instanceName,
const MySQL_Server_UpdateCredentials_Class& in)
{
SCXLogHandle hLog = SCXLogHandleFactory::GetLogHandle(L"mysql.provider.server");
CIM_PEX_BEGIN
{
SCX_LOGTRACE( hLog, L"MySQL_Server_Class_Provider::Invoke_UpdateCredentials Begin" )
// Parameters (from MOF file):
// [IN] uint16 Port
// [IN] string BindAddress (optional)
// [IN] string Username (optional)
// [IN] string Password (optional)
// [IN] boolean B64Encoded (optional)
// Validate that we have mandatory arguments
if ( !in.Port_exists() )
{
SCX_LOGTRACE( hLog, L"Missing arguments to Invoke_UpdateCredentials method" );
context.Post(MI_RESULT_INVALID_PARAMETER);
return;
}
uint16_t port = in.Port_value();
std::string bindAddress = ( in.BindAddress_exists() ? in.BindAddress_value().Str() : "" );
std::string username = ( in.Username_exists() ? in.Username_value().Str() : "" );
std::string password = ( in.Password_exists() ? in.Password_value().Str() : "" );
// If we need to decode a Base64-encoded password, do so
if ( in.B64Encoded_exists() && in.B64Encoded_value() )
{
bool result = util::Base64Helper::Decode(password, password);
if ( ! result )
{
// Base64 conversion error - return failure
context.Post(MI_RESULT_FAILED);
return;
}
}
SCX_LOGTRACE( hLog, "MySQL_Server_Class_Provider::Invoke_UpdateCredentials - Port: " + StrToUTF8(StrFrom(port))
+ ", Bind Address: " + bindAddress + ", Username: " + username
+ ", Password: " + ( password.size() ? "<not empty>" : "<empty>") );
bool returnFlag = false;
try
{
util::unique_ptr<MySQL_Authentication> pAuth(g_pFactory->GetAuthentication());
pAuth->Load();
pAuth->AddCredentialSet(port, bindAddress, username, password);
pAuth->Save();
returnFlag = true;
}
catch (SCXException& e)
{
SCX_LOGERROR(hLog, L"Failure updating credentials: " + e.What());
}
MySQL_Server_UpdateCredentials_Class inst;
inst.MIReturn_value(returnFlag);
context.Post(inst);
context.Post(MI_RESULT_OK);
}
CIM_PEX_END( L"MySQL_Server_Class_Provider::Invoke_UpdateCredentials", hLog );
}
void MySQL_Server_Class_Provider::Invoke_DeleteCredentials(
Context& context,
const String& nameSpace,
const MySQL_Server_Class& instanceName,
const MySQL_Server_DeleteCredentials_Class& in)
{
SCXLogHandle hLog = SCXLogHandleFactory::GetLogHandle(L"mysql.provider.server");
CIM_PEX_BEGIN
{
SCX_LOGTRACE( hLog, L"MySQL_Server_Class_Provider::Invoke_DeleteCredentials Begin" )
// Parameters (from MOF file):
// [IN] uint16 Port
// Validate that we have mandatory arguments
if ( !in.Port_exists() )
{
SCX_LOGTRACE( hLog, L"Missing arguments to Invoke_DeleteCredentials method" );
context.Post(MI_RESULT_INVALID_PARAMETER);
return;
}
uint16_t port = in.Port_value();
SCX_LOGTRACE( hLog, L"MySQL_Server_Class_Provider::Invoke_DeleteCredentials - Port: " + StrFrom(port) );
bool returnFlag = false;
try
{
util::unique_ptr<MySQL_Authentication> pAuth(g_pFactory->GetAuthentication());
pAuth->Load();
pAuth->DeleteCredentialSet(port);
pAuth->Save();
returnFlag = true;
}
catch (SCXException& e)
{
SCX_LOGERROR(hLog, L"Failure deleting credentials: " + e.What());
}
MySQL_Server_DeleteCredentials_Class inst;
inst.MIReturn_value(returnFlag);
context.Post(inst);
context.Post(MI_RESULT_OK);
}
CIM_PEX_END( L"MySQL_Server_Class_Provider::Invoke_DeleteCredentials", hLog );
}
MI_END_NAMESPACE
| 33.990323 | 124 | 0.624988 | Bhaskers-Blu-Org2 |
a30172f20b7ffc51b3953b50b8337ba4888b5840 | 4,479 | cpp | C++ | example/multi-surfaces/src/minko/geometry/CubeGeometryDown.cpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | null | null | null | example/multi-surfaces/src/minko/geometry/CubeGeometryDown.cpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | null | null | null | example/multi-surfaces/src/minko/geometry/CubeGeometryDown.cpp | undeadinu/minko | 9171805751fb3a50c6fcab0b78892cdd4253ee11 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2014 Aerys
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 "CubeGeometryDown.hpp"
using namespace minko;
using namespace minko::geometry;
using namespace minko::render;
using namespace minko::render;
void
CubeGeometryDown::initialize(std::shared_ptr<AbstractContext> context)
{
float xyzData[] =
{
// top
0.5f, -1.2f +0.5f, -0.5f, 0.f, 1.f, 0.f, 1.f, 0.f,
-0.5f,-1.2f + 0.5f, 0.5f, 0.f, 1.f, 0.f, 0.f, 1.f,
0.5f, -1.2f +0.5f, 0.5f, 0.f, 1.f, 0.f, 1.f, 1.f,
0.5f, -1.2f +0.5f, -0.5f, 0.f, 1.f, 0.f, 1.f, 0.f,
-0.5f,-1.2f + 0.5f, -0.5f, 0.f, 1.f, 0.f, 0.f, 0.f,
-0.5f,-1.2f + 0.5f, 0.5f, 0.f, 1.f, 0.f, 0.f, 1.f,
// bottom
-0.5f,-1.2f + -0.5f, 0.5f, 0.f, -1.f, 0.f, 0.f, 0.f,
0.5f, -1.2f +-0.5f, -0.5f, 0.f, -1.f, 0.f, 1.f, 1.f,
0.5f, -1.2f +-0.5f, 0.5f, 0.f, -1.f, 0.f, 1.f, 0.f,
-0.5f,-1.2f + -0.5f, -0.5f, 0.f, -1.f, 0.f, 0.f, 1.f,
0.5f, -1.2f +-0.5f, -0.5f, 0.f, -1.f, 0.f, 1.f, 1.f,
-0.5f,-1.2f + -0.5f, 0.5f, 0.f, -1.f, 0.f, 0.f, 0.f,
// front
0.5f, -1.2f + -0.5f, -0.5f, 0.f, 0.f, -1.f, 0.f, 1.f,
-0.5f,-1.2f + 0.5f, -0.5f, 0.f, 0.f, -1.f, 1.f, 0.f,
0.5f, -1.2f + 0.5f, -0.5f, 0.f, 0.f, -1.f, 0.f, 0.f,
-0.5f,-1.2f + 0.5f, -0.5f, 0.f, 0.f, -1.f, 1.f, 0.f,
0.5f, -1.2f + -0.5f, -0.5f, 0.f, 0.f, -1.f, 0.f, 1.f,
-0.5f,-1.2f + -0.5f, -0.5f, 0.f, 0.f, -1.f, 1.f, 1.f,
// back
-0.5f,-1.2f + 0.5f, 0.5f, 0.f, 0.f, 1.f, 0.f, 0.f,
-0.5f,-1.2f + -0.5f, 0.5f, 0.f, 0.f, 1.f, 0.f, 1.f,
0.5f, -1.2f + 0.5f, 0.5f, 0.f, 0.f, 1.f, 1.f, 0.f,
-0.5f,-1.2f + -0.5f, 0.5f, 0.f, 0.f, 1.f, 0.f, 1.f,
0.5f, -1.2f + -0.5f, 0.5f, 0.f, 0.f, 1.f, 1.f, 1.f,
0.5f, -1.2f + 0.5f, 0.5f, 0.f, 0.f, 1.f, 1.f, 0.f,
// left
-0.5f,-1.2f + -0.5f, 0.5f, -1.f, 0.f, 0.f, 1.f, 1.f,
-0.5f,-1.2f + 0.5f, -0.5f, -1.f, 0.f, 0.f, 0.f, 0.f,
-0.5f,-1.2f + -0.5f, -0.5f, -1.f, 0.f, 0.f, 0.f, 1.f,
-0.5f,-1.2f + 0.5f, -0.5f, -1.f, 0.f, 0.f, 0.f, 0.f,
-0.5f,-1.2f + -0.5f, 0.5f, -1.f, 0.f, 0.f, 1.f, 1.f,
-0.5f,-1.2f + 0.5f, 0.5f, -1.f, 0.f, 0.f, 1.f, 0.f,
// right
0.5f,-1.2f + -0.5f, -0.5f, 1.f, 0.f, 0.f, 1.f, 1.f,
0.5f,-1.2f + 0.5f, -0.5f, 1.f, 0.f, 0.f, 1.f, 0.f,
0.5f,-1.2f + 0.5f, 0.5f, 1.f, 0.f, 0.f, 0.f, 0.f,
0.5f,-1.2f + 0.5f, 0.5f, 1.f, 0.f, 0.f, 0.f, 0.f,
0.5f,-1.2f + -0.5f, 0.5f, 1.f, 0.f, 0.f, 0.f, 1.f,
0.5f,-1.2f + -0.5f, -0.5f, 1.f, 0.f, 0.f, 1.f, 1.f
};
unsigned short i[] =
{
0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23,
24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35
};
auto vertexBuffer = VertexBuffer::create(context, std::begin(xyzData), std::end(xyzData));
vertexBuffer->addAttribute("position", 3, 0);
vertexBuffer->addAttribute("normal", 3, 3);
vertexBuffer->addAttribute("uv", 2, 6);
addVertexBuffer(vertexBuffer);
indices(IndexBuffer::create(context, std::begin(i), std::end(i)));
}
| 47.147368 | 97 | 0.485823 | undeadinu |
a301d0bf6bf24f228b6516bb9883443158fc5dc7 | 4,897 | hpp | C++ | include/RED4ext/Map.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | 1 | 2021-02-01T23:07:50.000Z | 2021-02-01T23:07:50.000Z | include/RED4ext/Map.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | include/RED4ext/Map.hpp | Cyberpunk-Extended-Development-Team/RED4ext.SDK | 2dc828c761d87a1b4235ce9ca4fbdf9fb4312fae | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <cstdint>
#include <functional>
#include <RED4ext/Common.hpp>
#include <RED4ext/DynArray.hpp>
#include <RED4ext/REDfunc.hpp>
namespace RED4ext
{
struct IMemoryAllocator;
template<typename K, typename T, class Compare = std::less<K>>
struct Map
{
enum class Flags : int32_t
{
NotSorted = 1 << 0
};
Map(IMemoryAllocator* aAllocator = nullptr)
: Map(aAllocator, aAllocator)
{
}
Map(IMemoryAllocator* aKeyAllocator, IMemoryAllocator* aValueAllocator)
: keys(aKeyAllocator)
, values(aValueAllocator)
, flags(0)
{
}
void ForEach(std::function<void(const K&, T&)> aFunctor) const
{
uint32_t size = GetSize();
for (uint32_t i = 0; i != size; ++i)
{
aFunctor(keys[i], const_cast<T&>(values[i]));
}
}
uint32_t GetCapactiy() const
{
return keys.capacity;
}
uint32_t GetSize() const
{
return keys.size;
}
T* Get(const K& aKey)
{
const auto it = LowerBound(aKey);
if (it == keys.end() || *it != aKey)
return nullptr;
uint32_t index = static_cast<uint32_t>(it - keys.begin());
return &values[index];
}
std::pair<T*, bool> Insert(const K& aKey, const T& aValue)
{
return Emplace(std::forward<const K&>(aKey), std::forward<const T&>(aValue));
}
std::pair<T*, bool> Insert(const K& aKey, T&& aValue)
{
return Emplace(std::forward<const K&>(aKey), std::forward<T&&>(aValue));
}
std::pair<T*, bool> InsertOrAssign(const K& aKey, const T& aValue)
{
std::pair<T*, bool> pair = Emplace(std::forward<const K&>(aKey), std::forward<const T&>(aValue));
if (!pair.second)
{
*pair.first = aValue;
}
return pair;
}
std::pair<T*, bool> InsertOrAssign(const K& aKey, T&& aValue)
{
std::pair<T*, bool> pair = Emplace(std::forward<const K&>(aKey), std::forward<T&&>(aValue));
if (!pair.second)
{
*pair.first = std::move(aValue);
}
return pair;
}
template<class... TArgs>
std::pair<T*, bool> Emplace(const K& aKey, TArgs&&... aArgs)
{
const auto it = LowerBound(aKey);
uint32_t index = static_cast<uint32_t>(it - keys.begin());
if (it != keys.end() && *it == aKey)
{
// Do nothing if the map already contains this key.
return {&values[index], false};
}
keys.Emplace(&keys.entries[index], std::forward<const K&>(aKey));
values.Emplace(&values.entries[index], std::forward<TArgs>(aArgs)...);
return {&values[index], true};
}
bool Remove(const K& aKey)
{
const T* valuePtr = Get(aKey);
if (valuePtr == nullptr)
return false;
uint32_t index = static_cast<uint32_t>(valuePtr - values.begin());
return RemoveAt(index);
}
bool RemoveAt(uint32_t aIndex)
{
if (aIndex >= GetSize())
return false;
keys.RemoveAt(aIndex);
values.RemoveAt(aIndex);
return true;
}
void Sort()
{
// Need to somehow use std::sort...
// This is how the game does it:
uint32_t size = GetSize();
for (uint32_t i = 1; i < size; ++i)
{
K tmpKey = std::move(keys[i]);
T tmpValue = std::move(values[i]);
uint32_t currentIdx = i;
while (currentIdx != 0)
{
if (!Compare{}(tmpKey, keys[currentIdx - 1]))
break;
keys[currentIdx] = std::move(keys[currentIdx - 1]);
values[currentIdx] = std::move(values[currentIdx - 1]);
--currentIdx;
}
keys[currentIdx] = std::move(tmpKey);
values[currentIdx] = std::move(tmpValue);
}
flags &= ~(int32_t)Flags::NotSorted;
}
void Clear()
{
keys.Clear();
values.Clear();
}
void Reserve(uint32_t aCount)
{
keys.Reserve(aCount);
values.Reserve(aCount);
}
DynArray<K> keys; // 00
DynArray<T> values; // 10
int32_t flags; // 20
private:
const K* LowerBound(const K& aKey) const
{
if ((flags & (int32_t)Flags::NotSorted) == (int32_t)Flags::NotSorted)
{
const_cast<Map*>(this)->Sort();
}
return std::lower_bound(keys.begin(), keys.end(), aKey, Compare{});
}
};
RED4EXT_ASSERT_SIZE(RED4EXT_ASSERT_ESCAPE(Map<void*, void*>), 0x28);
RED4EXT_ASSERT_OFFSET(RED4EXT_ASSERT_ESCAPE(Map<void*, void*>), keys, 0);
RED4EXT_ASSERT_OFFSET(RED4EXT_ASSERT_ESCAPE(Map<void*, void*>), values, 0x10);
RED4EXT_ASSERT_OFFSET(RED4EXT_ASSERT_ESCAPE(Map<void*, void*>), flags, 0x20);
} // namespace RED4ext
| 25.638743 | 105 | 0.550541 | Cyberpunk-Extended-Development-Team |
a3023474f92dcc869cfa07d44bca6f0ade4ebe44 | 788 | hpp | C++ | inc/Game.hpp | fklemme/DungeonsAndDoenekes | ce57b3f445ba3cf3e6f82922abd08dd58894c33c | [
"MIT"
] | null | null | null | inc/Game.hpp | fklemme/DungeonsAndDoenekes | ce57b3f445ba3cf3e6f82922abd08dd58894c33c | [
"MIT"
] | null | null | null | inc/Game.hpp | fklemme/DungeonsAndDoenekes | ce57b3f445ba3cf3e6f82922abd08dd58894c33c | [
"MIT"
] | 1 | 2020-06-24T16:08:05.000Z | 2020-06-24T16:08:05.000Z | #pragma once
#include <SFML/Graphics/Font.hpp>
#include <SFML/Graphics/RenderWindow.hpp>
#include <memory>
#include <vector>
#include "Layers/Layer.hpp"
#include "Player.hpp"
class Game {
public:
Game();
~Game();
void run();
void push_layer(std::unique_ptr<Layer> layer);
template <typename LayerType, typename... Args>
void emplace_layer(Args&&... args) {
push_layer(std::make_unique<LayerType>(std::forward<Args>(args)...));
}
inline void update_layers() { m_layers_update = true; }
inline const sf::Font& font() const { return m_font; }
private:
sf::RenderWindow m_main_window;
sf::Font m_font;
std::vector<std::unique_ptr<Layer>> m_layers;
bool m_layers_update = false;
std::unique_ptr<Player> m_player;
}; | 21.888889 | 77 | 0.666244 | fklemme |
a30433d17263c1f965bdcde4b49b22ad926000df | 7,548 | cpp | C++ | source/core/common/PropertyTermInfo.cpp | izenecloud/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 77 | 2015-02-12T20:59:20.000Z | 2022-03-05T18:40:49.000Z | source/core/common/PropertyTermInfo.cpp | fytzzh/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 1 | 2017-04-28T08:55:47.000Z | 2017-07-10T10:10:53.000Z | source/core/common/PropertyTermInfo.cpp | fytzzh/sf1r-lite | 8de9aa83c38c9cd05a80b216579552e89609f136 | [
"Apache-2.0"
] | 33 | 2015-01-05T03:03:05.000Z | 2022-02-06T04:22:46.000Z | ///
/// @file PropertyExpr.h
/// @brief header file of PropertyExpr
/// @author Dohyun YUn
/// @date 2008-12-10
///
#include "PropertyTermInfo.h"
#include <glog/logging.h>
using namespace std;
namespace sf1r {
PropertyTermInfo::PropertyTermInfo(void) : isWildCardQuery_(false)
{
} // end - PropertyTermInfo()
PropertyTermInfo::~PropertyTermInfo(void)
{
} // end - ~PropertyTermInfo()
PropertyTermInfo& PropertyTermInfo::operator=(const PropertyTermInfo& other)
{
searchProperty_ = other.searchProperty_;
termIdPositionMap_ = other.termIdPositionMap_ ;
termIdFrequencyMap_ = other.termIdFrequencyMap_;
termIdKeywordMap_ = other.termIdKeywordMap_;
isWildCardQuery_ = other.isWildCardQuery_;
return *this;
}
void PropertyTermInfo::setSearchProperty(const string& searchProperty)
{
searchProperty_ = searchProperty;
}
const string& PropertyTermInfo::getSearchProperty(void) const
{
return searchProperty_;
}
void PropertyTermInfo::dealWithTerm(izenelib::util::UString& keyword, termid_t termId, unsigned int nPos)
{
id_uint_list_map_t::iterator termIdPositionPos;
ID_FREQ_MAP_T::iterator termIdFrequencyPos;
// insert keyword into termIdKeywordMap_
termIdKeywordMap_.insert( make_pair(termId , keyword) );
// insert position information of given term into position list.
termIdPositionPos = termIdPositionMap_.find( termId );
if( termIdPositionPos == termIdPositionMap_.end() ) // if it is not inserted yet.
{
std::string keywordString;
keyword.convertString( keywordString , izenelib::util::UString::UTF_8 );
// DLOG(INFO) << "[PropertyTermInfo] new term id is inserted" << endl
// << "(Term : " << keywordString << " , " << termId
// << ") (pos : " << nPos << ") (freq : 1)" << endl;
std::list<unsigned int> sequenceList;
sequenceList.push_back( nPos );
termIdPositionMap_.insert( std::make_pair( termId, sequenceList ) );
termIdFrequencyMap_.insert( std::make_pair( termId, (float)1 ) );
}
else // already exist
{
termIdPositionPos->second.push_back( nPos );
termIdFrequencyPos = termIdFrequencyMap_.find( termId );
if( termIdFrequencyPos != termIdFrequencyMap_.end() )
termIdFrequencyPos->second += (float)1;
else
{
DLOG(ERROR) << "[PropertyTermInfo] term id is not found in frequency map" << endl;
return;
}
// DLOG(INFO) << "[PropertyTermInfo] term id is exist" << endl
// << "(TermId : " << termId << ") (pos : " << nPos
// << ") (freq : " << termIdFrequencyPos->second<< ")" << endl;
}
} // end - dealWithTerm()
std::string PropertyTermInfo::toString(void) const
{
stringstream ss;
ss << "PropertyTermInfo" << endl;
ss << "----------------------------------" << endl;
ss << "Property : " << searchProperty_ << endl;
ss << "TermIdPositionmap : " << endl;;
for( id_uint_list_map_t::const_iterator iter = termIdPositionMap_.begin();
iter != termIdPositionMap_.end(); iter++)
{
ss << "(" << iter->first << " : ";
for( std::list<unsigned int>::const_iterator iter2 = iter->second.begin();
iter2 != iter->second.end(); iter2++)
ss << *iter2 << " ";
ss << endl;
} // end - for
ss << endl << "TermIdFrequency : " << endl;
for(ID_FREQ_MAP_T::const_iterator iter = termIdFrequencyMap_.begin();
iter != termIdFrequencyMap_.end(); iter++)
{
ss << "(" << iter->first << " , " << iter->second << ") ";
} // end - for
ss << endl << "----------------------------------" << endl;
return ss.str();
} // end - print()
void PropertyTermInfo::getPositionedTermIdList(std::vector<termid_t>& termIdList) const
{
// Copy termid-list<offset> map to termoffset-id map
std::map<unsigned int, termid_t> termPositionIdMap;
id_uint_list_map_t::const_iterator iter
= termIdPositionMap_.begin();
unsigned int maxOffset = 0;
for(; iter != termIdPositionMap_.end(); iter++)
{
std::list<unsigned int>::const_iterator offsetIter = iter->second.begin();
for(; offsetIter != iter->second.end(); offsetIter++)
{
unsigned int offset = *offsetIter;
std::pair<std::map<unsigned int, termid_t>::iterator , bool> ret
= termPositionIdMap.insert(make_pair(offset,iter->first) );
if ( !ret.second )
{
DLOG(ERROR) << "[PropertyTermInfo] Error Line : "<< __LINE__
<< " - position value is duplicated (pos : " << *offsetIter
<< ", termid : " << iter->first << ")" << endl;
return;
}
if( offset > maxOffset )
maxOffset = offset;
} // end - end of the list
} // end - for end of the termid
// Copy termoffset-id map to termIdList.
termIdList.clear();
for(unsigned int offset=0; offset<=maxOffset; ++offset )
{
std::map<unsigned int, termid_t>::iterator utidItr = termPositionIdMap.find( offset );
if( utidItr != termPositionIdMap.end() )
termIdList.push_back( utidItr->second );
} // end - for
} // end - getPositionedTermIdList()
void PropertyTermInfo::getPositionedTermStringList(std::vector<izenelib::util::UString>& termStringList) const
{
std::vector<termid_t> termIdList;
this->getPositionedTermIdList( termIdList );
termStringList.clear();
std::vector<termid_t>::const_iterator iter=termIdList.begin();
for(; iter != termIdList.end(); iter++)
{
std::map<termid_t, izenelib::util::UString>::const_iterator termStringIter = termIdKeywordMap_.find( *iter );
if ( termStringIter == termIdKeywordMap_.end() )
{
DLOG(ERROR) << "[PropertyTermInfo] Error Line(" << __LINE__ << ") : cannot found term id." << endl;
return;
}
termStringList.push_back( termStringIter->second );
}
} // end - getPositionedTermStringList()
void PropertyTermInfo::getPositionedFullTermString(izenelib::util::UString& termString) const
{
termString.clear();
std::vector<izenelib::util::UString> termStringList;
this->getPositionedTermStringList( termStringList );
izenelib::util::UString SPACE_UCHAR(" ", izenelib::util::UString::UTF_8);
std::vector<izenelib::util::UString>::iterator iter = termStringList.begin();
for(; iter != termStringList.end(); iter++)
{
termString += *iter;
if ( iter + 1 != termStringList.end() )
termString += SPACE_UCHAR;
}
} // end - getPositionedFullTermString()
void PropertyTermInfo::clear(void)
{
searchProperty_.clear();
termIdPositionMap_.clear();
termIdFrequencyMap_.clear();
isWildCardQuery_ = false;
}
} // namespace sf1r
| 36.288462 | 121 | 0.564918 | izenecloud |
a30496fde2ace9a9a4e85b8e631f083e94e6ed2a | 1,929 | inl | C++ | source/Locks_Win32.inl | CodeChex/ConcurrentLock | 42d8e140c4352c425cf59a7e73493edc7d74d9d4 | [
"MIT"
] | null | null | null | source/Locks_Win32.inl | CodeChex/ConcurrentLock | 42d8e140c4352c425cf59a7e73493edc7d74d9d4 | [
"MIT"
] | null | null | null | source/Locks_Win32.inl | CodeChex/ConcurrentLock | 42d8e140c4352c425cf59a7e73493edc7d74d9d4 | [
"MIT"
] | null | null | null | #pragma once
#ifdef IMPL_USING_MFC
typedef class CSyncObject cclSyncObject;
typedef class CSingleLock cclSingleLock;
typedef class CMutex cclMutex;
typedef class CCriticalSection cclCriticalSection;
typedef class CEvent cclEvent;
#else
class _CCL_API cclMutex : public cclSyncObject
{
public:
cclMutex() : cclSyncObject()
{
m_mtx = ::CreateMutex(NULL,FALSE,NULL);
};
virtual ~cclMutex()
{
Unlock();
if ( m_mtx ) ::CloseHandle(m_mtx);
m_mtx = NULL;
};
protected:
virtual BOOL Lock(DWORD dwTimeout=INFINITE)
{
return ( ::WaitForSingleObjectEx(m_mtx,dwTimeout,TRUE) == WAIT_OBJECT_0 );
}
virtual BOOL Unlock()
{
return ::ReleaseMutex(m_mtx);
}
protected:
HANDLE m_mtx;
};
class _CCL_API cclCriticalSection : public cclSyncObject
{
public:
cclCriticalSection() : cclSyncObject()
{
memset(&m_critsec,0,sizeof(m_critsec));
::InitializeCriticalSection(&m_critsec);
};
virtual ~cclCriticalSection()
{
Unlock();
::DeleteCriticalSection(&m_critsec);
memset(&m_critsec,0,sizeof(m_critsec));
};
protected:
virtual BOOL Lock(DWORD dwTimeout=INFINITE)
{
::EnterCriticalSection(&m_critsec);
return TRUE;
};
virtual BOOL Unlock()
{
::LeaveCriticalSection(&m_critsec);
return TRUE;
}
protected:
CRITICAL_SECTION m_critsec;
};
class _CCL_API cclEvent
{
public:
cclEvent()
{
m_evt = ::CreateEvent(NULL,FALSE,FALSE,NULL);
};
virtual ~cclEvent()
{
PulseEvent();
if ( m_evt ) ::CloseHandle(m_evt);
};
BOOL SetEvent()
{
return ::SetEvent(m_evt);
};
BOOL ResetEvent()
{
return ::ResetEvent(m_evt);
};
BOOL PulseEvent()
{
return ::PulseEvent(m_evt);
};
DWORD Wait(DWORD dwTimeout=INFINITE)
{
//ResetEvent();
return ( ::WaitForSingleObjectEx(m_evt,dwTimeout,TRUE) == WAIT_OBJECT_0 );
};
protected:
HANDLE m_evt;
};
#endif // _AFXDLL | 17.536364 | 77 | 0.66563 | CodeChex |
a3053f70ec5b4b24801fc1b36e908bf2462bde63 | 811 | cpp | C++ | src/network/scope_runner.cpp | Andrei-Masilevich/barbacoa-server-lib | 2eda2fab20c6c1d5a8a78b71952ca61330d04878 | [
"MIT"
] | null | null | null | src/network/scope_runner.cpp | Andrei-Masilevich/barbacoa-server-lib | 2eda2fab20c6c1d5a8a78b71952ca61330d04878 | [
"MIT"
] | null | null | null | src/network/scope_runner.cpp | Andrei-Masilevich/barbacoa-server-lib | 2eda2fab20c6c1d5a8a78b71952ca61330d04878 | [
"MIT"
] | null | null | null | #include <server_lib/network/scope_runner.h>
#include <server_lib/asserts.h>
namespace server_lib {
namespace network {
std::unique_ptr<scope_runner::shared_lock> scope_runner::continue_lock()
{
long expected = count;
while (expected >= 0 && !count.compare_exchange_weak(expected, expected + 1))
spin_loop_pause();
if (expected < 0)
return nullptr;
else
return std::unique_ptr<shared_lock>(new shared_lock(count));
}
void scope_runner::stop()
{
long expected = 0;
while (!count.compare_exchange_weak(expected, -1))
{
if (expected < 0)
return;
expected = 0;
spin_loop_pause();
}
}
} // namespace network
} // namespace server_lib
| 23.852941 | 85 | 0.583231 | Andrei-Masilevich |
a305587ca91f04c9498f5b84ebcb7c3d9b74a335 | 698 | cpp | C++ | libcxx/test/std/containers/sequences/list/list.cons/assign_move.addressof.compile.pass.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 605 | 2019-10-18T01:15:54.000Z | 2022-03-31T14:31:04.000Z | libcxx/test/std/containers/sequences/list/list.cons/assign_move.addressof.compile.pass.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 3,180 | 2019-10-18T01:21:21.000Z | 2022-03-31T23:25:41.000Z | libcxx/test/std/containers/sequences/list/list.cons/assign_move.addressof.compile.pass.cpp | LaudateCorpus1/llvm-project | ff2e0f0c1112558b3f30d8afec7c9882c33c79e3 | [
"Apache-2.0"
] | 275 | 2019-10-18T05:27:22.000Z | 2022-03-30T09:04:21.000Z | //===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++03
// <list>
// list& operator=(list&& c);
// Validate whether the operation properly guards against ADL-hijacking operator&
#include <list>
#include "test_macros.h"
#include "operator_hijacker.h"
void test() {
std::list<operator_hijacker> lo;
std::list<operator_hijacker> l;
l = std::move(lo);
}
| 25.851852 | 81 | 0.545845 | LaudateCorpus1 |
a306029088ea13bc75f5ea6a091d0a886c784f89 | 8,586 | inl | C++ | include/util/Quaternion.inl | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 227 | 2018-09-17T16:03:35.000Z | 2022-03-19T02:02:45.000Z | include/util/Quaternion.inl | DragonJoker/RendererLib | 0f8ad8edec1b0929ebd10247d3dd0a9ee8f8c91a | [
"MIT"
] | 39 | 2018-02-06T22:22:24.000Z | 2018-08-29T07:11:06.000Z | include/util/Quaternion.inl | DragonJoker/Ashes | a6ed950b3fd8fb9626c60b4291fbd52ea75ac66e | [
"MIT"
] | 8 | 2019-05-04T10:33:32.000Z | 2021-04-05T13:19:27.000Z | /*
This file belongs to Ashes.
See LICENSE file in root folder
*/
#include <math.h>
#include "util/Vectorisation.hpp"
namespace utils
{
template< typename T >
QuaternionT< T >::QuaternionT( NoInit const & )noexcept
{
}
template< typename T >
constexpr QuaternionT< T >::QuaternionT()noexcept
: x{}
, y{}
, z{}
, w{ T{ 1 } }
{
}
template< typename T >
template< typename W
, typename X
, typename Y
, typename Z >
constexpr QuaternionT< T >::QuaternionT( W const & w
, X const & x
, Y const & y
, Z const & z )noexcept
: x{ T( x ) }
, y{ T( y ) }
, z{ T( z ) }
, w{ T( w ) }
{
}
template< typename T >
QuaternionT< T >::QuaternionT( Vec3T< T > const & u, Vec3T< T > const & v )noexcept
{
Vec3T< T > const localW( cross( u, v ) );
T dot = dot( u, v );
QuaternionT< T > q( T{ 1 } + dot, localW.x, localW.y, localW.z );
*this = normalize( q );
}
template< typename T >
QuaternionT< T >::QuaternionT( Vec3T< RadiansT< T > > const & euler )noexcept
{
Vec3T< T > c{ vectorCall( utils::cos< T >, euler * T{ 0.5 } ) };
Vec3T< T > s{ vectorCall( utils::sin< T >, euler * T{ 0.5 } ) };
w = c.x * c.y * c.z + s.x * s.y * s.z;
x = s.x * c.y * c.z - c.x * s.y * s.z;
y = c.x * s.y * c.z + s.x * c.y * s.z;
z = c.x * c.y * s.z - s.x * s.y * c.z;
}
template< typename T >
template< typename U >
QuaternionT< T >::QuaternionT( QuaternionT< U > const & rhs )noexcept
: x{ T( rhs.x ) }
, y{ T( rhs.y ) }
, z{ T( rhs.z ) }
, w{ T( rhs.w ) }
{
}
template< typename T >
template< typename U >
QuaternionT< T > & QuaternionT< T >::operator=( QuaternionT< U > const & rhs )noexcept
{
x = T( rhs.x );
y = T( rhs.y );
z = T( rhs.z );
w = T( rhs.w );
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator+=( QuaternionT< U > const & rhs )noexcept
{
x = T( x + rhs.x );
y = T( y + rhs.y );
z = T( z + rhs.z );
w = T( w + rhs.w );
return *this;
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator-=( QuaternionT< U > const & rhs )noexcept
{
x = T( x - rhs.x );
y = T( y - rhs.y );
z = T( z - rhs.z );
w = T( w - rhs.w );
return *this;
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator*=( QuaternionT< U > const & rhs )noexcept
{
QuaternionT< T > const p{ *this };
w = p.w * rhs.w - p.x * rhs.x - p.y * rhs.y - p.z * rhs.z;
x = p.w * rhs.x + p.x * rhs.w + p.y * rhs.z - p.z * rhs.y;
y = p.w * rhs.y + p.y * rhs.w + p.z * rhs.x - p.x * rhs.z;
z = p.w * rhs.z + p.z * rhs.w + p.x * rhs.y - p.y * rhs.x;
return *this;
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator*=( U const & rhs )noexcept
{
x = T( x * rhs );
y = T( y * rhs );
z = T( z * rhs );
w = T( w * rhs );
return *this;
}
template< typename T >
template< typename U >
inline QuaternionT< T > & QuaternionT< T >::operator/=( U const & rhs )noexcept
{
x = T( x / rhs );
y = T( y / rhs );
z = T( z / rhs );
w = T( w / rhs );
return *this;
}
template< typename T >
T dot( QuaternionT< T > const & lhs, QuaternionT< T > const & rhs )noexcept
{
return sqrt( lhs.x * rhs.x
+ lhs.y * rhs.y
+ lhs.z * rhs.z
+ lhs.w * rhs.w );
}
template< typename T >
QuaternionT< T > cross( QuaternionT< T > const & lhs, QuaternionT< T > const & rhs )noexcept
{
return QuaternionT< T >
{
lhs.w * rhs.w - lhs.x * rhs.x - lhs.y * rhs.y - lhs.z * rhs.z,
lhs.w * rhs.x + lhs.x * rhs.w + lhs.y * rhs.z - lhs.z * rhs.y,
lhs.w * rhs.y + lhs.y * rhs.w + lhs.z * rhs.x - lhs.x * rhs.z,
lhs.w * rhs.z + lhs.z * rhs.w + lhs.x * rhs.y - lhs.y * rhs.x
};
}
template< typename T >
T length( QuaternionT< T > const & quat )noexcept
{
return dot( quat, quat );
}
template< typename T >
T distance( QuaternionT< T > const & lhs, QuaternionT< T > const & rhs )noexcept
{
return length( rhs - lhs );
}
template< typename T >
QuaternionT< T > normalize( QuaternionT< T > const & vec )noexcept
{
auto norm = length( vec );
return QuaternionT< T >
{
vec.x / norm,
vec.y / norm,
vec.z / norm,
vec.w / norm
};
}
template <typename T >
QuaternionT< T > conjugate( QuaternionT< T > const & q )noexcept
{
return QuaternionT< T >( q.w, -q.x, -q.y, -q.z );
}
template <typename T >
QuaternionT< T > inverse( QuaternionT< T > const & q )noexcept
{
return conjugate( q ) / dot( q, q );
}
template< typename T, typename U >
Vec3T< T > rotate( QuaternionT< T > const & q, Vec3T< U > const & v )noexcept
{
return q * v;
}
template< typename T, typename U >
Vec4T< T > rotate( QuaternionT< T > const & q, Vec4T< U > const & v )noexcept
{
return q * v;
}
template< typename T >
QuaternionT< T > rotate( QuaternionT< T > const & q,
RadiansT < T > const & angle,
Vec3T< T > const & axis )noexcept
{
assert( std::abs( length( axis ) - T( 1 ) ) <= T( 0.001 ) );
T const sinA = sin( angle * T( 0.5 ) );
return q * QuaternionT< T >{ cos( angle * T( 0.5 ) )
, axis.x * sinA
, axis.y * sinA
, axis.z * sinA };
}
template< typename T >
QuaternionT< T > pitch( QuaternionT< T > const & q,
RadiansT < T > const & angle )noexcept
{
return rotate( q, angle, Vec3T< T >{ T{ 1 }, T{}, T{} } );
}
template< typename T >
QuaternionT< T > yaw( QuaternionT< T > const & q,
RadiansT < T > const & angle )noexcept
{
return rotate( q, angle, Vec3T< T >{ T{}, T{ 1 }, T{} } );
}
template< typename T >
QuaternionT< T > roll( QuaternionT< T > const & q,
RadiansT < T > const & angle )noexcept
{
return rotate( q, angle, Vec3T< T >{ T{}, T{}, T{ 1 } } );
}
template< typename T >
Mat4T< T > toMat4( QuaternionT< T > const & q )noexcept
{
Mat4T< T > result{ T{ 1 } };
T qxx{ q.x * q.x };
T qyy{ q.y * q.y };
T qzz{ q.z * q.z };
T qxz{ q.x * q.z };
T qxy{ q.x * q.y };
T qyz{ q.y * q.z };
T qwx{ q.w * q.x };
T qwy{ q.w * q.y };
T qwz{ q.w * q.z };
result[0][0] = T{ 1 } - T{ 2 } * ( qyy + qzz );
result[0][1] = T{ 2 } * ( qxy + qwz );
result[0][2] = T{ 2 } * ( qxz - qwy );
result[1][0] = T{ 2 } * ( qxy - qwz );
result[1][1] = T{ 1 } - T{ 2 } * ( qxx + qzz );
result[1][2] = T{ 2 } * ( qyz + qwx );
result[2][0] = T{ 2 } * ( qxz + qwy );
result[2][1] = T{ 2 } * ( qyz - qwx );
result[2][2] = T{ 1 } - T{ 2 } * ( qxx + qyy );
return result;
}
template< typename T >
inline bool operator==( QuaternionT< T > const & lhs
, QuaternionT< T > const & rhs )noexcept
{
return lhs.x == rhs.x
&& lhs.y == rhs.y
&& lhs.z == rhs.z
&& lhs.w == rhs.w;
}
template< typename T >
inline bool operator!=( QuaternionT< T > const & lhs
, QuaternionT< T > const & rhs )noexcept
{
return lhs.x != rhs.x
|| lhs.y != rhs.y
|| lhs.z != rhs.z
|| lhs.w != rhs.w;
}
template< typename T, typename U >
inline QuaternionT< T > operator+( QuaternionT< T > const & lhs
, QuaternionT< U > const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result += rhs;
return result;
}
template< typename T, typename U >
inline QuaternionT< T > operator-( QuaternionT< T > const & lhs
, QuaternionT< U > const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result -= rhs;
return result;
}
template< typename T, typename U >
inline QuaternionT< T > operator*( QuaternionT< T > const & lhs
, QuaternionT< U > const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result *= rhs;
return result;
}
template< typename T, typename U >
inline QuaternionT< T > operator*( QuaternionT< T > const & lhs
, U const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result *= rhs;
return result;
}
template< typename T, typename U >
inline QuaternionT< T > operator/( QuaternionT< T > const & lhs
, U const & rhs )noexcept
{
QuaternionT< T > result{ lhs };
result /= rhs;
return result;
}
template< typename T, typename U >
inline Vec3T< T > operator*( QuaternionT< T > const & lhs
, Vec3T< U > const & rhs )noexcept
{
Vec3T< T > const quatVector{ lhs.x, lhs.y, lhs.z };
Vec3T< T > const uv{ cross( quatVector, rhs ) };
Vec3T< T > const uuv{ cross( quatVector, uv ) };
return rhs + ( ( uv * lhs.w ) + uuv ) * static_cast< T >( 2 );
}
template< typename T, typename U >
inline Vec4T< T > operator*( QuaternionT< T > const & lhs
, Vec4T< U > const & rhs )noexcept
{
return Vec4T< T >
{
lhs.x * rhs.x,
lhs.y * rhs.y,
lhs.z * rhs.z,
lhs.w * rhs.w
};
}
}
| 23.718232 | 95 | 0.555439 | DragonJoker |
a30829060bc8c519ef8adb29efe198508ef8b566 | 993 | hh | C++ | include/ATLHECTBPrimaryGeneratorAction.hh | lopezzot/ATLHECTB | 1d45179e70aaa6b7dd6eb08c3d13063f440cfc9f | [
"MIT"
] | 5 | 2021-05-20T15:54:33.000Z | 2022-03-14T14:08:42.000Z | include/ATLHECTBPrimaryGeneratorAction.hh | lopezzot/ATLHECTB | 1d45179e70aaa6b7dd6eb08c3d13063f440cfc9f | [
"MIT"
] | 8 | 2021-09-14T15:06:04.000Z | 2021-10-17T15:35:03.000Z | include/ATLHECTBPrimaryGeneratorAction.hh | lopezzot/ATLHECTB | 1d45179e70aaa6b7dd6eb08c3d13063f440cfc9f | [
"MIT"
] | null | null | null | //**************************************************
// \file ATLHECTBPrimaryGeneratorAction.hh
// \brief: Definition of ATLHECTBPrimaryGeneratorAction class
// \author: Lorenzo Pezzotti (CERN EP-SFT-sim) @lopezzot
// \start date: 11 May 2021
//**************************************************
//Prevent including header multiple times
//
#ifndef ATLHECTBPrimaryGeneratorAction_h
#define ATLHECTBPrimaryGeneratorAction_h 1
//Includers from Geant4
//
#include "G4VUserPrimaryGeneratorAction.hh"
#include "globals.hh"
class G4ParticleGun;
class G4Event;
class ATLHECTBPrimaryGeneratorAction : public G4VUserPrimaryGeneratorAction {
public:
ATLHECTBPrimaryGeneratorAction();
virtual ~ATLHECTBPrimaryGeneratorAction();
virtual void GeneratePrimaries( G4Event* event );
void SetRandomFlag( G4bool value ); //to check what this does
private:
G4ParticleGun* fParticleGun;
};
#endif
//**************************************************
| 25.461538 | 77 | 0.633434 | lopezzot |
a30b8628cb77e07b0bf402769735aa28a0e2f30d | 2,609 | cpp | C++ | code/ch_3-CREATIONAL_PATTERNS/00-project_skeleton/main.cpp | ordinary-developer/book_design_patterns_4_d_e_gamma_r_helm_r_johnson_j_vlissides | 69b80ee82446e15e9f76547a3fe5cb71e8e0e147 | [
"MIT"
] | null | null | null | code/ch_3-CREATIONAL_PATTERNS/00-project_skeleton/main.cpp | ordinary-developer/book_design_patterns_4_d_e_gamma_r_helm_r_johnson_j_vlissides | 69b80ee82446e15e9f76547a3fe5cb71e8e0e147 | [
"MIT"
] | null | null | null | code/ch_3-CREATIONAL_PATTERNS/00-project_skeleton/main.cpp | ordinary-developer/book_design_patterns_4_d_e_gamma_r_helm_r_johnson_j_vlissides | 69b80ee82446e15e9f76547a3fe5cb71e8e0e147 | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
enum Direction { North, South, East, West };
class MapSite {
public:
virtual void Enter() = 0;
};
class Room : public MapSite {
public:
Room(unsigned int number) : _number(number) { }
MapSite* GetSide(Direction direction) const {
return _sides[direction];
}
void SetSide(Direction direction, MapSite* mapSite) {
_sides[direction] = mapSite;
}
virtual void Enter() { }
unsigned int GetNumber() const { return _number; }
void SetNumber(unsigned int value) { _number = value; }
private:
MapSite* _sides[4];
unsigned int _number;
};
class Spell { };
class EnchantedRoom : public Room {
public:
EnchantedRoom(unsigned int number, Spell *spell)
: Room(number), _spell(spell) { }
private:
Spell* _spell;
};
class RoomWithABomb : public Room {
public:
RoomWithABomb(unsigned int number)
: Room(number) { }
};
class Wall : public MapSite {
public:
Wall() { }
virtual void Enter() { }
};
class BombedWall : public Wall { };
class Door : public MapSite {
public:
Door(Room* room1 = 0, Room* room2 = 0)
: _room1(room1), _room2(room2) { }
virtual void Enter() { }
private:
Room* _room1;
Room* _room2;
bool _isOpen;
};
class DoorNeedingSpell : public Door {
public:
DoorNeedingSpell(Room* room1, Room* room2)
: Door(room1, room2) { }
};
class Maze {
public:
Maze() { }
void AddRoom(Room* room) {
_rooms[room->GetNumber()] = room;
}
Room* GetRoomByNumber(unsigned int number) {
return _rooms[number];
}
private:
std::unordered_map<unsigned int, Room*> _rooms;
};
class MazeGame {
public:
Maze* CreateMaze() {
Maze* maze = new Maze();
Room* room1 = new Room(1);
Room* room2 = new Room(2);
Door* door = new Door(room1, room2);
room1->SetSide(North, new Wall());
room1->SetSide(East, door);
room1->SetSide(South, new Wall());
room1->SetSide(West, new Wall());
room2->SetSide(North, new Wall());
room2->SetSide(East, new Wall());
room2->SetSide(South, new Wall());
room2->SetSide(West, door);
return maze;
}
};
int main() {
MazeGame game;
game.CreateMaze();
return 0;
}
| 19.470149 | 63 | 0.536987 | ordinary-developer |
a3134f0ddf77dd8ab6ea8aab99f7033f4c6e4618 | 1,209 | cpp | C++ | source/mango/filesystem/path.cpp | aniketanvit/mango | 659a6836354ae881c6860f5b961d65ac1f1e85c6 | [
"Zlib"
] | 1 | 2021-08-06T09:27:45.000Z | 2021-08-06T09:27:45.000Z | source/mango/filesystem/path.cpp | galek/mango | 975b438ac9a22ed3a849da6187e1fdf3d547c926 | [
"Zlib"
] | null | null | null | source/mango/filesystem/path.cpp | galek/mango | 975b438ac9a22ed3a849da6187e1fdf3d547c926 | [
"Zlib"
] | 1 | 2021-07-10T11:41:01.000Z | 2021-07-10T11:41:01.000Z | /*
MANGO Multimedia Development Platform
Copyright (C) 2012-2016 Twilight Finland 3D Oy Ltd. All rights reserved.
*/
#include <algorithm>
#include <mango/filesystem/path.hpp>
namespace mango
{
// -----------------------------------------------------------------
// Path
// -----------------------------------------------------------------
Path::Path(const std::string& pathname, const std::string& password)
{
// create mapper to raw filesystem
m_mapper = getFileMapper();
// parse and create mappers
m_pathname = parse(pathname, password);
m_mapper->index(m_files, m_pathname);
}
Path::Path(const Path& path, const std::string& pathname, const std::string& password)
{
// use parent's mapper
m_mapper = path.m_mapper;
// parse and create mappers
m_pathname = parse(path.m_pathname + pathname, password);
m_mapper->index(m_files, m_pathname);
}
Path::~Path()
{
}
void Path::updateIndex()
{
m_files.clear();
m_mapper->index(m_files, m_pathname);
}
const std::string& Path::pathname() const
{
return m_pathname;
}
} // namespace mango
| 23.705882 | 90 | 0.548387 | aniketanvit |
a314039585b82df9ad2ef923cf0f75ed7b4d8ec3 | 329 | hh | C++ | Resources/Sources/Includes/Timer/Timer.hh | hunyadix/dcolscan_tools | df5fb7a01d43dec358f24808b9bbf1c7baf75c7d | [
"MIT"
] | null | null | null | Resources/Sources/Includes/Timer/Timer.hh | hunyadix/dcolscan_tools | df5fb7a01d43dec358f24808b9bbf1c7baf75c7d | [
"MIT"
] | null | null | null | Resources/Sources/Includes/Timer/Timer.hh | hunyadix/dcolscan_tools | df5fb7a01d43dec358f24808b9bbf1c7baf75c7d | [
"MIT"
] | null | null | null | #ifndef TIMER_H
#define TIMER_H
#include <string>
#include <iostream>
class Timer
{
protected:
time_t start_t;
time_t current_t;
double seconds_elapsed;
public:
Timer();
~Timer();
virtual void restart(std::string text_p);
virtual void print_seconds(std::string pretext_p, std::string post_text_p);
};
#endif
| 15.666667 | 77 | 0.723404 | hunyadix |
a314f906e51cbfbcb7d7bb92ba8c975db7a82c02 | 7,687 | cpp | C++ | src/sim/displays/testmfd.cpp | Terebinth/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 117 | 2015-01-13T14:48:49.000Z | 2022-03-16T01:38:19.000Z | src/sim/displays/testmfd.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 4 | 2015-05-01T13:09:53.000Z | 2017-07-22T09:11:06.000Z | src/sim/displays/testmfd.cpp | darongE/freefalcon-central | c28d807183ab447ef6a801068aa3769527d55deb | [
"BSD-2-Clause"
] | 78 | 2015-01-13T09:27:47.000Z | 2022-03-18T14:39:09.000Z | #include "stdhdr.h"
#include "camplib.h"
#include "mfd.h"
#include "Graphics/Include/render2d.h"
#include "dispcfg.h"
#include "simdrive.h"
#include "camp2sim.h"
#include "hud.h"
#include "aircrft.h"
#include "fack.h"
#include "otwdrive.h" //MI
#include "cpmanager.h" //MI
#include "icp.h" //MI
#include "aircrft.h" //MI
#include "fcc.h" //MI
#include "radardoppler.h" //MI
//MI
void DrawBullseyeCircle(VirtualDisplay* display, float cursorX, float cursorY);
struct MfdTestButtons
{
char *label1, *label2;
enum { ModeNoop = 0, // do nothing
ModeParent, // hand off to parent
ModeTest1,
ModeTest2, // two test sub modes
ModeRaltTest,
ModeRunTest,
ModeClear,
};
int nextMode;
};
#define NOENTRY { NULL, NULL, MfdTestButtons::ModeNoop}
#define PARENT { NULL, NULL, MfdTestButtons::ModeParent}
static const MfdTestButtons testpage1[20] =
{
// test page menu
{"BIT1", NULL, MfdTestButtons::ModeTest2}, // 1
NOENTRY,
{"CLR", NULL, MfdTestButtons::ModeClear},
NOENTRY,
NOENTRY, // 5
{"MFDS", NULL, MfdTestButtons::ModeRunTest},
{"RALT", "500", MfdTestButtons::ModeRaltTest},
{"TGP", NULL, MfdTestButtons::ModeRunTest},
{"FINS", NULL, MfdTestButtons::ModeRunTest},
{"TFR", NULL, MfdTestButtons::ModeRunTest}, // 10
PARENT,
PARENT,
PARENT,
PARENT, // current mode
PARENT, // 15
{"RSU", NULL, MfdTestButtons::ModeRunTest},
{"INS", NULL, MfdTestButtons::ModeRunTest},
{"SMS", NULL, MfdTestButtons::ModeNoop},
{"FCR", NULL, MfdTestButtons::ModeRunTest},
{"DTE", NULL, MfdTestButtons::ModeRunTest}, // 20
};
static const MfdTestButtons testpage2[20] =
{
// test page menu
{"BIT2", NULL, MfdTestButtons::ModeTest1}, // 1
NOENTRY,
{"CLR", NULL, MfdTestButtons::ModeClear},
NOENTRY,
NOENTRY, // 5
{"IFF1", NULL, MfdTestButtons::ModeRunTest},
{"IFF2", NULL, MfdTestButtons::ModeRunTest},
{"IFF3", NULL, MfdTestButtons::ModeRunTest},
{"IFFC", NULL, MfdTestButtons::ModeRunTest},
{"TCN", NULL, MfdTestButtons::ModeRunTest}, // 10
PARENT,
PARENT,
PARENT,
PARENT,
PARENT, // 15
{NULL, NULL, MfdTestButtons::ModeNoop},
{NULL, NULL, MfdTestButtons::ModeNoop},
{NULL, NULL, MfdTestButtons::ModeNoop},
{"TISL", NULL, MfdTestButtons::ModeRunTest},
{"UFC", NULL, MfdTestButtons::ModeRunTest}, // 20
};
struct MfdTestPage
{
const MfdTestButtons *buttons;
};
static const MfdTestPage mfdpages[] =
{
{testpage1},
{testpage2},
};
static const int NMFDPAGES = sizeof(mfdpages) / sizeof(mfdpages[0]);
TestMfdDrawable::TestMfdDrawable()
{
bitpage = 0;
bittest = -1;
timer = 0;
}
void TestMfdDrawable::Display(VirtualDisplay* newDisplay)
{
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
//MI
float cX, cY = 0;
if (g_bRealisticAvionics)
{
RadarDopplerClass* theRadar = (RadarDopplerClass*)FindSensor(playerAC, SensorClass::Radar);
if ( not theRadar)
{
ShiWarning("Oh Oh shouldn't be here without a radar");
return;
}
else
{
theRadar->GetCursorPosition(&cX, &cY);
}
}
display = newDisplay;
ShiAssert(bitpage >= 0 and bitpage < sizeof(mfdpages) / sizeof(mfdpages[0]));
ShiAssert(display not_eq NULL);
const MfdTestButtons *mb = mfdpages[bitpage].buttons;
AircraftClass *self = MfdDisplay[OnMFD()]->GetOwnShip();
ShiAssert(self not_eq NULL);
//MI changed
if (g_bRealisticAvionics)
{
if (OTWDriver.pCockpitManager and OTWDriver.pCockpitManager->mpIcp and
OTWDriver.pCockpitManager->mpIcp->ShowBullseyeInfo)
{
DrawBullseyeCircle(display, cX, cY);
}
else
DrawReference(self);
}
else
DrawReference(self);
display->SetColor(GetMfdColor(MFD_LABELS));
char buf[100];
for (int i = 0; i < 20; i++)
{
int hilite = 0;
if (i == bittest and timer > SimLibElapsedTime)
hilite = 1;
switch (mb[i].nextMode)
{
case MfdTestButtons::ModeRaltTest:
sprintf(buf, "%.0f", hilite ? 300.0f : TheHud->lowAltWarning);
LabelButton(i, mb[i].label1, buf, hilite);
break;
default:
if (mb[i].label1)
LabelButton(i, mb[i].label1, mb[i].label2, hilite);
else if (mb[i].nextMode == MfdTestButtons::ModeParent)
MfdDrawable::DefaultLabel(i);
}
}
if (playerAC and playerAC->mFaults)
{
FackClass *fack = playerAC->mFaults;
float yinc = display->TextHeight();
const static float namex = -0.6f;
const static float starty = 0.6f;
float y = starty;
float x = namex;
float xinc = 0.3F;
for (int i = 0; i < fack->GetMflListCount(); i++)
{
const char *fname;
int subsys;
int count;
char timestr[100];
if (fack->GetMflEntry(i, &fname, &subsys, &count, timestr) == false)
continue;
char outstr[100];
for (int i = 0; i < 5; i++)
{
switch (i)
{
case 1:
sprintf(outstr, "%-4s", fname);
display->TextLeft(x, y, outstr);
x += xinc;
break;
case 2:
sprintf(outstr, "%03d", subsys);
display->TextLeft(x, y, outstr);
x += xinc;
break;
case 3:
x -= 0.1F;
sprintf(outstr, "%2d", count);
display->TextLeft(x, y, outstr);
x += xinc;
break;
case 4:
x -= 0.1F;
sprintf(outstr, "%s", timestr);
display->TextLeft(x, y, outstr);
x += xinc;
break;
default:
break;
}
}
//sprintf (outstr, "%-4s %03d %2d %s", fname, subsys, count, timestr);
//ShiAssert(strlen(outstr) < sizeof outstr);
//display->TextLeft(namex, y, outstr);
y -= yinc;
x = namex;
}
}
}
void TestMfdDrawable::PushButton(int whichButton, int whichMFD)
{
ShiAssert(bitpage >= 0 and bitpage < sizeof(mfdpages) / sizeof(mfdpages[0]));
ShiAssert(whichButton >= 0 and whichButton < 20);
AircraftClass *playerAC = SimDriver.GetPlayerAircraft();
switch (mfdpages[bitpage].buttons[whichButton].nextMode)
{
case MfdTestButtons::ModeNoop:
break;
case MfdTestButtons::ModeRaltTest:
case MfdTestButtons::ModeRunTest:
bittest = whichButton;
timer = SimLibElapsedTime + 5 * CampaignSeconds;
break;
case MfdTestButtons::ModeTest2:
bitpage = 1;
break;
case MfdTestButtons::ModeTest1:
bitpage = 0;
break;
case MfdTestButtons::ModeParent:
MfdDrawable::PushButton(whichButton, whichMFD);
break;
case MfdTestButtons::ModeClear: // clear MFL
if (playerAC and playerAC->mFaults)
playerAC->mFaults->ClearMfl();
break;
}
}
| 27.651079 | 99 | 0.540263 | Terebinth |
a315330d149eb40f0f5fb7f4446f6495d8738149 | 32,773 | cpp | C++ | lammps-master/src/fix_box_relax.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/fix_box_relax.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | lammps-master/src/fix_box_relax.cpp | rajkubp020/helloword | 4bd22691de24b30a0f5b73821c35a7ac0666b034 | [
"MIT"
] | null | null | null | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
/* ----------------------------------------------------------------------
Contributing author: Aidan Thompson (SNL)
------------------------------------------------------------------------- */
#include <cmath>
#include <cstring>
#include <cstdlib>
#include "fix_box_relax.h"
#include "atom.h"
#include "domain.h"
#include "update.h"
#include "comm.h"
#include "force.h"
#include "kspace.h"
#include "modify.h"
#include "compute.h"
#include "error.h"
#include "math_extra.h"
using namespace LAMMPS_NS;
using namespace FixConst;
enum{NONE,XYZ,XY,YZ,XZ};
enum{ISO,ANISO,TRICLINIC};
#define MAX_LIFO_DEPTH 2 // 3 box0 arrays in *.h dimensioned to this
/* ---------------------------------------------------------------------- */
FixBoxRelax::FixBoxRelax(LAMMPS *lmp, int narg, char **arg) :
Fix(lmp, narg, arg),
id_temp(NULL), id_press(NULL), tflag(0), pflag(0)
{
if (narg < 5) error->all(FLERR,"Illegal fix box/relax command");
scalar_flag = 1;
extscalar = 1;
global_freq = 1;
no_change_box = 1;
// default values
pcouple = NONE;
allremap = 1;
vmax = 0.0001;
deviatoric_flag = 0;
nreset_h0 = 0;
p_target[0] = p_target[1] = p_target[2] =
p_target[3] = p_target[4] = p_target[5] = 0.0;
p_flag[0] = p_flag[1] = p_flag[2] =
p_flag[3] = p_flag[4] = p_flag[5] = 0;
// turn on tilt factor scaling, whenever applicable
dimension = domain->dimension;
scaleyz = scalexz = scalexy = 0;
if (domain->yperiodic && domain->xy != 0.0) scalexy = 1;
if (domain->zperiodic && dimension == 3) {
if (domain->yz != 0.0) scaleyz = 1;
if (domain->xz != 0.0) scalexz = 1;
}
// set fixed-point to default = center of cell
fixedpoint[0] = 0.5*(domain->boxlo[0]+domain->boxhi[0]);
fixedpoint[1] = 0.5*(domain->boxlo[1]+domain->boxhi[1]);
fixedpoint[2] = 0.5*(domain->boxlo[2]+domain->boxhi[2]);
// process keywords
int iarg = 3;
while (iarg < narg) {
if (strcmp(arg[iarg],"iso") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
pcouple = XYZ;
p_target[0] = p_target[1] = p_target[2] = force->numeric(FLERR,arg[iarg+1]);
p_flag[0] = p_flag[1] = p_flag[2] = 1;
if (dimension == 2) {
p_target[2] = 0.0;
p_flag[2] = 0;
}
iarg += 2;
} else if (strcmp(arg[iarg],"aniso") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
pcouple = NONE;
p_target[0] = p_target[1] = p_target[2] = force->numeric(FLERR,arg[iarg+1]);
p_flag[0] = p_flag[1] = p_flag[2] = 1;
if (dimension == 2) {
p_target[2] = 0.0;
p_flag[2] = 0;
}
iarg += 2;
} else if (strcmp(arg[iarg],"tri") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
pcouple = NONE;
scalexy = scalexz = scaleyz = 0;
p_target[0] = p_target[1] = p_target[2] = force->numeric(FLERR,arg[iarg+1]);
p_flag[0] = p_flag[1] = p_flag[2] = 1;
p_target[3] = p_target[4] = p_target[5] = 0.0;
p_flag[3] = p_flag[4] = p_flag[5] = 1;
if (dimension == 2) {
p_target[2] = p_target[3] = p_target[4] = 0.0;
p_flag[2] = p_flag[3] = p_flag[4] = 0;
}
iarg += 2;
} else if (strcmp(arg[iarg],"x") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
p_target[0] = force->numeric(FLERR,arg[iarg+1]);
p_flag[0] = 1;
deviatoric_flag = 1;
iarg += 2;
} else if (strcmp(arg[iarg],"y") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
p_target[1] = force->numeric(FLERR,arg[iarg+1]);
p_flag[1] = 1;
deviatoric_flag = 1;
iarg += 2;
} else if (strcmp(arg[iarg],"z") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
p_target[2] = force->numeric(FLERR,arg[iarg+1]);
p_flag[2] = 1;
deviatoric_flag = 1;
iarg += 2;
if (dimension == 2)
error->all(FLERR,"Invalid fix box/relax command for a 2d simulation");
} else if (strcmp(arg[iarg],"yz") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
p_target[3] = force->numeric(FLERR,arg[iarg+1]);
p_flag[3] = 1;
deviatoric_flag = 1;
scaleyz = 0;
iarg += 2;
if (dimension == 2)
error->all(FLERR,"Invalid fix box/relax command for a 2d simulation");
} else if (strcmp(arg[iarg],"xz") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
p_target[4] = force->numeric(FLERR,arg[iarg+1]);
p_flag[4] = 1;
deviatoric_flag = 1;
scalexz = 0;
iarg += 2;
if (dimension == 2)
error->all(FLERR,"Invalid fix box/relax command for a 2d simulation");
} else if (strcmp(arg[iarg],"xy") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
p_target[5] = force->numeric(FLERR,arg[iarg+1]);
p_flag[5] = 1;
deviatoric_flag = 1;
scalexy = 0;
iarg += 2;
} else if (strcmp(arg[iarg],"couple") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
if (strcmp(arg[iarg+1],"xyz") == 0) pcouple = XYZ;
else if (strcmp(arg[iarg+1],"xy") == 0) pcouple = XY;
else if (strcmp(arg[iarg+1],"yz") == 0) pcouple = YZ;
else if (strcmp(arg[iarg+1],"xz") == 0) pcouple = XZ;
else if (strcmp(arg[iarg+1],"none") == 0) pcouple = NONE;
else error->all(FLERR,"Illegal fix box/relax command");
iarg += 2;
} else if (strcmp(arg[iarg],"dilate") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
if (strcmp(arg[iarg+1],"all") == 0) allremap = 1;
else if (strcmp(arg[iarg+1],"partial") == 0) allremap = 0;
else error->all(FLERR,"Illegal fix box/relax command");
iarg += 2;
} else if (strcmp(arg[iarg],"vmax") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
vmax = force->numeric(FLERR,arg[iarg+1]);
iarg += 2;
} else if (strcmp(arg[iarg],"nreset") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
nreset_h0 = force->inumeric(FLERR,arg[iarg+1]);
if (nreset_h0 < 0) error->all(FLERR,"Illegal fix box/relax command");
iarg += 2;
} else if (strcmp(arg[iarg],"scalexy") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
if (strcmp(arg[iarg+1],"yes") == 0) scalexy = 1;
else if (strcmp(arg[iarg+1],"no") == 0) scalexy = 0;
else error->all(FLERR,"Illegal fix box/relax command");
iarg += 2;
} else if (strcmp(arg[iarg],"scalexz") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
if (strcmp(arg[iarg+1],"yes") == 0) scalexz = 1;
else if (strcmp(arg[iarg+1],"no") == 0) scalexz = 0;
else error->all(FLERR,"Illegal fix box/relax command");
iarg += 2;
} else if (strcmp(arg[iarg],"scaleyz") == 0) {
if (iarg+2 > narg) error->all(FLERR,"Illegal fix box/relax command");
if (strcmp(arg[iarg+1],"yes") == 0) scaleyz = 1;
else if (strcmp(arg[iarg+1],"no") == 0) scaleyz = 0;
else error->all(FLERR,"Illegal fix box/relax command");
iarg += 2;
} else if (strcmp(arg[iarg],"fixedpoint") == 0) {
if (iarg+4 > narg) error->all(FLERR,"Illegal fix box/relax command");
fixedpoint[0] = force->numeric(FLERR,arg[iarg+1]);
fixedpoint[1] = force->numeric(FLERR,arg[iarg+2]);
fixedpoint[2] = force->numeric(FLERR,arg[iarg+3]);
iarg += 4;
} else error->all(FLERR,"Illegal fix box/relax command");
}
if (p_flag[0] || p_flag[1] || p_flag[2]) box_change_size = 1;
if (p_flag[3] || p_flag[4] || p_flag[5]) box_change_shape = 1;
if (allremap == 0) restart_pbc = 1;
// error checks
if (dimension == 2 && (p_flag[2] || p_flag[3] || p_flag[4]))
error->all(FLERR,"Invalid fix box/relax command for a 2d simulation");
if (dimension == 2 && (pcouple == YZ || pcouple == XZ))
error->all(FLERR,"Invalid fix box/relax command for a 2d simulation");
if (pcouple == XYZ && (p_flag[0] == 0 || p_flag[1] == 0))
error->all(FLERR,"Invalid fix box/relax command pressure settings");
if (pcouple == XYZ && dimension == 3 && p_flag[2] == 0)
error->all(FLERR,"Invalid fix box/relax command pressure settings");
if (pcouple == XY && (p_flag[0] == 0 || p_flag[1] == 0))
error->all(FLERR,"Invalid fix box/relax command pressure settings");
if (pcouple == YZ && (p_flag[1] == 0 || p_flag[2] == 0))
error->all(FLERR,"Invalid fix box/relax command pressure settings");
if (pcouple == XZ && (p_flag[0] == 0 || p_flag[2] == 0))
error->all(FLERR,"Invalid fix box/relax command pressure settings");
// require periodicity in tensile dimension
if (p_flag[0] && domain->xperiodic == 0)
error->all(FLERR,"Cannot use fix box/relax on a non-periodic dimension");
if (p_flag[1] && domain->yperiodic == 0)
error->all(FLERR,"Cannot use fix box/relax on a non-periodic dimension");
if (p_flag[2] && domain->zperiodic == 0)
error->all(FLERR,"Cannot use fix box/relax on a non-periodic dimension");
// require periodicity in 2nd dim of off-diagonal tilt component
if (p_flag[3] && domain->zperiodic == 0)
error->all(FLERR,
"Cannot use fix box/relax on a 2nd non-periodic dimension");
if (p_flag[4] && domain->zperiodic == 0)
error->all(FLERR,
"Cannot use fix box/relax on a 2nd non-periodic dimension");
if (p_flag[5] && domain->yperiodic == 0)
error->all(FLERR,
"Cannot use fix box/relax on a 2nd non-periodic dimension");
if (scaleyz == 1 && domain->zperiodic == 0)
error->all(FLERR,"Cannot use fix box/relax "
"with tilt factor scaling on a 2nd non-periodic dimension");
if (scalexz == 1 && domain->zperiodic == 0)
error->all(FLERR,"Cannot use fix box/relax "
"with tilt factor scaling on a 2nd non-periodic dimension");
if (scalexy == 1 && domain->yperiodic == 0)
error->all(FLERR,"Cannot use fix box/relax "
"with tilt factor scaling on a 2nd non-periodic dimension");
if (p_flag[3] && scaleyz == 1)
error->all(FLERR,"Cannot use fix box/relax with "
"both relaxation and scaling on a tilt factor");
if (p_flag[4] && scalexz == 1)
error->all(FLERR,"Cannot use fix box/relax with "
"both relaxation and scaling on a tilt factor");
if (p_flag[5] && scalexy == 1)
error->all(FLERR,"Cannot use fix box/relax with "
"both relaxation and scaling on a tilt factor");
if (!domain->triclinic && (p_flag[3] || p_flag[4] || p_flag[5]))
error->all(FLERR,"Can not specify Pxy/Pxz/Pyz in "
"fix box/relax with non-triclinic box");
if (pcouple == XYZ && dimension == 3 &&
(p_target[0] != p_target[1] || p_target[0] != p_target[2]))
error->all(FLERR,"Invalid fix box/relax pressure settings");
if (pcouple == XYZ && dimension == 2 && p_target[0] != p_target[1])
error->all(FLERR,"Invalid fix box/relax pressure settings");
if (pcouple == XY && p_target[0] != p_target[1])
error->all(FLERR,"Invalid fix box/relax pressure settings");
if (pcouple == YZ && p_target[1] != p_target[2])
error->all(FLERR,"Invalid fix box/relax pressure settings");
if (pcouple == XZ && p_target[0] != p_target[2])
error->all(FLERR,"Invalid fix box/relax pressure settings");
if (vmax <= 0.0) error->all(FLERR,"Illegal fix box/relax command");
// pstyle = TRICLINIC if any off-diagonal term is controlled -> 6 dof
// else pstyle = ISO if XYZ coupling or XY coupling in 2d -> 1 dof
// else pstyle = ANISO -> 3 dof
if (p_flag[3] || p_flag[4] || p_flag[5]) pstyle = TRICLINIC;
else if (pcouple == XYZ || (dimension == 2 && pcouple == XY)) pstyle = ISO;
else pstyle = ANISO;
// create a new compute temp style
// id = fix-ID + temp
// compute group = all since pressure is always global (group all)
// and thus its KE/temperature contribution should use group all
int n = strlen(id) + 6;
id_temp = new char[n];
strcpy(id_temp,id);
strcat(id_temp,"_temp");
char **newarg = new char*[3];
newarg[0] = id_temp;
newarg[1] = (char *) "all";
newarg[2] = (char *) "temp";
modify->add_compute(3,newarg);
delete [] newarg;
tflag = 1;
// create a new compute pressure style (virial only)
// id = fix-ID + press, compute group = all
// pass id_temp as 4th arg to pressure constructor
n = strlen(id) + 7;
id_press = new char[n];
strcpy(id_press,id);
strcat(id_press,"_press");
newarg = new char*[5];
newarg[0] = id_press;
newarg[1] = (char *) "all";
newarg[2] = (char *) "pressure";
newarg[3] = id_temp;
newarg[4] = (char *) "virial";
modify->add_compute(5,newarg);
delete [] newarg;
pflag = 1;
dimension = domain->dimension;
nrigid = 0;
rfix = 0;
current_lifo = 0;
}
/* ---------------------------------------------------------------------- */
FixBoxRelax::~FixBoxRelax()
{
delete [] rfix;
// delete temperature and pressure if fix created them
if (tflag) modify->delete_compute(id_temp);
if (pflag) modify->delete_compute(id_press);
delete [] id_temp;
delete [] id_press;
}
/* ---------------------------------------------------------------------- */
int FixBoxRelax::setmask()
{
int mask = 0;
mask |= MIN_ENERGY;
return mask;
}
/* ---------------------------------------------------------------------- */
void FixBoxRelax::init()
{
// set temperature and pressure ptrs
int icompute = modify->find_compute(id_temp);
if (icompute < 0)
error->all(FLERR,"Temperature ID for fix box/relax does not exist");
temperature = modify->compute[icompute];
icompute = modify->find_compute(id_press);
if (icompute < 0)
error->all(FLERR,"Pressure ID for fix box/relax does not exist");
pressure = modify->compute[icompute];
pv2e = 1.0 / force->nktv2p;
if (force->kspace) kspace_flag = 1;
else kspace_flag = 0;
// detect if any rigid fixes exist so rigid bodies move when box is remapped
// rfix[] = indices to each fix rigid
delete [] rfix;
nrigid = 0;
rfix = NULL;
for (int i = 0; i < modify->nfix; i++)
if (modify->fix[i]->rigid_flag) nrigid++;
if (nrigid) {
rfix = new int[nrigid];
nrigid = 0;
for (int i = 0; i < modify->nfix; i++)
if (modify->fix[i]->rigid_flag) rfix[nrigid++] = i;
}
// initial box dimensions
xprdinit = domain->xprd;
yprdinit = domain->yprd;
zprdinit = domain->zprd;
if (dimension == 2) zprdinit = 1.0;
vol0 = xprdinit * yprdinit * zprdinit;
h0[0] = domain->h[0];
h0[1] = domain->h[1];
h0[2] = domain->h[2];
h0[3] = domain->h[3];
h0[4] = domain->h[4];
h0[5] = domain->h[5];
// hydrostatic target pressure and deviatoric target stress
compute_press_target();
if (deviatoric_flag) compute_sigma();
}
/* ----------------------------------------------------------------------
compute energy and force due to extra degrees of freedom
------------------------------------------------------------------------- */
double FixBoxRelax::min_energy(double *fextra)
{
double eng,scale,scalex,scaley,scalez,scalevol;
temperature->compute_scalar();
if (pstyle == ISO) pressure->compute_scalar();
else {
temperature->compute_vector();
pressure->compute_vector();
}
couple();
// trigger virial computation on every iteration of minimizer
pressure->addstep(update->ntimestep+1);
// compute energy, forces for each extra degree of freedom
// returned eng = PV must be in units of energy
// returned fextra must likewise be in units of energy
if (pstyle == ISO) {
scale = domain->xprd/xprdinit;
if (dimension == 3) {
eng = pv2e * p_target[0] * (scale*scale*scale-1.0)*vol0;
fextra[0] = pv2e * (p_current[0] - p_target[0])*3.0*scale*scale*vol0;
} else {
eng = pv2e * p_target[0] * (scale*scale-1.0)*vol0;
fextra[0] = pv2e * (p_current[0] - p_target[0])*2.0*scale*vol0;
}
} else {
fextra[0] = fextra[1] = fextra[2] = 0.0;
scalex = scaley = scalez = 1.0;
if (p_flag[0]) scalex = domain->xprd/xprdinit;
if (p_flag[1]) scaley = domain->yprd/yprdinit;
if (p_flag[2]) scalez = domain->zprd/zprdinit;
scalevol = scalex*scaley*scalez;
eng = pv2e * p_hydro * (scalevol-1.0)*vol0;
if (p_flag[0])
fextra[0] = pv2e * (p_current[0] - p_hydro)*scaley*scalez*vol0;
if (p_flag[1])
fextra[1] = pv2e * (p_current[1] - p_hydro)*scalex*scalez*vol0;
if (p_flag[2])
fextra[2] = pv2e * (p_current[2] - p_hydro)*scalex*scaley*vol0;
if (pstyle == TRICLINIC) {
fextra[3] = fextra[4] = fextra[5] = 0.0;
if (p_flag[3])
fextra[3] = pv2e*p_current[3]*scaley*yprdinit*scalex*xprdinit*yprdinit;
if (p_flag[4])
fextra[4] = pv2e*p_current[4]*scalex*xprdinit*scaley*yprdinit*xprdinit;
if (p_flag[5])
fextra[5] = pv2e*p_current[5]*scalex*xprdinit*scalez*zprdinit*xprdinit;
}
if (deviatoric_flag) {
compute_deviatoric();
if (p_flag[0]) fextra[0] -= fdev[0]*xprdinit;
if (p_flag[1]) fextra[1] -= fdev[1]*yprdinit;
if (p_flag[2]) fextra[2] -= fdev[2]*zprdinit;
if (pstyle == TRICLINIC) {
if (p_flag[3]) fextra[3] -= fdev[3]*yprdinit;
if (p_flag[4]) fextra[4] -= fdev[4]*xprdinit;
if (p_flag[5]) fextra[5] -= fdev[5]*xprdinit;
}
eng += compute_strain_energy();
}
}
return eng;
}
/* ----------------------------------------------------------------------
store extra dof values for minimization linesearch starting point
boxlo0,boxhi0 = box dimensions
box values are pushed onto a LIFO stack so nested calls can be made
values are popped by calling min_step(0.0)
------------------------------------------------------------------------- */
void FixBoxRelax::min_store()
{
for (int i = 0; i < 3; i++) {
boxlo0[current_lifo][i] = domain->boxlo[i];
boxhi0[current_lifo][i] = domain->boxhi[i];
}
if (pstyle == TRICLINIC) {
boxtilt0[current_lifo][0] = domain->yz;
boxtilt0[current_lifo][1] = domain->xz;
boxtilt0[current_lifo][2] = domain->xy;
}
}
/* ----------------------------------------------------------------------
clear the LIFO stack for min_store
------------------------------------------------------------------------- */
void FixBoxRelax::min_clearstore()
{
current_lifo = 0;
}
/* ----------------------------------------------------------------------
push the LIFO stack for min_store
------------------------------------------------------------------------- */
void FixBoxRelax::min_pushstore()
{
if (current_lifo >= MAX_LIFO_DEPTH) {
error->all(FLERR,"Attempt to push beyond stack limit in fix box/relax");
return;
}
current_lifo++;
}
/* ----------------------------------------------------------------------
pop the LIFO stack for min_store
------------------------------------------------------------------------- */
void FixBoxRelax::min_popstore()
{
if (current_lifo <= 0) {
error->all(FLERR,"Attempt to pop empty stack in fix box/relax");
return;
}
current_lifo--;
}
/* ----------------------------------------------------------------------
check if time to reset reference state. If so, do so.
------------------------------------------------------------------------- */
int FixBoxRelax::min_reset_ref()
{
int itmp = 0;
// if nreset_h0 > 0, reset reference box
// every nreset_h0 timesteps
// only needed for deviatoric external stress
if (deviatoric_flag && nreset_h0 > 0) {
int delta = update->ntimestep - update->beginstep;
if (delta % nreset_h0 == 0) {
compute_sigma();
itmp = 1;
}
}
return itmp;
}
/* ----------------------------------------------------------------------
change the box dimensions by fraction ds = alpha*hextra
------------------------------------------------------------------------- */
void FixBoxRelax::min_step(double alpha, double *hextra)
{
if (pstyle == ISO) {
ds[0] = ds[1] = ds[2] = alpha*hextra[0];
} else {
ds[0] = ds[1] = ds[2] = 0.0;
if (p_flag[0]) ds[0] = alpha*hextra[0];
if (p_flag[1]) ds[1] = alpha*hextra[1];
if (p_flag[2]) ds[2] = alpha*hextra[2];
if (pstyle == TRICLINIC) {
ds[3] = ds[4] = ds[5] = 0.0;
if (p_flag[3]) ds[3] = alpha*hextra[3];
if (p_flag[4]) ds[4] = alpha*hextra[4];
if (p_flag[5]) ds[5] = alpha*hextra[5];
}
}
remap();
if (kspace_flag) force->kspace->setup();
}
/* ----------------------------------------------------------------------
max allowed step size along hextra
------------------------------------------------------------------------- */
double FixBoxRelax::max_alpha(double *hextra)
{
double alpha = 1.0;
if (pstyle == ISO) alpha = vmax/fabs(hextra[0]);
else {
if (p_flag[0]) alpha = MIN(alpha,vmax/fabs(hextra[0]));
if (p_flag[1]) alpha = MIN(alpha,vmax/fabs(hextra[1]));
if (p_flag[2]) alpha = MIN(alpha,vmax/fabs(hextra[2]));
if (pstyle == TRICLINIC) {
if (p_flag[3]) alpha = MIN(alpha,vmax/fabs(hextra[3]));
if (p_flag[4]) alpha = MIN(alpha,vmax/fabs(hextra[4]));
if (p_flag[5]) alpha = MIN(alpha,vmax/fabs(hextra[5]));
}
}
return alpha;
}
/* ----------------------------------------------------------------------
return number of degrees of freedom added by this fix
------------------------------------------------------------------------- */
int FixBoxRelax::min_dof()
{
if (pstyle == ISO) return 1;
if (pstyle == TRICLINIC) return 6;
return 3;
}
/* ----------------------------------------------------------------------
dilate the box and owned/ghost atoms around center of box
------------------------------------------------------------------------- */
void FixBoxRelax::remap()
{
int i,n;
// rescale simulation box from linesearch starting point
// scale atom coords for all atoms or only for fix group atoms
double **x = atom->x;
int *mask = atom->mask;
n = atom->nlocal + atom->nghost;
// convert pertinent atoms and rigid bodies to lamda coords
if (allremap) domain->x2lamda(n);
else {
for (i = 0; i < n; i++)
if (mask[i] & groupbit)
domain->x2lamda(x[i],x[i]);
}
if (nrigid)
for (i = 0; i < nrigid; i++)
modify->fix[rfix[i]]->deform(0);
// reset global and local box to new size/shape
for (i = 0; i < 3; i++)
if (p_flag[i]) {
double currentBoxLo0 = boxlo0[current_lifo][i];
double currentBoxHi0 = boxhi0[current_lifo][i];
domain->boxlo[i] = currentBoxLo0 + (currentBoxLo0 - fixedpoint[i])/domain->h[i]*ds[i]*h0[i];
domain->boxhi[i] = currentBoxHi0 + (currentBoxHi0 - fixedpoint[i])/domain->h[i]*ds[i]*h0[i];
if (domain->boxlo[i] >= domain->boxhi[i])
error->all(FLERR,"Fix box/relax generated negative box length");
}
// scale tilt factors with cell, if set
if (scaleyz) domain->yz = (domain->boxhi[2] - domain->boxlo[2])*h0[3]/h0[2];
if (scalexz) domain->xz = (domain->boxhi[2] - domain->boxlo[2])*h0[4]/h0[2];
if (scalexy) domain->xy = (domain->boxhi[1] - domain->boxlo[1])*h0[5]/h0[1];
if (pstyle == TRICLINIC) {
if (p_flag[3]) domain->yz = boxtilt0[current_lifo][0]+ds[3]*yprdinit;
if (p_flag[4]) domain->xz = boxtilt0[current_lifo][1]+ds[4]*xprdinit;
if (p_flag[5]) domain->xy = boxtilt0[current_lifo][2]+ds[5]*xprdinit;
}
domain->set_global_box();
domain->set_local_box();
// convert pertinent atoms and rigid bodies back to box coords
if (allremap) domain->lamda2x(n);
else {
for (i = 0; i < n; i++)
if (mask[i] & groupbit)
domain->lamda2x(x[i],x[i]);
}
if (nrigid)
for (i = 0; i < nrigid; i++)
modify->fix[rfix[i]]->deform(1);
}
/* ---------------------------------------------------------------------- */
void FixBoxRelax::couple()
{
double *tensor = pressure->vector;
if (pstyle == ISO)
p_current[0] = p_current[1] = p_current[2] = pressure->scalar;
else if (pcouple == XYZ) {
double ave = 1.0/3.0 * (tensor[0] + tensor[1] + tensor[2]);
p_current[0] = p_current[1] = p_current[2] = ave;
} else if (pcouple == XY) {
double ave = 0.5 * (tensor[0] + tensor[1]);
p_current[0] = p_current[1] = ave;
p_current[2] = tensor[2];
} else if (pcouple == YZ) {
double ave = 0.5 * (tensor[1] + tensor[2]);
p_current[1] = p_current[2] = ave;
p_current[0] = tensor[0];
} else if (pcouple == XZ) {
double ave = 0.5 * (tensor[0] + tensor[2]);
p_current[0] = p_current[2] = ave;
p_current[1] = tensor[1];
} else {
p_current[0] = tensor[0];
p_current[1] = tensor[1];
p_current[2] = tensor[2];
}
// switch order from xy-xz-yz to Voigt
if (pstyle == TRICLINIC) {
p_current[3] = tensor[5];
p_current[4] = tensor[4];
p_current[5] = tensor[3];
}
}
/* ---------------------------------------------------------------------- */
int FixBoxRelax::modify_param(int narg, char **arg)
{
if (strcmp(arg[0],"temp") == 0) {
if (narg < 2) error->all(FLERR,"Illegal fix_modify command");
if (tflag) {
modify->delete_compute(id_temp);
tflag = 0;
}
delete [] id_temp;
int n = strlen(arg[1]) + 1;
id_temp = new char[n];
strcpy(id_temp,arg[1]);
int icompute = modify->find_compute(arg[1]);
if (icompute < 0)
error->all(FLERR,"Could not find fix_modify temperature ID");
temperature = modify->compute[icompute];
if (temperature->tempflag == 0)
error->all(FLERR,
"Fix_modify temperature ID does not compute temperature");
if (temperature->igroup != 0 && comm->me == 0)
error->warning(FLERR,"Temperature for fix modify is not for group all");
// reset id_temp of pressure to new temperature ID
icompute = modify->find_compute(id_press);
if (icompute < 0)
error->all(FLERR,"Pressure ID for fix modify does not exist");
modify->compute[icompute]->reset_extra_compute_fix(id_temp);
return 2;
} else if (strcmp(arg[0],"press") == 0) {
if (narg < 2) error->all(FLERR,"Illegal fix_modify command");
if (pflag) {
modify->delete_compute(id_press);
pflag = 0;
}
delete [] id_press;
int n = strlen(arg[1]) + 1;
id_press = new char[n];
strcpy(id_press,arg[1]);
int icompute = modify->find_compute(arg[1]);
if (icompute < 0) error->all(FLERR,"Could not find fix_modify pressure ID");
pressure = modify->compute[icompute];
if (pressure->pressflag == 0)
error->all(FLERR,"Fix_modify pressure ID does not compute pressure");
return 2;
}
return 0;
}
/* ----------------------------------------------------------------------
compute sigma tensor (needed whenever reference box is reset)
-----------------------------------------------------------------------*/
void FixBoxRelax::compute_sigma()
{
double pdeviatoric[3][3];
double tmp1[3][3],sigma_tensor[3][3],h_invtmp[3][3];
// reset reference box dimensions
xprdinit = domain->xprd;
yprdinit = domain->yprd;
zprdinit = domain->zprd;
if (dimension == 2) zprdinit = 1.0;
vol0 = xprdinit * yprdinit * zprdinit;
h0_inv[0] = domain->h_inv[0];
h0_inv[1] = domain->h_inv[1];
h0_inv[2] = domain->h_inv[2];
h0_inv[3] = domain->h_inv[3];
h0_inv[4] = domain->h_inv[4];
h0_inv[5] = domain->h_inv[5];
h_invtmp[0][0] = h0_inv[0];
h_invtmp[1][1] = h0_inv[1];
h_invtmp[2][2] = h0_inv[2];
h_invtmp[1][2] = h0_inv[3];
h_invtmp[0][2] = h0_inv[4];
h_invtmp[0][1] = h0_inv[5];
h_invtmp[2][1] = 0.0;
h_invtmp[2][0] = 0.0;
h_invtmp[1][0] = 0.0;
// compute target deviatoric stress tensor pdevmod
pdeviatoric[0][0] = pdeviatoric[1][1] = pdeviatoric[2][2] = 0.0;
if (p_flag[0]) pdeviatoric[0][0] = p_target[0] - p_hydro;
if (p_flag[1]) pdeviatoric[1][1] = p_target[1] - p_hydro;
if (p_flag[2]) pdeviatoric[2][2] = p_target[2] - p_hydro;
pdeviatoric[1][2] = pdeviatoric[2][1] = p_target[3];
pdeviatoric[0][2] = pdeviatoric[2][0] = p_target[4];
pdeviatoric[0][1] = pdeviatoric[1][0] = p_target[5];
// Modify to account for off-diagonal terms
// These equations come from the stationarity relation:
// Pdev,sys = Pdev,targ*hinv^t*hdiag
// where:
// Pdev,sys is the system deviatoric stress tensor,
// Pdev,targ = pdeviatoric, effective target deviatoric stress
// hinv^t is the transpose of the inverse h tensor
// hdiag is the diagonal part of the h tensor
pdeviatoric[1][1] -= pdeviatoric[1][2]*h0_inv[3]*h0[1];
pdeviatoric[0][1] -= pdeviatoric[0][2]*h0_inv[3]*h0[1];
pdeviatoric[1][0] = pdeviatoric[0][1];
pdeviatoric[0][0] -= pdeviatoric[0][1]*h0_inv[5]*h0[0] +
pdeviatoric[0][2]*h0_inv[4]*h0[0];
// compute symmetric sigma tensor
MathExtra::times3(h_invtmp,pdeviatoric,tmp1);
MathExtra::times3_transpose(tmp1,h_invtmp,sigma_tensor);
MathExtra::scalar_times3(vol0,sigma_tensor);
sigma[0] = sigma_tensor[0][0];
sigma[1] = sigma_tensor[1][1];
sigma[2] = sigma_tensor[2][2];
sigma[3] = sigma_tensor[1][2];
sigma[4] = sigma_tensor[0][2];
sigma[5] = sigma_tensor[0][1];
}
/* ----------------------------------------------------------------------
compute strain energy
-----------------------------------------------------------------------*/
double FixBoxRelax::compute_strain_energy()
{
// compute strain energy = 0.5*Tr(sigma*h*h^t) in energy units
double* h = domain->h;
double d0,d1,d2;
if (dimension == 3) {
d0 =
sigma[0]*(h[0]*h[0]+h[5]*h[5]+h[4]*h[4]) +
sigma[5]*( h[1]*h[5]+h[3]*h[4]) +
sigma[4]*( h[2]*h[4]);
d1 =
sigma[5]*( h[5]*h[1]+h[4]*h[3]) +
sigma[1]*( h[1]*h[1]+h[3]*h[3]) +
sigma[3]*( h[2]*h[3]);
d2 =
sigma[4]*( h[4]*h[2]) +
sigma[3]*( h[3]*h[2]) +
sigma[2]*( h[2]*h[2]);
} else {
d0 = sigma[0]*(h[0]*h[0]+h[5]*h[5]) + sigma[5]*h[1]*h[5];
d1 = sigma[5]*h[5]*h[1] + sigma[1]*h[1]*h[1];
d2 = 0.0;
}
double energy = 0.5*(d0+d1+d2)*pv2e;
return energy;
}
/* ----------------------------------------------------------------------
compute deviatoric barostat force = h*sigma*h^t
-----------------------------------------------------------------------*/
void FixBoxRelax::compute_deviatoric()
{
double* h = domain->h;
// [ 0 5 4 ] [ 0 5 4 ] [ 0 5 4 ]
// [ 5 1 3 ] = [ - 1 3 ] [ 5 1 3 ]
// [ 4 3 2 ] [ - - 2 ] [ 4 3 2 ]
if (dimension == 3) {
fdev[0] = pv2e*(h[0]*sigma[0]+h[5]*sigma[5]+h[4]*sigma[4]);
fdev[1] = pv2e*(h[1]*sigma[1]+h[3]*sigma[3]);
fdev[2] = pv2e*(h[2]*sigma[2]);
fdev[3] = pv2e*(h[1]*sigma[3]+h[3]*sigma[2]);
fdev[4] = pv2e*(h[0]*sigma[4]+h[5]*sigma[3]+h[4]*sigma[2]);
fdev[5] = pv2e*(h[0]*sigma[5]+h[5]*sigma[1]+h[4]*sigma[3]);
} else {
fdev[0] = pv2e*(h[0]*sigma[0]+h[5]*sigma[5]);
fdev[1] = pv2e*(h[1]*sigma[1]);
fdev[5] = pv2e*(h[0]*sigma[5]+h[5]*sigma[1]);
}
}
/* ----------------------------------------------------------------------
compute hydrostatic target pressure
-----------------------------------------------------------------------*/
void FixBoxRelax::compute_press_target()
{
pflagsum = p_flag[0] + p_flag[1] + p_flag[2];
p_hydro = 0.0;
for (int i = 0; i < 3; i++)
if (p_flag[i]) p_hydro += p_target[i];
if (pflagsum) p_hydro /= pflagsum;
for (int i = 0; i < 3; i++) {
if (p_flag[i] && fabs(p_hydro - p_target[i]) > 1.0e-6) deviatoric_flag = 1;
}
if (pstyle == TRICLINIC) {
for (int i = 3; i < 6; i++)
if (p_flag[i] && fabs(p_target[i]) > 1.0e-6) deviatoric_flag = 1;
}
}
/* ----------------------------------------------------------------------
compute PV and strain energy for access to the user
---------------------------------------------------------------------- */
double FixBoxRelax::compute_scalar()
{
double ftmp[6] = {0.0,0.0,0.0,0.0,0.0,0.0};
if (update->ntimestep == 0) return 0.0;
return min_energy(ftmp);
}
| 33.578893 | 98 | 0.548775 | rajkubp020 |
a315cdc1064f02ffa24047319bab9fe841bf95bb | 404 | cpp | C++ | General/Learning/C++/2/main.cpp | 123456789x/usaco-guide-solutions | fa3ea5c7c8160aec29f48187e39b0301a4d633fd | [
"MIT"
] | null | null | null | General/Learning/C++/2/main.cpp | 123456789x/usaco-guide-solutions | fa3ea5c7c8160aec29f48187e39b0301a4d633fd | [
"MIT"
] | null | null | null | General/Learning/C++/2/main.cpp | 123456789x/usaco-guide-solutions | fa3ea5c7c8160aec29f48187e39b0301a4d633fd | [
"MIT"
] | null | null | null | #include "ops.h"
#include <iostream>
using std::cin;
using std::cout;
int main()
{
int a;
cout << "Enter first integer: ";
cin >> a;
int b;
cout << "Enter second integer: ";
cin >> b;
cout << "Sum: " << add(a, b) << "\n";
cout << "Difference: " << subtract(a, b) << "\n";
cout << "Product: " << multiply(a, b) << "\n";
cout << "Quotient: " << divide(a, b) << "\n";
return 0;
}
| 16.833333 | 51 | 0.502475 | 123456789x |
a315db2068e255ba201668903a5a9b702359df53 | 642 | cc | C++ | ash/wm/window_mirror_view_pip.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | ash/wm/window_mirror_view_pip.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | ash/wm/window_mirror_view_pip.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/wm/window_mirror_view_pip.h"
namespace ash {
WindowMirrorViewPip::WindowMirrorViewPip(aura::Window* source,
bool trilinear_filtering_on_init)
: WindowMirrorView(source, trilinear_filtering_on_init) {}
WindowMirrorViewPip::~WindowMirrorViewPip() = default;
void WindowMirrorViewPip::InitLayerOwner() {
// Do nothing.
}
ui::Layer* WindowMirrorViewPip::GetMirrorLayer() {
return layer();
}
} // namespace ash
| 26.75 | 74 | 0.716511 | zealoussnow |
a317e995715beea086b7baf60a338651bebc03a4 | 2,274 | cpp | C++ | src/3rdparty/khtml/src/svg/SVGStopElement.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | src/3rdparty/khtml/src/svg/SVGStopElement.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | src/3rdparty/khtml/src/svg/SVGStopElement.cpp | afarcat/QtHtmlView | fff12b6f5c08c2c6db15dd73e4f0b55421827b39 | [
"Apache-2.0"
] | null | null | null | /*
Copyright (C) 2004, 2005, 2007, 2008 Nikolas Zimmermann <zimmermann@kde.org>
2004, 2005, 2006, 2007 Rob Buis <buis@kde.org>
This file is part of the KDE project
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
*/
#include "wtf/Platform.h"
#if ENABLE(SVG)
#include "SVGStopElement.h"
#include "Document.h"
#include "RenderSVGGradientStop.h"
#include "SVGGradientElement.h"
#include "SVGNames.h"
namespace WebCore
{
SVGStopElement::SVGStopElement(const QualifiedName &tagName, Document *doc)
: SVGStyledElement(tagName, doc)
, m_offset(0.0f)
{
}
SVGStopElement::~SVGStopElement()
{
}
ANIMATED_PROPERTY_DEFINITIONS(SVGStopElement, float, Number, number, Offset, offset, SVGNames::offsetAttr, m_offset)
void SVGStopElement::parseMappedAttribute(MappedAttribute *attr)
{
if (attr->name() == SVGNames::offsetAttr) {
const String &value = attr->value();
// qCDebug(KHTML_LOG) << "parse offset:" << value;
if (value.endsWith("%")) {
setOffsetBaseValue(value.substring(0, value.length() - 1).toFloat() / 100.0f);
} else {
setOffsetBaseValue(value.toFloat());
}
setChanged();
} else {
SVGStyledElement::parseMappedAttribute(attr);
}
}
RenderObject *SVGStopElement::createRenderer(RenderArena *arena, RenderStyle *)
{
return new(arena) RenderSVGGradientStop(this);
}
// KHTML ElementImpl pure virtual method
quint32 SVGStopElement::id() const
{
return SVGNames::stopTag.id();
}
}
#endif // ENABLE(SVG)
| 28.78481 | 116 | 0.700528 | afarcat |
a319e16bef55bf8bb3add0f3ffc26bf2662edd74 | 1,318 | cpp | C++ | BashuOJ-Code/3137.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/3137.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | BashuOJ-Code/3137.cpp | magicgh/algorithm-contest-code | c21a90b11f73535c61e6363a4305b74cff24a85b | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iomanip>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#define ri register int
#define ll long long
using namespace std;
const int MAXN=1005;
const int INF=0x7fffffff/2;
struct point{int x,y;};
int map[MAXN][MAXN];
bool vst[MAXN][MAXN];
int n,m,Max=-INF;
int dx[4]={-1,1,0,0},dy[4]={0,0,-1,1};
inline int getint()
{
int num=0,bj=1;
char c=getchar();
while(c<'0'||c>'9')bj=(c=='-'||bj==-1)?-1:1,c=getchar();
while(c>='0'&&c<='9')num=num*10+c-'0',c=getchar();
return num*bj;
}
inline bool Check(int k)
{
memset(vst,0,sizeof(vst));
queue<point>q;
q.push((point){1,1});
while(!q.empty())
{
point now=q.front();q.pop();
if(vst[now.x][now.y])continue;
vst[now.x][now.y]=1;
for(ri i=0;i<4;i++)
{
point next=(point){now.x+dx[i],now.y+dy[i]};
if(next.x>=1&&next.x<=n&&next.y>=1&&next.y<=m&&!vst[next.x][next.y]&&map[next.x][next.y]<=k)
{
if(next.x==n)return 1;
q.push(next);
}
}
}
return 0;
}
int Binary()
{
int l=0,r=Max;
while(l<=r)
{
int mid=(l+r)>>1;
if(Check(mid))r=mid-1;
else l=mid+1;
}
return l;
}
int main()
{
n=getint(),m=getint();
for(ri i=1;i<=n;i++)
for(ri j=1;j<=m;j++)map[i][j]=getint(),Max=max(Max,map[i][j]);
printf("%d\n",Binary());
return 0;
}
| 18.828571 | 95 | 0.592564 | magicgh |
a31bef877c09c15ad0837dc6e8ef96790c93786a | 3,990 | cpp | C++ | code/tools/popart-current1/moc_ColourDialog.cpp | kibet-gilbert/co1_metaanalysis | 1089cc03bc4dbabab543a8dadf49130d8e399665 | [
"CC-BY-3.0"
] | 1 | 2021-01-01T05:57:08.000Z | 2021-01-01T05:57:08.000Z | code/tools/popart-current1/moc_ColourDialog.cpp | kibet-gilbert/co1_metaanalysis | 1089cc03bc4dbabab543a8dadf49130d8e399665 | [
"CC-BY-3.0"
] | null | null | null | code/tools/popart-current1/moc_ColourDialog.cpp | kibet-gilbert/co1_metaanalysis | 1089cc03bc4dbabab543a8dadf49130d8e399665 | [
"CC-BY-3.0"
] | 1 | 2021-01-01T06:15:56.000Z | 2021-01-01T06:15:56.000Z | /****************************************************************************
** Meta object code from reading C++ file 'ColourDialog.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.7)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "src/gui/ColourDialog.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'ColourDialog.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.7. 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_ColourDialog_t {
QByteArrayData data[6];
char stringdata0[75];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_ColourDialog_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_ColourDialog_t qt_meta_stringdata_ColourDialog = {
{
QT_MOC_LITERAL(0, 0, 12), // "ColourDialog"
QT_MOC_LITERAL(1, 13, 12), // "changeColour"
QT_MOC_LITERAL(2, 26, 0), // ""
QT_MOC_LITERAL(3, 27, 20), // "toggleChangeMapTheme"
QT_MOC_LITERAL(4, 48, 5), // "state"
QT_MOC_LITERAL(5, 54, 20) // "toggleChangeNetTheme"
},
"ColourDialog\0changeColour\0\0"
"toggleChangeMapTheme\0state\0"
"toggleChangeNetTheme"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_ColourDialog[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
3, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 1, 29, 2, 0x08 /* Private */,
3, 1, 32, 2, 0x08 /* Private */,
5, 1, 35, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void, QMetaType::Int, 2,
QMetaType::Void, QMetaType::Int, 4,
QMetaType::Void, QMetaType::Int, 4,
0 // eod
};
void ColourDialog::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
ColourDialog *_t = static_cast<ColourDialog *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->changeColour((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->toggleChangeMapTheme((*reinterpret_cast< int(*)>(_a[1]))); break;
case 2: _t->toggleChangeNetTheme((*reinterpret_cast< int(*)>(_a[1]))); break;
default: ;
}
}
}
const QMetaObject ColourDialog::staticMetaObject = {
{ &QDialog::staticMetaObject, qt_meta_stringdata_ColourDialog.data,
qt_meta_data_ColourDialog, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *ColourDialog::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *ColourDialog::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_ColourDialog.stringdata0))
return static_cast<void*>(this);
return QDialog::qt_metacast(_clname);
}
int ColourDialog::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QDialog::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 3)
qt_static_metacall(this, _c, _id, _a);
_id -= 3;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 3)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 3;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 31.92 | 96 | 0.624561 | kibet-gilbert |
a31c7917c40f652b2f9ef88a3bd093593060846b | 9,091 | cpp | C++ | emulation/hel/lib/athena/HAL.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | emulation/hel/lib/athena/HAL.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | emulation/hel/lib/athena/HAL.cpp | NWalker1208/synthesis | c7bb2d49a7a3fc4d4db9f857aabcc4a4c3b74c34 | [
"Apache-2.0"
] | null | null | null | /*----------------------------------------------------------------------------*/
/* Copyright (c) FIRST 2016-2017. All Rights Reserved. */
/* Open Source Software - may be modified and shared by FRC teams. The code */
/* must be accompanied by the FIRST BSD license file in the root directory of */
/* the project. */
/*----------------------------------------------------------------------------*/
#include "HAL/HAL.h"
//#include <signal.h> // linux for kill
//#include <unistd.h>
//#include <sys/time.h>
#include <atomic>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <mutex>
#include <thread>
#include "FRC_NetworkCommunication/CANSessionMux.h"
#include "FRC_NetworkCommunication/FRCComm.h"
#include "FRC_NetworkCommunication/LoadOut.h"
#include "HAL/ChipObject.h"
#include "HAL/DriverStation.h"
#include "HAL/Errors.h"
#include "HAL/Notifier.h"
#include "HAL/cpp/priority_mutex.h"
#include "HAL/handles/HandlesInternal.h"
#include "ctre/ctre.h"
#include "visa/visa.h"
#include <chrono>
using namespace hal;
static std::unique_ptr<tGlobal> global;
static std::unique_ptr<tSysWatchdog> watchdog;
const char* WPILibVersion = "Fake";
static hal::priority_mutex timeMutex;
static uint32_t timeEpoch = 0;
static uint32_t prevFPGATime = 0;
static HAL_NotifierHandle rolloverNotifier = 0;
using namespace hal;
extern "C" {
HAL_PortHandle HAL_GetPort(int32_t channel) {
// Dont allow a number that wouldn't fit in a uint8_t
if (channel < 0 || channel >= 255) return HAL_kInvalidHandle;
return createPortHandle(channel, 1);
}
/**
* @deprecated Uses module numbers
*/
HAL_PortHandle HAL_GetPortWithModule(int32_t module, int32_t channel) {
// Dont allow a number that wouldn't fit in a uint8_t
if (channel < 0 || channel >= 255) return HAL_kInvalidHandle;
if (module < 0 || module >= 255) return HAL_kInvalidHandle;
return createPortHandle(channel, module);
}
const char* HAL_GetErrorMessage(int32_t code) {
switch (code) {
case 0:
return "";
case CTR_RxTimeout:
return CTR_RxTimeout_MESSAGE;
case CTR_TxTimeout:
return CTR_TxTimeout_MESSAGE;
case CTR_InvalidParamValue:
return CTR_InvalidParamValue_MESSAGE;
case CTR_UnexpectedArbId:
return CTR_UnexpectedArbId_MESSAGE;
case CTR_TxFailed:
return CTR_TxFailed_MESSAGE;
case CTR_SigNotUpdated:
return CTR_SigNotUpdated_MESSAGE;
case NiFpga_Status_FifoTimeout:
return NiFpga_Status_FifoTimeout_MESSAGE;
case NiFpga_Status_TransferAborted:
return NiFpga_Status_TransferAborted_MESSAGE;
case NiFpga_Status_MemoryFull:
return NiFpga_Status_MemoryFull_MESSAGE;
case NiFpga_Status_SoftwareFault:
return NiFpga_Status_SoftwareFault_MESSAGE;
case NiFpga_Status_InvalidParameter:
return NiFpga_Status_InvalidParameter_MESSAGE;
case NiFpga_Status_ResourceNotFound:
return NiFpga_Status_ResourceNotFound_MESSAGE;
case NiFpga_Status_ResourceNotInitialized:
return NiFpga_Status_ResourceNotInitialized_MESSAGE;
case NiFpga_Status_HardwareFault:
return NiFpga_Status_HardwareFault_MESSAGE;
case NiFpga_Status_IrqTimeout:
return NiFpga_Status_IrqTimeout_MESSAGE;
case SAMPLE_RATE_TOO_HIGH:
return SAMPLE_RATE_TOO_HIGH_MESSAGE;
case VOLTAGE_OUT_OF_RANGE:
return VOLTAGE_OUT_OF_RANGE_MESSAGE;
case LOOP_TIMING_ERROR:
return LOOP_TIMING_ERROR_MESSAGE;
case SPI_WRITE_NO_MOSI:
return SPI_WRITE_NO_MOSI_MESSAGE;
case SPI_READ_NO_MISO:
return SPI_READ_NO_MISO_MESSAGE;
case SPI_READ_NO_DATA:
return SPI_READ_NO_DATA_MESSAGE;
case INCOMPATIBLE_STATE:
return INCOMPATIBLE_STATE_MESSAGE;
case NO_AVAILABLE_RESOURCES:
return NO_AVAILABLE_RESOURCES_MESSAGE;
case RESOURCE_IS_ALLOCATED:
return RESOURCE_IS_ALLOCATED_MESSAGE;
case RESOURCE_OUT_OF_RANGE:
return RESOURCE_OUT_OF_RANGE_MESSAGE;
case HAL_INVALID_ACCUMULATOR_CHANNEL:
return HAL_INVALID_ACCUMULATOR_CHANNEL_MESSAGE;
case HAL_HANDLE_ERROR:
return HAL_HANDLE_ERROR_MESSAGE;
case NULL_PARAMETER:
return NULL_PARAMETER_MESSAGE;
case ANALOG_TRIGGER_LIMIT_ORDER_ERROR:
return ANALOG_TRIGGER_LIMIT_ORDER_ERROR_MESSAGE;
case ANALOG_TRIGGER_PULSE_OUTPUT_ERROR:
return ANALOG_TRIGGER_PULSE_OUTPUT_ERROR_MESSAGE;
case PARAMETER_OUT_OF_RANGE:
return PARAMETER_OUT_OF_RANGE_MESSAGE;
case HAL_COUNTER_NOT_SUPPORTED:
return HAL_COUNTER_NOT_SUPPORTED_MESSAGE;
case ERR_CANSessionMux_InvalidBuffer:
return ERR_CANSessionMux_InvalidBuffer_MESSAGE;
case ERR_CANSessionMux_MessageNotFound:
return ERR_CANSessionMux_MessageNotFound_MESSAGE;
case WARN_CANSessionMux_NoToken:
return WARN_CANSessionMux_NoToken_MESSAGE;
case ERR_CANSessionMux_NotAllowed:
return ERR_CANSessionMux_NotAllowed_MESSAGE;
case ERR_CANSessionMux_NotInitialized:
return ERR_CANSessionMux_NotInitialized_MESSAGE;
case VI_ERROR_SYSTEM_ERROR:
return VI_ERROR_SYSTEM_ERROR_MESSAGE;
case VI_ERROR_INV_OBJECT:
return VI_ERROR_INV_OBJECT_MESSAGE;
case VI_ERROR_RSRC_LOCKED:
return VI_ERROR_RSRC_LOCKED_MESSAGE;
case VI_ERROR_RSRC_NFOUND:
return VI_ERROR_RSRC_NFOUND_MESSAGE;
case VI_ERROR_INV_RSRC_NAME:
return VI_ERROR_INV_RSRC_NAME_MESSAGE;
case VI_ERROR_QUEUE_OVERFLOW:
return VI_ERROR_QUEUE_OVERFLOW_MESSAGE;
case VI_ERROR_IO:
return VI_ERROR_IO_MESSAGE;
case VI_ERROR_ASRL_PARITY:
return VI_ERROR_ASRL_PARITY_MESSAGE;
case VI_ERROR_ASRL_FRAMING:
return VI_ERROR_ASRL_FRAMING_MESSAGE;
case VI_ERROR_ASRL_OVERRUN:
return VI_ERROR_ASRL_OVERRUN_MESSAGE;
case VI_ERROR_RSRC_BUSY:
return VI_ERROR_RSRC_BUSY_MESSAGE;
case VI_ERROR_INV_PARAMETER:
return VI_ERROR_INV_PARAMETER_MESSAGE;
case HAL_PWM_SCALE_ERROR:
return HAL_PWM_SCALE_ERROR_MESSAGE;
case HAL_SERIAL_PORT_NOT_FOUND:
return HAL_SERIAL_PORT_NOT_FOUND_MESSAGE;
case HAL_THREAD_PRIORITY_ERROR:
return HAL_THREAD_PRIORITY_ERROR_MESSAGE;
case HAL_THREAD_PRIORITY_RANGE_ERROR:
return HAL_THREAD_PRIORITY_RANGE_ERROR_MESSAGE;
case HAL_SERIAL_PORT_OPEN_ERROR:
return HAL_SERIAL_PORT_OPEN_ERROR_MESSAGE;
case HAL_SERIAL_PORT_ERROR:
return HAL_SERIAL_PORT_ERROR_MESSAGE;
default:
return "Unknown error status";
}
}
/**
* Returns the runtime type of this HAL
*/
HAL_RuntimeType HAL_GetRuntimeType() { return HAL_Athena; }
/**
* Return the FPGA Version number.
* For now, expect this to be competition year.
* @return FPGA Version number.
*/
int32_t HAL_GetFPGAVersion(int32_t* status) {
if (!global) {
*status = NiFpga_Status_ResourceNotInitialized;
return 0;
}
return global->readVersion(status);
}
/**
* Return the FPGA Revision number.
* The format of the revision is 3 numbers.
* The 12 most significant bits are the Major Revision.
* the next 8 bits are the Minor Revision.
* The 12 least significant bits are the Build Number.
* @return FPGA Revision number.
*/
int64_t HAL_GetFPGARevision(int32_t* status) {
return 0;
}
/**
* Read the microsecond-resolution timer on the FPGA.
*
* @return The current time in microseconds according to the FPGA (since FPGA
* reset).
*/
uint64_t HAL_GetFPGATime(int32_t* status) {
*status = 0;
return std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
/**
* Get the state of the "USER" button on the roboRIO
* @return true if the button is currently pressed down
*/
HAL_Bool HAL_GetFPGAButton(int32_t* status) {
return false;
}
HAL_Bool HAL_GetSystemActive(int32_t* status) {
return false;
}
HAL_Bool HAL_GetBrownedOut(int32_t* status) {
return false;
}
static void timerRollover(uint64_t currentTime, HAL_NotifierHandle handle) {}
void HAL_BaseInitialize(int32_t* status) {
static std::atomic_bool initialized{false};
static hal::priority_mutex initializeMutex;
// Initial check, as if it's true initialization has finished
if (initialized) return;
std::lock_guard<hal::priority_mutex> lock(initializeMutex);
// Second check in case another thread was waiting
if (initialized) return;
initialized = true;
}
/**
* Call this to start up HAL. This is required for robot programs.
*/
int32_t HAL_Initialize(int32_t timeout, int32_t mode) {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
HAL_InitializeDriverStation();
return 1;
}
int64_t HAL_Report(int32_t resource, int32_t instanceNumber, int32_t context,
const char* feature) {
if (feature == nullptr) {
feature = "";
}
return 0;
}
// TODO: HACKS
// No need for header definitions, as we should not run from user code.
void NumericArrayResize() {}
void RTSetCleanupProc() {}
void EDVR_CreateReference() {}
} // extern "C"
| 31.456747 | 124 | 0.738093 | NWalker1208 |
a31dd59641a3825257069c7c0bfcaf7d3dd7b398 | 4,577 | cpp | C++ | examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/xrc/derivdlg.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 471 | 2019-06-26T09:59:09.000Z | 2022-03-30T04:59:42.000Z | examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/xrc/derivdlg.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 1,432 | 2017-06-21T04:08:48.000Z | 2020-08-25T16:21:15.000Z | examples/pxScene2d/external/WinSparkle/3rdparty/wxWidgets/samples/xrc/derivdlg.cpp | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 317 | 2017-06-20T19:57:17.000Z | 2020-09-16T10:28:30.000Z | //-----------------------------------------------------------------------------
// Name: derivdlg.cpp
// Purpose: XML resources sample: A derived dialog
// Author: Robert O'Connor (rob@medicalmnemonics.com), Vaclav Slavik
// Copyright: (c) Robert O'Connor and Vaclav Slavik
// Licence: wxWindows licence
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Standard wxWidgets headers
//-----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
// For all others, include the necessary headers (this file is usually all you
// need because it includes almost all "standard" wxWidgets headers)
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
//-----------------------------------------------------------------------------
// Header of this .cpp file
//-----------------------------------------------------------------------------
#include "derivdlg.h"
//-----------------------------------------------------------------------------
// Remaining headers: Needed wx headers, then wx/contrib headers, then application headers
//-----------------------------------------------------------------------------
#include "wx/xrc/xmlres.h" // XRC XML resouces
//-----------------------------------------------------------------------------
// Event table: connect the events to the handler functions to process them
//-----------------------------------------------------------------------------
wxBEGIN_EVENT_TABLE(PreferencesDialog, wxDialog)
EVT_BUTTON( XRCID( "my_button" ), PreferencesDialog::OnMyButtonClicked )
EVT_UPDATE_UI(XRCID( "my_checkbox" ), PreferencesDialog::OnUpdateUIMyCheckbox )
// Note that the ID here isn't a XRCID, it is one of the standard wx ID's.
EVT_BUTTON( wxID_OK, PreferencesDialog::OnOK )
wxEND_EVENT_TABLE()
//-----------------------------------------------------------------------------
// Public members
//-----------------------------------------------------------------------------
// Constructor (Notice how small and easy it is)
PreferencesDialog::PreferencesDialog(wxWindow* parent)
{
wxXmlResource::Get()->LoadDialog(this, parent, wxT("derived_dialog"));
}
//-----------------------------------------------------------------------------
// Private members (including the event handlers)
//-----------------------------------------------------------------------------
void PreferencesDialog::OnMyButtonClicked( wxCommandEvent &WXUNUSED(event) )
{
// Construct a message dialog.
wxMessageDialog msgDlg(this, _("You clicked on My Button"));
// Show it modally.
msgDlg.ShowModal();
}
// Update the enabled/disabled state of the edit/delete buttons depending on
// whether a row (item) is selected in the listctrl
void PreferencesDialog::OnUpdateUIMyCheckbox( wxUpdateUIEvent &WXUNUSED(event) )
{
// Get a boolean value of whether the checkbox is checked
bool myCheckBoxIsChecked;
// You could just write:
// myCheckBoxIsChecked = event.IsChecked();
// since the event that was passed into this function already has the
// is a pointer to the right control. However,
// this is the XRCCTRL way (which is more obvious as to what is going on).
myCheckBoxIsChecked = XRCCTRL(*this, "my_checkbox", wxCheckBox)->IsChecked();
// Now call either Enable(true) or Enable(false) on the textctrl, depending
// on the value of that boolean.
XRCCTRL(*this, "my_textctrl", wxTextCtrl)->Enable(myCheckBoxIsChecked);
}
void PreferencesDialog::OnOK( wxCommandEvent& WXUNUSED(event) )
{
// Construct a message dialog (An extra parameters to put a cancel button on).
wxMessageDialog msgDlg2(this, _("Press OK to close Derived dialog, or Cancel to abort"),
_("Overriding base class OK button handler"),
wxOK | wxCANCEL | wxCENTER );
// Show the message dialog, and if it returns wxID_OK (ie they clicked on OK button)...
if (msgDlg2.ShowModal() == wxID_OK)
{
// ...then end this Preferences dialog.
EndModal( wxID_OK );
// You could also have used event.Skip() which would then skip up
// to the wxDialog's event table and see if there was a EVT_BUTTON
// handler for wxID_OK and if there was, then execute that code.
}
// Otherwise do nothing.
}
| 41.609091 | 92 | 0.531134 | madanagopaltcomcast |
a31e176d85994ea627a676eb124c63c4048eb030 | 6,103 | hpp | C++ | include/System/Net/SimpleAsyncResult_--c__DisplayClass11_0.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/System/Net/SimpleAsyncResult_--c__DisplayClass11_0.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | include/System/Net/SimpleAsyncResult_--c__DisplayClass11_0.hpp | RedBrumbler/BeatSaber-Quest-Codegen | 73dda50b5a3e51f10d86b766dcaa24b0c6226e25 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.Net.SimpleAsyncResult
#include "System/Net/SimpleAsyncResult.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Func`2<T, TResult>
template<typename T, typename TResult>
class Func_2;
}
// Forward declaring namespace: System::Net
namespace System::Net {
// Forward declaring type: SimpleAsyncCallback
class SimpleAsyncCallback;
}
// Completed forward declares
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::System::Net::SimpleAsyncResult::$$c__DisplayClass11_0);
DEFINE_IL2CPP_ARG_TYPE(::System::Net::SimpleAsyncResult::$$c__DisplayClass11_0*, "System.Net", "SimpleAsyncResult/<>c__DisplayClass11_0");
// Type namespace: System.Net
namespace System::Net {
// Size: 0x28
#pragma pack(push, 1)
// Autogenerated type: System.Net.SimpleAsyncResult/System.Net.<>c__DisplayClass11_0
// [TokenAttribute] Offset: FFFFFFFF
// [CompilerGeneratedAttribute] Offset: FFFFFFFF
class SimpleAsyncResult::$$c__DisplayClass11_0 : public ::Il2CppObject {
public:
#ifdef USE_CODEGEN_FIELDS
public:
#else
#ifdef CODEGEN_FIELD_ACCESSIBILITY
CODEGEN_FIELD_ACCESSIBILITY:
#else
protected:
#endif
#endif
// public System.Func`2<System.Net.SimpleAsyncResult,System.Boolean> func
// Size: 0x8
// Offset: 0x10
::System::Func_2<::System::Net::SimpleAsyncResult*, bool>* func;
// Field size check
static_assert(sizeof(::System::Func_2<::System::Net::SimpleAsyncResult*, bool>*) == 0x8);
// public System.Object locker
// Size: 0x8
// Offset: 0x18
::Il2CppObject* locker;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// public System.Net.SimpleAsyncCallback callback
// Size: 0x8
// Offset: 0x20
::System::Net::SimpleAsyncCallback* callback;
// Field size check
static_assert(sizeof(::System::Net::SimpleAsyncCallback*) == 0x8);
public:
// Get instance field reference: public System.Func`2<System.Net.SimpleAsyncResult,System.Boolean> func
::System::Func_2<::System::Net::SimpleAsyncResult*, bool>*& dyn_func();
// Get instance field reference: public System.Object locker
::Il2CppObject*& dyn_locker();
// Get instance field reference: public System.Net.SimpleAsyncCallback callback
::System::Net::SimpleAsyncCallback*& dyn_callback();
// System.Boolean <RunWithLock>b__0(System.Net.SimpleAsyncResult inner)
// Offset: 0x1B35664
bool $RunWithLock$b__0(::System::Net::SimpleAsyncResult* inner);
// System.Void <RunWithLock>b__1(System.Net.SimpleAsyncResult inner)
// Offset: 0x1B356EC
void $RunWithLock$b__1(::System::Net::SimpleAsyncResult* inner);
// public System.Void .ctor()
// Offset: 0x1B351A4
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static SimpleAsyncResult::$$c__DisplayClass11_0* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<SimpleAsyncResult::$$c__DisplayClass11_0*, creationType>()));
}
}; // System.Net.SimpleAsyncResult/System.Net.<>c__DisplayClass11_0
#pragma pack(pop)
static check_size<sizeof(SimpleAsyncResult::$$c__DisplayClass11_0), 32 + sizeof(::System::Net::SimpleAsyncCallback*)> __System_Net_SimpleAsyncResult_$$c__DisplayClass11_0SizeCheck;
static_assert(sizeof(SimpleAsyncResult::$$c__DisplayClass11_0) == 0x28);
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::$RunWithLock$b__0
// Il2CppName: <RunWithLock>b__0
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::*)(::System::Net::SimpleAsyncResult*)>(&System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::$RunWithLock$b__0)> {
static const MethodInfo* get() {
static auto* inner = &::il2cpp_utils::GetClassFromName("System.Net", "SimpleAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::SimpleAsyncResult::$$c__DisplayClass11_0*), "<RunWithLock>b__0", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inner});
}
};
// Writing MetadataGetter for method: System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::$RunWithLock$b__1
// Il2CppName: <RunWithLock>b__1
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::*)(::System::Net::SimpleAsyncResult*)>(&System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::$RunWithLock$b__1)> {
static const MethodInfo* get() {
static auto* inner = &::il2cpp_utils::GetClassFromName("System.Net", "SimpleAsyncResult")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(System::Net::SimpleAsyncResult::$$c__DisplayClass11_0*), "<RunWithLock>b__1", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{inner});
}
};
// Writing MetadataGetter for method: System::Net::SimpleAsyncResult::$$c__DisplayClass11_0::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
| 52.162393 | 247 | 0.720957 | RedBrumbler |
a31fd9b3c3314742f183f1cff978de2151256284 | 2,178 | cpp | C++ | icp/BlockEditor/port.cpp | vmarcin/FIT-projects | 69e3e0f1f271aefd3135f92a681738a4f1a24395 | [
"MIT"
] | null | null | null | icp/BlockEditor/port.cpp | vmarcin/FIT-projects | 69e3e0f1f271aefd3135f92a681738a4f1a24395 | [
"MIT"
] | null | null | null | icp/BlockEditor/port.cpp | vmarcin/FIT-projects | 69e3e0f1f271aefd3135f92a681738a4f1a24395 | [
"MIT"
] | null | null | null | /**
* @file port.cpp
* @brief Port implementation
* @author Matúš Liščinský xlisci02, Marcin Vladimír xmarci10
*/
#include "port.h"
/**
* @brief Port constructor
*/
Port::Port()
{
this->connected_to=NULL;
}
/**
* @brief Instert complex number to map
* @param real real part of complex number
* @param imaginary imaginary part of complex number
*/
void Port::setComplex(double real, double imaginary){
this->setReal(real);
this->setImaginary(imaginary);
}
/**
* @brief Add new item to port type
* @param new item
*/
void Port::addTypeKey(std::string key){
this->keys.push_back(key);
}
/**
* @brief Insert real part of complex number to map
* @param real part which will be set
*/
void Port::setReal(double real){
this->m.insert(std::make_pair("real", real));
}
/**
* @brief Insert imaginary part of complex number to map
* @param imaginary part which will be set
*/
void Port::setImaginary(double imaginary){
this->m.insert(std::make_pair("im", imaginary));
}
/**
* @brief Set polar form of complex number to map
* @param magnitude magnitude part of polar form
* @param phase_angle phase part of polar form
*/
void Port::setPolar(double magnitude, double phase_angle){
this->m.insert(std::make_pair("magnitude", magnitude));
this->m.insert(std::make_pair("angle", phase_angle));
}
/**
* @brief Convert map contain to string
* @return return created string
*/
std::string Port::mapToString(){
std::string result;
if(this->m.empty()){
for(auto &x : this->keys){
result.append(" ");
result.append(x);
result.append(": -\n");
}
return result.substr(0,result.size()-1);
}
for(auto &x : this->m){
result.append(" ");
result.append(x.first);
result.append(": ");
// zaokruhlenie
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << x.second;
std::string val = stream.str();
result.append(val);
result.append("\n");
}
return result.substr(0,result.size()-1);
}
| 25.034483 | 66 | 0.605142 | vmarcin |
a31ff1002e10a9fc2080d1d0259ded8a332b8518 | 39,397 | cpp | C++ | Data/Juliet-C/Juliet-C-v102/testcases/CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime/main.cpp | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-C/Juliet-C-v102/testcases/CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime/main.cpp | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | Data/Juliet-C/Juliet-C-v102/testcases/CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime/main.cpp | b19e93n/PLC-Pyramid | 6d5b57be6995a94ef7402144cee965862713b031 | [
"MIT"
] | null | null | null | /* NOTE - eventually this file will be automatically updated using a Perl script that understand
* the naming of test case files, functions, and namespaces.
*/
#include <time.h> /* for time() */
#include <stdlib.h> /* for srand() */
#include "std_testcase.h"
#include "testcases.h"
int main(int argc, char * argv[]) {
/* seed randomness */
srand( (unsigned)time(NULL) );
global_argc = argc;
global_argv = argv;
#ifndef OMITGOOD
/* Calling C good functions */
/* BEGIN-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_01_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_01_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_02_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_02_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_03_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_03_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_04_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_04_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_05_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_05_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_06_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_06_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_07_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_07_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_08_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_08_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_09_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_09_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_10_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_10_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_11_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_11_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_12_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_12_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_13_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_13_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_14_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_14_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_15_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_15_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_16_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_16_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_17_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_17_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_18_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_18_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_19_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_19_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_01_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_01_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_02_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_02_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_03_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_03_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_04_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_04_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_05_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_05_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_06_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_06_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_07_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_07_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_08_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_08_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_09_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_09_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_10_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_10_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_11_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_11_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_12_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_12_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_13_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_13_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_14_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_14_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_15_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_15_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_16_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_16_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_17_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_17_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_18_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_18_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_19_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_19_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_01_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_01_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_02_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_02_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_03_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_03_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_04_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_04_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_05_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_05_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_06_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_06_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_07_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_07_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_08_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_08_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_09_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_09_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_10_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_10_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_11_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_11_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_12_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_12_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_13_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_13_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_14_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_14_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_15_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_15_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_16_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_16_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_17_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_17_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_18_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_18_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_19_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_19_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_01_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_01_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_02_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_02_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_03_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_03_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_04_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_04_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_05_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_05_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_06_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_06_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_07_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_07_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_08_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_08_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_09_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_09_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_10_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_10_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_11_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_11_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_12_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_12_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_13_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_13_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_14_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_14_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_15_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_15_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_16_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_16_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_17_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_17_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_18_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_18_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_19_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_19_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_01_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_01_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_02_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_02_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_03_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_03_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_04_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_04_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_05_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_05_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_06_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_06_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_07_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_07_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_08_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_08_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_09_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_09_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_10_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_10_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_11_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_11_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_12_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_12_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_13_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_13_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_14_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_14_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_15_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_15_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_16_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_16_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_17_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_17_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_18_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_18_good();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_19_good();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_19_good();
/* END-AUTOGENERATED-C-GOOD-FUNCTION-CALLS */
#ifdef __cplusplus
/* Calling C++ good functions */
/* BEGIN-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */
/* END-AUTOGENERATED-CPP-GOOD-FUNCTION-CALLS */
#endif /* __cplusplus */
#endif /* OMITGOOD */
#ifndef OMITBAD
/* Calling C bad functions */
/* BEGIN-AUTOGENERATED-C-BAD-FUNCTION-CALLS */
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_01_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_01_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_02_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_02_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_03_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_03_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_04_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_04_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_05_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_05_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_06_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_06_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_07_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_07_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_08_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_08_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_09_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_09_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_10_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_10_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_11_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_11_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_12_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_12_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_13_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_13_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_14_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_14_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_15_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_15_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_16_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_16_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_17_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_17_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_18_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_18_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_19_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_bind_listen_19_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_01_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_01_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_02_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_02_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_03_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_03_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_04_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_04_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_05_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_05_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_06_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_06_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_07_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_07_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_08_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_08_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_09_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_09_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_10_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_10_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_11_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_11_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_12_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_12_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_13_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_13_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_14_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_14_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_15_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_15_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_16_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_16_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_17_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_17_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_18_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_18_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_19_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__accept_listen_bind_19_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_01_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_01_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_02_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_02_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_03_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_03_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_04_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_04_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_05_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_05_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_06_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_06_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_07_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_07_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_08_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_08_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_09_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_09_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_10_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_10_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_11_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_11_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_12_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_12_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_13_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_13_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_14_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_14_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_15_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_15_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_16_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_16_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_17_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_17_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_18_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_18_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_19_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__bind_accept_listen_19_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_01_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_01_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_02_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_02_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_03_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_03_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_04_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_04_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_05_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_05_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_06_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_06_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_07_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_07_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_08_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_08_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_09_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_09_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_10_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_10_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_11_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_11_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_12_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_12_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_13_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_13_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_14_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_14_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_15_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_15_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_16_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_16_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_17_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_17_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_18_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_18_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_19_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_accept_bind_19_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_01_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_01_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_02_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_02_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_03_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_03_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_04_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_04_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_05_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_05_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_06_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_06_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_07_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_07_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_08_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_08_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_09_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_09_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_10_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_10_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_11_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_11_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_12_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_12_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_13_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_13_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_14_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_14_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_15_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_15_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_16_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_16_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_17_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_17_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_18_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_18_bad();
printLine("Calling CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_19_bad();");
CWE666_Operation_on_Resource_in_Wrong_Phase_of_Lifetime__listen_bind_accept_19_bad();
/* END-AUTOGENERATED-C-BAD-FUNCTION-CALLS */
#ifdef __cplusplus
/* Calling C++ bad functions */
/* BEGIN-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */
/* END-AUTOGENERATED-CPP-BAD-FUNCTION-CALLS */
#endif /* __cplusplus */
#endif /* OMITBAD */
return 0;
}
| 62.238547 | 110 | 0.892657 | b19e93n |
a3209886efc315f89493c2ee1a487458965182fa | 2,196 | hpp | C++ | geo/po.hpp | ExploreWilder/libgeo | 118ba7f527cbfb5fc6b600495208c1c7d4178414 | [
"BSD-2-Clause"
] | 1 | 2019-11-17T11:47:27.000Z | 2019-11-17T11:47:27.000Z | externals/browser/externals/browser/externals/libgeo/geo/po.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 1 | 2021-01-07T03:37:34.000Z | 2021-01-08T03:33:51.000Z | externals/browser/externals/browser/externals/libgeo/geo/po.hpp | HanochZhu/vts-browser-unity-plugin | 32a22d41e21b95fb015326f95e401d87756d0374 | [
"BSD-2-Clause"
] | 2 | 2019-09-25T05:22:02.000Z | 2021-02-14T14:10:03.000Z | /**
* Copyright (c) 2017 Melown Technologies SE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef geo_po_hpp_included_
#define geo_po_hpp_included_
#include <string>
#include <vector>
#include <boost/program_options.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include "srsdef.hpp"
namespace geo {
inline void validate(boost::any &v
, const std::vector<std::string> &values
, SrsDefinition*, int)
{
namespace po = boost::program_options;
namespace ba = boost::algorithm;
po::validators::check_first_occurrence(v);
auto srs(SrsDefinition::fromString
(po::validators::get_single_string(values)));
if (srs.empty()) {
throw po::validation_error(po::validation_error::invalid_option_value);
}
// ok
v = boost::any(srs);
}
} // namespace geo
#endif // geo_po_hpp_included_
| 35.419355 | 79 | 0.729964 | ExploreWilder |
a320b15e86086b1e0bb832f591301d234fe314d6 | 523 | cpp | C++ | source/ItemRocket.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | 1 | 2016-08-15T16:11:40.000Z | 2016-08-15T16:11:40.000Z | source/ItemRocket.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | null | null | null | source/ItemRocket.cpp | fgrehm/pucrs-doom2d | edea7d5d762f427a5a8c944d36819009eb514429 | [
"MIT"
] | null | null | null |
#include "ItemRocket.h"
ItemRocket::ItemRocket(int _x, int _y):
x(_x),
y(_y)
{
sprite = new cgf::Sprite();
sprite->load("data/img/rocket.png");
sprite->scale(1.2, 1.2);
sf::Vector2f vpos = sf::Vector2f();
vpos.x = x;
vpos.y = y;
sprite->setPosition(vpos);
}
ItemRocket::~ItemRocket(){
if (sprite){
delete sprite;
}
}
void ItemRocket::visit(Inventory *iv) {
iv->refillRocketLauncher(1);
}
void ItemRocket::draw(cgf::Game* game){
game->getScreen()->draw(*sprite);
}
| 16.34375 | 40 | 0.602294 | fgrehm |
a321d9f446d98819bfdb96a0c0f06b204ad73d0b | 767 | cpp | C++ | HackerEarth/Number Theory/Basics/expmodulo.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | 1 | 2022-03-25T10:20:25.000Z | 2022-03-25T10:20:25.000Z | HackerEarth/Number Theory/Basics/expmodulo.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | null | null | null | HackerEarth/Number Theory/Basics/expmodulo.cpp | hendry19901990/AlgorithmsUnlocked | e85b6dea4b3aea9b8015db24384b1527d828395d | [
"Xnet",
"X11"
] | null | null | null | #include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <limits>
#include <string.h>
using namespace std;
typedef long long int ll ;
ll expmodulo(ll a, ll b, ll mod)
{
if(a == 0 || b == 0 || a < 0 || b < 0) return 0;
else if(b == 0) return 1;
else if(b == 1) return a % mod;
else if(b&1) return (a * expmodulo(a * a, b>>1, mod) % mod); // No Overflow.
else {
return expmodulo(a * a, b>>1, mod);
}
}
int main(int argc, char *argv[])
{
if(argc < 3)
{
cout << "Enter the base, power & mod-num : [b,pb,md] " << endl;
return -1;
}
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int mod = atoi(argv[3]);
cout << "Exponent Modulo is : " << expmodulo(a,b,mod) << endl;
return 0;
} | 25.566667 | 80 | 0.529335 | hendry19901990 |
a324b0a39da5ae987baf61cc4429f2866caecd8e | 9,059 | cpp | C++ | ouzel/graphics/opengl/ShaderOGL.cpp | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | ouzel/graphics/opengl/ShaderOGL.cpp | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | ouzel/graphics/opengl/ShaderOGL.cpp | keima97/ouzel | e6673e678b4739235371a15ae3863942b692c5fb | [
"BSD-2-Clause"
] | null | null | null | // Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.
#include "ShaderOGL.h"
#include "core/Engine.h"
#include "RendererOGL.h"
#include "files/FileSystem.h"
#include "utils/Log.h"
namespace ouzel
{
namespace graphics
{
ShaderOGL::ShaderOGL()
{
}
ShaderOGL::~ShaderOGL()
{
if (programId)
{
RendererOGL::deleteResource(programId, RendererOGL::ResourceType::Program);
}
if (vertexShaderId)
{
RendererOGL::deleteResource(vertexShaderId, RendererOGL::ResourceType::Shader);
}
if (pixelShaderId)
{
RendererOGL::deleteResource(pixelShaderId, RendererOGL::ResourceType::Shader);
}
}
void ShaderOGL::free()
{
Shader::free();
pixelShaderConstantLocations.clear();
vertexShaderConstantLocations.clear();
if (programId)
{
RendererOGL::deleteResource(programId, RendererOGL::ResourceType::Program);
programId = 0;
}
if (vertexShaderId)
{
RendererOGL::deleteResource(vertexShaderId, RendererOGL::ResourceType::Shader);
vertexShaderId = 0;
}
if (pixelShaderId)
{
RendererOGL::deleteResource(pixelShaderId, RendererOGL::ResourceType::Shader);
pixelShaderId = 0;
}
}
void ShaderOGL::printShaderMessage(GLuint shaderId)
{
GLint logLength = 0;
glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0)
{
std::vector<char> logMessage(static_cast<size_t>(logLength));
glGetShaderInfoLog(shaderId, logLength, nullptr, logMessage.data());
Log(Log::Level::ERR) << "Shader compilation error: " << logMessage.data();
}
}
void ShaderOGL::printProgramMessage()
{
GLint logLength = 0;
glGetProgramiv(programId, GL_INFO_LOG_LENGTH, &logLength);
if (logLength > 0)
{
std::vector<char> logMessage(static_cast<size_t>(logLength));
glGetProgramInfoLog(programId, logLength, nullptr, logMessage.data());
Log(Log::Level::ERR) << "Shader linking error: " << logMessage.data();
}
}
bool ShaderOGL::upload()
{
if (uploadData.dirty)
{
if (!pixelShaderId)
{
pixelShaderId = glCreateShader(GL_FRAGMENT_SHADER);
const GLchar* pixelShaderBuffer = reinterpret_cast<const GLchar*>(uploadData.pixelShaderData.data());
GLint pixelShaderSize = static_cast<GLint>(uploadData.pixelShaderData.size());
glShaderSource(pixelShaderId, 1, &pixelShaderBuffer, &pixelShaderSize);
glCompileShader(pixelShaderId);
GLint status;
glGetShaderiv(pixelShaderId, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
Log(Log::Level::ERR) << "Failed to compile pixel shader";
printShaderMessage(pixelShaderId);
return false;
}
if (RendererOGL::checkOpenGLError())
{
return false;
}
}
if (!vertexShaderId)
{
vertexShaderId = glCreateShader(GL_VERTEX_SHADER);
const GLchar* vertexShaderBuffer = reinterpret_cast<const GLchar*>(uploadData.vertexShaderData.data());
GLint vertexShaderSize = static_cast<GLint>(uploadData.vertexShaderData.size());
glShaderSource(vertexShaderId, 1, &vertexShaderBuffer, &vertexShaderSize);
glCompileShader(vertexShaderId);
GLint status;
glGetShaderiv(vertexShaderId, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE)
{
Log(Log::Level::ERR) << "Failed to compile vertex shader";
printShaderMessage(vertexShaderId);
return false;
}
}
if (!programId)
{
programId = glCreateProgram();
glAttachShader(programId, vertexShaderId);
glAttachShader(programId, pixelShaderId);
GLuint index = 0;
if (uploadData.vertexAttributes & VERTEX_POSITION)
{
glBindAttribLocation(programId, index, "in_Position");
++index;
}
if (uploadData.vertexAttributes & VERTEX_COLOR)
{
glBindAttribLocation(programId, index, "in_Color");
++index;
}
if (uploadData.vertexAttributes & VERTEX_NORMAL)
{
glBindAttribLocation(programId, index, "in_Normal");
++index;
}
if (uploadData.vertexAttributes & VERTEX_TEXCOORD0)
{
glBindAttribLocation(programId, index, "in_TexCoord0");
++index;
}
if (uploadData.vertexAttributes & VERTEX_TEXCOORD1)
{
glBindAttribLocation(programId, index, "in_TexCoord1");
++index;
}
glLinkProgram(programId);
GLint status;
glGetProgramiv(programId, GL_LINK_STATUS, &status);
if (status == GL_FALSE)
{
Log(Log::Level::ERR) << "Failed to link shader";
printProgramMessage();
return false;
}
if (RendererOGL::checkOpenGLError())
{
return false;
}
glDetachShader(programId, vertexShaderId);
glDeleteShader(vertexShaderId);
vertexShaderId = 0;
glDetachShader(programId, pixelShaderId);
glDeleteShader(pixelShaderId);
pixelShaderId = 0;
if (RendererOGL::checkOpenGLError())
{
return false;
}
RendererOGL::useProgram(programId);
GLint texture0Location = glGetUniformLocation(programId, "texture0");
if (texture0Location != -1) glUniform1i(texture0Location, 0);
GLint texture1Location = glGetUniformLocation(programId, "texture1");
if (texture1Location != -1) glUniform1i(texture1Location, 1);
if (RendererOGL::checkOpenGLError())
{
return false;
}
}
pixelShaderConstantLocations.clear();
pixelShaderConstantLocations.reserve(uploadData.pixelShaderConstantInfo.size());
for (const ConstantInfo& info : uploadData.pixelShaderConstantInfo)
{
GLint location = glGetUniformLocation(programId, info.name.c_str());
if (location == -1 || RendererOGL::checkOpenGLError())
{
Log(Log::Level::ERR) << "Failed to get OpenGL uniform location";
return false;
}
pixelShaderConstantLocations.push_back({ location, info.size });
}
vertexShaderConstantLocations.clear();
vertexShaderConstantLocations.reserve(uploadData.vertexShaderConstantInfo.size());
for (const ConstantInfo& info : uploadData.vertexShaderConstantInfo)
{
GLint location = glGetUniformLocation(programId, info.name.c_str());
if (location == -1 || RendererOGL::checkOpenGLError())
{
Log(Log::Level::ERR) << "Failed to get OpenGL uniform location";
return false;
}
vertexShaderConstantLocations.push_back({ location, info.size });
}
uploadData.dirty = false;
}
return true;
}
} // namespace graphics
} // namespace ouzel
| 34.842308 | 123 | 0.48725 | keima97 |
a325a79cfcd6b9e8bf4d890f77532e9828eb62cd | 1,446 | cpp | C++ | src/GL.cpp | neo-bolea/procedurally | 449d583dc09f3779617490b26d4af469b31ec414 | [
"MIT"
] | 4 | 2019-11-19T17:05:44.000Z | 2020-03-30T20:09:53.000Z | src/GL.cpp | neo-bolea/procedurally | 449d583dc09f3779617490b26d4af469b31ec414 | [
"MIT"
] | 5 | 2019-12-07T18:07:30.000Z | 2020-03-23T10:47:41.000Z | src/GL.cpp | neo-bolea/procedurally | 449d583dc09f3779617490b26d4af469b31ec414 | [
"MIT"
] | null | null | null | #include "Graphics/GL.h"
#include "Common/Debug.h"
#include "Graphics/MathGL.h"
#include "Graphics/Shader.h"
#include <GL/glew.h>
#define NOMINMAX
#include <fstream>
#include <Shlwapi.h>
#pragma comment(lib,"shlwapi.lib")
namespace GL
{
void GLAPIENTRY
ErrorCallback( GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar* message,
const void* userParam )
{
if(type != GL_DEBUG_TYPE_ERROR) { return; }
Debug::Log(std::string("OpenGL: ")
+ "Type = " + std::to_string(type)
+ ", Severity = " + std::to_string(severity)
+ ", " + (char *)message, Debug::Error, { "Graphics" });
}
#undef StaticGLGetInteger
#define StaticGLGetInteger(name, handle) \
int name() \
{ \
static int name = -1; \
if(name == -1) \
{ glGetIntegerv(handle, &name); } \
return name; \
}
StaticGLGetInteger(TextureMaxSize, GL_MAX_TEXTURE_SIZE)
StaticGLGetInteger(Texture3DMaxSize, GL_MAX_3D_TEXTURE_SIZE)
}
namespace GLHelper
{
uint CreateUBO(uint bindingPoint, uint size, GL::DrawType drawType)
{
uint ubo;
glGenBuffers(1, &ubo);
glBindBuffer(GL_UNIFORM_BUFFER, ubo);
glBufferData(GL_UNIFORM_BUFFER, size, NULL, (int)drawType);
glBindBufferBase(GL_UNIFORM_BUFFER, bindingPoint, ubo);
return ubo;
}
void BindUBOData(uint offset, uint size, void *data)
{ glBufferSubData(GL_UNIFORM_BUFFER, offset, size, data); }
} | 22.59375 | 68 | 0.670816 | neo-bolea |
a326f975e214f4cd3eef9d9b481d2e5a85c75595 | 381 | hpp | C++ | include/unicy/has_insertion_operator.hpp | quantumsheep/unicy | 7109b2e99e3853b802e1952ac4bf07dcbcd43978 | [
"MIT"
] | 1 | 2020-07-16T18:42:30.000Z | 2020-07-16T18:42:30.000Z | include/unicy/has_insertion_operator.hpp | quantumsheep/unicy | 7109b2e99e3853b802e1952ac4bf07dcbcd43978 | [
"MIT"
] | null | null | null | include/unicy/has_insertion_operator.hpp | quantumsheep/unicy | 7109b2e99e3853b802e1952ac4bf07dcbcd43978 | [
"MIT"
] | 1 | 2020-07-16T18:46:49.000Z | 2020-07-16T18:46:49.000Z | #pragma once
#include <iostream>
#include <type_traits>
#include <utility>
namespace Unicy
{
template <typename Ty, typename = void>
struct has_insertion_operator : std::false_type
{
};
template <typename Ty>
struct has_insertion_operator<
Ty,
std::void_t<decltype(std::declval<std::ostream &>() << std::declval<Ty>())>>
: std::true_type
{
};
} // namespace Unicy
| 15.875 | 80 | 0.695538 | quantumsheep |
a327bcae9393442faf5bfdab23a9f538f30cfab3 | 718 | cpp | C++ | Data-Structures/Queue/tests/tests.cpp | HetDaftary/Data-Structures-and-Algorithms | 716f7c3d6225188e15be856e46dad9d7ef76a4ba | [
"MIT"
] | 1 | 2020-10-10T10:26:16.000Z | 2020-10-10T10:26:16.000Z | Data-Structures/Queue/tests/tests.cpp | HetDaftary/Data-Structures-and-Algorithms | 716f7c3d6225188e15be856e46dad9d7ef76a4ba | [
"MIT"
] | null | null | null | Data-Structures/Queue/tests/tests.cpp | HetDaftary/Data-Structures-and-Algorithms | 716f7c3d6225188e15be856e46dad9d7ef76a4ba | [
"MIT"
] | null | null | null | #if defined(_WIN32) || defined(_WIN64) || (defined(__CYGWIN__) && !defined(_WIN32)) // Windows uses a different system for path names.
#include "..\includer.hpp"
#else
#include "../includer.hpp"
#endif
int main() {
// Without fixed size.
Queue<int, false> qu;
for (int i = 0; i < 5; i++) {
qu.enqueue(i);
qu.displayQueue(cout);
}
while (!qu.isEmpty()) {
qu.dequeue();
qu.displayQueue(cout);
}
// With Fixed Size.
Queue<int, true> qu1(5);
for (int i = 0; i < 5; i++) {
qu1.enqueue(i);
qu1.displayQueue(cout);
}
while (!qu1.isEmpty()) {
qu1.dequeue();
qu1.displayQueue(cout);
}
return 0;
} | 21.757576 | 135 | 0.530641 | HetDaftary |
a32846cdfeefc5f63c158d789962d8646e0f2b3f | 5,461 | cpp | C++ | 2course/Programming/examples/2018_2019/lecture_9_10_1903_01to15_1st.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 9 | 2017-04-03T08:52:58.000Z | 2020-06-05T18:25:02.000Z | 2course/Programming/examples/2018_2019/lecture_9_10_1903_01to15_1st.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 6 | 2018-02-07T18:26:27.000Z | 2021-09-02T04:46:06.000Z | 2course/Programming/examples/2018_2019/lecture_9_10_1903_01to15_1st.cpp | posgen/OmsuMaterials | 6132fe300154db97327667728c4cf3b0e19420e6 | [
"Unlicense"
] | 10 | 2018-11-12T18:18:47.000Z | 2020-06-06T06:17:01.000Z | #include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
#include <algorithm>
#include <random>
#include <ctime>
using namespace std;
double rand_a_b(double a, double b)
{
static mt19937_64 gnr{ time(nullptr) };
static const size_t max_gnr = gnr.max();
return a + (b - a) * ( double(gnr()) / max_gnr );
}
/**
Задумка для собственного типа данных: релализовать динамический массив
действительных чисел с возможностью положительных и отрицательных индексов.
Пример массива: [ 10.5, 5.6, -9.3, 11.1, 0.567 ]
'+' индексы: 0 1 2 3 4
'-' индексы: -5 -4 -3 -2 -1
Условия на создаваемый тип:
- создание массива заданной размерности;
- создание массива заданной размерности и заполнение каждого элемента
конкретным значением;
- нет проверки выхода индекса массива за его границы;
*/
class DynArray1D
{
public:
/**
Конструктор с одним параметром:
создаёт динамический массив на число элементов,
заданных значением параметра *array_size*.
*/
DynArray1D(size_t array_size);
/**
Конструктор с двумя параметрами:
создаёт динамический массив на число элементов,
заданных значением параметра *array_size* и
каждому элементу присваивает значение *value*.
*/
DynArray1D(size_t array_size, double value);
/**
Конструктор копий:
создаёт копию другого динамического массива типа DynArray1D.
Нужен для предотвращения копирования по умолчанию, когда в разные
переменные-объекты данного типа попадают адреса одного и того же
блока динамической памяти.
*/
DynArray1D(const DynArray1D& other);
/**
Деструктор:
автоматически удаляет динамическую память, когда перемнная
данного класса выходит из области видимости.
*/
~DynArray1D();
/// Методы класса
/// Узнать длину конкретного объекта данного типа
size_t length() const;
/// Узнать ёмкость конкретного объекта данного типа
size_t capacity() const;
/// Перегруженные операторы
/**
Оператор "квадратные скобки" используется для обращения к элементам
массива по положительному или отрицательному индексу.
Возращает ссылку на конкретный элемент.
*/
double& operator[](int index);
/**
Оператор "<<" перегружен для добавления элементов в конкретный массив.
*/
DynArray1D& operator<<(double value);
/// Оператор присваивания - перегружен для правильно копирования одного объекта массива в другой.
void operator=(const DynArray1D& other);
private:
/**
Поля класса DynArray1D.
- _arr - указатель, использующийся для хранения элементов массива;
- _length - текущая длина массива;
- _capacity - текущая ёмкость массива, т.е. количество элементов
типа double, которые уже выделены в виде динамической памяти.
Для каждого из полей указаны значения по умолчанию.
*/
double *_arr = nullptr;
size_t _length = 0;
size_t _capacity = 0;
};
int main()
{
DynArray1D vec{10, 4.5};
cout << vec.length() << endl;
vec[-4] = 15.0;
vec << 3.7 << 6.8 << 9.88 << 33.33323;
for (size_t i = 0; i < vec.length(); i++) {
cout << vec[i] << ' ';
}
cout << endl;
DynArray1D another_array{2};
another_array = vec;
for (size_t i = 0; i < another_array.length(); i++) {
cout << another_array[i] << ' ';
}
cout << endl;
}
/// Определение конструкторов и деструктора:
DynArray1D::DynArray1D(size_t array_size)
{
_arr = new double[array_size];
_length = _capacity = array_size;
}
DynArray1D::DynArray1D(size_t array_size, double value)
{
_arr = new double[array_size];
_length = _capacity = array_size;
for (size_t i = 0; i < _length; i++) {
_arr[i] = value;
}
}
DynArray1D::DynArray1D(const DynArray1D& other)
{
cout << "Copy ctor" << endl;
_length = other._length;
_capacity = other._capacity;
_arr = new double[_capacity];
for (size_t i = 0; i < _length; i++)
{
_arr[i] = other._arr[i];
}
}
~DynArray1D()
{
delete[] _arr;
}
/// Определение методов-класса:
size_t DynArray1D::length() const
{
return _length;
}
size_t DynArray1D::capacity() const
{
return _capacity;
}
double& DynArray1D::operator[](int index)
{
if (index >= 0) {
return _arr[index];
}
return _arr[_length + index];
}
DynArray1D& DynArray1D::operator<<(double value)
{
if (_capacity == 0) {
_capacity = 8;
_arr = new double[_capacity];
_arr[0] = value;
_length++;
return *this;
}
if (_capacity == _length) {
double *ptr = new double[2 * _capacity];
_capacity *= 2;
for (size_t i = 0; i < _length; i++) {
ptr[i] = _arr[i];
}
ptr[_length] = value;
_length++;
delete[] _arr;
_arr = ptr;
return *this;
}
_arr[_length] = value;
_length++;
return *this;
}
void DynArray1D::operator=(const DynArray1D& other)
{
cout << "Operator= called" << endl;
delete[] _arr;
_length = other._length;
_capacity = other._capacity;
_arr = new double[_capacity];
for (size_t i = 0; i < _length; i++)
{
_arr[i] = other._arr[i];
}
}
| 23.640693 | 101 | 0.609412 | posgen |
cd142dd2813a41ecc952d1b0b8c6f299d6ec04b9 | 278 | cc | C++ | OnlineDB/CSCCondDB/test/stubs/CSCChamberMapPopConAnalyzer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-24T19:10:26.000Z | 2019-02-19T11:45:32.000Z | OnlineDB/CSCCondDB/test/stubs/CSCChamberMapPopConAnalyzer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 3 | 2018-08-23T13:40:24.000Z | 2019-12-05T21:16:03.000Z | OnlineDB/CSCCondDB/test/stubs/CSCChamberMapPopConAnalyzer.cc | nistefan/cmssw | ea13af97f7f2117a4f590a5e654e06ecd9825a5b | [
"Apache-2.0"
] | 5 | 2018-08-21T16:37:52.000Z | 2020-01-09T13:33:17.000Z | #include "CondCore/PopCon/interface/PopConAnalyzer.h"
#include "CSCChamberMapHandler.h"
#include "FWCore/Framework/interface/MakerMacros.h"
typedef popcon::PopConAnalyzer<popcon::CSCChamberMapImpl> CSCChamberMapPopConAnalyzer;
DEFINE_FWK_MODULE(CSCChamberMapPopConAnalyzer);
| 30.888889 | 86 | 0.852518 | nistefan |
cd165cb5ba7a1c9856c9d5e9fe5a555d9f5cf20b | 14,800 | cpp | C++ | Client/userlist.cpp | alice-create/O-Chat | fea0ebe0f19cfeaca068468b87684e2421ad5700 | [
"Apache-2.0"
] | null | null | null | Client/userlist.cpp | alice-create/O-Chat | fea0ebe0f19cfeaca068468b87684e2421ad5700 | [
"Apache-2.0"
] | null | null | null | Client/userlist.cpp | alice-create/O-Chat | fea0ebe0f19cfeaca068468b87684e2421ad5700 | [
"Apache-2.0"
] | null | null | null | #include "userlist.h"
#include "ui_userlist.h"
#include "info.h"
#include "addfriend.h"
userlist::userlist(QWidget *parent) :
QWidget(parent),
ui(new Ui::userlist)
{
ui->setupUi(this);
// sock = new QTcpSocket(this);
// lists = ui -> listWidget;
// person = new user();
// QListWidgetItem *itemN = new QListWidgetItem();
// lists -> addItem(itemN);
// lists -> setItemWidget(itemN, person);
// QString IP = "192.168.43.143";
// quint16 port = 1023;
// sock->connectToHost(IP, port);
// connect(sock, SIGNAL(connected()), this, SLOT(slot_connected()));
}
userlist::userlist(QTcpSocket *socket,QString id, QString name, quint16 People, QStringList IDList, QStringList NameList, QStringList onList, QWidget *parent) :
QWidget(parent),
ui(new Ui::userlist)
{
ui->setupUi(this);
// this->setWindowFlags(Qt::FramelessWindowHint);
sock = socket;
lists = ui -> listWidget; //框架
/*生成个人信息*/
off = ui -> pushButton_2;
myname = ui -> label;
myID = ui -> label_2;
off -> setText("Off-Line");
mID = id;
mName = name;
myID -> setText("ID:" + mID);
myname -> setText(mName);
/*好友列表*/
people = People;
IDlist = IDList;
Namelist = NameList;
onlist = onList;
initList();
/*重要:设置QListWidget的contextMenuPolicy属性,不然不能显示右键菜单*/
ui -> widget -> setProperty("contextMenuPolicy", Qt::CustomContextMenu);
/*初始化一个包含rename的菜单*/
menu = new QMenu(this);
rename = new QAction(tr("Config Username"), this);
menu -> addAction(rename);
/*绑定右键显示菜单:在单击右键之后会执行槽函数, 槽函数中负责弹出右键菜单*/
connect(this, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(on_widget_customContextMenuRequested(const QPoint &pos)));
/*为菜单上的Delete选项添加响应函数*/
connect(this -> rename, SIGNAL(triggered()), this, SLOT(slot_changename()));
connect(sock, SIGNAL(readyRead()), this, SLOT(slot_recvmessage()));
}
userlist::~userlist()
{
delete ui;
}
void userlist::on_pushButton_clicked()
{
QString b_id = ui -> lineEdit -> text();
QString id = mID;
QString sendData = "#04|" + id + "|" + b_id;
qDebug() << sendData;
sock -> write(sendData.toUtf8());
}
void userlist::slot_recvmessage() {
QByteArray recvArray = sock -> readAll();
qDebug() << recvArray;
QString recvStr(recvArray);
qDebug() << recvStr;
QStringList recvList = recvStr.split("|");
if(recvList[0] == "#04") {//发送好友邀请
// qDebug() << recvStr;
if(recvList[1] == "0") {
info *information = new info(sock, "04", "0", "0");
information -> show();
}
else
{
if(recvList[2] == "0") {
info *information = new info(sock, "04", "1", "0");
information -> show();
}
if(recvList[2] == "1") {
info *information = new info(sock, "04", "1", "1");
information -> show();
}
if(recvList[2] == "2") {
info *information = new info(sock, "04", "1", "2");
information -> show();
}
}
}
if(recvList[0] == "###05") {//展示邀请
QStringList noList = recvList[0].split("###");
QString no = noList[1];
QString id = recvList[1];
QString b_id = recvList[2];
info *infomation = new info(sock, no, id, b_id);
infomation -> show();
}
if(recvList[0] == "###04")
{
QStringList noList = recvList[0].split("###");
QString no = noList[1];
QString id = recvList[1];
QString b_id = recvList[2];
addFriend *infomation = new addFriend(sock, no, id, b_id);
infomation -> show();
}
if(recvList[0] == "###07")//同意
{
qDebug() << "###07";
QStringList noList = recvList[0].split("###");
QString no = noList[1];
QString id = recvList[1];
QString b_id = recvList[2];
QString Name = recvList[3];
QString status = recvList[4];
people += 1;
IDlist.append(b_id);
Namelist.append(Name);
onlist.append(status);
person = new user(sock, mID, Name, b_id, status, false);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> addItem(itemN);
lists -> setItemWidget(itemN, person);
// info *infomation = new info(sock, no, id, b_id);
// infomation -> show();
}
if(recvList[0] == "###00")
//chatting
{
quint16 row = 0;
quint16 i = 0;
QString b_id = recvList[2];
QString is_chat = recvList[3];
QString s;
QString n;
if(is_chat == "0") {
for(i = 0; i < people; i++) {
if(IDlist[i] == b_id) {
row = i;
s = onlist[i];
n = Namelist[i];
if(s == "0") {
onlist.removeAt(row);
Namelist.removeAt(row);
IDlist.removeAt(row);
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
onlist.append(s);
Namelist.append(n);
IDlist.append(b_id);
person = new user(sock, mID, n, b_id, s, true);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> addItem(itemN);
lists -> setItemWidget(itemN, person);
break;
}
else {
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
person = new user(sock, mID, n, b_id, s, true);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> insertItem(row, itemN);
lists -> setItemWidget(itemN, person);
break;
}
}
}
}
else {
//传消息
chatwindow -> MainChatWin::send_tochat(recvStr);
}
}
if(recvList[0] == "#07") {//点开聊天框
if(recvList[1] == "1") {
info *information = new info(sock, "07", "1", "0");
information -> show();
} else {
quint16 i;
QString uID = recvList[2];
QString uName = recvList[3];
QString s;
for(i = 0; i < people; i++) {
if(IDlist[i] == uID) {
s = onlist[i];
break;
}
}
chatwindow = new MainChatWin(sock, mID, mName, uID, uName, s);
chatwindow -> show();
}
}
if(recvList[0] == "###03") {//好友申请
QString b_id = recvList[2];
QString have_info = recvList[3];
bool flag = false;
if(have_info == "0") flag = false;
else flag = true;
info *information = new info(sock, "###03", "0", b_id);
information -> show();
QString s = "0";
QString n;
quint16 row = 0;
quint16 i = 0;
for(i = 0; i < people; i++) {
if(IDlist[i] == b_id) {
row = i;
n = Namelist[i];
if(s == "0") {
onlist.removeAt(row);
Namelist.removeAt(row);
IDlist.removeAt(row);
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
onlist.append("0");
Namelist.append(n);
IDlist.append(b_id);
person = new user(sock, mID, n, b_id, s, flag);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> addItem(itemN);
lists -> setItemWidget(itemN, person);
break;
}
}
}
}
if(recvList[0] == "###02") {//下线
qDebug() << "###02";
QString b_id = recvList[2];
QString have_info = recvList[3];
bool flag = false;
if(have_info == "0") flag = false;
else flag = true;
info *information = new info(sock, "###02", "0", b_id);
information -> show();
QString s = "1";
QString n;
quint16 row = 0;
quint16 i = 0;
for(i = 0; i < people; i++) {
qDebug() << "i:" << i;
if(IDlist[i] == b_id) {
row = i;
n = Namelist[i];
if(s == "1") {
onlist[i] = "1";
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
person = new user(sock, mID, n, b_id, s, flag);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> insertItem(row, itemN);
lists -> setItemWidget(itemN, person);
break;
}
}
}
}
if(recvList[0] == "#14") {//删除好友
QString if_success = recvList[1];
QString b_id = recvList[2];
if(if_success == "0") {
info *information = new info(sock, "#14", "0", "0");
information -> show();
QString n;
quint16 row = 0;
quint16 i = 0;
for(i = 0; i < people; i++) {
if(IDlist[i] == b_id) {
row = i;
n = Namelist[i];
onlist.removeAt(row);
Namelist.removeAt(row);
IDlist.removeAt(row);
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
people -= 1;
break;
}
}
}
else {
info * information = new info(sock, "#14", "1", "0");
information -> show();
}
}
if(recvList[0] == "#11") {//修改备注
QString is_success = recvList[1];
QString id = recvList[2];
QString nickname = recvList[3];
QString s;
QString is_info = recvList[4];
bool flag = false;
if(is_info == "0") flag = false;
else flag = true;
if(is_success == "0") {
info *information = new info(sock, "11", "0", "0");
information -> show();
for(quint16 i = 0; i < people; i++) {
if(IDlist[i] == id) {
Namelist[i] = nickname;
s = onlist[i];
QListWidgetItem* item = lists -> takeItem(i);
lists -> removeItemWidget(item);
person = new user(sock, mID, nickname, id, s, flag);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> insertItem(i, itemN);
lists -> setItemWidget(itemN, person);
break;
}
}
} else {
info *information = new info(sock, "11", "1", "0");
information -> show();
}
}
if(recvList[0] == "#12") {//修改昵称
QString is_success = recvList[1];
if(is_success == "0") {
info *information = new info(sock, "12", "0", "0");
information -> show();
QString newname = recvList[4];
myname -> setText(newname);
} else {
QString errortype = recvList[2];
if(errortype == "0") {
info *information = new info(sock, "12", "1", "0");
information -> show();
}
if(errortype == "1") {
info *information = new info(sock, "12", "1", "1");
information -> show();
}
if(errortype == "2") {
info *information = new info(sock, "12", "1", "2");
information -> show();
}
}
}
if(recvList[0] == "###06") {
QString uid = recvList[2];
QString n;
quint16 row = 0;
quint16 i = 0;
for(i = 0; i < people; i++) {
if(IDlist[i] == uid) {
row = i;
n = Namelist[i];
onlist.removeAt(row);
Namelist.removeAt(row);
IDlist.removeAt(row);
QListWidgetItem* item = lists -> takeItem(row);
lists -> removeItemWidget(item);
people -= 1;
break;
}
}
}
if(recvList[0] == "#16") {//历史消息
chatwindow -> send_tochat(recvStr);
}
}
void userlist::initList() {
quint16 i;
for(i = 0; i < people; i++) {
QString Name = Namelist[i];
QString ID = IDlist[i];
QString status =onlist[i];
person = new user(sock, mID, Name, ID, status, false);
QListWidgetItem *itemN = new QListWidgetItem();
itemN -> setSizeHint(QSize(280, 80));
lists -> addItem(itemN);
lists -> setItemWidget(itemN, person);
}
}
void userlist::on_pushButton_2_clicked()
{
QString sendData = "#03|" + mID;
sock->write(sendData.toUtf8());
this -> close();
}
//修改名字
void userlist::slot_changename() {
configname *info = new configname(sock, mID, mName);
info -> show();
// QString nickname = info -> nickname;
// ui -> label -> setText(nickname);
}
void userlist::mousePressEvent(QMouseEvent *evt) {
mousePos = QPoint(evt -> x(), evt -> y());
}
void userlist::mouseReleaseEvent(QMouseEvent *evt) {
if(mousePos == QPoint(evt->x(), evt->y()) & evt -> button() & Qt::LeftButton)
{
emit clicked();
}
}
void userlist::on_widget_customContextMenuRequested(const QPoint &pos)
{
menu -> exec(QCursor::pos());
}
| 33.408578 | 160 | 0.45223 | alice-create |
cd169ab7115e1d4809405332afa37bb4d2241d55 | 1,176 | cpp | C++ | Plugins/org.blueberry.ui.qt/src/berrySelectionChangedEvent.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.ui.qt/src/berrySelectionChangedEvent.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/org.blueberry.ui.qt/src/berrySelectionChangedEvent.cpp | liu3xing3long/MITK-2016.11 | 385c506f9792414f40337e106e13d5fd61aa3ccc | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /*===================================================================
BlueBerry Platform
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.
This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.
See LICENSE.txt or http://www.mitk.org for details.
===================================================================*/
#include "berrySelectionChangedEvent.h"
#include "berryISelectionProvider.h"
namespace berry
{
SelectionChangedEvent::SelectionChangedEvent(
ISelectionProvider::Pointer source, ISelection::ConstPointer selection)
{
poco_assert(source.IsNotNull());
poco_assert(selection.IsNotNull());
this->source = source;
this->selection = selection;
}
ISelectionProvider::Pointer SelectionChangedEvent::GetSource() const
{
return source;
}
ISelection::ConstPointer SelectionChangedEvent::GetSelection() const
{
return selection;
}
ISelectionProvider::Pointer SelectionChangedEvent::GetSelectionProvider() const
{
return this->GetSource();
}
}
| 23.52 | 80 | 0.664966 | liu3xing3long |
cd1781c14ed9473225ed64a08227af44da19bd24 | 449 | hpp | C++ | lib/libCFG/include/CapstoneHelper.hpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | 14 | 2021-05-03T16:03:22.000Z | 2022-02-14T23:42:39.000Z | lib/libCFG/include/CapstoneHelper.hpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | 1 | 2021-09-27T12:01:33.000Z | 2021-09-27T12:01:33.000Z | lib/libCFG/include/CapstoneHelper.hpp | cyber-itl/citl-static-analysis | 32ef8e519dac1c6a49ff41d902a62df8f5a8e948 | [
"MIT"
] | null | null | null | #pragma once
#include <cstdint>
#include <tuple>
#include <vector>
#include "capstone/capstone.h"
std::tuple<cs_arch, cs_mode> map_triple_cs(uint32_t triple);
std::vector<uint64_t> get_imm_vals(const cs_insn &insn, cs_arch arch, uint32_t base_reg, uint64_t reg_val);
bool is_nop(cs_arch arch, cs_insn *insn);
bool is_pc_in_arm_ops(cs_arm arm_details);
bool is_lr_in_arm_ops(cs_arm arm_details);
unsigned rotr32(unsigned val, unsigned amt);
| 21.380952 | 107 | 0.781737 | cyber-itl |
cd1b8cc2ff02d9f9df983c15e2b9063567054ce4 | 4,999 | cc | C++ | chrome/browser/chromeos/extensions/document_scan/document_scan_api.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 575 | 2015-06-18T23:58:20.000Z | 2022-03-23T09:32:39.000Z | chrome/browser/chromeos/extensions/document_scan/document_scan_api.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 113 | 2015-05-04T09:58:14.000Z | 2022-01-31T19:35:03.000Z | chrome/browser/chromeos/extensions/document_scan/document_scan_api.cc | iridium-browser/iridium-browser | 907e31cf5ce5ad14d832796e3a7c11e496828959 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 52 | 2015-07-14T10:40:50.000Z | 2022-03-15T01:11:49.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/extensions/document_scan/document_scan_api.h"
#include <utility>
#include <vector>
#include "base/base64.h"
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "chrome/browser/ash/scanning/lorgnette_scanner_manager.h"
#include "chrome/browser/ash/scanning/lorgnette_scanner_manager_factory.h"
#include "content/public/browser/browser_context.h"
#include "third_party/cros_system_api/dbus/lorgnette/dbus-constants.h"
namespace extensions {
namespace api {
namespace {
// Error messages that can be included in a response when scanning fails.
constexpr char kUserGestureRequiredError[] =
"User gesture required to perform scan";
constexpr char kNoScannersAvailableError[] = "No scanners available";
constexpr char kUnsupportedMimeTypesError[] = "Unsupported MIME types";
constexpr char kScanImageError[] = "Failed to scan image";
constexpr char kVirtualPrinterUnavailableError[] =
"Virtual USB printer unavailable";
// The name of the virtual USB printer used for testing.
constexpr char kVirtualUSBPrinter[] = "DavieV Virtual USB Printer (USB)";
// The testing MIME type.
constexpr char kTestingMimeType[] = "testing";
// The PNG MIME type.
constexpr char kScannerImageMimeTypePng[] = "image/png";
// The PNG image data URL prefix of a scanned image.
constexpr char kPngImageDataUrlPrefix[] = "data:image/png;base64,";
} // namespace
DocumentScanScanFunction::DocumentScanScanFunction() = default;
DocumentScanScanFunction::~DocumentScanScanFunction() = default;
ExtensionFunction::ResponseAction DocumentScanScanFunction::Run() {
params_ = document_scan::Scan::Params::Create(*args_);
EXTENSION_FUNCTION_VALIDATE(params_.get());
if (!user_gesture())
return RespondNow(Error(kUserGestureRequiredError));
ash::LorgnetteScannerManagerFactory::GetForBrowserContext(browser_context())
->GetScannerNames(
base::BindOnce(&DocumentScanScanFunction::OnNamesReceived, this));
return did_respond() ? AlreadyResponded() : RespondLater();
}
void DocumentScanScanFunction::OnNamesReceived(
std::vector<std::string> scanner_names) {
if (scanner_names.empty()) {
Respond(Error(kNoScannersAvailableError));
return;
}
bool should_use_virtual_usb_printer = false;
if (params_->options.mime_types) {
std::vector<std::string>& mime_types = *params_->options.mime_types;
if (base::Contains(mime_types, kTestingMimeType)) {
should_use_virtual_usb_printer = true;
} else if (!base::Contains(mime_types, kScannerImageMimeTypePng)) {
Respond(Error(kUnsupportedMimeTypesError));
return;
}
}
// TODO(pstew): Call a delegate method here to select a scanner and options.
// The first scanner supporting one of the requested MIME types used to be
// selected. The testing MIME type dictates that the virtual USB printer
// should be used if available. Otherwise, since all of the scanners only
// support PNG, select the first scanner in the list.
std::string scanner_name;
if (should_use_virtual_usb_printer) {
if (!base::Contains(scanner_names, kVirtualUSBPrinter)) {
Respond(Error(kVirtualPrinterUnavailableError));
return;
}
scanner_name = kVirtualUSBPrinter;
} else {
scanner_name = scanner_names[0];
}
lorgnette::ScanSettings settings;
settings.set_color_mode(lorgnette::MODE_COLOR); // Hardcoded for now.
ash::LorgnetteScannerManagerFactory::GetForBrowserContext(browser_context())
->Scan(
scanner_name, settings, base::NullCallback(),
base::BindRepeating(&DocumentScanScanFunction::OnPageReceived, this),
base::BindOnce(&DocumentScanScanFunction::OnScanCompleted, this));
}
void DocumentScanScanFunction::OnPageReceived(std::string scanned_image,
uint32_t /*page_number*/) {
// Take only the first page of the scan.
if (!scan_data_.has_value()) {
scan_data_ = std::move(scanned_image);
}
}
void DocumentScanScanFunction::OnScanCompleted(
bool success,
lorgnette::ScanFailureMode /*failure_mode*/) {
// TODO(pstew): Enlist a delegate to display received scan in the UI and
// confirm that this scan should be sent to the caller. If this is a
// multi-page scan, provide a means for adding additional scanned images up to
// the requested limit.
if (!scan_data_.has_value() || !success) {
Respond(Error(kScanImageError));
return;
}
std::string image_base64;
base::Base64Encode(scan_data_.value(), &image_base64);
document_scan::ScanResults scan_results;
scan_results.data_urls.push_back(kPngImageDataUrlPrefix + image_base64);
scan_results.mime_type = kScannerImageMimeTypePng;
Respond(ArgumentList(document_scan::Scan::Results::Create(scan_results)));
}
} // namespace api
} // namespace extensions
| 35.707143 | 80 | 0.744549 | iridium-browser |
cd1ba70d97f48201fb4cad0a3bcfb145b041d3cb | 647 | cpp | C++ | SRCS/Sound.cpp | Dreinale/Bomberman_project | ed98d44f54906b1e3f7941b58d8e1493711f355b | [
"MIT"
] | 1 | 2021-07-12T21:59:28.000Z | 2021-07-12T21:59:28.000Z | SRCS/Sound.cpp | Dreinale/Bomberman_project | ed98d44f54906b1e3f7941b58d8e1493711f355b | [
"MIT"
] | null | null | null | SRCS/Sound.cpp | Dreinale/Bomberman_project | ed98d44f54906b1e3f7941b58d8e1493711f355b | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2021
** sound
** File description:
** soudn
*/
#include "Sound.hpp"
Zic::Zic(float *volume, int play_time, std::string path)
{
_play_time = play_time;
music = LoadMusicStream(path.c_str());
_volume = volume;
}
void Zic::play_music()
{
PlayMusicStream(music);
SetMusicVolume(music, *_volume);
}
void Zic::stop()
{
StopMusicStream(music);
}
void Zic::update()
{
UpdateMusicStream(music);
int timePlayed = GetMusicTimePlayed(music)/GetMusicTimeLength(music)*400;
if (_play_time != 0 && timePlayed > _play_time) StopMusicStream(music);
}
Zic::~Zic()
{
UnloadMusicStream(music);
}
| 15.780488 | 77 | 0.669243 | Dreinale |
cd1d14a8b2a9f623c969a7ac83bc5af4c5a425d4 | 732 | cpp | C++ | src/battery.cpp | Fanteria/bar-indicators | cdc19c80a0d6917be9ed2cdabe09e8a5c8e7b624 | [
"MIT"
] | null | null | null | src/battery.cpp | Fanteria/bar-indicators | cdc19c80a0d6917be9ed2cdabe09e8a5c8e7b624 | [
"MIT"
] | null | null | null | src/battery.cpp | Fanteria/bar-indicators | cdc19c80a0d6917be9ed2cdabe09e8a5c8e7b624 | [
"MIT"
] | null | null | null | #include<iostream>
#include<fstream>
#include<string>
std::string batteryStatus[] = {"", "", "", "", ""};
int main (int argc, char ** argv) {
if (argc != 3)
exit(1);
// Load percentage.
std::string line;
std::ifstream f(*(argv + 1));
std::getline(f, line);
f.close();
std::cout << line << " ";
int percentage = std::stoi(line);
// Load charging status.
std::ifstream statusFile(*(argv + 2));
std::getline(statusFile, line);
statusFile.close();
// Charging status icon.
if (line == "Charging")
std::cout << "";
else if (line == "Discharging")
std::cout << "";
std::cout << batteryStatus[percentage / 25] << std::endl;
return 0;
} | 22.181818 | 61 | 0.538251 | Fanteria |
cd1d1bb00f17e4b5cccd14584692d6c8100f57f1 | 13,350 | cpp | C++ | lgc/patch/PatchInitializeWorkgroupMemory.cpp | flygod1159/llpc | 58664d422f062ce29680f7ca40407cdf70944209 | [
"MIT"
] | 1 | 2022-01-13T16:44:16.000Z | 2022-01-13T16:44:16.000Z | lgc/patch/PatchInitializeWorkgroupMemory.cpp | flygod1159/llpc | 58664d422f062ce29680f7ca40407cdf70944209 | [
"MIT"
] | null | null | null | lgc/patch/PatchInitializeWorkgroupMemory.cpp | flygod1159/llpc | 58664d422f062ce29680f7ca40407cdf70944209 | [
"MIT"
] | null | null | null | /*
***********************************************************************************************************************
*
* Copyright (c) 2021-2021 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
/**
***********************************************************************************************************************
* @file PatchInitializeWorkgroupMemory.cpp
* @brief LLPC source file: contains declaration and implementation of class lgc::PatchInitializeWorkgroupMemory.
***********************************************************************************************************************
*/
#include "lgc/patch/PatchInitializeWorkgroupMemory.h"
#include "lgc/patch/ShaderInputs.h"
#include "lgc/state/PipelineShaders.h"
#include "lgc/state/PipelineState.h"
#include "lgc/util/BuilderBase.h"
#include "llvm/IR/IntrinsicsAMDGPU.h"
#define DEBUG_TYPE "lgc-patch-initialize-workgroup-memory"
using namespace lgc;
using namespace llvm;
static cl::opt<bool>
ForceInitWorkgroupMemory("force-init-workgroup-memory",
cl::desc("Force to initialize the workgroup memory with zero for internal use"),
cl::init(false));
namespace lgc {
// =====================================================================================================================
// Initializes static members.
char LegacyPatchInitializeWorkgroupMemory::ID = 0;
// =====================================================================================================================
// Pass creator, creates the pass of setting up the value for workgroup global variables.
ModulePass *createLegacyPatchInitializeWorkgroupMemory() {
return new LegacyPatchInitializeWorkgroupMemory();
}
// =====================================================================================================================
LegacyPatchInitializeWorkgroupMemory::LegacyPatchInitializeWorkgroupMemory() : ModulePass(ID) {
}
// =====================================================================================================================
// Executes this LLVM patching pass on the specified LLVM module.
//
// @param [in/out] module : LLVM module to be run on
// @returns : True if the module was modified by the transformation and false otherwise
bool LegacyPatchInitializeWorkgroupMemory::runOnModule(Module &module) {
PipelineState *pipelineState = getAnalysis<LegacyPipelineStateWrapper>().getPipelineState(&module);
PipelineShadersResult &pipelineShaders = getAnalysis<LegacyPipelineShaders>().getResult();
return m_impl.runImpl(module, pipelineShaders, pipelineState);
}
// =====================================================================================================================
// Executes this LLVM patching pass on the specified LLVM module.
//
// @param [in/out] module : LLVM module to be run on
// @param [in/out] analysisManager : Analysis manager to use for this transformation
// @returns : The preserved analyses (The analyses that are still valid after this pass)
PreservedAnalyses PatchInitializeWorkgroupMemory::run(Module &module, ModuleAnalysisManager &analysisManager) {
PipelineState *pipelineState = analysisManager.getResult<PipelineStateWrapper>(module).getPipelineState();
PipelineShadersResult &pipelineShaders = analysisManager.getResult<PipelineShaders>(module);
if (runImpl(module, pipelineShaders, pipelineState))
return PreservedAnalyses::none();
return PreservedAnalyses::all();
}
// =====================================================================================================================
// Executes this LLVM patching pass on the specified LLVM module.
//
// @param [in/out] module : LLVM module to be run on
// @param pipelineShaders : Pipeline shaders analysis result
// @param pipelineState : Pipeline state
// @returns : True if the module was modified by the transformation and false otherwise
bool PatchInitializeWorkgroupMemory::runImpl(Module &module, PipelineShadersResult &pipelineShaders,
PipelineState *pipelineState) {
LLVM_DEBUG(dbgs() << "Run the pass Patch-Initialize-Workgroup-Memory\n");
m_pipelineState = pipelineState;
// This pass works on compute shader.
if (!m_pipelineState->hasShaderStage(ShaderStageCompute))
return false;
SmallVector<GlobalVariable *> workgroupGlobals;
for (GlobalVariable &global : module.globals()) {
// The pass process the cases that the workgroup memory is forced to be initialized or the workgroup variable has an
// zero initializer
if (global.getType()->getPointerAddressSpace() == ADDR_SPACE_LOCAL &&
(ForceInitWorkgroupMemory || (global.hasInitializer() && global.getInitializer()->isNullValue())))
workgroupGlobals.push_back(&global);
}
if (workgroupGlobals.empty())
return false;
Patch::init(&module);
m_shaderStage = ShaderStageCompute;
m_entryPoint = pipelineShaders.getEntryPoint(static_cast<ShaderStage>(m_shaderStage));
BuilderBase builder(*m_context);
Instruction *insertPos = &*m_entryPoint->front().getFirstInsertionPt();
builder.SetInsertPoint(insertPos);
// Fill the map of each variable with zeroinitializer and calculate its corresponding offset on LDS
unsigned offset = 0;
for (auto global : workgroupGlobals) {
unsigned varSize = getTypeSizeInDwords(global->getType()->getPointerElementType());
m_globalLdsOffsetMap.insert({global, builder.getInt32(offset)});
offset += varSize;
}
// The new LDS is an i32 array
const unsigned ldsSize = offset;
auto ldsTy = ArrayType::get(builder.getInt32Ty(), ldsSize);
auto lds = new GlobalVariable(module, ldsTy, false, GlobalValue::ExternalLinkage, nullptr, "lds", nullptr,
GlobalValue::NotThreadLocal, ADDR_SPACE_LOCAL);
lds->setAlignment(MaybeAlign(16));
// Replace the original LDS variables with the new LDS variable
for (auto globalOffsetPair : m_globalLdsOffsetMap) {
GlobalVariable *global = globalOffsetPair.first;
Value *offset = globalOffsetPair.second;
Value *pointer = builder.CreateGEP(lds->getType()->getPointerElementType(), lds, {builder.getInt32(0), offset});
pointer = builder.CreateBitCast(pointer, global->getType());
global->replaceAllUsesWith(pointer);
global->eraseFromParent();
}
initializeWithZero(lds, builder);
return true;
}
// =====================================================================================================================
// Initialize the given LDS variable with zero.
//
// @param lds : The LDS variable to be initialized
// @param builder : BuilderBase to use for instruction constructing
void PatchInitializeWorkgroupMemory::initializeWithZero(GlobalVariable *lds, BuilderBase &builder) {
auto entryInsertPos = &*m_entryPoint->front().getFirstInsertionPt();
auto originBlock = entryInsertPos->getParent();
auto endInitBlock = originBlock->splitBasicBlock(entryInsertPos);
endInitBlock->setName(".endInit");
auto initBlock = BasicBlock::Create(*m_context, ".init", originBlock->getParent(), endInitBlock);
auto bodyBlock = BasicBlock::Create(*m_context, ".body", originBlock->getParent(), initBlock);
auto forHeaderBlock = BasicBlock::Create(*m_context, ".for.header", originBlock->getParent(), bodyBlock);
builder.SetInsertPoint(originBlock->getTerminator());
// Get thread info
auto &shaderMode = m_pipelineState->getShaderModes()->getComputeShaderMode();
const auto &entryArgIdxs = m_pipelineState->getShaderInterfaceData(m_shaderStage)->entryArgIdxs;
Value *localInvocationId = getFunctionArgument(m_entryPoint, entryArgIdxs.cs.localInvocationId);
const unsigned actualNumThreads = shaderMode.workgroupSizeX * shaderMode.workgroupSizeY * shaderMode.workgroupSizeZ;
Value *threadId = builder.CreateExtractElement(localInvocationId, uint64_t(0));
if (shaderMode.workgroupSizeY > 1) {
Value *stride = builder.CreateMul(builder.getInt32(shaderMode.workgroupSizeX),
builder.CreateExtractElement(localInvocationId, 1));
threadId = builder.CreateAdd(threadId, stride);
}
if (shaderMode.workgroupSizeZ > 1) {
Value *stride = builder.CreateMul(builder.getInt32(shaderMode.workgroupSizeX * shaderMode.workgroupSizeY),
builder.CreateExtractElement(localInvocationId, 2));
threadId = builder.CreateAdd(threadId, stride);
}
originBlock->getTerminator()->replaceUsesOfWith(endInitBlock, forHeaderBlock);
// Each thread stores a zero to the continues LDS
// for (int loopIdx = 0; loopIdx < loopCount; ++loopIdx) {
// if (threadId * loopCount + loopIdx < requiredNumThreads) {
// unsigned ldsOffset = (threadId * loopCount) + loopIdx;
// CreateStore(zero, ldsOffset);
// }
// }
PHINode *loopIdxPhi = nullptr;
const unsigned requiredNumThreads = lds->getType()->getPointerElementType()->getArrayNumElements();
Value *loopCount = builder.getInt32((requiredNumThreads + actualNumThreads - 1) / actualNumThreads);
// Construct ".for.Header" block
{
builder.SetInsertPoint(forHeaderBlock);
loopIdxPhi = builder.CreatePHI(builder.getInt32Ty(), 2);
loopIdxPhi->addIncoming(builder.getInt32(0), originBlock);
Value *isInLoop = builder.CreateICmpULT(loopIdxPhi, loopCount);
builder.CreateCondBr(isInLoop, bodyBlock, endInitBlock);
}
// Construct ".body" block
{
builder.SetInsertPoint(bodyBlock);
// The active thread is : threadId x loopCount + loopIdx < requiredNumThreads
Value *index = builder.CreateMul(threadId, loopCount);
index = builder.CreateAdd(index, loopIdxPhi);
Value *isActiveThread = builder.CreateICmpULT(index, builder.getInt32(requiredNumThreads));
builder.CreateCondBr(isActiveThread, initBlock, endInitBlock);
// Construct ".init" block
{
builder.SetInsertPoint(initBlock);
// ldsOffset = (threadId * loopCount) + loopIdx
Value *ldsOffset = builder.CreateMul(threadId, loopCount);
ldsOffset = builder.CreateAdd(ldsOffset, loopIdxPhi);
Value *writePtr =
builder.CreateGEP(lds->getType()->getPointerElementType(), lds, {builder.getInt32(0), ldsOffset});
builder.CreateAlignedStore(builder.getInt32(0), writePtr, Align(4));
// Update loop index
Value *loopNext = builder.CreateAdd(loopIdxPhi, builder.getInt32(1));
loopIdxPhi->addIncoming(loopNext, initBlock);
builder.CreateBr(forHeaderBlock);
}
}
{
// Set barrier after writing LDS
builder.SetInsertPoint(&*endInitBlock->getFirstInsertionPt());
builder.CreateIntrinsic(Intrinsic::amdgcn_s_barrier, {}, {});
}
}
// =====================================================================================================================
// Return the size in dwords of a variable type
//
// @param inputTy : The type to be calculated
unsigned PatchInitializeWorkgroupMemory::getTypeSizeInDwords(Type *inputTy) {
if (inputTy->isSingleValueType()) {
// Variable in LDS is stored in dwords and padded as 4 dwords
unsigned dwordCount = 4;
unsigned elemCount = inputTy->isVectorTy() ? cast<FixedVectorType>(inputTy)->getNumElements() : 1;
if (inputTy->getScalarSizeInBits() == 64 && elemCount > 1)
dwordCount = 8;
return dwordCount;
}
if (inputTy->isArrayTy()) {
const unsigned elemSize = getTypeSizeInDwords(inputTy->getContainedType(0));
return inputTy->getArrayNumElements() * elemSize;
} else {
assert(inputTy->isStructTy());
const unsigned memberCount = inputTy->getStructNumElements();
unsigned memberSize = 0;
for (unsigned idx = 0; idx < memberCount; ++idx)
memberSize += getTypeSizeInDwords(inputTy->getStructElementType(idx));
return memberSize;
}
}
} // namespace lgc
// =====================================================================================================================
// Initializes the pass of initialize workgroup memory with zero.
INITIALIZE_PASS(LegacyPatchInitializeWorkgroupMemory, DEBUG_TYPE, "Patch for initialize workgroup memory", false, false)
| 48.021583 | 120 | 0.65161 | flygod1159 |
cd1dd4cfa212c487e4f213d8ac9c0eb63a3ef0e9 | 1,593 | cpp | C++ | 01_sensor/06_grey_MPU9250/src/main.cpp | satoruosawa/samples-for-m5stack | ccc003bda296f769c8e20bfed757bed0d6419ce7 | [
"MIT"
] | null | null | null | 01_sensor/06_grey_MPU9250/src/main.cpp | satoruosawa/samples-for-m5stack | ccc003bda296f769c8e20bfed757bed0d6419ce7 | [
"MIT"
] | null | null | null | 01_sensor/06_grey_MPU9250/src/main.cpp | satoruosawa/samples-for-m5stack | ccc003bda296f769c8e20bfed757bed0d6419ce7 | [
"MIT"
] | null | null | null | // define must ahead #include <M5Stack.h>
// #define M5STACK_MPU6886
#define M5STACK_MPU9250
// #define M5STACK_MPU6050
// #define M5STACK_200Q
#include <M5Stack.h>
float accX = 0.0F;
float accY = 0.0F;
float accZ = 0.0F;
float gyroX = 0.0F;
float gyroY = 0.0F;
float gyroZ = 0.0F;
float pitch = 0.0F;
float roll = 0.0F;
float yaw = 0.0F;
float temp = 0.0F;
// the setup routine runs once when M5Stack starts up
void setup() {
// Initialize the M5Stack object
M5.begin();
/*
Power chip connected to gpio21, gpio22, I2C device
Set battery charging voltage and current
If used battery, please call this function in your project
*/
M5.Power.begin();
M5.IMU.Init();
M5.Lcd.fillScreen(BLACK);
M5.Lcd.setTextColor(GREEN, BLACK);
M5.Lcd.setTextSize(2);
}
// the loop routine runs over and over again forever
void loop() {
// put your main code here, to run repeatedly:
M5.IMU.getGyroData(&gyroX, &gyroY, &gyroZ);
M5.IMU.getAccelData(&accX, &accY, &accZ);
M5.IMU.getAhrsData(&pitch, &roll, &yaw);
M5.IMU.getTempData(&temp);
M5.Lcd.setCursor(0, 20);
M5.Lcd.printf("%6.2f %6.2f %6.2f ", gyroX, gyroY, gyroZ);
M5.Lcd.setCursor(220, 42);
M5.Lcd.print(" o/s");
M5.Lcd.setCursor(0, 65);
M5.Lcd.printf(" %5.2f %5.2f %5.2f ", accX, accY, accZ);
M5.Lcd.setCursor(220, 87);
M5.Lcd.print(" G");
M5.Lcd.setCursor(0, 110);
M5.Lcd.printf(" %5.2f %5.2f %5.2f ", pitch, roll, yaw);
M5.Lcd.setCursor(220, 132);
M5.Lcd.print(" degree");
M5.Lcd.setCursor(0, 155);
M5.Lcd.printf("Temperature : %.2f C", temp);
delay(1);
} | 24.507692 | 66 | 0.64909 | satoruosawa |
cd1e2c99ce4f8a6aa2e2beb9c0800cc5e481246e | 2,456 | cc | C++ | src/connectivity/overnet/deprecated/lib/packet_protocol/aead_codec_test.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 1 | 2019-04-21T18:02:26.000Z | 2019-04-21T18:02:26.000Z | src/connectivity/overnet/deprecated/lib/packet_protocol/aead_codec_test.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | src/connectivity/overnet/deprecated/lib/packet_protocol/aead_codec_test.cc | OpenTrustGroup/fuchsia | 647e593ea661b8bf98dcad2096e20e8950b24a97 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 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 "src/connectivity/overnet/deprecated/lib/packet_protocol/aead_codec.h"
#include <random>
#include "gtest/gtest.h"
namespace overnet {
namespace aead_codec_test {
struct TestArgs {
const EVP_AEAD* aead;
std::vector<uint64_t> seqs;
Slice payload;
};
class AEADCodec : public ::testing::TestWithParam<TestArgs> {};
TEST_P(AEADCodec, Basics) {
std::vector<uint8_t> key;
std::random_device rng;
for (size_t i = 0; i < EVP_AEAD_key_length(GetParam().aead); i++) {
key.push_back(rng());
}
const char* ad = "HELLO!";
overnet::AEADCodec codec1(GetParam().aead, key.data(), key.size(),
reinterpret_cast<const uint8_t*>(ad), strlen(ad));
overnet::AEADCodec codec2(GetParam().aead, key.data(), key.size(),
reinterpret_cast<const uint8_t*>(ad), strlen(ad));
std::vector<Slice> encoded;
for (uint64_t seq : GetParam().seqs) {
auto enc = codec1.Encode(seq, GetParam().payload);
ASSERT_TRUE(enc.is_ok()) << enc;
encoded.push_back(*enc);
EXPECT_NE(*enc, GetParam().payload);
auto dec = codec2.Decode(seq, *enc);
ASSERT_TRUE(dec.is_ok()) << dec;
EXPECT_NE(*dec, encoded.back());
EXPECT_EQ(*dec, GetParam().payload);
}
for (size_t i = 0; i < encoded.size(); i++) {
for (size_t j = i + 1; j < encoded.size(); j++) {
EXPECT_NE(encoded[i], encoded[j]) << "i=" << i << " j=" << j;
}
}
}
const auto kTestCases = [] {
std::vector<TestArgs> out;
for (auto aead : {
EVP_aead_aes_128_gcm(),
EVP_aead_aes_256_gcm(),
EVP_aead_chacha20_poly1305(),
EVP_aead_xchacha20_poly1305(),
EVP_aead_aes_128_ctr_hmac_sha256(),
EVP_aead_aes_256_ctr_hmac_sha256(),
EVP_aead_aes_128_gcm_siv(),
EVP_aead_aes_256_gcm_siv(),
}) {
out.push_back(TestArgs{
aead, {1, 2, 3, 5, 8, 13, 21, 34}, Slice::FromContainer({1, 2, 3, 4, 5, 6, 7, 8})});
out.push_back(
TestArgs{aead, {0x123456789abcdefull, 123, 321}, Slice::RepeatedChar(1024 * 1024, 'a')});
}
return out;
}();
INSTANTIATE_TEST_SUITE_P(AEADCodecTest, AEADCodec,
::testing::ValuesIn(kTestCases.begin(), kTestCases.end()));
} // namespace aead_codec_test
} // namespace overnet
| 30.7 | 97 | 0.626221 | OpenTrustGroup |
cd1fbb632f3b5d2c4c1cfc7fda4abefe73307c2b | 3,813 | cpp | C++ | 3rdparty/spirv-tools/source/opt/strip_nonsemantic_info_pass.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | 188 | 2021-08-11T07:42:41.000Z | 2022-03-31T09:58:09.000Z | 3rdparty/spirv-tools/source/opt/strip_nonsemantic_info_pass.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | 2 | 2021-09-25T16:51:34.000Z | 2021-11-21T15:59:11.000Z | 3rdparty/spirv-tools/source/opt/strip_nonsemantic_info_pass.cpp | amrezzd/bgfx | 560669f6c0e19daf8f29e1f085599f0765e4ee35 | [
"BSD-2-Clause"
] | 16 | 2021-09-02T08:37:25.000Z | 2022-03-30T16:53:26.000Z | // Copyright (c) 2018 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 "source/opt/strip_nonsemantic_info_pass.h"
#include <cstring>
#include <vector>
#include "source/opt/instruction.h"
#include "source/opt/ir_context.h"
#include "source/util/string_utils.h"
namespace spvtools {
namespace opt {
Pass::Status StripNonSemanticInfoPass::Process() {
bool modified = false;
std::vector<Instruction*> to_remove;
bool other_uses_for_decorate_string = false;
for (auto& inst : context()->module()->annotations()) {
switch (inst.opcode()) {
case SpvOpDecorateStringGOOGLE:
if (inst.GetSingleWordInOperand(1) == SpvDecorationHlslSemanticGOOGLE ||
inst.GetSingleWordInOperand(1) == SpvDecorationUserTypeGOOGLE) {
to_remove.push_back(&inst);
} else {
other_uses_for_decorate_string = true;
}
break;
case SpvOpMemberDecorateStringGOOGLE:
if (inst.GetSingleWordInOperand(2) == SpvDecorationHlslSemanticGOOGLE ||
inst.GetSingleWordInOperand(2) == SpvDecorationUserTypeGOOGLE) {
to_remove.push_back(&inst);
} else {
other_uses_for_decorate_string = true;
}
break;
case SpvOpDecorateId:
if (inst.GetSingleWordInOperand(1) ==
SpvDecorationHlslCounterBufferGOOGLE) {
to_remove.push_back(&inst);
}
break;
default:
break;
}
}
for (auto& inst : context()->module()->extensions()) {
const std::string ext_name = inst.GetInOperand(0).AsString();
if (ext_name == "SPV_GOOGLE_hlsl_functionality1") {
to_remove.push_back(&inst);
} else if (ext_name == "SPV_GOOGLE_user_type") {
to_remove.push_back(&inst);
} else if (!other_uses_for_decorate_string &&
ext_name == "SPV_GOOGLE_decorate_string") {
to_remove.push_back(&inst);
} else if (ext_name == "SPV_KHR_non_semantic_info") {
to_remove.push_back(&inst);
}
}
// remove any extended inst imports that are non semantic
std::unordered_set<uint32_t> non_semantic_sets;
for (auto& inst : context()->module()->ext_inst_imports()) {
assert(inst.opcode() == SpvOpExtInstImport &&
"Expecting an import of an extension's instruction set.");
const std::string extension_name = inst.GetInOperand(0).AsString();
if (spvtools::utils::starts_with(extension_name, "NonSemantic.")) {
non_semantic_sets.insert(inst.result_id());
to_remove.push_back(&inst);
}
}
// if we removed some non-semantic sets, then iterate over the instructions in
// the module to remove any OpExtInst that referenced those sets
if (!non_semantic_sets.empty()) {
context()->module()->ForEachInst(
[&non_semantic_sets, &to_remove](Instruction* inst) {
if (inst->opcode() == SpvOpExtInst) {
if (non_semantic_sets.find(inst->GetSingleWordInOperand(0)) !=
non_semantic_sets.end()) {
to_remove.push_back(inst);
}
}
},
true);
}
for (auto* inst : to_remove) {
modified = true;
context()->KillInst(inst);
}
return modified ? Status::SuccessWithChange : Status::SuccessWithoutChange;
}
} // namespace opt
} // namespace spvtools
| 32.87069 | 80 | 0.664044 | amrezzd |
cd1fe66e1137d11b16d38839645d99ff6077284a | 12,962 | cc | C++ | tensorflow/compiler/mlir/xla/transforms/lhlo_legalize_to_linalg.cc | Samsomyajit/tensorflow | c7adb780108f100e5181128745e3917b8fce6887 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/mlir/xla/transforms/lhlo_legalize_to_linalg.cc | Samsomyajit/tensorflow | c7adb780108f100e5181128745e3917b8fce6887 | [
"Apache-2.0"
] | null | null | null | tensorflow/compiler/mlir/xla/transforms/lhlo_legalize_to_linalg.cc | Samsomyajit/tensorflow | c7adb780108f100e5181128745e3917b8fce6887 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2019 The TensorFlow Authors. 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.
==============================================================================*/
// This file implements logic for lowering HLO dialect to LHLO dialect.
#include "absl/memory/memory.h"
#include "llvm/ADT/StringSwitch.h"
#include "mlir/Dialect/Linalg/IR/LinalgOps.h" // TF:local_config_mlir
#include "mlir/Dialect/Linalg/IR/LinalgTypes.h" // TF:local_config_mlir
#include "mlir/Dialect/StandardOps/Ops.h" // TF:local_config_mlir
#include "mlir/IR/Attributes.h" // TF:local_config_mlir
#include "mlir/IR/Builders.h" // TF:local_config_mlir
#include "mlir/IR/Function.h" // TF:local_config_mlir
#include "mlir/IR/Location.h" // TF:local_config_mlir
#include "mlir/IR/MLIRContext.h" // TF:local_config_mlir
#include "mlir/IR/Operation.h" // TF:local_config_mlir
#include "mlir/IR/PatternMatch.h" // TF:local_config_mlir
#include "mlir/IR/StandardTypes.h" // TF:local_config_mlir
#include "mlir/Pass/Pass.h" // TF:local_config_mlir
#include "mlir/Transforms/DialectConversion.h" // TF:local_config_mlir
#include "tensorflow/compiler/mlir/xla/ir/lhlo_ops.h"
namespace mlir {
namespace xla_lhlo {
namespace {
// TODO(pifon): Move LHLO -> STD op map to a separate lib.
template <typename LHLO_BinaryOp>
struct ScalarOp;
template <>
struct ScalarOp<xla_lhlo::AddOp> {
using FOp = ::mlir::AddFOp;
using IOp = ::mlir::AddIOp;
};
template <>
struct ScalarOp<xla_lhlo::CompareOp> {
using FOp = ::mlir::CmpFOp;
using IOp = ::mlir::CmpIOp;
};
template <>
struct ScalarOp<xla_lhlo::DivOp> {
using FOp = ::mlir::DivFOp;
using IOp = ::mlir::DivISOp;
};
template <>
struct ScalarOp<xla_lhlo::MulOp> {
using FOp = ::mlir::MulFOp;
using IOp = ::mlir::MulIOp;
};
template <>
struct ScalarOp<xla_lhlo::SubOp> {
using FOp = ::mlir::SubFOp;
using IOp = ::mlir::SubIOp;
};
template <typename LHLO_BinaryOp>
using ScalarFOp = typename ScalarOp<LHLO_BinaryOp>::FOp;
template <typename LHLO_BinaryOp>
using ScalarIOp = typename ScalarOp<LHLO_BinaryOp>::IOp;
template <typename LhloOp>
Operation* GetLinalgBodyOp(Location loc, LhloOp lhlo_op, Type element_type,
ArrayRef<Type> body_result_types,
ArrayRef<Value*> block_args, OpBuilder b) {
if (element_type.isa<IntegerType>()) {
return b.template create<ScalarIOp<LhloOp>>(loc, body_result_types,
block_args, mlir::None);
}
if (element_type.isa<FloatType>()) {
return b.template create<ScalarFOp<LhloOp>>(loc, body_result_types,
block_args, mlir::None);
}
return nullptr;
}
template <>
Operation* GetLinalgBodyOp<xla_lhlo::MaxOp>(Location loc,
xla_lhlo::MaxOp lhlo_op,
Type element_type,
ArrayRef<Type> body_result_types,
ArrayRef<Value*> block_args,
OpBuilder b) {
const auto& lhs = block_args[0];
const auto& rhs = block_args[1];
if (element_type.isa<IntegerType>()) {
auto lhs_gt_rhs =
b.create<ScalarIOp<CompareOp>>(loc, CmpIPredicate::SGT, lhs, rhs);
return b.create<::mlir::SelectOp>(loc, lhs_gt_rhs, lhs, rhs);
}
if (element_type.isa<FloatType>()) {
auto lhs_gt_rhs =
b.create<ScalarFOp<CompareOp>>(loc, CmpFPredicate::OGT, lhs, rhs);
return b.create<::mlir::SelectOp>(loc, lhs_gt_rhs, lhs, rhs);
}
return nullptr;
}
template <>
Operation* GetLinalgBodyOp<xla_lhlo::MinOp>(Location loc,
xla_lhlo::MinOp lhlo_op,
Type element_type,
ArrayRef<Type> body_result_types,
ArrayRef<Value*> block_args,
OpBuilder b) {
const auto& lhs = block_args[0];
const auto& rhs = block_args[1];
if (element_type.isa<IntegerType>()) {
auto lhs_lt_rhs =
b.create<ScalarIOp<CompareOp>>(loc, CmpIPredicate::SLT, lhs, rhs);
return b.create<::mlir::SelectOp>(loc, lhs_lt_rhs, lhs, rhs);
}
if (element_type.isa<FloatType>()) {
auto lhs_lt_rhs =
b.create<ScalarFOp<CompareOp>>(loc, CmpFPredicate::OLT, lhs, rhs);
return b.create<::mlir::SelectOp>(loc, lhs_lt_rhs, lhs, rhs);
}
return nullptr;
}
template <>
Operation* GetLinalgBodyOp<xla_lhlo::AndOp>(Location loc,
xla_lhlo::AndOp lhlo_op,
Type element_type,
ArrayRef<Type> body_result_types,
ArrayRef<Value*> block_args,
OpBuilder b) {
return element_type.isa<IntegerType>()
? b.create<::mlir::AndOp>(loc, body_result_types, block_args,
mlir::None)
: nullptr;
}
CmpFPredicate getFloatCmpPredicate(StringRef xla_comparison_direction) {
return llvm::StringSwitch<CmpFPredicate>(xla_comparison_direction)
.Case("EQ", CmpFPredicate::OEQ)
.Case("NE", CmpFPredicate::ONE)
.Case("GE", CmpFPredicate::OGE)
.Case("GT", CmpFPredicate::OGT)
.Case("LE", CmpFPredicate::OLE)
.Case("LT", CmpFPredicate::OLT)
.Default(CmpFPredicate::NumPredicates);
}
CmpIPredicate getIntCmpPredicate(StringRef xla_comparison_direction) {
return llvm::StringSwitch<CmpIPredicate>(xla_comparison_direction)
.Case("EQ", CmpIPredicate::EQ)
.Case("NE", CmpIPredicate::NE)
.Case("GE", CmpIPredicate::SGE)
.Case("GT", CmpIPredicate::SGT)
.Case("LE", CmpIPredicate::SLE)
.Case("LT", CmpIPredicate::SLT)
.Default(CmpIPredicate::NumPredicates);
}
template <>
Operation* GetLinalgBodyOp<xla_lhlo::CompareOp>(
Location loc, xla_lhlo::CompareOp lhlo_op, Type element_type,
ArrayRef<Type> body_result_types, ArrayRef<Value*> block_args,
OpBuilder b) {
const auto& lhs = block_args[0];
const auto& rhs = block_args[1];
if (element_type.isa<IntegerType>()) {
return b.create<ScalarIOp<CompareOp>>(
loc, getIntCmpPredicate(lhlo_op.comparison_direction()), lhs, rhs);
}
if (element_type.isa<FloatType>()) {
return b.create<ScalarFOp<CompareOp>>(
loc, getFloatCmpPredicate(lhlo_op.comparison_direction()), lhs, rhs);
}
return nullptr;
}
template <>
Operation* GetLinalgBodyOp<xla_lhlo::ExpOp>(Location loc,
xla_lhlo::ExpOp lhlo_op,
Type element_type,
ArrayRef<Type> body_result_types,
ArrayRef<Value*> block_args,
OpBuilder b) {
return element_type.isa<FloatType>()
? b.create<::mlir::ExpOp>(loc, body_result_types, block_args,
mlir::None)
: nullptr;
}
template <typename LhloOp>
class LhloToLinalgOpConverter : public ConversionPattern {
public:
explicit LhloToLinalgOpConverter(MLIRContext* context)
: ConversionPattern(LhloOp::getOperationName(), 1, context) {}
PatternMatchResult matchAndRewrite(
Operation* lhlo_op, ArrayRef<Value*> args,
ConversionPatternRewriter& rewriter) const final {
const auto& loc = lhlo_op->getLoc();
auto arg_type = lhlo_op->getOperand(0)->getType().dyn_cast<ShapedType>();
if (!arg_type || !arg_type.hasStaticShape()) {
emitError(loc,
"lhlo to linalg conversion expects statically shaped args");
return matchFailure();
}
if (!arg_type || !arg_type.getElementType().isIntOrFloat()) {
return matchFailure();
}
// Construct the indexing maps needed for linalg.generic ops.
SmallVector<Attribute, 2> indexing_maps;
SmallVector<Type, 4> body_arg_types, body_result_types;
unsigned nloops = 0;
const auto operandCount = args.size() - 1;
for (const auto& arg : llvm::enumerate(args)) {
auto memref_type = arg.value()->getType().dyn_cast<MemRefType>();
if (!memref_type) {
return matchFailure();
}
if (nloops && nloops != memref_type.getRank()) {
return matchFailure();
}
nloops = std::max(nloops, static_cast<unsigned>(memref_type.getRank()));
indexing_maps.emplace_back(
AffineMapAttr::get(rewriter.getMultiDimIdentityMap(nloops)));
auto& result_or_body_arg =
arg.index() < operandCount ? body_arg_types : body_result_types;
result_or_body_arg.emplace_back(memref_type.getElementType());
}
// Pointwise-ops have all surrounding loops parallel, so the loop triple is
// [argDim, 0, 0].
const SmallVector<Attribute, 3> loop_types{
rewriter.getI64IntegerAttr(nloops), rewriter.getI64IntegerAttr(0),
rewriter.getI64IntegerAttr(0)};
// Define the number of input memref/output memrefs.
const SmallVector<Attribute, 2> nmemrefs{
rewriter.getI64IntegerAttr(body_arg_types.size()),
rewriter.getI64IntegerAttr(body_result_types.size())};
auto linalg_op = rewriter.create<linalg::GenericOp>(
loc, args, rewriter.getArrayAttr(indexing_maps),
rewriter.getArrayAttr(loop_types), rewriter.getArrayAttr(nmemrefs),
/*doc=*/nullptr, /*fun=*/nullptr, /*library_call=*/nullptr);
// Add a block to the region.
auto* region = &linalg_op.region();
auto* block = rewriter.createBlock(region, region->end());
block->addArguments(body_arg_types);
block->addArguments(body_result_types);
SmallVector<Value*, 4> body_args;
for (int i = 0, e = body_arg_types.size(); i < e; ++i) {
body_args.push_back(block->getArgument(i));
}
rewriter.setInsertionPointToEnd(block);
Operation* op = GetLinalgBodyOp<LhloOp>(
loc, llvm::cast<LhloOp>(lhlo_op), body_arg_types[0], body_result_types,
body_args, rewriter);
rewriter.create<linalg::YieldOp>(loc, llvm::to_vector<1>(op->getResults()));
rewriter.replaceOp(lhlo_op, {});
return matchSuccess();
}
};
void populateLHLOToLinalgConversionPattern(MLIRContext* context,
OwningRewritePatternList* patterns) {
patterns->insert<LhloToLinalgOpConverter<xla_lhlo::AddOp>,
LhloToLinalgOpConverter<xla_lhlo::AndOp>,
LhloToLinalgOpConverter<xla_lhlo::CompareOp>,
LhloToLinalgOpConverter<xla_lhlo::DivOp>,
LhloToLinalgOpConverter<xla_lhlo::ExpOp>,
LhloToLinalgOpConverter<xla_lhlo::MaxOp>,
LhloToLinalgOpConverter<xla_lhlo::MinOp>,
LhloToLinalgOpConverter<xla_lhlo::MulOp>,
LhloToLinalgOpConverter<xla_lhlo::SubOp>>(context);
}
// Converts LHLO ops to Linalg generic.
// Sample result for xla_lhlo::AddOp.
//
// "xla_lhlo.add"(%arg1, %arg2, %out) :
// (memref<2x2xf32>, memref<2x2xf32>, memref<2x2xf32>) -> ()
//
// will be converted to
//
// #map0 = (d0, d1) -> (d0, d1)
// "linalg.generic"(%arg1, %arg2, %out) ( {
// ^bb0(%arg4: f32, %arg5: f32):
// %0 = addf %arg4, %arg5 : f32
// "linalg.yield"(%0) : (f32) -> ()
// }) {
// indexing_maps = [#map0, #map0, #map0],
// n_loop_types = [2, 0, 0],
// n_views = [2, 1]
// } : (memref<2x2xf32>, memref<2x2xf32>, memref<2x2xf32>) -> ()
// }
struct LhloLegalizeToLinalg : public FunctionPass<LhloLegalizeToLinalg> {
void runOnFunction() override {
OwningRewritePatternList patterns;
ConversionTarget target(getContext());
target.addLegalDialect<linalg::LinalgDialect, StandardOpsDialect>();
auto func = getFunction();
populateLHLOToLinalgConversionPattern(func.getContext(), &patterns);
if (failed(applyPartialConversion(func, target, patterns, nullptr))) {
signalPassFailure();
}
}
};
} // namespace
std::unique_ptr<OpPassBase<FuncOp>> createLegalizeToLinalgPass() {
return absl::make_unique<LhloLegalizeToLinalg>();
}
static PassRegistration<LhloLegalizeToLinalg> legalize_pass(
"lhlo-legalize-to-linalg", "Legalize from LHLO dialect to Linalg dialect");
} // namespace xla_lhlo
} // namespace mlir
| 38.924925 | 80 | 0.632464 | Samsomyajit |
cd1ffc92ab570432a5a298c529e1c74373753446 | 874 | cpp | C++ | PhantomEngine/PhantomAction.cpp | DexianZhao/PhantomGameEngine | cf8e341d21e3973856d9f23ad0b1af9db831bac7 | [
"MIT"
] | 4 | 2019-11-08T00:15:13.000Z | 2021-03-26T13:34:50.000Z | src/PhantomEngine/PhantomAction.cpp | DexianZhao/PhantomEngineV2 | cc3bf02ca1d442713d471ca8835ca026bb32e841 | [
"MIT"
] | 4 | 2021-03-13T10:26:09.000Z | 2021-03-13T10:45:35.000Z | src/PhantomEngine/PhantomAction.cpp | DexianZhao/PhantomEngineV2 | cc3bf02ca1d442713d471ca8835ca026bb32e841 | [
"MIT"
] | 3 | 2020-06-01T01:53:05.000Z | 2021-03-21T03:51:33.000Z | //////////////////////////////////////////////////////////////////////////////////////////////////////
/*
文件 : PhantomAction.cpp
幻影游戏引擎, 2009-2016, Phantom Game Engine, http://www.aixspace.com
Design Writer : 赵德贤 Dexian Zhao
Email: yuzhou_995@hotmail.com
Copyright 2009-2016 Zhao Dexian
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
*/
//////////////////////////////////////////////////////////////////////////////////////////////////////
#include "PhantomUIDialog.h"
#include "PhantomManager.h"
#include "PhantomAction.h"
namespace Phantom{
ActionBase::ActionBase()
{
m_context = 0;
m_bBegin = true;
m_next = 0;
m_current = this;
}
ActionBase::~ActionBase()
{
safe_release(m_next);
}
};
| 23.621622 | 103 | 0.372998 | DexianZhao |
cd210fd1cec964065fd0ac3ed6ddbc1e90a98691 | 2,782 | cpp | C++ | src/ai/la/WordSetChecker.cpp | name212/GrammarEngine | 1912809d6a19977c9d2fff88279b76a6152b659d | [
"MIT"
] | 55 | 2015-04-11T17:39:27.000Z | 2022-01-07T17:52:22.000Z | src/ai/la/WordSetChecker.cpp | name212/GrammarEngine | 1912809d6a19977c9d2fff88279b76a6152b659d | [
"MIT"
] | 17 | 2017-11-22T13:31:11.000Z | 2021-06-06T08:30:43.000Z | src/ai/la/WordSetChecker.cpp | qwazer/GrammarEngine | 08e1eb7bdfd77f29a51a7063848d74b9171291c4 | [
"MIT"
] | 28 | 2015-05-21T08:27:31.000Z | 2022-02-24T21:42:36.000Z | #include <lem/solarix/LA_WordEntrySet.h>
#include <lem/solarix/word_form.h>
#include <lem/solarix/WordSetChecker.h>
using namespace Solarix;
WordSetChecker::WordSetChecker()
: set_type(UNKNOWN), positive(false)
{}
WordSetChecker::WordSetChecker(int type, const lem::UCString &Setname, bool Positive, const lem::UCString & ExportNodeName, ViolationHandler _handler)
: set_type(type), set_name(Setname), positive(Positive), export_node_name(ExportNodeName), violation_handler(_handler)
{}
bool WordSetChecker::operator!=(const WordSetChecker & x) const
{
return set_type != x.set_type ||
set_name != x.set_name ||
positive != x.positive ||
export_node_name != x.export_node_name ||
violation_handler != x.violation_handler;
}
WordSetChecker::WordSetChecker(const WordSetChecker & x)
: set_type(x.set_type), set_name(x.set_name), positive(x.positive), export_node_name(x.export_node_name), violation_handler(x.violation_handler)
{
}
void WordSetChecker::operator=(const WordSetChecker & x)
{
set_type = x.set_type;
set_name = x.set_name;
positive = x.positive;
export_node_name = x.export_node_name;
violation_handler = x.violation_handler;
return;
}
#if defined SOL_SAVEBIN
void WordSetChecker::SaveBin(lem::Stream& bin) const
{
bin.write(&set_type, sizeof(set_type));
bin.write(&set_name, sizeof(set_name));
bin.write(&positive, sizeof(positive));
bin.write(&export_node_name, sizeof(export_node_name));
bin.write(&violation_handler, sizeof(violation_handler));
return;
}
#endif
#if defined SOL_LOADBIN
void WordSetChecker::LoadBin(lem::Stream& bin)
{
bin.read(&set_type, sizeof(set_type));
bin.read(&set_name, sizeof(set_name));
bin.read(&positive, sizeof(positive));
bin.read(&export_node_name, sizeof(export_node_name));
bin.read(&violation_handler, sizeof(violation_handler));
LEM_CHECKIT_Z(set_type == 0 || set_type == 1 || set_type == 2);
LEM_CHECKIT_Z(positive == 0 || positive == 1);
return;
}
#endif
#if defined SOL_CAA
bool WordSetChecker::Check(SynGram &sg, const Solarix::Word_Form &wf, WordEntrySet & sets) const
{
// #if defined LEM_DEBUG
// if( set_name.eqi(L"PPAsAdjModif") /*&& wf.GetOriginPos()==5*/ )
// printf( "DEBUG WordSetChecker::Check\n" );
// #endif
switch (set_type)
{
case 0:
return Affirmate(sets.FindWordSet(set_name, *wf.GetName()));
case 1:
return Affirmate(sets.FindWordEntrySet(set_name, wf.GetEntryKey()));
case 2:
return Affirmate(sets.FindWordformSet(sg, set_name, wf));
default: LEM_STOPIT;
}
return false;
}
#endif
| 27.009709 | 151 | 0.675054 | name212 |
cd229ade02b635fa8b562ca56a06c88e6bf80d38 | 1,772 | hpp | C++ | src/common/StringFormer.hpp | zhaldak/signature | f4c8eafd2d2af6b60f0b1380d5d4b01d33f35b74 | [
"MIT"
] | null | null | null | src/common/StringFormer.hpp | zhaldak/signature | f4c8eafd2d2af6b60f0b1380d5d4b01d33f35b74 | [
"MIT"
] | null | null | null | src/common/StringFormer.hpp | zhaldak/signature | f4c8eafd2d2af6b60f0b1380d5d4b01d33f35b74 | [
"MIT"
] | 1 | 2020-02-01T11:41:39.000Z | 2020-02-01T11:41:39.000Z | #pragma once
#include <algorithm>
#include <string_view>
#include <cstdio>
#include <cstdint>
#include <cstdarg>
class StringFormer
{
public:
StringFormer(StringFormer&&) = delete;
StringFormer(StringFormer const&) = delete;
StringFormer& operator=(StringFormer&&) = delete;
StringFormer& operator=(StringFormer const&) = delete;
~StringFormer() = default;
StringFormer(char* buffer, size_t size)
: m_start(buffer)
, m_end(buffer + size)
, m_free(buffer)
{
if (0 != size) { buffer[0] = '\0'; }
}
StringFormer& operator() (char const* format, ...)
{
va_list args;
va_start(args, format);
append(format, args);
va_end(args);
return *this;
}
int append(char const* format, ...)
{
va_list args;
va_start(args, format);
int res = append(format, args);
va_end(args);
return res;
}
int append(char const* format, va_list vlist)
{
if (not format || free_size() == 0) { return 0; }
int printed = vsnprintf(m_free, free_size(), format, vlist);
int res = std::min(printed, free_size());
m_free += res;
return res - (is_full() ? 1 : 0);
}
std::string_view sv() const noexcept { return {m_start, size()}; }
char const* c_str() const noexcept { return m_start; }
size_t size() const noexcept { return m_free - m_start - (is_full() ? 1 : 0); }
size_t capacity() const noexcept { return m_end - m_start; }
int free_size() const noexcept { return m_end - m_free; }
bool is_full() const noexcept { return m_free == m_end; }
bool empty() const noexcept { return m_free == m_start; }
void reset() noexcept { m_free = m_start; }
private:
char* m_start;
char* const m_end;
char* m_free;
};
| 24.273973 | 88 | 0.61851 | zhaldak |
cd232a6bc8d430afe3bf2d8375c894eff92b5662 | 34,676 | cpp | C++ | TerrainApps/CManager/frame.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | 4 | 2019-02-08T13:51:26.000Z | 2021-12-07T13:11:06.000Z | TerrainApps/CManager/frame.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | null | null | null | TerrainApps/CManager/frame.cpp | nakijun/vtp | 7bd2b2abd3a3f778a32ba30be099cfba9b892922 | [
"MIT"
] | 7 | 2017-12-03T10:13:17.000Z | 2022-03-29T09:51:18.000Z | //
// Name: frame.cpp
// Purpose: The frame class for the Content Manager.
//
// Copyright (c) 2001-2011 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include <wx/stdpaths.h>
#include "vtlib/vtlib.h"
#include "vtlib/core/NavEngines.h"
#include "vtdata/FileFilters.h"
#include "vtdata/vtLog.h"
#include "vtdata/DataPath.h"
#include "vtdata/Version.h"
#include "vtui/Helper.h" // for ProgressDialog and AddType
#include "xmlhelper/easyxml.hpp"
#include "app.h"
#include "frame.h"
#include "canvas.h"
#include "menu_id.h"
#include "TreeView.h"
#include "ItemGroup.h"
// dialogs
#include "PropDlg.h"
#include "ModelDlg.h"
#include "LightDlg.h"
#include "wxosg/SceneGraphDlg.h"
#include "osgUtil/SmoothingVisitor"
#ifndef __WXMSW__
# include "icons/cmanager.xpm"
# include "bitmaps/axes.xpm"
# include "bitmaps/contents_open.xpm"
# include "bitmaps/item_new.xpm"
# include "bitmaps/item_remove.xpm"
# include "bitmaps/model_add.xpm"
# include "bitmaps/model_remove.xpm"
# include "bitmaps/properties.xpm"
# include "bitmaps/rulers.xpm"
# include "bitmaps/wireframe.xpm"
# include "bitmaps/stats.xpm"
#endif
DECLARE_APP(vtApp)
//
// Blank window class to use in bottom half of splitter2
//
class Blank: public wxWindow
{
public:
Blank(wxWindow *parent) : wxWindow(parent, -1) {}
void OnPaint( wxPaintEvent &event ) { wxPaintDC dc(this); }
DECLARE_EVENT_TABLE()
};
BEGIN_EVENT_TABLE(Blank,wxWindow)
EVT_PAINT( Blank::OnPaint )
END_EVENT_TABLE()
//////////////////////////////////////////////////////////////////////////
// vtFrame class implementation
//
BEGIN_EVENT_TABLE(vtFrame, wxFrame)
EVT_CHAR(vtFrame::OnChar)
EVT_CLOSE(vtFrame::OnClose)
EVT_IDLE(vtFrame::OnIdle)
EVT_MENU(wxID_OPEN, vtFrame::OnOpen)
EVT_MENU(wxID_SAVE, vtFrame::OnSave)
EVT_MENU(wxID_EXIT, vtFrame::OnExit)
EVT_MENU(ID_SCENE_SCENEGRAPH, vtFrame::OnSceneGraph)
EVT_MENU(ID_TEST_XML, vtFrame::OnTestXML)
EVT_MENU(ID_ITEM_NEW, vtFrame::OnItemNew)
EVT_MENU(ID_ITEM_DEL, vtFrame::OnItemDelete)
EVT_MENU(ID_ITEM_ADDMODEL, vtFrame::OnItemAddModel)
EVT_UPDATE_UI(ID_ITEM_ADDMODEL, vtFrame::OnUpdateItemAddModel)
EVT_MENU(ID_ITEM_REMOVEMODEL, vtFrame::OnItemRemoveModel)
EVT_UPDATE_UI(ID_ITEM_REMOVEMODEL, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_MODELPROPS, vtFrame::OnItemModelProps)
EVT_UPDATE_UI(ID_ITEM_MODELPROPS, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_ROTMODEL, vtFrame::OnItemRotModel)
EVT_UPDATE_UI(ID_ITEM_ROTMODEL, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_SET_AMBIENT, vtFrame::OnItemSetAmbient)
EVT_UPDATE_UI(ID_ITEM_SET_AMBIENT, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_SMOOTHING, vtFrame::OnItemSmoothing)
EVT_UPDATE_UI(ID_ITEM_SMOOTHING, vtFrame::OnUpdateItemModelExists)
EVT_MENU(ID_ITEM_SAVE, vtFrame::OnItemSave)
EVT_MENU(ID_VIEW_ORIGIN, vtFrame::OnViewOrigin)
EVT_UPDATE_UI(ID_VIEW_ORIGIN, vtFrame::OnUpdateViewOrigin)
EVT_MENU(ID_VIEW_RULERS, vtFrame::OnViewRulers)
EVT_UPDATE_UI(ID_VIEW_RULERS, vtFrame::OnUpdateViewRulers)
EVT_MENU(ID_VIEW_WIREFRAME, vtFrame::OnViewWireframe)
EVT_UPDATE_UI(ID_VIEW_WIREFRAME, vtFrame::OnUpdateViewWireframe)
EVT_MENU(ID_VIEW_STATS, vtFrame::OnViewStats)
EVT_MENU(ID_VIEW_LIGHTS, vtFrame::OnViewLights)
EVT_MENU(ID_HELP_ABOUT, vtFrame::OnHelpAbout)
END_EVENT_TABLE()
vtFrame *GetMainFrame()
{
return (vtFrame *) wxGetApp().GetTopWindow();
}
// My frame constructor
vtFrame::vtFrame(wxFrame *parent, const wxString& title, const wxPoint& pos,
const wxSize& size, long style) :
wxFrame(parent, wxID_ANY, title, pos, size, style)
{
VTLOG(" constructing Frame (%x, title, pos, size, %x)\n", parent, style);
m_bCloseOnIdle = false;
#if WIN32
// Give it an icon
SetIcon(wxIcon(_T("cmanager")));
#endif
ReadDataPath();
VTLOG("Using Datapaths:\n");
int i, n = vtGetDataPath().size();
if (n == 0)
VTLOG(" none.\n");
for (i = 0; i < n; i++)
VTLOG(" %s\n", (const char *) vtGetDataPath()[i]);
m_pCurrentModel = NULL;
m_pCurrentItem = NULL;
m_bShowOrigin = true;
m_bShowRulers = false;
m_bWireframe = false;
CreateMenus();
CreateToolbar();
CreateStatusBar();
SetDropTarget(new DnDFile);
// frame icon
SetIcon(wxICON(cmanager));
VTLOG(" creating component windows\n");
// splitters
m_splitter = new wxSplitterWindow(this, wxID_ANY, wxDefaultPosition,
wxDefaultSize, wxSP_3D /*| wxSP_LIVE_UPDATE*/);
m_splitter2 = new wxSplitterWindow(m_splitter, wxID_ANY, wxDefaultPosition,
wxDefaultSize, wxSP_3D | wxSP_LIVE_UPDATE);
m_blank = new Blank(m_splitter2); // (wxWindowID) -1, _T("blank"), wxDefaultPosition);
m_pTree = new MyTreeCtrl(m_splitter2, ID_TREECTRL,
wxPoint(0, 0), wxSize(200, 400),
// wxTR_HAS_BUTTONS |
wxTR_EDIT_LABELS |
wxNO_BORDER);
m_pTree->SetBackgroundColour(*wxLIGHT_GREY);
// We definitely want full color and a 24-bit Z-buffer!
int gl_attrib[8] = { WX_GL_RGBA, WX_GL_DOUBLEBUFFER,
WX_GL_BUFFER_SIZE, 24, WX_GL_DEPTH_SIZE, 24, 0, 0 };
// Make a vtGLCanvas
VTLOG1(" creating canvas\n");
m_canvas = new CManagerCanvas(m_splitter, wxID_ANY, wxPoint(0, 0), wxSize(-1, -1),
0, _T("CManagerCanvas"), gl_attrib);
VTLOG(" creating scenegraphdialog\n");
m_pSceneGraphDlg = new SceneGraphDlg(this, wxID_ANY, _T("Scene Graph"),
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER);
m_pSceneGraphDlg->SetSize(250, 350);
m_pPropDlg = new PropPanel(m_splitter2, wxID_ANY,
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE);
m_pModelDlg = new ModelPanel(m_splitter2, wxID_ANY,
wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE);
m_pModelDlg->Show(false);
m_pModelDlg->InitDialog();
m_pLightDlg = new LightDlg(this, -1, _T("Lights"));
m_splitter->Initialize(m_splitter2);
////////////////////////
m_pTree->Show(true);
m_canvas->Show(true);
m_splitter->SplitVertically( m_splitter2, m_canvas, 260);
m_splitter2->SplitHorizontally( m_pTree, m_blank, 200);
m_pPropDlg->Show(true);
m_pPropDlg->InitDialog();
// Show the frame
Show(true);
// Load the font
vtString fontfile = "Arial.ttf";
m_pFont = osgText::readFontFile((const char *)fontfile);
if (!m_pFont.valid())
{
vtString fontname = "Fonts/" + fontfile;
vtString font_path = FindFileOnPaths(vtGetDataPath(), fontname);
if (font_path != "")
m_pFont = osgText::readFontFile((const char *)font_path);
if (!m_pFont.valid())
{
VTLOG("Couldn't find or read font from file '%s'\n",
(const char *) fontname);
}
}
#if 0
// TEST CODE
osg::Node *node = osgDB::readNodeFile("in.obj");
osgDB::Registry::instance()->writeNode(*node, "out.osg");
#endif
SetCurrentItemAndModel(NULL, NULL);
m_pTree->RefreshTreeItems(this);
}
vtFrame::~vtFrame()
{
VTLOG(" destructing Frame\n");
FreeContents();
delete m_canvas;
delete m_pSceneGraphDlg;
delete m_pLightDlg;
}
void vtFrame::UseLight(vtTransform *pLight)
{
m_pLightDlg->UseLight(pLight);
}
//////////////////////////////
using namespace std;
void vtFrame::ReadDataPath()
{
// Look these up, we might need them
wxString Dir1 = wxStandardPaths::Get().GetUserConfigDir();
wxString Dir2 = wxStandardPaths::Get().GetConfigDir();
vtString AppDataUser = (const char *) Dir1.mb_str(wxConvUTF8);
vtString AppDataCommon = (const char *) Dir2.mb_str(wxConvUTF8);
// Read the vt datapaths
vtLoadDataPath(AppDataUser, AppDataCommon);
vtStringArray &dp = vtGetDataPath();
// Supply the special symbols {appdata} and {appdatacommon}
for (uint i = 0; i < dp.size(); i++)
{
dp[i].Replace("{appdata}", AppDataUser);
dp[i].Replace("{appdatacommon}", AppDataCommon);
}
}
void vtFrame::CreateMenus()
{
// Make menus
wxMenu *fileMenu = new wxMenu;
fileMenu->Append(wxID_OPEN, _T("Open Content File"), _T("Open"));
fileMenu->Append(wxID_SAVE, _T("&Save Content File"));
fileMenu->AppendSeparator();
fileMenu->Append(ID_SCENE_SCENEGRAPH, _T("Scene Graph"));
fileMenu->AppendSeparator();
fileMenu->Append(ID_TEST_XML, _T("Test XML"));
fileMenu->AppendSeparator();
fileMenu->Append(ID_SET_DATA_PATH, _T("Set Data Path"));
fileMenu->AppendSeparator();
fileMenu->Append(wxID_EXIT, _T("E&xit\tEsc"), _T("Exit"));
wxMenu *itemMenu = new wxMenu;
itemMenu->Append(ID_ITEM_NEW, _T("New Item"));
itemMenu->Append(ID_ITEM_DEL, _T("Delete Item"));
itemMenu->AppendSeparator();
itemMenu->Append(ID_ITEM_ADDMODEL, _T("Add Model"));
itemMenu->Append(ID_ITEM_REMOVEMODEL, _T("Remove Model"));
itemMenu->Append(ID_ITEM_MODELPROPS, _T("Model Properties"));
itemMenu->AppendSeparator();
itemMenu->Append(ID_ITEM_ROTMODEL, _T("Rotate Model Around X Axis"));
itemMenu->Append(ID_ITEM_SET_AMBIENT, _T("Set materials' ambient from diffuse"));
itemMenu->Append(ID_ITEM_SMOOTHING, _T("Fix normals (apply smoothing)"));
itemMenu->AppendSeparator();
itemMenu->Append(ID_ITEM_SAVE, _T("Save Model"));
wxMenu *viewMenu = new wxMenu;
viewMenu->AppendCheckItem(ID_VIEW_ORIGIN, _T("Show Local Origin"));
viewMenu->AppendCheckItem(ID_VIEW_RULERS, _T("Show Rulers"));
viewMenu->AppendCheckItem(ID_VIEW_WIREFRAME, _T("&Wireframe\tCtrl+W"));
viewMenu->Append(ID_VIEW_STATS, _T("Statistics (cycle)\tx"));
viewMenu->Append(ID_VIEW_LIGHTS, _T("Lights"));
wxMenu *helpMenu = new wxMenu;
helpMenu->Append(ID_HELP_ABOUT, _T("About VTP Content Manager..."));
wxMenuBar *menuBar = new wxMenuBar;
menuBar->Append(fileMenu, _T("&File"));
menuBar->Append(itemMenu, _T("&Item"));
menuBar->Append(viewMenu, _T("&View"));
menuBar->Append(helpMenu, _T("&Help"));
SetMenuBar(menuBar);
}
void vtFrame::CreateToolbar()
{
// tool bar
m_pToolbar = CreateToolBar(wxTB_HORIZONTAL | wxNO_BORDER | wxTB_DOCKABLE);
m_pToolbar->SetMargins(2, 2);
m_pToolbar->SetToolBitmapSize(wxSize(20, 20));
AddTool(wxID_OPEN, wxBITMAP(contents_open), _("Open Contents File"), false);
m_pToolbar->AddSeparator();
AddTool(ID_ITEM_NEW, wxBITMAP(item_new), _("New Item"), false);
AddTool(ID_ITEM_DEL, wxBITMAP(item_remove), _("Delete Item"), false);
m_pToolbar->AddSeparator();
AddTool(ID_ITEM_ADDMODEL, wxBITMAP(model_add), _("Add Model"), false);
AddTool(ID_ITEM_REMOVEMODEL, wxBITMAP(model_remove), _("Remove Model"), false);
AddTool(ID_ITEM_MODELPROPS, wxBITMAP(properties), _("Model Properties"), false);
m_pToolbar->AddSeparator();
AddTool(ID_VIEW_ORIGIN, wxBITMAP(axes), _("Show Axes"), true);
AddTool(ID_VIEW_RULERS, wxBITMAP(rulers), _("Show Rulers"), true);
AddTool(ID_VIEW_WIREFRAME, wxBITMAP(wireframe), _("Wireframe"), true);
m_pToolbar->AddSeparator();
AddTool(ID_VIEW_STATS, wxBITMAP(stats), _("Statistics (cycle)"), false);
m_pToolbar->Realize();
}
//
// Utility methods
//
void vtFrame::OnChar(wxKeyEvent& event)
{
long key = event.GetKeyCode();
if (key == 27)
{
// Esc: exit application
// It's not safe to close immediately, as that will kill the canvas,
// and it might some Canvas event that caused us to close. So,
// simply stop rendering, and delay closing until the next Idle event.
m_canvas->m_bRunning = false;
m_bCloseOnIdle = true;
}
}
void vtFrame::OnClose(wxCloseEvent &event)
{
VTLOG("Frame OnClose\n");
if (m_canvas)
{
m_canvas->m_bRunning = false;
m_bCloseOnIdle = true;
}
event.Skip();
}
void vtFrame::OnIdle(wxIdleEvent& event)
{
// Check if we were requested to close on the next Idle event.
if (m_bCloseOnIdle)
{
VTLOG("CloseOnIdle, calling Close()\n");
Close();
}
else
event.Skip();
}
//
// Intercept menu commands
//
void vtFrame::OnOpen(wxCommandEvent& event)
{
m_canvas->m_bRunning = false;
wxFileDialog loadFile(NULL, _T("Load Content File"), _T(""), _T(""),
FSTRING_VTCO, wxFD_OPEN);
loadFile.SetFilterIndex(1);
if (loadFile.ShowModal() == wxID_OK)
LoadContentsFile(loadFile.GetPath());
m_canvas->m_bRunning = true;
}
void vtFrame::OnSave(wxCommandEvent& event)
{
m_canvas->m_bRunning = false;
wxFileDialog loadFile(NULL, _T("Save Content File"), _T(""), _T(""),
FSTRING_VTCO, wxFD_SAVE);
loadFile.SetFilterIndex(1);
if (loadFile.ShowModal() == wxID_OK)
SaveContentsFile(loadFile.GetPath());
m_canvas->m_bRunning = true;
}
void vtFrame::LoadContentsFile(const wxString &fname)
{
VTLOG("LoadContentsFile '%s'\n", (const char *) fname.mb_str(wxConvUTF8));
FreeContents();
try
{
m_Man.ReadXML(fname.mb_str(wxConvUTF8));
}
catch (xh_io_exception &e)
{
string str = e.getFormattedMessage();
DisplayMessageBox(wxString(str.c_str(), wxConvUTF8));
return;
}
SetCurrentItem(NULL);
SetCurrentModel(NULL);
m_pTree->RefreshTreeItems(this);
}
void vtFrame::FreeContents()
{
VTLOG("FreeContents\n");
for (uint i = 0; i < m_Man.NumItems(); i++)
{
vtItem *item = m_Man.GetItem(i);
ItemGroup *ig = m_itemmap[item];
delete ig;
}
m_itemmap.clear();
m_nodemap.clear();
m_Man.Clear();
m_pCurrentItem = NULL;
m_pCurrentModel = NULL;
}
void vtFrame::SaveContentsFile(const wxString &fname)
{
VTLOG("SaveContentsFile '%s'\n", (const char *) fname.mb_str(wxConvUTF8));
try
{
m_Man.WriteXML(fname.mb_str(wxConvUTF8));
}
catch (xh_io_exception &e)
{
string str = e.getFormattedMessage();
DisplayMessageBox(wxString(str.c_str(), wxConvUTF8));
}
}
/// String comparison which considers '/' and '\' equivalent
bool SamePath(const vtString &s1, const vtString &s2)
{
int i, n = s1.GetLength();
for (i = 0; i < n; i++)
{
if (s1[i] != s2[i] &&
!(s1[i] == '/' && s2[i] == '\\') &&
!(s1[i] == '\\' && s2[i] == '/'))
break;
}
return i == n;
}
void vtFrame::AddModelFromFile(const wxString &fname1)
{
vtString fname = (const char *) fname1.mb_str();
VTLOG("AddModelFromFile '%s'\n", (const char *) fname);
// Change backslashes to slashes.
fname.Replace('\\', '/');
// Check if its on the known data path.
vtStringArray &paths = vtGetDataPath();
for (uint i = 0; i < paths.size(); i++)
{
int n = paths[i].GetLength();
if (SamePath(paths[i], fname.Left(n)))
{
// found it
fname = fname.Right(fname.GetLength() - n);
break;
}
}
vtModel *nm = AddModel(wxString(fname, *wxConvCurrent));
if (nm)
SetCurrentItemAndModel(m_pCurrentItem, nm);
}
void vtFrame::ModelNameChanged(vtModel *model)
{
vtTransform *trans = m_nodemap[model];
if (trans)
m_nodemap[model] = NULL;
model->m_attempted_load = false;
DisplayCurrentModel();
// update tree view
m_pTree->RefreshTreeItems(this);
// update 3d scene graph
UpdateItemGroup(m_pCurrentItem);
}
int vtFrame::GetModelTriCount(vtModel *model)
{
vtTransform *trans = m_nodemap[model];
if (!trans)
return 0;
return 0;
}
void vtFrame::OnExit(wxCommandEvent& event)
{
VTLOG("Got Exit event, shutting down.\n");
if (m_canvas)
{
m_canvas->m_bRunning = false;
delete m_canvas;
m_canvas = NULL;
}
Destroy();
}
void vtFrame::OnSceneGraph(wxCommandEvent& event)
{
m_pSceneGraphDlg->Show(true);
}
void vtFrame::OnItemNew(wxCommandEvent& event)
{
AddNewItem();
m_pTree->RefreshTreeItems(this);
}
void vtFrame::OnItemDelete(wxCommandEvent& event)
{
if (!m_pCurrentItem)
return;
m_Man.RemoveItem(m_pCurrentItem);
SetCurrentItemAndModel(NULL, NULL);
m_pTree->RefreshTreeItems(this);
}
void vtFrame::OnItemAddModel(wxCommandEvent& event)
{
wxString filter= _("3D Model Files|");
AddType(filter, FSTRING_3DS);
AddType(filter, FSTRING_DAE);
AddType(filter, FSTRING_FLT);
AddType(filter, FSTRING_LWO);
AddType(filter, FSTRING_OBJ);
AddType(filter, FSTRING_IVE);
AddType(filter, FSTRING_OSG);
filter += _T("|");
filter += FSTRING_ALL;
wxFileDialog loadFile(NULL, _T("Load 3d Model"), _T(""), _T(""), filter, wxFD_OPEN);
loadFile.SetFilterIndex(0);
if (loadFile.ShowModal() != wxID_OK)
return;
AddModelFromFile(loadFile.GetPath());
}
void vtFrame::OnUpdateItemAddModel(wxUpdateUIEvent& event)
{
event.Enable(m_pCurrentItem != NULL);
}
void vtFrame::OnItemRemoveModel(wxCommandEvent& event)
{
vtModel *previous = m_pCurrentModel;
m_pCurrentItem->RemoveModel(m_pCurrentModel);
SetCurrentItemAndModel(m_pCurrentItem, NULL);
// update tree view
m_pTree->RefreshTreeItems(this);
// update 3d scene graph
UpdateItemGroup(m_pCurrentItem);
// free memory
m_nodemap.erase(previous);
}
void vtFrame::OnItemModelProps(wxCommandEvent& event)
{
vtModel *mod = m_pCurrentModel;
osg::Node *node = m_nodemap[mod];
if (!node)
return;
FBox3 box;
GetNodeBoundBox(node, box);
wxString str, s;
s.Printf(_T("Extents:\n %f %f (width %f)\n %f %f (height %f)\n %f %f (depth %f)\n"),
box.min.x, box.max.x, box.max.x - box.min.x,
box.min.y, box.max.y, box.max.y - box.min.y,
box.min.z, box.max.z, box.max.z - box.min.z);
str += s;
vtPrimInfo info;
GetNodePrimCounts(node, info);
s.Printf(_T("\nPrimitives:\n"));
str += s;
s.Printf(_T(" Vertices: %d\n"), info.MemVertices);
str += s;
s.Printf(_T(" Vertices Drawn: %d\n"), info.Vertices);
if (info.Vertices != info.MemVertices) str += s;
s.Printf(_T(" Primitives: %d\n"), info.Primitives);
str += s;
s.Printf(_T(" Points: %d\n"), info.Points);
if (info.Points) str += s;
s.Printf(_T(" TriStrips: %d\n"), info.TriStrips);
if (info.TriStrips) str += s;
s.Printf(_T(" TriFans: %d\n"), info.TriFans);
if (info.TriFans) str += s;
s.Printf(_T(" Triangles: %d\n"), info.Triangles);
if (info.Triangles) str += s;
s.Printf(_T(" Quads: %d\n"), info.Quads);
if (info.Quads) str += s;
s.Printf(_T(" QuadStrips: %d\n"), info.QuadStrips);
if (info.QuadStrips) str += s;
s.Printf(_T(" Polygons: %d\n"), info.Polygons);
if (info.Polygons) str += s;
s.Printf(_T(" LineStrips: %d\n"), info.LineStrips);
if (info.LineStrips) str += s;
s.Printf(_T(" LineSegments: %d\n"), info.LineSegments);
if (info.LineSegments) str += s;
wxMessageBox(str, _T("Model Properties"));
}
void vtFrame::OnUpdateItemModelExists(wxUpdateUIEvent& event)
{
event.Enable(m_pCurrentItem && m_pCurrentModel);
}
// Walk an OSG scenegraph looking for geodes with statesets, change the ambient
// component of any materials found.
class SetAmbientVisitor : public osg::NodeVisitor
{
public:
SetAmbientVisitor() : NodeVisitor(NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
virtual void apply(osg::Geode& geode)
{
osg::StateSet *ss1 = geode.getStateSet();
if (ss1)
SetAmbient(ss1);
for (unsigned i=0; i<geode.getNumDrawables(); ++i)
{
osg::StateSet *ss2 = geode.getDrawable(i)->getStateSet();
if (ss2)
SetAmbient(ss2);
}
osg::NodeVisitor::apply(geode);
}
void SetAmbient(osg::StateSet *ss)
{
osg::StateAttribute *state = ss->getAttribute(osg::StateAttribute::MATERIAL);
if (!state) return;
osg::Material *mat = dynamic_cast<osg::Material *>(state);
if (!mat) return;
osg::Vec4 amb = mat->getAmbient(FAB);
osg::Vec4 d = mat->getDiffuse(FAB);
VTLOG("oldamb %f %f %f, ", amb.r(), amb.g(), amb.b(), amb.a());
osg::Material *newmat = (osg::Material *)mat->clone(osg::CopyOp::DEEP_COPY_ALL);
newmat->setAmbient(FAB, osg::Vec4(d.r()*ratio,d.g()*ratio,d.b()*ratio,1));
amb = newmat->getAmbient(FAB);
VTLOG("newamb %f %f %f\n", amb.r(), amb.g(), amb.b(), amb.a());
ss->setAttribute(newmat);
}
float ratio;
};
void vtFrame::OnItemRotModel(wxCommandEvent& event)
{
vtModel *mod = m_pCurrentModel;
osg::Node *node = m_nodemap[mod];
// this node is actually the scaling transform; we want its child
vtTransform *transform = dynamic_cast<vtTransform*>(node);
if (!transform)
return;
osg::Node *node2 = transform->getChild(0);
ApplyVertexRotation(node2, FPoint3(1,0,0), -PID2f);
}
void vtFrame::OnItemSetAmbient(wxCommandEvent& event)
{
vtModel *mod = m_pCurrentModel;
osg::Node *node = m_nodemap[mod];
SetAmbientVisitor sav;
sav.ratio = 0.4f;
node->accept(sav);
}
void vtFrame::OnItemSmoothing(wxCommandEvent& event)
{
vtModel *mod = m_pCurrentModel;
osg::Node *node = m_nodemap[mod];
osgUtil::SmoothingVisitor smoother;
node->accept(smoother);
}
void vtFrame::OnItemSave(wxCommandEvent& event)
{
vtTransform *trans = m_nodemap[m_pCurrentModel];
if (!trans)
return;
NodePtr node = trans->getChild(0);
if (!node.valid())
return;
#if 0
// To be elegant, we could ask OSG for all formats that it knows how to write.
// This code does that, but it isn't reliable because osgDB::queryPlugin
// only works if the plugin wasn't already loaded.
// This also needs the headers osgDB/ReaderWriter and osgDB/PluginQuery.
osgDB::FileNameList plugins = osgDB::listAllAvailablePlugins();
int count = 0;
for (osgDB::FileNameList::iterator itr = plugins.begin();
itr != plugins.end(); ++itr)
{
count++;
const std::string& fileName = *itr;
osgDB::ReaderWriterInfoList infoList;
if (osgDB::queryPlugin(fileName, infoList))
{
VTLOG("Got query of: %s, %d entries\n", fileName.c_str(), infoList.size());
for(osgDB::ReaderWriterInfoList::iterator rwi_itr = infoList.begin();
rwi_itr != infoList.end(); ++rwi_itr)
{
// Each ReaderWrite has one or more features (like readNode, writeObject)
// and one or more extensions (like .png, .osgb)
osgDB::ReaderWriterInfo& info = *(*rwi_itr);
// Features:
if (info.features & osgDB::ReaderWriter::FEATURE_WRITE_NODE)
{
osgDB::ReaderWriter::FormatDescriptionMap::iterator fdm_itr;
for (fdm_itr = info.extensions.begin();
fdm_itr != info.extensions.end();
++fdm_itr)
{
VTLOG("%s (%s) " fdm_itr->first.c_str(), fdm_itr->second.c_str());
}
VTLOG1("\n");
}
}
}
}
VTLOG("Total plugins: %d\n", count);
#else
// Just hard-code the formats we expect to be writable with OSG 3.x
wxString filter = _("All Files|*.*");
AddType(filter, _("OpenSceneGraph Ascii file format (*.osg)|*.osg"));
AddType(filter, _("OpenSceneGraph native binary format (*.ive)|*.ive"));
AddType(filter, _("OpenSceneGraph extendable binary format (*.osgb)|*.osgb"));
AddType(filter, _("OpenSceneGraph extendable Ascii format (*.osgt)|*.osgt"));
AddType(filter, _("OpenSceneGraph extendable XML format (*.osgx)|*.osgx"));
AddType(filter, _("3D Studio model format (*.3ds)|*.3ds"));
AddType(filter, _("Alias Wavefront OBJ format (*.obj)|*.obj"));
AddType(filter, _("OpenFlight format (*.flt)|*.flt"));
AddType(filter, _("STL ASCII format (*.sta)|*.sta"));
AddType(filter, _("STL binary format (*.stl)|*.stl"));
#endif
// ask the user for a filename
wxFileDialog saveFile(NULL, _("Export"), _T(""), _T(""),
filter, wxFD_SAVE);
saveFile.SetFilterIndex(1);
if (saveFile.ShowModal() != wxID_OK)
return;
wxString path = saveFile.GetPath();
vtString fname = (const char *) path.mb_str(wxConvUTF8);
if (fname == "")
return;
OpenProgressDialog(_T("Writing file"), path, false, this);
// OSG/IVE has a different axis convention that VTLIB does (Z up, not Y up)
// So we must rotate before saving, then rotate back again
ApplyVertexRotation(node, FPoint3(1,0,0), PID2f);
bool success = vtSaveModel(node, fname);
// Rotate back again
ApplyVertexRotation(node, FPoint3(1,0,0), -PID2f);
CloseProgressDialog();
if (success)
wxMessageBox(_("File saved.\n"));
else
wxMessageBox(_("Error in writing file.\n"));
}
void vtFrame::UpdateWidgets()
{
if (!m_pCurrentItem)
return;
ItemGroup *ig = m_itemmap[m_pCurrentItem];
if (ig)
{
ig->ShowOrigin(m_bShowOrigin);
ig->ShowRulers(m_bShowRulers);
}
}
void vtFrame::OnViewOrigin(wxCommandEvent& event)
{
m_bShowOrigin = !m_bShowOrigin;
if (m_bShowOrigin)
m_bShowRulers = false;
UpdateWidgets();
m_canvas->Refresh(false);
}
void vtFrame::OnUpdateViewOrigin(wxUpdateUIEvent& event)
{
event.Check(m_bShowOrigin);
}
void vtFrame::OnViewRulers(wxCommandEvent& event)
{
m_bShowRulers = !m_bShowRulers;
if (m_bShowRulers)
m_bShowOrigin = false;
UpdateWidgets();
m_canvas->Refresh(false);
}
void vtFrame::OnUpdateViewRulers(wxUpdateUIEvent& event)
{
event.Check(m_bShowRulers);
}
void vtFrame::OnViewWireframe(wxCommandEvent& event)
{
m_bWireframe = !m_bWireframe;
vtGetScene()->SetGlobalWireframe(m_bWireframe);
m_canvas->Refresh(false);
}
void vtFrame::OnUpdateViewWireframe(wxUpdateUIEvent& event)
{
event.Check(m_bWireframe);
}
void vtFrame::OnViewStats(wxCommandEvent& event)
{
#ifdef VTP_USE_OSG_STATS
// Yes, this is a hack, but it doesn't seem that StatsHandler can be cycled
// any other way than by key event.
osgViewer::GraphicsWindow *pGW = vtGetScene()->GetGraphicsWindow();
if ((NULL != pGW) && pGW->valid())
pGW->getEventQueue()->keyPress('x');
#endif
}
void vtFrame::OnViewLights(wxCommandEvent& event)
{
m_pLightDlg->Show(true);
}
void vtFrame::OnHelpAbout(wxCommandEvent& event)
{
m_canvas->m_bRunning = false; // stop rendering
wxString str = _T("VTP Content Manager\n\n");
str += _T("Manages sources of 3d models for the Virtual Terrain Project software.\n\n");
str += _T("Please read the HTML documentation and license.\n");
str += _T("Send feedback to: ben@vterrain.org\n");
str += _T("\nVersion: ");
str += _T(VTP_VERSION);
str += _T("\n");
str += _T("Build date: ");
str += _T(__DATE__);
wxMessageBox(str, _T("About CManager"));
m_canvas->m_bRunning = true; // start rendering again
m_canvas->Refresh(false);
}
//////////////////////////////////////////////////////////////////////////
void vtFrame::AddNewItem()
{
VTLOG("Creating new Item\n");
vtItem *pItem = new vtItem;
pItem->m_name = "untitled";
m_Man.AddItem(pItem);
SetCurrentItemAndModel(pItem, NULL);
}
vtModel *vtFrame::AddModel(const wxString &fname_in)
{
VTLOG("AddModel %s\n", (const char *) fname_in.mb_str());
#if 0
const char *fname = StartOfFilename(fname_in.mb_str());
vtString onpath = FindFileOnPaths(vtGetDataPaths(), fname);
if (onpath == "")
{
// Warning! May not be on the data path.
wxString str;
str.Printf(_T("That file:\n%hs\ndoes not appear to be on the data")
_T(" paths:"), fname);
for (int i = 0; i < vtGetDataPaths().GetSize(); i++)
{
vtString *vts = vtGetDataPaths()[i];
const char *cpath = (const char *) *vts;
wxString path = cpath;
str += _T("\n");
str += path;
}
DisplayMessageBox(str);
return NULL;
}
#else
// data path code is too complicated, just store absolute paths
vtString fname = (const char *) fname_in.mb_str();
#endif
// If there is no item, make a new one.
if (!m_pCurrentItem)
AddNewItem();
vtModel *new_model = new vtModel;
new_model->m_filename = fname;
osg::Node *node = AttemptLoad(new_model);
if (!node)
{
delete new_model;
return NULL;
}
// add to current item
m_pCurrentItem->AddModel(new_model);
// update tree view
m_pTree->RefreshTreeItems(this);
// update 3d scene graph
UpdateItemGroup(m_pCurrentItem);
return new_model;
}
vtTransform *vtFrame::AttemptLoad(vtModel *model)
{
VTLOG("AttemptLoad '%s'\n", (const char *) model->m_filename);
model->m_attempted_load = true;
// stop rendering while progress dialog is open
m_canvas->m_bRunning = false;
wxString str(model->m_filename, wxConvUTF8);
OpenProgressDialog(_T("Reading file"), str, false, this);
NodePtr pNode;
vtString fullpath = FindFileOnPaths(vtGetDataPath(), model->m_filename);
if (fullpath != "")
{
UpdateProgressDialog(5, str);
pNode = vtLoadModel(fullpath);
}
CloseProgressDialog();
// resume rendering after progress dialog is closed
m_canvas->m_bRunning = true;
if (!pNode.valid())
{
str.Printf(_T("Sorry, couldn't load model from %hs"), (const char *) model->m_filename);
VTLOG1(str.mb_str(wxConvUTF8));
DisplayMessageBox(str);
return NULL;
}
else
VTLOG(" Loaded OK.\n");
// check
FSphere sphere;
s2v(pNode->getBound(), sphere);
// Wrap in a transform node so that we can scale/rotate the node
vtTransform *pTrans = new vtTransform;
pTrans->setName("Scaling Transform");
pTrans->addChild(pNode);
// Add to map of model -> nodes
m_nodemap[model] = pTrans;
UpdateTransform(model);
return pTrans;
}
void vtFrame::SetCurrentItemAndModel(vtItem *item, vtModel *model)
{
m_blank->Show(item == NULL && model == NULL);
m_pModelDlg->Show(item != NULL && model != NULL);
m_pPropDlg->Show(item != NULL && model == NULL);
SetCurrentItem(item);
SetCurrentModel(model);
if (item != NULL && model == NULL)
{
DisplayCurrentItem();
m_splitter2->ReplaceWindow(m_splitter2->GetWindow2(), m_pPropDlg);
ZoomToCurrentItem();
}
else if (item != NULL && model != NULL)
m_splitter2->ReplaceWindow(m_splitter2->GetWindow2(), m_pModelDlg);
else
m_splitter2->ReplaceWindow(m_splitter2->GetWindow2(), m_blank);
}
void vtFrame::SetCurrentItem(vtItem *item)
{
VTLOG("SetCurrentItem(%s)\n", item == NULL ? "none" : (const char *) item->m_name);
if (item == m_pCurrentItem)
return;
if (m_pCurrentItem)
GetItemGroup(m_pCurrentItem)->GetTop()->SetEnabled(false);
m_pCurrentItem = item;
m_pCurrentModel = NULL;
if (item)
{
UpdateItemGroup(item);
m_pPropDlg->SetCurrentItem(item);
}
m_pTree->RefreshTreeStatus(this);
if (m_pCurrentItem)
GetItemGroup(m_pCurrentItem)->GetTop()->SetEnabled(true);
}
ItemGroup *vtFrame::GetItemGroup(vtItem *item)
{
ItemGroup *ig = m_itemmap[item];
if (!ig)
{
ig = new ItemGroup(item);
m_itemmap[item] = ig;
ig->CreateNodes();
vtScene *pScene = vtGetScene();
vtGroup *pRoot = pScene->GetRoot();
pRoot->addChild(ig->GetTop());
}
return ig;
}
void vtFrame::UpdateItemGroup(vtItem *item)
{
ItemGroup *ig = GetItemGroup(item);
ig->AttemptToLoadModels();
ig->AttachModels(m_pFont);
ig->ShowOrigin(m_bShowOrigin);
ig->ShowRulers(m_bShowRulers);
ig->SetRanges();
}
//
// True to show the current item as an LOD'd object
//
void vtFrame::ShowItemGroupLOD(bool bTrue)
{
if (!m_pCurrentItem)
return;
ItemGroup *ig = GetItemGroup(m_pCurrentItem);
if (ig)
ig->ShowLOD(bTrue);
}
void vtFrame::SetCurrentModel(vtModel *model)
{
VTLOG("SetCurrentModel(%s)\n", model == NULL ? "none" : (const char *) model->m_filename);
if (model == m_pCurrentModel)
return;
// 3d scene graph: turn off previous node
if (m_pCurrentModel)
{
vtTransform *trans = m_nodemap[m_pCurrentModel];
if (trans)
trans->SetEnabled(false);
}
m_pCurrentModel = model;
// update properties dialog
m_pModelDlg->SetCurrentModel(model);
// update 3d scene graph
if (model)
{
DisplayCurrentModel();
ZoomToCurrentModel();
}
// update tree view
m_pTree->RefreshTreeStatus(this);
}
//
// Update 3d scene graph and 3d view
// also attempt to load any models which have not yet been loaded, and put
// the status to the properties dialog
//
void vtFrame::DisplayCurrentModel()
{
// show this individual model, not the LOD'd item
ShowItemGroupLOD(false);
vtTransform *trans = m_nodemap[m_pCurrentModel];
if (!trans && !m_pCurrentModel->m_attempted_load)
{
trans = AttemptLoad(m_pCurrentModel);
}
if (trans)
{
trans->SetEnabled(true);
m_pModelDlg->SetModelStatus("Good");
}
else
{
m_pModelDlg->SetModelStatus("Failed to load.");
}
}
void vtFrame::ZoomToCurrentModel()
{
ZoomToModel(m_pCurrentModel);
}
void vtFrame::ZoomToModel(vtModel *model)
{
vtTransform *trans = m_nodemap[model];
if (!trans)
return;
vtCamera *pCamera = vtGetScene()->GetCamera();
float fYon = pCamera->GetFOV();
FSphere sph;
trans->GetBoundSphere(sph);
// consider the origin-center bounding sphere
float origin_centered = sph.center.Length() + sph.radius;
// how far back does the camera have to be to see the whole sphere
float dist = origin_centered / sinf(fYon / 2);
wxGetApp().m_pTrackball->SetRadius(dist);
wxGetApp().m_pTrackball->SetZoomScale(sph.radius);
wxGetApp().m_pTrackball->SetTransScale(sph.radius/2);
wxGetApp().m_pTrackball->SetTrans(FPoint3(0,0,0));
pCamera->SetYon(sph.radius * 100.0f);
}
void vtFrame::DisplayCurrentItem()
{
ShowItemGroupLOD(true);
}
void vtFrame::ZoomToCurrentItem()
{
if (!m_pCurrentItem)
return;
if (m_pCurrentItem->NumModels() < 1)
return;
vtModel *model = m_pCurrentItem->GetModel(0);
if (model)
ZoomToModel(model);
}
void vtFrame::RefreshTreeItems()
{
m_pTree->RefreshTreeItems(this);
}
void vtFrame::SetItemName(vtItem *item, const vtString &name)
{
item->m_name = name;
m_pPropDlg->SetCurrentItem(item);
}
//////////////////////////////////////////////////////////////////////////
bool DnDFile::OnDropFiles(wxCoord, wxCoord, const wxArrayString& filenames)
{
size_t nFiles = filenames.GetCount();
for ( size_t n = 0; n < nFiles; n++ )
{
wxString str = filenames[n];
if (str.Right(4).CmpNoCase(_T("vtco")) == 0)
GetMainFrame()->LoadContentsFile(str);
else
GetMainFrame()->AddModelFromFile(str);
}
return true;
}
//////////////////////////////////////////////////////////////////////////
void vtFrame::OnTestXML(wxCommandEvent& event)
{
#if 0
vtContentManager Man;
try {
Man.ReadXML("content3.vtco");
Man.WriteXML("content4.vtco");
}
catch (xh_io_exception &e)
{
string str = e.getFormattedMessage();
DisplayMessageBox(wxString(str.c_str(), wxConvUTF8));
return;
}
#elif 0
vtImage *image = new vtImage("C:/TEMP/test_transparent.png");
// Compress
osg::ref_ptr<osg::State> state = new osg::State;
// get OpenGL driver to create texture from image.
vtMaterial *mat = new vtMaterial;
mat->SetTexture(image);
mat->m_pTexture->apply(*state);
image->GetOsgImage()->readImageFromCurrentTexture(0,true);
osgDB::ReaderWriter::WriteResult wr;
osgDB::Registry *reg = osgDB::Registry::instance();
wr = reg->writeImage(*(image->GetOsgImage()), "C:/TEMP/test_transparent.dds");
#endif
}
void vtFrame::DisplayMessageBox(const wxString &str)
{
m_canvas->m_bRunning = false;
wxMessageBox(str);
m_canvas->m_bRunning = true;
m_canvas->Refresh(false);
}
void vtFrame::UpdateCurrentModelLOD()
{
// safety
if (!m_pCurrentItem)
return;
ItemGroup *ig = m_itemmap[m_pCurrentItem];
if (!ig)
return;
ig->SetRanges();
}
void vtFrame::UpdateScale(vtModel *model)
{
UpdateTransform(model);
UpdateItemGroup(m_pCurrentItem);
}
void vtFrame::UpdateTransform(vtModel *model)
{
// scale may occasionally be 0 while the user is typing a new value.
if (model->m_scale == 0.0f)
return;
vtTransform *trans = m_nodemap[model];
if (!trans)
return;
trans->Identity();
vtString ext = GetExtension(model->m_filename, false);
trans->Scale(model->m_scale);
}
void vtFrame::RenderingPause()
{
m_canvas->m_bRunning = false;
}
void vtFrame::RenderingResume()
{
m_canvas->m_bRunning = true;
}
void vtFrame::UpdateStatusText()
{
if (!GetStatusBar())
return;
vtScene *scene = vtGetScene();
if (!scene)
return;
// get framerate
float fps = scene->GetFrameRate();
// get camera distance
float dist = 0;
if (NULL != wxGetApp().m_pTrackball)
dist = wxGetApp().m_pTrackball->GetRadius();
wxString str;
str.Printf(_T("fps %.3g, camera distance %.2f meters"), fps, dist);
SetStatusText(str);
}
| 25.385066 | 91 | 0.701061 | nakijun |
cd24d16e13fdef4060d3fde1f6b9d7b22eaba84f | 1,521 | cpp | C++ | Sources/WebApp/AppFramework/SDL2Caches.cpp | kovacsv/VisualScriptEngineWeb | e7eb8089018969d691a4e47a92eea43e75bfb017 | [
"MIT"
] | 19 | 2020-08-01T14:52:21.000Z | 2022-03-27T01:09:59.000Z | Sources/WebApp/AppFramework/SDL2Caches.cpp | kovacsv/VisualScriptEngineWeb | e7eb8089018969d691a4e47a92eea43e75bfb017 | [
"MIT"
] | 17 | 2020-08-14T15:03:07.000Z | 2020-09-24T17:08:52.000Z | Sources/WebApp/AppFramework/SDL2Caches.cpp | kovacsv/VisualScriptEngineWeb | e7eb8089018969d691a4e47a92eea43e75bfb017 | [
"MIT"
] | null | null | null | #include "SDL2Caches.hpp"
#include "NE_StringUtils.hpp"
FontTextureCacheKey::FontTextureCacheKey (const std::wstring& text, const NUIE::ColorCacheKey& color, int size) :
text (text),
color (color),
size (size)
{
}
bool FontTextureCacheKey::operator== (const FontTextureCacheKey& rhs) const
{
return text == rhs.text && color == rhs.color && size == rhs.size;
}
bool FontTextureCacheKey::operator!= (const FontTextureCacheKey& rhs) const
{
return !operator== (rhs);
}
FontController::FontController (const std::string& fontPath) :
FontCache::Controller (),
fontPath (fontPath)
{
}
TTF_Font* FontController::CreateValue (const int& key)
{
return TTF_OpenFont (fontPath.c_str (), key);
}
void FontController::DisposeValue (TTF_Font*& value)
{
TTF_CloseFont (value);
}
FontTextureController::FontTextureController (SDL_Renderer* renderer, FontCache& fontCache) :
FontTextureCache::Controller (),
renderer (renderer),
fontCache (fontCache)
{
}
SDL_Texture* FontTextureController::CreateValue (const FontTextureCacheKey& key)
{
TTF_Font* ttfFont = fontCache.Get (key.size);
std::string textStr = NE::WStringToString (key.text);
SDL_Color sdlColor = { key.color.r, key.color.g, key.color.b, 255 };
SDL_Surface* surface = TTF_RenderUTF8_Blended (ttfFont, textStr.c_str (), sdlColor);
SDL_Texture* texture = SDL_CreateTextureFromSurface (renderer, surface);
SDL_FreeSurface (surface);
return texture;
}
void FontTextureController::DisposeValue (SDL_Texture*& value)
{
SDL_DestroyTexture (value);
}
| 24.532258 | 113 | 0.748849 | kovacsv |
cd26e8480f16b32070d2ad7407364896f7a40aa1 | 2,308 | cpp | C++ | src/AdventOfCode2020/Day23-CrabCups/Day23-CrabCups.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | src/AdventOfCode2020/Day23-CrabCups/Day23-CrabCups.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | src/AdventOfCode2020/Day23-CrabCups/Day23-CrabCups.cpp | dbartok/advent-of-code-cpp | c8c2df7a21980f8f3e42128f7bc5df8288f18490 | [
"MIT"
] | null | null | null | #include "Day23-CrabCups.h"
#include "CupMixer.h"
#include <AdventOfCodeCommon/DisableLibraryWarningsMacros.h>
__BEGIN_LIBRARIES_DISABLE_WARNINGS
#include <vector>
#include <algorithm>
#include <numeric>
__END_LIBRARIES_DISABLE_WARNINGS
namespace
{
size_t MANY_CUPS_NUMBER = 1'000'000;
}
namespace AdventOfCode
{
namespace Year2020
{
namespace Day23
{
std::vector<size_t> convertStringToDigitwiseVector(const std::string& str)
{
std::vector<size_t> digitwiseVector;
std::transform(str.cbegin(), str.cend(), std::back_inserter(digitwiseVector), [](char c)
{
return c - '0';
});
return digitwiseVector;
}
std::string convertDigitwiseVectorToString(const std::vector<size_t>& digitwiseVector)
{
std::string result;
std::transform(digitwiseVector.cbegin(), digitwiseVector.cend(), std::back_inserter(result), [](size_t digit)
{
return digit + '0';
});
return result;
}
void addPaddingToInitialCups(std::vector<Cup>& cups)
{
const size_t numPaddingCupsRequired = MANY_CUPS_NUMBER - cups.size();
std::vector<Cup> paddingCups(numPaddingCupsRequired);
const size_t firstPaddingCup = cups.size() + 1;
std::iota(paddingCups.begin(), paddingCups.end(), firstPaddingCup);
cups.insert(cups.end(), std::make_move_iterator(paddingCups.cbegin()), std::make_move_iterator(paddingCups.cend()));
}
std::string cupLabelsStartingFromCupOne(const std::string& initialCupLabellingString, size_t numMixes)
{
std::vector<Cup> initialCups = convertStringToDigitwiseVector(initialCupLabellingString);
CupMixer cupMixer{std::move(initialCups)};
cupMixer.mixRepeatedly(numMixes);
std::vector<Cup> labelsOnCupsAfterCupOne = cupMixer.getLabelsOnCupsAfterCupOne();
return convertDigitwiseVectorToString(labelsOnCupsAfterCupOne);
}
int64_t twoCupLabelsAfterCupOneMultipliedManyCups(const std::string& initialCupLabellingString, size_t numMixes)
{
std::vector<Cup> initialCups = convertStringToDigitwiseVector(initialCupLabellingString);
addPaddingToInitialCups(initialCups);
CupMixer cupMixer{std::move(initialCups)};
cupMixer.mixRepeatedly(numMixes);
return cupMixer.getTwoCupLabelsAfterCupOneMultiplied();
}
}
}
}
| 27.807229 | 120 | 0.727903 | dbartok |
cd27753b2c2eb1db41ed81d13b6cccb941eaa480 | 52,967 | cpp | C++ | src/OpenGL/common/Image.cpp | aswimmingfish/swiftshader | dc7759ccc3151a1aefefa9f86610e66f6fe9311c | [
"Apache-2.0"
] | 1 | 2020-09-29T03:14:19.000Z | 2020-09-29T03:14:19.000Z | src/OpenGL/common/Image.cpp | longde123/SwiftShader | 2ddef8858e5015140f374d5c06d1a68b7c78af10 | [
"Apache-2.0"
] | null | null | null | src/OpenGL/common/Image.cpp | longde123/SwiftShader | 2ddef8858e5015140f374d5c06d1a68b7c78af10 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 The SwiftShader Authors. 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 "Image.hpp"
#include "Renderer/Blitter.hpp"
#include "../libEGL/Texture.hpp"
#include "../common/debug.h"
#include "Common/Math.hpp"
#include "Common/Thread.hpp"
#include <GLES3/gl3.h>
#include <string.h>
namespace
{
int getNumBlocks(int w, int h, int blockSizeX, int blockSizeY)
{
return ((w + blockSizeX - 1) / blockSizeX) * ((h + blockSizeY - 1) / blockSizeY);
}
enum DataType
{
Bytes_1,
Bytes_2,
Bytes_4,
Bytes_8,
Bytes_16,
ByteRGB,
UByteRGB,
ShortRGB,
UShortRGB,
IntRGB,
UIntRGB,
RGB565,
FloatRGB,
HalfFloatRGB,
RGBA4444,
RGBA5551,
RGB10A2UI,
R11G11B10F,
RGB9E5,
SRGB,
SRGBA,
D16,
D24,
D32,
D32F,
S8,
S24_8,
};
template<DataType dataType>
void LoadImageRow(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
UNIMPLEMENTED();
}
template<>
void LoadImageRow<Bytes_1>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset, source, width);
}
template<>
void LoadImageRow<Bytes_2>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 2, source, width * 2);
}
template<>
void LoadImageRow<Bytes_4>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 4, source, width * 4);
}
template<>
void LoadImageRow<Bytes_8>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 8, source, width * 8);
}
template<>
void LoadImageRow<Bytes_16>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 16, source, width * 16);
}
template<>
void LoadImageRow<ByteRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
unsigned char *destB = dest + xoffset * 4;
for(int x = 0; x < width; x++)
{
destB[4 * x + 0] = source[x * 3 + 0];
destB[4 * x + 1] = source[x * 3 + 1];
destB[4 * x + 2] = source[x * 3 + 2];
destB[4 * x + 3] = 0x7F;
}
}
template<>
void LoadImageRow<UByteRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
unsigned char *destB = dest + xoffset * 4;
for(int x = 0; x < width; x++)
{
destB[4 * x + 0] = source[x * 3 + 0];
destB[4 * x + 1] = source[x * 3 + 1];
destB[4 * x + 2] = source[x * 3 + 2];
destB[4 * x + 3] = 0xFF;
}
}
template<>
void LoadImageRow<ShortRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *sourceS = reinterpret_cast<const unsigned short*>(source);
unsigned short *destS = reinterpret_cast<unsigned short*>(dest + xoffset * 8);
for(int x = 0; x < width; x++)
{
destS[4 * x + 0] = sourceS[x * 3 + 0];
destS[4 * x + 1] = sourceS[x * 3 + 1];
destS[4 * x + 2] = sourceS[x * 3 + 2];
destS[4 * x + 3] = 0x7FFF;
}
}
template<>
void LoadImageRow<UShortRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *sourceS = reinterpret_cast<const unsigned short*>(source);
unsigned short *destS = reinterpret_cast<unsigned short*>(dest + xoffset * 8);
for(int x = 0; x < width; x++)
{
destS[4 * x + 0] = sourceS[x * 3 + 0];
destS[4 * x + 1] = sourceS[x * 3 + 1];
destS[4 * x + 2] = sourceS[x * 3 + 2];
destS[4 * x + 3] = 0xFFFF;
}
}
template<>
void LoadImageRow<IntRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceI = reinterpret_cast<const unsigned int*>(source);
unsigned int *destI = reinterpret_cast<unsigned int*>(dest + xoffset * 16);
for(int x = 0; x < width; x++)
{
destI[4 * x + 0] = sourceI[x * 3 + 0];
destI[4 * x + 1] = sourceI[x * 3 + 1];
destI[4 * x + 2] = sourceI[x * 3 + 2];
destI[4 * x + 3] = 0x7FFFFFFF;
}
}
template<>
void LoadImageRow<UIntRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceI = reinterpret_cast<const unsigned int*>(source);
unsigned int *destI = reinterpret_cast<unsigned int*>(dest + xoffset * 16);
for(int x = 0; x < width; x++)
{
destI[4 * x + 0] = sourceI[x * 3 + 0];
destI[4 * x + 1] = sourceI[x * 3 + 1];
destI[4 * x + 2] = sourceI[x * 3 + 2];
destI[4 * x + 3] = 0xFFFFFFFF;
}
}
template<>
void LoadImageRow<RGB565>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
memcpy(dest + xoffset * 2, source, width * 2);
}
template<>
void LoadImageRow<FloatRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const float *sourceF = reinterpret_cast<const float*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 16);
for(int x = 0; x < width; x++)
{
destF[4 * x + 0] = sourceF[x * 3 + 0];
destF[4 * x + 1] = sourceF[x * 3 + 1];
destF[4 * x + 2] = sourceF[x * 3 + 2];
destF[4 * x + 3] = 1.0f;
}
}
template<>
void LoadImageRow<HalfFloatRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *sourceH = reinterpret_cast<const unsigned short*>(source);
unsigned short *destH = reinterpret_cast<unsigned short*>(dest + xoffset * 8);
for(int x = 0; x < width; x++)
{
destH[4 * x + 0] = sourceH[x * 3 + 0];
destH[4 * x + 1] = sourceH[x * 3 + 1];
destH[4 * x + 2] = sourceH[x * 3 + 2];
destH[4 * x + 3] = 0x3C00; // SEEEEEMMMMMMMMMM, S = 0, E = 15, M = 0: 16bit flpt representation of 1
}
}
template<>
void LoadImageRow<RGBA4444>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *source4444 = reinterpret_cast<const unsigned short*>(source);
unsigned char *dest4444 = dest + xoffset * 4;
for(int x = 0; x < width; x++)
{
unsigned short rgba = source4444[x];
dest4444[4 * x + 0] = ((rgba & 0x00F0) << 0) | ((rgba & 0x00F0) >> 4);
dest4444[4 * x + 1] = ((rgba & 0x0F00) >> 4) | ((rgba & 0x0F00) >> 8);
dest4444[4 * x + 2] = ((rgba & 0xF000) >> 8) | ((rgba & 0xF000) >> 12);
dest4444[4 * x + 3] = ((rgba & 0x000F) << 4) | ((rgba & 0x000F) >> 0);
}
}
template<>
void LoadImageRow<RGBA5551>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *source5551 = reinterpret_cast<const unsigned short*>(source);
unsigned char *dest5551 = dest + xoffset * 4;
for(int x = 0; x < width; x++)
{
unsigned short rgba = source5551[x];
dest5551[4 * x + 0] = ((rgba & 0x003E) << 2) | ((rgba & 0x003E) >> 3);
dest5551[4 * x + 1] = ((rgba & 0x07C0) >> 3) | ((rgba & 0x07C0) >> 8);
dest5551[4 * x + 2] = ((rgba & 0xF800) >> 8) | ((rgba & 0xF800) >> 13);
dest5551[4 * x + 3] = (rgba & 0x0001) ? 0xFF : 0;
}
}
template<>
void LoadImageRow<RGB10A2UI>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *source1010102U = reinterpret_cast<const unsigned int*>(source);
unsigned short *dest16U = reinterpret_cast<unsigned short*>(dest + xoffset * 8);
for(int x = 0; x < width; x++)
{
unsigned int rgba = source1010102U[x];
dest16U[4 * x + 0] = (rgba & 0x00000FFC) >> 2;
dest16U[4 * x + 1] = (rgba & 0x003FF000) >> 12;
dest16U[4 * x + 2] = (rgba & 0xFFC00000) >> 22;
dest16U[4 * x + 3] = (rgba & 0x00000003);
}
}
template<>
void LoadImageRow<R11G11B10F>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const sw::R11G11B10FData *sourceRGB = reinterpret_cast<const sw::R11G11B10FData*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 16);
for(int x = 0; x < width; x++, sourceRGB++, destF+=4)
{
sourceRGB->toRGBFloats(destF);
destF[3] = 1.0f;
}
}
template<>
void LoadImageRow<RGB9E5>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const sw::RGB9E5Data *sourceRGB = reinterpret_cast<const sw::RGB9E5Data*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 16);
for(int x = 0; x < width; x++, sourceRGB++, destF += 4)
{
sourceRGB->toRGBFloats(destF);
destF[3] = 1.0f;
}
}
template<>
void LoadImageRow<SRGB>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
dest += xoffset * 4;
for(int x = 0; x < width; x++)
{
for(int rgb = 0; rgb < 3; ++rgb)
{
*dest++ = sw::sRGB8toLinear8(*source++);
}
*dest++ = 255;
}
}
template<>
void LoadImageRow<SRGBA>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
dest += xoffset * 4;
for(int x = 0; x < width; x++)
{
for(int rgb = 0; rgb < 3; ++rgb)
{
*dest++ = sw::sRGB8toLinear8(*source++);
}
*dest++ = *source++;
}
}
template<>
void LoadImageRow<D16>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned short *sourceD16 = reinterpret_cast<const unsigned short*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 4);
for(int x = 0; x < width; x++)
{
destF[x] = (float)sourceD16[x] / 0xFFFF;
}
}
template<>
void LoadImageRow<D24>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceD24 = reinterpret_cast<const unsigned int*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 4);
for(int x = 0; x < width; x++)
{
destF[x] = (float)(sourceD24[x] & 0xFFFFFF00) / 0xFFFFFF00;
}
}
template<>
void LoadImageRow<D32>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceD32 = reinterpret_cast<const unsigned int*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 4);
for(int x = 0; x < width; x++)
{
destF[x] = (float)sourceD32[x] / 0xFFFFFFFF;
}
}
template<>
void LoadImageRow<S8>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
const unsigned int *sourceI = reinterpret_cast<const unsigned int*>(source);
unsigned char *destI = dest + xoffset;
for(int x = 0; x < width; x++)
{
destI[x] = static_cast<unsigned char>(sourceI[x] & 0x000000FF); // FIXME: Quad layout
}
}
template<>
void LoadImageRow<D32F>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
struct D32FS8 { float depth32f; unsigned int stencil24_8; };
const D32FS8 *sourceD32FS8 = reinterpret_cast<const D32FS8*>(source);
float *destF = reinterpret_cast<float*>(dest + xoffset * 4);
for(int x = 0; x < width; x++)
{
destF[x] = sourceD32FS8[x].depth32f;
}
}
template<>
void LoadImageRow<S24_8>(const unsigned char *source, unsigned char *dest, GLint xoffset, GLsizei width)
{
struct D32FS8 { float depth32f; unsigned int stencil24_8; };
const D32FS8 *sourceD32FS8 = reinterpret_cast<const D32FS8*>(source);
unsigned char *destI = dest + xoffset;
for(int x = 0; x < width; x++)
{
destI[x] = static_cast<unsigned char>(sourceD32FS8[x].stencil24_8 & 0x000000FF); // FIXME: Quad layout
}
}
template<DataType dataType>
void LoadImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, int inputPitch, int inputHeight, int destPitch, GLsizei destHeight, const void *input, void *buffer)
{
for(int z = 0; z < depth; ++z)
{
const unsigned char *inputStart = static_cast<const unsigned char*>(input) + (z * inputPitch * inputHeight);
unsigned char *destStart = static_cast<unsigned char*>(buffer) + ((zoffset + z) * destPitch * destHeight);
for(int y = 0; y < height; ++y)
{
const unsigned char *source = inputStart + y * inputPitch;
unsigned char *dest = destStart + (y + yoffset) * destPitch;
LoadImageRow<dataType>(source, dest, xoffset, width);
}
}
}
}
namespace egl
{
sw::Format ConvertFormatType(GLenum format, GLenum type)
{
switch(format)
{
case GL_LUMINANCE:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_L8;
case GL_HALF_FLOAT: return sw::FORMAT_L16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_L16F;
case GL_FLOAT: return sw::FORMAT_L32F;
default: UNREACHABLE(type);
}
break;
case GL_LUMINANCE8_EXT:
return sw::FORMAT_L8;
case GL_LUMINANCE16F_EXT:
return sw::FORMAT_L16F;
case GL_LUMINANCE32F_EXT:
return sw::FORMAT_L32F;
case GL_LUMINANCE_ALPHA:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_A8L8;
case GL_HALF_FLOAT: return sw::FORMAT_A16L16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_A16L16F;
case GL_FLOAT: return sw::FORMAT_A32L32F;
default: UNREACHABLE(type);
}
break;
case GL_LUMINANCE8_ALPHA8_EXT:
return sw::FORMAT_A8L8;
case GL_LUMINANCE_ALPHA16F_EXT:
return sw::FORMAT_A16L16F;
case GL_LUMINANCE_ALPHA32F_EXT:
return sw::FORMAT_A32L32F;
case GL_RGBA:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_A8B8G8R8;
case GL_UNSIGNED_SHORT_4_4_4_4: return sw::FORMAT_R4G4B4A4;
case GL_UNSIGNED_SHORT_5_5_5_1: return sw::FORMAT_R5G5B5A1;
case GL_HALF_FLOAT: return sw::FORMAT_A16B16G16R16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_A16B16G16R16F;
case GL_FLOAT: return sw::FORMAT_A32B32G32R32F;
default: UNREACHABLE(type);
}
break;
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_A8R8G8B8;
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT: return sw::FORMAT_A4R4G4B4;
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT: return sw::FORMAT_A1R5G5B5;
default: UNREACHABLE(type);
}
break;
case GL_RGB:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_B8G8R8;
case GL_UNSIGNED_SHORT_5_6_5: return sw::FORMAT_R5G6B5;
case GL_HALF_FLOAT: return sw::FORMAT_B16G16R16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_B16G16R16F;
case GL_FLOAT: return sw::FORMAT_B32G32R32F;
default: UNREACHABLE(type);
}
break;
case GL_ALPHA:
switch(type)
{
case GL_UNSIGNED_BYTE: return sw::FORMAT_A8;
case GL_HALF_FLOAT: return sw::FORMAT_A16F;
case GL_HALF_FLOAT_OES: return sw::FORMAT_A16F;
case GL_FLOAT: return sw::FORMAT_A32F;
default: UNREACHABLE(type);
}
break;
case GL_ALPHA8_EXT:
return sw::FORMAT_A8;
case GL_ALPHA16F_EXT:
return sw::FORMAT_A16F;
case GL_ALPHA32F_EXT:
return sw::FORMAT_A32F;
case GL_RED_INTEGER:
switch(type)
{
case GL_INT: return sw::FORMAT_R32I;
case GL_UNSIGNED_INT: return sw::FORMAT_R32UI;
default: UNREACHABLE(type);
}
break;
case GL_RG_INTEGER:
switch(type)
{
case GL_INT: return sw::FORMAT_G32R32I;
case GL_UNSIGNED_INT: return sw::FORMAT_G32R32UI;
default: UNREACHABLE(type);
}
break;
case GL_RGBA_INTEGER:
switch(type)
{
case GL_INT: return sw::FORMAT_A32B32G32R32I;
case GL_UNSIGNED_INT: return sw::FORMAT_A32B32G32R32UI;
default: UNREACHABLE(type);
}
break;
case GL_DEPTH_COMPONENT:
switch(type)
{
case GL_UNSIGNED_SHORT: return sw::FORMAT_D16;
case GL_UNSIGNED_INT_24_8_OES: return sw::FORMAT_D24S8;
case GL_UNSIGNED_INT: return sw::FORMAT_D32;
case GL_FLOAT: return sw::FORMAT_D32F;
default: UNREACHABLE(type);
}
break;
default:
UNREACHABLE(format);
}
return sw::FORMAT_NULL;
}
sw::Format SelectInternalFormat(GLenum format, GLenum type)
{
switch(format)
{
case GL_ETC1_RGB8_OES:
return sw::FORMAT_ETC1;
case GL_COMPRESSED_R11_EAC:
return sw::FORMAT_R11_EAC;
case GL_COMPRESSED_SIGNED_R11_EAC:
return sw::FORMAT_SIGNED_R11_EAC;
case GL_COMPRESSED_RG11_EAC:
return sw::FORMAT_RG11_EAC;
case GL_COMPRESSED_SIGNED_RG11_EAC:
return sw::FORMAT_SIGNED_RG11_EAC;
case GL_COMPRESSED_RGB8_ETC2:
return sw::FORMAT_RGB8_ETC2;
case GL_COMPRESSED_SRGB8_ETC2:
return sw::FORMAT_SRGB8_ETC2;
case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
return sw::FORMAT_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
return sw::FORMAT_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GL_COMPRESSED_RGBA8_ETC2_EAC:
return sw::FORMAT_RGBA8_ETC2_EAC;
case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
return sw::FORMAT_SRGB8_ALPHA8_ETC2_EAC;
case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:
return sw::FORMAT_RGBA_ASTC_4x4_KHR;
case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:
return sw::FORMAT_RGBA_ASTC_5x4_KHR;
case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:
return sw::FORMAT_RGBA_ASTC_5x5_KHR;
case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:
return sw::FORMAT_RGBA_ASTC_6x5_KHR;
case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:
return sw::FORMAT_RGBA_ASTC_6x6_KHR;
case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:
return sw::FORMAT_RGBA_ASTC_8x5_KHR;
case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:
return sw::FORMAT_RGBA_ASTC_8x6_KHR;
case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:
return sw::FORMAT_RGBA_ASTC_8x8_KHR;
case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:
return sw::FORMAT_RGBA_ASTC_10x5_KHR;
case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:
return sw::FORMAT_RGBA_ASTC_10x6_KHR;
case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:
return sw::FORMAT_RGBA_ASTC_10x8_KHR;
case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:
return sw::FORMAT_RGBA_ASTC_10x10_KHR;
case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:
return sw::FORMAT_RGBA_ASTC_12x10_KHR;
case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:
return sw::FORMAT_RGBA_ASTC_12x12_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_4x4_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_5x4_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_5x5_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_6x5_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_6x6_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x5_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x6_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_8x8_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x5_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x6_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x8_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_10x10_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_12x10_KHR;
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
return sw::FORMAT_SRGB8_ALPHA8_ASTC_12x12_KHR;
#if S3TC_SUPPORT
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
return sw::FORMAT_DXT1;
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
return sw::FORMAT_DXT3;
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
return sw::FORMAT_DXT5;
#endif
default:
break;
}
switch(type)
{
case GL_FLOAT:
switch(format)
{
case GL_ALPHA:
case GL_ALPHA32F_EXT:
return sw::FORMAT_A32F;
case GL_LUMINANCE:
case GL_LUMINANCE32F_EXT:
return sw::FORMAT_L32F;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE_ALPHA32F_EXT:
return sw::FORMAT_A32L32F;
case GL_RED:
case GL_R32F:
return sw::FORMAT_R32F;
case GL_RG:
case GL_RG32F:
return sw::FORMAT_G32R32F;
case GL_RGB:
case GL_RGB32F:
return sw::FORMAT_X32B32G32R32F;
case GL_RGBA:
case GL_RGBA32F:
return sw::FORMAT_A32B32G32R32F;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT32F:
return sw::FORMAT_D32F;
default:
UNREACHABLE(format);
}
case GL_HALF_FLOAT:
case GL_HALF_FLOAT_OES:
switch(format)
{
case GL_ALPHA:
case GL_ALPHA16F_EXT:
return sw::FORMAT_A16F;
case GL_LUMINANCE:
case GL_LUMINANCE16F_EXT:
return sw::FORMAT_L16F;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE_ALPHA16F_EXT:
return sw::FORMAT_A16L16F;
case GL_RED:
case GL_R16F:
return sw::FORMAT_R16F;
case GL_RG:
case GL_RG16F:
return sw::FORMAT_G16R16F;
case GL_RGB:
case GL_RGB16F:
case GL_RGBA:
case GL_RGBA16F:
return sw::FORMAT_A16B16G16R16F;
default:
UNREACHABLE(format);
}
case GL_BYTE:
switch(format)
{
case GL_R8_SNORM:
case GL_R8:
case GL_RED:
return sw::FORMAT_R8I_SNORM;
case GL_R8I:
case GL_RED_INTEGER:
return sw::FORMAT_R8I;
case GL_RG8_SNORM:
case GL_RG8:
case GL_RG:
return sw::FORMAT_G8R8I_SNORM;
case GL_RG8I:
case GL_RG_INTEGER:
return sw::FORMAT_G8R8I;
case GL_RGB8_SNORM:
case GL_RGB8:
case GL_RGB:
return sw::FORMAT_X8B8G8R8I_SNORM;
case GL_RGB8I:
case GL_RGB_INTEGER:
return sw::FORMAT_X8B8G8R8I;
case GL_RGBA8_SNORM:
case GL_RGBA8:
case GL_RGBA:
return sw::FORMAT_A8B8G8R8I_SNORM;
case GL_RGBA8I:
case GL_RGBA_INTEGER:
return sw::FORMAT_A8B8G8R8I;
default:
UNREACHABLE(format);
}
case GL_UNSIGNED_BYTE:
switch(format)
{
case GL_LUMINANCE:
case GL_LUMINANCE8_EXT:
return sw::FORMAT_L8;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE8_ALPHA8_EXT:
return sw::FORMAT_A8L8;
case GL_R8_SNORM:
case GL_R8:
case GL_RED:
return sw::FORMAT_R8;
case GL_R8UI:
case GL_RED_INTEGER:
return sw::FORMAT_R8UI;
case GL_RG8_SNORM:
case GL_RG8:
case GL_RG:
return sw::FORMAT_G8R8;
case GL_RG8UI:
case GL_RG_INTEGER:
return sw::FORMAT_G8R8UI;
case GL_RGB8_SNORM:
case GL_RGB8:
case GL_RGB:
case GL_SRGB8:
return sw::FORMAT_X8B8G8R8;
case GL_RGB8UI:
case GL_RGB_INTEGER:
return sw::FORMAT_X8B8G8R8UI;
case GL_RGBA8_SNORM:
case GL_RGBA8:
case GL_RGBA:
case GL_SRGB8_ALPHA8:
return sw::FORMAT_A8B8G8R8;
case GL_RGBA8UI:
case GL_RGBA_INTEGER:
return sw::FORMAT_A8B8G8R8UI;
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
return sw::FORMAT_A8R8G8B8;
case GL_ALPHA:
case GL_ALPHA8_EXT:
return sw::FORMAT_A8;
case SW_YV12_BT601:
return sw::FORMAT_YV12_BT601;
case SW_YV12_BT709:
return sw::FORMAT_YV12_BT709;
case SW_YV12_JFIF:
return sw::FORMAT_YV12_JFIF;
default:
UNREACHABLE(format);
}
case GL_SHORT:
switch(format)
{
case GL_R16I:
case GL_RED_INTEGER:
return sw::FORMAT_R16I;
case GL_RG16I:
case GL_RG_INTEGER:
return sw::FORMAT_G16R16I;
case GL_RGB16I:
case GL_RGB_INTEGER:
return sw::FORMAT_X16B16G16R16I;
case GL_RGBA16I:
case GL_RGBA_INTEGER:
return sw::FORMAT_A16B16G16R16I;
default:
UNREACHABLE(format);
}
case GL_UNSIGNED_SHORT:
switch(format)
{
case GL_R16UI:
case GL_RED_INTEGER:
return sw::FORMAT_R16UI;
case GL_RG16UI:
case GL_RG_INTEGER:
return sw::FORMAT_G16R16UI;
case GL_RGB16UI:
case GL_RGB_INTEGER:
return sw::FORMAT_X16B16G16R16UI;
case GL_RGBA16UI:
case GL_RGBA_INTEGER:
return sw::FORMAT_A16B16G16R16UI;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT16:
return sw::FORMAT_D32FS8_TEXTURE;
default:
UNREACHABLE(format);
}
case GL_INT:
switch(format)
{
case GL_RED_INTEGER:
case GL_R32I:
return sw::FORMAT_R32I;
case GL_RG_INTEGER:
case GL_RG32I:
return sw::FORMAT_G32R32I;
case GL_RGB_INTEGER:
case GL_RGB32I:
return sw::FORMAT_X32B32G32R32I;
case GL_RGBA_INTEGER:
case GL_RGBA32I:
return sw::FORMAT_A32B32G32R32I;
default:
UNREACHABLE(format);
}
case GL_UNSIGNED_INT:
switch(format)
{
case GL_RED_INTEGER:
case GL_R32UI:
return sw::FORMAT_R32UI;
case GL_RG_INTEGER:
case GL_RG32UI:
return sw::FORMAT_G32R32UI;
case GL_RGB_INTEGER:
case GL_RGB32UI:
return sw::FORMAT_X32B32G32R32UI;
case GL_RGBA_INTEGER:
case GL_RGBA32UI:
return sw::FORMAT_A32B32G32R32UI;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32_OES:
return sw::FORMAT_D32FS8_TEXTURE;
default:
UNREACHABLE(format);
}
case GL_UNSIGNED_INT_24_8_OES:
if(format == GL_DEPTH_STENCIL || format == GL_DEPTH24_STENCIL8)
{
return sw::FORMAT_D32FS8_TEXTURE;
}
else UNREACHABLE(format);
case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
if(format == GL_DEPTH_STENCIL || format == GL_DEPTH32F_STENCIL8)
{
return sw::FORMAT_D32FS8_TEXTURE;
}
else UNREACHABLE(format);
case GL_UNSIGNED_SHORT_4_4_4_4:
return sw::FORMAT_A8R8G8B8;
case GL_UNSIGNED_SHORT_5_5_5_1:
return sw::FORMAT_A8R8G8B8;
case GL_UNSIGNED_SHORT_5_6_5:
return sw::FORMAT_R5G6B5;
case GL_UNSIGNED_INT_2_10_10_10_REV:
if(format == GL_RGB10_A2UI)
{
return sw::FORMAT_A16B16G16R16UI;
}
else
{
return sw::FORMAT_A2B10G10R10;
}
case GL_UNSIGNED_INT_10F_11F_11F_REV:
case GL_UNSIGNED_INT_5_9_9_9_REV:
return sw::FORMAT_A32B32G32R32F;
default:
UNREACHABLE(type);
}
return sw::FORMAT_NULL;
}
// Returns the size, in bytes, of a single texel in an Image
static int ComputePixelSize(GLenum format, GLenum type)
{
switch(type)
{
case GL_BYTE:
switch(format)
{
case GL_R8:
case GL_R8I:
case GL_R8_SNORM:
case GL_RED: return sizeof(char);
case GL_RED_INTEGER: return sizeof(char);
case GL_RG8:
case GL_RG8I:
case GL_RG8_SNORM:
case GL_RG: return sizeof(char) * 2;
case GL_RG_INTEGER: return sizeof(char) * 2;
case GL_RGB8:
case GL_RGB8I:
case GL_RGB8_SNORM:
case GL_RGB: return sizeof(char) * 3;
case GL_RGB_INTEGER: return sizeof(char) * 3;
case GL_RGBA8:
case GL_RGBA8I:
case GL_RGBA8_SNORM:
case GL_RGBA: return sizeof(char) * 4;
case GL_RGBA_INTEGER: return sizeof(char) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_BYTE:
switch(format)
{
case GL_R8:
case GL_R8UI:
case GL_RED: return sizeof(unsigned char);
case GL_RED_INTEGER: return sizeof(unsigned char);
case GL_ALPHA8_EXT:
case GL_ALPHA: return sizeof(unsigned char);
case GL_LUMINANCE8_EXT:
case GL_LUMINANCE: return sizeof(unsigned char);
case GL_LUMINANCE8_ALPHA8_EXT:
case GL_LUMINANCE_ALPHA: return sizeof(unsigned char) * 2;
case GL_RG8:
case GL_RG8UI:
case GL_RG: return sizeof(unsigned char) * 2;
case GL_RG_INTEGER: return sizeof(unsigned char) * 2;
case GL_RGB8:
case GL_RGB8UI:
case GL_SRGB8:
case GL_RGB: return sizeof(unsigned char) * 3;
case GL_RGB_INTEGER: return sizeof(unsigned char) * 3;
case GL_RGBA8:
case GL_RGBA8UI:
case GL_SRGB8_ALPHA8:
case GL_RGBA: return sizeof(unsigned char) * 4;
case GL_RGBA_INTEGER: return sizeof(unsigned char) * 4;
case GL_BGRA_EXT:
case GL_BGRA8_EXT: return sizeof(unsigned char)* 4;
default: UNREACHABLE(format);
}
break;
case GL_SHORT:
switch(format)
{
case GL_R16I:
case GL_RED_INTEGER: return sizeof(short);
case GL_RG16I:
case GL_RG_INTEGER: return sizeof(short) * 2;
case GL_RGB16I:
case GL_RGB_INTEGER: return sizeof(short) * 3;
case GL_RGBA16I:
case GL_RGBA_INTEGER: return sizeof(short) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT:
switch(format)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT: return sizeof(unsigned short);
case GL_R16UI:
case GL_RED_INTEGER: return sizeof(unsigned short);
case GL_RG16UI:
case GL_RG_INTEGER: return sizeof(unsigned short) * 2;
case GL_RGB16UI:
case GL_RGB_INTEGER: return sizeof(unsigned short) * 3;
case GL_RGBA16UI:
case GL_RGBA_INTEGER: return sizeof(unsigned short) * 4;
default: UNREACHABLE(format);
}
break;
case GL_INT:
switch(format)
{
case GL_R32I:
case GL_RED_INTEGER: return sizeof(int);
case GL_RG32I:
case GL_RG_INTEGER: return sizeof(int) * 2;
case GL_RGB32I:
case GL_RGB_INTEGER: return sizeof(int) * 3;
case GL_RGBA32I:
case GL_RGBA_INTEGER: return sizeof(int) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT:
switch(format)
{
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH_COMPONENT: return sizeof(unsigned int);
case GL_R32UI:
case GL_RED_INTEGER: return sizeof(unsigned int);
case GL_RG32UI:
case GL_RG_INTEGER: return sizeof(unsigned int) * 2;
case GL_RGB32UI:
case GL_RGB_INTEGER: return sizeof(unsigned int) * 3;
case GL_RGBA32UI:
case GL_RGBA_INTEGER: return sizeof(unsigned int) * 4;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_4_4_4_4:
case GL_UNSIGNED_SHORT_5_5_5_1:
case GL_UNSIGNED_SHORT_5_6_5:
case GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT:
case GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT:
return sizeof(unsigned short);
case GL_UNSIGNED_INT_10F_11F_11F_REV:
case GL_UNSIGNED_INT_5_9_9_9_REV:
case GL_UNSIGNED_INT_2_10_10_10_REV:
case GL_UNSIGNED_INT_24_8_OES:
return sizeof(unsigned int);
case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
return sizeof(float) + sizeof(unsigned int);
case GL_FLOAT:
switch(format)
{
case GL_DEPTH_COMPONENT32F:
case GL_DEPTH_COMPONENT: return sizeof(float);
case GL_ALPHA32F_EXT:
case GL_ALPHA: return sizeof(float);
case GL_LUMINANCE32F_EXT:
case GL_LUMINANCE: return sizeof(float);
case GL_LUMINANCE_ALPHA32F_EXT:
case GL_LUMINANCE_ALPHA: return sizeof(float) * 2;
case GL_RED: return sizeof(float);
case GL_R32F: return sizeof(float);
case GL_RG: return sizeof(float) * 2;
case GL_RG32F: return sizeof(float) * 2;
case GL_RGB: return sizeof(float) * 3;
case GL_RGB32F: return sizeof(float) * 3;
case GL_RGBA: return sizeof(float) * 4;
case GL_RGBA32F: return sizeof(float) * 4;
default: UNREACHABLE(format);
}
break;
case GL_HALF_FLOAT:
case GL_HALF_FLOAT_OES:
switch(format)
{
case GL_ALPHA16F_EXT:
case GL_ALPHA: return sizeof(unsigned short);
case GL_LUMINANCE16F_EXT:
case GL_LUMINANCE: return sizeof(unsigned short);
case GL_LUMINANCE_ALPHA16F_EXT:
case GL_LUMINANCE_ALPHA: return sizeof(unsigned short) * 2;
case GL_RED: return sizeof(unsigned short);
case GL_R16F: return sizeof(unsigned short);
case GL_RG: return sizeof(unsigned short) * 2;
case GL_RG16F: return sizeof(unsigned short) * 2;
case GL_RGB: return sizeof(unsigned short) * 3;
case GL_RGB16F: return sizeof(unsigned short) * 3;
case GL_RGBA: return sizeof(unsigned short) * 4;
case GL_RGBA16F: return sizeof(unsigned short) * 4;
default: UNREACHABLE(format);
}
break;
default: UNREACHABLE(type);
}
return 0;
}
GLsizei ComputePitch(GLsizei width, GLenum format, GLenum type, GLint alignment)
{
ASSERT(alignment > 0 && sw::isPow2(alignment));
GLsizei rawPitch = ComputePixelSize(format, type) * width;
return (rawPitch + alignment - 1) & ~(alignment - 1);
}
size_t ComputePackingOffset(GLenum format, GLenum type, GLsizei width, GLsizei height, GLint alignment, GLint skipImages, GLint skipRows, GLint skipPixels)
{
GLsizei pitchB = ComputePitch(width, format, type, alignment);
return (skipImages * height + skipRows) * pitchB + skipPixels * ComputePixelSize(format, type);
}
inline GLsizei ComputeCompressedPitch(GLsizei width, GLenum format)
{
return ComputeCompressedSize(width, 1, format);
}
GLsizei ComputeCompressedSize(GLsizei width, GLsizei height, GLenum format)
{
switch(format)
{
case GL_COMPRESSED_RGB_S3TC_DXT1_EXT:
case GL_COMPRESSED_RGBA_S3TC_DXT1_EXT:
case GL_ETC1_RGB8_OES:
case GL_COMPRESSED_R11_EAC:
case GL_COMPRESSED_SIGNED_R11_EAC:
case GL_COMPRESSED_RGB8_ETC2:
case GL_COMPRESSED_SRGB8_ETC2:
case GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2:
case GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2:
return 8 * getNumBlocks(width, height, 4, 4);
case GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE:
case GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE:
case GL_COMPRESSED_RG11_EAC:
case GL_COMPRESSED_SIGNED_RG11_EAC:
case GL_COMPRESSED_RGBA8_ETC2_EAC:
case GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:
case GL_COMPRESSED_RGBA_ASTC_4x4_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:
return 16 * getNumBlocks(width, height, 4, 4);
case GL_COMPRESSED_RGBA_ASTC_5x4_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:
return 16 * getNumBlocks(width, height, 5, 4);
case GL_COMPRESSED_RGBA_ASTC_5x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:
return 16 * getNumBlocks(width, height, 5, 5);
case GL_COMPRESSED_RGBA_ASTC_6x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:
return 16 * getNumBlocks(width, height, 6, 5);
case GL_COMPRESSED_RGBA_ASTC_6x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:
return 16 * getNumBlocks(width, height, 6, 6);
case GL_COMPRESSED_RGBA_ASTC_8x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:
return 16 * getNumBlocks(width, height, 8, 5);
case GL_COMPRESSED_RGBA_ASTC_8x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:
return 16 * getNumBlocks(width, height, 8, 6);
case GL_COMPRESSED_RGBA_ASTC_8x8_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:
return 16 * getNumBlocks(width, height, 8, 8);
case GL_COMPRESSED_RGBA_ASTC_10x5_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:
return 16 * getNumBlocks(width, height, 10, 5);
case GL_COMPRESSED_RGBA_ASTC_10x6_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:
return 16 * getNumBlocks(width, height, 10, 6);
case GL_COMPRESSED_RGBA_ASTC_10x8_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:
return 16 * getNumBlocks(width, height, 10, 8);
case GL_COMPRESSED_RGBA_ASTC_10x10_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:
return 16 * getNumBlocks(width, height, 10, 10);
case GL_COMPRESSED_RGBA_ASTC_12x10_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:
return 16 * getNumBlocks(width, height, 12, 10);
case GL_COMPRESSED_RGBA_ASTC_12x12_KHR:
case GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:
return 16 * getNumBlocks(width, height, 12, 12);
default:
return 0;
}
}
void Image::typeinfo() {}
Image::~Image()
{
if(parentTexture)
{
parentTexture->release();
}
ASSERT(!shared);
}
void Image::release()
{
int refs = dereference();
if(refs > 0)
{
if(parentTexture)
{
parentTexture->sweep();
}
}
else
{
delete this;
}
}
void Image::unbind(const egl::Texture *parent)
{
if(parentTexture == parent)
{
parentTexture = nullptr;
}
release();
}
bool Image::isChildOf(const egl::Texture *parent) const
{
return parentTexture == parent;
}
void Image::loadImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLenum format, GLenum type, const UnpackInfo& unpackInfo, const void *input)
{
GLsizei inputWidth = (unpackInfo.rowLength == 0) ? width : unpackInfo.rowLength;
GLsizei inputPitch = ComputePitch(inputWidth, format, type, unpackInfo.alignment);
GLsizei inputHeight = (unpackInfo.imageHeight == 0) ? height : unpackInfo.imageHeight;
input = ((char*)input) + ComputePackingOffset(format, type, inputWidth, inputHeight, unpackInfo.alignment, unpackInfo.skipImages, unpackInfo.skipRows, unpackInfo.skipPixels);
sw::Format selectedInternalFormat = SelectInternalFormat(format, type);
if(selectedInternalFormat == sw::FORMAT_NULL)
{
return;
}
if(selectedInternalFormat == internalFormat)
{
void *buffer = lock(0, 0, sw::LOCK_WRITEONLY);
if(buffer)
{
switch(type)
{
case GL_BYTE:
switch(format)
{
case GL_R8:
case GL_R8I:
case GL_R8_SNORM:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_ALPHA8_EXT:
case GL_LUMINANCE:
case GL_LUMINANCE8_EXT:
LoadImageData<Bytes_1>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG8:
case GL_RG8I:
case GL_RG8_SNORM:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE8_ALPHA8_EXT:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB8:
case GL_RGB8I:
case GL_RGB8_SNORM:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<ByteRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA8:
case GL_RGBA8I:
case GL_RGBA8_SNORM:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_BYTE:
switch(format)
{
case GL_R8:
case GL_R8UI:
case GL_R8_SNORM:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_ALPHA8_EXT:
case GL_LUMINANCE:
case GL_LUMINANCE8_EXT:
LoadImageData<Bytes_1>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG8:
case GL_RG8UI:
case GL_RG8_SNORM:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE8_ALPHA8_EXT:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB8:
case GL_RGB8UI:
case GL_RGB8_SNORM:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<UByteRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA8:
case GL_RGBA8UI:
case GL_RGBA8_SNORM:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_SRGB8:
LoadImageData<SRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_SRGB8_ALPHA8:
LoadImageData<SRGBA>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_5_6_5:
switch(format)
{
case GL_RGB565:
case GL_RGB:
LoadImageData<RGB565>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_4_4_4_4:
switch(format)
{
case GL_RGBA4:
case GL_RGBA:
LoadImageData<RGBA4444>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT_5_5_5_1:
switch(format)
{
case GL_RGB5_A1:
case GL_RGBA:
LoadImageData<RGBA5551>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT_10F_11F_11F_REV:
switch(format)
{
case GL_R11F_G11F_B10F:
case GL_RGB:
LoadImageData<R11G11B10F>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT_5_9_9_9_REV:
switch(format)
{
case GL_RGB9_E5:
case GL_RGB:
LoadImageData<RGB9E5>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT_2_10_10_10_REV:
switch(format)
{
case GL_RGB10_A2UI:
LoadImageData<RGB10A2UI>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB10_A2:
case GL_RGBA:
case GL_RGBA_INTEGER:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_FLOAT:
switch(format)
{
// float textures are converted to RGBA, not BGRA
case GL_ALPHA:
case GL_ALPHA32F_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_LUMINANCE:
case GL_LUMINANCE32F_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE_ALPHA32F_EXT:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RED:
case GL_R32F:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG:
case GL_RG32F:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB:
case GL_RGB32F:
LoadImageData<FloatRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA:
case GL_RGBA32F:
LoadImageData<Bytes_16>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT32F:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_HALF_FLOAT:
case GL_HALF_FLOAT_OES:
switch(format)
{
case GL_ALPHA:
case GL_ALPHA16F_EXT:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_LUMINANCE:
case GL_LUMINANCE16F_EXT:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_LUMINANCE_ALPHA:
case GL_LUMINANCE_ALPHA16F_EXT:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RED:
case GL_R16F:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG:
case GL_RG16F:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB:
case GL_RGB16F:
LoadImageData<HalfFloatRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA:
case GL_RGBA16F:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_SHORT:
switch(format)
{
case GL_R16I:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG16I:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB16I:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<ShortRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA16I:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_SHORT:
switch(format)
{
case GL_R16UI:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
LoadImageData<Bytes_2>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG16UI:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB16UI:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<UShortRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA16UI:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_DEPTH_COMPONENT:
case GL_DEPTH_COMPONENT16:
LoadImageData<D16>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_INT:
switch(format)
{
case GL_R32I:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG32I:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB32I:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<IntRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA32I:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_16>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT:
switch(format)
{
case GL_R32UI:
case GL_RED:
case GL_RED_INTEGER:
case GL_ALPHA:
case GL_LUMINANCE:
LoadImageData<Bytes_4>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RG32UI:
case GL_RG:
case GL_RG_INTEGER:
case GL_LUMINANCE_ALPHA:
LoadImageData<Bytes_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGB32UI:
case GL_RGB:
case GL_RGB_INTEGER:
LoadImageData<UIntRGB>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_RGBA32UI:
case GL_RGBA:
case GL_RGBA_INTEGER:
case GL_BGRA_EXT:
case GL_BGRA8_EXT:
LoadImageData<Bytes_16>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
case GL_DEPTH_COMPONENT16:
case GL_DEPTH_COMPONENT24:
case GL_DEPTH_COMPONENT32_OES:
case GL_DEPTH_COMPONENT:
LoadImageData<D32>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
break;
default: UNREACHABLE(format);
}
break;
case GL_UNSIGNED_INT_24_8_OES:
loadD24S8ImageData(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, input, buffer);
break;
case GL_FLOAT_32_UNSIGNED_INT_24_8_REV:
loadD32FS8ImageData(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, input, buffer);
break;
default: UNREACHABLE(type);
}
}
unlock();
}
else
{
sw::Surface source(width, height, depth, ConvertFormatType(format, type), const_cast<void*>(input), inputPitch, inputPitch * inputHeight);
sw::Rect sourceRect(0, 0, width, height);
sw::Rect destRect(xoffset, yoffset, xoffset + width, yoffset + height);
sw::blitter.blit(&source, sourceRect, this, destRect, false);
}
}
void Image::loadD24S8ImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, int inputPitch, int inputHeight, const void *input, void *buffer)
{
LoadImageData<D24>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
unsigned char *stencil = reinterpret_cast<unsigned char*>(lockStencil(0, 0, 0, sw::PUBLIC));
if(stencil)
{
LoadImageData<S8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getStencilPitchB(), getHeight(), input, stencil);
unlockStencil();
}
}
void Image::loadD32FS8ImageData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, int inputPitch, int inputHeight, const void *input, void *buffer)
{
LoadImageData<D32F>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getPitch(), getHeight(), input, buffer);
unsigned char *stencil = reinterpret_cast<unsigned char*>(lockStencil(0, 0, 0, sw::PUBLIC));
if(stencil)
{
LoadImageData<S24_8>(xoffset, yoffset, zoffset, width, height, depth, inputPitch, inputHeight, getStencilPitchB(), getHeight(), input, stencil);
unlockStencil();
}
}
void Image::loadCompressedData(GLint xoffset, GLint yoffset, GLint zoffset, GLsizei width, GLsizei height, GLsizei depth, GLsizei imageSize, const void *pixels)
{
if(zoffset != 0 || depth != 1)
{
UNIMPLEMENTED(); // FIXME
}
int inputPitch = ComputeCompressedPitch(width, format);
int rows = imageSize / inputPitch;
void *buffer = lock(xoffset, yoffset, sw::LOCK_WRITEONLY);
if(buffer)
{
for(int i = 0; i < rows; i++)
{
memcpy((void*)((GLbyte*)buffer + i * getPitch()), (void*)((GLbyte*)pixels + i * inputPitch), inputPitch);
}
}
unlock();
}
}
| 31.565554 | 211 | 0.693621 | aswimmingfish |
cd2fa4921c143259a4adcecca86c08b4d31061f4 | 337 | cpp | C++ | cEpiabm/src/dataclasses/household.cpp | Saketkr21/epiabm | 3ec0dcbc78d3fd4114ed3c6bdd78ef39f0013d2f | [
"BSD-3-Clause"
] | null | null | null | cEpiabm/src/dataclasses/household.cpp | Saketkr21/epiabm | 3ec0dcbc78d3fd4114ed3c6bdd78ef39f0013d2f | [
"BSD-3-Clause"
] | null | null | null | cEpiabm/src/dataclasses/household.cpp | Saketkr21/epiabm | 3ec0dcbc78d3fd4114ed3c6bdd78ef39f0013d2f | [
"BSD-3-Clause"
] | 1 | 2022-03-14T06:00:30.000Z | 2022-03-14T06:00:30.000Z |
#include "household.hpp"
namespace epiabm
{
Household::Household(size_t mcellPos) :
MembersInterface(mcellPos),
m_params(),
m_mcellPos(mcellPos)
{}
size_t Household::microcellPos() const { return m_mcellPos; }
HouseholdParams& Household::params() { return m_params; }
} // namespace epiabm
| 17.736842 | 65 | 0.661721 | Saketkr21 |
cd308f4a93d6b788f5e0759b238cc90487b2c8b1 | 3,686 | cpp | C++ | src/lib/Unidraw/ulabel.cpp | emer/iv | e2ecb3acd834b8764c8582753cc86afcc4281af5 | [
"BSD-3-Clause"
] | null | null | null | src/lib/Unidraw/ulabel.cpp | emer/iv | e2ecb3acd834b8764c8582753cc86afcc4281af5 | [
"BSD-3-Clause"
] | null | null | null | src/lib/Unidraw/ulabel.cpp | emer/iv | e2ecb3acd834b8764c8582753cc86afcc4281af5 | [
"BSD-3-Clause"
] | null | null | null | #ifdef HAVE_CONFIG_H
#include <../../config.h>
#endif
/*
* Copyright (c) 1990, 1991 Stanford University
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided
* that the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the name of Stanford not be used in advertising or
* publicity pertaining to distribution of the software without specific,
* written prior permission. Stanford makes no representations about
* the suitability of this software for any purpose. It is provided "as is"
* without express or implied warranty.
*
* STANFORD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS.
* IN NO EVENT SHALL STANFORD BE LIABLE FOR ANY SPECIAL, INDIRECT OR
* CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
* DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
* WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*
* Implementation of ULabel, an object derived from Graphic.
*/
#include <Unidraw/globals.h>
#include <Unidraw/Graphic/ulabel.h>
#include <IV-2_6/InterViews/painter.h>
#include <InterViews/transformer.h>
#include <IV-2_6/_enter.h>
#include <string.h>
/*****************************************************************************/
ULabel::ULabel (const char* s, Graphic* gr) : Graphic(gr) {
_font = nil;
if (gr != nil) {
ULabel::SetFont(gr->GetFont());
}
_string = strnew(s);
}
ULabel::~ULabel () {
delete [] _string;
Unref(_font);
}
void ULabel::SetFont (PSFont* font) {
if (_font != font) {
Ref(font);
Unref(_font);
_font = font;
invalidateCaches();
}
}
extern PSPattern* pssolid; // hack (see header file)
PSPattern* ULabel::GetPattern () { return pssolid; }
PSFont* ULabel::GetFont () { return _font; }
Graphic* ULabel::Copy () { return new ULabel(_string, this); }
void ULabel::getExtent (
float& x0, float& y0, float& cx, float& cy, float& tol, Graphic* gs
) {
PSFont* f = gs->GetFont();
float width = f->Width(_string);
float height = f->Height();
if (gs->GetTransformer() == nil) {
x0 = 0;
y0 = 0;
cx = width / 2;
cy = height / 2;
} else {
transformRect(0, 0, width, height, x0, y0, cx, cy, gs);
cx = (cx + x0)/2;
cy = (cy + y0)/2;
}
tol = 0;
}
boolean ULabel::contains (PointObj& po, Graphic* gs) {
PointObj pt (&po);
PSFont* f = gs->GetFont();
invTransform(pt._x, pt._y, gs);
BoxObj b (0, 0, f->Width(_string), f->Height());
return b.Contains(pt);
}
boolean ULabel::intersects (BoxObj& userb, Graphic* gs) {
Transformer* t = gs->GetTransformer();
PSFont* f = gs->GetFont();
Coord xmax = f->Width(_string);
Coord ymax = f->Height();
Coord tx0, ty0, tx1, ty1;
if (t != nil && t->Rotated()) {
Coord x[4], tx[5];
Coord y[4], ty[5];
x[0] = x[3] = y[0] = y[1] = 0;
x[2] = x[1] = xmax;
y[2] = y[3] = ymax;
transformList(x, y, 4, tx, ty, gs);
tx[4] = tx[0];
ty[4] = ty[0];
FillPolygonObj fp (tx, ty, 5);
return fp.Intersects(userb);
} else if (t != nil) {
t->Transform(0, 0, tx0, ty0);
t->Transform(xmax, ymax, tx1, ty1);
BoxObj b1 (tx0, ty0, tx1, ty1);
return b1.Intersects(userb);
} else {
BoxObj b2 (0, 0, xmax, ymax);
return b2.Intersects(userb);
}
}
void ULabel::draw (Canvas *c, Graphic* gs) {
update(gs);
_p->Text(c, _string, 0, 0);
}
| 27.303704 | 79 | 0.627509 | emer |
cd312e2187caf0c3593f1946fe944c2acd8e20ad | 3,745 | cc | C++ | lite/tests/kernels/sequence_pad_test.cc | winter-wang/Paddle-Lite | cd09ad060a0d7f20f55c4d6951ca95be75dc2c9c | [
"Apache-2.0"
] | 6 | 2020-07-01T02:52:16.000Z | 2021-06-22T12:15:59.000Z | lite/tests/kernels/sequence_pad_test.cc | winter-wang/Paddle-Lite | cd09ad060a0d7f20f55c4d6951ca95be75dc2c9c | [
"Apache-2.0"
] | null | null | null | lite/tests/kernels/sequence_pad_test.cc | winter-wang/Paddle-Lite | cd09ad060a0d7f20f55c4d6951ca95be75dc2c9c | [
"Apache-2.0"
] | 1 | 2021-07-24T15:30:46.000Z | 2021-07-24T15:30:46.000Z | // Copyright (c) 2021 PaddlePaddle Authors. 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 <gtest/gtest.h>
#include <cstring>
#include "lite/api/paddle_use_kernels.h"
#include "lite/api/paddle_use_ops.h"
#include "lite/core/arena/framework.h"
#include "lite/tests/utils/fill_data.h"
namespace paddle {
namespace lite {
template <class T>
class SequencePadTester : public arena::TestCase {
protected:
std::string x_ = "x";
std::string pad_value_ = "pad_value";
std::string out_ = "out";
std::string length_ = "length";
DDim x_dims_{{9, 2, 3, 4}};
LoD x_lod_{{{0, 2, 5, 9}}};
T value_ = 0;
int padded_length_ = 4;
public:
SequencePadTester(const Place& place, const std::string& alias)
: TestCase(place, alias) {}
void RunBaseline(Scope* scope) override {
auto* out = scope->NewTensor(out_);
auto out_shape = x_dims_.Vectorize();
out_shape[0] = padded_length_;
out_shape.insert(out_shape.begin(),
static_cast<int64_t>(x_lod_[0].size() - 1));
out->Resize(out_shape);
auto* out_data = out->template mutable_data<T>();
for (int64_t i = 0; i < out->numel(); i++) {
out_data[i] = value_;
}
int n = x_dims_.production() / x_dims_[0];
int out_step = padded_length_ * n;
auto* x = scope->FindTensor(x_);
auto* x_data = x->template data<T>();
for (size_t i = 1; i < x_lod_[0].size(); i++) {
int x_step = (x_lod_[0][i] - x_lod_[0][i - 1]) * n;
memcpy(out_data, x_data, sizeof(T) * x_step);
x_data += x_step;
out_data += out_step;
}
auto* length = scope->NewTensor(length_);
length->Resize({static_cast<int64_t>(x_lod_[0].size() - 1)});
int64_t* length_data = length->template mutable_data<int64_t>();
for (size_t i = 1; i < x_lod_[0].size(); i++) {
length_data[i - 1] = x_lod_[0][i] - x_lod_[0][i - 1];
}
}
void PrepareOpDesc(cpp::OpDesc* op_desc) {
op_desc->SetType("sequence_pad");
op_desc->SetInput("X", {x_});
op_desc->SetInput("PadValue", {pad_value_});
op_desc->SetOutput("Out", {out_});
op_desc->SetOutput("Length", {length_});
op_desc->SetAttr("padded_length", padded_length_);
}
void PrepareData() override {
std::vector<T> x_data(x_dims_.production());
fill_data_rand<T>(x_data.data(), -10, 10, x_dims_.production());
SetCommonTensor(x_, x_dims_, x_data.data(), x_lod_);
std::vector<T> pad_value_data{0};
SetCommonTensor(pad_value_, DDim{{1}}, pad_value_data.data());
}
};
template <class T>
void TestSequencePad(const Place place,
const float abs_error,
const std::string alias) {
std::unique_ptr<arena::TestCase> tester(
new SequencePadTester<T>(place, alias));
arena::Arena arena(std::move(tester), place, abs_error);
arena.TestPrecision();
}
TEST(sequence_pad, precision) {
Place place;
float abs_error = 1e-5;
#if defined(LITE_WITH_ARM) || defined(LITE_WITH_X86)
place = TARGET(kHost);
#else
return;
#endif
TestSequencePad<float>(place, abs_error, "def");
TestSequencePad<int>(place, abs_error, "int32");
TestSequencePad<int64_t>(place, abs_error, "int64");
}
} // namespace lite
} // namespace paddle
| 32.008547 | 75 | 0.658745 | winter-wang |
cd332b0704436ea6dd1415cc10a86ee6c4d4c083 | 43,948 | hpp | C++ | include/jsoncons/json_container.hpp | snatesh/NEMoSys_fork | 5c1d8244c274a8e9e2a66c23baa91329dcdaf0eb | [
"NCSA"
] | 4 | 2019-10-25T00:37:17.000Z | 2020-06-02T22:23:02.000Z | include/jsoncons/json_container.hpp | snatesh/NEMoSys_fork | 5c1d8244c274a8e9e2a66c23baa91329dcdaf0eb | [
"NCSA"
] | null | null | null | include/jsoncons/json_container.hpp | snatesh/NEMoSys_fork | 5c1d8244c274a8e9e2a66c23baa91329dcdaf0eb | [
"NCSA"
] | null | null | null | // Copyright 2013 Daniel Parker
// Distributed under the Boost license, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
// See https://github.com/danielaparker/jsoncons for latest version
#ifndef JSONCONS_JSON_CONTAINER_HPP
#define JSONCONS_JSON_CONTAINER_HPP
#include <string>
#include <vector>
#include <deque>
#include <exception>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <utility>
#include <initializer_list>
#include <jsoncons/jsoncons.hpp>
#include <jsoncons/json_traits.hpp>
#include <jsoncons/jsoncons_util.hpp>
namespace jsoncons {
template <class Json>
class Json_string_base_
{
public:
typedef typename Json::allocator_type allocator_type;
Json_string_base_()
: self_allocator_()
{
}
Json_string_base_(const allocator_type& allocator)
: self_allocator_(allocator)
{
}
private:
allocator_type self_allocator_;
};
template <class Json>
class Json_string_
{
public:
typedef typename Json::allocator_type allocator_type;
typedef typename Json::char_allocator_type char_allocator_type;
typedef typename Json::char_type char_type;
typedef typename Json::string_storage_type string_storage_type;
typedef typename string_storage_type::iterator iterator;
typedef typename string_storage_type::const_iterator const_iterator;
//using Json_string_base_<Json>::get_allocator;
Json_string_()
: //Json_string_base_<Json>(),
string_()
{
}
Json_string_(const Json_string_& val)
: //Json_string_base_<Json>(val.get_allocator()),
string_(val.string_)
{
}
Json_string_(const Json_string_& val, const allocator_type& allocator)
: //Json_string_base_<Json>(allocator),
string_(val.string_,char_allocator_type(allocator))
{
}
Json_string_(Json_string_&& val) JSONCONS_NOEXCEPT
: //Json_string_base_<Json>(val.get_allocator()),
string_(std::move(val.string_))
{
}
Json_string_(Json_string_&& val, const allocator_type& allocator)
: //Json_string_base_<Json>(allocator),
string_(std::move(val.string_),char_allocator_type(allocator))
{
}
explicit Json_string_(const allocator_type& allocator)
: //Json_string_base_<Json>(allocator),
string_(char_allocator_type(allocator))
{
}
Json_string_(const char_type* data, size_t length)
: //Json_string_base_<Json>(),
string_(data,length)
{
}
Json_string_(const char_type* data, size_t length, allocator_type allocator)
: //Json_string_base_<Json>(allocator),
string_(data, length, allocator)
{
}
const char_type* data() const
{
return string_.data();
}
const char_type* c_str() const
{
return string_.c_str();
}
size_t length() const
{
return string_.size();
}
allocator_type get_allocator() const
{
return string_.get_allocator();
}
private:
string_storage_type string_;
Json_string_<Json>& operator=(const Json_string_<Json>&) = delete;
};
// json_array
template <class Json>
class Json_array_base_
{
public:
typedef typename Json::allocator_type allocator_type;
public:
Json_array_base_()
: self_allocator_()
{
}
Json_array_base_(const allocator_type& allocator)
: self_allocator_(allocator)
{
}
allocator_type get_allocator() const
{
return self_allocator_;
}
allocator_type self_allocator_;
};
template <class Json>
class json_array: public Json_array_base_<Json>
{
public:
typedef typename Json::allocator_type allocator_type;
typedef Json value_type;
typedef typename std::allocator_traits<allocator_type>:: template rebind_alloc<value_type> val_allocator_type;
typedef typename Json::array_storage_type array_storage_type;
typedef typename array_storage_type::iterator iterator;
typedef typename array_storage_type::const_iterator const_iterator;
typedef typename std::iterator_traits<iterator>::reference reference;
typedef typename std::iterator_traits<const_iterator>::reference const_reference;
using Json_array_base_<Json>::get_allocator;
json_array()
: Json_array_base_<Json>(),
elements_()
{
}
explicit json_array(const allocator_type& allocator)
: Json_array_base_<Json>(allocator),
elements_(val_allocator_type(allocator))
{
}
explicit json_array(size_t n,
const allocator_type& allocator = allocator_type())
: Json_array_base_<Json>(allocator),
elements_(n,Json(),val_allocator_type(allocator))
{
}
explicit json_array(size_t n,
const Json& value,
const allocator_type& allocator = allocator_type())
: Json_array_base_<Json>(allocator),
elements_(n,value,val_allocator_type(allocator))
{
}
template <class InputIterator>
json_array(InputIterator begin, InputIterator end, const allocator_type& allocator = allocator_type())
: Json_array_base_<Json>(allocator),
elements_(begin,end,val_allocator_type(allocator))
{
}
json_array(const json_array& val)
: Json_array_base_<Json>(val.get_allocator()),
elements_(val.elements_)
{
}
json_array(const json_array& val, const allocator_type& allocator)
: Json_array_base_<Json>(allocator),
elements_(val.elements_,val_allocator_type(allocator))
{
}
json_array(json_array&& val) JSONCONS_NOEXCEPT
: Json_array_base_<Json>(val.get_allocator()),
elements_(std::move(val.elements_))
{
}
json_array(json_array&& val, const allocator_type& allocator)
: Json_array_base_<Json>(allocator),
elements_(std::move(val.elements_),val_allocator_type(allocator))
{
}
json_array(std::initializer_list<Json> init)
: Json_array_base_<Json>(),
elements_(std::move(init))
{
}
json_array(std::initializer_list<Json> init,
const allocator_type& allocator)
: Json_array_base_<Json>(allocator),
elements_(std::move(init),val_allocator_type(allocator))
{
}
~json_array()
{
}
void swap(json_array<Json>& val)
{
elements_.swap(val.elements_);
}
size_t size() const {return elements_.size();}
size_t capacity() const {return elements_.capacity();}
void clear() {elements_.clear();}
void shrink_to_fit()
{
for (size_t i = 0; i < elements_.size(); ++i)
{
elements_[i].shrink_to_fit();
}
elements_.shrink_to_fit();
}
void reserve(size_t n) {elements_.reserve(n);}
void resize(size_t n) {elements_.resize(n);}
void resize(size_t n, const Json& val) {elements_.resize(n,val);}
void remove_range(size_t from_index, size_t to_index)
{
JSONCONS_ASSERT(from_index <= to_index);
JSONCONS_ASSERT(to_index <= elements_.size());
elements_.erase(elements_.begin()+from_index,elements_.begin()+to_index);
}
void erase(iterator first, iterator last)
{
elements_.erase(first,last);
}
Json& operator[](size_t i) {return elements_[i];}
const Json& operator[](size_t i) const {return elements_[i];}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void add(T&& value)
{
elements_.emplace_back(Json(std::forward<T&&>(value)));
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void add(T&& value)
{
elements_.emplace_back(std::forward<T&&>(value),get_allocator());
}
#if defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 9
// work around https://gcc.gnu.org/bugzilla/show_bug.cgi?id=54577
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
add(const_iterator pos, T&& value)
{
iterator it = elements_.begin() + (pos - elements_.begin());
return elements_.emplace(it, Json(std::forward<T&&>(value)));
}
#else
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
add(const_iterator pos, T&& value)
{
return elements_.emplace(pos, Json(std::forward<T&&>(value)));
}
#endif
iterator begin() {return elements_.begin();}
iterator end() {return elements_.end();}
const_iterator begin() const {return elements_.begin();}
const_iterator end() const {return elements_.end();}
bool operator==(const json_array<Json>& rhs) const
{
if (size() != rhs.size())
{
return false;
}
for (size_t i = 0; i < size(); ++i)
{
if (elements_[i] != rhs.elements_[i])
{
return false;
}
}
return true;
}
private:
array_storage_type elements_;
json_array& operator=(const json_array<Json>&) = delete;
};
// json_object
template <class BidirectionalIt,class BinaryPredicate>
BidirectionalIt last_wins_unique_sequence(BidirectionalIt first, BidirectionalIt last, BinaryPredicate compare)
{
if (first == last)
{
return last;
}
typedef typename BidirectionalIt::value_type value_type;
typedef typename BidirectionalIt::pointer pointer;
std::vector<value_type> dups;
{
std::vector<pointer> v(std::distance(first,last));
auto p = v.begin();
for (auto it = first; it != last; ++it)
{
*p++ = &(*it);
}
std::sort(v.begin(), v.end(), [&](pointer a, pointer b){return compare(*a,*b)<0;});
auto it = v.begin();
auto end = v.end();
for (auto begin = it+1; begin != end; ++it, ++begin)
{
if (compare(*(*it),*(*begin)) == 0)
{
dups.push_back(*(*it));
}
}
}
if (dups.size() == 0)
{
return last;
}
auto it = last;
for (auto p = first; p != last && p != it; )
{
bool no_dup = true;
if (dups.size() > 0)
{
for (auto q = dups.begin(); no_dup && q != dups.end();)
{
if (compare(*p,*q) == 0)
{
dups.erase(q);
no_dup = false;
}
else
{
++q;
}
}
}
if (!no_dup)
{
--it;
for (auto r = p; r != it; ++r)
{
*r = std::move(*(r+1));
}
}
else
{
++p;
}
}
return it;
}
template <class KeyT, class ValueT>
class key_value_pair
{
public:
typedef KeyT key_storage_type;
typedef typename KeyT::value_type char_type;
typedef typename KeyT::allocator_type allocator_type;
typedef typename ValueT::string_view_type string_view_type;
key_value_pair()
{
}
key_value_pair(const key_storage_type& name, const ValueT& val)
: key_(name), value_(val)
{
}
key_value_pair(key_storage_type&& name, ValueT&& val)
: key_(std::forward<key_storage_type&&>(name)),
value_(std::forward<ValueT&&>(val))
{
}
key_value_pair(const key_value_pair& member)
: key_(member.key_), value_(member.value_)
{
}
key_value_pair(key_value_pair&& member)
: key_(std::move(member.key_)), value_(std::move(member.value_))
{
}
template <class T>
key_value_pair(key_storage_type&& name,
T&& val,
const allocator_type& allocator)
: key_(std::forward<key_storage_type&&>(name)), value_(std::forward<T&&>(val), allocator)
{
}
string_view_type key() const
{
return string_view_type(key_.data(),key_.size());
}
ValueT& value()
{
return value_;
}
const ValueT& value() const
{
return value_;
}
void value(const ValueT& value)
{
value_ = value;
}
void value(ValueT&& value)
{
value_ = std::forward<ValueT&&>(value);
}
void swap(key_value_pair& member)
{
key_.swap(member.key_);
value_.swap(member.value_);
}
key_value_pair& operator=(const key_value_pair& member)
{
if (this != & member)
{
key_ = member.key_;
value_ = member.value_;
}
return *this;
}
key_value_pair& operator=(key_value_pair&& member)
{
if (this != &member)
{
key_.swap(member.key_);
value_.swap(member.value_);
}
return *this;
}
void shrink_to_fit()
{
key_.shrink_to_fit();
value_.shrink_to_fit();
}
#if !defined(JSONCONS_NO_DEPRECATED)
const key_storage_type& name() const
{
return key_;
}
#endif
private:
key_storage_type key_;
ValueT value_;
};
template <class KeyT,class Json>
class Json_object_
{
public:
typedef typename Json::allocator_type allocator_type;
typedef typename Json::char_type char_type;
typedef typename Json::char_allocator_type char_allocator_type;
typedef KeyT key_storage_type;
typedef typename Json::string_view_type string_view_type;
typedef key_value_pair<KeyT,Json> value_type;
typedef typename std::allocator_traits<allocator_type>:: template rebind_alloc<value_type> kvp_allocator_type;
typedef typename Json::object_storage_type object_storage_type;
typedef typename object_storage_type::iterator iterator;
typedef typename object_storage_type::const_iterator const_iterator;
protected:
allocator_type self_allocator_;
object_storage_type members_;
public:
Json_object_()
: self_allocator_(), members_()
{
}
Json_object_(const allocator_type& allocator)
: self_allocator_(allocator),
members_(kvp_allocator_type(allocator))
{
}
Json_object_(const Json_object_& val)
: self_allocator_(val.get_allocator()), members_(val.members_)
{
}
Json_object_(Json_object_&& val)
: self_allocator_(val.get_allocator()),
members_(std::move(val.members_))
{
}
Json_object_(const Json_object_& val, const allocator_type& allocator) :
self_allocator_(allocator),
members_(val.members_,kvp_allocator_type(allocator))
{
}
Json_object_(Json_object_&& val,const allocator_type& allocator) :
self_allocator_(allocator), members_(std::move(val.members_),kvp_allocator_type(allocator))
{
}
void swap(Json_object_& val)
{
members_.swap(val.members_);
}
allocator_type get_allocator() const
{
return this->self_allocator_;
}
};
template <class KeyT,class Json,bool PreserveOrder>
class json_object
{
};
// Do not preserve order
template <class KeyT,class Json>
class json_object<KeyT,Json,false> : public Json_object_<KeyT,Json>
{
public:
using typename Json_object_<KeyT,Json>::allocator_type;
using typename Json_object_<KeyT,Json>::char_type;
using typename Json_object_<KeyT,Json>::char_allocator_type;
using typename Json_object_<KeyT,Json>::key_storage_type;
using typename Json_object_<KeyT,Json>::string_view_type;
using typename Json_object_<KeyT,Json>::value_type;
using typename Json_object_<KeyT,Json>::kvp_allocator_type;
using typename Json_object_<KeyT,Json>::object_storage_type;
using typename Json_object_<KeyT,Json>::iterator;
using typename Json_object_<KeyT,Json>::const_iterator;
using Json_object_<KeyT,Json>::get_allocator;
json_object()
: Json_object_<KeyT,Json>()
{
}
json_object(const allocator_type& allocator)
: Json_object_<KeyT,Json>(allocator)
{
}
json_object(const json_object& val)
: Json_object_<KeyT,Json>(val)
{
}
json_object(json_object&& val)
: Json_object_<KeyT,Json>(std::forward<json_object&&>(val))
{
}
json_object(const json_object& val, const allocator_type& allocator)
: Json_object_<KeyT,Json>(val,allocator)
{
}
json_object(json_object&& val,const allocator_type& allocator)
: Json_object_<KeyT,Json>(std::forward<json_object&&>(val),allocator)
{
}
json_object(std::initializer_list<typename Json::array> init)
: Json_object_<KeyT,Json>()
{
for (const auto& element : init)
{
if (element.size() != 2 || !element[0].is_string())
{
JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list");
break;
}
}
for (auto& element : init)
{
set(element[0].as_string_view(), std::move(element[1]));
}
}
json_object(std::initializer_list<typename Json::array> init,
const allocator_type& allocator)
: Json_object_<KeyT,Json>(allocator)
{
for (const auto& element : init)
{
if (element.size() != 2 || !element[0].is_string())
{
JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list");
break;
}
}
for (auto& element : init)
{
set(element[0].as_string_view(), std::move(element[1]));
}
}
void swap(json_object& val)
{
Json_object_<KeyT,Json>::swap(val);
}
iterator begin()
{
return this->members_.begin();
}
iterator end()
{
return this->members_.end();
}
const_iterator begin() const
{
return this->members_.begin();
}
const_iterator end() const
{
return this->members_.end();
}
size_t size() const {return this->members_.size();}
size_t capacity() const {return this->members_.capacity();}
void clear() {this->members_.clear();}
void shrink_to_fit()
{
for (size_t i = 0; i < this->members_.size(); ++i)
{
this->members_[i].shrink_to_fit();
}
this->members_.shrink_to_fit();
}
void reserve(size_t n) {this->members_.reserve(n);}
Json& at(size_t i)
{
if (i >= this->members_.size())
{
JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript");
}
return this->members_[i].value();
}
const Json& at(size_t i) const
{
if (i >= this->members_.size())
{
JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript");
}
return this->members_[i].value();
}
iterator find(string_view_type name)
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
auto result = (it != this->members_.end() && it->key() == name) ? it : this->members_.end();
return result;
}
const_iterator find(string_view_type name) const
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(),
name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
auto result = (it != this->members_.end() && it->key() == name) ? it : this->members_.end();
return result;
}
void erase(iterator first, iterator last)
{
this->members_.erase(first,last);
}
void erase(string_view_type name)
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it != this->members_.end() && it->key() == name)
{
this->members_.erase(it);
}
}
template<class InputIt, class UnaryPredicate>
void insert(InputIt first, InputIt last, UnaryPredicate pred)
{
size_t count = std::distance(first,last);
this->members_.reserve(this->members_.size() + count);
for (auto s = first; s != last; ++s)
{
this->members_.emplace_back(pred(*s));
}
std::stable_sort(this->members_.begin(),this->members_.end(),
[](const value_type& a, const value_type& b){return a.key().compare(b.key()) < 0;});
auto it = std::unique(this->members_.rbegin(), this->members_.rend(),
[](const value_type& a, const value_type& b){ return !(a.key().compare(b.key()));});
this->members_.erase(this->members_.begin(),it.base());
}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void set(string_view_type name, T&& value)
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
this->members_.emplace(it,
key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void set(string_view_type name, T&& value)
{
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator() );
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value),get_allocator() ));
}
else
{
this->members_.emplace(it,
key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator() );
}
}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void set_(key_storage_type&& name, T&& value)
{
string_view_type s(name.data(), name.size());
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
else if (string_view_type(it->key().data(),it->key().length()) == s)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void set_(key_storage_type&& name, T&& value)
{
string_view_type s(name.data(), name.size());
auto it = std::lower_bound(this->members_.begin(),this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator() );
}
else if (string_view_type(it->key().data(), it->key().length()) == s)
{
it->value(Json(std::forward<T&&>(value),get_allocator() ));
}
else
{
this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator() );
}
}
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
set(iterator hint, string_view_type name, T&& value)
{
iterator it;
if (hint != this->members_.end() && hint->key() <= name)
{
it = std::lower_bound(hint,this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
else
{
it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
it = this->members_.emplace(it,
key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<!is_stateless<U>::value,iterator>::type
set(iterator hint, string_view_type name, T&& value)
{
iterator it;
if (hint != this->members_.end() && hint->key() <= name)
{
it = std::lower_bound(hint,this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
else
{
it = std::lower_bound(this->members_.begin(),this->members_.end(), name,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator() );
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value),get_allocator() ));
}
else
{
it = this->members_.emplace(it,
key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator() );
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
set_(iterator hint, key_storage_type&& name, T&& value)
{
string_view_type s(name.data(), name.size());
iterator it;
if (hint != this->members_.end() && hint->key() <= s)
{
it = std::lower_bound(hint,this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
else
{
it = std::lower_bound(this->members_.begin(),this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (string_view_type(it->key().data(), it->key().length()) == s)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
it = this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<!is_stateless<U>::value,iterator>::type
set_(iterator hint, key_storage_type&& name, T&& value)
{
string_view_type s(name.data(), name.size());
iterator it;
if (hint != this->members_.end() && hint->key() <= s)
{
it = std::lower_bound(hint,this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
else
{
it = std::lower_bound(this->members_.begin(),this->members_.end(), s,
[](const value_type& a, string_view_type k){return a.key().compare(k) < 0;});
}
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator() );
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (string_view_type(it->key().data(), it->key().length()) == s)
{
it->value(Json(std::forward<T&&>(value),get_allocator() ));
}
else
{
it = this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator() );
}
return it;
}
bool operator==(const json_object& rhs) const
{
if (size() != rhs.size())
{
return false;
}
for (auto it = this->members_.begin(); it != this->members_.end(); ++it)
{
auto rhs_it = std::lower_bound(rhs.begin(), rhs.end(), *it,
[](const value_type& a, const value_type& b){return a.key().compare(b.key()) < 0;});
if (rhs_it == rhs.end() || rhs_it->key() != it->key() || rhs_it->value() != it->value())
{
return false;
}
}
return true;
}
private:
json_object& operator=(const json_object&) = delete;
};
// Preserve order
template <class KeyT,class Json>
class json_object<KeyT,Json,true> : public Json_object_<KeyT,Json>
{
public:
using typename Json_object_<KeyT,Json>::allocator_type;
using typename Json_object_<KeyT,Json>::char_type;
using typename Json_object_<KeyT,Json>::char_allocator_type;
using typename Json_object_<KeyT,Json>::key_storage_type;
using typename Json_object_<KeyT,Json>::string_view_type;
using typename Json_object_<KeyT,Json>::value_type;
using typename Json_object_<KeyT,Json>::kvp_allocator_type;
using typename Json_object_<KeyT,Json>::object_storage_type;
using typename Json_object_<KeyT,Json>::iterator;
using typename Json_object_<KeyT,Json>::const_iterator;
using Json_object_<KeyT,Json>::get_allocator;
json_object()
: Json_object_<KeyT,Json>()
{
}
json_object(const allocator_type& allocator)
: Json_object_<KeyT,Json>(allocator)
{
}
json_object(const json_object& val)
: Json_object_<KeyT,Json>(val)
{
}
json_object(json_object&& val)
: Json_object_<KeyT,Json>(std::forward<json_object&&>(val))
{
}
json_object(const json_object& val, const allocator_type& allocator)
: Json_object_<KeyT,Json>(val,allocator)
{
}
json_object(json_object&& val,const allocator_type& allocator)
: Json_object_<KeyT,Json>(std::forward<json_object&&>(val),allocator)
{
}
json_object(std::initializer_list<typename Json::array> init)
: Json_object_<KeyT,Json>()
{
for (const auto& element : init)
{
if (element.size() != 2 || !element[0].is_string())
{
JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list");
break;
}
}
for (auto& element : init)
{
set(element[0].as_string_view(), std::move(element[1]));
}
}
json_object(std::initializer_list<typename Json::array> init,
const allocator_type& allocator)
: Json_object_<KeyT,Json>(allocator)
{
for (const auto& element : init)
{
if (element.size() != 2 || !element[0].is_string())
{
JSONCONS_THROW_EXCEPTION(std::runtime_error, "Cannot create object from initializer list");
break;
}
}
for (auto& element : init)
{
set(element[0].as_string_view(), std::move(element[1]));
}
}
void swap(json_object& val)
{
Json_object_<KeyT,Json>::swap(val);
}
iterator begin()
{
return this->members_.begin();
}
iterator end()
{
return this->members_.end();
}
const_iterator begin() const
{
return this->members_.begin();
}
const_iterator end() const
{
return this->members_.end();
}
size_t size() const {return this->members_.size();}
size_t capacity() const {return this->members_.capacity();}
void clear() {this->members_.clear();}
void shrink_to_fit()
{
for (size_t i = 0; i < this->members_.size(); ++i)
{
this->members_[i].shrink_to_fit();
}
this->members_.shrink_to_fit();
}
void reserve(size_t n) {this->members_.reserve(n);}
Json& at(size_t i)
{
if (i >= this->members_.size())
{
JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript");
}
return this->members_[i].value();
}
const Json& at(size_t i) const
{
if (i >= this->members_.size())
{
JSONCONS_THROW_EXCEPTION(std::out_of_range,"Invalid array subscript");
}
return this->members_[i].value();
}
iterator find(string_view_type name)
{
return std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& kvp){return kvp.key() == name;});
}
const_iterator find(string_view_type name) const
{
return std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& kvp){return kvp.key() == name;});
}
void erase(iterator first, iterator last)
{
this->members_.erase(first,last);
}
void erase(string_view_type name)
{
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& kvp){return kvp.key() == name;});
if (it != this->members_.end())
{
this->members_.erase(it);
}
}
template<class InputIt, class UnaryPredicate>
void insert(InputIt first, InputIt last, UnaryPredicate pred)
{
size_t count = std::distance(first,last);
this->members_.reserve(this->members_.size() + count);
for (auto s = first; s != last; ++s)
{
this->members_.emplace_back(pred(*s));
}
auto it = last_wins_unique_sequence(this->members_.begin(), this->members_.end(),
[](const value_type& a, const value_type& b){ return a.key().compare(b.key());});
this->members_.erase(it,this->members_.end());
}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void set(string_view_type name, T&& value)
{
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& a){return a.key() == name;});
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
else
{
it->value(Json(std::forward<T&&>(value)));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void set(string_view_type name, T&& value)
{
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[name](const value_type& a){return a.key() == name;});
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value),get_allocator());
}
else
{
it->value(Json(std::forward<T&&>(value),get_allocator()));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<is_stateless<U>::value
>::type* = nullptr>
void set_(key_storage_type&& name, T&& value)
{
string_view_type s(name.data(),name.size());
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[s](const value_type& a){return a.key().compare(s) == 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
else
{
it->value(Json(std::forward<T&&>(value)));
}
}
template <class T, class U=allocator_type,
typename std::enable_if<!is_stateless<U>::value
>::type* = nullptr>
void set_(key_storage_type&& name, T&& value)
{
string_view_type s(name.data(),name.size());
auto it = std::find_if(this->members_.begin(),this->members_.end(),
[s](const value_type& a){return a.key().compare(s) == 0;});
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value),get_allocator());
}
else
{
it->value(Json(std::forward<T&&>(value),get_allocator()));
}
}
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
set(iterator hint, string_view_type name, T&& value)
{
iterator it = hint;
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(), get_allocator()),
std::forward<T&&>(value));
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
it = this->members_.emplace(it,
key_storage_type(name.begin(),name.end()),
std::forward<T&&>(value));
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<!is_stateless<U>::value,iterator>::type
set(iterator hint, string_view_type name, T&& value)
{
iterator it = hint;
if (it == this->members_.end())
{
this->members_.emplace_back(key_storage_type(name.begin(),name.end(),get_allocator()),
std::forward<T&&>(value),get_allocator());
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value),get_allocator()));
}
else
{
it = this->members_.emplace(it,
key_storage_type(name.begin(),name.end(),get_allocator()),
std::forward<T&&>(value),get_allocator());
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<is_stateless<U>::value,iterator>::type
set_(iterator hint, key_storage_type&& name, T&& value)
{
iterator it = hint;
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value)));
}
else
{
it = this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value));
}
return it;
}
template <class T, class U=allocator_type>
typename std::enable_if<!is_stateless<U>::value,iterator>::type
set_(iterator hint, key_storage_type&& name, T&& value)
{
iterator it = hint;
if (it == this->members_.end())
{
this->members_.emplace_back(std::forward<key_storage_type&&>(name),
std::forward<T&&>(value), get_allocator());
it = this->members_.begin() + (this->members_.size() - 1);
}
else if (it->key() == name)
{
it->value(Json(std::forward<T&&>(value), get_allocator()));
}
else
{
it = this->members_.emplace(it,
std::forward<key_storage_type&&>(name),
std::forward<T&&>(value), get_allocator());
}
return it;
}
bool operator==(const json_object& rhs) const
{
if (size() != rhs.size())
{
return false;
}
for (auto it = this->members_.begin(); it != this->members_.end(); ++it)
{
auto rhs_it = std::find_if(rhs.begin(),rhs.end(),
[it](const value_type& a){return a.key() == it->key();});
if (rhs_it == rhs.end() || rhs_it->key() != it->key() || rhs_it->value() != it->value())
{
return false;
}
}
return true;
}
private:
json_object& operator=(const json_object&) = delete;
};
}
#endif
| 30.647141 | 127 | 0.554132 | snatesh |
cd34af2faa7cdce1a63b00f7b07ac9f51bf477fe | 7,113 | hpp | C++ | src/layer/common/reshape_layer-inl.hpp | pl8787/textnet-release | c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f | [
"Apache-2.0"
] | 114 | 2017-06-14T07:05:31.000Z | 2021-06-13T05:30:49.000Z | src/layer/common/reshape_layer-inl.hpp | pl8787/textnet-release | c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f | [
"Apache-2.0"
] | 7 | 2017-11-17T08:16:55.000Z | 2019-10-05T00:09:20.000Z | src/layer/common/reshape_layer-inl.hpp | pl8787/textnet-release | c85a4162c55b4cfe22eab6f8f0c8b615854f9b8f | [
"Apache-2.0"
] | 40 | 2017-06-15T03:21:10.000Z | 2021-10-31T15:03:30.000Z | #ifndef TEXTNET_LAYER_RESHAPE_LAYER_INL_HPP_
#define TEXTNET_LAYER_RESHAPE_LAYER_INL_HPP_
#include <iostream>
#include <fstream>
#include <sstream>
#include <set>
#include <mshadow/tensor.h>
#include "../layer.h"
#include "../op.h"
namespace textnet {
namespace layer {
template<typename xpu>
class ReshapeLayer : public Layer<xpu>{
public:
ReshapeLayer(LayerType type) { this->layer_type = type; }
virtual ~ReshapeLayer(void) {}
virtual int BottomNodeNum() { return 1; }
virtual int TopNodeNum() { return 1; }
virtual int ParamNodeNum() { return 0; }
void PrintTensor(const char * name, mshadow::Tensor<xpu, 1> x) {
mshadow::Shape<1> s = x.shape_;
cout << name << " shape " << s[0] << endl;
for (unsigned int d1 = 0; d1 < s[0]; ++d1) {
cout << x[d1] << " ";
}
cout << endl;
}
void PrintTensor(const char * name, mshadow::Tensor<xpu, 2> x) {
mshadow::Shape<2> s = x.shape_;
cout << name << " shape " << s[0] << "x" << s[1] << endl;
for (unsigned int d1 = 0; d1 < s[0]; ++d1) {
for (unsigned int d2 = 0; d2 < s[1]; ++d2) {
cout << x[d1][d2] << " ";
}
cout << endl;
}
cout << endl;
}
void PrintTensor(const char * name, mshadow::Tensor<xpu, 3> x) {
mshadow::Shape<3> s = x.shape_;
cout << name << " shape " << s[0] << "x" << s[1] << "x" << s[2] << endl;
for (unsigned int d1 = 0; d1 < s[0]; ++d1) {
for (unsigned int d2 = 0; d2 < s[1]; ++d2) {
for (unsigned int d3 = 0; d3 < s[2]; ++d3) {
cout << x[d1][d2][d3] << " ";
}
cout << ";";
}
cout << endl;
}
}
void PrintTensor(const char * name, mshadow::Tensor<xpu, 4> x) {
mshadow::Shape<4> s = x.shape_;
cout << name << " shape " << s[0] << "x" << s[1] << "x" << s[2] << "x" << s[3] << endl;
for (unsigned int d1 = 0; d1 < s[0]; ++d1) {
for (unsigned int d2 = 0; d2 < s[1]; ++d2) {
for (unsigned int d3 = 0; d3 < s[2]; ++d3) {
for (unsigned int d4 = 0; d4 < s[3]; ++d4) {
cout << x[d1][d2][d3][d4] << " ";
}
cout << "|";
}
cout << ";";
}
cout << endl;
}
}
virtual void Require() {
// default value, just set the value you want
this->defaults["D0"] = SettingV(0);
this->defaults["D1"] = SettingV(0);
this->defaults["D2"] = SettingV(0);
this->defaults["D3"] = SettingV(0);
this->defaults["L0"] = SettingV(0);
this->defaults["L1"] = SettingV(0);
// require value, set to SettingV(),
// it will force custom to set in config
Layer<xpu>::Require();
}
virtual void SetupLayer(std::map<std::string, SettingV> &setting,
const std::vector<Node<xpu>*> &bottom,
const std::vector<Node<xpu>*> &top,
mshadow::Random<xpu> *prnd) {
Layer<xpu>::SetupLayer(setting, bottom, top, prnd);
utils::Check(bottom.size() == BottomNodeNum(),
"ReshapeLayer:bottom size problem.");
utils::Check(top.size() == TopNodeNum(),
"ReshapeLayer:top size problem.");
// Dx represents data axis x shape
// Lx represents length axis x shape
// if set to 0, copy the shape size as bottom axis
// if set to -1, automatically compute shape.
// So only one -1 can be set, and its value can be derived from other values.
D0 = setting["D0"].iVal();
D1 = setting["D1"].iVal();
D2 = setting["D2"].iVal();
D3 = setting["D3"].iVal();
L0 = setting["L0"].iVal();
L1 = setting["L1"].iVal();
}
virtual void Reshape(const std::vector<Node<xpu>*> &bottom,
const std::vector<Node<xpu>*> &top,
bool show_info = false) {
utils::Check(bottom.size() == BottomNodeNum(),
"ReshapeLayer:bottom size problem.");
utils::Check(top.size() == TopNodeNum(),
"ReshapeLayer:top size problem.");
in_data_shape = bottom[0]->data.shape_;
in_len_shape = bottom[0]->length.shape_;
out_data_shape[0] = D0==0 ? in_data_shape[0] : D0;
out_data_shape[1] = D1==0 ? in_data_shape[1] : D1;
out_data_shape[2] = D2==0 ? in_data_shape[2] : D2;
out_data_shape[3] = D3==0 ? in_data_shape[3] : D3;
out_len_shape[0] = L0==0 ? in_len_shape[0] : L0;
out_len_shape[1] = L1==0 ? in_len_shape[1] : L1;
if (D0 == -1) {
out_data_shape[0] = 1;
out_data_shape[0] = in_data_shape.Size() / out_data_shape.Size();
} else if (D1 == -1) {
out_data_shape[1] = 1;
out_data_shape[1] = in_data_shape.Size() / out_data_shape.Size();
} else if (D2 == -1) {
out_data_shape[2] = 1;
out_data_shape[2] = in_data_shape.Size() / out_data_shape.Size();
} else if (D3 == -1) {
out_data_shape[3] = 1;
out_data_shape[3] = in_data_shape.Size() / out_data_shape.Size();
}
if (L0 == -1) {
out_len_shape[0] = 1;
out_len_shape[0] = in_len_shape.Size() / out_len_shape.Size();
} else if (L1 == -1) {
out_len_shape[1] = 1;
out_len_shape[1] = in_len_shape.Size() / out_len_shape.Size();
}
utils::Check(out_data_shape.Size() == in_data_shape.Size(),
"ReshapeLayer: data shape mismatch.");
utils::Check(out_len_shape.Size() == in_len_shape.Size(),
"ReshapeLayer: length shape mismatch.");
top[0]->Resize(out_data_shape, out_len_shape, true);
if (show_info) {
bottom[0]->PrintShape("bottom0");
top[0]->PrintShape("top0");
}
}
virtual void CheckReshape(const std::vector<Node<xpu>*> &bottom,
const std::vector<Node<xpu>*> &top) {
// Check for reshape
bool need_reshape = false;
if (in_data_shape.Size() != bottom[0]->data.shape_.Size()) {
need_reshape = true;
}
// Do reshape
if (need_reshape) {
this->Reshape(bottom, top);
}
}
virtual void Forward(const std::vector<Node<xpu>*> &bottom,
const std::vector<Node<xpu>*> &top) {
using namespace mshadow::expr;
mshadow::Tensor<xpu, 1> bottom0_data = bottom[0]->data_d1();
mshadow::Tensor<xpu, 1> bottom0_len = bottom[0]->length_d1();
mshadow::Tensor<xpu, 1> top0_data = top[0]->data_d1();
mshadow::Tensor<xpu, 1> top0_len = top[0]->length_d1();
top0_data = F<op::identity>(bottom0_data);
top0_len = F<op::identity>(bottom0_len);
}
virtual void Backprop(const std::vector<Node<xpu>*> &bottom,
const std::vector<Node<xpu>*> &top) {
using namespace mshadow::expr;
mshadow::Tensor<xpu, 1> bottom0_diff = bottom[0]->diff_d1();
mshadow::Tensor<xpu, 1> top0_diff = top[0]->diff_d1();
bottom0_diff = F<op::identity>(top0_diff);
}
protected:
int D0;
int D1;
int D2;
int D3;
int L0;
int L1;
mshadow::Shape<4> in_data_shape;
mshadow::Shape<2> in_len_shape;
mshadow::Shape<4> out_data_shape;
mshadow::Shape<2> out_len_shape;
};
} // namespace layer
} // namespace textnet
#endif
| 31.754464 | 91 | 0.556446 | pl8787 |
cd38e1ef9672b455e3ad9810398c6a0a5c68fe75 | 3,312 | cpp | C++ | C++/tictactoe.cpp | OluSure/Hacktoberfest2021-1 | ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea | [
"MIT"
] | 215 | 2021-10-01T08:18:16.000Z | 2022-03-29T04:12:03.000Z | C++/tictactoe.cpp | OluSure/Hacktoberfest2021-1 | ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea | [
"MIT"
] | 51 | 2021-10-01T08:16:42.000Z | 2021-10-31T13:51:51.000Z | C++/tictactoe.cpp | OluSure/Hacktoberfest2021-1 | ad1bafb0db2f0cdeaae8f87abbaa716638c5d2ea | [
"MIT"
] | 807 | 2021-10-01T08:11:45.000Z | 2021-11-21T18:57:09.000Z | #include <stdio.h>
#include <stdlib.h>
#include <bits/stdc++.h>
using namespace std;
char square[10] = { 'o', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
int choice, player;
int checkForWin();
void displayBoard();
void markBoard(char mark);
int main()
{
int gameStatus;
char mark;
player = 1;
do
{
displayBoard();
// change turns
player = (player % 2) ? 1 : 2;
// get input
cout<< "Player " <<player <<" enter a number: ";
cin >> choice;
// set the correct character based on player turn
mark = (player == 1) ? 'X' : 'O';
// set board based on user choice or invalid choice
markBoard(mark);
gameStatus = checkForWin();
player++;
}
while (gameStatus == -1);
if (gameStatus == 1)
cout<< "==>\aPlayer "<<--player <<" wins";
else
cout<< "==>\aGame draw";
return 0;
}
int checkForWin()
{
int returnValue = 0;
if (square[1] == square[2] && square[2] == square[3])
{
returnValue = 1;
}
else if (square[4] == square[5] && square[5] == square[6])
returnValue = 1;
else if (square[7] == square[8] && square[8] == square[9])
returnValue = 1;
else if (square[1] == square[4] && square[4] == square[7])
returnValue = 1;
else if (square[2] == square[5] && square[5] == square[8])
returnValue = 1;
else if (square[3] == square[6] && square[6] == square[9])
returnValue = 1;
else if (square[1] == square[5] && square[5] == square[9])
returnValue = 1;
else if (square[3] == square[5] && square[5] == square[7])
returnValue = 1;
else if (square[1] != '1' && square[2] != '2' && square[3] != '3' &&
square[4] != '4' && square[5] != '5' && square[6] != '6' && square[7]
!= '7' && square[8] != '8' && square[9] != '9')
returnValue = 0;
else
returnValue = -1;
return returnValue;
}
void displayBoard()
{
system("cls");
cout<< "\n\n\tTic Tac Toe\n\n";
cout<<"Player 1 (X) - Player 2 (O)\n\n\n";
cout<<" | | \n";
cout<<" " << square[1] << " | " << square[2] << " | " << square[3] <<endl;
cout<<"_____|_____|_____\n";
cout<<" | | \n";
cout<<" " << square[4] << " | " << square[5] << " | " << square[6]<< endl;
cout<<"_____|_____|_____\n";
cout<<" | | \n";
cout<<" " << square[7] << " | " << square[8] << " | " << square[9]<< endl;
cout<<" | | \n";
}
void markBoard(char mark)
{
if (choice == 1 && square[1] == '1')
square[1] = mark;
else if (choice == 2 && square[2] == '2')
square[2] = mark;
else if (choice == 3 && square[3] == '3')
square[3] = mark;
else if (choice == 4 && square[4] == '4')
square[4] = mark;
else if (choice == 5 && square[5] == '5')
square[5] = mark;
else if (choice == 6 && square[6] == '6')
square[6] = mark;
else if (choice == 7 && square[7] == '7')
square[7] = mark;
else if (choice == 8 && square[8] == '8')
square[8] = mark;
else if (choice == 9 && square[9] == '9')
square[9] = mark;
else
{
cout<< "Invalid move ";
player--;
}
}
| 21.506494 | 83 | 0.462862 | OluSure |
cd3c3bcfed4b9ef19161bdc8e38477bd8c604bb7 | 224 | cpp | C++ | 113.cpp | abdullah1107/uva | 5c7107d41a586e30aa7cc91cd7498b82dbc506ee | [
"MIT"
] | null | null | null | 113.cpp | abdullah1107/uva | 5c7107d41a586e30aa7cc91cd7498b82dbc506ee | [
"MIT"
] | null | null | null | 113.cpp | abdullah1107/uva | 5c7107d41a586e30aa7cc91cd7498b82dbc506ee | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int main()
{
double m,n,p,k;
while(scanf("%lf %lf",&n,&p)!=EOF)
{
k=pow(p,1/n);
printf("%0.lf\n",k);
}
return 0;
}
| 14.933333 | 38 | 0.526786 | abdullah1107 |
cd3d78ff7f43762aeff7c21c690982d576577192 | 5,277 | cxx | C++ | test/test_shm.cxx | yushansuger/nwcp | 8c2e6a31af59f3d209c962438b8b123b415b4fa4 | [
"MIT"
] | null | null | null | test/test_shm.cxx | yushansuger/nwcp | 8c2e6a31af59f3d209c962438b8b123b415b4fa4 | [
"MIT"
] | null | null | null | test/test_shm.cxx | yushansuger/nwcp | 8c2e6a31af59f3d209c962438b8b123b415b4fa4 | [
"MIT"
] | 1 | 2020-09-14T09:06:25.000Z | 2020-09-14T09:06:25.000Z | #include "cpshm.h"
#include <stdio.h>
#include "cpstring.h"
const char* shm_id = "test_nwdl_shm";
struct TEST_SHM_DATA
{
char str[128];
int len;
};
void print_data(TEST_SHM_DATA* data)
{
printf("TEST_SHM_DATA::str: %s \nTEST_SHM_DATA::len: %d\n\n",
data->str, data->len);
}
int test_1()
{
cpshm_t shm_t = 0;
int ret = -1;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t);
if (CPDL_SUCCESS != ret)
{
return -1;
}
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -2;
}
}
else
{
ret = cpshm_map(shm_id, &shm_t);
if (CPDL_SUCCESS != ret)
{
return -1;
}
}
TEST_SHM_DATA* data = 0;
unsigned int len = 0;
ret = cpshm_data(shm_t, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);;
return -4;
}
strlcpy(data->str, "test_1 shm by nonwill", 128);
data->len = strlen(data->str);
print_data(data);
ret = cpshm_unmap(shm_t);
data = 0;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -2;
}
cpshm_t shm_t2 = 0;
ret = cpshm_map(shm_id, &shm_t2);
ret = cpshm_data(shm_t2, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t2);
ret = cpshm_close(&shm_t);
return -5;
}
print_data(data);
ret = cpshm_close(&shm_t2);
ret = cpshm_close(&shm_t);
return 1;
}
int test_2()
{
cpshm_t shm_t = 0;
int ret = -1;
ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t);
if (CPDL_SUCCESS != ret)
{
return -1;
}
TEST_SHM_DATA* data = 0;
unsigned int len = 0;
ret = cpshm_data(shm_t, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -5;
}
strlcpy(data->str, "test_2 shm by nonwill", 128);
data->len = strlen(data->str);
print_data(data);
ret = cpshm_close(&shm_t);
shm_t = 0;
data = 0;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS == ret)
{
//ret = cpshm_close(&shm_t);
return -2;
}
ret = cpshm_map(shm_id, &shm_t);
if (CPDL_SUCCESS == ret)
{
ret = cpshm_close(&shm_t);
return -3;
}
ret = cpshm_data(shm_t, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS == ret)
{
print_data(data);
ret = cpshm_close(&shm_t);
return -4;
}
return 1;
}
int test_3()
{
cpshm_t shm_t = 0;
int ret = -1;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t);
if (CPDL_SUCCESS != ret)
{
return -1;
}
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -2;
}
}
TEST_SHM_DATA* data = 0;
unsigned int len = 0;
ret = cpshm_data(shm_t, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);;
return -4;
}
strlcpy(data->str, "test_3 shm by nonwill", 128);
data->len = strlen(data->str);
print_data(data);
cpshm_t shm_t2 = 0;
ret = cpshm_map(shm_id, &shm_t2);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return -5;
}
ret = cpshm_close(&shm_t);
ret = cpshm_data(shm_t2, (cpshm_d*)&data, &len);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t2);
return -5;
}
print_data(data);
ret = cpshm_close(&shm_t2);
return 1;
}
void test_4()
{
cpshm_t shm_t = 0;
int ret = -1;
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_create(shm_id, sizeof(TEST_SHM_DATA), &shm_t);
if (CPDL_SUCCESS != ret)
{
return ;
}
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return ;
}
}
cpshm_t shm_t2 = 0;
cpshm_t shm_t3 = 0;
ret = cpshm_map(shm_id, &shm_t2);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return ;
}
ret = cpshm_close(&shm_t2);
ret = cpshm_map(shm_id, &shm_t3);
if (CPDL_SUCCESS != ret)
{
ret = cpshm_close(&shm_t);
return ;
}
else
{
ret = cpshm_close(&shm_t3);
}
ret = cpshm_exist(shm_id);
if (CPDL_SUCCESS != ret)
{
printf("test_4 cpshm_exist : no shm exist\n");
}
ret = cpshm_close(&shm_t);
}
int main(int /*argc*/, char* /*argv*/[])
{
test_1();
test_2();
test_3();
test_4();
#ifdef _NWCP_WIN32
system("pause");
#endif
return 1;
}
| 19.838346 | 67 | 0.492515 | yushansuger |
cd3da9cdf1f7eae7625770ccb27a08b05ae42506 | 5,722 | cpp | C++ | SDK/EnchantedCompass_functions.cpp | alxalx14/Sea-Of-Thieves-SDK | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | [
"MIT"
] | 3 | 2021-03-27T08:30:37.000Z | 2021-04-18T19:32:53.000Z | SDK/EnchantedCompass_functions.cpp | alxalx14/Sea-Of-Thieves-SDK | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | [
"MIT"
] | null | null | null | SDK/EnchantedCompass_functions.cpp | alxalx14/Sea-Of-Thieves-SDK | f56a0340eb33726c98fc53eb0678fa2d59aa8294 | [
"MIT"
] | 1 | 2021-06-01T03:05:50.000Z | 2021-06-01T03:05:50.000Z | // Name: SeaOfThieves, Version: 2.0.23
#include "../pch.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Functions
//---------------------------------------------------------------------------
void UTaleQuestMultiTargetCompassServiceDesc::AfterRead()
{
UTaleQuestToolServiceDesc::AfterRead();
READ_PTR_FULL(CompassDesc, UClass);
}
void UTaleQuestMultiTargetCompassServiceDesc::BeforeDelete()
{
UTaleQuestToolServiceDesc::BeforeDelete();
DELE_PTR_FULL(CompassDesc);
}
void UTaleQuestSetCompassTargetToTargetStep::AfterRead()
{
UTaleQuestStep::AfterRead();
}
void UTaleQuestSetCompassTargetToTargetStep::BeforeDelete()
{
UTaleQuestStep::BeforeDelete();
}
void UTaleQuestSetCompassTargetBaseStepDesc::AfterRead()
{
UTaleQuestStepDesc::AfterRead();
}
void UTaleQuestSetCompassTargetBaseStepDesc::BeforeDelete()
{
UTaleQuestStepDesc::BeforeDelete();
}
void UTaleQuestSetCompassTargetToActorStepDesc::AfterRead()
{
UTaleQuestSetCompassTargetBaseStepDesc::AfterRead();
}
void UTaleQuestSetCompassTargetToActorStepDesc::BeforeDelete()
{
UTaleQuestSetCompassTargetBaseStepDesc::BeforeDelete();
}
void UTaleQuestSetCompassTargetToPointStepDesc::AfterRead()
{
UTaleQuestSetCompassTargetBaseStepDesc::AfterRead();
}
void UTaleQuestSetCompassTargetToPointStepDesc::BeforeDelete()
{
UTaleQuestSetCompassTargetBaseStepDesc::BeforeDelete();
}
void AMultiTargetEnchantedCompass::AfterRead()
{
ACompass::AfterRead();
READ_PTR_FULL(InventoryItem, UInventoryItemComponent);
}
void AMultiTargetEnchantedCompass::BeforeDelete()
{
ACompass::BeforeDelete();
DELE_PTR_FULL(InventoryItem);
}
// Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.GetFloatMax
// (Final, Native, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// float ReturnValue (ConstParm, Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float APrototypeMultiTargetEnchantedCompass::GetFloatMax()
{
static auto fn = UObject::FindObject<UFunction>("Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.GetFloatMax");
APrototypeMultiTargetEnchantedCompass_GetFloatMax_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.CalculateDesiredYaw
// (Event, Public, HasOutParms, HasDefaults, BlueprintEvent, Const)
// Parameters:
// struct FRotator CompassRotation (ConstParm, Parm, OutParm, ZeroConstructor, ReferenceParm, IsPlainOldData, NoDestructor)
// float ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
float APrototypeMultiTargetEnchantedCompass::CalculateDesiredYaw(const struct FRotator& CompassRotation)
{
static auto fn = UObject::FindObject<UFunction>("Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.CalculateDesiredYaw");
APrototypeMultiTargetEnchantedCompass_CalculateDesiredYaw_Params params;
params.CompassRotation = CompassRotation;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.BP_GetTargetLocations
// (Final, Native, Public, BlueprintCallable, BlueprintPure)
// Parameters:
// TArray<struct FVector> ReturnValue (ConstParm, Parm, OutParm, ZeroConstructor, ReturnParm)
TArray<struct FVector> APrototypeMultiTargetEnchantedCompass::BP_GetTargetLocations()
{
static auto fn = UObject::FindObject<UFunction>("Function EnchantedCompass.PrototypeMultiTargetEnchantedCompass.BP_GetTargetLocations");
APrototypeMultiTargetEnchantedCompass_BP_GetTargetLocations_Params params;
auto flags = fn->FunctionFlags;
fn->FunctionFlags |= 0x00000400;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
void APrototypeMultiTargetEnchantedCompass::AfterRead()
{
AMultiTargetEnchantedCompass::AfterRead();
}
void APrototypeMultiTargetEnchantedCompass::BeforeDelete()
{
AMultiTargetEnchantedCompass::BeforeDelete();
}
void UTaleQuestMultiTargetCompassAddTrackedLocationStep::AfterRead()
{
UTaleQuestStep::AfterRead();
READ_PTR_FULL(Desc, UTaleQuestMultiTargetCompassAddTrackedLocationStepDesc);
}
void UTaleQuestMultiTargetCompassAddTrackedLocationStep::BeforeDelete()
{
UTaleQuestStep::BeforeDelete();
DELE_PTR_FULL(Desc);
}
void UTaleQuestMultiTargetCompassAddTrackedLocationStepDesc::AfterRead()
{
UTaleQuestStepDesc::AfterRead();
}
void UTaleQuestMultiTargetCompassAddTrackedLocationStepDesc::BeforeDelete()
{
UTaleQuestStepDesc::BeforeDelete();
}
void UTaleQuestMultiTargetCompassRemoveTrackedLocationStep::AfterRead()
{
UTaleQuestStep::AfterRead();
}
void UTaleQuestMultiTargetCompassRemoveTrackedLocationStep::BeforeDelete()
{
UTaleQuestStep::BeforeDelete();
}
void UTaleQuestMultiTargetCompassRemoveTrackedLocationStepDesc::AfterRead()
{
UTaleQuestStepDesc::AfterRead();
}
void UTaleQuestMultiTargetCompassRemoveTrackedLocationStepDesc::BeforeDelete()
{
UTaleQuestStepDesc::BeforeDelete();
}
void UTaleQuestMultiTargetCompassService::AfterRead()
{
UTaleQuestToolService::AfterRead();
}
void UTaleQuestMultiTargetCompassService::BeforeDelete()
{
UTaleQuestToolService::BeforeDelete();
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 23.841667 | 171 | 0.773855 | alxalx14 |