hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3da1ed6ca101bd811623e8f9480527f1509ef6c6 | 3,777 | cpp | C++ | src/Library/Geometry/TriangleMeshLoaderBezier.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | 1 | 2018-12-20T19:31:02.000Z | 2018-12-20T19:31:02.000Z | src/Library/Geometry/TriangleMeshLoaderBezier.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | src/Library/Geometry/TriangleMeshLoaderBezier.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////
//
// TriangleMeshLoaderBezier.cpp - Implementation of the bezier mesh
// loader
//
// Author: Aravind Krishnaswamy
// Date of Birth: August 7, 2002
// Tabs: 4
// Comments:
//
// License Information: Please see the attached LICENSE.TXT file
//
//////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "TriangleMeshLoaderBezier.h"
#include "BezierTesselation.h"
#include "GeometryUtilities.h"
#include "../Interfaces/ILog.h"
#include "../Utilities/MediaPathLocator.h"
#include <stdio.h>
using namespace RISE;
using namespace RISE::Implementation;
TriangleMeshLoaderBezier::TriangleMeshLoaderBezier(
const char * szFile,
const unsigned int detail,
const bool bCombineSharedVertices_,
const bool bCenterObject_,
const IFunction2D* displacement_,
Scalar disp_scale_
) :
nDetail( detail ),
bCombineSharedVertices( bCombineSharedVertices_ ),
bCenterObject( bCenterObject_ ),
displacement( displacement_ ),
disp_scale( disp_scale_ )
{
strncpy( szFilename, GlobalMediaPathLocator().Find(szFile).c_str(), 256 );
}
TriangleMeshLoaderBezier::~TriangleMeshLoaderBezier( )
{
}
bool TriangleMeshLoaderBezier::LoadTriangleMesh( ITriangleMeshGeometryIndexed* pGeom )
{
FILE* inputFile = fopen( szFilename, "r" );
if( !inputFile || !pGeom ) {
GlobalLog()->Print( eLog_Error, "TriangleMeshLoaderBezier:: Failed to open file or bad geometry object" );
return false;
}
pGeom->BeginIndexedTriangles();
char line[4096];
if( fgets( (char*)&line, 4096, inputFile ) != NULL )
{
// Read that first line, it tells us how many
// patches are dealing with here
unsigned int numPatches = 0;
sscanf( line, "%u", &numPatches );
BezierPatchesListType patches;
for( unsigned int i=0; i<numPatches; i++ )
{
// We assume every 16 lines gives us a patch
BezierPatch patch;
for( int j=0; j<4; j++ ) {
for( int k=0; k<4; k++ ) {
double x, y, z;
if( fscanf( inputFile, "%lf %lf %lf", &x, &y, &z ) == EOF ) {
GlobalLog()->PrintSourceError( "TriangleMeshLoaderBezier:: Fatal error while reading file. Nothing will be loaded", __FILE__, __LINE__ );
return false;
}
patch.c[j].pts[k] = Point3( x, y, z );
}
}
patches.push_back( patch );
}
GlobalLog()->PrintEx( eLog_Event, "TriangleMeshLoaderBezier:: Tesselating %u bezier patches...", numPatches );
// Now tesselate all the patches together and then add them to
// the geometry object
IndexTriangleListType indtris;
VerticesListType vertices;
NormalsListType normals;
TexCoordsListType coords;
GeneratePolygonsFromBezierPatches( indtris, vertices, normals, coords, patches, nDetail );
if( bCombineSharedVertices ) {
GlobalLog()->PrintEx( eLog_Event, "TriangleMeshLoaderBezier:: Attempting to combine shared vertices..." );
CombineSharedVerticesFromGrids( indtris, vertices, numPatches, nDetail, nDetail );
}
CalculateVertexNormals( indtris, normals, vertices );
if( bCenterObject ) {
CenterObject( vertices );
}
if( displacement ) {
RemapTextureCoords( coords );
ApplyDisplacementMapToObject( indtris, vertices, normals, coords, *displacement, disp_scale );
// After applying displacement, recalculate the vertex normals
normals.clear();
CalculateVertexNormals( indtris, normals, vertices );
}
pGeom->AddVertices( vertices );
pGeom->AddNormals( normals );
pGeom->AddTexCoords( coords );
pGeom->AddIndexedTriangles( indtris );
GlobalLog()->PrintEx( eLog_Event, "TriangleMeshGeometryIndexed:: Constructing acceleration structures for %u triangles", indtris.size() );
}
pGeom->DoneIndexedTriangles();
fclose( inputFile );
return true;
}
| 27.977778 | 144 | 0.684141 | aravindkrishnaswamy |
3dac70154b3cf3642d5b6cde7005fdae00c73bbc | 24,055 | cpp | C++ | glib-adv/aest.cpp | ksemer/snap | 0084126c30ad49a4437bc8ea30be78484f8c58d7 | [
"BSD-3-Clause"
] | 1,805 | 2015-01-06T20:01:35.000Z | 2022-03-29T16:12:51.000Z | glib-adv/aest.cpp | lizhaoqing/snap | 907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5 | [
"BSD-3-Clause"
] | 168 | 2015-01-07T22:57:29.000Z | 2022-03-15T01:20:24.000Z | glib-adv/aest.cpp | lizhaoqing/snap | 907c34aac6bcddc7c2f8efb64be76e87dd7e4ea5 | [
"BSD-3-Clause"
] | 768 | 2015-01-09T02:28:45.000Z | 2022-03-30T00:53:46.000Z | /////////////////////////////////////////////////
// Attribute-Estimator
PAttrEst TAttrEst::Load(TSIn& SIn){
TStr TypeNm(SIn);
if (TypeNm==TTypeNm<TAttrEstRnd>()){return new TAttrEstRnd(SIn);}
else if (TypeNm==TTypeNm<TAttrEstIGain>()){return new TAttrEstIGain(SIn);}
else if (TypeNm==TTypeNm<TAttrEstIGainNorm>()){return new TAttrEstIGainNorm(SIn);}
else if (TypeNm==TTypeNm<TAttrEstIGainRatio>()){return new TAttrEstIGainRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstMantarasDist>()){return new TAttrEstMantarasDist(SIn);}
else if (TypeNm==TTypeNm<TAttrEstMdl>()){return new TAttrEstMdl(SIn);}
else if (TypeNm==TTypeNm<TAttrEstGStat>()){return new TAttrEstGStat(SIn);}
else if (TypeNm==TTypeNm<TAttrEstChiSquare>()){return new TAttrEstChiSquare(SIn);}
else if (TypeNm==TTypeNm<TAttrEstOrt>()){return new TAttrEstOrt(SIn);}
else if (TypeNm==TTypeNm<TAttrEstGini>()){return new TAttrEstGini(SIn);}
else if (TypeNm==TTypeNm<TAttrEstWgtEvd>()){return new TAttrEstWgtEvd(SIn);}
else if (TypeNm==TTypeNm<TAttrEstTextWgtEvd>()){return new TAttrEstTextWgtEvd(SIn);}
else if (TypeNm==TTypeNm<TAttrEstOddsRatio>()){return new TAttrEstOddsRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstWgtOddsRatio>()){return new TAttrEstWgtOddsRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstCondOddsRatio>()){return new TAttrEstCondOddsRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstLogPRatio>()){return new TAttrEstLogPRatio(SIn);}
else if (TypeNm==TTypeNm<TAttrEstExpPDiff>()){return new TAttrEstExpPDiff(SIn);}
else if (TypeNm==TTypeNm<TAttrEstMutInf>()){return new TAttrEstMutInf(SIn);}
else if (TypeNm==TTypeNm<TAttrEstCrossEnt>()){return new TAttrEstCrossEnt(SIn);}
else if (TypeNm==TTypeNm<TAttrEstTermFq>()){return new TAttrEstTermFq(SIn);}
else {Fail; return NULL;}
}
PTbValDs TAttrEst::GetCSValDs(const int& AttrN, const int& SplitN,
const PTbValSplit& ValSplit, const PDmDs& DmDs){
PTbValDs CSValDs=new TTbValDs(DmDs->GetCDs()->GetDscs());
for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){
TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN);
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double ValW=DmDs->GetCAVDs(CDsc, AttrN)->GetValW(Val);
CSValDs->AddVal(CDsc, ValW);
}
}
CSValDs->Def();
return CSValDs;
}
PTbValDs TAttrEst::GetSValDs(const int& AttrN,
const PTbValSplit& ValSplit, const PDmDs& DmDs){
PTbValDs SValDs=new TTbValDs(ValSplit->GetSplits());
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){
TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN);
double ValW=DmDs->GetAVDs(AttrN)->GetValW(Val);
SValDs->AddVal(SplitN, ValW);
}
}
SValDs->Def();
return SValDs;
}
PTbValDs TAttrEst::GetSCValDs(const int& CDsc, const int& AttrN,
const PTbValSplit& ValSplit, const PDmDs& DmDs){
PTbValDs SCValDs=new TTbValDs(ValSplit->GetSplits());
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){
TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN);
double ValW=DmDs->GetCAVDs(CDsc, AttrN)->GetValW(Val);
SCValDs->AddVal(SplitN, ValW);
}
}
SCValDs->Def();
return SCValDs;
}
double TAttrEst::GetCEntropy(
const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){
double CEntropy=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
if (CPrb>0){CEntropy-=CPrb*TMath::Log2(CPrb);}
}
return CEntropy;
}
double TAttrEst::GetAEntropy(const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){
PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double AEntropy=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
double SPrb=PrbEst->GetVPrb(SplitN, SValDs, PriorSValDs);
if (SPrb>0){AEntropy-=SPrb*TMath::Log2(SPrb);}
}
return AEntropy;
}
double TAttrEst::GetCAEntropy(const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs, const PPrbEst& PrbEst){
double CAEntropy=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
double SEntropy=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CAPrb=SPrb*PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs());
if (CAPrb>0){SEntropy-=CAPrb*TMath::Log2(CAPrb);}
}
CAEntropy+=SEntropy;
}
return CAEntropy;
}
PPrbEst TAttrEst::GetPrbEst(const PPrbEst& PrbEst){
if (!PrbEst.Empty()){return PrbEst;}
else {return PPrbEst(new TPrbEstRelFq());}
}
PPp TAttrEst::GetPrbEstPp(const TStr& Nm, const TStr& DNm){
PPp Pp=new TPp(Nm, DNm, ptSet);
Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm));
return Pp;
}
const TStr TAttrEst::DNm("Attribute Estimate");
PPp TAttrEst::GetPp(const TStr& Nm, const TStr& DNm){
PPp Pp=new TPp(Nm, DNm, ptSel);
Pp->AddPp(TAttrEstRnd::GetPp(TTypeNm<TAttrEstRnd>(), TAttrEstRnd::DNm));
Pp->AddPp(TAttrEstIGain::GetPp(TTypeNm<TAttrEstIGain>(), TAttrEstIGain::DNm));
Pp->AddPp(TAttrEstIGainNorm::GetPp(TTypeNm<TAttrEstIGainNorm>(), TAttrEstIGainNorm::DNm));
Pp->AddPp(TAttrEstIGainRatio::GetPp(TTypeNm<TAttrEstIGainRatio>(), TAttrEstIGainRatio::DNm));
Pp->AddPp(TAttrEstMantarasDist::GetPp(TTypeNm<TAttrEstMantarasDist>(), TAttrEstMantarasDist::DNm));
Pp->AddPp(TAttrEstMdl::GetPp(TTypeNm<TAttrEstMdl>(), TAttrEstMdl::DNm));
Pp->AddPp(TAttrEstGStat::GetPp(TTypeNm<TAttrEstGStat>(), TAttrEstGStat::DNm));
Pp->AddPp(TAttrEstChiSquare::GetPp(TTypeNm<TAttrEstChiSquare>(), TAttrEstChiSquare::DNm));
Pp->AddPp(TAttrEstOrt::GetPp(TTypeNm<TAttrEstOrt>(), TAttrEstOrt::DNm));
Pp->AddPp(TAttrEstGini::GetPp(TTypeNm<TAttrEstGini>(), TAttrEstGini::DNm));
Pp->AddPp(TAttrEstWgtEvd::GetPp(TTypeNm<TAttrEstWgtEvd>(), TAttrEstWgtEvd::DNm));
Pp->AddPp(TAttrEstTextWgtEvd::GetPp(TTypeNm<TAttrEstTextWgtEvd>(), TAttrEstTextWgtEvd::DNm));
Pp->AddPp(TAttrEstOddsRatio::GetPp(TTypeNm<TAttrEstOddsRatio>(), TAttrEstOddsRatio::DNm));
Pp->AddPp(TAttrEstWgtOddsRatio::GetPp(TTypeNm<TAttrEstWgtOddsRatio>(), TAttrEstWgtOddsRatio::DNm));
Pp->AddPp(TAttrEstCondOddsRatio::GetPp(TTypeNm<TAttrEstCondOddsRatio>(), TAttrEstCondOddsRatio::DNm));
Pp->AddPp(TAttrEstLogPRatio::GetPp(TTypeNm<TAttrEstLogPRatio>(), TAttrEstLogPRatio::DNm));
Pp->AddPp(TAttrEstExpPDiff::GetPp(TTypeNm<TAttrEstExpPDiff>(), TAttrEstExpPDiff::DNm));
Pp->AddPp(TAttrEstMutInf::GetPp(TTypeNm<TAttrEstMutInf>(), TAttrEstMutInf::DNm));
Pp->AddPp(TAttrEstCrossEnt::GetPp(TTypeNm<TAttrEstCrossEnt>(), TAttrEstCrossEnt::DNm));
Pp->AddPp(TAttrEstTermFq::GetPp(TTypeNm<TAttrEstTermFq>(), TAttrEstTermFq::DNm));
Pp->PutDfVal(TTypeNm<TAttrEstIGain>());
return Pp;
}
PAttrEst TAttrEst::New(const PPp& Pp){
if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstRnd>())){
return new TAttrEstRnd(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGain>())){
return new TAttrEstIGain(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGainNorm>())){
return new TAttrEstIGainNorm(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstIGainRatio>())){
return new TAttrEstIGainRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMantarasDist>())){
return new TAttrEstMantarasDist(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMdl>())){
return new TAttrEstMdl(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstGStat>())){
return new TAttrEstGStat(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstChiSquare>())){
return new TAttrEstChiSquare(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstOrt>())){
return new TAttrEstOrt(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstGini>())){
return new TAttrEstGini(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstWgtEvd>())){
return new TAttrEstWgtEvd(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstTextWgtEvd>())){
return new TAttrEstTextWgtEvd(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstOddsRatio>())){
return new TAttrEstOddsRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstWgtOddsRatio>())){
return new TAttrEstWgtOddsRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstCondOddsRatio>())){
return new TAttrEstCondOddsRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstLogPRatio>())){
return new TAttrEstLogPRatio(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstExpPDiff>())){
return new TAttrEstExpPDiff(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstMutInf>())){
return new TAttrEstMutInf(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstCrossEnt>())){
return new TAttrEstCrossEnt(Pp->GetSelPp());}
else if (Pp->GetVal()==TPpVal(TTypeNm<TAttrEstTermFq>())){
return new TAttrEstTermFq(Pp->GetSelPp());}
else {Fail; return NULL;}
}
/////////////////////////////////////////////////
// Attribute-Estimator-Random
const TStr TAttrEstRnd::DNm("Random");
PPp TAttrEstRnd::GetPp(const TStr& Nm, const TStr& DNm){
PPp Pp=new TPp(Nm, DNm, ptSet);
Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm));
Pp->AddPpInt("Seed", "Random-Seed", 0, TInt::Mx, 1);
return Pp;
}
/////////////////////////////////////////////////
// Attribute-Estimator-Information-Gain
const TStr TAttrEstIGain::DNm("Inf-Gain");
/////////////////////////////////////////////////
// Attribute-Estimator-Information-Gain-Normalized
const TStr TAttrEstIGainNorm::DNm("Inf-Gain-Normalized");
/////////////////////////////////////////////////
// Attribute-Estimator-Information-Gain-Ratio
const TStr TAttrEstIGainRatio::DNm("Inf-Gain-Ratio");
/////////////////////////////////////////////////
// Attribute-Estimator-Mantaras-Distance
const TStr TAttrEstMantarasDist::DNm("Mantaras-Distance");
/////////////////////////////////////////////////
// Attribute-Estimator-MDL
double TAttrEstMdl::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
double SumW=DmDs->GetSumW();
int CDscs=DmDs->GetCDs()->GetDscs();
double IGainAttrQ=IGain.GetAttrQ(AttrN, ValSplit, DmDs, PriorDmDs);
double LnPart=TSpecFunc::LnComb(TFlt::Round(SumW)+CDscs-1, CDscs-1);
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
double SSumW=0;
for (int ValN=0; ValN<ValSplit->GetSplitVals(SplitN); ValN++){
TTbVal Val=ValSplit->GetSplitVal(SplitN, ValN);
double ValW=DmDs->GetAVDs(AttrN)->GetValW(Val);
SSumW+=ValW;
}
LnPart-=TSpecFunc::LnComb(TFlt::Round(SSumW+CDscs-1), CDscs-1);
}
return IGainAttrQ+LnPart/SumW;
}
const TStr TAttrEstMdl::DNm("MDL");
/////////////////////////////////////////////////
// Attribute-Estimator-G-Statistics
const TStr TAttrEstGStat::DNm("G-Statistics");
/////////////////////////////////////////////////
// Attribute-Estimator-Chi-Square
double TAttrEstChiSquare::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs&){
double ChiSquare=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double Frac=SPrb*DmDs->GetCDs()->GetValW(CDsc);
if (Frac>0){ChiSquare+=TMath::Sqr(Frac-CSValDs->GetValW(CDsc))/Frac;}
}
}
return ChiSquare;
}
const TStr TAttrEstChiSquare::DNm("Chi-Square");
/////////////////////////////////////////////////
// Attribute-Estimator-ORT
double TAttrEstOrt::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(ValSplit->GetSplits()==2); // **make exception
PTbValDs CSValDs1=GetCSValDs(AttrN, 0, ValSplit, DmDs);
PTbValDs CSValDs2=GetCSValDs(AttrN, 1, ValSplit, DmDs);
double Cos=0; double Norm1=0; double Norm2=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CSPrb1=PrbEst->GetVPrb(CDsc, CSValDs1, PriorDmDs->GetCDs());
double CSPrb2=PrbEst->GetVPrb(CDsc, CSValDs2, PriorDmDs->GetCDs());
Cos+=CSPrb1*CSPrb2; Norm1+=TMath::Sqr(CSPrb1); Norm2+=TMath::Sqr(CSPrb2);
}
if ((Norm1==0)||(Norm2==0)){Cos=1;}
else {Cos=Cos/(sqrt(Norm1)*sqrt(Norm2));}
return 1-Cos;
}
const TStr TAttrEstOrt::DNm("ORT");
/////////////////////////////////////////////////
// Attribute-Estimator-Gini
double TAttrEstGini::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
double Gini=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
double Sum=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
Sum+=TMath::Sqr(PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs()));}
Gini+=SPrb*Sum;
}
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
Gini-=TMath::Sqr(CPrb);
}
return Gini;
}
const TStr TAttrEstGini::DNm("Gini-Index");
/////////////////////////////////////////////////
// Attribute-Estimator-Weight-Of-Evidence
double TAttrEstWgtEvd::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return 0;}
double WgtEvd=0;
for (int SplitN=0; SplitN<ValSplit->GetSplits(); SplitN++){
PTbValDs CSValDs=GetCSValDs(AttrN, SplitN, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double OrigCPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
double CPrb=OrigCPrb;
if (CPrb==0){CPrb=1/TMath::Sqr(PriorSumW);}
if (CPrb==1){CPrb=1-(1/TMath::Sqr(PriorSumW));}
double OddsC=CPrb/(1-CPrb);
double CSPrb=PrbEst->GetVPrb(CDsc, CSValDs, PriorDmDs->GetCDs());
if (CSPrb==0){CSPrb=1/TMath::Sqr(PriorSumW);}
if (CSPrb==1){CSPrb=1-(1/TMath::Sqr(PriorSumW));}
double OddsCS=CSPrb/(1-CSPrb);
WgtEvd+=OrigCPrb*SPrb*fabs(log(OddsCS/OddsC));
}
}
return WgtEvd;
}
const TStr TAttrEstWgtEvd::DNm("Weight-Of-Evidence");
/////////////////////////////////////////////////
// Attribute-Estimator-Text-Weight-Of-Evidence
double TAttrEstTextWgtEvd::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return 0;}
double WgtEvd=0;
PTbValDs CS1ValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs);
double S1Prb=CS1ValDs->GetSumPrb(DmDs->GetSumW());
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double OrigCPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
double CPrb=OrigCPrb;
if (CPrb==0){CPrb=1/TMath::Sqr(PriorSumW);}
if (CPrb==1){CPrb=1-(1/TMath::Sqr(PriorSumW));}
double OddsC=CPrb/(1-CPrb);
double CS1Prb=PrbEst->GetVPrb(CDsc, CS1ValDs, PriorDmDs->GetCDs());
if (CS1Prb==0){CS1Prb=1/TMath::Sqr(PriorSumW);}
if (CS1Prb==1){CS1Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsCS1=CS1Prb/(1-CS1Prb);
WgtEvd+=OrigCPrb*S1Prb*fabs(log(OddsCS1/OddsC));
}
return WgtEvd;
}
const TStr TAttrEstTextWgtEvd::DNm("Text-Weight-Of-Evidence");
/////////////////////////////////////////////////
// Attribute-Estimator-Odds-Ratio
double TAttrEstOddsRatio::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return TFlt::Mn;}
// split-number-0: false; split-number-1: true
PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs);
PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs);
double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs);
if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);}
if (S1C0Prb==1){S1C0Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsS1C0=S1C0Prb/(1-S1C0Prb);
if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);}
if (S1C1Prb==1){S1C1Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsS1C1=S1C1Prb/(1-S1C1Prb);
double OddsRatio=log(OddsS1C1/OddsS1C0);
return OddsRatio;
}
const TStr TAttrEstOddsRatio::DNm("Odds-Ratio");
/////////////////////////////////////////////////
// Attribute-Estimator-Weighted-Odds-Ratio
double TAttrEstWgtOddsRatio::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
PTbValDs CSValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs);
double SPrb=CSValDs->GetSumPrb(DmDs->GetSumW());
double WgtOddsRatio=SPrb*OddsRatio.GetAttrQ(AttrN, ValSplit, DmDs, PriorDmDs);
return WgtOddsRatio;
}
const TStr TAttrEstWgtOddsRatio::DNm("Weighted-Odds-Ratio");
/////////////////////////////////////////////////
// Attribute-Estimator-Conditional-Odds-Ratio
double TAttrEstCondOddsRatio::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return TFlt::Mn;}
// split-number-0: false; split-number-1: true
PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs);
PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs);
double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs);
if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);}
if (S1C0Prb==1){S1C0Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsS1C0=S1C0Prb/(1-S1C0Prb);
if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);}
if (S1C1Prb==1){S1C1Prb=1-(1/TMath::Sqr(PriorSumW));}
double OddsS1C1=S1C1Prb/(1-S1C1Prb);
double CondOddsRatio;
if (S1C0Prb-S1C1Prb>InvTsh){
CondOddsRatio=InvWgt*log(OddsS1C0/OddsS1C1);
} else {
CondOddsRatio=log(OddsS1C1/OddsS1C0);
}
return CondOddsRatio;
}
const TStr TAttrEstCondOddsRatio::DNm("Conditional-Odds-Ratio");
PPp TAttrEstCondOddsRatio::GetPp(const TStr& Nm, const TStr& DNm){
PPp Pp=new TPp(Nm, DNm, ptSet);
Pp->AddPp(TPrbEst::GetPp(TTypeNm<TPrbEst>(), TPrbEst::DNm));
Pp->AddPpFlt("InvTsh", "Inversion-Treshold", 0, 1, 0.9);
Pp->AddPpFlt("InvWgt", "Inversion-Weight", 0, 1, 0.1);
return Pp;
}
/////////////////////////////////////////////////
// Attribute-Estimator-Log-Probability-Ratio
double TAttrEstLogPRatio::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
double PriorSumW=PriorDmDs->GetSumW();
if (PriorSumW==0){return TFlt::Mn;}
// split-number-0: false; split-number-1: true
PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs);
PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs);
double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs);
if (S1C0Prb==0){S1C0Prb=1/TMath::Sqr(PriorSumW);}
if (S1C1Prb==0){S1C1Prb=1/TMath::Sqr(PriorSumW);}
double LogPRatio=log(S1C1Prb/S1C0Prb);
return LogPRatio;
}
const TStr TAttrEstLogPRatio::DNm("Log-Probability-Ratio");
/////////////////////////////////////////////////
// Attribute-Estimator-Exp-Probability-Difference
double TAttrEstExpPDiff::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(DmDs->GetCDs()->GetDscs()==2); // **make exception
IAssert(ValSplit->GetSplits()==2); // **make exception
double SumW=DmDs->GetSumW();
if (SumW==0){return TFlt::Mn;}
// split-number-0: false; split-number-1: true
PTbValDs SC0ValDs=GetSCValDs(0, AttrN, ValSplit, DmDs);
PTbValDs SC1ValDs=GetSCValDs(1, AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1C0Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC0ValDs, PriorSValDs);
double S1C1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SC1ValDs, PriorSValDs);
double ExpPDiff=exp(S1C1Prb-S1C0Prb);
return ExpPDiff;
}
const TStr TAttrEstExpPDiff::DNm("Exp-Probability-Difference");
/////////////////////////////////////////////////
// Attribute-Estimator-Mutual-Information
double TAttrEstMutInf::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(ValSplit->GetSplits()==2); // **make exception
// split-number-0: false; split-number-1: true
PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SValDs, PriorSValDs);
if (S1Prb==0){return TFlt::Mn;}
double MutInf=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
PTbValDs SCValDs=GetSCValDs(CDsc, AttrN, ValSplit, DmDs);
double S1CPrb=PrbEst->GetVPrb(TTbVal::PosVal, SCValDs, PriorSValDs);
if (S1CPrb==0){S1CPrb=1/TMath::Sqr(DmDs->GetSumW());}
MutInf+=CPrb*log(S1CPrb/S1Prb);
}
return MutInf;
}
const TStr TAttrEstMutInf::DNm("Mutual-Information");
/////////////////////////////////////////////////
// Attribute-Estimator-Cross-Entropy
double TAttrEstCrossEnt::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs& PriorDmDs){
IAssert(ValSplit->GetSplits()==2); // **make exception
// split-number-0: false; split-number-1: true
PTbValDs CS1ValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs);
PTbValDs SValDs=GetSValDs(AttrN, ValSplit, DmDs);
PTbValDs PriorSValDs=GetSValDs(AttrN, ValSplit, PriorDmDs);
double S1Prb=PrbEst->GetVPrb(TTbVal::PosVal, SValDs, PriorSValDs);
if (S1Prb==0){return TFlt::Mn;}
double CrossEnt=0;
for (int CDsc=0; CDsc<DmDs->GetCDs()->GetDscs(); CDsc++){
double CPrb=PrbEst->GetCPrb(CDsc, DmDs, PriorDmDs);
double CS1Prb=PrbEst->GetVPrb(CDsc, CS1ValDs, PriorDmDs->GetCDs());
if (CS1Prb>0){Assert(CPrb>0);
CrossEnt+=CS1Prb*log(CS1Prb/CPrb);}
}
CrossEnt*=S1Prb;
return CrossEnt;
}
const TStr TAttrEstCrossEnt::DNm("Cross-Entropy");
/////////////////////////////////////////////////
// Attribute-Estimator-Term-Frequency
double TAttrEstTermFq::GetAttrQ(
const int& AttrN, const PTbValSplit& ValSplit,
const PDmDs& DmDs, const PDmDs&){
IAssert(ValSplit->GetSplits()==2); // **make exception
PTbValDs CSValDs=GetCSValDs(AttrN, 1, ValSplit, DmDs);
return CSValDs->GetSumW();
}
const TStr TAttrEstTermFq::DNm("Term-Frequency");
| 41.331615 | 105 | 0.665849 | ksemer |
3dac85c8bafbc7d9a7802659675a8a65a627d769 | 743 | hh | C++ | gem5/src/mem/ruby/network/booksim2/rptrafficmanager.hh | jyhuang91/flyover | 952a0fffee952c9f88b93017b6bba65a84d562cb | [
"MIT"
] | 3 | 2020-11-01T08:23:10.000Z | 2021-12-21T02:53:36.000Z | gem5/src/mem/ruby/network/booksim2/rptrafficmanager.hh | jyhuang91/flyover | 952a0fffee952c9f88b93017b6bba65a84d562cb | [
"MIT"
] | null | null | null | gem5/src/mem/ruby/network/booksim2/rptrafficmanager.hh | jyhuang91/flyover | 952a0fffee952c9f88b93017b6bba65a84d562cb | [
"MIT"
] | 1 | 2020-12-07T00:57:30.000Z | 2020-12-07T00:57:30.000Z | /*
* rptrafficmanager.hh
* - A traffic manager for Router Parking
*
* Author: Jiayi Huang
*/
#ifndef _RPTRAFFICMANAGER_HPP_
#define _RPTRAFFICMANAGER_HPP_
#include <cassert>
#include "mem/ruby/network/booksim2/trafficmanager.hh"
class RPTrafficManager : public TrafficManager {
private:
vector<vector<int> > _packet_size;
vector<vector<int> > _packet_size_rate;
vector<int> _packet_size_max_val;
// ============ Internal methods ============
protected:
virtual void _Inject();
virtual void _Step( );
virtual void _GeneratePacket( int source, int size, int cl, uint64_t time );
public:
RPTrafficManager( const Configuration &config, const vector<BSNetwork *> & net );
virtual ~RPTrafficManager( );
};
#endif
| 19.051282 | 83 | 0.713324 | jyhuang91 |
3dadd9169507170884588ae2e6e56af05806cd41 | 3,213 | cpp | C++ | problems/kickstart/2021/E/palindromic-crossword/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/kickstart/2021/E/palindromic-crossword/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/kickstart/2021/E/palindromic-crossword/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#ifdef LOCAL
#include "code/formatting.hpp"
#else
#define debug(...) (void)0
#endif
using namespace std;
static_assert(sizeof(int) == 4 && sizeof(long) == 8);
struct disjoint_set {
int N, S;
vector<int> next, size;
explicit disjoint_set(int N = 0) : N(N), S(N), next(N), size(N, 1) {
iota(begin(next), end(next), 0);
}
void assign(int N) { *this = disjoint_set(N); }
bool same(int i, int j) { return find(i) == find(j); }
bool unit(int i) { return i == next[i] && size[i] == 1; }
bool root(int i) { return find(i) == i; }
void reroot(int u) {
if (u != find(u)) {
size[u] = size[find(u)];
next[u] = next[find(u)] = u;
}
}
int find(int i) {
while (i != next[i]) {
i = next[i] = next[next[i]];
}
return i;
}
bool join(int i, int j) {
i = find(i);
j = find(j);
if (i != j) {
if (size[i] < size[j]) {
swap(i, j);
}
next[j] = i;
size[i] += size[j];
S--;
return true;
}
return false;
}
};
auto solve() {
int N, M;
cin >> N >> M;
vector<string> grid(N);
for (int i = 0; i < N; i++) {
cin >> grid[i];
}
disjoint_set dsu(N * M);
auto id = [&](int i, int j) { return i * M + j; };
// columns
for (int i = 0; i < N; i++) {
int j = 0;
do {
while (j < M && grid[i][j] == '#')
j++;
int a = j;
while (j < M && grid[i][j] != '#')
j++;
int b = j;
for (int c = a, d = b - 1; c < d; c++, d--) {
dsu.join(id(i, c), id(i, d));
}
} while (j < M);
}
// rows
for (int j = 0; j < M; j++) {
int i = 0;
do {
while (i < N && grid[i][j] == '#')
i++;
int a = i;
while (i < N && grid[i][j] != '#')
i++;
int b = i;
for (int c = a, d = b - 1; c < d; c++, d--) {
dsu.join(id(c, j), id(d, j));
}
} while (i < N);
}
vector<string> ans = grid;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (grid[i][j] != '.' && grid[i][j] != '#') {
int x = dsu.find(id(i, j));
int r = x / M, c = x - r * M;
ans[r][c] = grid[i][j];
}
}
}
int filled = 0;
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (ans[i][j] != '#') {
int x = dsu.find(id(i, j));
int r = x / M, c = x - r * M;
ans[i][j] = ans[r][c];
filled += ans[i][j] != '.' && grid[i][j] == '.';
}
}
}
cout << filled << '\n';
for (int i = 0; i < N; i++) {
cout << ans[i] << '\n';
}
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int T;
cin >> T;
for (int t = 1; t <= T; t++) {
cout << "Case #" << t << ": ";
solve();
}
return 0;
}
| 23.452555 | 72 | 0.347028 | brunodccarvalho |
3db11026f8a1ee573b6de54f080be4cc6a948a9f | 5,028 | hpp | C++ | src/Input.hpp | mechanicsfoundry/raytracinginoneweekend-glsl | 515905135456fe263be9bc13b708222c28827a4d | [
"MIT"
] | 4 | 2021-03-01T13:33:30.000Z | 2021-03-14T20:05:00.000Z | src/Input.hpp | mechanicsfoundry/raytracinginoneweekend-glsl | 515905135456fe263be9bc13b708222c28827a4d | [
"MIT"
] | null | null | null | src/Input.hpp | mechanicsfoundry/raytracinginoneweekend-glsl | 515905135456fe263be9bc13b708222c28827a4d | [
"MIT"
] | null | null | null | #pragma once
enum class DPadDirection
{
UP,
DOWN,
LEFT,
RIGHT
};
// these are matched to SDL key map scancodes
enum class Scancode
{
S_UNKNOWN = 0,
S_A = 4,
S_B = 5,
S_C = 6,
S_D = 7,
S_E = 8,
S_F = 9,
S_G = 10,
S_H = 11,
S_I = 12,
S_J = 13,
S_K = 14,
S_L = 15,
S_M = 16,
S_N = 17,
S_O = 18,
S_P = 19,
S_Q = 20,
S_R = 21,
S_S = 22,
S_T = 23,
S_U = 24,
S_V = 25,
S_W = 26,
S_X = 27,
S_Y = 28,
S_Z = 29,
S_1 = 30,
S_2 = 31,
S_3 = 32,
S_4 = 33,
S_5 = 34,
S_6 = 35,
S_7 = 36,
S_8 = 37,
S_9 = 38,
S_0 = 39,
S_RETURN = 40,
S_ESCAPE = 41,
S_BACKSPACE = 42,
S_TAB = 43,
S_SPACE = 44,
S_MINUS = 45,
S_EQUALS = 46,
S_LEFTBRACKET = 47,
S_RIGHTBRACKET = 48,
S_BACKSLASH = 49,
S_NONUSHASH = 50,
S_SEMICOLON = 51,
S_APOSTROPHE = 52,
S_GRAVE = 53,
S_COMMA = 54,
S_PERIOD = 55,
S_SLASH = 56,
S_CAPSLOCK = 57,
S_F1 = 58,
S_F2 = 59,
S_F3 = 60,
S_F4 = 61,
S_F5 = 62,
S_F6 = 63,
S_F7 = 64,
S_F8 = 65,
S_F9 = 66,
S_F10 = 67,
S_F11 = 68,
S_F12 = 69,
S_PRINTSCREEN = 70,
S_SCROLLLOCK = 71,
S_PAUSE = 72,
S_INSERT = 73,
S_HOME = 74,
S_PAGEUP = 75,
S_DELETE = 76,
S_END = 77,
S_PAGEDOWN = 78,
S_RIGHT = 79,
S_LEFT = 80,
S_DOWN = 81,
S_UP = 82,
S_NUMLOCKCLEAR = 83,
S_KP_DIVIDE = 84,
S_KP_MULTIPLY = 85,
S_KP_MINUS = 86,
S_KP_PLUS = 87,
S_KP_ENTER = 88,
S_KP_1 = 89,
S_KP_2 = 90,
S_KP_3 = 91,
S_KP_4 = 92,
S_KP_5 = 93,
S_KP_6 = 94,
S_KP_7 = 95,
S_KP_8 = 96,
S_KP_9 = 97,
S_KP_0 = 98,
S_KP_PERIOD = 99,
S_NONUSBACKSLASH = 100,
S_APPLICATION = 101,
S_POWER = 102,
S_KP_EQUALS = 103,
S_F13 = 104,
S_F14 = 105,
S_F15 = 106,
S_F16 = 107,
S_F17 = 108,
S_F18 = 109,
S_F19 = 110,
S_F20 = 111,
S_F21 = 112,
S_F22 = 113,
S_F23 = 114,
S_F24 = 115,
S_EXECUTE = 116,
S_HELP = 117,
S_MENU = 118,
S_SELECT = 119,
S_STOP = 120,
S_AGAIN = 121,
S_UNDO = 122,
S_CUT = 123,
S_COPY = 124,
S_PASTE = 125,
S_FIND = 126,
S_MUTE = 127,
S_VOLUMEUP = 128,
S_VOLUMEDOWN = 129,
S_KP_COMMA = 133,
S_KP_EQUALSAS400 = 134,
S_INTERNATIONAL1 = 135,
S_INTERNATIONAL2 = 136,
S_INTERNATIONAL3 = 137,
S_INTERNATIONAL4 = 138,
S_INTERNATIONAL5 = 139,
S_INTERNATIONAL6 = 140,
S_INTERNATIONAL7 = 141,
S_INTERNATIONAL8 = 142,
S_INTERNATIONAL9 = 143,
S_LANG1 = 144,
S_LANG2 = 145,
S_LANG3 = 146,
S_LANG4 = 147,
S_LANG5 = 148,
S_LANG6 = 149,
S_LANG7 = 150,
S_LANG8 = 151,
S_LANG9 = 152,
S_ALTERASE = 153,
S_SYSREQ = 154,
S_CANCEL = 155,
S_CLEAR = 156,
S_PRIOR = 157,
S_RETURN2 = 158,
S_SEPARATOR = 159,
S_OUT = 160,
S_OPER = 161,
S_CLEARAGAIN = 162,
S_CRSEL = 163,
S_EXSEL = 164,
S_KP_00 = 176,
S_KP_000 = 177,
S_THOUSANDSSEPARATOR = 178,
S_DECIMALSEPARATOR = 179,
S_CURRENCYUNIT = 180,
S_CURRENCYSUBUNIT = 181,
S_KP_LEFTPAREN = 182,
S_KP_RIGHTPAREN = 183,
S_KP_LEFTBRACE = 184,
S_KP_RIGHTBRACE = 185,
S_KP_TAB = 186,
S_KP_BACKSPACE = 187,
S_KP_A = 188,
S_KP_B = 189,
S_KP_C = 190,
S_KP_D = 191,
S_KP_E = 192,
S_KP_F = 193,
S_KP_XOR = 194,
S_KP_POWER = 195,
S_KP_PERCENT = 196,
S_KP_LESS = 197,
S_KP_GREATER = 198,
S_KP_AMPERSAND = 199,
S_KP_DBLAMPERSAND = 200,
S_KP_VERTICALBAR = 201,
S_KP_DBLVERTICALBAR = 202,
S_KP_COLON = 203,
S_KP_HASH = 204,
S_KP_SPACE = 205,
S_KP_AT = 206,
S_KP_EXCLAM = 207,
S_KP_MEMSTORE = 208,
S_KP_MEMRECALL = 209,
S_KP_MEMCLEAR = 210,
S_KP_MEMADD = 211,
S_KP_MEMSUBTRACT = 212,
S_KP_MEMMULTIPLY = 213,
S_KP_MEMDIVIDE = 214,
S_KP_PLUSMINUS = 215,
S_KP_CLEAR = 216,
S_KP_CLEARENTRY = 217,
S_KP_BINARY = 218,
S_KP_OCTAL = 219,
S_KP_DECIMAL = 220,
S_KP_HEXADECIMAL = 221,
S_LCTRL = 224,
S_LSHIFT = 225,
S_LALT = 226,
S_LGUI = 227,
S_RCTRL = 228,
S_RSHIFT = 229,
S_RALT = 230,
S_RGUI = 231,
S_MODE = 257,
S_AUDIONEXT = 258,
S_AUDIOPREV = 259,
S_AUDIOSTOP = 260,
S_AUDIOPLAY = 261,
S_AUDIOMUTE = 262,
S_MEDIASELECT = 263,
S_WWW = 264,
S_MAIL = 265,
S_CALCULATOR = 266,
S_COMPUTER = 267,
S_AC_SEARCH = 268,
S_AC_HOME = 269,
S_AC_BACK = 270,
S_AC_FORWARD = 271,
S_AC_STOP = 272,
S_AC_REFRESH = 273,
S_AC_BOOKMARKS = 274,
S_BRIGHTNESSDOWN = 275,
S_BRIGHTNESSUP = 276,
S_DISPLAYSWITCH = 277,
S_KBDILLUMTOGGLE = 278,
S_KBDILLUMDOWN = 279,
S_KBDILLUMUP = 280,
S_EJECT = 281,
S_SLEEP = 282,
S_APP1 = 283,
S_APP2 = 284,
S_AUDIOREWIND = 285,
S_AUDIOFASTFORWARD = 286,
NUM_SCANCODES = 512
};
| 19.413127 | 45 | 0.552506 | mechanicsfoundry |
3db1981084b1813f6fd4be3eb695e9820fb1ef9e | 507 | cpp | C++ | utils/src/drawing/Point.cpp | AleksievAleksandar/Chess | 4dd9e27ddf3302aa959d3a8854d3bc5fcb970dde | [
"MIT"
] | null | null | null | utils/src/drawing/Point.cpp | AleksievAleksandar/Chess | 4dd9e27ddf3302aa959d3a8854d3bc5fcb970dde | [
"MIT"
] | null | null | null | utils/src/drawing/Point.cpp | AleksievAleksandar/Chess | 4dd9e27ddf3302aa959d3a8854d3bc5fcb970dde | [
"MIT"
] | null | null | null | //Coresponding header
#include "utils/drawing/Point.h"
//C system includes
//C++ system includes
//Thitrd-party includes
//Own includes
//Forward Declarations
const Point Point::ZERO(0, 0);
const Point Point::UNDEFINED(1000, 1000);
Point::Point(int32_t inputX, int32_t inputY) :
x(inputX), y(inputY)
{}
bool Point::operator==(const Point & other) const
{
return ((this->x == other.x) && (this->y == other.y));
}
bool Point::operator!=(const Point& other) const
{
return !(*this == other);
}
| 15.363636 | 55 | 0.674556 | AleksievAleksandar |
3db374f94ab913c1d8f1e0148d5847f4bf406d94 | 1,961 | cpp | C++ | NatureUserInterfaceApp/GUI/NuiPangoPolygonMeshShader.cpp | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | 3 | 2016-07-14T13:04:35.000Z | 2017-04-01T09:58:27.000Z | NatureUserInterfaceApp/GUI/NuiPangoPolygonMeshShader.cpp | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | null | null | null | NatureUserInterfaceApp/GUI/NuiPangoPolygonMeshShader.cpp | hustztz/NatureUserInterfaceStudio | 3cdac6b6ee850c5c8470fa5f1554c7447be0d8af | [
"MIT"
] | 1 | 2021-11-21T15:33:35.000Z | 2021-11-21T15:33:35.000Z | #include "NuiPangoPolygonMeshShader.h"
#include "Shape\NuiPolygonMesh.h"
NuiPangoPolygonMeshShader::NuiPangoPolygonMeshShader()
: m_numTriangles(0)
{
glGenBuffers(1, &m_vbo);
glGenBuffers(1, &m_ibo);
}
NuiPangoPolygonMeshShader::~NuiPangoPolygonMeshShader()
{
uninitializeBuffers();
}
bool NuiPangoPolygonMeshShader::initializeBuffers(NuiPolygonMesh* pMesh)
{
if(!pMesh)
return false;
int currentNumTriangles = pMesh->getTrianglesNum();
if (abs(currentNumTriangles - m_numTriangles) > 100)
{
pMesh->evaluateMesh();
m_numTriangles = currentNumTriangles;
}
if (0 == m_numTriangles)
return false;
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, pMesh->getVerticesBufferSize(), pMesh->getVerticesBuffer(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, pMesh->getIndicesBufferSize(), pMesh->getIndicesBuffer(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return true;
}
void NuiPangoPolygonMeshShader::drawMesh(const pangolin::OpenGlMatrix& mvp, bool bNormals)
{
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glVertexPointer(3, GL_FLOAT, sizeof(pcl::PointXYZRGBNormal), 0);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
if (bNormals)
{
glColorPointer(3, GL_FLOAT, sizeof(pcl::PointXYZRGBNormal), (void *)(sizeof(float) * 4));
}
else
{
glColorPointer(3, GL_UNSIGNED_BYTE, sizeof(pcl::PointXYZRGBNormal), (void *)(sizeof(float) * 8));
}
glEnableClientState(GL_VERTEX_ARRAY);
glEnableClientState(GL_COLOR_ARRAY);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glDrawElements(GL_TRIANGLES, m_numTriangles * 3, GL_UNSIGNED_INT, 0);
glDisableClientState(GL_COLOR_ARRAY);
glDisableClientState(GL_VERTEX_ARRAY);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}
void NuiPangoPolygonMeshShader::uninitializeBuffers()
{
glDeleteBuffers(1, &m_vbo);
glDeleteBuffers(1, &m_ibo);
} | 26.146667 | 113 | 0.782764 | hustztz |
3db437c0abe19da4bb1dadb1d6c2e45b4ee1a2bc | 3,235 | cpp | C++ | src/bindings.cpp | joshuarrrrr/wand | b53bb4880714bf39ce9c6e3f903d0f1edcaf8047 | [
"MIT"
] | null | null | null | src/bindings.cpp | joshuarrrrr/wand | b53bb4880714bf39ce9c6e3f903d0f1edcaf8047 | [
"MIT"
] | null | null | null | src/bindings.cpp | joshuarrrrr/wand | b53bb4880714bf39ce9c6e3f903d0f1edcaf8047 | [
"MIT"
] | null | null | null | #include <pybind11/pybind11.h>
#include <pybind11/chrono.h>
#include <pybind11/numpy.h>
#include <pybind11/stl.h>
#include <string>
#include <multitouch_device.hpp>
#include <touch_point.hpp>
namespace py = pybind11;
using namespace wand;
PYBIND11_MODULE(wand, m) {
m.doc() = "";
py::class_<TouchPoint, std::shared_ptr<TouchPoint>>{m, "TouchPoint"}
.def(py::init<int>(), py::arg("id"))
.def("__repr__", [](const TouchPoint& touch) { return "<wand.TouchPoint " + std::to_string(touch.id()) + ">"; })
.def_property_readonly("id", &TouchPoint::id)
.def_property_readonly("active", &TouchPoint::active)
.def_property_readonly("start_time", &TouchPoint::start_time)
.def_property_readonly("update_time", &TouchPoint::update_time)
.def_property_readonly("end_time", &TouchPoint::end_time)
.def_property_readonly("duration", &TouchPoint::duration)
.def_property_readonly("start_x", &TouchPoint::start_x)
.def_property_readonly("start_y", &TouchPoint::start_y)
.def_property_readonly("start_pos",
[](const TouchPoint& touch) {
std::array<double, 2> pos = {touch.start_x(), touch.start_y()};
return py::array_t<double>(2, pos.data());
})
.def_property_readonly("x", &TouchPoint::x)
.def_property_readonly("y", &TouchPoint::y)
.def_property_readonly("pos",
[](const TouchPoint& touch) {
std::array<double, 2> pos = {touch.x(), touch.y()};
return py::array_t<double>(2, pos.data());
})
.def_property_readonly(
"direction",
[](const TouchPoint& touch) {
std::array<double, 2> direction = {touch.x() - touch.start_x(), touch.y() - touch.start_y()};
return py::array_t<double>(2, direction.data());
})
.def_property_readonly("timestamps", &TouchPoint::timestamps)
.def_property_readonly("x_positions", &TouchPoint::x_positions)
.def_property_readonly("y_positions", &TouchPoint::y_positions);
py::class_<MultitouchDevice, std::shared_ptr<MultitouchDevice>>{m, "MultitouchDevice"}
.def(py::init<std::string>(), py::arg("path"))
.def("__repr__",
[](const MultitouchDevice& device) { return "<wand.MultitouchDevice \"" + device.name() + "\">"; })
.def_property_readonly("name", &MultitouchDevice::name)
.def_property_readonly("num_slots", &MultitouchDevice::num_slots)
.def_property_readonly("touch_points", &MultitouchDevice::touch_points)
.def_property_readonly("running", &MultitouchDevice::running)
.def("start", &MultitouchDevice::start)
.def("stop", &MultitouchDevice::stop)
.def("poll_events", [](MultitouchDevice& dev) {
TouchPtrSet new_touch_points, updated_touch_points, finished_touch_points;
dev.poll_events(new_touch_points, updated_touch_points, finished_touch_points);
return std::make_tuple(std::move(new_touch_points), std::move(updated_touch_points),
std::move(finished_touch_points));
});
}
| 46.884058 | 118 | 0.622875 | joshuarrrrr |
3db73ec1c3b65834ef9d175708b430a03d76ff31 | 12,569 | cpp | C++ | ThirdParty/JSBSim/include/math/FGLocation.cpp | Lynnvon/FlightSimulator | 2dca6f8364b7f4972a248de3dbc3a711740f5ed4 | [
"MIT"
] | 1 | 2022-02-03T08:29:35.000Z | 2022-02-03T08:29:35.000Z | ThirdParty/JSBSim/include/math/FGLocation.cpp | Lynnvon/FlightSimulator | 2dca6f8364b7f4972a248de3dbc3a711740f5ed4 | [
"MIT"
] | null | null | null | ThirdParty/JSBSim/include/math/FGLocation.cpp | Lynnvon/FlightSimulator | 2dca6f8364b7f4972a248de3dbc3a711740f5ed4 | [
"MIT"
] | null | null | null | /*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Module: FGLocation.cpp
Author: Jon S. Berndt
Date started: 04/04/2004
Purpose: Store an arbitrary location on the globe
------- Copyright (C) 1999 Jon S. Berndt ([email protected]) ------------------
------- (C) 2004 Mathias Froehlich ([email protected]) ----
------- (C) 2011 Ola Røer Thorsen ([email protected]) -----------
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation; either version 2 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc., 59
Temple Place - Suite 330, Boston, MA 02111-1307, USA.
Further information about the GNU Lesser General Public License can also be
found on the world wide web at http://www.gnu.org.
FUNCTIONAL DESCRIPTION
------------------------------------------------------------------------------
This class encapsulates an arbitrary position in the globe with its accessors.
It has vector properties, so you can add multiply ....
HISTORY
------------------------------------------------------------------------------
04/04/2004 MF Created
11/01/2011 ORT Encapsulated ground callback code in FGLocation and removed
it from FGFDMExec.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
INCLUDES
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#include <cmath>
#include "FGLocation.h"
namespace JSBSim {
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
CLASS IMPLEMENTATION
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
FGLocation::FGLocation(void)
: mECLoc(1.0, 0.0, 0.0), mCacheValid(false)
{
e2 = c = 0.0;
a = ec = ec2 = 1.0;
mLon = mLat = mRadius = 0.0;
mGeodLat = GeodeticAltitude = 0.0;
mTl2ec.InitMatrix();
mTec2l.InitMatrix();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGLocation::FGLocation(double lon, double lat, double radius)
: mCacheValid(false)
{
e2 = c = 0.0;
a = ec = ec2 = 1.0;
mLon = mLat = mRadius = 0.0;
mGeodLat = GeodeticAltitude = 0.0;
mTl2ec.InitMatrix();
mTec2l.InitMatrix();
double sinLat = sin(lat);
double cosLat = cos(lat);
double sinLon = sin(lon);
double cosLon = cos(lon);
mECLoc = { radius*cosLat*cosLon,
radius*cosLat*sinLon,
radius*sinLat };
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGLocation::FGLocation(const FGColumnVector3& lv)
: mECLoc(lv), mCacheValid(false)
{
e2 = c = 0.0;
a = ec = ec2 = 1.0;
mLon = mLat = mRadius = 0.0;
mGeodLat = GeodeticAltitude = 0.0;
mTl2ec.InitMatrix();
mTec2l.InitMatrix();
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGLocation::FGLocation(const FGLocation& l)
: mECLoc(l.mECLoc), mCacheValid(l.mCacheValid)
{
a = l.a;
e2 = l.e2;
c = l.c;
ec = l.ec;
ec2 = l.ec2;
mEllipseSet = l.mEllipseSet;
/*ag
* if the cache is not valid, all of the following values are unset.
* They will be calculated once ComputeDerivedUnconditional is called.
* If unset, they may possibly contain NaN and could thus trigger floating
* point exceptions.
*/
if (!mCacheValid) return;
mLon = l.mLon;
mLat = l.mLat;
mRadius = l.mRadius;
mTl2ec = l.mTl2ec;
mTec2l = l.mTec2l;
mGeodLat = l.mGeodLat;
GeodeticAltitude = l.GeodeticAltitude;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
FGLocation& FGLocation::operator=(const FGLocation& l)
{
mECLoc = l.mECLoc;
mCacheValid = l.mCacheValid;
mEllipseSet = l.mEllipseSet;
a = l.a;
e2 = l.e2;
c = l.c;
ec = l.ec;
ec2 = l.ec2;
//ag See comment in constructor above
if (!mCacheValid) return *this;
mLon = l.mLon;
mLat = l.mLat;
mRadius = l.mRadius;
mTl2ec = l.mTl2ec;
mTec2l = l.mTec2l;
mGeodLat = l.mGeodLat;
GeodeticAltitude = l.GeodeticAltitude;
return *this;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGLocation::SetLongitude(double longitude)
{
double rtmp = mECLoc.Magnitude(eX, eY);
// Check if we have zero radius.
// If so set it to 1, so that we can set a position
if (0.0 == mECLoc.Magnitude())
rtmp = 1.0;
// Fast return if we are on the north or south pole ...
if (rtmp == 0.0)
return;
mCacheValid = false;
mECLoc(eX) = rtmp*cos(longitude);
mECLoc(eY) = rtmp*sin(longitude);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGLocation::SetLatitude(double latitude)
{
mCacheValid = false;
double r = mECLoc.Magnitude();
if (r == 0.0) {
mECLoc(eX) = 1.0;
r = 1.0;
}
double rtmp = mECLoc.Magnitude(eX, eY);
if (rtmp != 0.0) {
double fac = r/rtmp*cos(latitude);
mECLoc(eX) *= fac;
mECLoc(eY) *= fac;
} else {
mECLoc(eX) = r*cos(latitude);
mECLoc(eY) = 0.0;
}
mECLoc(eZ) = r*sin(latitude);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGLocation::SetRadius(double radius)
{
mCacheValid = false;
double rold = mECLoc.Magnitude();
if (rold == 0.0)
mECLoc(eX) = radius;
else
mECLoc *= radius/rold;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGLocation::SetPosition(double lon, double lat, double radius)
{
mCacheValid = false;
double sinLat = sin(lat);
double cosLat = cos(lat);
double sinLon = sin(lon);
double cosLon = cos(lon);
mECLoc = { radius*cosLat*cosLon,
radius*cosLat*sinLon,
radius*sinLat };
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGLocation::SetPositionGeodetic(double lon, double lat, double height)
{
assert(mEllipseSet);
mCacheValid = false;
double slat = sin(lat);
double clat = cos(lat);
double RN = a / sqrt(1.0 - e2*slat*slat);
mECLoc(eX) = (RN + height)*clat*cos(lon);
mECLoc(eY) = (RN + height)*clat*sin(lon);
mECLoc(eZ) = ((1 - e2)*RN + height)*slat;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGLocation::SetEllipse(double semimajor, double semiminor)
{
mCacheValid = false;
mEllipseSet = true;
a = semimajor;
ec = semiminor/a;
ec2 = ec * ec;
e2 = 1.0 - ec2;
c = a * e2;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
double FGLocation::GetSeaLevelRadius(void) const
{
assert(mEllipseSet);
ComputeDerived();
double cosLat = cos(mLat);
return a*ec/sqrt(1.0-e2*cosLat*cosLat);
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
void FGLocation::ComputeDerivedUnconditional(void) const
{
// The radius is just the Euclidean norm of the vector.
mRadius = mECLoc.Magnitude();
// The distance of the location to the Z-axis, which is the axis
// through the poles.
double rxy = mECLoc.Magnitude(eX, eY);
// Compute the longitude and its sin/cos values.
double sinLon, cosLon;
if (rxy == 0.0) {
sinLon = 0.0;
cosLon = 1.0;
mLon = 0.0;
} else {
sinLon = mECLoc(eY)/rxy;
cosLon = mECLoc(eX)/rxy;
mLon = atan2(mECLoc(eY), mECLoc(eX));
}
// Compute the geocentric & geodetic latitudes.
double sinLat, cosLat;
if (mRadius == 0.0) {
mLat = 0.0;
sinLat = 0.0;
cosLat = 1.0;
if (mEllipseSet) {
mGeodLat = 0.0;
GeodeticAltitude = -a;
}
}
else {
mLat = atan2( mECLoc(eZ), rxy );
// Calculate the geodetic latitude based on "Transformation from Cartesian to
// geodetic coordinates accelerated by Halley's method", Fukushima T. (2006)
// Journal of Geodesy, Vol. 79, pp. 689-693
// Unlike I. Sofair's method which uses a closed form solution, Fukushima's
// method is an iterative method whose convergence is so fast that only one
// iteration suffices. In addition, Fukushima's method has a much better
// numerical stability over Sofair's method at the North and South poles and
// it also gives the correct result for a spherical Earth.
if (mEllipseSet) {
double s0 = fabs(mECLoc(eZ));
double zc = ec * s0;
double c0 = ec * rxy;
double c02 = c0 * c0;
double s02 = s0 * s0;
double a02 = c02 + s02;
double a0 = sqrt(a02);
double a03 = a02 * a0;
double s1 = zc*a03 + c*s02*s0;
double c1 = rxy*a03 - c*c02*c0;
double cs0c0 = c*c0*s0;
double b0 = 1.5*cs0c0*((rxy*s0-zc*c0)*a0-cs0c0);
s1 = s1*a03-b0*s0;
double cc = ec*(c1*a03-b0*c0);
mGeodLat = sign(mECLoc(eZ))*atan(s1 / cc);
double s12 = s1 * s1;
double cc2 = cc * cc;
double norm = sqrt(s12 + cc2);
cosLat = cc / norm;
sinLat = sign(mECLoc(eZ)) * s1 / norm;
GeodeticAltitude = (rxy*cc + s0*s1 - a*sqrt(ec2*s12 + cc2)) / norm;
}
else {
sinLat = mECLoc(eZ)/mRadius;
cosLat = rxy/mRadius;
}
}
// Compute the transform matrices from and to the earth centered frame.
// See Stevens and Lewis, "Aircraft Control and Simulation", Second Edition,
// Eqn. 1.4-13, page 40. In Stevens and Lewis notation, this is C_n/e - the
// orientation of the navigation (local) frame relative to the ECEF frame,
// and a transformation from ECEF to nav (local) frame.
mTec2l = { -cosLon*sinLat, -sinLon*sinLat, cosLat,
-sinLon , cosLon , 0.0 ,
-cosLon*cosLat, -sinLon*cosLat, -sinLat };
// In Stevens and Lewis notation, this is C_e/n - the
// orientation of the ECEF frame relative to the nav (local) frame,
// and a transformation from nav (local) to ECEF frame.
mTl2ec = mTec2l.Transposed();
// Mark the cached values as valid
mCacheValid = true;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The calculations, below, implement the Haversine formulas to calculate
// heading and distance to a set of lat/long coordinates from the current
// position.
//
// The basic equations are (lat1, long1 are source positions; lat2
// long2 are target positions):
//
// R = earth’s radius
// Δlat = lat2 − lat1
// Δlong = long2 − long1
//
// For the waypoint distance calculation:
//
// a = sin²(Δlat/2) + cos(lat1)∙cos(lat2)∙sin²(Δlong/2)
// c = 2∙atan2(√a, √(1−a))
// d = R∙c
double FGLocation::GetDistanceTo(double target_longitude,
double target_latitude) const
{
ComputeDerived();
double delta_lat_rad = target_latitude - mLat;
double delta_lon_rad = target_longitude - mLon;
double distance_a = pow(sin(0.5*delta_lat_rad), 2.0)
+ (cos(mLat) * cos(target_latitude)
* (pow(sin(0.5*delta_lon_rad), 2.0)));
return 2.0 * GetRadius() * atan2(sqrt(distance_a), sqrt(1.0 - distance_a));
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
// The calculations, below, implement the Haversine formulas to calculate
// heading and distance to a set of lat/long coordinates from the current
// position.
//
// The basic equations are (lat1, long1 are source positions; lat2
// long2 are target positions):
//
// R = earth’s radius
// Δlat = lat2 − lat1
// Δlong = long2 − long1
//
// For the heading angle calculation:
//
// θ = atan2(sin(Δlong)∙cos(lat2), cos(lat1)∙sin(lat2) − sin(lat1)∙cos(lat2)∙cos(Δlong))
double FGLocation::GetHeadingTo(double target_longitude,
double target_latitude) const
{
ComputeDerived();
double delta_lon_rad = target_longitude - mLon;
double Y = sin(delta_lon_rad) * cos(target_latitude);
double X = cos(mLat) * sin(target_latitude)
- sin(mLat) * cos(target_latitude) * cos(delta_lon_rad);
double heading_to_waypoint_rad = atan2(Y, X);
if (heading_to_waypoint_rad < 0) heading_to_waypoint_rad += 2.0*M_PI;
return heading_to_waypoint_rad;
}
//%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
} // namespace JSBSim
| 28.565909 | 89 | 0.557403 | Lynnvon |
3dbc6b4a4e76a80b1006d2832fe4f8eb1fc8cd74 | 667 | cpp | C++ | tests/all.cpp | robclu/wrench | 8fff96c35b4d2ff351edd8ec2b7ce0d03343bda7 | [
"MIT"
] | null | null | null | tests/all.cpp | robclu/wrench | 8fff96c35b4d2ff351edd8ec2b7ce0d03343bda7 | [
"MIT"
] | null | null | null | tests/all.cpp | robclu/wrench | 8fff96c35b4d2ff351edd8ec2b7ce0d03343bda7 | [
"MIT"
] | null | null | null | //==--- wrench/tests/all.cpp ------------------------------- -*- C++ -*- ---==//
//
// Wrench
//
// Copyright (c) 2020 Rob Clucas.
//
// This file is distributed under the MIT License. See LICENSE for details.
//
//==------------------------------------------------------------------------==//
//
/// \file all.cpp
/// \brief This file implements all tests.
//
//==------------------------------------------------------------------------==//
#include "algorithm/algorithm.hpp"
#include "memory/memory.hpp"
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | 30.318182 | 80 | 0.4003 | robclu |
3dbd2980368ebc42b00ccbf542aa0777d2c7b032 | 2,137 | cc | C++ | fides/mock_settings_document.cc | cschuet/fides | c31ad020f213f859ddeb7a7be558e7769a501044 | [
"FSFAP"
] | 2 | 2018-07-27T00:29:35.000Z | 2018-07-29T14:44:59.000Z | fides/mock_settings_document.cc | cschuet/fides | c31ad020f213f859ddeb7a7be558e7769a501044 | [
"FSFAP"
] | null | null | null | fides/mock_settings_document.cc | cschuet/fides | c31ad020f213f859ddeb7a7be558e7769a501044 | [
"FSFAP"
] | null | null | null | // Copyright 2015 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 "fides/mock_settings_document.h"
#include "fides/identifier_utils.h"
namespace fides {
MockSettingsDocument::MockSettingsDocument(const VersionStamp& version_stamp)
: version_stamp_(version_stamp) {}
MockSettingsDocument::~MockSettingsDocument() {}
std::unique_ptr<MockSettingsDocument> MockSettingsDocument::Clone() const {
std::unique_ptr<MockSettingsDocument> copy(
new MockSettingsDocument(version_stamp_));
copy->deletions_ = deletions_;
copy->key_value_map_ = key_value_map_;
return copy;
}
BlobRef MockSettingsDocument::GetValue(const Key& key) const {
auto entry = key_value_map_.find(key);
return entry != key_value_map_.end() ? BlobRef(&entry->second) : BlobRef();
}
std::set<Key> MockSettingsDocument::GetKeys(const Key& prefix) const {
std::set<Key> result;
for (const auto& entry : utils::GetRange(prefix, key_value_map_))
result.insert(entry.first);
return result;
}
std::set<Key> MockSettingsDocument::GetDeletions(const Key& prefix) const {
std::set<Key> result;
for (const auto& entry : utils::GetRange(prefix, deletions_))
result.insert(entry);
return result;
}
VersionStamp MockSettingsDocument::GetVersionStamp() const {
return version_stamp_;
}
bool MockSettingsDocument::HasKeysOrDeletions(const Key& prefix) const {
return utils::HasKeys(prefix, key_value_map_) ||
utils::HasKeys(prefix, deletions_);
}
void MockSettingsDocument::SetKey(const Key& key, const std::string& value) {
key_value_map_.insert(std::make_pair(key, std::move(value)));
}
void MockSettingsDocument::ClearKey(const Key& key) {
key_value_map_.erase(key);
}
void MockSettingsDocument::ClearKeys() {
key_value_map_.clear();
}
void MockSettingsDocument::SetDeletion(const Key& key) {
deletions_.insert(key);
}
void MockSettingsDocument::ClearDeletion(const Key& key) {
deletions_.erase(key);
}
void MockSettingsDocument::ClearDeletions() {
deletions_.clear();
}
} // namespace fides
| 27.753247 | 77 | 0.750585 | cschuet |
3dbdc45ea055ecc6fc7cf67d92f3a5c3fad796cc | 3,509 | cpp | C++ | EngCode/SOHTA engine/Graphics.cpp | AthosMatos/ATHOS-Engine | 24b09042cd8d661ac70d0f6b302a8b129a843fbd | [
"MIT"
] | null | null | null | EngCode/SOHTA engine/Graphics.cpp | AthosMatos/ATHOS-Engine | 24b09042cd8d661ac70d0f6b302a8b129a843fbd | [
"MIT"
] | null | null | null | EngCode/SOHTA engine/Graphics.cpp | AthosMatos/ATHOS-Engine | 24b09042cd8d661ac70d0f6b302a8b129a843fbd | [
"MIT"
] | null | null | null | #include "Graphics.h"
#include <string.h>
void Graphics::init(HWND hwnd)
{
cout << "GRAPHICS STARTED\n";
d3d = new D3D;
d2d = new D2D;
RQ2D = new RenderQueue_2D;
fistscene = new StdScene;
d3d->InitD3D(hwnd);
InitSharedScreen(d3d->Adapter);
d2d->InitD2D(sharedSurface10);
d2d->UpdateClassResources(keyedMutex11, keyedMutex10);
d3d->Adapter->Release();
sharedSurface10->Release();
keyedMutex11->Release();
keyedMutex10->Release();
cout << "GRAPHICS LOADED\n";
}
void Graphics::startScene()
{
fistscene->LoadScene();
d2d->SetRenderArea(sharedTex11, 0, 0, 0, 0);
sharedTex11->Release();
}
void Graphics::Update(double FrameTime, double FPS)
{
fistscene->SceneInput(FrameTime);
fistscene->UpdateScene(FrameTime,FPS);
}
void Graphics::Render()
{
//bckground color
float bgColor[4] = { 0.0f,0.05f,0.1f,1.0f };
//Clear our backbuffer
d3d->d3dDevCon->ClearRenderTargetView(d3d->renderTargetView, bgColor);
d3d->d3dDevCon->ClearDepthStencilView(d3d->depthStencilView, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0);
fistscene->Renderscene();
RQ2D->Render();
d3d->SwapChain->Present(0, 0);
}
void Graphics::Release()
{
if (d2d)d2d->Release();
if (d3d)d3d->Release();
if (fistscene)fistscene->Release();
if (RQ2D)RQ2D->Release();
}
void Graphics::InitSharedScreen(IDXGIAdapter1* Adapter)
{
//Create our Direc3D 10.1 Device///////////////////////////////////////////////////////////////////////////////////////
HRESULT hr = D3D10CreateDevice1(Adapter, D3D10_DRIVER_TYPE_HARDWARE, NULL, D3D10_CREATE_DEVICE_BGRA_SUPPORT,
D3D10_FEATURE_LEVEL_9_3, D3D10_1_SDK_VERSION, &d3d101Device);
//Create Shared Texture that Direct3D 10.1 will render on//////////////////////////////////////////////////////////////
D3D11_TEXTURE2D_DESC sharedTexDesc;
ZeroMemory(&sharedTexDesc, sizeof(sharedTexDesc));
sharedTexDesc.Width = H_res;
sharedTexDesc.Height = V_res;
sharedTexDesc.Format = DXGI_FORMAT_B8G8R8A8_UNORM;
sharedTexDesc.MipLevels = 1;
sharedTexDesc.ArraySize = 1;
sharedTexDesc.SampleDesc.Count = 1;
sharedTexDesc.Usage = D3D11_USAGE_DEFAULT;
sharedTexDesc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
sharedTexDesc.MiscFlags = D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX;
hr = d3d->d3dDevice->CreateTexture2D(&sharedTexDesc, NULL, &sharedTex11);
// Get the keyed mutex for the shared texture (for D3D11)///////////////////////////////////////////////////////////////
hr = sharedTex11->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex11);
// Get the shared handle needed to open the shared texture in D3D10.1///////////////////////////////////////////////////
IDXGIResource* sharedResource10;
HANDLE sharedHandle10;
hr = sharedTex11->QueryInterface(__uuidof(IDXGIResource), (void**)&sharedResource10);
hr = sharedResource10->GetSharedHandle(&sharedHandle10);
sharedResource10->Release();
// Open the surface for the shared texture in D3D10.1///////////////////////////////////////////////////////////////////
hr = d3d101Device->OpenSharedResource(sharedHandle10, __uuidof(IDXGISurface1), (void**)(&sharedSurface10));
hr = sharedSurface10->QueryInterface(__uuidof(IDXGIKeyedMutex), (void**)&keyedMutex10);
d3d101Device->IASetPrimitiveTopology(D3D10_PRIMITIVE_TOPOLOGY_POINTLIST);
d3d101Device->Release();
}
| 30.513043 | 124 | 0.647763 | AthosMatos |
3dc6dd6bd96bf2220ffed2970168c76685ac3ccd | 1,263 | cpp | C++ | c11httpd/worker_pool.cpp | toalexjin/c11httpd | 6774d96c72d60ad8c371a6d846744a9ccc98d7ee | [
"MIT"
] | null | null | null | c11httpd/worker_pool.cpp | toalexjin/c11httpd | 6774d96c72d60ad8c371a6d846744a9ccc98d7ee | [
"MIT"
] | null | null | null | c11httpd/worker_pool.cpp | toalexjin/c11httpd | 6774d96c72d60ad8c371a6d846744a9ccc98d7ee | [
"MIT"
] | null | null | null | /**
* Process worker pool.
*
* Copyright (c) 2015 Alex Jin ([email protected])
*/
#include "c11httpd/worker_pool.h"
#include <signal.h>
namespace c11httpd {
err_t worker_pool_t::create(int number) {
if (!this->m_main_process) {
return err_t();
}
for (int i = 0; i < number; ++i) {
const auto pid = fork();
if (pid == -1) {
return err_t::current();
}
if (pid == 0) {
this->m_self_pid = getpid();
this->m_main_process = false;
break;
} else {
assert(this->m_main_process);
this->m_workers.insert(pid);
}
}
return err_t();
}
err_t worker_pool_t::kill(pid_t pid) {
err_t ret;
if (!this->m_main_process) {
return ret;
}
auto pos = this->m_workers.find(pid);
if (pos == this->m_workers.end()) {
return ret;
}
if (::kill(pid, SIGTERM) == -1) {
ret = err_t::current();
}
this->m_workers.erase(pos);
return ret;
}
void worker_pool_t::kill_all() {
if (!this->m_main_process) {
return;
}
for (auto it = this->m_workers.cbegin(); it != this->m_workers.cend(); ++it) {
::kill((*it), SIGTERM);
}
this->m_workers.clear();
}
bool worker_pool_t::on_terminated(pid_t pid) {
if (!this->m_main_process) {
return false;
}
return this->m_workers.erase(pid) > 0;
}
} // namespace c11httpd.
| 15.592593 | 79 | 0.618369 | toalexjin |
3dcc020c864f9a41ba0be26926ad485193f0f698 | 2,958 | hpp | C++ | include/CppML/Functional/Bind.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | 48 | 2019-05-14T10:07:08.000Z | 2021-04-08T08:26:20.000Z | include/CppML/Functional/Bind.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | null | null | null | include/CppML/Functional/Bind.hpp | changjurhee/CppML | 6d4cc6d0dd2fa3055823f191dc7fe953e4966fc5 | [
"MIT"
] | 4 | 2019-11-18T15:35:32.000Z | 2021-12-02T05:23:04.000Z | /**
* Copyright Žiga Sajovic, XLAB 2019
* Distributed under the MIT License
*
* https://github.com/ZigaSajovic/CppML
**/
#ifndef CPPML_BIND_HPP
#define CPPML_BIND_HPP
#include "../Pack/Insert.hpp"
#include "./Compose.hpp"
#include "./Partial.hpp"
namespace ml {
/*
* # Par:
* Is a parameter holder for ml::Bind.
*/
template <int I, typename T> struct Par {
template <typename Pipe> using f = ml::Insert<I, T, Pipe>;
};
/*
* # Bind:
* Binds arguments, creating a partially evaluated metafunction
* **NOTE** that Is must be in sorted order
*/
template <typename F, typename... Ts> struct Bind;
template <typename F, int... Is, typename... Args>
struct Bind<F, Par<Is, Args>...>
: ml::Invoke<ml::Compose<Par<Is, Args>...>, F> {};
/*
* Below are a few optimizations to avoid work. When we are binding
* successive parameters, from the first forward, it is the same as
* if we used ml::Partial, which is more efficient.
*/
template <typename F, typename T0>
struct Bind<F, Par<0, T0>> : ml::Partial<F, T0> {};
template <typename F, typename T0, typename T1>
struct Bind<F, Par<0, T0>, Par<1, T1>> : ml::Partial<F, T0, T1> {};
template <typename F, typename T0, typename T1, typename T2>
struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>>
: ml::Partial<F, T0, T1, T2> {};
template <typename F, typename T0, typename T1, typename T2, typename T3>
struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>>
: ml::Partial<F, T0, T1, T2, T3> {};
template <typename F, typename T0, typename T1, typename T2, typename T3,
typename T4>
struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>, Par<4, T4>>
: ml::Partial<F, T0, T1, T2, T3, T4> {};
template <typename F, typename T0, typename T1, typename T2, typename T3,
typename T4, typename T5>
struct Bind<F, Par<0, T0>, Par<1, T1>, Par<2, T2>, Par<3, T3>, Par<4, T4>,
Par<5, T5>> : ml::Partial<F, T0, T1, T2, T3, T4, T5> {};
/*
* # _pi:
*/
template <typename T> using _p0 = Par<0, T>;
template <typename T> using _p1 = Par<1, T>;
template <typename T> using _p2 = Par<2, T>;
template <typename T> using _p3 = Par<3, T>;
template <typename T> using _p4 = Par<4, T>;
template <typename T> using _p5 = Par<5, T>;
template <typename T> using _p6 = Par<6, T>;
template <typename T> using _p7 = Par<7, T>;
template <typename T> using _p8 = Par<8, T>;
template <typename T> using _p9 = Par<9, T>;
template <typename T> using _p10 = Par<10, T>;
template <typename T> using _p11 = Par<11, T>;
template <typename T> using _p12 = Par<12, T>;
template <typename T> using _p13 = Par<13, T>;
template <typename T> using _p14 = Par<14, T>;
template <typename T> using _p15 = Par<15, T>;
template <typename T> using _p16 = Par<16, T>;
template <typename T> using _p17 = Par<17, T>;
template <typename T> using _p18 = Par<18, T>;
template <typename T> using _p19 = Par<19, T>;
template <typename T> using _p20 = Par<20, T>;
} // namespace ml
#endif
| 34.395349 | 74 | 0.647059 | changjurhee |
3dd3c37f0f0095ce5a16fc2bbd023478f50d6855 | 14,921 | hpp | C++ | kaluun/parser.hpp | dimitarm/kaluun | 1fd73fafcc2853f9cd2cebbc08dafef93e17ea28 | [
"MIT"
] | 2 | 2016-09-09T10:36:20.000Z | 2017-08-14T02:41:43.000Z | kaluun/parser.hpp | dimitarm/kaluun | 1fd73fafcc2853f9cd2cebbc08dafef93e17ea28 | [
"MIT"
] | null | null | null | kaluun/parser.hpp | dimitarm/kaluun | 1fd73fafcc2853f9cd2cebbc08dafef93e17ea28 | [
"MIT"
] | null | null | null | /*
* parser.hpp
*
* Created on: Jun 23, 2015
* Author: dimitar
*/
#include "template.hpp"
#include <ostream>
#include <sstream>
#include <utility>
#include <tuple>
#include <typeinfo>
#include <vector>
#include <algorithm>
#include <boost/range.hpp>
#include <boost/range/algorithm/find.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/algorithm/cxx11/all_of.hpp>
#include <cctype>
#ifndef PARSER_HPP_
#define PARSER_HPP_
namespace kaluun {
template<class Template>
struct parser {
typedef Template templ_type;
typedef typename Template::context_type context_type;
typedef typename Template::out_type out_type;
typedef typename Template::in_type in_type;
typedef typename Template::holder_type holder_type;
typedef typename templ_type::in_type::const_iterator const_iterator_type;
typedef typename Template::expression_type expression_type;
typedef typename Template::condition_type condition_type;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
struct exception: public std::exception {
std::string msg_;
exception(const in_type& in, const_iterator_type pos, std::string msg) {
std::stringstream buf;
auto begin = in.begin();
for (int count = 10; pos != begin && count; pos--, count--) {
}
buf << msg << std::string(": ");
for (int count = 20; pos != in.end() && count; pos++, count--)
buf << *pos;
buf << std::endl;
msg_ = buf.str();
}
const char* what() const noexcept (true) {
return msg_.c_str();
}
};
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
const char OPEN_BRACKET = '{';
const char CLOSE_BRACKET = '}';
const char PERCENT = '%';
const char DIEZ = '#';
const char QUOTE1 = '\x27';
const char QUOTE2 = '\"';
const char WHITE_CHAR = ' ';
//tokens
const char TOKEN_FOR[3] = { 'f', 'o', 'r' };
const char TOKEN_IN[2] = { 'i', 'n' };
const char TOKEN_ENDFOR[6] = { 'e', 'n', 'd', 'f', 'o', 'r' };
const char TOKEN_IF[2] = { 'i', 'f' };
const char TOKEN_ELIF[4] = { 'e', 'l', 'i', 'f' };
const char TOKEN_ELSE[4] = { 'e', 'l', 's', 'e' };
const char TOKEN_ENDIF[5] = { 'e', 'n', 'd', 'i', 'f' };
const char TOKEN_SET[3] = { 's', 'e', 't' };
in_type& in_;
templ_type& tree_;
parser(in_type& in, templ_type& template_tree) :
in_(in), tree_(template_tree) {
}
const_iterator_type create_text_node(const_iterator_type pos, node_with_children<context_type, out_type>* cur_level_node) {
text_node<context_type, out_type, holder_type>* tx_node = new text_node<context_type, out_type, holder_type>;
const_iterator_type begin = pos;
bool open_bracket = false;
while (pos != in_.end()) {
if ((*pos == OPEN_BRACKET || *pos == PERCENT || *pos == DIEZ) && open_bracket) {
break;
} else if (*pos == OPEN_BRACKET)
open_bracket = true;
else
open_bracket = false;
pos++;
}
if (pos == in_.end()) {
holder_type pure_text(begin, pos);
tx_node->text_ = std::move(pure_text);
} else {
holder_type pure_text(begin, pos - 1);
tx_node->text_ = std::move(pure_text);
}
if (tx_node->text_.size() > 0)
cur_level_node->add_child(tx_node);
else
delete tx_node;
return pos;
}
/**
* Parse an expression. Returns true if expression has quotation and false otherwise.
* If the expression has quotation quoted_str holds the unquoted string
* If not expr_str holds the expression
*/
template<class Holder>
bool parse_expression(const_iterator_type& pos, Holder& expr_str, std::string& quoted_str) {
bool res = false;
while (*pos == WHITE_CHAR and pos != in_.end())
pos++; //skip all white chars
if (pos == in_.end())
throw exception(in_, pos, "unexpected end of template");
auto begin = pos; //start of expression
auto end = pos; //end of expression
//extract variable name
int quote = 0;
int num_white_chars = 0;
for (; pos != in_.end() && (*pos != CLOSE_BRACKET || quote != 0); pos++) {
if (quote != 0) { //inside quote
if (*pos == quote)
quote = 0;
else
quoted_str += *pos;
num_white_chars = 0; //white characters in the tail
} else {
if (*pos == QUOTE1 || *pos == QUOTE2) {
res = true;
quoted_str.append(begin, end); //append all unquoted string so far
end = begin; //make sure nothing will be added anymore
quote = *pos; //will check for corresponding same type of quote
} else {
if (res)
quoted_str += *pos;
else
end++;
if (*pos == WHITE_CHAR)
num_white_chars++;
else
num_white_chars = 0;
}
}
}
if (pos == in_.end())
throw exception(in_, pos, "unexpected end of template");
pos++;
if (*pos != CLOSE_BRACKET)
throw exception(in_, pos, "unexpected symbol");
pos++;
if (res)
quoted_str.erase(quoted_str.end() - num_white_chars, quoted_str.end());
else
expr_str = Holder(begin, end - num_white_chars);
return res;
}
bool parse_expression(const_iterator_type& pos, std::string& expr_str, std::string& quoted_str) {
bool res = false;
while (*pos == WHITE_CHAR and pos != in_.end())
pos++; //skip all white chars
if (pos == in_.end())
throw exception(in_, pos, "unexpected end of template");
//extract variable name
int quote = 0;
int num_white_chars = 0;
for (; pos != in_.end() && (*pos != CLOSE_BRACKET || quote != 0); pos++) {
if (quote != 0) { //inside quote
if (*pos == quote)
quote = 0;
else
quoted_str += *pos;
num_white_chars = 0; //white characters in the tail
} else {
if (*pos == QUOTE1 || *pos == QUOTE2) {
res = true;
quoted_str.append(expr_str); //append all unquoted string so far
expr_str.clear(); //make sure nothing will be added anymore
quote = *pos; //will check for corresponding same type of quote
} else {
if (res)
quoted_str += *pos;
else
expr_str += *pos;
if (*pos == WHITE_CHAR)
num_white_chars++;
else
num_white_chars = 0;
}
}
}
if (pos == in_.end())
throw exception(in_, pos, "unexpected end of template");
pos++;
if (*pos != CLOSE_BRACKET)
throw exception(in_, pos, "unexpected symbol");
pos++;
if (res)
quoted_str.erase(quoted_str.end() - num_white_chars, quoted_str.end());
else
expr_str.erase(expr_str.end() - num_white_chars, expr_str.end());
return res;
}
const_iterator_type create_variable_node(const_iterator_type pos, node_with_children<context_type, out_type>* cur_level_node) {
holder_type expr_text;
std::string unquoted_expr_text;
node<context_type, out_type>* v_node;
if (parse_expression(pos, expr_text, unquoted_expr_text)) {
text_node<context_type, out_type, std::string>* node = new text_node<context_type, out_type, std::string>;
v_node = node;
node->text_ = unquoted_expr_text;
} else {
if (std::all_of(std::begin(expr_text), std::end(expr_text), [](char ch){ return isalnum(ch) || ch == '.'; })) { //todo use better algorithm to check if variable or not
variable_node<context_type, out_type, holder_type>* node = new variable_node<context_type, out_type, holder_type>;
v_node = node;
node->name_ = expr_text;
} else {
expression_node<context_type, out_type, expression_type>* ex_node = new expression_node<context_type, out_type, expression_type>;
expression_type::parse(expr_text, ex_node->expression_);
v_node = ex_node;
}
}
cur_level_node->add_child(v_node);
return pos;
}
const_iterator_type create_comment_node(const_iterator_type pos) {
do {
while (pos != in_.end() && *pos != DIEZ)
pos++;
pos++;
} while (pos != in_.end() && *pos != CLOSE_BRACKET);
pos++;
return pos;
}
node<context_type, out_type>* create_loop_node(boost::iterator_range<const_iterator_type>& var, boost::iterator_range<const_iterator_type>& local_var,
node_with_children<context_type, out_type>* cur_level_node) { //for row in rows
for_loop_node<context_type, out_type, holder_type>* loop_node = new for_loop_node<context_type, out_type, holder_type>;
loop_node->loop_variable_ = holder_type(var.begin(), var.end());
loop_node->local_loop_variable_ = holder_type(local_var.begin(), local_var.end());
cur_level_node->add_child(loop_node);
return loop_node;
}
node_with_children<context_type, out_type>* create_if_condition_node(const_iterator_type expr_begin, const_iterator_type expr_end, bool ifnode,
node_with_children<context_type, out_type>* cur_level_node) { //for row in rows
holder_type expression_string(expr_begin, expr_end);
if_node<context_type, out_type, condition_type>* c_node;
if (ifnode)
c_node = new if_node<context_type, out_type, condition_type>;
else {
if_node<context_type, out_type, condition_type>* ifnode = dynamic_cast<if_node<context_type, out_type, condition_type>*>(cur_level_node);
if(!ifnode)
throw exception(in_, expr_begin, std::string("template error: expected node was if or elif, got: ") + typeid(*cur_level_node).name());
c_node = new elif_node<context_type, out_type, condition_type>;
ifnode->else_node_ = c_node;
}
condition_type::parse(expression_string, c_node->condition_);
cur_level_node->add_child(c_node);
return c_node;
}
set_node<context_type, out_type, expression_type, holder_type>* create_set_node(const_iterator_type begin, const_iterator_type end,
node_with_children<context_type, out_type>* cur_level_node) {
const_iterator_type eq_pos = boost::range::find(boost::make_iterator_range(begin, end), '=');
if (eq_pos != end) {
auto variable = boost::trim_copy_if(boost::make_iterator_range(begin, eq_pos), boost::is_any_of(" \t")); //variable name
auto expression_string = boost::trim_copy_if(boost::make_iterator_range(eq_pos + 1, end), boost::is_any_of(" \t")); //expression string
set_node<context_type, out_type, expression_type, holder_type> * node_ptr = new set_node<context_type, out_type, expression_type, holder_type>;
node_ptr->variable_name_ = holder_type(variable.begin(), variable.end());
expression_type::parse(holder_type(expression_string.begin(), expression_string.end()), node_ptr->expression_);
cur_level_node->add_child(node_ptr);
return node_ptr;
} else
throw exception(in_, begin, "cannot parse set node");
}
std::pair<node<context_type, out_type>*, int> create_statement_node(const_iterator_type begin, const_iterator_type end,
node_with_children<context_type, out_type>* cur_level_node) {
boost::iterator_range<const_iterator_type> node_text(begin, end);
std::vector<boost::iterator_range<const_iterator_type> > tokens(5); // Search for tokens
boost::split(tokens, node_text, boost::is_any_of(" \t"), boost::token_compress_on);
//remove spaces at the beginning and at the end if any
if (tokens.back().size() == 0)
tokens.erase(tokens.end() - 1);
if (tokens.front().size() == 0)
tokens.erase(tokens.begin());
//for in
if (tokens[0] == TOKEN_FOR && tokens[2] == TOKEN_IN && tokens.size() == 4)
return std::make_pair(create_loop_node(tokens[3], tokens[1], cur_level_node), 1);
//endfor
else if (tokens[0] == TOKEN_ENDFOR && tokens.size() == 1)
return std::make_pair(nullptr, -1);
//if, elif
else if (tokens[0] == TOKEN_IF && tokens.size() > 1)
return std::make_pair(create_if_condition_node(tokens[1].begin(), tokens.back().end(), true, cur_level_node), 1);
else if (tokens[0] == TOKEN_ELIF && tokens.size() > 1)
return std::make_pair(create_if_condition_node(tokens[1].begin(), tokens.back().end(), false, cur_level_node), 1);
//else
else if (tokens[0] == TOKEN_ELSE && tokens.size() == 1) {
if_node<context_type, out_type, condition_type>* ifnode = dynamic_cast<if_node<context_type, out_type, condition_type>*>(cur_level_node);
if (ifnode) {
node_with_children<context_type, out_type> * else_node = new node_with_children<context_type, out_type>;
ifnode->else_node_ = else_node;
cur_level_node->add_child(else_node);
return std::make_pair(else_node, 1);
} else
throw exception(in_, begin, std::string("template error: expected node was if or elif, got: ") + typeid(*cur_level_node).name());
}
//endif
else if (tokens[0] == TOKEN_ENDIF && tokens.size() == 1) {
int count = -1;
node_with_children<context_type, out_type>* n = cur_level_node;
while (typeid(*n) != typeid(if_node<context_type, out_type, condition_type> )) {
if (n->parent_ == NULL)
throw exception(in_, begin, std::string("not valid template"));
n = n->parent_;
count--;
}
return std::make_pair(nullptr, count);
}
//set
else if (tokens[0] == TOKEN_SET) {
return std::make_pair(create_set_node(tokens[1].begin(), tokens.back().end(), cur_level_node), 0);
} else
throw exception(in_, begin, "unknown node");
}
static void parse_template(in_type& in, templ_type& template_tree) {
parser p(in, template_tree);
p.internal_parse();
}
void internal_parse() {
const_iterator_type pos = in_.begin();
node_with_children<context_type, out_type>* cur_level_node = &tree_.root_;
while (pos != in_.end()) {
pos = create_text_node(pos, cur_level_node); //text node
if (pos == in_.end())
break;
if (*pos == OPEN_BRACKET) { //variable node
pos++;
pos = create_variable_node(pos, cur_level_node);
} else if (*pos == PERCENT) { //statement node
pos++;
const_iterator_type begin = pos;
for (; *pos != PERCENT; pos++) {
}
if (pos == in_.end())
throw exception(in_, pos, std::string("cannot find second open bracket"));
node<context_type, out_type> * st_node;
int level;
std::tie(st_node, level) = create_statement_node(begin, pos, cur_level_node);
//if (level == 0) //just add child node - stay on that level
//nothing to do. node was added to cur_level_node
if (level < 0) { //go as many levels up as necessary
while (level < 0) {
if (cur_level_node == NULL)
throw exception(in_, pos, std::string("not valid template"));
cur_level_node = cur_level_node->parent_;
level++;
}
} else if (level == 1) { //add 1 more level
if (!dynamic_cast<node_with_children<context_type, out_type>*>(st_node))
throw exception(in_, pos, std::string("node_with_children_expected, got: ") + typeid(*(st_node)).name());
cur_level_node = static_cast<node_with_children<context_type, out_type>*>(st_node);
}
pos++;
if (*pos != CLOSE_BRACKET)
throw exception(in_, pos, std::string("cannot find second open bracket"));
pos++;
} else if (*pos == DIEZ) { //comment node
pos++;
pos = create_comment_node(pos);
} else
throw exception(in_, pos, std::string("unexpected symbol"));
}
if (cur_level_node != &tree_.root_)
throw exception(in_, pos, std::string("not valid template"));
}
private:
//utilities
};
}
#endif /* PARSER_HPP_ */
| 36.392683 | 170 | 0.66765 | dimitarm |
3dd4ca477e3afdbe065a75f914787087cabd4fcd | 5,036 | hpp | C++ | engine/src/main_check.hpp | Sidharth-S-S/cloe | 974ef649e7dc6ec4e6869e4cf690c5b021e5091e | [
"Apache-2.0"
] | 20 | 2020-07-07T18:28:35.000Z | 2022-03-21T04:35:28.000Z | engine/src/main_check.hpp | Sidharth-S-S/cloe | 974ef649e7dc6ec4e6869e4cf690c5b021e5091e | [
"Apache-2.0"
] | 46 | 2021-01-20T10:13:09.000Z | 2022-03-29T12:27:19.000Z | engine/src/main_check.hpp | Sidharth-S-S/cloe | 974ef649e7dc6ec4e6869e4cf690c5b021e5091e | [
"Apache-2.0"
] | 12 | 2021-01-25T08:01:24.000Z | 2021-07-27T10:09:53.000Z | /*
* Copyright 2020 Robert Bosch GmbH
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
*/
/**
* \file main_check.hpp
* \see main.cpp
*
* This file contains the "check" options and command.
*/
#pragma once
#include <iostream> // for ostream, cout
#include <string> // for string
#include <vector> // for vector<>
#include "main_stack.hpp" // for Stack, StackOptions, new_stack
namespace engine {
struct CheckOptions {
cloe::StackOptions stack_options;
std::ostream& output = std::cout;
std::string delimiter = ",";
// Flags:
bool distinct = false;
bool summarize = false;
bool output_json = false;
int json_indent = 2;
};
/**
* Output nothing in the case that a file is valid, and an error message if
* there is a problem.
*
* This mirrors most closely the standard unix command-line philosophy.
*/
inline void check_stack(const cloe::StackOptions& opt, const std::vector<std::string>& files,
bool* ok = nullptr) {
if (ok) {
*ok = false;
}
cloe::Stack s = cloe::new_stack(opt, files);
s.check_completeness();
if (ok) {
*ok = true;
}
}
/**
* Output a summary of its state, ranging from OK to FATAL.
*
* This is useful for those who want a definitive answer for the input.
*/
inline std::string check_summary(const CheckOptions& opt, const std::vector<std::string>& files,
bool* ok = nullptr) {
cloe::StackOptions stack_opt = opt.stack_options;
stack_opt.error = boost::none;
try {
check_stack(stack_opt, files, ok);
return "OK";
} catch (cloe::StackIncompleteError& e) {
return "INCOMPLETE (" + std::string(e.what()) + ")";
} catch (cloe::ConfError& e) {
return "INVALID (" + std::string(e.what()) + ")";
} catch (std::exception& e) {
return "ERROR (" + std::string(e.what()) + ")";
}
}
/**
* Output a JSON value of its state, with null returned for ok, and an
* error object for each error.
*/
inline cloe::Json check_json(const CheckOptions& opt, const std::vector<std::string>& files,
bool* ok = nullptr) {
cloe::StackOptions stack_opt = opt.stack_options;
stack_opt.error = boost::none;
if (opt.summarize) {
return check_summary(opt, files, ok);
} else {
try {
check_stack(stack_opt, files, ok);
return nullptr;
} catch (cloe::SchemaError& e) {
return e;
} catch (cloe::ConfError& e) {
return e;
} catch (std::exception& e) {
return cloe::Json{
{"error", e.what()},
};
}
}
}
inline int check_merged(const CheckOptions& opt, const std::vector<std::string>& filepaths) {
bool ok = false;
if (opt.output_json) {
opt.output << check_json(opt, filepaths, &ok).dump(opt.json_indent) << std::endl;
} else if (opt.summarize) {
opt.output << check_summary(opt, filepaths, &ok) << std::endl;
} else {
try {
check_stack(opt.stack_options, filepaths, &ok);
} catch (cloe::ConcludedError&) {
} catch (std::exception& e) {
opt.output << e.what() << std::endl;
}
}
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
inline int check_distinct(const CheckOptions& opt, const std::vector<std::string>& filepaths) {
int exit_code = EXIT_SUCCESS;
auto check_each = [&](std::function<void(const std::string&, bool*)> func) {
for (const auto& x : filepaths) {
bool ok = true;
func(x, &ok);
if (!ok) {
exit_code = EXIT_FAILURE;
}
}
};
if (opt.output_json) {
// Output for each file a summary
cloe::Json output;
check_each([&](const auto& f, bool* ok) {
output[f] = check_json(opt, std::vector<std::string>{f}, ok);
});
opt.output << output.dump(opt.json_indent) << std::endl;
} else if (opt.summarize) {
check_each([&](const auto& f, bool* ok) {
opt.output << f << ": " << check_summary(opt, std::vector<std::string>{f}, ok) << std::endl;
});
} else {
check_each([&](const auto& f, bool* ok) {
try {
check_stack(opt.stack_options, std::vector<std::string>{f}, ok);
} catch (cloe::ConcludedError&) {
} catch (std::exception& e) {
opt.output << f << ": " << e.what() << std::endl;
}
});
}
return exit_code;
}
inline int check(const CheckOptions& opt, const std::vector<std::string>& filepaths) {
if (opt.distinct) {
return check_distinct(opt, filepaths);
} else {
return check_merged(opt, filepaths);
}
}
} // namespace engine
| 28.292135 | 98 | 0.623114 | Sidharth-S-S |
3dd4d9409d3676ff423e59449739cdc779baf087 | 2,198 | cpp | C++ | contact/contact.cpp | anantja-in/usaco | 1b680b40cfba18fa4dadf031c39dff3f0f2b7c30 | [
"MIT"
] | null | null | null | contact/contact.cpp | anantja-in/usaco | 1b680b40cfba18fa4dadf031c39dff3f0f2b7c30 | [
"MIT"
] | null | null | null | contact/contact.cpp | anantja-in/usaco | 1b680b40cfba18fa4dadf031c39dff3f0f2b7c30 | [
"MIT"
] | null | null | null | /*
ID: anant901
PROG: contact
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <utility>
#include <vector>
#include <algorithm>
using namespace std;
int compare(pair<int, string>& a, pair<int,string>& b){
return a.first > b.first;
}
int val(string a){
int res = 0;
int pow = 1;
for(int x=a.length()-1; x>=0; x--){
if(a[x]=='1') res += pow;
pow *= 2;
}
return res;
}
bool compare_strings(string &a, string &b) {
if(a.length() == b.length()) return val(a)<val(b);
else return a.length()<b.length();
}
string format(string s) {
vector <string> strings;
string temp="";
for(int x=0; x<s.length(); x++) {
if(s[x] == ' ') {
strings.push_back(temp);
temp = "";
}
else {
temp += s[x];
}
}
strings.push_back(temp);
sort(strings.begin(), strings.end(), compare_strings);
string f="";
for(int x=0; x<strings.size(); x++) {
if(x>0){
if(x%6==0){
f+='\n';
}
else {
f+=' ';
}
}
f+=strings[x];
}
return f;
}
int main() {
ofstream fout ("contact.out");
ifstream fin ("contact.in");
int A,B,N;
fin>>A>>B>>N;
string stream="", line;
while(getline(fin, line)) stream += line;
map <string,int> freq;
for(long x=A-1; x<stream.length(); x++) {
for(int y=x-B+1; y<=x-A+1; y++) {
if(y<0) continue;
// look at stream[y] to stream[x]
string temp = stream.substr(y, x-y+1);
if(freq.find(temp) != freq.end()) {
freq[temp] += 1;
}
else {
freq[temp] = 1;
}
}
}
map <int, string> reverse_freq;
for(map<string,int>::iterator it=freq.begin(); it!=freq.end(); ++it) {
if(reverse_freq.find(it->second) != reverse_freq.end()) {
reverse_freq[it->second] += " ";
reverse_freq[it->second] += it->first;
}
else {
reverse_freq[it->second] = it->first;
}
}
vector< pair<int,string> > pairs;
for(map<int,string>::iterator itr = reverse_freq.begin(); itr!=reverse_freq.end(); ++itr)
pairs.push_back(*itr);
sort(pairs.begin(), pairs.end(), compare);
if(pairs.size()<N) N=pairs.size();
for(int x=0; x<N; x++) {
fout<<pairs[x].first<<endl<<format(pairs[x].second)<<endl;
}
fout.close();
return 0;
}
| 19.113043 | 91 | 0.568699 | anantja-in |
3ddac18b8dea1f584d40151ca4efb8bad8b28d0b | 5,812 | hpp | C++ | src/gui/logind_session_lnx.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/gui/logind_session_lnx.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | src/gui/logind_session_lnx.hpp | CoSoSys/cppdevtk | 99d6c3d328c05a55dae54e82fcbedad93d0cfaa0 | [
"BSL-1.0",
"Apache-2.0"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \file
///
/// \copyright Copyright (C) 2015 - 2020 CoSoSys Ltd <[email protected]>\n
/// Licensed under the Apache License, Version 2.0 (the "License");\n
/// you may not use this file except in compliance with the License.\n
/// You may obtain a copy of the License at\n
/// http://www.apache.org/licenses/LICENSE-2.0\n
/// Unless required by applicable law or agreed to in writing, software\n
/// distributed under the License is distributed on an "AS IS" BASIS,\n
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n
/// See the License for the specific language governing permissions and\n
/// limitations under the License.\n
/// Please see the file COPYING.
///
/// \authors Cristian ANITA <[email protected]>, <[email protected]>
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef CPPDEVTK_GUI_LOGIND_SESSION_LNX_HPP_INCLUDED_
#define CPPDEVTK_GUI_LOGIND_SESSION_LNX_HPP_INCLUDED_
#include <cppdevtk/gui/config.hpp>
#if (!CPPDEVTK_PLATFORM_LINUX)
# error "This file is Linux specific!!!"
#endif
#if (CPPDEVTK_PLATFORM_ANDROID)
# error "This file is not for Android!!!"
#endif
#include "session_impl_lnx.hpp"
#include <cppdevtk/util/dbus_utils.hpp>
#include <QtCore/QStringList>
#include <QtCore/QVariant>
#include <QtCore/QVariantMap>
#include <QtDBus/QDBusObjectPath>
#include <QtDBus/QDBusInterface>
namespace cppdevtk {
namespace gui {
namespace detail {
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// \sa <a href=https://www.freedesktop.org/wiki/Software/systemd/logind">logind Session</a>
/// \note All functions, except slots and destructor, may throw DBusException
/// \attention Tested and Locked()/Unlocked() signals:
/// - are not emitted when Lock/Unlock from DE (tested with KDE); screensaver signals are emitted.
/// - are emitted when Lock()/Unlock() method are called
/// - verify: dbus-monitor --monitor --system "type='signal',sender='org.freedesktop.login1',interface='org.freedesktop.login1.Session',path='/org/freedesktop/login1/session/_32'"
class LogindSession: public Session::Impl {
friend class ::cppdevtk::gui::Session;
friend class LogindManager;
Q_OBJECT
public:
virtual ~LogindSession();
virtual bool Activate();
// On Ubuntu 14.04 fails with org.freedesktop.DBus.Error.AccessDenied
// TODO: report bug
virtual bool Lock();
virtual bool Unlock();
virtual QString GetId() const;
virtual bool GetIdleHint() const;
virtual Session::IdleTime GetIdleSinceHint() const;
virtual QString GetType() const;
virtual uint GetUser() const;
virtual QString GetRemoteHost() const;
virtual bool IsActive() const;
virtual bool IsRemote() const;
bool operator==(const LogindSession& other) const;
bool operator!=(const LogindSession& other) const;
static bool IsLogindServiceRegistered();
private Q_SLOTS:
void OnDBusPropertiesChanged(const QString& interfaceName, const QVariantMap& changedProperties,
const QStringList& invalidatedProperties);
private:
Q_DISABLE_COPY(LogindSession)
explicit LogindSession(const QDBusObjectPath& logindSessionPath);
qulonglong DoGetIdleSinceHint() const;
mutable QDBusInterface logindSessionPropertiesInterface_;
};
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Inline functions
inline QString LogindSession::GetId() const {
const QDBusInterface& kDBusInterface = DBusInterfaceRef();
return util::GetDBusStringProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()),
kDBusInterface.interface(), kDBusInterface.connection(), "Id");
}
inline QString LogindSession::GetType() const {
const QDBusInterface& kDBusInterface = DBusInterfaceRef();
return util::GetDBusStringProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()),
kDBusInterface.interface(), kDBusInterface.connection(), "Type");
}
inline uint LogindSession::GetUser() const {
const QDBusInterface& kDBusInterface = DBusInterfaceRef();
return util::GetDBusUInt32Property(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()),
kDBusInterface.interface(), kDBusInterface.connection(), "User");
}
inline QString LogindSession::GetRemoteHost() const {
const QDBusInterface& kDBusInterface = DBusInterfaceRef();
return util::GetDBusStringProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()),
kDBusInterface.interface(), kDBusInterface.connection(), "RemoteHost");
}
inline bool LogindSession::IsActive() const {
const QDBusInterface& kDBusInterface = DBusInterfaceRef();
return util::GetDBusBooleanProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()),
kDBusInterface.interface(), kDBusInterface.connection(), "Active");
}
inline bool LogindSession::IsRemote() const {
const QDBusInterface& kDBusInterface = DBusInterfaceRef();
return util::GetDBusBooleanProperty(kDBusInterface.service(), QDBusObjectPath(kDBusInterface.path()),
kDBusInterface.interface(), kDBusInterface.connection(), "Remote");
}
inline bool LogindSession::operator==(const LogindSession& other) const {
return GetId() == other.GetId();
}
inline bool LogindSession::operator!=(const LogindSession& other) const {
return GetId() != other.GetId();
}
} // namespace detail
} // namespace gui
} // namespace cppdevtk
#endif // CPPDEVTK_GUI_LOGIND_SESSION_LNX_HPP_INCLUDED_
| 37.986928 | 180 | 0.682725 | CoSoSys |
3ddbaa2d7749a946d533e6e07fa4456bdf001396 | 234 | cpp | C++ | Engine/Source/Color.cpp | Denisdrk6/ProjectIII | 89634bcf4a3520ba78158dff50aee568089968cb | [
"MIT"
] | 7 | 2022-02-16T12:09:19.000Z | 2022-03-14T15:59:48.000Z | Engine/Source/Color.cpp | Denisdrk6/Dune-Fremen-s-Rising | 89634bcf4a3520ba78158dff50aee568089968cb | [
"MIT"
] | 1 | 2022-03-18T19:46:23.000Z | 2022-03-18T19:46:23.000Z | Engine/Source/Color.cpp | Denisdrk6/Dune-Fremen-s-Rising | 89634bcf4a3520ba78158dff50aee568089968cb | [
"MIT"
] | 1 | 2022-02-20T19:49:09.000Z | 2022-02-20T19:49:09.000Z | #include "Color.h"
#include "Profiling.h"
Color red = Color(1.0f, 0.0f, 0.0f);
Color green = Color(0.0f, 1.0f, 0.0f);
Color blue = Color(0.0f, 0.0f, 1.0f);
Color black = Color(0.0f, 0.0f, 0.0f);
Color white = Color(1.0f, 1.0f, 1.0f); | 29.25 | 38 | 0.628205 | Denisdrk6 |
3de170da2c63cee6ebe2b839d9a4196efaa7e167 | 1,336 | hpp | C++ | include/blokus/ai/logic.hpp | sunfl0w/CPP_HokusBlokus | aedb8d42143cce9fe2b7107ce4f6d15ef76dc58c | [
"MIT"
] | 1 | 2020-09-04T16:35:38.000Z | 2020-09-04T16:35:38.000Z | include/blokus/ai/logic.hpp | sunfl0w/CPP_HokusBlokus | aedb8d42143cce9fe2b7107ce4f6d15ef76dc58c | [
"MIT"
] | null | null | null | include/blokus/ai/logic.hpp | sunfl0w/CPP_HokusBlokus | aedb8d42143cce9fe2b7107ce4f6d15ef76dc58c | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <random>
#include <iostream>
#include "gameState.hpp"
#include "move.hpp"
#include "player.hpp"
#include "color.hpp"
#include "logger.hpp"
namespace HokusBlokus::Blokus::AI {
/**
* @brief This class defines some virtual methods for creating AIs for the game of Blokus.
* One can inherit from this class to create a new logic.
*
*/
class Logic {
public:
/**
* @brief Constructs a new Logic.
*
*/
Logic();
/**
* @brief Destroys a Logic.
*
*/
virtual ~Logic();
/**
* @brief Gets the next Move to play. In this method the AI hast to be implemented.
*
* @param currentGameState The GameState to get the next Move for.
* @param ownPlayerID The ID of the Player that is played by the AI.
* @return The next move that should be played.
*/
virtual HokusBlokus::Blokus::Move GetNextMove(HokusBlokus::Blokus::GameState currentGameState, int ownPlayerID);
/**
* @brief Will be executed when a game of Blokus ends.
*
* @param winningPlayerID The ID of the Player that won.
*/
virtual void OnGameEnd(int winningPlayerID);
};
} // namespace Piranhas::Logic | 27.265306 | 120 | 0.589072 | sunfl0w |
3de67ac7a4b63b7c9d67d2d2ac6d85223f0a8b12 | 53,170 | cpp | C++ | src/core/blocks/chains.cpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 12 | 2021-07-11T11:14:14.000Z | 2022-03-28T11:37:29.000Z | src/core/blocks/chains.cpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 103 | 2021-06-26T17:09:43.000Z | 2022-03-30T12:05:18.000Z | src/core/blocks/chains.cpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 8 | 2021-07-27T14:45:26.000Z | 2022-03-01T08:07:18.000Z | /* SPDX-License-Identifier: BSD-3-Clause */
/* Copyright © 2019 Fragcolor Pte. Ltd. */
#include "foundation.hpp"
#include "shared.hpp"
#include <chrono>
#include <memory>
#include <set>
#if !defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__)
#include <taskflow/taskflow.hpp>
#endif
namespace chainblocks {
enum RunChainMode { Inline, Detached, Stepped };
struct ChainBase {
typedef EnumInfo<RunChainMode> RunChainModeInfo;
static inline RunChainModeInfo runChainModeInfo{"RunChainMode", CoreCC,
'runC'};
static inline Type ModeType{
{CBType::Enum, {.enumeration = {.vendorId = CoreCC, .typeId = 'runC'}}}};
static inline Types ChainTypes{
{CoreInfo::ChainType, CoreInfo::StringType, CoreInfo::NoneType}};
static inline Types ChainVarTypes{ChainTypes, {CoreInfo::ChainVarType}};
static inline Parameters waitParamsInfo{
{"Chain", CBCCSTR("The chain to wait."), {ChainVarTypes}},
{"Passthrough",
CBCCSTR("The output of this block will be its input."),
{CoreInfo::BoolType}}};
static inline Parameters stopChainParamsInfo{
{"Chain", CBCCSTR("The chain to stop."), {ChainVarTypes}},
{"Passthrough",
CBCCSTR("The output of this block will be its input."),
{CoreInfo::BoolType}}};
static inline Parameters runChainParamsInfo{
{"Chain", CBCCSTR("The chain to run."), {ChainTypes}}};
ParamVar chainref{};
std::shared_ptr<CBChain> chain;
bool passthrough{false};
RunChainMode mode{RunChainMode::Inline};
CBComposeResult chainValidation{};
IterableExposedInfo exposedInfo{};
void destroy() {
chainblocks::arrayFree(chainValidation.requiredInfo);
chainblocks::arrayFree(chainValidation.exposedInfo);
}
static CBTypesInfo inputTypes() { return CoreInfo::AnyType; }
static CBTypesInfo outputTypes() { return CoreInfo::AnyType; }
std::unordered_set<const CBChain *> &gatheringChains() {
#ifdef WIN32
// we have to leak.. or windows tls emulation will crash at process end
thread_local std::unordered_set<const CBChain *> *chains =
new std::unordered_set<const CBChain *>();
return *chains;
#else
thread_local std::unordered_set<const CBChain *> chains;
return chains;
#endif
}
CBTypeInfo compose(const CBInstanceData &data) {
// Free any previous result!
arrayFree(chainValidation.requiredInfo);
arrayFree(chainValidation.exposedInfo);
// Actualize the chain here, if we are deserialized
// chain might already be populated!
if (!chain) {
if (chainref->valueType == CBType::Chain) {
chain = CBChain::sharedFromRef(chainref->payload.chainValue);
} else if (chainref->valueType == String) {
chain = GetGlobals().GlobalChains[chainref->payload.stringValue];
} else {
chain = nullptr;
CBLOG_DEBUG("ChainBase::compose on a null chain");
}
}
// Easy case, no chain...
if (!chain)
return data.inputType;
assert(data.chain);
if (chain.get() == data.chain) {
CBLOG_DEBUG(
"ChainBase::compose early return, data.chain == chain, name: {}",
chain->name);
return data.inputType; // we don't know yet...
}
chain->node = data.chain->node;
auto node = data.chain->node.lock();
assert(node);
// TODO FIXME, chainloader/chain runner might access this from threads
if (node->visitedChains.count(chain.get())) {
// TODO FIXME, we need to verify input and shared here...
// but visited does not mean composed...
return node->visitedChains[chain.get()];
}
// avoid stackoverflow
if (chain->isRoot || gatheringChains().count(chain.get())) {
CBLOG_DEBUG(
"ChainBase::compose early return, chain is being visited, name: {}",
chain->name);
return data.inputType; // we don't know yet...
}
CBLOG_TRACE("ChainBase::compose, source: {} composing: {} inputType: {}",
data.chain->name, chain->name, data.inputType);
// we can add early in this case!
// useful for Resume/Start
if (passthrough) {
auto [_, done] = node->visitedChains.emplace(chain.get(), data.inputType);
if (done) {
CBLOG_TRACE("Pre-Marking as composed: {} ptr: {}", chain->name,
(void *)chain.get());
}
} else if (mode == Stepped) {
auto [_, done] =
node->visitedChains.emplace(chain.get(), CoreInfo::AnyType);
if (done) {
CBLOG_TRACE("Pre-Marking as composed: {} ptr: {}", chain->name,
(void *)chain.get());
}
}
// and the subject here
gatheringChains().insert(chain.get());
DEFER(gatheringChains().erase(chain.get()));
auto dataCopy = data;
dataCopy.chain = chain.get();
IterableExposedInfo shared(data.shared);
IterableExposedInfo sharedCopy;
if (mode == RunChainMode::Detached) {
// keep only globals
auto end =
std::remove_if(shared.begin(), shared.end(),
[](const CBExposedTypeInfo &x) { return !x.global; });
sharedCopy = IterableExposedInfo(shared.begin(), end);
} else {
// we allow Detached but they need to be referenced during warmup
sharedCopy = shared;
}
dataCopy.shared = sharedCopy;
CBTypeInfo chainOutput;
// make sure to compose only once...
if (chain->composedHash.valueType == None) {
CBLOG_TRACE("Running {} compose", chain->name);
chainValidation = composeChain(
chain.get(),
[](const CBlock *errorBlock, const char *errorTxt,
bool nonfatalWarning, void *userData) {
if (!nonfatalWarning) {
CBLOG_ERROR("RunChain: failed inner chain validation, error: {}",
errorTxt);
throw ComposeError("RunChain: failed inner chain validation");
} else {
CBLOG_INFO("RunChain: warning during inner chain validation: {}",
errorTxt);
}
},
this, dataCopy);
chain->composedHash = Var(1, 1); // no need to hash properly here
chainOutput = chainValidation.outputType;
IterableExposedInfo exposing(chainValidation.exposedInfo);
// keep only globals
exposedInfo = IterableExposedInfo(
exposing.begin(),
std::remove_if(exposing.begin(), exposing.end(),
[](CBExposedTypeInfo &x) { return !x.global; }));
CBLOG_TRACE("Chain {} composed", chain->name);
} else {
CBLOG_TRACE("Skipping {} compose", chain->name);
// verify input type
if (!passthrough && mode != Stepped &&
data.inputType != chain->inputType) {
CBLOG_ERROR("Previous chain composed type {} requested call type {}",
*chain->inputType, data.inputType);
throw ComposeError("Attempted to call an already composed chain with a "
"different input type! chain: " +
chain->name);
}
// write output type
chainOutput = chain->outputType;
// ensure requirements match our input data
for (auto req : chain->requiredVariables) {
// find each in shared
auto res = std::find_if(shared.begin(), shared.end(),
[&](CBExposedTypeInfo &x) {
std::string_view vx(x.name);
return req == vx;
});
if (res == shared.end()) {
throw ComposeError("Attempted to call an already composed chain (" +
chain->name +
") with "
"a missing required variable: " +
req);
}
}
}
auto outputType = data.inputType;
if (!passthrough) {
if (mode == Inline)
outputType = chainOutput;
else if (mode == Stepped)
outputType = CoreInfo::AnyType; // unpredictable
else
outputType = data.inputType;
}
if (!passthrough && mode != Stepped) {
auto [_, done] = node->visitedChains.emplace(chain.get(), outputType);
if (done) {
CBLOG_TRACE(
"Marking as composed: {} ptr: {} inputType: {} outputType: {}",
chain->name, (void *)chain.get(), *chain->inputType,
chain->outputType);
}
}
return outputType;
}
void cleanup() { chainref.cleanup(); }
void warmup(CBContext *ctx) { chainref.warmup(ctx); }
// Use state to mark the dependency for serialization as well!
CBVar getState() {
if (chain) {
return Var(chain);
} else {
CBLOG_TRACE("getState no chain was avail");
return Var::Empty;
}
}
void setState(CBVar state) {
if (state.valueType == CBType::Chain) {
chain = CBChain::sharedFromRef(state.payload.chainValue);
}
}
};
struct Wait : public ChainBase {
CBOptionalString help() {
return CBCCSTR("Waits for another chain to complete before resuming "
"execution of the current chain.");
}
// we don't need OwnedVar here
// we keep the chain referenced!
CBVar _output{};
CBExposedTypeInfo _requiredChain{};
void cleanup() {
if (chainref.isVariable())
chain = nullptr;
ChainBase::cleanup();
}
static CBParametersInfo parameters() { return waitParamsInfo; }
void setParam(int index, const CBVar &value) {
switch (index) {
case 0:
chainref = value;
break;
case 1:
passthrough = value.payload.boolValue;
break;
default:
break;
}
}
CBVar getParam(int index) {
switch (index) {
case 0:
return chainref;
case 1:
return Var(passthrough);
default:
return Var::Empty;
}
}
CBExposedTypesInfo requiredVariables() {
if (chainref.isVariable()) {
_requiredChain =
CBExposedTypeInfo{chainref.variableName(),
CBCCSTR("The chain to run."), CoreInfo::ChainType};
return {&_requiredChain, 1, 0};
} else {
return {};
}
}
CBVar activate(CBContext *context, const CBVar &input) {
if (unlikely(!chain && chainref.isVariable())) {
auto vchain = chainref.get();
if (vchain.valueType == CBType::Chain) {
chain = CBChain::sharedFromRef(vchain.payload.chainValue);
} else if (vchain.valueType == String) {
chain = GetGlobals().GlobalChains[vchain.payload.stringValue];
} else {
chain = nullptr;
}
}
if (unlikely(!chain)) {
CBLOG_WARNING("Wait's chain is void");
return input;
} else {
while (isRunning(chain.get())) {
CB_SUSPEND(context, 0);
}
if (chain->finishedError.size() > 0) {
// if the chain has errors we need to propagate them
// we can avoid interruption using Maybe blocks
throw ActivationError(chain->finishedError);
}
if (passthrough) {
return input;
} else {
// no clone
_output = chain->finishedOutput;
return _output;
}
}
}
};
struct StopChain : public ChainBase {
CBOptionalString help() {
return CBCCSTR(
"Stops another chain. If no chain is given, stops the current chain.");
}
void setup() { passthrough = true; }
OwnedVar _output{};
CBExposedTypeInfo _requiredChain{};
CBTypeInfo _inputType{};
CBTypeInfo compose(const CBInstanceData &data) {
_inputType = data.inputType;
ChainBase::compose(data);
return data.inputType;
}
void composed(const CBChain *chain, const CBComposeResult *result) {
if (!chain && chainref->valueType == None &&
_inputType != result->outputType) {
CBLOG_ERROR("Stop input and chain output type mismatch, Stop input must "
"be the same type of the chain's output (regular flow), "
"chain: {} expected: {}",
chain->name, chain->outputType);
throw ComposeError("Stop input and chain output type mismatch");
}
}
void cleanup() {
if (chainref.isVariable())
chain = nullptr;
ChainBase::cleanup();
}
static CBParametersInfo parameters() { return stopChainParamsInfo; }
void setParam(int index, const CBVar &value) {
switch (index) {
case 0:
chainref = value;
break;
case 1:
passthrough = value.payload.boolValue;
break;
default:
break;
}
}
CBVar getParam(int index) {
switch (index) {
case 0:
return chainref;
case 1:
return Var(passthrough);
default:
return Var::Empty;
}
}
CBExposedTypesInfo requiredVariables() {
if (chainref.isVariable()) {
_requiredChain =
CBExposedTypeInfo{chainref.variableName(),
CBCCSTR("The chain to run."), CoreInfo::ChainType};
return {&_requiredChain, 1, 0};
} else {
return {};
}
}
CBVar activate(CBContext *context, const CBVar &input) {
if (unlikely(!chain && chainref.isVariable())) {
auto vchain = chainref.get();
if (vchain.valueType == CBType::Chain) {
chain = CBChain::sharedFromRef(vchain.payload.chainValue);
} else if (vchain.valueType == String) {
chain = GetGlobals().GlobalChains[vchain.payload.stringValue];
} else {
chain = nullptr;
}
}
if (unlikely(!chain)) {
// in this case we stop the current chain
context->stopFlow(input);
return input;
} else {
chainblocks::stop(chain.get());
if (passthrough) {
return input;
} else {
_output = chain->finishedOutput;
return _output;
}
}
}
};
struct Resume : public ChainBase {
static CBOptionalString help() {
return CBCCSTR("Resumes a given chain and suspends the current one. In "
"other words, switches flow execution to another chain.");
}
void setup() {
// we use those during ChainBase::compose
passthrough = true;
mode = Detached;
}
static inline Parameters params{
{"Chain", CBCCSTR("The name of the chain to switch to."), {ChainTypes}}};
static CBParametersInfo parameters() { return params; }
static CBTypesInfo inputTypes() { return CoreInfo::AnyType; }
static CBTypesInfo outputTypes() { return CoreInfo::AnyType; }
CBTypeInfo compose(const CBInstanceData &data) {
ChainBase::compose(data);
return data.inputType;
}
void setParam(int index, const CBVar &value) { chainref = value; }
CBVar getParam(int index) { return chainref; }
// NO cleanup, other chains reference this chain but should not stop it
// An arbitrary chain should be able to resume it!
// Cleanup mechanics still to figure, for now ref count of the actual chain
// symbol, TODO maybe use CBVar refcount!
CBVar activate(CBContext *context, const CBVar &input) {
auto current = context->chainStack.back();
auto pchain = [&] {
if (!chain) {
if (current->resumer) {
return current->resumer;
} else {
throw ActivationError("Resume, chain not found.");
}
} else {
return chain.get();
}
}();
// assign the new chain as current chain on the flow
context->flow->chain = pchain;
// Allow to re run chains
if (chainblocks::hasEnded(pchain)) {
chainblocks::stop(pchain);
}
// Prepare if no callc was called
if (!pchain->coro) {
pchain->node = context->main->node;
chainblocks::prepare(pchain, context->flow);
}
// we should be valid as this block should be dependent on current
// do this here as stop/prepare might overwrite
pchain->resumer = current;
// Start it if not started
if (!chainblocks::isRunning(pchain)) {
chainblocks::start(pchain, input);
}
// And normally we just delegate the CBNode + CBFlow
// the following will suspend this current chain
// and in node tick when re-evaluated tick will
// resume with the chain we just set above!
chainblocks::suspend(context, 0);
return input;
}
};
struct Start : public Resume {
static CBOptionalString help() {
return CBCCSTR("Starts a given chain and suspends the current one. In "
"other words, switches flow execution to another chain.");
}
CBVar activate(CBContext *context, const CBVar &input) {
auto current = context->chainStack.back();
auto pchain = [&] {
if (!chain) {
if (current->resumer) {
return current->resumer;
} else {
throw ActivationError("Resume, chain not found.");
}
} else {
return chain.get();
}
}();
// assign the new chain as current chain on the flow
context->flow->chain = pchain;
// ensure chain is not running, we start from top
chainblocks::stop(pchain);
// Prepare
pchain->node = context->main->node;
chainblocks::prepare(pchain, context->flow);
// we should be valid as this block should be dependent on current
// do this here as stop/prepare might overwrite
pchain->resumer = current;
// Start
chainblocks::start(pchain, input);
// And normally we just delegate the CBNode + CBFlow
// the following will suspend this current chain
// and in node tick when re-evaluated tick will
// resume with the chain we just set above!
chainblocks::suspend(context, 0);
return input;
}
};
struct Recur : public ChainBase {
static CBTypesInfo inputTypes() { return CoreInfo::AnyType; }
static CBTypesInfo outputTypes() { return CoreInfo::AnyType; }
CBTypeInfo compose(const CBInstanceData &data) {
// set current chain as `chain`
_wchain = data.chain->shared_from_this();
// find all variables to store in current chain
// use vector in the end.. cos slightly faster
for (auto &shared : data.shared) {
if (shared.scope == data.chain) {
CBVar ctxVar{};
ctxVar.valueType = ContextVar;
ctxVar.payload.stringValue = shared.name;
auto &p = _vars.emplace_back();
p = ctxVar;
}
}
_len = _vars.size();
return ChainBase::compose(data);
}
void warmup(CBContext *ctx) {
_storage.resize(_len);
for (auto &v : _vars) {
v.warmup(ctx);
}
auto schain = _wchain.lock();
assert(schain);
_chain = schain.get();
}
void cleanup() {
for (auto &v : _vars) {
v.cleanup();
}
// force releasing resources
for (size_t i = 0; i < _len; i++) {
// must release on capacity
for (uint32_t j = 0; j < _storage[i].cap; j++) {
destroyVar(_storage[i].elements[j]);
}
arrayFree(_storage[i]);
}
_storage.resize(0);
}
CBVar activate(CBContext *context, const CBVar &input) {
// store _vars
for (size_t i = 0; i < _len; i++) {
const auto len = _storage[i].len;
arrayResize(_storage[i], len + 1);
cloneVar(_storage[i].elements[len], _vars[i].get());
}
// (Do self)
// Run within the root flow
auto runRes = runSubChain(_chain, context, input);
if (unlikely(runRes.state == Failed)) {
// meaning there was an exception while
// running the sub chain, stop the parent too
context->stopFlow(runRes.output);
}
// restore _vars
for (size_t i = 0; i < _len; i++) {
auto pops = arrayPop<CBSeq, CBVar>(_storage[i]);
cloneVar(_vars[i].get(), pops);
}
return runRes.output;
}
std::weak_ptr<CBChain> _wchain;
CBChain *_chain;
std::deque<ParamVar> _vars;
size_t _len; // cache it to have nothing on stack from us
std::vector<CBSeq> _storage;
};
struct BaseRunner : public ChainBase {
// Only chain runners should expose varaibles to the context
CBExposedTypesInfo exposedVariables() {
// Only inline mode ensures that variables will be really avail
// step and detach will run at different timing
CBExposedTypesInfo empty{};
return mode == RunChainMode::Inline ? CBExposedTypesInfo(exposedInfo)
: empty;
}
void cleanup() {
if (chain) {
if (mode == RunChainMode::Inline && chain->chainUsers.count(this) != 0) {
chain->chainUsers.erase(this);
chain->cleanup();
} else {
chainblocks::stop(chain.get());
}
}
ChainBase::cleanup();
}
void doWarmup(CBContext *context) {
if (mode == RunChainMode::Inline && chain &&
chain->chainUsers.count(this) == 0) {
chain->chainUsers.emplace(this);
chain->warmup(context);
}
}
void activateDetached(CBContext *context, const CBVar &input) {
if (!chainblocks::isRunning(chain.get())) {
// validated during infer not here! (false)
auto node = context->main->node.lock();
if (node)
node->schedule(chain, input, false);
}
}
void activateStepMode(CBContext *context, const CBVar &input) {
// Allow to re run chains
if (chainblocks::hasEnded(chain.get())) {
// stop the root
if (!chainblocks::stop(chain.get())) {
throw ActivationError("Stepped sub-chain did not end normally.");
}
}
// Prepare if no callc was called
if (!chain->coro) {
chain->node = context->main->node;
// pre-set chain context with our context
// this is used to copy chainStack over to the new one
chain->context = context;
// Notice we don't share our flow!
// let the chain create one by passing null
chainblocks::prepare(chain.get(), nullptr);
}
// Starting
if (!chainblocks::isRunning(chain.get())) {
chainblocks::start(chain.get(), input);
}
// Tick the chain on the flow that this Step chain created
CBDuration now = CBClock::now().time_since_epoch();
chainblocks::tick(chain->context->flow->chain, now, input);
}
};
template <bool INPUT_PASSTHROUGH, RunChainMode CHAIN_MODE>
struct RunChain : public BaseRunner {
void setup() {
passthrough = INPUT_PASSTHROUGH;
mode = CHAIN_MODE;
}
static CBParametersInfo parameters() { return runChainParamsInfo; }
void setParam(int index, const CBVar &value) {
switch (index) {
case 0:
chainref = value;
break;
default:
break;
}
}
CBVar getParam(int index) {
switch (index) {
case 0:
return chainref;
default:
break;
}
return Var::Empty;
}
void warmup(CBContext *context) {
ChainBase::warmup(context);
doWarmup(context);
}
CBVar activate(CBContext *context, const CBVar &input) {
if (unlikely(!chain))
return input;
if constexpr (CHAIN_MODE == RunChainMode::Detached) {
activateDetached(context, input);
return input;
} else if constexpr (CHAIN_MODE == RunChainMode::Stepped) {
activateStepMode(context, input);
if constexpr (INPUT_PASSTHROUGH) {
return input;
} else {
return chain->previousOutput;
}
} else {
// Run within the root flow
auto runRes = runSubChain(chain.get(), context, input);
if (unlikely(runRes.state == Failed)) {
// meaning there was an exception while
// running the sub chain, stop the parent too
context->stopFlow(runRes.output);
return runRes.output;
} else {
if constexpr (INPUT_PASSTHROUGH) {
return input;
} else {
return runRes.output;
}
}
}
}
};
struct ChainNotFound : public ActivationError {
ChainNotFound() : ActivationError("Could not find a chain to run") {}
};
template <class T> struct BaseLoader : public BaseRunner {
CBTypeInfo _inputTypeCopy{};
IterableExposedInfo _sharedCopy;
CBTypeInfo compose(const CBInstanceData &data) {
_inputTypeCopy = data.inputType;
const IterableExposedInfo sharedStb(data.shared);
// copy shared
_sharedCopy = sharedStb;
if (mode == RunChainMode::Inline || mode == RunChainMode::Stepped) {
// If inline allow chains to receive a result
return CoreInfo::AnyType;
} else {
return data.inputType;
}
}
void setParam(int index, const CBVar &value) {
switch (index) {
case 1:
mode = RunChainMode(value.payload.enumValue);
break;
default:
break;
}
}
CBVar getParam(int index) {
switch (index) {
case 1:
return Var::Enum(mode, CoreCC, 'runC');
default:
break;
}
return Var::Empty;
}
void cleanup() { BaseRunner::cleanup(); }
CBVar activateChain(CBContext *context, const CBVar &input) {
if (unlikely(!chain))
throw ChainNotFound();
if (mode == RunChainMode::Detached) {
activateDetached(context, input);
} else if (mode == RunChainMode::Stepped) {
activateStepMode(context, input);
return chain->previousOutput;
} else {
// Run within the root flow
const auto runRes = runSubChain(chain.get(), context, input);
if (likely(runRes.state != Failed)) {
return runRes.output;
}
}
return input;
}
};
struct ChainLoader : public BaseLoader<ChainLoader> {
BlocksVar _onReloadBlocks{};
BlocksVar _onErrorBlocks{};
static inline Parameters params{
{"Provider",
CBCCSTR("The chainblocks chain provider."),
{ChainProvider::ProviderOrNone}},
{"Mode",
CBCCSTR("The way to run the chain. Inline: will run the sub chain "
"inline within the root chain, a pause in the child chain will "
"pause the root too; Detached: will run the chain separately in "
"the same node, a pause in this chain will not pause the root; "
"Stepped: the chain will run as a child, the root will tick the "
"chain every activation of this block and so a child pause "
"won't pause the root."),
{ModeType}},
{"OnReload",
CBCCSTR("Blocks to execute when the chain is reloaded, the input of "
"this flow will be the reloaded chain."),
{CoreInfo::BlocksOrNone}},
{"OnError",
CBCCSTR("Blocks to execute when a chain reload failed, the input of "
"this flow will be the error message."),
{CoreInfo::BlocksOrNone}}};
static CBParametersInfo parameters() { return params; }
CBChainProvider *_provider;
void setParam(int index, const CBVar &value) {
switch (index) {
case 0: {
cleanup(); // stop current
if (value.valueType == Object) {
_provider = (CBChainProvider *)value.payload.objectValue;
} else {
_provider = nullptr;
}
} break;
case 1: {
BaseLoader<ChainLoader>::setParam(index, value);
} break;
case 2: {
_onReloadBlocks = value;
} break;
case 3: {
_onErrorBlocks = value;
} break;
default:
break;
}
}
CBVar getParam(int index) {
switch (index) {
case 0:
if (_provider) {
return Var::Object(_provider, CoreCC, 'chnp');
} else {
return Var();
}
case 1:
return BaseLoader<ChainLoader>::getParam(index);
case 2:
return _onReloadBlocks;
case 3:
return _onErrorBlocks;
default: {
return Var::Empty;
}
}
}
CBTypeInfo compose(const CBInstanceData &data) {
CBInstanceData data2 = data;
data2.inputType = CoreInfo::ChainType;
_onReloadBlocks.compose(data2);
_onErrorBlocks.compose(data);
return BaseLoader<ChainLoader>::compose(data);
}
void cleanup() {
BaseLoader<ChainLoader>::cleanup();
_onReloadBlocks.cleanup();
_onErrorBlocks.cleanup();
if (_provider)
_provider->reset(_provider);
}
void warmup(CBContext *context) {
BaseLoader<ChainLoader>::warmup(context);
_onReloadBlocks.warmup(context);
_onErrorBlocks.warmup(context);
}
CBVar activate(CBContext *context, const CBVar &input) {
if (unlikely(!_provider))
return input;
if (unlikely(!_provider->ready(_provider))) {
CBInstanceData data{};
data.inputType = _inputTypeCopy;
data.shared = _sharedCopy;
data.chain = context->chainStack.back();
assert(data.chain->node.lock());
_provider->setup(_provider, GetGlobals().RootPath.c_str(), data);
}
if (unlikely(_provider->updated(_provider))) {
auto update = _provider->acquire(_provider);
if (unlikely(update.error != nullptr)) {
CBLOG_ERROR("Failed to reload a chain via ChainLoader, reason: {}",
update.error);
CBVar output{};
_onErrorBlocks.activate(context, Var(update.error), output);
} else {
if (chain) {
// stop and release previous version
chainblocks::stop(chain.get());
}
// but let the provider release the pointer!
chain.reset(update.chain,
[&](CBChain *x) { _provider->release(_provider, x); });
doWarmup(context);
CBLOG_INFO("Chain {} has been reloaded", update.chain->name);
CBVar output{};
_onReloadBlocks.activate(context, Var(chain), output);
}
}
try {
return BaseLoader<ChainLoader>::activateChain(context, input);
} catch (const ChainNotFound &ex) {
// let's ignore chain not found in this case
return input;
}
}
};
struct ChainRunner : public BaseLoader<ChainRunner> {
static inline Parameters params{
{"Chain",
CBCCSTR("The chain variable to compose and run."),
{CoreInfo::ChainVarType}},
{"Mode",
CBCCSTR("The way to run the chain. Inline: will run the sub chain "
"inline within the root chain, a pause in the child chain will "
"pause the root too; Detached: will run the chain separately in "
"the same node, a pause in this chain will not pause the root; "
"Stepped: the chain will run as a child, the root will tick the "
"chain every activation of this block and so a child pause "
"won't pause the root."),
{ModeType}}};
static CBParametersInfo parameters() { return params; }
ParamVar _chain{};
CBVar _chainHash{};
CBChain *_chainPtr = nullptr;
CBExposedTypeInfo _requiredChain{};
void setParam(int index, const CBVar &value) {
if (index == 0) {
_chain = value;
} else {
BaseLoader<ChainRunner>::setParam(index, value);
}
}
CBVar getParam(int index) {
if (index == 0) {
return _chain;
} else {
return BaseLoader<ChainRunner>::getParam(index);
}
}
void cleanup() {
BaseLoader<ChainRunner>::cleanup();
_chain.cleanup();
_chainPtr = nullptr;
}
void warmup(CBContext *context) {
BaseLoader<ChainRunner>::warmup(context);
_chain.warmup(context);
}
CBExposedTypesInfo requiredVariables() {
if (_chain.isVariable()) {
_requiredChain =
CBExposedTypeInfo{_chain.variableName(), CBCCSTR("The chain to run."),
CoreInfo::ChainType};
return {&_requiredChain, 1, 0};
} else {
return {};
}
}
void doCompose(CBContext *context) {
CBInstanceData data{};
data.inputType = _inputTypeCopy;
data.shared = _sharedCopy;
data.chain = context->chainStack.back();
chain->node = context->main->node;
// avoid stackoverflow
if (gatheringChains().count(chain.get()))
return; // we don't know yet...
gatheringChains().insert(chain.get());
DEFER(gatheringChains().erase(chain.get()));
// We need to validate the sub chain to figure it out!
auto res = composeChain(
chain.get(),
[](const CBlock *errorBlock, const char *errorTxt, bool nonfatalWarning,
void *userData) {
if (!nonfatalWarning) {
CBLOG_ERROR("RunChain: failed inner chain validation, error: {}",
errorTxt);
throw CBException("RunChain: failed inner chain validation");
} else {
CBLOG_INFO("RunChain: warning during inner chain validation: {}",
errorTxt);
}
},
this, data);
chainblocks::arrayFree(res.exposedInfo);
chainblocks::arrayFree(res.requiredInfo);
}
CBVar activate(CBContext *context, const CBVar &input) {
auto chainVar = _chain.get();
chain = CBChain::sharedFromRef(chainVar.payload.chainValue);
if (unlikely(!chain))
return input;
if (_chainHash.valueType == None || _chainHash != chain->composedHash ||
_chainPtr != chain.get()) {
// Compose and hash in a thread
await(
context,
[this, context, chainVar]() {
doCompose(context);
chain->composedHash = chainblocks::hash(chainVar);
},
[] {});
_chainHash = chain->composedHash;
_chainPtr = chain.get();
doWarmup(context);
}
return BaseLoader<ChainRunner>::activateChain(context, input);
}
};
enum class WaitUntil {
FirstSuccess, // will wait until the first success and stop any other
// pending operation
AllSuccess, // will wait until all complete, will stop and fail on any
// failure
SomeSuccess // will wait until all complete but won't fail if some of the
// chains failed
};
struct ManyChain : public std::enable_shared_from_this<ManyChain> {
uint32_t index;
std::shared_ptr<CBChain> chain;
std::shared_ptr<CBNode> node; // used only if MT
bool done;
};
struct ParallelBase : public ChainBase {
typedef EnumInfo<WaitUntil> WaitUntilInfo;
static inline WaitUntilInfo waitUntilInfo{"WaitUntil", CoreCC, 'tryM'};
static inline Type WaitUntilType{
{CBType::Enum, {.enumeration = {.vendorId = CoreCC, .typeId = 'tryM'}}}};
static inline Parameters _params{
{"Chain",
CBCCSTR("The chain to spawn and try to run many times concurrently."),
ChainBase::ChainVarTypes},
{"Policy",
CBCCSTR("The execution policy in terms of chains success."),
{WaitUntilType}},
{"Threads",
CBCCSTR("The number of cpu threads to use."),
{CoreInfo::IntType}},
{"Coroutines",
CBCCSTR("The number of coroutines to run on each thread."),
{CoreInfo::IntType}}};
static CBParametersInfo parameters() { return _params; }
void setParam(int index, const CBVar &value) {
switch (index) {
case 0:
chainref = value;
break;
case 1:
_policy = WaitUntil(value.payload.enumValue);
break;
case 2:
_threads = std::max(int64_t(1), value.payload.intValue);
break;
case 3:
_coros = std::max(int64_t(1), value.payload.intValue);
break;
default:
break;
}
}
CBVar getParam(int index) {
switch (index) {
case 0:
return chainref;
case 1:
return Var::Enum(_policy, CoreCC, 'tryM');
case 2:
return Var(_threads);
case 3:
return Var(_coros);
default:
return Var::Empty;
}
}
CBTypeInfo compose(const CBInstanceData &data) {
if (_threads > 1) {
mode = RunChainMode::Detached;
} else {
mode = RunChainMode::Inline;
}
ChainBase::compose(data); // discard the result, we do our thing here
_pool.reset(new ChainDoppelgangerPool<ManyChain>(CBChain::weakRef(chain)));
const IterableExposedInfo shared(data.shared);
// copy shared
_sharedCopy = shared;
return CoreInfo::NoneType; // not complete
}
struct Composer {
ParallelBase &server;
CBContext *context;
void compose(CBChain *chain) {
CBInstanceData data{};
data.inputType = server._inputType;
data.shared = server._sharedCopy;
data.chain = context->chainStack.back();
chain->node = context->main->node;
auto res = composeChain(
chain,
[](const struct CBlock *errorBlock, const char *errorTxt,
CBBool nonfatalWarning, void *userData) {
if (!nonfatalWarning) {
CBLOG_ERROR(errorTxt);
throw ActivationError("Http.Server handler chain compose failed");
} else {
CBLOG_WARNING(errorTxt);
}
},
nullptr, data);
arrayFree(res.exposedInfo);
arrayFree(res.requiredInfo);
}
} _composer{*this};
void warmup(CBContext *context) {
#if !defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__)
if (_threads > 1) {
const auto threads =
std::min(_threads, int64_t(std::thread::hardware_concurrency()));
if (!_exec || _exec->num_workers() != (size_t(threads))) {
_exec.reset(new tf::Executor(size_t(threads)));
}
}
#endif
_composer.context = context;
}
void cleanup() {
for (auto &v : _outputs) {
destroyVar(v);
}
_outputs.clear();
for (auto &cref : _chains) {
if (cref->node) {
cref->node->terminate();
}
stop(cref->chain.get());
_pool->release(cref);
}
_chains.clear();
}
virtual CBVar getInput(const std::shared_ptr<ManyChain> &mc,
const CBVar &input) = 0;
virtual size_t getLength(const CBVar &input) = 0;
CBVar activate(CBContext *context, const CBVar &input) {
auto node = context->main->node.lock();
auto len = getLength(input);
_outputs.resize(len);
_chains.resize(len);
Defer cleanups([this]() {
for (auto &cref : _chains) {
if (cref) {
if (cref->node) {
cref->node->terminate();
}
stop(cref->chain.get());
_pool->release(cref);
}
}
_chains.clear();
});
for (uint32_t i = 0; i < len; i++) {
_chains[i] = _pool->acquire(_composer);
_chains[i]->index = i;
_chains[i]->done = false;
}
size_t succeeded = 0;
size_t failed = 0;
// wait according to policy
while (true) {
const auto _suspend_state = chainblocks::suspend(context, 0);
if (unlikely(_suspend_state != CBChainState::Continue)) {
return Var::Empty;
} else {
#if defined(__EMSCRIPTEN__) && !defined(__EMSCRIPTEN_PTHREADS__)
{
#else
if (_threads == 1) {
#endif
// advance our chains and check
for (auto it = _chains.begin(); it != _chains.end(); ++it) {
auto &cref = *it;
if (cref->done)
continue;
// Prepare and start if no callc was called
if (!cref->chain->coro) {
cref->chain->node = context->main->node;
// pre-set chain context with our context
// this is used to copy chainStack over to the new one
cref->chain->context = context;
// Notice we don't share our flow!
// let the chain create one by passing null
chainblocks::prepare(cref->chain.get(), nullptr);
chainblocks::start(cref->chain.get(), getInput(cref, input));
}
// Tick the chain on the flow that this chain created
CBDuration now = CBClock::now().time_since_epoch();
chainblocks::tick(cref->chain->context->flow->chain, now,
getInput(cref, input));
if (!isRunning(cref->chain.get())) {
if (cref->chain->state == CBChain::State::Ended) {
if (_policy == WaitUntil::FirstSuccess) {
// success, next call clones, make sure to destroy
stop(cref->chain.get(), &_outputs[0]);
return _outputs[0];
} else {
stop(cref->chain.get(), &_outputs[succeeded]);
succeeded++;
}
} else {
stop(cref->chain.get());
failed++;
}
cref->done = true;
}
}
}
#if !defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__)
else {
// multithreaded
tf::Taskflow flow;
flow.for_each_dynamic(
_chains.begin(), _chains.end(),
[this, input](auto &cref) {
// skip if failed or ended
if (cref->done)
return;
// Prepare and start if no callc was called
if (!cref->chain->coro) {
if (!cref->node) {
cref->node = CBNode::make();
}
cref->chain->node = cref->node;
// Notice we don't share our flow!
// let the chain create one by passing null
chainblocks::prepare(cref->chain.get(), nullptr);
chainblocks::start(cref->chain.get(), getInput(cref, input));
}
// Tick the chain on the flow that this chain created
CBDuration now = CBClock::now().time_since_epoch();
chainblocks::tick(cref->chain->context->flow->chain, now,
getInput(cref, input));
// also tick the node
cref->node->tick();
},
_coros);
_exec->run(flow).get();
for (auto it = _chains.begin(); it != _chains.end(); ++it) {
auto &cref = *it;
if (!cref->done && !isRunning(cref->chain.get())) {
if (cref->chain->state == CBChain::State::Ended) {
if (_policy == WaitUntil::FirstSuccess) {
// success, next call clones, make sure to destroy
stop(cref->chain.get(), &_outputs[0]);
return _outputs[0];
} else {
stop(cref->chain.get(), &_outputs[succeeded]);
succeeded++;
}
} else {
stop(cref->chain.get());
failed++;
}
cref->done = true;
}
}
}
#endif
if ((succeeded + failed) == len) {
if (unlikely(succeeded == 0)) {
throw ActivationError("TryMany, failed all chains!");
} else {
// all ended let's apply policy here
if (_policy == WaitUntil::SomeSuccess) {
return Var(_outputs.data(), succeeded);
} else {
assert(_policy == WaitUntil::AllSuccess);
if (len == succeeded) {
return Var(_outputs.data(), succeeded);
} else {
throw ActivationError("TryMany, failed some chains!");
}
}
}
}
}
}
}
protected:
WaitUntil _policy{WaitUntil::AllSuccess};
std::unique_ptr<ChainDoppelgangerPool<ManyChain>> _pool;
IterableExposedInfo _sharedCopy;
Type _outputSeqType;
Types _outputTypes;
CBTypeInfo _inputType{};
std::vector<CBVar> _outputs;
std::vector<std::shared_ptr<ManyChain>> _chains;
int64_t _threads{1};
int64_t _coros{1};
#if !defined(__EMSCRIPTEN__) || defined(__EMSCRIPTEN_PTHREADS__)
std::unique_ptr<tf::Executor> _exec;
#endif
};
struct TryMany : public ParallelBase {
static CBTypesInfo inputTypes() { return CoreInfo::AnySeqType; }
static CBTypesInfo outputTypes() { return CoreInfo::AnySeqType; }
CBTypeInfo compose(const CBInstanceData &data) {
ParallelBase::compose(data);
if (data.inputType.seqTypes.len == 1) {
// copy single input type
_inputType = data.inputType.seqTypes.elements[0];
} else {
// else just mark as generic any
_inputType = CoreInfo::AnyType;
}
if (_policy == WaitUntil::FirstSuccess) {
// single result
return chain->outputType;
} else {
// seq result
_outputTypes = Types({chain->outputType});
_outputSeqType = Type::SeqOf(_outputTypes);
return _outputSeqType;
}
}
CBVar getInput(const std::shared_ptr<ManyChain> &mc,
const CBVar &input) override {
return input.payload.seqValue.elements[mc->index];
}
size_t getLength(const CBVar &input) override {
return size_t(input.payload.seqValue.len);
}
};
struct Expand : public ParallelBase {
int64_t _width{10};
static CBTypesInfo inputTypes() { return CoreInfo::AnyType; }
static CBTypesInfo outputTypes() { return CoreInfo::AnySeqType; }
static inline Parameters _params{
{{"Size", CBCCSTR("The maximum expansion size."), {CoreInfo::IntType}}},
ParallelBase::_params};
static CBParametersInfo parameters() { return _params; }
void setParam(int index, const CBVar &value) {
if (index == 0) {
_width = std::max(int64_t(1), value.payload.intValue);
} else {
ParallelBase::setParam(index - 1, value);
}
}
CBVar getParam(int index) {
if (index == 0) {
return Var(_width);
} else {
return ParallelBase::getParam(index - 1);
}
}
CBTypeInfo compose(const CBInstanceData &data) {
ParallelBase::compose(data);
// input
_inputType = data.inputType;
// output
_outputTypes = Types({chain->outputType});
_outputSeqType = Type::SeqOf(_outputTypes);
return _outputSeqType;
}
CBVar getInput(const std::shared_ptr<ManyChain> &mc,
const CBVar &input) override {
return input;
}
size_t getLength(const CBVar &input) override { return size_t(_width); }
};
struct Spawn : public ChainBase {
Spawn() { mode = RunChainMode::Detached; }
static CBTypesInfo inputTypes() { return CoreInfo::AnyType; }
static CBTypesInfo outputTypes() { return CoreInfo::ChainType; }
static inline Parameters _params{
{"Chain",
CBCCSTR("The chain to spawn and try to run many times concurrently."),
ChainBase::ChainVarTypes}};
static CBParametersInfo parameters() { return _params; }
void setParam(int index, const CBVar &value) {
switch (index) {
case 0:
chainref = value;
break;
default:
break;
}
}
CBVar getParam(int index) {
switch (index) {
case 0:
return chainref;
default:
return Var::Empty;
}
}
CBTypeInfo compose(const CBInstanceData &data) {
ChainBase::compose(data); // discard the result, we do our thing here
// chain should be populated now and such
_pool.reset(new ChainDoppelgangerPool<ManyChain>(CBChain::weakRef(chain)));
const IterableExposedInfo shared(data.shared);
// copy shared
_sharedCopy = shared;
_inputType = data.inputType;
return CoreInfo::ChainType;
}
struct Composer {
Spawn &server;
CBContext *context;
void compose(CBChain *chain) {
CBInstanceData data{};
data.inputType = server._inputType;
data.shared = server._sharedCopy;
data.chain = context->chainStack.back();
chain->node = context->main->node;
auto res = composeChain(
chain,
[](const struct CBlock *errorBlock, const char *errorTxt,
CBBool nonfatalWarning, void *userData) {
if (!nonfatalWarning) {
CBLOG_ERROR(errorTxt);
throw ActivationError("Http.Server handler chain compose failed");
} else {
CBLOG_WARNING(errorTxt);
}
},
nullptr, data);
arrayFree(res.exposedInfo);
arrayFree(res.requiredInfo);
}
} _composer{*this};
void warmup(CBContext *context) { _composer.context = context; }
CBVar activate(CBContext *context, const CBVar &input) {
auto node = context->main->node.lock();
auto c = _pool->acquire(_composer);
c->chain->onStop.clear(); // we have a fresh recycled chain here
std::weak_ptr<ManyChain> wc(c);
c->chain->onStop.emplace_back([this, wc]() {
if (auto c = wc.lock())
_pool->release(c);
});
node->schedule(c->chain, input, false);
return Var(c->chain); // notice this is "weak"
}
std::unique_ptr<ChainDoppelgangerPool<ManyChain>> _pool;
IterableExposedInfo _sharedCopy;
CBTypeInfo _inputType{};
};
struct Branch {
static CBTypesInfo inputTypes() { return CoreInfo::AnyType; }
static CBTypesInfo outputTypes() { return CoreInfo::AnyType; }
static CBParametersInfo parameters() {
static Parameters params{
{"Chains",
CBCCSTR("The chains to schedule and run on this branch."),
{CoreInfo::ChainType, CoreInfo::ChainSeqType, CoreInfo::NoneType}}};
return params;
}
void setParam(int index, const CBVar &value) {
switch (index) {
case 0:
_chains = value;
break;
default:
break;
}
}
CBVar getParam(int index) {
switch (index) {
case 0:
return _chains;
default:
return Var::Empty;
}
}
CBOptionalString help() {
return CBCCSTR(
"A branch is a child node that runs and is ticked when this block is "
"activated, chains on this node will inherit all of the available "
"exposed variables in the activator chain.");
}
void composeSubChain(const CBInstanceData &data, CBChainRef &chainref) {
auto chain = CBChain::sharedFromRef(chainref);
auto dataCopy = data;
dataCopy.chain = chain.get();
dataCopy.inputType = data.inputType;
auto cr = composeChain(
chain.get(),
[](const CBlock *errorBlock, const char *errorTxt, bool nonfatalWarning,
void *userData) {
if (!nonfatalWarning) {
CBLOG_ERROR("Branch: failed inner chain validation, error: {}",
errorTxt);
throw ComposeError("RunChain: failed inner chain validation");
} else {
CBLOG_INFO("Branch: warning during inner chain validation: {}",
errorTxt);
}
},
this, dataCopy);
_composes.emplace_back(cr);
_runChains.emplace_back(chain);
// add to merged requirements
for (auto &req : cr.requiredInfo) {
arrayPush(_mergedReqs, req);
}
}
void destroy() {
// release any old compose
for (auto &cr : _composes) {
arrayFree(cr.requiredInfo);
arrayFree(cr.exposedInfo);
}
_composes.clear();
arrayFree(_mergedReqs);
}
CBTypeInfo compose(const CBInstanceData &data) {
// release any old info
destroy();
_runChains.clear();
if (_chains.valueType == CBType::Seq) {
for (auto &chain : _chains) {
composeSubChain(data, chain.payload.chainValue);
}
} else if (_chains.valueType == CBType::Chain) {
composeSubChain(data, _chains.payload.chainValue);
}
const IterableExposedInfo shared(data.shared);
// copy shared
_sharedCopy = shared;
_node->instanceData.shared = _sharedCopy;
return data.inputType;
}
CBExposedTypesInfo requiredVariables() { return _mergedReqs; }
void warmup(CBContext *context) {
// grab all the variables we need and reference them
for (const auto &cr : _composes) {
for (const auto &req : cr.requiredInfo) {
if (_node->refs.count(req.name) == 0) {
auto vp = referenceVariable(context, req.name);
_node->refs[req.name] = vp;
}
}
}
for (const auto &chain : _runChains) {
_node->schedule(chain, Var::Empty, false);
}
}
void cleanup() {
for (auto &[_, vp] : _node->refs) {
releaseVariable(vp);
}
// this will also clear refs
_node->terminate();
}
CBVar activate(CBContext *context, const CBVar &input) {
if (!_node->tick(input)) {
// the node had errors in this case
throw ActivationError("Branched node had errors");
}
return input;
}
private:
OwnedVar _chains{Var::Empty};
std::shared_ptr<CBNode> _node = CBNode::make();
IterableExposedInfo _sharedCopy;
std::vector<CBComposeResult> _composes;
CBExposedTypesInfo _mergedReqs;
std::vector<std::shared_ptr<CBChain>> _runChains;
};
void registerChainsBlocks() {
using RunChainDo = RunChain<false, RunChainMode::Inline>;
using RunChainDispatch = RunChain<true, RunChainMode::Inline>;
using RunChainDetach = RunChain<true, RunChainMode::Detached>;
using RunChainStep = RunChain<false, RunChainMode::Stepped>;
REGISTER_CBLOCK("Resume", Resume);
REGISTER_CBLOCK("Start", Start);
REGISTER_CBLOCK("Wait", Wait);
REGISTER_CBLOCK("Stop", StopChain);
REGISTER_CBLOCK("Do", RunChainDo);
REGISTER_CBLOCK("Dispatch", RunChainDispatch);
REGISTER_CBLOCK("Detach", RunChainDetach);
REGISTER_CBLOCK("Step", RunChainStep);
REGISTER_CBLOCK("ChainLoader", ChainLoader);
REGISTER_CBLOCK("ChainRunner", ChainRunner);
REGISTER_CBLOCK("Recur", Recur);
REGISTER_CBLOCK("TryMany", TryMany);
REGISTER_CBLOCK("Spawn", Spawn);
REGISTER_CBLOCK("Expand", Expand);
REGISTER_CBLOCK("Branch", Branch);
}
}; // namespace chainblocks
#ifndef __EMSCRIPTEN__
// this is a hack to fix a linker issue with taskflow...
/*
duplicate symbol 'thread-local initialization routine for
tf::Executor::_per_thread' in: libcb_static.a(chains.cpp.o)
libcb_static.a(genetic.cpp.o)
*/
#include "genetic.hpp"
#endif | 29.391929 | 80 | 0.602276 | fragcolor-xyz |
3de6fdd38554b4043a8a064ba5229b2c48b65f20 | 3,549 | hpp | C++ | Source/Common/Context.hpp | gunstarpl/Perim-Game-07-2015 | 58efdee1857f5cccad909d5c2a76f2d6871657e6 | [
"Unlicense",
"MIT"
] | null | null | null | Source/Common/Context.hpp | gunstarpl/Perim-Game-07-2015 | 58efdee1857f5cccad909d5c2a76f2d6871657e6 | [
"Unlicense",
"MIT"
] | null | null | null | Source/Common/Context.hpp | gunstarpl/Perim-Game-07-2015 | 58efdee1857f5cccad909d5c2a76f2d6871657e6 | [
"Unlicense",
"MIT"
] | null | null | null | #pragma once
#include "Precompiled.hpp"
//
// Context
//
// Conveniently holds pointers to instances of different types.
// Use when you have to pass a non trivial number of references as a single argument.
//
class Context
{
public:
// Type declarations.
typedef std::pair<std::type_index, void*> InstancePtr;
typedef std::vector<InstancePtr> InstanceList;
typedef std::vector<Context> ContextList;
// Search function definition.
template<typename Type>
static bool SearchInstance(const InstancePtr& instance)
{
return instance.first == typeid(Type*);
}
public:
Context()
{
}
~Context()
{
}
// Restores instance to it's original state.
void Cleanup()
{
*this = Context();
}
// Sets an unique instance.
template<typename Type>
bool Set(Type* instance)
{
// Free instance handle if nullptr.
if(instance == nullptr)
{
this->Clear<Type>();
}
// Find instance by type.
auto it = std::find_if(m_instances.begin(), m_instances.end(), SearchInstance<Type>);
// Set the instance value.
if(it != m_instances.end())
{
// Replace value at existing handle.
it->second = instance;
return false;
}
else
{
// Add a new instance handle.
m_instances.emplace_back(typeid(Type*), instance);
return true;
}
}
// Gets an unique instance.
template<typename Type>
Type* Get() const
{
// Find instance by type.
auto it = std::find_if(m_instances.begin(), m_instances.end(), SearchInstance<Type>);
// Return instance reference.
if(it != m_instances.end())
{
return reinterpret_cast<Type*>(it->second);
}
else
{
return nullptr;
}
}
// Checks if has an instance of a given type.
template<typename Type>
bool Has() const
{
// Find instance by type.
auto it = std::find_if(m_instances.begin(), m_instances.end(), SearchInstance<Type>);
return it != m_instances.end();
}
// Clears the uniqe instance handle.
template<typename Type>
void Clear()
{
// Find and erase an instance.
m_instances.erase(std::find_if(m_instances.begin(), m_instances.end(), SearchInstance<Type>));
}
// Gets a subcontext.
Context& operator[](int index)
{
assert(index >= 0);
// Return self at zero index.
if(index == 0)
{
return *this;
}
// Resize context list if needed.
// Useful indices start from 1 here.
if(m_contexts.size() < size_t(index))
{
m_contexts.resize(index);
}
// Return a subcontext.
return m_contexts[index - 1];
}
const Context& operator[](int index) const
{
assert(index >= 0);
// Return self at zero index.
if(index == 0)
{
return *this;
}
// Return an empty context.
// Useful indices start from 1 here.
if(m_contexts.size() < size_t(index))
{
static const Context Invalid;
return Invalid;
}
// Return a subcontext.
return m_contexts[index - 1];
}
private:
// List of unique instances.
InstanceList m_instances;
// List of subcontextes.
ContextList m_contexts;
};
| 22.75 | 102 | 0.554804 | gunstarpl |
3de704a700d839d5f6b20357eda6a3740fc4021e | 4,675 | cpp | C++ | Libraries/graphics/Tests/test_PixelFormat.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | 9 | 2018-04-30T23:18:27.000Z | 2021-06-20T15:13:38.000Z | Libraries/graphics/Tests/test_PixelFormat.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | null | null | null | Libraries/graphics/Tests/test_PixelFormat.cpp | djgalloway/xcbuild | 936df10e59e5f5d531efca8bd48e445d88e78e0c | [
"BSD-2-Clause-NetBSD"
] | 4 | 2018-10-10T19:44:17.000Z | 2020-01-12T11:56:31.000Z | /**
Copyright (c) 2015-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
*/
#include <gtest/gtest.h>
#include <graphics/PixelFormat.h>
using graphics::PixelFormat;
TEST(PixelFormat, Properties)
{
/* Grayscale is one-byte. */
PixelFormat f0 = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::None);
EXPECT_EQ(f0.channels(), 1);
EXPECT_EQ(f0.bytesPerPixel(), 1);
EXPECT_EQ(f0.bitsPerPixel(), 8);
/* Ignored alpha is a byte but not a channel. */
PixelFormat f1 = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::IgnoredFirst);
EXPECT_EQ(f1.channels(), 1);
EXPECT_EQ(f1.bytesPerPixel(), 2);
EXPECT_EQ(f1.bitsPerPixel(), 16);
/* Real alpha is a channel too. */
PixelFormat f2 = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::First);
EXPECT_EQ(f2.channels(), 2);
EXPECT_EQ(f2.bytesPerPixel(), 2);
EXPECT_EQ(f2.bitsPerPixel(), 16);
/* RGB has three channels. */
PixelFormat f3 = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Forward, PixelFormat::Alpha::None);
EXPECT_EQ(f3.channels(), 3);
EXPECT_EQ(f3.bytesPerPixel(), 3);
EXPECT_EQ(f3.bitsPerPixel(), 24);
/* RGB can also have alpha. */
PixelFormat f4 = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Forward, PixelFormat::Alpha::PremultipliedLast);
EXPECT_EQ(f4.channels(), 4);
EXPECT_EQ(f4.bytesPerPixel(), 4);
EXPECT_EQ(f4.bitsPerPixel(), 32);
}
static std::vector<uint8_t>
Expected(std::vector<uint8_t> const &value)
{
return value;
}
TEST(PixelFormat, ConvertAlpha)
{
PixelFormat none = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::None);
PixelFormat last = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::Last);
/* Should add alpha as 0xFF (solid). */
EXPECT_EQ(PixelFormat::Convert({ 0x6A, 0x6B }, none, last), Expected({ 0x6A, 0xFF, 0x6B, 0xFF }));
/* Should strip out alpha, compositing against black. */
EXPECT_EQ(PixelFormat::Convert({ 0x60, 0x7F, 0x6B, 0xFF }, last, none), Expected({ 0x30, 0x6B }));
PixelFormat normal = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::Last);
PixelFormat premult = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::PremultipliedLast);
/* Should multiply in alpha. */
EXPECT_EQ(PixelFormat::Convert({ 0x60, 0x7F, 0x80, 0x40 }, normal, premult), Expected({ 0x30, 0x7F, 0x20, 0x40 }));
/* Should remove premultiplication. */
EXPECT_EQ(PixelFormat::Convert({ 0x30, 0x7F, 0x20, 0x40 }, premult, normal), Expected({ 0x60, 0x7F, 0x80, 0x40 }));
}
TEST(PixelFormat, ConvertGrayscale)
{
PixelFormat gray = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::None);
PixelFormat color = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Forward, PixelFormat::Alpha::None);
/* Should repeat the gray across the channels. */
EXPECT_EQ(PixelFormat::Convert({ 0x6A, 0x6B }, gray, color), Expected({ 0x6A, 0x6A, 0x6A, 0x6B, 0x6B, 0x6B }));
/* Should average the channels to grayscale. */
EXPECT_EQ(PixelFormat::Convert({ 0x1A, 0x3A, 0x5A, 0x10, 0x40, 0xA0 }, color, gray), Expected({ 0x3A, 0x50 }));
}
TEST(PixelFormat, ConvertRearrange)
{
/* Should flip alpha position. */
PixelFormat first = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::First);
PixelFormat last = PixelFormat(PixelFormat::Color::Grayscale, PixelFormat::Order::Forward, PixelFormat::Alpha::Last);
EXPECT_EQ(PixelFormat::Convert({ 0x6A, 0x7F }, last, first), Expected({ 0x7F, 0x6A }));
EXPECT_EQ(PixelFormat::Convert({ 0x7F, 0x6A }, first, last), Expected({ 0x6A, 0x7F }));
/* Should flip color channels. */
PixelFormat forward = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Forward, PixelFormat::Alpha::None);
PixelFormat reversed = PixelFormat(PixelFormat::Color::RGB, PixelFormat::Order::Reversed, PixelFormat::Alpha::None);
EXPECT_EQ(PixelFormat::Convert({ 0x6A, 0x6C, 0x6E }, forward, reversed), Expected({ 0x6E, 0x6C, 0x6A }));
EXPECT_EQ(PixelFormat::Convert({ 0x6E, 0x6C, 0x6A }, reversed, forward), Expected({ 0x6A, 0x6C, 0x6E }));
}
| 46.287129 | 137 | 0.706952 | djgalloway |
3de76419cd60453f8a99d7b4a59f72ef8da81325 | 3,597 | cpp | C++ | chapter6/Base.cpp | zzq1996/OJ | 359d0ad532732092a5afe5995312b12e8da74953 | [
"Apache-2.0"
] | null | null | null | chapter6/Base.cpp | zzq1996/OJ | 359d0ad532732092a5afe5995312b12e8da74953 | [
"Apache-2.0"
] | null | null | null | chapter6/Base.cpp | zzq1996/OJ | 359d0ad532732092a5afe5995312b12e8da74953 | [
"Apache-2.0"
] | null | null | null | /**
* @Author : zhang
* @create 2022/3/1 19:56
*/
#include "Base.h"
#include "iostream"
#include "vector"
using namespace std;
/*
* @Description 十进制整数转二进制
* 方法:除2取余,逆序排序
*/
void Base::f6_1() {
unsigned int n=0;
while (cin>>n){
if(n==0){
break;
}else{
vector<int> binary;
while (n!=0){
binary.push_back(n%2);
n=n/2;
}
//注意:这里是逆序输出
for (int i = binary.size()-1; i >= 0; --i) {
cout<<binary[i];
}
cout<<endl;
}
}
}
/*
* @Description 30位的非负十进制数转二进制
* 用字符串模拟数字,对字符串模拟的数字进行对2取模和对2整除运算
* ——取余:直接用最低位对2取模
* ——整除:定义函数完成
* char转int:char-‘0’
int转char:int+‘0’
*
*/
/*
* @Description 重写一个函数完成字符串的除法
* 对字符串str进行除2运算
*
* 返回的字符串:pos位置后的str字串即整除后的整数部分
*
* string字符串从0开始
*
* 输入: cout<<divide("12345",2);
* 输出:current:1,str[0]:0,reminder:1
current:12,str[1]:6,reminder:0
current:3,str[2]:1,reminder:1
current:14,str[3]:7,reminder:0
current:5,str[4]:2,reminder:1
str:06172
pos:1
6172
*
*/
string divide(string str,int x){
int reminder=0;//保留余数
//把字符串从高位到低位逐位除以2
for (int i = 0; i < str.size(); ++i) {
int current=reminder*10+str[i]-'0';
// cout<<"current:"<<current;
str[i]=current / x+'0';//str[i]保存的是整除2后的数
// cout<<",str["<<i<<"]:"<<str[i];
reminder = current % x;//若不能整除,则保留余数
// cout<<",reminder:"<<reminder<<endl;
}
int pos=0;
// cout<<"str:"<<str<<endl;
while(str[pos]=='0'){//寻找首个非0下标
pos++;
}
// cout<<"pos:"<<pos<<endl;
return str.substr(pos);//删除前置多余0
}
/*
* @Description 字符串转2进制
*/
void Base::f6_2() {
string str;
while (cin>>str){
vector<int> binary;
while(str.size()!=0){
int last=str[str.size()-1]-'0';//获取最低位的值
binary.push_back(last%2);//将最低位对2取模的结果存入向量
str= divide(str,2);//对2整除,更新字符串
}
//逆序输出向量
for (int i = binary.size()-1; i >=0; --i) {
cout<<binary[i];
}
cout<<endl;
}
}
/*
* @Description 输出二进制逆序数
*/
void Base::f6_3() {
string str;
while (cin>>str){
vector<int> binary;
while(str.size()!=0){
int last=str[str.size()-1]-'0';//获取最低位的值
binary.push_back(last%2);//将最低位对2取模的结果存入向量
str= divide(str,2);//对2整除,更新字符串
}
int sum=0,base=1;
for (int i = binary.size()-1; i >= 0; --i) {
sum=sum+binary[i]*base;
base=base*2;
}
cout<<sum<<endl;
}
}
/*
* @Description M进制转N进制
* 先转为10进制,再转为N进制
* 注意:1、进制大于10时,需实现字符与数字之间的转换
* 2、将十进制数转为N进制数的方法
*/
//数字转字符
char intToChar(int x){
if (x<10){
return x+'0';
}else{
return x-10+'a';
}
}
void Base::f6_4() {
int M=0,N=0;
string str;
while (cin>>M>>N>>str){
string str1;
int base=1;//转换的基数
long long num=0;//定义long long类型保存转换的十进制数
//将M进制的str转为10进制的num
for (int i = 0; i < str.size(); ++i) {
num=num+(str[i]-'0')*base;
base=base*M;
}
// cout<<"十进制数为:"<<num<<endl;
//将num转为N进制
//不断对N求余,求商,即可得到从低位到高位上的数
vector<char> answer;
while (num!=0){
answer.push_back(intToChar(num % N));
num=num/N;
}
//逆序输出向量数组
for (int i = answer.size()-1; i >= 0 ; --i) {
cout<<answer[i];
}
cout<<endl;
}
}
| 17.632353 | 56 | 0.48179 | zzq1996 |
3de7fde1b18eda98ac3b0ca94181b6a68699e670 | 2,916 | cpp | C++ | p4c_bm/templates/src/pd_counters.cpp | krambn/p4c-bm | e6be2c76f4568d5e01f62a8955ce2839d2fa0b36 | [
"Apache-2.0"
] | null | null | null | p4c_bm/templates/src/pd_counters.cpp | krambn/p4c-bm | e6be2c76f4568d5e01f62a8955ce2839d2fa0b36 | [
"Apache-2.0"
] | null | null | null | p4c_bm/templates/src/pd_counters.cpp | krambn/p4c-bm | e6be2c76f4568d5e01f62a8955ce2839d2fa0b36 | [
"Apache-2.0"
] | 6 | 2019-09-17T13:52:51.000Z | 2022-03-03T06:51:31.000Z | /* Copyright 2013-present Barefoot Networks, 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.
*/
/*
* Antonin Bas ([email protected])
*
*/
#include <bm/pdfixed/pd_common.h>
#include <thread>
#include "pd_client.h"
extern int *my_devices;
extern "C" {
//:: for ca_name, ca in counter_arrays.items():
//:: params = ["p4_pd_sess_hdl_t sess_hdl",
//:: "p4_pd_dev_target_t dev_tgt"]
//:: if ca.is_direct:
//:: params += ["p4_pd_entry_hdl_t entry_hdl"]
//:: else:
//:: params += ["int index"]
//:: #endif
//:: params += ["int flags"]
//:: param_str = ",\n ".join(params)
//:: name = pd_prefix + "counter_read_" + ca_name
p4_pd_counter_value_t
${name}
(
${param_str}
) {
assert(my_devices[dev_tgt.device_id]);
(void) flags;
p4_pd_counter_value_t counter_value;
BmCounterValue value;
// TODO: try / catch block
//:: if ca.is_direct:
pd_client(dev_tgt.device_id).c->bm_mt_read_counter(
value, 0, "${ca.table}", entry_hdl);
//:: else:
pd_client(dev_tgt.device_id).c->bm_counter_read(
value, 0, "${ca_name}", index);
//:: #endif
counter_value.bytes = (uint64_t) value.bytes;
counter_value.packets = (uint64_t) value.packets;
return counter_value;
}
//:: params = ["p4_pd_sess_hdl_t sess_hdl",
//:: "p4_pd_dev_target_t dev_tgt"]
//:: if ca.is_direct:
//:: params += ["p4_pd_entry_hdl_t entry_hdl"]
//:: else:
//:: params += ["int index"]
//:: #endif
//:: params += ["p4_pd_counter_value_t counter_value"]
//:: param_str = ",\n ".join(params)
//:: name = pd_prefix + "counter_write_" + ca_name
p4_pd_status_t
${name}
(
${param_str}
) {
assert(my_devices[dev_tgt.device_id]);
BmCounterValue value;
value.bytes = (int64_t) counter_value.bytes;
value.packets = (int64_t) counter_value.packets;
// TODO: try / catch block
//:: if ca.is_direct:
pd_client(dev_tgt.device_id).c->bm_mt_write_counter(
0, "${ca.table}", entry_hdl, value);
//:: else:
pd_client(dev_tgt.device_id).c->bm_counter_write(
0, "${ca_name}", index, value);
//:: #endif
return 0;
}
//:: name = pd_prefix + "counter_hw_sync_" + ca_name
p4_pd_status_t
${name}
(
p4_pd_sess_hdl_t sess_hdl,
p4_pd_dev_target_t dev_tgt,
p4_pd_stat_sync_cb cb_fn,
void *cb_cookie
) {
std::thread cb_thread(cb_fn, dev_tgt.device_id, cb_cookie);
cb_thread.detach();
return 0;
}
//:: #endfor
}
| 25.356522 | 75 | 0.665295 | krambn |
3df1534cd72d4c9bd9a355c602e7d34e307a79fb | 8,097 | inl | C++ | SoftRP/ArrayAllocatorImpl.inl | loreStefani/SoftRP | 2676145f74c734b272268820b1e1c503aa8ff765 | [
"MIT"
] | null | null | null | SoftRP/ArrayAllocatorImpl.inl | loreStefani/SoftRP | 2676145f74c734b272268820b1e1c503aa8ff765 | [
"MIT"
] | null | null | null | SoftRP/ArrayAllocatorImpl.inl | loreStefani/SoftRP | 2676145f74c734b272268820b1e1c503aa8ff765 | [
"MIT"
] | null | null | null | #ifndef SOFTRP_ARRAY_ALLOCATOR_IMPL_INL_
#define SOFTRP_ARRAY_ALLOCATOR_IMPL_INL_
#include "ArrayAllocator.h"
#include <utility>
#include <cassert>
namespace SoftRP {
/* ArrayAllocator implementation */
template<typename T, typename AllocationDesc, typename ArrayAllocationDesc>
inline ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::
ArrayAllocator(size_t allocStride, size_t allocAlignment)
: m_allocStride{ allocStride }, m_allocAlignment{ allocAlignment }
{
}
template<typename T, typename AllocationDesc, typename ArrayAllocationDesc>
inline ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::
ArrayAllocator(ArrayAllocator&& va) {
#ifdef SOFTRP_MULTI_THREAD
std::lock_guard<std::mutex> vaLock{ va.m_mutex };
#endif
m_allocStride = va.m_allocStride;
m_allocAlignment = va.m_allocAlignment;
m_allocations = std::move(va.m_allocations);
m_arrayAllocations = std::move(va.m_arrayAllocations);
}
template<typename T, typename AllocationDesc, typename ArrayAllocationDesc>
inline ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::~ArrayAllocator() {
#ifdef _DEBUG
for (auto& allocDesc : m_allocations)
assert(!allocDesc.hasAllocations());
for (auto& p : m_arrayAllocations)
assert(!p.second.hasAllocations());
#endif
}
template<typename T, typename AllocationDesc, typename ArrayAllocationDesc>
inline ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>& ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::operator=(ArrayAllocator&& va) {
if (&va == this)
return *this;
#ifdef SOFTRP_MULTI_THREAD
std::unique_lock<std::mutex> thisLock{ m_mutex, std::defer_lock };
std::unique_lock<std::mutex> vaLock{ va.m_mutex, std::defer_lock };
std::lock(thisLock, vaLock);
#endif
m_allocStride = va.m_allocStride;
m_allocAlignment = va.m_allocAlignment;
m_allocations = std::move(va.m_allocations);
m_arrayAllocations = std::move(va.m_arrayAllocations);
return *this;
}
template<typename T, typename AllocationDesc, typename ArrayAllocationDesc>
inline T* ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::allocate() {
#ifdef SOFTRP_MULTI_THREAD
std::lock_guard<std::mutex> lock{ m_mutex };
#endif
for (auto& allocDesc : m_allocations) {
if (allocDesc.canAllocate()) {
return allocDesc.allocate();
}
}
m_allocations.push_back(AllocationDesc{ m_allocStride, m_allocAlignment });
return m_allocations.back().allocate();
}
template<typename T, typename AllocationDesc, typename ArrayAllocationDesc>
inline void ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::deallocate(T* data) {
#ifdef SOFTRP_MULTI_THREAD
std::lock_guard<std::mutex> lock{ m_mutex };
#endif
for (auto& allocDesc : m_allocations) {
if (allocDesc.deallocate(data))
return;
}
throw std::runtime_error{ "Deallocation requested to the wrong allocator" };
}
template<typename T, typename AllocationDesc, typename ArrayAllocationDesc>
inline T* ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::allocateArray(size_t count) {
#ifdef SOFTRP_MULTI_THREAD
std::lock_guard<std::mutex> lock{ m_mutex };
#endif
auto it = m_arrayAllocations.find(count);
if (it != m_arrayAllocations.end()) {
return it->second.allocate();
} else {
ArrayAllocationDesc arrayAllocDesc{ m_allocStride, count, m_allocAlignment };
T* ptr = arrayAllocDesc.allocate();
m_arrayAllocations.emplace(count, std::move(arrayAllocDesc));
return ptr;
}
}
template<typename T, typename AllocationDesc, typename ArrayAllocationDesc>
inline void ArrayAllocator<T, AllocationDesc, ArrayAllocationDesc>::deallocateArray(T* dataArray) {
#ifdef SOFTRP_MULTI_THREAD
std::lock_guard<std::mutex> lock{ m_mutex };
#endif
for (auto& pair : m_arrayAllocations) {
auto& arrayAllocDesc = pair.second;
if (arrayAllocDesc.deallocate(dataArray))
return;
}
throw std::runtime_error{ "Deallocation requested to the wrong allocator" };
}
/* PoolAllocDescBase implementation */
template<typename T, typename Allocator>
inline PoolAllocDescBase<T, Allocator>::PoolAllocDescBase(size_t allocStride, size_t allocAlignment) {
const size_t elementSize = allocStride*sizeof(T);
const size_t allocSize = BLOCK_SIZE*elementSize;
m_data = static_cast<T*>(m_allocator.allocate(allocSize, allocAlignment));
m_end = m_data + allocStride*BLOCK_SIZE;
m_allocStride = allocStride;
}
template<typename T, typename Allocator>
inline PoolAllocDescBase<T, Allocator>::~PoolAllocDescBase() {
if (m_data) {
m_allocator.deallocate(m_data);
m_data = nullptr;
}
}
template<typename T, typename Allocator>
inline PoolAllocDescBase<T, Allocator>::PoolAllocDescBase(PoolAllocDescBase&& aad)
:m_allocationState{ aad.m_allocationState }, m_allocStride{ aad.m_allocStride }, m_data{ aad.m_data }, m_end{ aad.m_end } {
aad.m_data = nullptr;
}
template<typename T, typename Allocator>
inline PoolAllocDescBase<T, Allocator>& PoolAllocDescBase<T, Allocator>::operator=(PoolAllocDescBase&& aad) {
m_allocationState = aad.m_allocationState;
m_allocStride = aad.m_allocStride;
m_data = aad.m_data;
m_end = aad.m_end;
aad.m_data = nullptr;
}
template<typename T, typename Allocator>
inline T* PoolAllocDescBase<T, Allocator>::allocate() {
size_t index = m_nextIndex;
uint64_t currAlloc = static_cast<uint64_t>(1) << index;
for (size_t i = index; i < BLOCK_SIZE; i++) {
if ((m_allocationState & currAlloc) == 0) {
m_allocationState |= currAlloc;
m_nextIndex = i + 1;
return m_data + i*m_allocStride;
}
currAlloc <<= 1;
}
currAlloc = 1;
for (size_t i = 0; i < index; i++) {
if ((m_allocationState & currAlloc) == 0) {
m_allocationState |= currAlloc;
m_nextIndex = i + 1;
return m_data + i*m_allocStride;
}
currAlloc <<= 1;
}
return nullptr;
}
template<typename T, typename Allocator>
inline bool PoolAllocDescBase<T, Allocator>::canAllocate() const {
return m_allocationState != 0xFFFFFFFFFFFFFFFF;
}
template<typename T, typename Allocator>
inline bool PoolAllocDescBase<T, Allocator>::hasAllocations() const {
return m_allocationState != 0x0;
}
template<typename T, typename Allocator>
inline bool PoolAllocDescBase<T, Allocator>::deallocate(T* ptr) {
if (ptr < m_data || ptr >= m_end)
return false;
size_t index = (ptr - m_data) / m_allocStride;
#ifdef _DEBUG
if ((ptr - m_data) != index*m_allocStride)
throw std::runtime_error{ "Deallocating from the wrong address!" };
if ((m_allocationState & (static_cast<uint64_t>(1) << index)) == 0)
throw std::runtime_error{ "Deallocating from the wrong allocator!" };
#endif
m_allocationState &= ~(static_cast<uint64_t>(1) << index);
m_nextIndex = index;
return true;
}
/* PoolArrayAllocDescBase implementation */
template<typename T, typename Allocator>
inline PoolArrayAllocDescBase<T, Allocator>::PoolArrayAllocDescBase(size_t allocStride, size_t count, size_t allocAlignment)
: m_elementSize{ allocStride*sizeof(T) }, m_allocSize{ count*m_elementSize },
m_allocAlignment{ allocAlignment }
{
}
template<typename T, typename Allocator>
inline PoolArrayAllocDescBase<T, Allocator>::~PoolArrayAllocDescBase() {
for (const auto& p : m_allocated)
m_allocator.deallocate(p);
for (const auto& p : m_free)
m_allocator.deallocate(p);
}
template<typename T, typename Allocator>
inline T* PoolArrayAllocDescBase<T, Allocator>::allocate() {
T* ptr{ nullptr };
if (m_free.size() == 0)
ptr = static_cast<T*>(m_allocator.allocate(m_allocSize, m_allocAlignment));
else {
ptr = m_free.front();
m_free.pop_front();
}
m_allocated.emplace(ptr);
return ptr;
}
template<typename T, typename Allocator>
inline bool PoolArrayAllocDescBase<T, Allocator>::hasAllocations()const {
return m_allocated.size() != 0;
}
template<typename T, typename Allocator>
inline bool PoolArrayAllocDescBase<T, Allocator>::deallocate(T* ptr) {
auto it = m_allocated.find(ptr);
if (it == m_allocated.end())
return false;
m_allocated.erase(it);
m_free.emplace_back(ptr);
return true;
}
}
#endif | 31.628906 | 152 | 0.742003 | loreStefani |
ad0573882fe9cb2c61661fd4dfc0449f6af0996c | 1,486 | cpp | C++ | src/dll/Handler.cpp | Mathieu-Lala/unamed00 | e9a7bc3f2c0c791d719c1f3f68f23c2734f70f10 | [
"MIT"
] | 5 | 2020-02-23T13:48:42.000Z | 2020-04-12T17:43:12.000Z | src/dll/Handler.cpp | Mathieu-Lala/unamed00 | e9a7bc3f2c0c791d719c1f3f68f23c2734f70f10 | [
"MIT"
] | null | null | null | src/dll/Handler.cpp | Mathieu-Lala/unamed00 | e9a7bc3f2c0c791d719c1f3f68f23c2734f70f10 | [
"MIT"
] | null | null | null | /**
* @file src/dll/Handler.cpp
*
*/
#include <utility>
#include "dll/Handler.hpp"
dll::Handler::Handler() noexcept :
m_handler (EMPTY)
{ }
dll::Handler::Handler(Handler &&o) noexcept :
m_handler (std::exchange(o.m_handler, EMPTY)),
m_libpath (std::move(o.m_libpath))
{ }
dll::Handler &dll::Handler::operator=(dll::Handler &&o) noexcept
{
this->m_handler = std::exchange(o.m_handler, EMPTY);
this->m_libpath = std::move(o.m_libpath);
return *this;
}
dll::Handler::Handler(Path libpath) :
m_handler (EMPTY)
{
this->open(std::move(libpath));
}
dll::Handler::~Handler()
{
this->close();
}
bool dll::Handler::is_valid() const noexcept
{
return this->m_handler != EMPTY;
}
void dll::Handler::open(Path libpath)
{
this->close();
this->m_libpath = std::move(libpath);
# if defined(OS_LINUX)
this->m_handler = ::dlopen(this->m_libpath.c_str(), RTLD_LAZY);
# elif defined(OS_WINDOWS)
this->m_handler = ::LoadLibrary(this->m_libpath.c_str());
# endif
if (!this->is_valid())
throw error{ };
}
void dll::Handler::close()
{
if (!this->is_valid())
return;
# if defined(OS_LINUX)
auto ok = !::dlclose(this->m_handler);
# elif defined(OS_WINDOWS)
auto ok = ::FreeLibrary(this->m_handler);
# endif
this->m_handler = EMPTY;
this->m_libpath = "";
if (!ok)
throw error{ };
}
const dll::Handler::Path &dll::Handler::getPath() const noexcept
{
return this->m_libpath;
}
| 19.051282 | 67 | 0.62786 | Mathieu-Lala |
ad105cce07ac486786a156bf00bdcebbe804aa66 | 1,610 | cpp | C++ | LeetCode/ThousandOne/0394-decode_string.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0394-decode_string.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | LeetCode/ThousandOne/0394-decode_string.cpp | Ginkgo-Biloba/Cpp-Repo1-VS | 231c68a055e6bf69a3f7c224e7c0182b67ce5b67 | [
"Apache-2.0"
] | null | null | null | #include "leetcode.hpp"
/* 394. 字符串解码
给定一个经过编码的字符串,返回它解码后的字符串。
编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。
注意 k 保证为正整数。
你可以认为输入字符串总是有效的;
输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k。
例如不会出现像 3a 或 2[4] 的输入。
示例:
s = "3[a]2[bc]", 返回 "aaabcbc".
s = "3[a2[c]]", 返回 "accaccacc".
s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
*/
string decodeString(string const& E)
{
size_t len = E.length();
string D;
vector<int> cnt;
vector<string> rep;
for (size_t i = 0; i < len;)
{
if (isdigit(E[i]))
{
int n = E[i] - '0';
size_t k = i + 1;
// 保证符合要求,不用检查越界
for (; isdigit(E[k]); ++k)
n = n * 10 + (E[k] - '0');
cnt.push_back(n);
i = k;
}
else if (E[i] == '[')
{
string cur;
size_t k = i + 1;
for (; !isdigit(E[k]) && E[k] != ']'; ++k)
cur.push_back(E[k]);
rep.push_back(cur);
i = k;
}
else if (E[i] == ']')
{
string cur;
int n = cnt.back();
cur.reserve(rep.back().size() * n);
while (n--)
cur += rep.back();
rep.pop_back();
cnt.pop_back();
if (rep.empty())
D += cur;
else
rep.back() += cur;
++i;
}
// 又没说不能出现 **&*&¥@!%%&*&(* 这种
else // if (isalpha(E[i]))
{
bool out = rep.empty();
for (; i < len && !isdigit(E[i]) && E[i] != ']'; ++i)
{
if (out)
D.push_back(E[i]);
else
rep.back().push_back(E[i]);
}
}
}
return D;
}
int main()
{
OutExpr(decodeString("2[b4[F]c]").c_str(), "%s");
OutExpr(decodeString("3[a]2[bc]").c_str(), "%s");
OutExpr(decodeString("3[a2[c]]").c_str(), "%s");
OutExpr(decodeString("2[abc]3[cd]ef").c_str(), "%s");
}
| 18.089888 | 60 | 0.526087 | Ginkgo-Biloba |
ad10652207b6a8e6dbe40723e9792d48315ad841 | 5,141 | hpp | C++ | mcdc/Include/parser.hpp | yadaniel/MCDC | 6ca4475d813ddd19741f38f8f91c9dd477ebe4dd | [
"BSD-3-Clause"
] | 16 | 2020-04-23T09:18:07.000Z | 2022-02-06T11:14:22.000Z | mcdc/Include/parser.hpp | yadaniel/MCDC | 6ca4475d813ddd19741f38f8f91c9dd477ebe4dd | [
"BSD-3-Clause"
] | 1 | 2021-12-01T15:42:30.000Z | 2021-12-01T15:42:30.000Z | mcdc/Include/parser.hpp | yadaniel/MCDC | 6ca4475d813ddd19741f38f8f91c9dd477ebe4dd | [
"BSD-3-Clause"
] | 10 | 2019-11-15T22:14:05.000Z | 2021-08-02T09:04:28.000Z | // --------------------------------------------------------------------------------------------------------------------------------
// License: BSD-3-Clause
// --------------------------------------------------------------------------------------------------------------------------------
//
// Copyright 2019 Armin Montigny
//
// --------------------------------------------------------------------------------------------------------------------------------
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met :
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
// following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and /or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or
// promote products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------------------------------------------------------------
#pragma once
#ifndef PARSER_HPP
#define PARSER_HPP
//
// Implementation of a Shift Reduce Parser for boolean expressions
//
// This Software takes a string with a boolean expression as an input
// and transorms it to other representations, to be able to vealuate it
//
// The Parser, defined in this module, analyzes the given source (boolean expression)
// and generates code for a virtual machine or for an Abstract Syntax Tree AST
// or whatever, using a codegenerator.
//
// First the source is tokenized via a scanner, then the Parser analyzes the Tokens
// and tries to match it wit the productions in the grammar. If a match is found,
// then the code generator is called.
//
// So, the algorithm is a classical shift match reduce parser.
//
// The whole chain consist of:
//
// Scanner --> Parser --> Code Generator --> Virtual Machine
//
// The parser tkaes a source string as input and generates an object file and a symbol table
//
// Operation:
//
// The Parser calls the scanner to get the next token. The token will be shifted on the parse stack.
// Then, the top elements (one or more) of the parse stack will be compared to handles and
// the look ahead symnol in the grammar. If there is no match, the next token will be read
// and pushed on the stack. If there is a match, then the gode generator is called and the parse stack
// will be reduced. All matching elements on the parse stack (without the look ahead symbol) will be
// removed/replace by the non-terminal, the left hand side for/of this production.
// This will be done until the end of the source string has been detected or a syntax error has been found.
//
// Tokens have attributes, specifically the input terminal symbols
#include "scanner.hpp"
#include "codegenerator.hpp"
#include "grammar.hpp"
#include <utility>
// The parse stack is a vector of Tokens (with attributes). Since we want o work on more elements as
// the stack top, a std::vector is used and not a std::stack
using ParseStack = std::vector<TokenWithAttribute>;
class Parser
{
public:
// The parser needs to know about the scanner and the code geenrator
// The Grammar is a runtime constant
explicit Parser(Scanner& scannerForParser, CodeGeneratorBase* codeGeneratorForParser) noexcept : grammar(grammarForBooleanExpressions), scanner(scannerForParser), codeGeneratorForVM(codeGeneratorForParser), parseStack() {}
Parser() = delete;
Parser& operator =(const Parser&) = delete;
// Main interface. Do the parse. Returns false on error
bool parse();
protected:
// Yes I know. These are references
const Grammar& grammar;
Scanner& scanner;
CodeGeneratorBase* codeGeneratorForVM;
// Match function compares top of parse stack with handles of the grammar
std::pair<bool, uint> match();
// Calls Code generator and reduces the parse stack, be erasing/replacing handle elements with a none terminal
void reduce(uint positionOfProduction);
ParseStack parseStack;
// For debugging or learning purposes
void printParseStack(std::string title);
};
#endif
| 43.940171 | 223 | 0.682163 | yadaniel |
ad11dd5be153140c3c4eaa023dc8c6a12e2bd6e7 | 3,367 | cpp | C++ | Engine/src/shader.cpp | scilus/dmri-explorer | f23a9bf1af0ec41ef1f7b126bec237b6add542fb | [
"MIT"
] | 1 | 2021-10-01T16:28:38.000Z | 2021-10-01T16:28:38.000Z | Engine/src/shader.cpp | scilus/dmri-explorer | f23a9bf1af0ec41ef1f7b126bec237b6add542fb | [
"MIT"
] | 12 | 2021-09-16T20:01:24.000Z | 2022-03-24T00:24:17.000Z | Engine/src/shader.cpp | scilus/dmri-explorer | f23a9bf1af0ec41ef1f7b126bec237b6add542fb | [
"MIT"
] | 3 | 2021-09-16T19:06:18.000Z | 2022-02-17T19:49:05.000Z | #include "shader.h"
#include "utils.hpp"
#include <algorithm>
#include <cstring>
namespace
{
const int NUM_SHADER_INCLUDES = 3;
const char* SHADER_INCLUDE_PATHS[NUM_SHADER_INCLUDES] = {
"/include/camera_util.glsl",
"/include/orthogrid_util.glsl",
"/include/shfield_util.glsl"
};
}
namespace Slicer
{
namespace GPU
{
ShaderProgram::ShaderProgram(const std::string& filePath,
const GLenum shaderType)
:mShaderType(shaderType)
{
const std::string strShader = readFile(filePath);
GLint lenShader[1] = { static_cast<GLint>(strShader.length()) };
const GLchar* strShaderC_str = strShader.c_str();
GLuint shaderID = glCreateShader(shaderType);
glShaderSource(shaderID, 1, &strShaderC_str, lenShader);
glCompileShaderIncludeARB(shaderID,
mShaderIncludePaths.size(),
mShaderIncludePaths.data(),
mShaderIncludeLengths.data());
assertShaderCompilationSuccess(shaderID, filePath);
this->mProgramID = glCreateProgram();
glProgramParameteri(this->mProgramID, GL_PROGRAM_SEPARABLE, GL_TRUE);
glAttachShader(this->mProgramID, shaderID);
glLinkProgram(this->mProgramID);
assertProgramLinkingSuccess(this->mProgramID);
}
void ShaderProgram::CreateFilesystemForInclude()
{
for(int i = 0; i < NUM_SHADER_INCLUDES; ++i)
{
const auto pathName = SHADER_INCLUDE_PATHS[i];
const auto pathNameLen = std::strlen(pathName);
const std::string strInclude = readFile(
DMRI_EXPLORER_BINARY_DIR + std::string("/shaders") +
pathName);
// Add to virtual filesystem.
glNamedStringARB(GL_SHADER_INCLUDE_ARB, pathNameLen,
pathName, strInclude.length(), strInclude.c_str());
mShaderIncludePaths.push_back(pathName);
mShaderIncludeLengths.push_back(static_cast<int>(pathNameLen));
}
}
ProgramPipeline::ProgramPipeline(const std::vector<ShaderProgram>& shaderPrograms)
{
glGenProgramPipelines(1, &this->mPipelineID);
for(const ShaderProgram& p : shaderPrograms)
{
GLbitfield programStage = ProgramPipeline::convertShaderTypeToGLbitfield(p.Type());
glUseProgramStages(this->mPipelineID, programStage, p.ID());
}
}
ProgramPipeline::ProgramPipeline(const ShaderProgram& shaderProgram)
{
glGenProgramPipelines(1, &this->mPipelineID);
GLbitfield programStage = ProgramPipeline::convertShaderTypeToGLbitfield(shaderProgram.Type());
glUseProgramStages(this->mPipelineID, programStage, shaderProgram.ID());
}
const GLbitfield ProgramPipeline::convertShaderTypeToGLbitfield(const GLenum shaderType) const
{
switch(shaderType)
{
case GL_VERTEX_SHADER:
return GL_VERTEX_SHADER_BIT;
case GL_FRAGMENT_SHADER:
return GL_FRAGMENT_SHADER_BIT;
case GL_COMPUTE_SHADER:
return GL_COMPUTE_SHADER_BIT;
case GL_TESS_CONTROL_SHADER:
return GL_TESS_CONTROL_SHADER_BIT;
case GL_TESS_EVALUATION_SHADER:
return GL_TESS_EVALUATION_SHADER_BIT;
case GL_GEOMETRY_SHADER:
return GL_GEOMETRY_SHADER_BIT;
default:
throw std::runtime_error("Invalid shader type.");
}
}
void ProgramPipeline::Bind() const
{
glBindProgramPipeline(this->mPipelineID);
}
} // namespace GPU
} // namespace Slicer
| 31.46729 | 99 | 0.702703 | scilus |
ad1c520897b33c1ff46e05cfb8905dd4051d53ba | 361 | hpp | C++ | Helios/src/Input.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | Helios/src/Input.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | Helios/src/Input.hpp | rgracari/helio_test | 2d516d16da4252c8f92f5c265b6151c6e87bc907 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Bitmask.hpp"
namespace Helio
{
class Input
{
private:
Bitmask thisFrameKeys;
Bitmask lastFrameKeys;
public:
enum class Key
{
None = 0,
ArrowLeft,
ArrowRight,
ArrowUp,
ArrowDown,
Esc
};
void Update();
bool IsKeyPressed(Key keycode);
bool IsKeyDown(Key keycode);
bool IsKeyUp(Key keycode);
};
} | 12.033333 | 33 | 0.66205 | rgracari |
ad1d0040093879727d9f4956bb9fa75b2636b318 | 6,640 | cpp | C++ | quadrotor_motion_with_pid_control/subpackages/thrust_controller/src/source/thrust_controller.cpp | lesmesrafa/Multi-drone-behaviors | 1d35e4f1df6d9dd8e158b01ec7577aa21ce0b9a3 | [
"CC0-1.0"
] | null | null | null | quadrotor_motion_with_pid_control/subpackages/thrust_controller/src/source/thrust_controller.cpp | lesmesrafa/Multi-drone-behaviors | 1d35e4f1df6d9dd8e158b01ec7577aa21ce0b9a3 | [
"CC0-1.0"
] | null | null | null | quadrotor_motion_with_pid_control/subpackages/thrust_controller/src/source/thrust_controller.cpp | lesmesrafa/Multi-drone-behaviors | 1d35e4f1df6d9dd8e158b01ec7577aa21ce0b9a3 | [
"CC0-1.0"
] | null | null | null | #include "thrust_controller.hpp"
void ThrustController::ownSetUp()
{
static ros::NodeHandle nh;
std::string n_space ;
std::string estimated_speed_topic;
std::string estimated_pose_topic;
std::string altitude_rate_yaw_rate_topic;
std::string thrust_topic;
std::string flight_action_topic;
std::string robot_config_path;
std::string yaml_config_file;
ros_utils_lib::getPrivateParam<double> ("~uav_mass" , mass_ ,1);
ros_utils_lib::getPrivateParam<std::string>("~namespace" , n_space ,"drone1");
ros_utils_lib::getPrivateParam<std::string>("~estimated_speed_topic" , estimated_speed_topic ,"self_localization/speed");
ros_utils_lib::getPrivateParam<std::string>("~estimated_pose_topic" , estimated_pose_topic ,"self_localization/pose");
ros_utils_lib::getPrivateParam<std::string>("~altitude_rate_yaw_rate_topic" , altitude_rate_yaw_rate_topic ,"actuator_command/altitude_rate_yaw_rate");
ros_utils_lib::getPrivateParam<std::string>("~thrust_topic" , thrust_topic ,"actuator_command/thrust");
ros_utils_lib::getPrivateParam<std::string>("~flight_action_topic" , flight_action_topic ,"actuator_command/flight_action");
ros_utils_lib::getPrivateParam<std::string>("~robot_config_path" , robot_config_path ,"configs/"+n_space);
ros_utils_lib::getPrivateParam<std::string>("~yaml_config_file" , yaml_config_file ,"quadrotor_pid_controller_config.yaml");
std::cout << "uav_mass = " << mass_ << std::endl;
altitude_rate_yaw_rate_sub_ = nh.subscribe("/" + n_space + "/" + altitude_rate_yaw_rate_topic,1,&ThrustController::altitudeRateYawRateCallback,this);
pose_sub_ = nh.subscribe("/" + n_space + "/" + estimated_pose_topic ,1,&ThrustController::poseCallback,this);
speeds_sub_ = nh.subscribe("/" + n_space + "/" + estimated_speed_topic,1,&ThrustController::speedsCallback,this);
flight_action_sub = nh.subscribe("/" + n_space + "/" + flight_action_topic,1,&ThrustController::flightActionCallback,this);
thrust_pub_ = nh.advertise<mavros_msgs::Thrust>("/" + n_space + "/" + thrust_topic,1);
thrust_msg_.thrust = 0;
// Load file
YAML::Node yamlconf;
try
{
yamlconf = YAML::LoadFile(robot_config_path+"/"+yaml_config_file);
}
catch (std::exception& e)
{
std::cout<<"Yaml config file does not exist in path: "<<robot_config_path<<"/"<<yaml_config_file<<" . Taking default values"<<std::endl;
}
if(yamlconf["thrust_controller"]){
Kp_ = yamlconf["thrust_controller"]["kp"].as<float>();
Ki = yamlconf["thrust_controller"]["ki"].as<float>();
Kd_ = yamlconf["thrust_controller"]["kd"].as<float>();
}
//Code for publishing thrust value in a way that can be compared using rqt_plot tool (Only for debugging purposes
#if DEBUG == 1
thrust_debugger_pub_ = nh.advertise<std_msgs::Float32MultiArray>("/"+n_space+"/"+"debug/thrust_controller",1);
thrust_debugger_values_msg_.data = std::vector<float>(2);
std_msgs::MultiArrayDimension dim;
dim.label = "ThrustSignal";
dim.size = 2;
dim.stride = 1;
thrust_debugger_values_msg_.layout.dim.emplace_back(dim);
roll_pitch_yaw_rate_thrust_sub_ = nh.subscribe("/"+n_space+"/"+"actuator_command/roll_pitch_yaw_rate_thrust_test",1,
&ThrustController::rollPitchYawRateThrustCallback,this);
roll_pitch_yaw_rate_thrust_pub_ = nh.advertise<mav_msgs::RollPitchYawrateThrust>("/"+n_space+"/"+"actuator_command/roll_pitch_yaw_rate_thrust",1);
#endif
}
void ThrustController::computeThrust(double dz_reference){
// Initialize static variables
static ros::Time prev_time = ros::Time::now();
static float accum_error = 0.0f;
static float last_dz_error = 0.0f;
static float last_reference = 0.0f;
static ros_utils_lib::MovingAverageFilter dz_derivative_filtering(0.85);
float& thrust = thrust_msg_.thrust;
double dtime = (ros::Time::now()-prev_time).toSec();
prev_time = ros::Time::now();
double feed_forward = 0.0f;
// double feed_forward = dz_reference_ - last_reference;
float dz_error = (dz_reference- dz_measure_);
float dz_derivative_error = (dz_error-last_dz_error)/(dtime+1e-9);
// dz_derivative_error = dz_derivative_filtering.filterValue(dz_derivative_error);
last_reference = dz_reference;
last_dz_error = dz_error;
accum_error += dz_error;
accum_error = (accum_error > antiwindup_limit_)? antiwindup_limit_ : accum_error;
accum_error = (accum_error < - antiwindup_limit_)? - antiwindup_limit_ : accum_error;
thrust = mass_ * (GRAVITY_CONSTANT + feed_forward +Kp_ *dz_error + Ki*accum_error + Kd_*dz_derivative_error);
thrust = thrust /(cos(pitch_)*cos(roll_)); // project Thrust in z axis
thrust = (thrust < MIN_THRUST_)? MIN_THRUST_ : thrust; // LOW LIMIT THRUST IN [0, MAX_THRUST]
thrust = (thrust > MAX_THRUST_)? MAX_THRUST_ : thrust; // HIGH LIMIT THRUST IN [0, MAX_THRUST]
//std::cout << "dz_reference = " << dz_reference << std::endl;
//std::cout << "dz_error = " << dz_error << std::endl;
//std::cout << "thrust = " << thrust << std::endl;
}
void ThrustController::ownRun(){
computeThrust(dz_reference_);
publishThrust();
}
void ThrustController::publishThrust(){
thrust_pub_.publish(thrust_msg_);
}
// __________________________________CALLBACKS_________________________________________
void ThrustController::altitudeRateYawRateCallback(const geometry_msgs::TwistStamped& _msg){
thrust_msg_.header = _msg.header;
dz_reference_ = _msg.twist.linear.z;
}
void ThrustController::speedsCallback(const geometry_msgs::TwistStamped& _msg){
dz_measure_ = _msg.twist.linear.z;
}
void ThrustController::poseCallback(const geometry_msgs::PoseStamped& _msg){
position_=_msg.pose.position;
tf::Quaternion q;
tf::quaternionMsgToTF(_msg.pose.orientation,q);
tf::Matrix3x3 m(q);
double roll,pitch,yaw;
m.getRPY(roll, pitch, yaw);
roll_ = roll;
pitch_ = pitch;
}
/*------------------------ DEBUGGING FUNCTIONS --------------------------*/
#if DEBUG == 1
void ThrustController::rollPitchYawRateThrustCallback(const mav_msgs::RollPitchYawrateThrust& _msg){
std::cout << "dz_measure :"<< dz_measure_<< std::endl ;
std::cout << "dz_reference :"<< dz_reference_<< std::endl ;
thrust_debugger_values_msg_.data[0] = _msg.thrust.z;
thrust_debugger_values_msg_.data[1] = thrust_msg_.thrust;
thrust_debugger_pub_.publish(thrust_debugger_values_msg_);
static mav_msgs::RollPitchYawrateThrust msg;
msg = _msg;
msg.thrust.z = thrust_msg_.thrust;
std::cout << "prev_thrust :"<< _msg.thrust.z<< std::endl ;
std::cout << "new_thrust :"<< msg.thrust.z<< std::endl ;
roll_pitch_yaw_rate_thrust_pub_.publish(msg);
}
#endif
| 40.487805 | 152 | 0.72997 | lesmesrafa |
ad1da01581127b3687354f7b2d6dc194de671b41 | 696 | cpp | C++ | test_gendata.cpp | campfireai/lavastone | 5c15a922172c1aa567a582ae6625d150b7a154ab | [
"Unlicense"
] | 9 | 2021-09-14T23:10:26.000Z | 2021-11-28T12:02:02.000Z | test_gendata.cpp | campfireai/lavastone | 5c15a922172c1aa567a582ae6625d150b7a154ab | [
"Unlicense"
] | null | null | null | test_gendata.cpp | campfireai/lavastone | 5c15a922172c1aa567a582ae6625d150b7a154ab | [
"Unlicense"
] | 1 | 2021-09-16T04:54:31.000Z | 2021-09-16T04:54:31.000Z | #include "gendata.hpp"
#include <fstream>
#include <iostream>
int main(int argc, char *argv[]) {
if (argc != 2) {
std::cerr << "usage:\n"
<< "./test_gendata NUM_RECORDS\n";
exit(1);
}
size_t num_records = std::stoi(argv[1]);
std::string fname = "data.csv";
std::cout << "writing " << num_records << " records to " << fname << "\n";
std::ofstream outfile;
outfile.open(fname);
outfile << "title,author,author_location,num_likes"
<< "\n";
for (auto r : random_recipes(num_records)) {
outfile << "\"" << r.title << "\",\"" << r.author << "\",\""
<< r.author_location << "\",\"" << r.num_likes << "\"\n";
}
outfile.close();
}
| 25.777778 | 76 | 0.54023 | campfireai |
ad1ddad5142a021dc6e1cc083c4914ea6cea0fce | 494 | cpp | C++ | src/render/idle_recognizer.cpp | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 3 | 2015-02-22T20:34:28.000Z | 2020-03-04T08:55:25.000Z | src/render/idle_recognizer.cpp | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 22 | 2015-12-13T16:29:40.000Z | 2017-03-04T15:45:44.000Z | src/render/idle_recognizer.cpp | Reaping2/Reaping2 | 0d4c988c99413e50cc474f6206cf64176eeec95d | [
"MIT"
] | 14 | 2015-11-23T21:25:09.000Z | 2020-07-17T17:03:23.000Z | #include "render/idle_recognizer.h"
#include "core/i_move_component.h"
namespace render {
IdleRecognizer::IdleRecognizer( int32_t Id )
: Recognizer( Id )
{
}
bool IdleRecognizer::Recognize( Actor const& actor ) const
{
Opt<IMoveComponent> moveC = actor.Get<IMoveComponent>();
if ( !moveC.IsValid() )
{
return true;
}
if ( !moveC->IsMoving() )
{
//L1( " Idle RECOGNIZED! \n" );
return true;
}
return false;
}
} // namespace render
| 18.296296 | 60 | 0.615385 | MrPepperoni |
ad20873ab7d37247c6e6e99af3c83c82b6db1521 | 409 | cpp | C++ | cmake/test/main.cpp | blagodarin/seir | fec45228d161dabb8bb4aaa23c64ea218b84e8fd | [
"Apache-2.0"
] | null | null | null | cmake/test/main.cpp | blagodarin/seir | fec45228d161dabb8bb4aaa23c64ea218b84e8fd | [
"Apache-2.0"
] | null | null | null | cmake/test/main.cpp | blagodarin/seir | fec45228d161dabb8bb4aaa23c64ea218b84e8fd | [
"Apache-2.0"
] | null | null | null | // This file is part of Seir.
// Copyright (C) Sergei Blagodarin.
// SPDX-License-Identifier: Apache-2.0
#include <seir_base/string_utils.hpp>
#include <seir_u8main/u8main.hpp>
#include <iostream>
#include <plf_colony.h>
int u8main(int, char**)
{
std::string helloWorld = "Hello world!";
seir::normalizeWhitespace(helloWorld, seir::TrailingSpace::Remove);
std::cerr << helloWorld << '\n';
return 0;
}
| 21.526316 | 68 | 0.713936 | blagodarin |
ad22235ea03fb2f5c75be30d908be9762dad4ebe | 745 | cpp | C++ | countFrequency.cpp | harshallgarg/CPP | 4d15c5e5d426bb00d192368d21924ec9f017445f | [
"MIT"
] | 2 | 2020-08-09T02:09:50.000Z | 2020-08-09T07:07:47.000Z | countFrequency.cpp | harshallgarg/CPP | 4d15c5e5d426bb00d192368d21924ec9f017445f | [
"MIT"
] | null | null | null | countFrequency.cpp | harshallgarg/CPP | 4d15c5e5d426bb00d192368d21924ec9f017445f | [
"MIT"
] | 4 | 2020-05-25T10:24:14.000Z | 2021-05-03T07:52:35.000Z | //
// CountFrequency.cpp
// AnishC++
//
// Created by Anish Mookherjee on 20/10/19.
// Copyright © 2019 Anish Mookherjee. All rights reserved.
//
#include <iostream>
using namespace std;
int main()
{
int i,n;
cout<<"Enter no. of elements you want to enter."<<endl;
cin>>n;
int a[n];
int b[9];
cout<<"Enter elements."<<endl;
for(i=0;i<n;i++)
{
cin>>a[i];
b[a[i]]++;
}
int max=0,pos=0;
for(i=0;i<9;i++)
{
for(int j=0;j<9;j++)
{
if(max<b[j])
{
max=b[j];
pos=j;
b[j]=0;
}
}
if(max!=0)
for(int k=0;k<max;k++)
cout<<max<<endl;
}
return 0;
}
| 17.325581 | 59 | 0.42953 | harshallgarg |
ad266f076a48f37607ab583853ff65d659e79f8a | 5,190 | hh | C++ | src/transport/CMR.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 4 | 2015-03-07T16:20:23.000Z | 2020-02-10T13:40:16.000Z | src/transport/CMR.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 3 | 2018-02-27T21:24:22.000Z | 2020-12-16T00:56:44.000Z | src/transport/CMR.hh | RLReed/libdetran | 77637c788823e0a14aae7e40e476a291f6f3184b | [
"MIT"
] | 9 | 2015-03-07T16:20:26.000Z | 2022-01-29T00:14:23.000Z | /*
* CMR.hh
*
* Created on: May 17, 2012
* Author: robertsj
*/
#ifndef CMR_HH_
#define CMR_HH_
// Detran
#include "WithinGroupAcceleration.hh"
// System
namespace detran
{
/*!
* \class CMR
* \brief Coarse Mesh Rebalance
*
* Consider the one group problem
* \f[
* \Big ( \mu \frac{\partial}{\partial x}
* + \eta \frac{\partial}{\partial y}
* + \xi \frac{\partial}{\partial z}
* \Big ) \psi + \Sigma_t(\vec{r}) \psi(\vec{r}, \hat{\Omega}) =
* \Sigma_s(\vec{r}) \phi(\vec{r}) + q(\vec{r}, \hat{\Omega}) \, .
* \f]
* where we have explicitly separated the within-group scatter
* from the external source.
*
* Suppose we integrate this over a coarse cell of volume
* \f$ V = \Delta_x \Delta_y \Delta_z \f$ and over the
* angular space, \f$ 4\pi \f$. The
* streaming terms give rise to terms like
*
* \f[
* \begin{split}
* & \int_{4\pi} \mu \int^{\Delta_y}_{0} \int^{\Delta_z}_{0} dy dz
* \Bigg ( \frac{\partial \psi}{\partial x} \Big |_{x=\Delta_x}
* -\frac{\partial \psi}{\partial x} \Big |_{x=0} \Bigg ) =
* \int^{\Delta_y}_{0} \int^{\Delta_z}_{0} dy dz
* \Big ( J_x(\Delta_x, y, z) - J_x(0, y, z) \Big ) \, ,
* \end{split}
* \f]
*
* where \f$ J_x \f$ is the \f$x\f$-directed partial current. Similar
* terms can be found for the other directions.
*
* We can write the integrated transport equation as
*
* \f[
* \Delta_y \Delta_z \Big ( \bar{J}_x(\Delta_x) - \bar{J}_x(0) \Big ) +
* \Delta_x \Delta_z \Big ( \bar{J}_y(\Delta_y) - \bar{J}_y(0) \Big ) +
* \Delta_x \Delta_y \Big ( \bar{J}_z(\Delta_z) - \bar{J}_z(0) \Big ) +
* \Delta_x \Delta_y \Delta_z \bar{\Sigma_r} \bar{\phi}(\vec{r}) =
* \Delta_x \Delta_y \Delta_z \bar{q}(\vec{r})
* \f]
*
* where we have defined the average current across a face of the box as
*
* \f[
* \bar{J}_x(x) =
* \frac{\int^{\Delta_y}_{0} \int^{\Delta_z}_{0} dy dz J_x(x, y, z)}
* {\int^{\Delta_y}_{0} \int^{\Delta_z}_{0} dy dz} \, .
* \f]
*
* and similar averages for the removal rate and source. Note, it is
* the \e removal rate of interest on the left. This requires a coarse
* mesh averaged removal cross section and scalar flux. The removal
* cross section is simply the total cross section minus the
* within-group scattering cross section. As a consequence, the
* source \f$ q \f$ does \e not include the within-group scatter source.
*
* We simplify notation by writing
*
* \f[
* \sum_{p \in (x,y,z)} \frac{1}{\Delta_{p}}
* \Big ( \bar{J}_{p}(\Delta_{p}) - \bar{J}_{p}(0) \Big ) +
* \bar{\Sigma_r} \bar{\phi}(\vec{r}) =
* \bar{q}(\vec{r})
* \f]
*
* This neutron balance equation is not satisfied when the flux
* in not converged. However, if we can somehow force the flux
* to satisfy balance at the coarse level, then we can apply
* any correction to the fine level. Let us define rebalance
* factors \f$ f_i \f$ such that
*
* \f[
* \sum_{p \in (x,y,z)} \frac{1}{\Delta_{p}}
* \Big ( \bar{J}_{p}(\Delta_{p}) - \bar{J}_{p}(0) \Big ) +
* f_i \bar{\Sigma_r} \bar{\phi}_i =
* \bar{q}(\vec{r})
* \f]
*
*/
template <class D>
class CMR : public WithinGroupAcceleration<D>
{
public:
/// \name Useful Typedefs
// \{
typedef SP<CMR> SP_acceleration;
typedef WithingroupAcceleration<D> Base;
typedef typename Base::SP_acceleration SP_base;
typedef Base::SP_input SP_input;
typedef Base::SP_material SP_material;
typedef Base::SP_coarsemesh SP_coarsemesh;
typedef Base::SP_currenttally SP_currenttally;
typedef typename Base::SP_sweepsource SP_sweepsource;
// \}
/*!
* \brief Constructor
*
* @param input Input database
* @param material Material database
* @param coarsemesh Coarse mesh
* @param currenttally Current tally
*/
CMR(SP_input input,
SP_material material,
SP_coarsemesh coarsemesh,
SP_currenttally currenttally);
/// \name Public Interface
/// \{
/*!
* \brief Solve the low order equation to update the scalar flux moments
*
* @param group Energy group for this solve
* @param phi Reference to the group flux to be updated.
* @param source Smart pointer to up-to-date sweep source.
*
*/
void accelerate(u_int group,
State::moments_type &phi,
SP_sweepsource source);
/// \}
private:
/// \name Private Data
/// \{
/// Cell-integrated removal rate
vec_dbl d_R;
/// Cell-integrated source
vec_dbl d_Q;
/// Rebalance factors.
vec2_int d_f;
/// \}
/// \name Implementation
/// \{
/*!
* \brief Compute the coarse mesh integrated removal rate and source
* @param phi Reference to fine mesh flux
* @param source Smart pointer to sweep source
*/
void integrate(u_int group,
State::moments_type &phi,
SP_sweepsource source);
/// \}
};
} // end namespace detran
#include "CMR.i.hh"
#endif /* CMR_HH_ */
| 27.172775 | 75 | 0.584971 | RLReed |
ad270fc135aa168a8214ef24fd5419b8cad51509 | 11,906 | cpp | C++ | src/CoreGenPortal/PortalCore/CoreRegInfoWin.cpp | opensocsysarch/CoreGenPortal | b6c8c9ca13fa8add969511f153331cad83953799 | [
"Apache-2.0"
] | 1 | 2019-06-25T13:06:14.000Z | 2019-06-25T13:06:14.000Z | src/CoreGenPortal/PortalCore/CoreRegInfoWin.cpp | opensocsysarch/CoreGenPortal | b6c8c9ca13fa8add969511f153331cad83953799 | [
"Apache-2.0"
] | 128 | 2018-10-23T12:45:15.000Z | 2021-12-28T13:09:39.000Z | src/CoreGenPortal/PortalCore/CoreRegInfoWin.cpp | opensocsysarch/CoreGenPortal | b6c8c9ca13fa8add969511f153331cad83953799 | [
"Apache-2.0"
] | 1 | 2021-01-20T23:17:34.000Z | 2021-01-20T23:17:34.000Z | //
// _COREREGINFOWIN_CPP_
//
// Copyright (C) 2017-2020 Tactical Computing Laboratories, LLC
// All Rights Reserved
// [email protected]
//
// See LICENSE in the top level directory for licensing details
//
#include "CoreGenPortal/PortalCore/CoreRegInfoWin.h"
// Event Table
wxBEGIN_EVENT_TABLE(CoreRegInfoWin, wxDialog)
EVT_BUTTON(wxID_OK, CoreRegInfoWin::OnPressOk)
EVT_BUTTON(wxID_SAVE, CoreRegInfoWin::OnSave)
wxEND_EVENT_TABLE()
CoreRegInfoWin::CoreRegInfoWin( wxWindow* parent,
wxWindowID id,
const wxString& title,
CoreGenReg *Reg )
: wxDialog( parent, id, title, wxDefaultPosition,
wxSize(500,500), wxDEFAULT_DIALOG_STYLE|wxVSCROLL ){
RegNode = (CoreGenReg*)Reg;
// init the internals
this->SetLayoutAdaptationMode(wxDIALOG_ADAPTATION_MODE_ENABLED);
this->SetSizeHints( wxDefaultSize, wxDefaultSize );
// create the outer box sizer
OuterSizer = new wxBoxSizer( wxVERTICAL );
// create the scrolled window
Wnd = new wxScrolledWindow(this,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
0,
wxT("Scroll"));
// create the inner sizer
InnerSizer = new wxBoxSizer( wxVERTICAL );
// add all the interior data
// -- reg name
RegNameSizer = new wxBoxSizer( wxHORIZONTAL );
RegNameText = new wxStaticText( Wnd,
4,
wxT("Register Name"),
wxDefaultPosition,
wxSize(160,-1),
0 );
RegNameText->Wrap(-1);
RegNameSizer->Add( RegNameText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 );
RegNameCtrl = new wxTextCtrl( Wnd,
0,
Reg ? wxString(Reg->GetName()) : "",
wxDefaultPosition,
wxSize(320,25),
0,
wxDefaultValidator,
wxT("Reg Name") );
RegNameSizer->Add( RegNameCtrl, 0, wxALL, 0 );
InnerSizer->Add(RegNameSizer, 0, wxALIGN_CENTER|wxALL, 5 );
//-- reg idx
RegIdxSizer = new wxBoxSizer( wxHORIZONTAL );
RegIdxText = new wxStaticText( Wnd,
5,
wxT("Register Index"),
wxDefaultPosition,
wxSize(160, -1),
0 );
RegIdxText->Wrap(-1);
RegIdxSizer->Add( RegIdxText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 );
RegIdxCtrl = new wxTextCtrl( Wnd,
1,
Reg ? wxString::Format(wxT("%i"),Reg->GetIndex()) : "",
wxDefaultPosition,
wxSize(320,25),
0,
wxDefaultValidator,
wxT("Register Index") );
RegIdxSizer->Add( RegIdxCtrl, 0, wxALL, 0 );
InnerSizer->Add(RegIdxSizer, 0, wxALIGN_CENTER|wxALL, 5);
//-- width
WidthSizer = new wxBoxSizer( wxHORIZONTAL );
WidthText = new wxStaticText( Wnd,
6,
wxT("Register Width (in bits)"),
wxDefaultPosition,
wxSize(160, -1),
0 );
WidthText->Wrap(-1);
WidthSizer->Add( WidthText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 );
WidthCtrl = new wxTextCtrl( Wnd,
2,
Reg ? wxString::Format(wxT("%i"),Reg->GetWidth()): "",
wxDefaultPosition,
wxSize(320,25),
0,
wxDefaultValidator,
wxT("Register Width") );
WidthSizer->Add( WidthCtrl, 0, wxALL, 0 );
InnerSizer->Add( WidthSizer, 0, wxALIGN_CENTER|wxALL, 5 );
//-- simd
SIMDSizer = new wxBoxSizer( wxHORIZONTAL );
SIMDText = new wxStaticText( Wnd,
8,
wxT("SIMD Width (in bits)"),
wxDefaultPosition,
wxSize(160, -1),
0 );
SIMDText->Wrap(-1);
SIMDSizer->Add( SIMDText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 );
SIMDCtrl = new wxTextCtrl( Wnd,
16,
Reg ? std::to_string(Reg->GetSIMDWidth()) : "",
wxDefaultPosition,
wxSize(320,25),
0,
wxDefaultValidator,
wxT("Register Width") );
SIMDSizer->Add( SIMDCtrl, 0, wxALL, 0 );
InnerSizer->Add( SIMDSizer, 0, wxALIGN_CENTER|wxALL, 5 );
//-- subregs
SubRegSizer = new wxBoxSizer( wxHORIZONTAL );
SubRegText = new wxStaticText( Wnd,
7,
wxT("Subregister Fields"),
wxDefaultPosition,
wxSize(160, -1),
0 );
WidthText->Wrap(-1);
SubRegSizer->Add( SubRegText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 );
SubRegCtrl = new wxTextCtrl( Wnd,
3,
wxEmptyString,
wxDefaultPosition,
wxSize(320,100),
wxTE_MULTILINE|wxHSCROLL,
wxDefaultValidator,
wxT("Subregisters ") );
SubRegCtrl->AppendText(wxT("NAME:START_BIT:END_BIT\n"));
std::string SRName;
unsigned SRStart;
unsigned SREnd;
if(Reg){
for( unsigned i=0; i<Reg->GetNumSubRegs(); i++ ){
Reg->GetSubReg(i,SRName,SRStart,SREnd);
SubRegCtrl->AppendText(wxString(SRName) + wxT(":") +
wxString::Format(wxT("%i"),SRStart) + wxT(":") +
wxString::Format(wxT("%i"),SREnd) + wxT("\n") );
}
}
SubRegSizer->Add( SubRegCtrl, 0, wxALL, 0 );
InnerSizer->Add( SubRegSizer, 0, wxALIGN_CENTER|wxALL, 5 );
HCheckSizer1 = new wxBoxSizer( wxHORIZONTAL );
/*
if( Reg && Reg->IsSIMD() )
SIMDCheck->SetValue(true);
else
SIMDCheck->SetValue(false);
HCheckSizer1->Add(SIMDCheck, 0, wxALL, 0);
*/
//-- rw check box
RWCheck = new wxCheckBox( Wnd,
9,
wxT("Read/Write Register"),
wxDefaultPosition,
wxDefaultSize,
wxALIGN_RIGHT,
wxDefaultValidator,
wxT("RWREGISTER") );
if( Reg && Reg->IsRWAttr() )
RWCheck->SetValue(true);
else
RWCheck->SetValue(false);
HCheckSizer1->Add(RWCheck, 0, wxALL, 0);
//-- ro check box
ROCheck = new wxCheckBox( Wnd,
10,
wxT("Read-Only Register"),
wxDefaultPosition,
wxDefaultSize,
wxALIGN_RIGHT,
wxDefaultValidator,
wxT("ROREGISTER") );
if( Reg && Reg->IsROAttr() )
ROCheck->SetValue(true);
else
ROCheck->SetValue(false);
HCheckSizer1->Add(ROCheck, 0, wxALL, 0 );
InnerSizer->Add(HCheckSizer1, 0, wxALIGN_CENTER|wxALL, 5 );
HCheckSizer2 = new wxBoxSizer( wxHORIZONTAL );
//-- csr check box
CSRCheck = new wxCheckBox( Wnd,
11,
wxT("Config Status Register"),
wxDefaultPosition,
wxDefaultSize,
wxALIGN_RIGHT,
wxDefaultValidator,
wxT("CSRREGISTER") );
if( Reg && Reg->IsCSRAttr() )
CSRCheck->SetValue(true);
else
CSRCheck->SetValue(false);
HCheckSizer2->Add(CSRCheck, 0, wxALL, 0);
//-- ams check box
AMSCheck = new wxCheckBox( Wnd,
12,
wxT("Arithmetic Machine State Register"),
wxDefaultPosition,
wxDefaultSize,
wxALIGN_RIGHT,
wxDefaultValidator,
wxT("AMSREGISTER") );
if( Reg && Reg->IsAMSAttr() )
AMSCheck->SetValue(true);
else
AMSCheck->SetValue(false);
HCheckSizer2->Add(AMSCheck, 0, wxALL, 0);
InnerSizer->Add( HCheckSizer2, 0, wxALIGN_CENTER|wxALL, 5 );
HCheckSizer3 = new wxBoxSizer( wxHORIZONTAL );
//-- tus check box
TUSCheck = new wxCheckBox( Wnd,
13,
wxT("Thread Unit Shared Register"),
wxDefaultPosition,
wxDefaultSize,
wxALIGN_RIGHT,
wxDefaultValidator,
wxT("TUSREGISTER") );
if( Reg && Reg->IsTUSAttr() )
TUSCheck->SetValue(true);
else
TUSCheck->SetValue(false);
HCheckSizer3->Add(TUSCheck, 0, wxALL, 0);
//-- pc check box
PCCheck = new wxCheckBox( Wnd,
14,
wxT("PC Register"),
wxDefaultPosition,
wxDefaultSize,
wxALIGN_RIGHT,
wxDefaultValidator,
wxT("PCREGISTER") );
if( Reg && Reg->IsPCAttr() )
PCCheck->SetValue(true);
else
PCCheck->SetValue(false);
HCheckSizer3->Add(PCCheck, 0, wxALL, 0);
//-- shared check box
SharedCheck = new wxCheckBox( Wnd,
15,
wxT("Shared Register"),
wxDefaultPosition,
wxDefaultSize,
wxALIGN_RIGHT,
wxDefaultValidator,
wxT("SHAREDREGISTER") );
if( Reg && Reg->IsShared() )
SharedCheck->SetValue(true);
else
SharedCheck->SetValue(false);
HCheckSizer3->Add(SharedCheck, 0, wxALL, 0);
InnerSizer->Add( HCheckSizer3, 0, wxALIGN_CENTER|wxALL, 5 );
// add the static line
FinalStaticLine = new wxStaticLine( Wnd,
wxID_ANY,
wxDefaultPosition,
wxDefaultSize,
wxLI_HORIZONTAL );
InnerSizer->Add( FinalStaticLine, 1, wxEXPAND | wxALL, 5 );
// setup all the buttons
m_socbuttonsizer = new wxStdDialogButtonSizer();
m_userOK = new wxButton( Wnd, wxID_CANCEL );
m_userSAVE = new wxButton( Wnd, wxID_SAVE);
m_socbuttonsizer->SetAffirmativeButton( m_userOK );
m_socbuttonsizer->SetCancelButton( m_userSAVE );
m_socbuttonsizer->Realize();
InnerSizer->Add( m_socbuttonsizer, 0, wxALL, 5 );
Wnd->SetScrollbars(20,20,50,50);
Wnd->SetSizer( InnerSizer );
Wnd->SetAutoLayout(true);
Wnd->Layout();
// draw the dialog box until we get more info
OuterSizer->Add(Wnd, 1, wxEXPAND | wxALL, 5 );
this->SetSizer( OuterSizer );
this->SetAutoLayout( true );
this->Layout();
}
void CoreRegInfoWin::OnPressOk(wxCommandEvent& ok){
this->EndModal(wxID_OK);
}
void CoreRegInfoWin::OnSave(wxCommandEvent& save){
PortalMainFrame *PMF = (PortalMainFrame*)this->GetParent();
if(PMF->OnSave(this, this->RegNode, CGReg))
this->EndModal(wxID_SAVE);
}
CoreRegInfoWin::~CoreRegInfoWin(){
}
// EOF
| 34.914956 | 83 | 0.484378 | opensocsysarch |
ad2c6f33cff15e436e69dd2540314cc2cc8144ad | 4,895 | cpp | C++ | src/XliPlatform/sdl2/SDL2GLContext.cpp | mortend/uno-base | 53bf65ca269f89e3b6ac01845a1de498963c5cca | [
"MIT"
] | 4 | 2018-05-14T07:49:34.000Z | 2018-05-21T06:40:17.000Z | src/XliPlatform/sdl2/SDL2GLContext.cpp | mortend/uno-base | 53bf65ca269f89e3b6ac01845a1de498963c5cca | [
"MIT"
] | 2 | 2018-10-21T12:40:49.000Z | 2020-04-16T17:55:55.000Z | src/XliPlatform/sdl2/SDL2GLContext.cpp | mortend/uno-base | 53bf65ca269f89e3b6ac01845a1de498963c5cca | [
"MIT"
] | 4 | 2018-05-14T17:03:51.000Z | 2018-12-01T08:05:02.000Z | #include <XliPlatform/GLContext.h>
#include <XliPlatform/GL.h>
#include <XliPlatform/PlatformSpecific/SDL2.h>
#include <uBase/Memory.h>
namespace Xli
{
namespace PlatformSpecific
{
class SDL2GLContext: public GLContext
{
SDL_Window* window;
SDL_GLContext context;
public:
SDL2GLContext(Window* wnd, const GLContextAttributes& attribs)
{
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, attribs.ColorBits.R);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, attribs.ColorBits.G);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, attribs.ColorBits.B);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, attribs.ColorBits.A);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, attribs.DepthBits);
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, attribs.StencilBits);
#ifndef IOS
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, attribs.Samples > 1 ? 1 : 0);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, attribs.Samples);
#endif
SDL_GL_SetAttribute(SDL_GL_ACCUM_RED_SIZE, attribs.AccumBits.R);
SDL_GL_SetAttribute(SDL_GL_ACCUM_GREEN_SIZE, attribs.AccumBits.G);
SDL_GL_SetAttribute(SDL_GL_ACCUM_BLUE_SIZE, attribs.AccumBits.B);
SDL_GL_SetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, attribs.AccumBits.A);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, attribs.Buffers <= 1 ? 0 : 1);
SDL_GL_SetAttribute(SDL_GL_STEREO, attribs.Stereo ? 1 : 0);
#ifdef U_GL_ES2
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
#endif
window = SDL2::GetWindowHandle(wnd);
context = SDL_GL_CreateContext(window);
if (!context)
throw Exception("Failed to create OpenGL context");
Vector2i vp = wnd->GetClientSize();
glViewport(0, 0, vp.X, vp.Y);
#ifdef U_GL_DESKTOP
glewInit();
#endif
}
virtual ~SDL2GLContext()
{
SDL_GL_DeleteContext(context);
}
virtual GLContext* CreateSharedContext()
{
throw NotSupportedException(U_FUNCTION);
}
virtual void MakeCurrent(Window* wnd)
{
if (wnd)
window = SDL2::GetWindowHandle(wnd);
SDL_GL_MakeCurrent(wnd ? window : 0, wnd ? context : 0);
}
virtual bool IsCurrent()
{
return SDL_GL_GetCurrentContext() == context;
}
virtual void SwapBuffers()
{
SDL_GL_SwapWindow(window);
}
virtual void SetSwapInterval(int value)
{
SDL_GL_SetSwapInterval(value);
}
virtual int GetSwapInterval()
{
return SDL_GL_GetSwapInterval();
}
virtual Vector2i GetDrawableSize()
{
Vector2i size;
#ifdef LINUX
SDL_GetWindowSize(window, &size.X, &size.Y);
#else
SDL_GL_GetDrawableSize(window, &size.X, &size.Y);
#endif
return size;
}
virtual void GetAttributes(GLContextAttributes& result)
{
memset(&result, 0, sizeof(GLContextAttributes));
SDL_GL_GetAttribute(SDL_GL_RED_SIZE, &result.ColorBits.R);
SDL_GL_GetAttribute(SDL_GL_GREEN_SIZE, &result.ColorBits.G);
SDL_GL_GetAttribute(SDL_GL_BLUE_SIZE, &result.ColorBits.B);
SDL_GL_GetAttribute(SDL_GL_ALPHA_SIZE, &result.ColorBits.A);
SDL_GL_GetAttribute(SDL_GL_DEPTH_SIZE, &result.DepthBits);
SDL_GL_GetAttribute(SDL_GL_STENCIL_SIZE, &result.StencilBits);
SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &result.Samples);
SDL_GL_GetAttribute(SDL_GL_ACCUM_RED_SIZE, &result.AccumBits.R);
SDL_GL_GetAttribute(SDL_GL_ACCUM_GREEN_SIZE, &result.AccumBits.G);
SDL_GL_GetAttribute(SDL_GL_ACCUM_BLUE_SIZE, &result.AccumBits.B);
SDL_GL_GetAttribute(SDL_GL_ACCUM_ALPHA_SIZE, &result.AccumBits.A);
int doubleBuffer, stereo;
SDL_GL_GetAttribute(SDL_GL_DOUBLEBUFFER, &doubleBuffer);
SDL_GL_GetAttribute(SDL_GL_STEREO, &stereo);
result.Buffers = doubleBuffer ? 2 : 1;
result.Stereo = stereo ? true : false;
}
};
}
GLContext* GLContext::Create(Window* wnd, const GLContextAttributes& attribs)
{
return new PlatformSpecific::SDL2GLContext(wnd, attribs);
}
}
| 36.804511 | 92 | 0.595914 | mortend |
ad31f62e3f5313fa323f59cdd539a1bc6d62e9d6 | 14,715 | cpp | C++ | patch/game/clawmute.cpp | Tonyx97/TombMP | 7eb2d265df2fe7312b7ed07dd5943736340b921c | [
"MIT"
] | 3 | 2021-10-10T11:12:03.000Z | 2021-11-04T16:46:57.000Z | patch/game/clawmute.cpp | Tonyx97/TombMP | 7eb2d265df2fe7312b7ed07dd5943736340b921c | [
"MIT"
] | null | null | null | patch/game/clawmute.cpp | Tonyx97/TombMP | 7eb2d265df2fe7312b7ed07dd5943736340b921c | [
"MIT"
] | null | null | null | #include "objects.h"
#include "lara.h"
#include "control.h"
#include "effect2.h"
#include "sphere.h"
#include "people.h"
#include "traps.h"
#include <specific/standard.h>
#include <specific/fn_stubs.h>
#define CLAW_PLASMA_DAMAGE 200
#define CLAW_BITE_DAMAGE 100
#define CLAW_TOUCH (0x90)
#define CLAW_DIE_ANIM 20
#define CLAW_WALK_TURN (3*ONE_DEGREE)
#define CLAW_RUN_TURN (4*ONE_DEGREE)
#define CLAW_ATTACK1_RANGE SQUARE(WALL_L)
#define CLAW_ATTACK2_RANGE SQUARE(WALL_L*2)
#define CLAW_ATTACK3_RANGE SQUARE(WALL_L*4/3)
#define CLAW_FIRE_RANGE SQUARE(WALL_L*3)
#define CLAW_ROAR_CHANCE 0x60
#define CLAW_WALK_CHANCE (CLAW_ROAR_CHANCE + 0x400)
#define CLAW_AWARE_DISTANCE SQUARE(WALL_L)
enum claw_anims
{
CLAW_STOP,
CLAW_WALK,
CLAW_RUN,
CLAW_RUN_ATAK,
CLAW_WALK_ATAK1,
CLAW_WALK_ATAK2,
CLAW_SLASH_LEFT,
CLAW_SLASH_RIGHT,
CLAW_DEATH,
CLAW_CLAW_ATAK,
CLAW_FIRE_ATAK
};
void TriggerPlasma(int16_t item_number);
void TriggerPlasmaBallFlame(int16_t fx_number, long type, long xv, long yv, long zv);
void TriggerPlasmaBall(ITEM_INFO* item, long type, PHD_VECTOR* pos1, int16_t room_number, int16_t angle);
BITE_INFO claw_bite_left = { 19, -13, 3, 7 },
claw_bite_right = { 19, -13, 3, 4 };
void ClawmuteControl(int16_t item_number)
{
if (!CreatureActive(item_number))
return;
auto item = &items[item_number];
auto claw = (CREATURE_INFO*)item->data;
if (!claw)
return;
int16_t head = 0,
torso_y = 0,
torso_x = 0,
angle = 0,
tilt = 0;
if (item->hit_points <= 0)
{
if (item->current_anim_state != CLAW_DEATH)
{
item->anim_number = objects[item->object_number].anim_index + CLAW_DIE_ANIM;
item->frame_number = anims[item->anim_number].frame_base;
item->current_anim_state = CLAW_DEATH;
}
if (item->frame_number == anims[item->anim_number].frame_end - 1)
{
CreatureDie(item_number, true);
TriggerExplosionSparks(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 3, -2, 2, 0);
for (int i = 0; i < 2; ++i)
TriggerExplosionSparks(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 3, -1, 2, 0);
g_audio->play_sound(106, { item->pos.x_pos, item->pos.y_pos, item->pos.z_pos });
return;
}
}
else
{
AI_INFO info,
lara_info;
if (item->ai_bits)
GetAITarget(claw);
CreatureAIInfo(item, &info);
if (claw->enemy == lara_item)
{
lara_info.angle = info.angle;
lara_info.distance = info.distance;
}
else
{
int lara_dz = lara_item->pos.z_pos - item->pos.z_pos,
lara_dx = lara_item->pos.x_pos - item->pos.x_pos;
lara_info.angle = phd_atan(lara_dz, lara_dx) - item->pos.y_rot;
lara_info.distance = lara_dz * lara_dz + lara_dx * lara_dx;
}
if (info.zone_number == info.enemy_zone)
{
GetCreatureMood(item, &info, VIOLENT);
CreatureMood(item, &info, VIOLENT);
}
else
{
GetCreatureMood(item, &info, TIMID);
CreatureMood(item, &info, TIMID);
}
angle = CreatureTurn(item, claw->maximum_turn);
auto real_enemy = claw->enemy;
claw->enemy = lara_item;
if (lara_info.distance < CLAW_AWARE_DISTANCE || item->hit_status || TargetVisible(item, &lara_info))
AlertAllGuards(item_number);
claw->enemy = real_enemy;
switch (item->current_anim_state)
{
case CLAW_STOP:
{
claw->maximum_turn = 0;
claw->flags = 0;
head = info.angle;
if (item->ai_bits & GUARD)
{
head = AIGuard(claw);
item->goal_anim_state = CLAW_STOP;
}
else if (item->ai_bits & PATROL1)
{
item->goal_anim_state = CLAW_WALK;
head = 0;
}
else if (claw->mood == ESCAPE_MOOD)
item->goal_anim_state = CLAW_RUN;
else if (info.bite && info.distance < CLAW_ATTACK1_RANGE)
{
torso_y = info.angle;
torso_x = info.x_angle;
item->goal_anim_state = (info.angle < 0 ? CLAW_SLASH_LEFT : CLAW_SLASH_RIGHT);
}
else if (info.bite && info.distance < CLAW_ATTACK3_RANGE)
{
torso_y = info.angle;
torso_x = info.x_angle;
item->goal_anim_state = CLAW_CLAW_ATAK;
}
else if (Targetable(item, &info) && ((info.distance > CLAW_FIRE_RANGE && !item->item_flags[0]) || info.zone_number != info.enemy_zone))
item->goal_anim_state = CLAW_FIRE_ATAK;
else if (claw->mood == BORED_MOOD)
item->goal_anim_state = CLAW_WALK;
else if (item->required_anim_state)
item->goal_anim_state = item->required_anim_state;
else item->goal_anim_state = CLAW_RUN;
break;
}
case CLAW_WALK:
{
claw->maximum_turn = CLAW_WALK_TURN;
if (info.ahead)
head = info.angle;
if (item->ai_bits & PATROL1)
{
item->goal_anim_state = CLAW_WALK;
head = 0;
}
else if (info.bite && info.distance < CLAW_ATTACK3_RANGE)
{
claw->maximum_turn = CLAW_WALK_TURN;
item->goal_anim_state = (info.angle < 0 ? CLAW_WALK_ATAK1 : CLAW_WALK_ATAK2);
}
else if (Targetable(item, &info) && ((info.distance > CLAW_FIRE_RANGE && !item->item_flags[0]) || info.zone_number != info.enemy_zone))
{
claw->maximum_turn = CLAW_WALK_TURN;
item->goal_anim_state = CLAW_STOP;
}
else if (claw->mood == ESCAPE_MOOD || claw->mood == ATTACK_MOOD)
item->goal_anim_state = CLAW_RUN;
break;
}
case CLAW_RUN:
{
claw->maximum_turn = CLAW_RUN_TURN;
if (info.ahead)
head = info.angle;
if (item->ai_bits & GUARD)
item->goal_anim_state = CLAW_STOP;
else if (claw->mood == BORED_MOOD)
item->goal_anim_state = CLAW_STOP;
else if (claw->flags && info.ahead)
item->goal_anim_state = CLAW_STOP;
else if (info.bite && info.distance < CLAW_ATTACK2_RANGE)
item->goal_anim_state = (lara_item->speed == 0 ? CLAW_STOP : CLAW_RUN_ATAK);
else if (Targetable(item, &info) && ((info.distance > CLAW_FIRE_RANGE && !item->item_flags[0]) || info.zone_number != info.enemy_zone))
{
claw->maximum_turn = CLAW_WALK_TURN;
item->goal_anim_state = CLAW_STOP;
}
claw->flags = 0;
break;
}
case CLAW_WALK_ATAK1:
case CLAW_WALK_ATAK2:
case CLAW_SLASH_LEFT:
case CLAW_SLASH_RIGHT:
case CLAW_CLAW_ATAK:
case CLAW_RUN_ATAK:
{
if (info.ahead)
{
torso_y = info.angle;
torso_x = info.x_angle;
}
if (!claw->flags && (item->touch_bits & CLAW_TOUCH))
{
lara_item->hit_status = 1;
lara_item->hit_points -= CLAW_BITE_DAMAGE;
CreatureEffect(item, &claw_bite_left, DoBloodSplat);
CreatureEffect(item, &claw_bite_right, DoBloodSplat);
claw->flags = 1;
}
item->item_flags[0] = 0;
break;
}
case CLAW_FIRE_ATAK:
{
if (abs(info.angle) < CLAW_WALK_TURN)
item->pos.y_rot += info.angle;
else if (info.angle < 0)
item->pos.y_rot -= CLAW_WALK_TURN;
else item->pos.y_rot += CLAW_WALK_TURN;
if (info.ahead)
{
torso_y = info.angle >> 1;
torso_x = info.x_angle;
}
if (item->frame_number == anims[item->anim_number].frame_base && !(GetRandomControl() & 0x3))
item->item_flags[0] = 1;
if (item->frame_number - anims[item->anim_number].frame_base < 28)
TriggerPlasma(item_number);
else if (item->frame_number - anims[item->anim_number].frame_base == 28)
TriggerPlasmaBall(item, 0, nullptr, item->room_number, item->pos.y_rot);
{
int bright = item->frame_number - anims[item->anim_number].frame_base;
if (bright > 16)
if ((bright = anims[item->anim_number].frame_base + 28 + 16 - item->frame_number) > 16)
bright = 16;
if (bright > 0)
{
int rnd = GetRandomControl(),
r = ((rnd & 7) * bright) >> 4,
g = ((24 - ((rnd >> 6) & 3)) * bright) >> 4,
b = ((31 - ((rnd >> 4) & 3)) * bright) >> 4;
PHD_VECTOR pos { -32, -16, -192 };
GetJointAbsPosition(item, &pos, 13);
TriggerDynamicLight(pos.x, pos.y, pos.z, 13, r, g, b);
}
}
}
}
}
CreatureTilt(item, tilt);
CreatureJoint(item, 0, torso_x);
CreatureJoint(item, 1, torso_y);
CreatureJoint(item, 2, head);
CreatureAnimation(item_number, angle, tilt);
}
void TriggerPlasma(int16_t item_number)
{
int dx = lara_item->pos.x_pos - items[item_number].pos.x_pos,
dz = lara_item->pos.z_pos - items[item_number].pos.z_pos;
if (g_effects_draw_distance != -1 && (dx < -g_effects_draw_distance || dx > g_effects_draw_distance || dz < -g_effects_draw_distance || dz > g_effects_draw_distance))
return;
auto sptr = &spark[GetFreeSpark()];
int size = (GetRandomControl() & 31) + 64;
sptr->On = 1;
sptr->sB = 255;
sptr->sG = 48 + (GetRandomControl() & 31);
sptr->sR = 48;
sptr->dB = 192 + (GetRandomControl() & 63);
sptr->dG = 128 + (GetRandomControl() & 63);
sptr->dR = 32;
sptr->ColFadeSpeed = 12 + (GetRandomControl() & 3);
sptr->FadeToBlack = 8;
sptr->sLife = sptr->Life = (GetRandomControl() & 7) + 24;
sptr->TransType = COLADD;
sptr->extras = 0;
sptr->Dynamic = -1;
sptr->x = ((GetRandomControl() & 15) - 8);
sptr->y = 0;
sptr->z = ((GetRandomControl() & 15) - 8);
sptr->Xvel = ((GetRandomControl() & 31) - 16);
sptr->Yvel = (GetRandomControl() & 15) + 16;
sptr->Zvel = ((GetRandomControl() & 31) - 16);
sptr->Friction = 3;
if (GetRandomControl() & 1)
{
sptr->Flags = SP_SCALE | SP_DEF | SP_ROTATE | SP_EXPDEF | SP_ITEM | SP_NODEATTATCH;
sptr->RotAng = GetRandomControl() & 4095;
sptr->RotAdd = ((GetRandomControl() & 1) ? -(GetRandomControl() & 15) - 16 : (GetRandomControl() & 15) + 16);
}
else sptr->Flags = SP_SCALE | SP_DEF | SP_EXPDEF | SP_ITEM | SP_NODEATTATCH;
sptr->Gravity = (GetRandomControl() & 31) + 16;
sptr->MaxYvel = (GetRandomControl() & 7) + 16;
sptr->FxObj = item_number;
sptr->NodeNumber = SPN_CLAWMUTEPLASMA;
sptr->Def = (PHDSPRITESTRUCT*)objects[EXPLOSION1].mesh_ptr;
sptr->Scalar = 1;
sptr->Width = sptr->sWidth = size;
sptr->Height = sptr->sHeight = size;
sptr->dWidth = size >> 2;
sptr->dHeight = size >> 2;
}
void TriggerPlasmaBallFlame(int16_t fx_number, long type, long xv, long yv, long zv)
{
int dx = lara_item->pos.x_pos - effects[fx_number].pos.x_pos,
dz = lara_item->pos.z_pos - effects[fx_number].pos.z_pos;
if (g_effects_draw_distance != -1 && (dx < -g_effects_draw_distance || dx > g_effects_draw_distance || dz < -g_effects_draw_distance || dz > g_effects_draw_distance))
return;
auto sptr = &spark[GetFreeSpark()];
int size = (GetRandomControl() & 31) + 64;
sptr->On = 1;
sptr->sB = 255;
sptr->sG = 48 + (GetRandomControl() & 31);
sptr->sR = 48;
sptr->dB = 192 + (GetRandomControl() & 63);
sptr->dG = 128 + (GetRandomControl() & 63);
sptr->dR = 32;
sptr->ColFadeSpeed = 12 + (GetRandomControl() & 3);
sptr->FadeToBlack = 8;
sptr->sLife = sptr->Life = (GetRandomControl() & 7) + 24;
sptr->TransType = COLADD;
sptr->extras = 0;
sptr->Dynamic = -1;
sptr->x = ((GetRandomControl() & 15) - 8);
sptr->y = 0;
sptr->z = ((GetRandomControl() & 15) - 8);
sptr->Xvel = xv + (GetRandomControl() & 255) - 128;
sptr->Yvel = yv;
sptr->Zvel = zv + (GetRandomControl() & 255) - 128;
sptr->Friction = 5;
if (GetRandomControl() & 1)
{
sptr->Flags = SP_SCALE | SP_DEF | SP_ROTATE | SP_EXPDEF | SP_FX;
sptr->RotAng = GetRandomControl() & 4095;
sptr->RotAdd = ((GetRandomControl() & 1) ? -(GetRandomControl() & 15) - 16 : (GetRandomControl() & 15) + 16);
}
else sptr->Flags = SP_SCALE | SP_DEF | SP_EXPDEF | SP_FX;
sptr->FxObj = fx_number;
sptr->Def = (PHDSPRITESTRUCT*)objects[EXPLOSION1].mesh_ptr;
sptr->Scalar = 1;
sptr->Width = sptr->sWidth = size;
sptr->Height = sptr->sHeight = size;
sptr->dWidth = size >> 2;
sptr->dHeight = size >> 2;
sptr->Gravity = sptr->MaxYvel = 0;
if (type == 0)
{
sptr->Yvel = (GetRandomControl() & 511) - 256;
sptr->Xvel <<= 1;
sptr->Zvel <<= 1;
sptr->Scalar = 2;
sptr->Friction = 5 | (5 << 4);
sptr->dWidth >>= 1;
sptr->dHeight >>= 1;
}
}
void TriggerPlasmaBall(ITEM_INFO* item, long type, PHD_VECTOR* pos1, int16_t room_number, int16_t angle)
{
PHD_VECTOR pos;
PHD_ANGLE_VEC angles;
int speed;
if (type == 0)
{
pos = { -32, -16, -192 };
GetJointAbsPosition(item, &pos, 13);
speed = (GetRandomControl() & 7) + 8;
angles = phd_GetVectorAngles({ lara_item->pos.x_pos - pos.x, lara_item->pos.y_pos - pos.y - 256, lara_item->pos.z_pos - pos.z });
angles.x = item->pos.y_rot;
}
else
{
pos = { pos1->x, pos1->y, pos1->z };
speed = (GetRandomControl() & 15) + 16;
angles.x = GetRandomControl() << 1;
angles.y = 0x2000;
}
if (auto fx_number = CreateEffect(room_number); fx_number != NO_ITEM)
{
auto fx = &effects[fx_number];
fx->pos.x_pos = pos.x;
fx->pos.y_pos = pos.y;
fx->pos.z_pos = pos.z;
fx->pos.y_rot = angles.x;
fx->pos.x_rot = angles.y;
fx->object_number = EXTRAFX1;
fx->speed = speed;
fx->fallspeed = 0;
fx->flag1 = type;
}
}
void ControlClawmutePlasmaBall(int16_t fx_number)
{
auto fx = &effects[fx_number];
int old_x = fx->pos.x_pos,
old_y = fx->pos.y_pos,
old_z = fx->pos.z_pos;
if (fx->speed < 384 && fx->flag1 == 0)
fx->speed += (fx->speed >> 3) + 4;
if (fx->flag1 == 1)
{
fx->fallspeed++;
if (fx->speed > 8)
fx->speed -= 2;
if (fx->pos.x_rot > -0x3c00)
fx->pos.x_rot -= 0x100;
}
int speed = (fx->speed * phd_cos(fx->pos.x_rot)) >> W2V_SHIFT;
fx->pos.z_pos += (speed * phd_cos(fx->pos.y_rot)) >> W2V_SHIFT;
fx->pos.x_pos += (speed * phd_sin(fx->pos.y_rot)) >> W2V_SHIFT;
fx->pos.y_pos += -((fx->speed * phd_sin(fx->pos.x_rot)) >> W2V_SHIFT) + fx->fallspeed;
if (wibble & 4)
TriggerPlasmaBallFlame(fx_number, fx->flag1, 0, fx->flag1 == 0 ? (abs(old_y - fx->pos.y_pos) << 3) : 0, 0);
auto room_number = fx->room_number;
auto floor = GetFloor(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, &room_number);
if (fx->pos.y_pos >= GetHeight(floor, fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos) ||
fx->pos.y_pos < GetCeiling(floor, fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos))
{
if (fx->flag1 == 0)
{
PHD_VECTOR pos { old_x, old_y, old_z };
for (int i = 0; i < (5 + (GetRandomControl() & 3)); ++i)
TriggerPlasmaBall(nullptr, 1, &pos, fx->room_number, fx->pos.y_rot);
}
KillEffect(fx_number);
return;
}
if (room[room_number].flags & UNDERWATER)
{
KillEffect(fx_number);
return;
}
if (ItemNearLara(lara_item, &fx->pos, 200) && fx->flag1 == 0)
{
PHD_VECTOR pos { fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos };
for (int i = 0; i < (3 + (GetRandomControl() & 1)); ++i)
TriggerPlasmaBall(nullptr, 1, &pos, fx->room_number, fx->pos.y_rot);
lara_item->hit_points -= CLAW_PLASMA_DAMAGE;
lara_item->hit_status = 1;
KillEffect(fx_number);
return;
}
if (room_number != fx->room_number)
EffectNewRoom(fx_number, lara_item->room_number);
uint8_t radtab[2] = { 13, 7 };
if (radtab[fx->flag1])
{
int rnd = GetRandomControl(),
b = 31 - ((rnd >> 4) & 3),
g = 24 - ((rnd >> 6) & 3),
r = rnd & 7;
TriggerDynamicLight(fx->pos.x_pos, fx->pos.y_pos, fx->pos.z_pos, radtab[fx->flag1], r, g, b);
}
} | 26.705989 | 167 | 0.648726 | Tonyx97 |
ad32728610e0ead04a587989b860f9c32b6e0ab6 | 3,308 | hpp | C++ | OpenSimRoot/src/export/ExportBaseClass.hpp | nb-e/OpenRootSim | aaa1cd18e94ebf613c28737842401daba3b8d5ef | [
"BSD-3-Clause"
] | 1 | 2021-08-03T00:52:58.000Z | 2021-08-03T00:52:58.000Z | OpenSimRoot/src/export/ExportBaseClass.hpp | nb-e/OpenRootSim | aaa1cd18e94ebf613c28737842401daba3b8d5ef | [
"BSD-3-Clause"
] | null | null | null | OpenSimRoot/src/export/ExportBaseClass.hpp | nb-e/OpenRootSim | aaa1cd18e94ebf613c28737842401daba3b8d5ef | [
"BSD-3-Clause"
] | 1 | 2021-08-03T00:52:59.000Z | 2021-08-03T00:52:59.000Z | /*
Copyright © 2016, The Pennsylvania State University
All rights reserved.
Copyright © 2016 Forschungszentrum Jülich GmbH
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted under the GNU General Public License v3 and provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
Disclaimer
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.
You should have received the GNU GENERAL PUBLIC LICENSE v3 with this file in license.txt but can also be found at http://www.gnu.org/licenses/gpl-3.0.en.html
NOTE: The GPL.v3 license requires that all derivative work is distributed under the same license. That means that if you use this source code in any other program, you can only distribute that program with the full source code included and licensed under a GPL license.
*/
/*
* SHORT DESCRIPTION: Base class for export modules. If you are writing an
* export module for simroot - you should inherit from this class and
*
*/
#ifndef EXPORTBASECLASS_HPP_
#define EXPORTBASECLASS_HPP_
#include "../engine/DataDefinitions.hpp"
#include <map>
#include <vector>
#include <set>
class SimulaBase;
//default export class
class ExportBase{
public:
ExportBase(std::string module);
virtual ~ExportBase();
virtual void initialize()=0;
virtual void run(const Time &t)=0;
virtual void finalize()=0;
std::string getName()const;
bool &enabled();
Time getStartTime()const;
Time getEndTime()const;
Time getIntervalTime()const;
Time &getCurrentTime();
Time getNextOutputTime();
protected:
std::string moduleName;
Time startTime, endTime, intervalTime, currentTime;
std::set<Time> outputTimes;
SimulaBase* controls;
bool runModule;
};
//global map for registration of export classes.
//typedefinition of instantiation function of rate objects
typedef ExportBase* (*exportBaseInstantiationFunction)();
//instantiation of map that lists all rate classes
extern std::map<std::string, exportBaseInstantiationFunction > exportBaseClassesMap;
typedef std::vector<ExportBase*> ModuleList;
#endif /*EXPORTBASECLASS_HPP_*/
| 49.373134 | 755 | 0.796856 | nb-e |
ad34ff41bef08907bfa1b5c76777f7f6632f4050 | 19,327 | cpp | C++ | Pesto/src/EditorLayer.cpp | Tamookk/Basil | bdcdf4e6e13e64a34416b4412d366594f9d46f56 | [
"Apache-2.0"
] | null | null | null | Pesto/src/EditorLayer.cpp | Tamookk/Basil | bdcdf4e6e13e64a34416b4412d366594f9d46f56 | [
"Apache-2.0"
] | null | null | null | Pesto/src/EditorLayer.cpp | Tamookk/Basil | bdcdf4e6e13e64a34416b4412d366594f9d46f56 | [
"Apache-2.0"
] | null | null | null | #include "EditorLayer.h"
#include "Core/Application.h"
#include "Math/Math.h"
#include "Scene/SceneSerializer.h"
#include "Utils/PlatfomUtils.h"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <imgui.h>
#include <ImGuizmo.h>
namespace Basil
{
extern const std::filesystem::path assetPath;
// Constructor
EditorLayer::EditorLayer() : Layer("Sandbox2D")
{
viewportFocused = false;
viewportHovered = false;
showPhysicsColliders = false;
gizmoType = -1;
sceneState = SceneState::Edit;
}
void EditorLayer::onAttach()
{
PROFILE_FUNCTION();
// Set play and stop icons
iconPlay = Texture2D::create("res/icons/editor_play_stop/play_button.png");
iconStop = Texture2D::create("res/icons/editor_play_stop/stop_button.png");
// Create framebuffer
FramebufferSpecification fbSpec;
fbSpec.attachments = { FramebufferTextureFormat::RGBA8, FramebufferTextureFormat::RED_INTEGER, FramebufferTextureFormat::Depth };
fbSpec.width = 1280;
fbSpec.height = 720;
framebuffer = Framebuffer::create(fbSpec);
// Create scene
activeScene = makeShared<Scene>();
auto commandLineArgs = Application::get().getCommandLineArgs();
if (commandLineArgs.count > 1)
{
auto sceneFilePath = commandLineArgs[1];
SceneSerializer serializer(activeScene);
serializer.deserialize(sceneFilePath);
}
// Set up editor camera
editorCamera = EditorCamera(30.0f, 1.778f, 0.1f, 1000.0f);
// Create square entities
auto square = activeScene->createEntity("Green Square");
square.addComponent<SpriteRendererComponent>(glm::vec4{ 0.0f, 1.0f, 0.0f, 1.0f });
squareEntity = square;
auto redSquare = activeScene->createEntity("Red Square");
redSquare.addComponent<SpriteRendererComponent>(glm::vec4{ 1.0f, 0.0f, 0.0f, 1.0f });
redSquare.getComponent<TransformComponent>().translation = { 0.0f, 1.0f, 0.0f };
cameraEntity = activeScene->createEntity("Camera");
cameraEntity.addComponent<CameraComponent>();
secondCameraEntity = activeScene->createEntity("Clip-Space Entity");
auto& cc = secondCameraEntity.addComponent<CameraComponent>();
cc.primary = false;
class CameraController : public ScriptableEntity
{
public:
void onCreate() override {}
void onDestroy() override {}
void onUpdate(Timestep timeStep) override
{
auto& translation = getComponent<TransformComponent>().translation;
float speed = 5.0f;
if (Input::isKeyPressed(KeyCode::A))
translation.x -= speed * timeStep;
if (Input::isKeyPressed(KeyCode::D))
translation.x += speed * timeStep;
if (Input::isKeyPressed(KeyCode::W))
translation.y += speed * timeStep;
if (Input::isKeyPressed(KeyCode::S))
translation.y -= speed * timeStep;
}
};
cameraEntity.addComponent<NativeScriptComponent>().bind<CameraController>();
propertiesPanel.setContext(activeScene);
sceneHierarchyPanel.setContext(activeScene);
}
void EditorLayer::onDetach()
{
PROFILE_FUNCTION();
}
void EditorLayer::onUpdate(Timestep timeStep)
{
// Start timer for onUpdate
PROFILE_FUNCTION();
// Stop flickering on resize
{
FramebufferSpecification spec = framebuffer->getSpecification();
if (viewportSize.x > 0.0f && viewportSize.y > 0.0f && (spec.width != viewportSize.x || spec.height != viewportSize.y))
{
framebuffer->resize((uint32_t)viewportSize.x, (uint32_t)viewportSize.y);
editorCamera.setViewportSize(viewportSize.x, viewportSize.y);
activeScene->onViewportResize((uint32_t)viewportSize.x, (uint32_t)viewportSize.y);
}
}
// Render
Renderer2D::resetStats();
{
PROFILE_SCOPE("Renderer Prep");
framebuffer->bind();
Renderer::setClearColor({ 0.1f, 0.1f, 0.1f, 1.0f });
Renderer::clear();
framebuffer->clearAttachment(1, -1);
}
// Update scene
{
PROFILE_SCOPE("Renderer Draw");
switch (sceneState)
{
case SceneState::Edit:
{
PROFILE_SCOPE("Editor Update");
editorCamera.onUpdate(timeStep);
activeScene->onUpdateEditor(timeStep, editorCamera);
break;
}
case SceneState::Play:
{
PROFILE_SCOPE("Play Update");
activeScene->onUpdateRuntime(timeStep);
break;
}
}
auto [mx, my] = ImGui::GetMousePos();
mx -= viewportBounds[0].x;
my -= viewportBounds[0].y;
glm::vec2 viewportSize = viewportBounds[1] - viewportBounds[0];
my = viewportSize.y - my;
int mouseX = (int)mx;
int mouseY = (int)my;
if (mouseX >= 0 && mouseY >= 0 && mouseX < (int)viewportSize.x && mouseY < (int)viewportSize.y)
{
int pixelData = framebuffer->readPixel(1, mouseX, mouseY);
hoveredEntity = pixelData == -1 ? Entity() : Entity((entt::entity)pixelData, activeScene.get());
}
// Render the overlay
onOverlayRender();
framebuffer->unbind();
}
}
void EditorLayer::onEvent(Event& e)
{
// Editor camera on event
editorCamera.onEvent(e);
// Dispatch key pressed event
EventDispatcher dispatcher(e);
dispatcher.dispatch<KeyPressedEvent>(BIND_EVENT(EditorLayer::onKeyPressed));
dispatcher.dispatch<MouseButtonPressedEvent>(BIND_EVENT(EditorLayer::onMouseButtonPressed));
}
void EditorLayer::onImGuiRender()
{
PROFILE_FUNCTION();
// Setup variables
static bool dockSpaceOpen = true;
static bool optFullscreenPersistant = true;
bool optFullscreen = optFullscreenPersistant;
static ImGuiDockNodeFlags dockSpaceFlags = ImGuiDockNodeFlags_None;
// Set flags
ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking;
// If fullscreen
if (optFullscreen)
{
// Setup fullscreen mode
ImGuiViewport* viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->Pos);
ImGui::SetNextWindowSize(viewport->Size);
ImGui::SetNextWindowViewport(viewport->ID);
ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
windowFlags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove;
windowFlags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
}
// Set some flags
if (dockSpaceFlags & ImGuiDockNodeFlags_PassthruCentralNode)
windowFlags |= ImGuiWindowFlags_NoBackground;
// Create the ImGui instance
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
ImGui::Begin("DockSpace Demo", &dockSpaceOpen, windowFlags);
ImGui::PopStyleVar();
if (optFullscreen)
ImGui::PopStyleVar(2);
ImGuiIO& io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle();
float minWinSizeX = style.WindowMinSize.x;
style.WindowMinSize.x = 370.0f;
if (io.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
ImGuiID dockspaceID = ImGui::GetID("MyDockspace");
ImGui::DockSpace(dockspaceID, ImVec2(0.0f, 0.0f), dockSpaceFlags);
}
style.WindowMinSize.x = minWinSizeX;
// Menu bar
if (ImGui::BeginMenuBar())
{
if (ImGui::BeginMenu("File"))
{
// New scene
if (ImGui::MenuItem("New", "Ctrl+N"))
newScene();
// Open scene file
if (ImGui::MenuItem("Open...", "Ctrl+O"))
openScene();
// Save scene file
if (ImGui::MenuItem("Save...", "Ctrl+S"))
saveScene();
// Save scene file as
if (ImGui::MenuItem("Save As...", "Ctrl+Shift+S"))
saveSceneAs();
// Exit application
if (ImGui::MenuItem("Exit"))
Application::get().close();
ImGui::EndMenu();
}
ImGui::EndMenuBar();
}
// Content browser panel
contentBrowserPanel.onImGuiRender();
// Scene hierarchy panel
sceneHierarchyPanel.onImGuiRender();
// Properties panel
propertiesPanel.onImGuiRender(sceneHierarchyPanel.getSelectedEntity());
// Stats panel
ImGui::Begin("Stats");
Renderer2D::Statistics stats = Renderer2D::getStats();
ImGui::Text("Renderer2D Stats:");
ImGui::Text("Draw Calls: %d", stats.drawCalls);
ImGui::Text("Quads: %d", stats.quadCount);
ImGui::Text("Vertices: %d", stats.getTotalVertexCount());
ImGui::Text("Indices: %d", stats.getTotalIndexCount());
ImGui::End();
// Settings panel
ImGui::Begin("Settings");
ImGui::Checkbox("Show Physics Colliders", &showPhysicsColliders);
ImGui::End();
// Viewport
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, { 0, 0 });
ImGui::Begin("Viewport");
auto viewportMinRegion = ImGui::GetWindowContentRegionMin();
auto viewportMaxRegion = ImGui::GetWindowContentRegionMax();
auto viewportOffset = ImGui::GetWindowPos();
viewportBounds[0] = { viewportMinRegion.x + viewportOffset.x, viewportMinRegion.y + viewportOffset.y };
viewportBounds[1] = { viewportMaxRegion.x + viewportOffset.x, viewportMaxRegion.y + viewportOffset.y };
viewportFocused = ImGui::IsWindowFocused();
viewportHovered = ImGui::IsWindowHovered();
Application::get().getImGuiLayer()->setBlockEvents(!viewportFocused && !viewportHovered);
ImVec2 viewportPanelSize = ImGui::GetContentRegionAvail();
viewportSize = { viewportPanelSize.x, viewportPanelSize.y };
uint64_t textureID = framebuffer->getColorAttachmentRendererID();
ImGui::Image(reinterpret_cast<void*>(textureID), viewportPanelSize, ImVec2{ 0, 1 }, ImVec2{ 1, 0 });
// Accept drag and drop data from the Content Browser panel (currently a scene file)
if (ImGui::BeginDragDropTarget())
{
if (const ImGuiPayload* data = ImGui::AcceptDragDropPayload("CONTENT_BROWSER_ITEM"))
{
const wchar_t* path = (const wchar_t*)data->Data;
// Open a scene
openScene(std::filesystem::path(assetPath) / path);
}
ImGui::EndDragDropTarget();
}
// Gizmos
Entity selectedEntity = sceneHierarchyPanel.getSelectedEntity();
if (selectedEntity && gizmoType != -1)
{
ImGuizmo::SetOrthographic(false);
ImGuizmo::SetDrawlist();
// Set rect size
ImGuizmo::SetRect(viewportBounds[0].x, viewportBounds[0].y, viewportBounds[1].x - viewportBounds[0].x, viewportBounds[1].y - viewportBounds[0].y);
// Set camera (runtime camera from entity)
//auto cameraEntity = activeScene->getPrimaryCameraEntity();
//const auto& camera = cameraEntity.getComponent<CameraComponent>().camera;
//const glm::mat4& cameraProjection = camera.getProjection();
//glm::mat4 cameraView = glm::inverse(cameraEntity.getComponent<TransformComponent>().getTransform());
// Editor camera
const glm::mat4& cameraProjection = editorCamera.getProjection();
glm::mat4 cameraView = editorCamera.getViewMatrix();
// Entity transform
auto& tc = selectedEntity.getComponent<TransformComponent>();
glm::mat4 transform = tc.getTransform();
// Snapping
bool snap = Input::isKeyPressed(Key::LeftControl);
float snapValue = 0.5f;
if (gizmoType == ImGuizmo::OPERATION::ROTATE)
snapValue = 45.0f;
float snapValues[3] = { snapValue, snapValue, snapValue };
ImGuizmo::Manipulate(glm::value_ptr(cameraView), glm::value_ptr(cameraProjection), (ImGuizmo::OPERATION)gizmoType,
ImGuizmo::LOCAL, glm::value_ptr(transform), nullptr, snap ? snapValues : nullptr);
if (ImGuizmo::IsUsing())
{
glm::vec3 translation, rotation, scale;
Math::decomposeTransform(transform, translation, rotation, scale);
glm::vec3 deltaRotation = rotation - tc.rotation;
tc.translation = translation;
tc.rotation += deltaRotation;
tc.scale = scale;
}
}
ImGui::End();
ImGui::PopStyleVar();
UI_Toolbar();
ImGui::End();
}
// On key pressed function
bool EditorLayer::onKeyPressed(KeyPressedEvent& e)
{
// Shortcuts
if (e.getRepeatCount() > 0)
return false;
bool control = Input::isKeyPressed(Key::LeftControl) || Input::isKeyPressed(Key::RightControl);
bool shift = Input::isKeyPressed(Key::LeftShift) || Input::isKeyPressed(Key::RightShift);
switch (e.getKeycode())
{
case (int)Key::N:
if (control)
newScene();
break;
case (int)Key::O:
if (control)
openScene();
break;
case (int)Key::S:
if (control)
if (shift)
saveSceneAs();
else
saveScene();
break;
case (int)Key::D:
if (control)
onDuplicateEntity();
break;
// Gizmos
case (int)Key::Q:
if(!ImGuizmo::IsUsing())
gizmoType = -1;
break;
case (int)Key::W:
if (!ImGuizmo::IsUsing())
gizmoType = ImGuizmo::OPERATION::TRANSLATE;
break;
case (int)Key::E:
if (!ImGuizmo::IsUsing())
gizmoType = ImGuizmo::OPERATION::ROTATE;
break;
case (int)Key::R:
if (!ImGuizmo::IsUsing())
gizmoType = ImGuizmo::OPERATION::SCALE;
break;
}
return false;
}
// On mouse button pressed function
bool EditorLayer::onMouseButtonPressed(MouseButtonPressedEvent& e)
{
if (e.getMouseButton() == (int)Mouse::ButtonLeft)
{
if (viewportHovered && !ImGuizmo::IsOver() && !Input::isKeyPressed(Key::LeftAlt))
sceneHierarchyPanel.setSelectedEntity(hoveredEntity);
}
return false;
}
// On overlay render function
void EditorLayer::onOverlayRender()
{
// Start a new batch to render physics colliders
if (sceneState == SceneState::Play)
{
Entity camera = activeScene->getPrimaryCameraEntity();
Renderer2D::beginScene(camera.getComponent<CameraComponent>().camera, camera.getComponent<TransformComponent>().getTransform());
}
else
{
Renderer2D::beginScene(editorCamera);
}
// If visualising physics colliders is enabled
if (showPhysicsColliders)
{
// Render box colliders
{
PROFILE_SCOPE("Render Box Colliders");
// Get all components with box collider 2D components
auto view = activeScene->getAllEntitiesWith<TransformComponent, BoxCollider2DComponent>();
for (auto entity : view)
{
// Get the transform and box collider 2D components for the entity
auto [tc, bc2d] = view.get<TransformComponent, BoxCollider2DComponent>(entity);
// Calculate the translation, scale, and transform of the box collider
glm::vec3 translation = tc.translation + glm::vec3(bc2d.offset, 0.001f);
glm::vec3 scale = tc.scale * glm::vec3(bc2d.size * 2.0f, 1.0f);
glm::mat4 transform = glm::translate(glm::mat4(1.0f), translation)
* glm::rotate(glm::mat4(1.0f), tc.rotation.z, glm::vec3(0.0f, 0.0f, 1.0f))
* glm::scale(glm::mat4(1.0f), scale);
// Render the box collider visualisation
Renderer2D::drawRect(transform, glm::vec4(0, 1, 0, 1));
}
}
// Render circle colliders
{
PROFILE_SCOPE("Render Circle Colliders");
// Get all components with circle collider 2D components
auto view = activeScene->getAllEntitiesWith<TransformComponent, CircleCollider2DComponent>();
for (auto entity : view)
{
// Get the transform and circle collider 2D components for the entity
auto [tc, cc2d] = view.get<TransformComponent, CircleCollider2DComponent>(entity);
// Calculate the translation, scale, and transform of the box collider
glm::vec3 translation = tc.translation + glm::vec3(cc2d.offset, 0.001f);
glm::vec3 scale = tc.scale * glm::vec3(cc2d.radius * 2.0f);
glm::mat4 transform = glm::translate(glm::mat4(1.0f), translation)
* glm::scale(glm::mat4(1.0f), scale);
// Render the circle collider visualisation
Renderer2D::drawCircle(transform, glm::vec4(0, 1, 0, 1), 0.01f);
}
}
}
// Finish the batch
Renderer2D::endScene();
}
// Make a new scene
void EditorLayer::newScene()
{
activeScene = makeShared<Scene>();
activeScene->onViewportResize((uint32_t)viewportSize.x, (uint32_t)viewportSize.y);
sceneHierarchyPanel.setContext(activeScene);
editorScenePath = std::filesystem::path();
}
// Open a scene
void EditorLayer::openScene()
{
std::string filePath = FileDialogs::openFile("Basil Scene (*.scene)\0*.scene\0");
if (!filePath.empty())
openScene(filePath);
}
// Open a scene (with a given file path)
void EditorLayer::openScene(const std::filesystem::path path)
{
// Close scene if it is playing
if (sceneState != SceneState::Edit)
onSceneStop();
if (path.extension().string() != ".scene")
{
LOG_WARN("Could not load {0} - not a scene file", path.filename().string());
return;
}
Shared<Scene> newScene = makeShared<Scene>();
SceneSerializer serializer(newScene);
if (serializer.deserialize(path.string()))
{
editorScene = newScene;
editorScene->onViewportResize((uint32_t)viewportSize.x, (uint32_t)viewportSize.y);
sceneHierarchyPanel.setContext(editorScene);
activeScene = editorScene;
editorScenePath = path;
}
}
// Save a scene
void EditorLayer::saveScene()
{
if (!editorScenePath.empty())
serializeScene(activeScene, editorScenePath);
else
saveSceneAs();
}
// Save a scene as
void EditorLayer::saveSceneAs()
{
std::string filePath = FileDialogs::saveFile("Basil Scene (*.scene)\0*.scene\0");
if (!filePath.empty())
{
serializeScene(activeScene, filePath);
editorScenePath = filePath;
}
}
// Serialize a scene
void EditorLayer::serializeScene(Shared<Scene> scene, const std::filesystem::path& path)
{
SceneSerializer serializer(scene);
serializer.serialize(path.string());
}
// When the scene plays
void EditorLayer::onScenePlay()
{
sceneState = SceneState::Play;
activeScene = Scene::copy(editorScene);
activeScene->onRuntimeStart();
sceneHierarchyPanel.setContext(activeScene);
}
// When the scene stops
void EditorLayer::onSceneStop()
{
sceneState = SceneState::Edit;
activeScene->onRuntimeStop();
activeScene = editorScene;
sceneHierarchyPanel.setContext(activeScene);
}
// When an entity is duplicated
void EditorLayer::onDuplicateEntity()
{
if (sceneState != SceneState::Edit)
return;
Entity selectedEntity = sceneHierarchyPanel.getSelectedEntity();
if (selectedEntity)
editorScene->duplicateEntity(selectedEntity);
}
// -- UI -- //
// Create the UI toolbar
void EditorLayer::UI_Toolbar()
{
// Push style
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 2));
ImGui::PushStyleVar(ImGuiStyleVar_ItemInnerSpacing, ImVec2(0, 0));
ImGui::PushStyleColor(ImGuiCol_Button, ImVec4(0, 0, 0, 0));
auto& colors = ImGui::GetStyle().Colors;
const auto& buttonHoveredColor = colors[ImGuiCol_ButtonHovered];
ImGui::PushStyleColor(ImGuiCol_ButtonHovered, ImVec4(buttonHoveredColor.x, buttonHoveredColor.y, buttonHoveredColor.z, 0.5f));
const auto& buttonActiveColor = colors[ImGuiCol_ButtonActive];
ImGui::PushStyleColor(ImGuiCol_ButtonActive, ImVec4(buttonActiveColor.x, buttonActiveColor.y, buttonActiveColor.z, 0.5f));
// Create toolbar flags
int toolbarFlags = ImGuiWindowFlags_NoDecoration | ImGuiWindowFlags_NoScrollbar;
toolbarFlags |= ImGuiWindowFlags_NoScrollWithMouse;
// Begin toolbar
ImGui::Begin("##Toolbar", nullptr, toolbarFlags);
// Set button size and icon
float size = ImGui::GetWindowHeight() - 4;
Shared<Texture2D> icon = sceneState == SceneState::Edit ? iconPlay : iconStop;
ImGui::SetCursorPosX((ImGui::GetWindowContentRegionMax().x * 0.5) - (size * 0.5));
// If button pressed
if (ImGui::ImageButton((ImTextureID)icon->getRendererID(), ImVec2(size, size), ImVec2(0, 0), ImVec2(1, 1), 0))
{
if (sceneState == SceneState::Edit)
onScenePlay();
else if (sceneState == SceneState::Play)
onSceneStop();
}
// End toolbar
ImGui::PopStyleVar(2);
ImGui::PopStyleColor(3);
ImGui::End();
}
} | 29.551988 | 149 | 0.699384 | Tamookk |
ad35292af1d0299a74c438036ecdb3f975a4beb3 | 3,712 | cpp | C++ | engine/screens/source/EquipmentScreen.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 60 | 2019-08-21T04:08:41.000Z | 2022-03-10T13:48:04.000Z | engine/screens/source/EquipmentScreen.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 3 | 2021-03-18T15:11:14.000Z | 2021-10-20T12:13:07.000Z | engine/screens/source/EquipmentScreen.cpp | prolog/shadow-of-the-wyrm | a1312c3e9bb74473f73c4e7639e8bd537f10b488 | [
"MIT"
] | 8 | 2019-11-16T06:29:05.000Z | 2022-01-23T17:33:43.000Z | #include "Conversion.hpp"
#include "EquipmentScreen.hpp"
#include "EquipmentTextKeys.hpp"
#include "EquipmentTranslator.hpp"
#include "Game.hpp"
#include "OptionsComponent.hpp"
#include "PromptTextKeys.hpp"
#include "TextComponent.hpp"
#include "TextKeys.hpp"
using namespace std;
EquipmentScreen::EquipmentScreen(DisplayPtr new_display, CreaturePtr new_creature)
: Screen(new_display), creature(new_creature)
{
initialize();
}
// Initialize the equipment screen, showing the user the list of eq
// slots and displaying further information in the inventory prompt.
void EquipmentScreen::initialize()
{
vector<ScreenComponentPtr> eq_screen;
// Set the title information
title_text_sid = TextKeys::EQUIPMENT;
// Create the various options and text
int current_id = 0;
DisplayEquipmentMap dem = EquipmentTranslator::create_display_equipment(creature);
uint longest = 0;
for (DisplayEquipmentMap::const_iterator e_it = dem.begin(); e_it != dem.end(); e_it++)
{
EquipmentWornLocation worn_location = e_it->first;
string worn_location_name = EquipmentTextKeys::get_equipment_text_from_given_worn_location(worn_location);
if (worn_location_name.size() > longest) longest = worn_location_name.size() + 1;
}
for (DisplayEquipmentMap::const_iterator e_it = dem.begin(); e_it != dem.end(); e_it++)
{
ostringstream ss;
EquipmentWornLocation worn_location = e_it->first;
DisplayItem display_item = e_it->second;
Colour item_colour = display_item.get_colour();
string worn_location_name = EquipmentTextKeys::get_equipment_text_from_given_worn_location(worn_location);
string item_description = display_item.get_description();
ss << String::add_trailing_spaces(worn_location_name, longest) << ": ";
vector<pair<string, Colour>> flags = display_item.get_flags();
OptionsComponentPtr options = std::make_shared<OptionsComponent>();
Option current_option;
TextComponentPtr option_text_component = current_option.get_description();
option_text_component->add_text(ss.str());
option_text_component->add_text(item_description, item_colour);
for (const TextColour& flag_pair : flags)
{
ostringstream flag_ss;
flag_ss << " ";
Colour colour = flag_pair.second;
flag_ss << flag_pair.first;
option_text_component->add_text(flag_ss.str(), colour);
}
current_option.set_id(current_id);
options->add_option(current_option);
options->add_option_description("");
current_id++;
eq_screen.push_back(options);
string res_abrv = StringTable::get(EquipmentTextKeys::EQUIPMENT_RESISTS_FLAGS);
string item_addl_desc;
string di_addl_desc = display_item.get_additional_description();
String::reset_and_pad(item_addl_desc, 6 /* 6 = extra padding for '[a] : ' */);
// Only show the resistances abbreviation if the item's got anything...
if (!di_addl_desc.empty())
{
ostringstream ss;
ss << String::add_trailing_spaces(res_abrv, longest) << ": " << di_addl_desc;
di_addl_desc = ss.str();
}
item_addl_desc += di_addl_desc;
TextComponentPtr eq_text = std::make_shared<TextComponent>(item_addl_desc, Colour::COLOUR_BOLD_YELLOW);
eq_screen.push_back(eq_text);
}
// Enable the equipment screen
add_page(eq_screen);
// Set the prompt
PromptPtr eq_prompt = std::make_unique<Prompt>(PromptLocation::PROMPT_LOCATION_LOWER_RIGHT);
// Accept any input - the equipment manager will take care of sorting out
// what's a valid command and what is not.
eq_prompt->set_accept_any_input(true);
eq_prompt->set_text_sid(PromptTextKeys::PROMPT_EQUIPMENT);
user_prompt = std::move(eq_prompt);
line_increment = 1;
}
| 33.142857 | 110 | 0.739763 | prolog |
ad392c4204e6794d3d7960ac0f35c44a5daf9403 | 1,213 | cpp | C++ | Arc/src/Arc/Renderer/EditorCamera.cpp | MohitSethi99/AGE | 4291ebeaa4af5b60518bc55eae079fd2cfe55d8f | [
"Apache-2.0"
] | null | null | null | Arc/src/Arc/Renderer/EditorCamera.cpp | MohitSethi99/AGE | 4291ebeaa4af5b60518bc55eae079fd2cfe55d8f | [
"Apache-2.0"
] | null | null | null | Arc/src/Arc/Renderer/EditorCamera.cpp | MohitSethi99/AGE | 4291ebeaa4af5b60518bc55eae079fd2cfe55d8f | [
"Apache-2.0"
] | null | null | null | #include "arcpch.h"
#include "EditorCamera.h"
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/gtx/quaternion.hpp>
namespace ArcEngine
{
EditorCamera::EditorCamera(float fov, float aspectRatio, float nearClip, float farClip)
: m_Fov(fov), m_AspectRatio(aspectRatio), m_NearClip(nearClip), m_FarClip(farClip), Camera(glm::perspective(glm::radians(fov), aspectRatio, nearClip, farClip))
{
}
void EditorCamera::OnUpdate(Timestep timestep)
{
ARC_PROFILE_SCOPE();
float cosYaw = glm::cos(glm::radians(m_Yaw));
float sinYaw = glm::sin(glm::radians(m_Yaw));
float cosPitch = glm::cos(glm::radians(m_Pitch));
float sinPitch = glm::sin(glm::radians(m_Pitch));
m_Forward.x = cosYaw * cosPitch;
m_Forward.y = sinPitch;
m_Forward.z = sinYaw * cosPitch;
m_Forward = glm::normalize(m_Forward);
m_Right = glm::normalize(glm::cross(m_Forward, {0, 1, 0}));
m_Up = glm::normalize(glm::cross(m_Right, m_Forward));
m_ViewMatrix = glm::lookAt(m_Position, m_Position + m_Forward, m_Up);
}
void EditorCamera::SetViewportSize(float width, float height)
{
ARC_PROFILE_SCOPE();
m_AspectRatio = width / height;
m_Projection = glm::perspective(m_Fov, m_AspectRatio, m_NearClip, m_FarClip);
}
}
| 28.880952 | 161 | 0.727947 | MohitSethi99 |
ad40256c053577a8bbb2d49273a2a3265ecf901c | 655 | cpp | C++ | application/robotcontrol.cpp | hcmarchezi/manipulator-robot-api | 6ec50278496b10d3b31557f92f62d1521edefa2a | [
"MIT"
] | null | null | null | application/robotcontrol.cpp | hcmarchezi/manipulator-robot-api | 6ec50278496b10d3b31557f92f62d1521edefa2a | [
"MIT"
] | null | null | null | application/robotcontrol.cpp | hcmarchezi/manipulator-robot-api | 6ec50278496b10d3b31557f92f62d1521edefa2a | [
"MIT"
] | null | null | null | #include "robotcontrol.h"
#include <QLabel>
#include <QMessageBox>
#include <iostream>
namespace HIC
{
RobotControl::RobotControl(QWidget *parent) : QWidget(parent), _glWidget(NULL)
{
this->setLayout(new QVBoxLayout(this));
}
void RobotControl::setGLWidget(HIC::ApplicationGLWidget* glWidget)
{
_glWidget = glWidget;
PDC::Robot* robot = _glWidget->robot();
for(int index=0; index < robot->LinkCount(); index++)
{
PDC::Link* link = robot->GetLink(index);
HIC::JointControl* jointControl = new HIC::JointControl(this, link, _glWidget);
this->layout()->addWidget(jointControl);
}
}
} // namespace HIC
| 20.46875 | 87 | 0.674809 | hcmarchezi |
ad42adce43dc6195ea01496eb87eca5dde246f17 | 4,403 | cpp | C++ | globe/globe_overlay.cpp | MarkY-LunarG/LunarGlobe | d32a6145eebc68ad4d7e28bdd4fab88cbdd33545 | [
"Apache-2.0"
] | 2 | 2018-06-20T15:19:38.000Z | 2018-07-13T15:13:30.000Z | globe/globe_overlay.cpp | MarkY-LunarG/LunarGlobe | d32a6145eebc68ad4d7e28bdd4fab88cbdd33545 | [
"Apache-2.0"
] | 25 | 2018-07-27T23:02:01.000Z | 2019-03-15T17:00:05.000Z | globe/globe_overlay.cpp | MarkY-LunarG/LunarGravity | d32a6145eebc68ad4d7e28bdd4fab88cbdd33545 | [
"Apache-2.0"
] | null | null | null | //
// Project: LunarGlobe
// SPDX-License-Identifier: Apache-2.0
//
// File: globe/globe_overlay.hpp
// Copyright(C): 2019; LunarG, Inc.
// Author(s): Mark Young <[email protected]>
//
#include "globe_resource_manager.hpp"
#include "globe_submit_manager.hpp"
#include "globe_font.hpp"
#include "globe_overlay.hpp"
GlobeOverlay::GlobeOverlay(GlobeResourceManager* resource_manager, GlobeSubmitManager* submit_manager,
VkDevice vk_device)
: _resource_mgr(resource_manager),
_submit_mgr(submit_manager),
_vk_device(vk_device),
_vk_render_pass(VK_NULL_HANDLE) {}
GlobeOverlay::~GlobeOverlay() {
for (const auto font_element : _fonts) {
font_element.second->UnloadFromRenderPass();
_resource_mgr->FreeFont(font_element.second);
}
}
void GlobeOverlay::UpdateViewport(float viewport_width, float viewport_height) {
_viewport_width = viewport_width;
_viewport_height = viewport_height;
}
bool GlobeOverlay::SetRenderPass(VkRenderPass render_pass) {
if (VK_NULL_HANDLE != _vk_render_pass || VK_NULL_HANDLE == render_pass) {
for (const auto font_element : _fonts) {
font_element.second->UnloadFromRenderPass();
}
}
_vk_render_pass = render_pass;
if (VK_NULL_HANDLE != render_pass) {
for (const auto font_element : _fonts) {
font_element.second->LoadIntoRenderPass(_vk_render_pass, _viewport_width, _viewport_height);
}
}
return true;
}
bool GlobeOverlay::LoadFont(const std::string& font_name, float max_height) {
auto font_present = _fonts.find(font_name);
if (font_present == _fonts.end()) {
_fonts[font_name] = _resource_mgr->LoadFontMap(font_name, max_height);
if (VK_NULL_HANDLE != _vk_render_pass) {
_fonts[font_name]->LoadIntoRenderPass(_vk_render_pass, _viewport_width, _viewport_height);
}
} else if (font_present->second->Size() < max_height) {
_resource_mgr->FreeFont(font_present->second);
_fonts[font_name] = _resource_mgr->LoadFontMap(font_name, max_height);
}
return (_fonts[font_name] != nullptr);
}
int32_t GlobeOverlay::AddScreenSpaceStaticText(const std::string& font_name, float font_height, float x, float y,
const glm::vec3& fg_color, const glm::vec4& bg_color,
const std::string& text) {
auto font_present = _fonts.find(font_name);
if (font_present == _fonts.end()) {
return -1;
}
glm::vec3 starting_pos(x, y, 0.f);
glm::vec3 text_dir(1.f, 0.f, 0.f);
glm::vec3 up_dir(0.f, -1.f, 0.f);
float text_height = font_height / _viewport_height;
return _fonts[font_name]->AddStaticString(text, fg_color, bg_color, starting_pos, text_dir, up_dir, text_height,
_submit_mgr->GetGraphicsQueueIndex());
}
int32_t GlobeOverlay::AddScreenSpaceDynamicText(const std::string& font_name, float font_height, float x, float y,
const glm::vec3& fg_color, const glm::vec4& bg_color,
const std::string& text, uint32_t copies) {
auto font_present = _fonts.find(font_name);
if (font_present == _fonts.end()) {
return -1;
}
glm::vec3 starting_pos(x, y, 0.f);
glm::vec3 text_dir(1.f, 0.f, 0.f);
glm::vec3 up_dir(0.f, -1.f, 0.f);
float text_height = font_height / _viewport_height;
return _fonts[font_name]->AddDynamicString(text, fg_color, bg_color, starting_pos, text_dir, up_dir, text_height,
_submit_mgr->GetGraphicsQueueIndex(), copies);
}
bool GlobeOverlay::UpdateDynamicText(const std::string& font_name, int32_t string_index, const std::string& text,
uint32_t copy) {
auto font_present = _fonts.find(font_name);
if (font_present == _fonts.end()) {
return false;
}
return font_present->second->UpdateStringText(string_index, text, copy);
}
bool GlobeOverlay::Draw(VkCommandBuffer command_buffer, uint32_t copy) {
glm::mat4 identity(1.f);
for (const auto font_element : _fonts) {
font_element.second->DrawStrings(command_buffer, identity, copy);
}
return true;
}
| 40.394495 | 117 | 0.642062 | MarkY-LunarG |
ad51652b42155e2d682c2a5f2b97729194d11156 | 291 | cpp | C++ | algorithm_cpp/basic/get_line.cpp | eunjin115/TIL | 2c9179e4dabdf5d8876871987de8b705c011b672 | [
"MIT"
] | null | null | null | algorithm_cpp/basic/get_line.cpp | eunjin115/TIL | 2c9179e4dabdf5d8876871987de8b705c011b672 | [
"MIT"
] | null | null | null | algorithm_cpp/basic/get_line.cpp | eunjin115/TIL | 2c9179e4dabdf5d8876871987de8b705c011b672 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(void){
char arr[10];
cout << "문자 입력";
cin.getline(arr,10, ' '); // 10은 최대 입력 가능 문자수, default 종결 문자는 \n (개행문자)
// cin.getline(arr,10,' '); // [예] 세 번째 인자는 종결 문자 설정 -> 공백(' ')
cout << arr << endl;
return 0;
} | 22.384615 | 75 | 0.522337 | eunjin115 |
ad51e5ab2ec0c7ecd6be302e3cc13731df5d6bce | 4,387 | hpp | C++ | include/sprout/darkroom/intersects/intersection.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | 4 | 2021-12-29T22:17:40.000Z | 2022-03-23T11:53:44.000Z | dsp/lib/sprout/sprout/darkroom/intersects/intersection.hpp | TheSlowGrowth/TapeLooper | ee8d8dccc27e39a6f6f6f435847e4d5e1b97c264 | [
"MIT"
] | 16 | 2021-10-31T21:41:09.000Z | 2022-01-22T10:51:34.000Z | include/sprout/darkroom/intersects/intersection.hpp | thinkoid/Sprout | a5a5944bb1779d3bb685087c58c20a4e18df2f39 | [
"BSL-1.0"
] | null | null | null | /*=============================================================================
Copyright (c) 2011-2019 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPROUT_DARKROOM_INTERSECTS_INTERSECTION_HPP
#define SPROUT_DARKROOM_INTERSECTS_INTERSECTION_HPP
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/tuple/tuple.hpp>
#include <sprout/utility/forward.hpp>
#include <sprout/type_traits/enabler_if.hpp>
#include <sprout/darkroom/access/access.hpp>
#include <sprout/darkroom/coords/vector.hpp>
#include <sprout/darkroom/materials/material.hpp>
namespace sprout {
namespace darkroom {
namespace intersects {
//
// intersection
//
typedef sprout::tuples::tuple<
bool,
double,
sprout::darkroom::coords::vector3d_t,
sprout::darkroom::coords::vector3d_t,
sprout::darkroom::materials::material,
bool
> intersection;
//
// has_is_from_inside
//
template<typename T>
struct has_is_from_inside
: public sprout::bool_constant<(sprout::darkroom::access::size<T>::value >= 6)>
{};
//
// does_intersect
// distance
// point_of_intersection
// normal
// material
// is_from_inside
//
template<typename T>
inline SPROUT_CONSTEXPR auto
does_intersect(T&& t)
SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<0>(SPROUT_FORWARD(T, t)))
-> decltype(sprout::darkroom::access::get<0>(SPROUT_FORWARD(T, t)))
{
return sprout::darkroom::access::get<0>(SPROUT_FORWARD(T, t));
}
template<typename T>
inline SPROUT_CONSTEXPR auto
distance(T&& t)
SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<1>(SPROUT_FORWARD(T, t)))
-> decltype(sprout::darkroom::access::get<1>(SPROUT_FORWARD(T, t)))
{
return sprout::darkroom::access::get<1>(SPROUT_FORWARD(T, t));
}
template<typename T>
inline SPROUT_CONSTEXPR auto
point_of_intersection(T&& t)
SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<2>(SPROUT_FORWARD(T, t)))
-> decltype(sprout::darkroom::access::get<2>(SPROUT_FORWARD(T, t)))
{
return sprout::darkroom::access::get<2>(SPROUT_FORWARD(T, t));
}
template<typename T>
inline SPROUT_CONSTEXPR auto
normal(T&& t)
SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<3>(SPROUT_FORWARD(T, t)))
-> decltype(sprout::darkroom::access::get<3>(SPROUT_FORWARD(T, t)))
{
return sprout::darkroom::access::get<3>(SPROUT_FORWARD(T, t));
}
template<typename T>
inline SPROUT_CONSTEXPR auto
material(T&& t)
SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<4>(SPROUT_FORWARD(T, t)))
-> decltype(sprout::darkroom::access::get<4>(SPROUT_FORWARD(T, t)))
{
return sprout::darkroom::access::get<4>(SPROUT_FORWARD(T, t));
}
template<
typename T,
typename sprout::enabler_if<sprout::darkroom::intersects::has_is_from_inside<typename std::decay<T>::type>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR auto
is_from_inside(T&& t)
SPROUT_NOEXCEPT_IF_EXPR(sprout::darkroom::access::get<5>(SPROUT_FORWARD(T, t)))
-> decltype(sprout::darkroom::access::get<5>(SPROUT_FORWARD(T, t)))
{
return sprout::darkroom::access::get<5>(SPROUT_FORWARD(T, t));
}
template<
typename T,
typename sprout::enabler_if<!sprout::darkroom::intersects::has_is_from_inside<typename std::decay<T>::type>::value>::type = sprout::enabler
>
inline SPROUT_CONSTEXPR typename sprout::darkroom::access::element<5, sprout::darkroom::intersects::intersection>::type
is_from_inside(T&&)
SPROUT_NOEXCEPT_IF_EXPR((typename sprout::darkroom::access::element<5, sprout::darkroom::intersects::intersection>::type()))
{
return typename sprout::darkroom::access::element<5, sprout::darkroom::intersects::intersection>::type();
}
//
// make_intersection
//
template<typename... Elements>
inline SPROUT_CONSTEXPR sprout::tuples::tuple<Elements...>
make_intersection(Elements const&... elems) {
return sprout::tuples::make_tuple(elems...);
}
} // namespace intersects
} // namespace darkroom
} // namespace sprout
#endif // #ifndef SPROUT_DARKROOM_INTERSECTS_INTERSECTION_HPP
| 34.81746 | 143 | 0.681787 | thinkoid |
ad57bfa905c555a89c327f57f1996baca4213954 | 3,069 | hpp | C++ | include/CobraModelParser/MatlabV5/ParserImpl.hpp | qacwnfq/CobraModelParser | 9e03ff6e9f05e4a971b39a85360494925c72dbeb | [
"MIT"
] | null | null | null | include/CobraModelParser/MatlabV5/ParserImpl.hpp | qacwnfq/CobraModelParser | 9e03ff6e9f05e4a971b39a85360494925c72dbeb | [
"MIT"
] | null | null | null | include/CobraModelParser/MatlabV5/ParserImpl.hpp | qacwnfq/CobraModelParser | 9e03ff6e9f05e4a971b39a85360494925c72dbeb | [
"MIT"
] | null | null | null | #ifndef COBRAMODELPARSER_MATLABV5_PARSERIMPL_HPP
#define COBRAMODELPARSER_MATLABV5_PARSERIMPL_HPP
#include <algorithm>
#include <fstream>
#include <vector>
#include <ostream>
#include "CobraModelParser/Exceptions.hpp"
#include "CobraModelParser/FileLoader.hpp"
#include "CobraModelParser/ModelBuilder.hpp"
#include "CobraModelParser/Parser.hpp"
#include "CobraModelParser/MatlabV5/ArrayFlags.hpp"
#include "CobraModelParser/MatlabV5/Header.hpp"
#include "ArrayDimensions.hpp"
#include "ArrayName.hpp"
#include "FieldNameLength.hpp"
#include "FieldNames.hpp"
#include "Fields.hpp"
#include "PolytopeParser.hpp"
namespace CobraModelParser {
namespace MatlabV5 {
class ParserImpl : public Parser {
public:
Model parseModelFromFile(std::string filename) override {
ByteParser byteParser;
ByteQueue byteQueue = FileLoader::loadFileContentsAsByteQueue(filename);
Header header(byteQueue, byteParser);
const std::pair<Eigen::MatrixXd, Eigen::VectorXd> &data = parseBody(byteQueue, byteParser);
return ModelBuilder()
.setModelOrigin(filename)
.setModelDescription(header.getHeaderText())
.setData(data.first, data.second)
.build();
}
private:
std::pair<Eigen::MatrixXd, Eigen::VectorXd>
parseBody(ByteQueue &byteQueue, const ByteParser &byteParser) const {
TagParser tagParser(byteParser);
Tag tag = tagParser.parseTag(byteQueue);
if (byteQueue.getRemainingBytes() != tag.getNumberOfBytes()) {
throw UnexpectedSizeException(byteQueue.getRemainingBytes(), tag.getNumberOfBytes());
}
auto expectedType = DataTypeTable::lookUp(14);
if (expectedType != tag.getType()) {
throw UnexpectedDataTypeException(expectedType.getSymbol(), tag.getType().getSymbol());
}
const ArrayFlags &arrayFlags = ArrayFlags::fromByteQueue(byteQueue, byteParser, tagParser);
const ArrayDimensions &arrayDimensions = ArrayDimensions::fromByteQueue(byteQueue, byteParser,
tagParser);
const ArrayName &name = ArrayName::fromByteQueue(byteQueue, byteParser, tagParser);
const FieldNameLength &fieldNameLength = FieldNameLength::fromByteQueue(byteQueue, byteParser);
const FieldNames &fieldNames = FieldNames::fromByteQueue(byteQueue, byteParser, tagParser,
fieldNameLength);
const Fields &fields = Fields::fromByteQueue(byteQueue, byteParser, tagParser, fieldNames);
return PolytopeParser::fromFields(fields, byteParser, tagParser);
}
};
}
}
#endif //COBRAMODELPARSER_MATLABV5_PARSERIMPL_HPP
| 40.92 | 111 | 0.623004 | qacwnfq |
ad57c191e0688deba12bf9b3fb676cf283bd46fe | 2,024 | hpp | C++ | Libraries/Physics/Analyzer.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | 3 | 2022-02-11T10:34:33.000Z | 2022-02-24T17:44:17.000Z | Libraries/Physics/Analyzer.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | null | null | null | Libraries/Physics/Analyzer.hpp | RyanTylerRae/WelderEngineRevamp | 3efdad59dd1821ddb1c09b59520e8e2d7023bb10 | [
"MIT"
] | null | null | null | // MIT Licensed (see LICENSE.md).
#pragma once
/// Tracks down which object, if any, was not sent to be checked
/// for collision when it should have (assuming at least one broad phase caught
/// it).
#define OBJECT_TRACKING 1
namespace Zero
{
namespace Physics
{
// The result of a single frame
struct BroadPhaseFrameData
{
BroadPhaseFrameData(void);
/// Clears out all data for the next frame(sets to 0).
void Reset(void);
/// Information about the results of the broad phase.
uint PossibleCollisionsReturned;
uint ActualCollisions;
real TimeTaken;
};
// The statistics for a single broad phases entire life.
struct Statistics
{
Statistics(void);
/// Adds the frame results to the total results.
void Update(const BroadPhaseFrameData& result);
/// Prints the results out to a file.
void PrintResults(void);
/// The name of the broad phase
String Name;
/// The broad phase type, used to help determine what is a more optimal
/// broad phase for certain situations.
uint mType;
/// Collisions data
uint PossibleCollisionsReturned;
uint ActualCollisions;
uint CollisionsMissed;
/// Iterations
uint Iterations;
/// Insertion / Removal.
Profile::Record InsertionTime;
Profile::Record RemovalTime;
/// Time taken to update the broad phase (generally dynamic broad phases).
Profile::Record UpdateTime;
/// Time taken to test objects / get possible pairs.
Profile::Record CollisionTime;
/// Time taken for construction.
Profile::Record ConstructionTime;
/// Time taken for ray casts.
Profile::Record RayCastTime;
};
class Analyzer
{
public:
Analyzer(void);
~Analyzer(void);
typedef Array<Statistics*> StatisticsVec;
void AnalyzePerformance(uint type, StatisticsVec& statistics);
void AnalyzeDynamic(StatisticsVec& statistics);
void AnalyzeStatic(StatisticsVec& statistics);
void ReportSpike(const char* type, real ms);
real CalculateScore(Statistics& stats);
void PrintResults();
};
} // namespace Physics
} // namespace Zero
| 23.534884 | 79 | 0.731719 | RyanTylerRae |
ad5868309d617990cf94e0603699f7c75e01f739 | 635 | hpp | C++ | src/jellyfish/Material.hpp | FelipeEd/Jellyfish3D | 448ca5462fdab2a28677c7f4d05d2e733267da6f | [
"Apache-2.0"
] | null | null | null | src/jellyfish/Material.hpp | FelipeEd/Jellyfish3D | 448ca5462fdab2a28677c7f4d05d2e733267da6f | [
"Apache-2.0"
] | null | null | null | src/jellyfish/Material.hpp | FelipeEd/Jellyfish3D | 448ca5462fdab2a28677c7f4d05d2e733267da6f | [
"Apache-2.0"
] | null | null | null | #pragma once
extern bool pbr;
class Material
{
private:
public:
unsigned int m_texAlbedo;
// TODO change to textures
unsigned int m_texMetallic;
unsigned int m_texNormal;
unsigned int m_texRoughness;
unsigned int m_texAo;
// Load Ao Roughness and Metallic on one texture
unsigned int m_texARM;
glm::vec4 m_color;
bool useNormalmap;
public:
Material(); // Flat color
Material(const std::string &textureFile, const std::string &size);
~Material(){};
void deleteTextures();
void setColor(glm::vec4 color) { m_color = color; }
void setUniforms(Shader &shader);
};
| 19.242424 | 70 | 0.677165 | FelipeEd |
ad5920935ac5a29a023ee509a94db7e1f3378b70 | 719 | cpp | C++ | algorithms_2/BinaryInsertionSort/BinaryInsertionSort.cpp | neutrinobomber/c-stuff | 0a98d8d618a8226e7e2a63b262ef8fe3ec43e185 | [
"MIT"
] | null | null | null | algorithms_2/BinaryInsertionSort/BinaryInsertionSort.cpp | neutrinobomber/c-stuff | 0a98d8d618a8226e7e2a63b262ef8fe3ec43e185 | [
"MIT"
] | null | null | null | algorithms_2/BinaryInsertionSort/BinaryInsertionSort.cpp | neutrinobomber/c-stuff | 0a98d8d618a8226e7e2a63b262ef8fe3ec43e185 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
void BinaryInsertionSort(int arr[], int len)
{
for (int i = 1; i < len; i++)
{
int begin = 0;
int end = i;
int mid = i / 2;
do
{
if (arr[i] > arr[mid])
{
begin = mid + 1;
}
else if (arr[i] < arr[mid])
{
end = mid;
}
else
{
break;
}
mid = (begin + end) / 2;
} while (begin < end);
if (mid < i)
{
int tmp = arr[i];
for (int j = i - 1; j >= mid; j--)
{
arr[j + 1] = arr[j];
}
arr[mid] = tmp;
}
}
}
int main()
{
const int len = 5;
int arr[len] = { 5, 4, 3, 2, 1 };
BinaryInsertionSort(arr, len);
for (size_t i = 0; i < len; i++)
{
cout << arr[i] << " ";
}
cout << endl;
return 0;
} | 12.614035 | 44 | 0.456189 | neutrinobomber |
ad5fc91f5069b2eaa46e855e02c428883200814d | 17,358 | cpp | C++ | src/libtsduck/dtv/tsSignalizationDemux.cpp | ASTRO-Strobel/tsduck | f1da3d49df35b3d9740fb2c8031c92d0f261829a | [
"BSD-2-Clause"
] | 2 | 2020-02-27T04:34:41.000Z | 2020-04-29T10:43:23.000Z | src/libtsduck/dtv/tsSignalizationDemux.cpp | mirakc/tsduck-arib | c400025b7d31e26c0c15471e81adf2ad50632281 | [
"BSD-2-Clause"
] | null | null | null | src/libtsduck/dtv/tsSignalizationDemux.cpp | mirakc/tsduck-arib | c400025b7d31e26c0c15471e81adf2ad50632281 | [
"BSD-2-Clause"
] | 1 | 2019-10-27T03:19:28.000Z | 2019-10-27T03:19:28.000Z | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2020, Thierry Lelegard
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
//----------------------------------------------------------------------------
#include "tsSignalizationDemux.h"
TSDUCK_SOURCE;
//----------------------------------------------------------------------------
// Constructors and destructors.
//----------------------------------------------------------------------------
ts::SignalizationDemux::SignalizationDemux(DuckContext& duck, SignalizationHandlerInterface* handler, std::initializer_list<TID> tids) :
_duck(duck),
_demux(duck, this, this),
_handler(handler),
_tids(),
_service_ids(),
_last_pat(),
_last_pat_handled(false)
{
_last_pat.invalidate();
for (auto it = tids.begin(); it != tids.end(); ++it) {
addTableId(*it);
}
}
//----------------------------------------------------------------------------
// Get the NIT PID, either from last PAT or default PID.
//----------------------------------------------------------------------------
ts::PID ts::SignalizationDemux::nitPID() const
{
return _last_pat.isValid() && _last_pat.nit_pid != PID_NULL ? _last_pat.nit_pid : PID(PID_NIT);
}
//----------------------------------------------------------------------------
// Reset the demux.
//----------------------------------------------------------------------------
void ts::SignalizationDemux::reset()
{
_demux.reset();
_demux.setPIDFilter(NoPID);
_tids.clear();
_service_ids.clear();
_last_pat.invalidate();
_last_pat_handled = false;
}
//----------------------------------------------------------------------------
// Add a signalization table id to filter.
//----------------------------------------------------------------------------
bool ts::SignalizationDemux::addTableId(TID tid)
{
// Do not repeat already filtered table ids.
if (hasTableId(tid)) {
return true;
}
// Configure the demux according to the table id.
switch (tid) {
case TID_PAT: {
_demux.addPID(PID_PAT);
// The current PAT may have already been received without notification to the application.
if (_last_pat.isValid() && _handler != nullptr && !_last_pat_handled) {
_last_pat_handled = true;
_handler->handlePAT(_last_pat, PID_PAT);
}
break;
}
case TID_CAT: {
_demux.addPID(PID_CAT);
break;
}
case TID_PMT: {
// We need the PAT to get PMT PID's.
_demux.addPID(PID_PAT);
// If a PAT is known, add all PMT PID's.
if (_last_pat.isValid()) {
for (auto it = _last_pat.pmts.begin(); it != _last_pat.pmts.end(); ++it) {
_demux.addPID(it->second);
}
}
break;
}
case TID_TSDT: {
_demux.addPID(PID_TSDT);
break;
}
case TID_NIT_ACT:
case TID_NIT_OTH: {
// We need the PAT to get the NIT PID.
_demux.addPID(PID_PAT);
_demux.addPID(nitPID());
break;
}
case TID_SDT_ACT:
case TID_SDT_OTH:
case TID_BAT: {
// SDT and BAT share the same PID.
_demux.addPID(PID_SDT);
break;
}
case TID_RST: {
_demux.addPID(PID_RST);
break;
}
case TID_TDT:
case TID_TOT: {
// TDT and TOT share the same PID.
_demux.addPID(PID_TDT);
break;
}
case TID_MGT:
case TID_CVCT:
case TID_TVCT:
case TID_RRT:
case TID_STT: {
// With ATSC, the PSIP base PID contains almost all tables.
_demux.addPID(PID_PSIP);
break;
}
default: {
// Unsupported table id.
return false;
}
}
// Add the table id.
_tids.insert(tid);
return true;
}
//----------------------------------------------------------------------------
// Remove a signalization table id to filter.
//----------------------------------------------------------------------------
bool ts::SignalizationDemux::removeTableId(TID tid)
{
// Do nothing if the table id was not filtered.
if (!hasTableId(tid)) {
return false;
}
// Remove the table id first.
_tids.erase(tid);
// Configure the demux according to the table id.
switch (tid) {
case TID_PAT: {
// Stop monitoring the PAT only when there is no need to get PMT's or NIT.
if (!hasTableId(TID_PMT) && _service_ids.empty() && !hasTableId(TID_NIT_ACT) && !hasTableId(TID_NIT_OTH)) {
_demux.removePID(PID_PAT);
}
break;
}
case TID_CAT: {
_demux.removePID(PID_CAT);
break;
}
case TID_PMT: {
// If a PAT is known, remove all PMT PID's which are not specifically monitored by service id.
if (_last_pat.isValid()) {
for (auto it = _last_pat.pmts.begin(); it != _last_pat.pmts.end(); ++it) {
if (!hasServiceId(it->first)) {
_demux.removePID(it->second);
}
}
}
break;
}
case TID_TSDT: {
_demux.removePID(PID_TSDT);
break;
}
case TID_NIT_ACT:
case TID_NIT_OTH: {
// Remove the PID only if no type of NIT is monitored.
if (!hasTableId(TID_NIT_ACT) && !hasTableId(TID_NIT_OTH)) {
_demux.removePID(nitPID());
}
break;
}
case TID_SDT_ACT:
case TID_SDT_OTH:
case TID_BAT: {
// SDT and BAT share the same PID. Remove the PID only if none is monitored.
if (!hasTableId(TID_SDT_ACT) && !hasTableId(TID_SDT_OTH) && !hasTableId(TID_BAT)) {
_demux.removePID(PID_SDT);
}
break;
}
case TID_RST: {
_demux.removePID(PID_RST);
break;
}
case TID_TDT:
case TID_TOT: {
// TDT and TOT share the same PID. Remove the PID only if none is monitored.
if (!hasTableId(TID_TDT) && !hasTableId(TID_TOT)) {
_demux.removePID(PID_TDT);
}
break;
}
case TID_MGT:
case TID_CVCT:
case TID_TVCT:
case TID_RRT:
case TID_STT: {
// With ATSC, the PSIP base PID contains almost all tables.
if (!hasTableId(TID_MGT) && !hasTableId(TID_CVCT) && !hasTableId(TID_TVCT) && !hasTableId(TID_RRT) && !hasTableId(TID_STT)) {
_demux.removePID(PID_PSIP);
}
break;
}
default: {
// Unsupported table id.
return false;
}
}
// Table id successfully removed.
return true;
}
//----------------------------------------------------------------------------
// Add a service id to filter its PMT.
//----------------------------------------------------------------------------
void ts::SignalizationDemux::addServiceId(uint16_t sid)
{
// Do something only when the service is not yet monitored.
if (!hasServiceId(sid)) {
// Remember the service id to monitor.
_service_ids.insert(sid);
// We need the PAT to get PMT PID's.
_demux.addPID(PID_PAT);
// If a PAT is known and references the service, add its PMT PID.
if (_last_pat.isValid()) {
const auto it(_last_pat.pmts.find(sid));
if (it != _last_pat.pmts.end()) {
_demux.addPID(it->second);
}
}
}
}
//----------------------------------------------------------------------------
// Remove a service id to filter its PMT.
//----------------------------------------------------------------------------
void ts::SignalizationDemux::removeServiceId(uint16_t sid)
{
// Do something only when the service is currently monitored.
if (hasServiceId(sid)) {
// Forget the service id to monitor.
_service_ids.erase(sid);
// If a PAT is known and references the service, remove its PMT PID.
// If all PMT's are still monitored, don't change anything.
if (_last_pat.isValid() && !hasTableId(TID_PMT)) {
const auto it(_last_pat.pmts.find(sid));
if (it != _last_pat.pmts.end()) {
_demux.removePID(it->second);
}
}
}
}
//----------------------------------------------------------------------------
// Remove all service ids to filter PMT's.
//----------------------------------------------------------------------------
void ts::SignalizationDemux::removeAllServiceIds()
{
// If a PAT is known, remove all PMT PID's.
// If all PMT's are still monitored, don't change anything.
if (_last_pat.isValid() && !hasTableId(TID_PMT)) {
for (auto it = _last_pat.pmts.begin(); it != _last_pat.pmts.end(); ++it) {
_demux.removePID(it->second);
}
}
// Forget all service ids.
_service_ids.clear();
}
//----------------------------------------------------------------------------
// Invoked by SectionDemux when a complete table is received.
//----------------------------------------------------------------------------
void ts::SignalizationDemux::handleTable(SectionDemux&, const BinaryTable& table)
{
const PID pid = table.sourcePID();
const TID tid = table.tableId();
// The PAT needs to be monitored outside explicit filtering.
if (tid == TID_PAT && pid == PID_PAT) {
const PAT pat(_duck, table);
if (pat.isValid()) {
// Check if all PMT's are monitored.
const bool all_pmts = hasTableId(TID_PMT);
// If a previous PAT was there, remove unused PMT PID's.
if (_last_pat.isValid() && (all_pmts || !_service_ids.empty())) {
// Loop on all previous services
for (auto it1 = _last_pat.pmts.begin(); it1 != _last_pat.pmts.end(); ++it1) {
// If the service no longer exists or has changed its PMT PID, remove the previous PMT PID.
const auto it2(pat.pmts.find(it1->first));
if (it2 == pat.pmts.end() || it2->second != it1->second) {
_demux.removePID(it1->second);
}
}
}
// Remember the last PAT.
_last_pat = pat;
_last_pat_handled = false;
// Then, monitor new PMT PID's. Some of them may be already monitored.
for (auto it = pat.pmts.begin(); it != pat.pmts.end(); ++it) {
if (all_pmts || hasServiceId(it->first)) {
_demux.addPID(it->second);
}
}
// Monitor non-standard NIT PID.
if (hasTableId(TID_NIT_ACT) || hasTableId(TID_NIT_OTH)) {
_demux.addPID(nitPID());
}
// Notify the PAT to the application.
if (_handler != nullptr && hasTableId(TID_PAT)) {
_last_pat_handled = true;
_handler->handlePAT(pat, pid);
}
}
}
// Other tables have no special treatment. They are directly passed to the application.
// PMT may be selectively filtered by service id (table id extention).
else if (_handler != nullptr && (hasTableId(tid) || (tid == TID_PMT && hasServiceId(table.tableIdExtension())))) {
switch (tid) {
case TID_CAT: {
const CAT cat(_duck, table);
if (cat.isValid() && pid == PID_CAT) {
_handler->handleCAT(cat, pid);
}
break;
}
case TID_PMT: {
const PMT pmt(_duck, table);
if (pmt.isValid()) {
_handler->handlePMT(pmt, pid);
}
break;
}
case TID_TSDT: {
const TSDT tsdt(_duck, table);
if (tsdt.isValid() && pid == PID_TSDT) {
_handler->handleTSDT(tsdt, pid);
}
break;
}
case TID_NIT_ACT:
case TID_NIT_OTH: {
const NIT nit(_duck, table);
if (nit.isValid() && pid == nitPID()) {
_handler->handleNIT(nit, pid);
}
break;
}
case TID_SDT_ACT:
case TID_SDT_OTH: {
const SDT sdt(_duck, table);
if (sdt.isValid() && pid == PID_SDT) {
_handler->handleSDT(sdt, pid);
}
break;
}
case TID_BAT: {
const BAT bat(_duck, table);
if (bat.isValid() && pid == PID_BAT) {
_handler->handleBAT(bat, pid);
}
break;
}
case TID_RST: {
const RST rst(_duck, table);
if (rst.isValid() && pid == PID_RST) {
_handler->handleRST(rst, pid);
}
break;
}
case TID_TDT: {
const TDT tdt(_duck, table);
if (tdt.isValid() && pid == PID_TDT) {
_handler->handleTDT(tdt, pid);
}
break;
}
case TID_TOT: {
const TOT tot(_duck, table);
if (tot.isValid() && pid == PID_TOT) {
_handler->handleTOT(tot, pid);
}
break;
}
case TID_MGT: {
const MGT mgt(_duck, table);
if (mgt.isValid() && pid == PID_PSIP) {
_handler->handleMGT(mgt, pid);
}
break;
}
case TID_CVCT: {
const CVCT vct(_duck, table);
if (vct.isValid() && pid == PID_PSIP) {
// Call specific and generic form of VCT handler.
_handler->handleCVCT(vct, pid);
_handler->handleVCT(vct, pid);
}
break;
}
case TID_TVCT: {
const TVCT vct(_duck, table);
if (vct.isValid() && pid == PID_PSIP) {
// Call specific and generic form of VCT handler.
_handler->handleTVCT(vct, pid);
_handler->handleVCT(vct, pid);
}
break;
}
case TID_RRT: {
const RRT rrt(_duck, table);
if (rrt.isValid() && pid == PID_PSIP) {
_handler->handleRRT(rrt, pid);
}
break;
}
default: {
// Unsupported table id or processed elsewhere (PAT, STT).
break;
}
}
}
}
//----------------------------------------------------------------------------
// Invoked by SectionDemux when a section is received.
//----------------------------------------------------------------------------
void ts::SignalizationDemux::handleSection(SectionDemux&, const Section& section)
{
// We use this handler for ATSC System Time Table (STT) only.
// This table violates the common usage rules of MPEG sections, see file tsSTT.h.
if (_handler != nullptr && section.tableId() == TID_STT && hasTableId(TID_STT) && section.sourcePID() == PID_PSIP) {
const STT stt(_duck, section);
if (stt.isValid()) {
_handler->handleSTT(stt, PID_PSIP);
}
}
}
| 34.372277 | 137 | 0.474997 | ASTRO-Strobel |
ad6222e6c100a11297409217fcdb1f11d8d82b08 | 3,880 | cpp | C++ | project/Windows/Engine/BlurEffect.cpp | mholtkamp/vakz | ad72c9b971c442450d530b82fb8d976c0fccbff7 | [
"MIT"
] | 5 | 2016-12-15T18:36:40.000Z | 2019-12-04T00:48:40.000Z | project/Windows/Engine/BlurEffect.cpp | mholtkamp/vakz | ad72c9b971c442450d530b82fb8d976c0fccbff7 | [
"MIT"
] | null | null | null | project/Windows/Engine/BlurEffect.cpp | mholtkamp/vakz | ad72c9b971c442450d530b82fb8d976c0fccbff7 | [
"MIT"
] | 1 | 2021-04-15T09:37:43.000Z | 2021-04-15T09:37:43.000Z | #include "BlurEffect.h"
#include "Log.h"
#include "VGL.h"
#include "VInput.h"
#include "Settings.h"
// Vertex data needed to render quad that covers entire screen
static float s_arPosition[8] = {-1.0f, -1.0f,
-1.0f, 1.0f,
1.0f, 1.0f,
1.0f, -1.0f};
static float s_arTexCoord[8] = {0.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
1.0f, 0.0f};
//*****************************************************************************
// Constructor
//*****************************************************************************
BlurEffect::BlurEffect()
{
m_nType = EFFECT_BLUR;
m_nBlurFactor = 4;
m_nSampleDistance = 1;
}
//*****************************************************************************
// Destructor
//*****************************************************************************
BlurEffect::~BlurEffect()
{
}
//*****************************************************************************
// Render
//*****************************************************************************
void BlurEffect::Render(void* pScene,
unsigned int hFBO,
unsigned int hColorAttach,
unsigned int hDepthAttach)
{
static int s_nTestFactor = 1;
unsigned int hProg = GetShaderProgram(BLUR_EFFECT_PROGRAM);
int hTexture = -1;
int hDimensions = -1;
int hBlurFactor = -1;
int hSampleDistance = -1;
int hPosition = -1;
int hTexCoord = -1;
glUseProgram(hProg);
glBindBuffer(GL_ARRAY_BUFFER, 0);
hTexture = glGetUniformLocation(hProg, "uTexture");
hDimensions = glGetUniformLocation(hProg, "uDimensions");
hBlurFactor = glGetUniformLocation(hProg, "uBlurFactor");
hSampleDistance = glGetUniformLocation(hProg, "uSampleDistance");
hPosition = glGetAttribLocation(hProg, "aPosition");
hTexCoord = glGetAttribLocation(hProg, "aTexCoord");
glBindTexture(GL_TEXTURE_2D, hColorAttach);
glUniform1i(hTexture, 0);
glUniform1i(hBlurFactor, 6);
glUniform1i(hSampleDistance, m_nSampleDistance);
glUniform2f(hDimensions,
static_cast<float>(g_nResolutionX),
static_cast<float>(g_nResolutionY));
glEnableVertexAttribArray(hPosition);
glEnableVertexAttribArray(hTexCoord);
glVertexAttribPointer(hPosition,
2,
GL_FLOAT,
GL_FALSE,
0,
s_arPosition);
glVertexAttribPointer(hTexCoord,
2,
GL_FLOAT,
GL_FALSE,
0,
s_arTexCoord);
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
}
//*****************************************************************************
// SetBlurFactor
//*****************************************************************************
void BlurEffect::SetBlurFactor(int nFactor)
{
if (nFactor >= MIN_BLUR_FACTOR &&
nFactor <= MAX_BLUR_FACTOR)
{
m_nBlurFactor = nFactor;
}
else
{
LogWarning("Invalid blur factor in BlurEffect::SetBlurFactor()");
}
}
//*****************************************************************************
// SetSampleDistance
//*****************************************************************************
void BlurEffect::SetSampleDistance(int nDistance)
{
if (nDistance >= MIN_SAMPLE_DISTANCE &&
nDistance <= MAX_SAMPLE_DISTANCE)
{
m_nSampleDistance = nDistance;
}
else
{
LogWarning("Invalid sample distance in BlurEffect::SetSampleDistance()");
}
}
| 32.066116 | 81 | 0.439948 | mholtkamp |
ad66124e89381da2a18d6281e39597f5fa615abe | 2,041 | cpp | C++ | src/wspp_wrapper.cpp | osmiumhydorogen/CppRosBridge_demo | a8b9eb442654f54465cf58ca62da8c583fb746e4 | [
"MIT"
] | null | null | null | src/wspp_wrapper.cpp | osmiumhydorogen/CppRosBridge_demo | a8b9eb442654f54465cf58ca62da8c583fb746e4 | [
"MIT"
] | null | null | null | src/wspp_wrapper.cpp | osmiumhydorogen/CppRosBridge_demo | a8b9eb442654f54465cf58ca62da8c583fb746e4 | [
"MIT"
] | 1 | 2022-03-17T01:38:05.000Z | 2022-03-17T01:38:05.000Z | #include <wspp_wrapper.hpp>
//#include <websocketpp/common/memory.hpp>
namespace crb_sock
{
WsppWrapper::WsppWrapper()
{
_client_ep.clear_access_channels(websocketpp::log::alevel::all);
_client_ep.clear_error_channels(websocketpp::log::elevel::all);
_client_ep.init_asio();
_client_ep.start_perpetual();
m_thread.reset(new websocketpp::lib::thread(&wspp_client_t::run, &_client_ep));
}
int WsppWrapper::connect(std::string const &uri)
{
websocketpp::lib::error_code ec;
wspp_client_t::connection_ptr con = _client_ep.get_connection(uri, ec);
_con = con;
if (ec) {
std::cout << "> Connect initialization error: " << ec.message() << std::endl;
return -1;
}
/*
_on_message = [&](websocketpp::connection_hdl hdl_, wspp_client_t::message_ptr msg_)
{
std::cout << "Something resieved." << std::endl;
if (msg_->get_opcode() == websocketpp::frame::opcode::text)
{
this->_callbk(msg_->get_payload());
}
};
// */
con->set_message_handler(websocketpp::lib::bind(
&WsppWrapper::_on_message,
this,
websocketpp::lib::placeholders::_1,
websocketpp::lib::placeholders::_2
));
hdl=con->get_handle();
_client_ep.connect(con);
}
void WsppWrapper::_on_message(websocketpp::connection_hdl hdl_, wspp_client_t::message_ptr msg_)
{
//std::cout << "Something recieved." << std::endl;
if (msg_->get_opcode() == websocketpp::frame::opcode::text)
{
this->_callbk(msg_->get_payload());
}
}
int WsppWrapper::sendStr(const std::string &str)
{
websocketpp::lib::error_code ec;
//std::cout <<"sending:" << str <<std::endl;
_client_ep.send(hdl, str, websocketpp::frame::opcode::text, ec);
}
int WsppWrapper::setRecieveCb(SockCallback_t cb)
{
_callbk = cb;
}
WsppWrapper::~WsppWrapper()
{
/*
websocketpp::lib::error_code ec;
_client_ep.close(hdl, websocketpp::close::status::going_away, "", ec);
if (ec) {
std::cout << "> Error closing connection " << ": "
<< ec.message() << std::endl;
}
m_thread->join();
// */
}
}
| 25.197531 | 97 | 0.66242 | osmiumhydorogen |
ad66eb1e8eb04907ffcbcead70c6462695a816a0 | 1,017 | cpp | C++ | stringPattern.cpp | thomasjmurphy/dataStructures | 1a2fef47cb3734574e7bd7948b0a705b915940da | [
"MIT"
] | null | null | null | stringPattern.cpp | thomasjmurphy/dataStructures | 1a2fef47cb3734574e7bd7948b0a705b915940da | [
"MIT"
] | null | null | null | stringPattern.cpp | thomasjmurphy/dataStructures | 1a2fef47cb3734574e7bd7948b0a705b915940da | [
"MIT"
] | null | null | null | #include <sstream>
#include <string>
#include <unordered_map>
using namespace std;
//Given a pattern and a string, check if the string can be mapped bijectively to that
//pattern. see LeetCode problem 290.
vector<string> split(string str)
{
stringstream ss(str);
vector<string> ret;
string word;
while(getline(ss,word,' '))
{
ret.push_back(word);
}
return ret;
}
class Solution {
public:
bool wordPattern(string pattern, string str) {
vector<string> vec = split(str);
if(vec.size() != pattern.length())
{
return 0;
}
unordered_map<char,string> map;
unordered_map<string,int> mapInj;
for(int i = 0; i < vec.size(); i++)
{
if(map[pattern[i]].empty() && mapInj[vec[i]] == 0)
{
map[pattern[i]] = vec[i];
mapInj[vec[i]] = 1;
}
else
{
if(map[pattern[i]] != vec[i])
{
return 0;
}
}
}
return 1;
}
};
| 20.34 | 85 | 0.52999 | thomasjmurphy |
ad682fe7eebba2cddbcfd6d37f866fd2258444ea | 655 | inl | C++ | src/ivorium_core/Attribute/Fields/PrivField.inl | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | 3 | 2021-02-26T02:59:09.000Z | 2022-02-08T16:44:21.000Z | src/ivorium_core/Attribute/Fields/PrivField.inl | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | src/ivorium_core/Attribute/Fields/PrivField.inl | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | namespace iv
{
//==================== PrivField_Owner =================================
template< class T >
void PrivField_Owner< T >::Field_Modify( PrivField< T > * field, T const & val )
{
field->Modify( val );
}
//==================== LField_RW =================================
template< class T >
PrivField< T >::PrivField( Instance * inst, PrivField_Owner< T > * impl ) :
Field< T >( inst ),
impl( impl )
{
}
template< class T >
void PrivField< T >::Modify( T const & val )
{
this->Field< T >::Modify( val );
}
template< class T >
void PrivField< T >::OnChanged( bool real )
{
this->impl->Field_OnChanged( this, real );
}
}
| 20.46875 | 80 | 0.519084 | ivorne |
ad696df102133daeabc06ece304610ebe0163a3a | 1,610 | hpp | C++ | Lib/Chip/ATSAMD21G18A.hpp | operativeF/Kvasir | dfbcbdc9993d326ef8cc73d99129e78459c561fd | [
"Apache-2.0"
] | null | null | null | Lib/Chip/ATSAMD21G18A.hpp | operativeF/Kvasir | dfbcbdc9993d326ef8cc73d99129e78459c561fd | [
"Apache-2.0"
] | null | null | null | Lib/Chip/ATSAMD21G18A.hpp | operativeF/Kvasir | dfbcbdc9993d326ef8cc73d99129e78459c561fd | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <cstdint>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/AC.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/ADC.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/DAC.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/DMAC.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/DSU.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/EIC.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/EVSYS.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/GCLK.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/I2S.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/MTB.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/NVMCTRL.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/PAC0.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/PAC1.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/PAC2.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/PM.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/PORT.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/RTC.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM0.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM1.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM2.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM3.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM4.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/SERCOM5.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/SYSCTRL.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/TC3.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/TC4.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/TC5.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/TCC0.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/TCC1.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/TCC2.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/USB.hpp>
#include <Chip/CM0+/Atmel/ATSAMD21G18A/WDT.hpp>
| 46 | 51 | 0.775776 | operativeF |
ad74c256718a0e83b6b2e2c032c9e8d99cc66578 | 75 | hpp | C++ | src/ImageView/path_utility.hpp | miere43/imageview | a264fa44ba0140a8171913be763abdddbc531b4a | [
"Unlicense"
] | 1 | 2021-06-24T12:19:41.000Z | 2021-06-24T12:19:41.000Z | src/ImageView/path_utility.hpp | miere43/imageview | a264fa44ba0140a8171913be763abdddbc531b4a | [
"Unlicense"
] | null | null | null | src/ImageView/path_utility.hpp | miere43/imageview | a264fa44ba0140a8171913be763abdddbc531b4a | [
"Unlicense"
] | null | null | null | #pragma once
struct Path_Utility
{
//static wchar_t* combine_path()
}; | 12.5 | 36 | 0.706667 | miere43 |
ad81f548c629a05d4d2f5237e9c7dc6cdeaf0e1c | 6,087 | hpp | C++ | bindings/python/multibody/joint/joints-models.hpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | 8 | 2021-05-12T03:04:59.000Z | 2021-08-10T11:43:36.000Z | bindings/python/multibody/joint/joints-models.hpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | null | null | null | bindings/python/multibody/joint/joints-models.hpp | thanhndv212/pinocchio | 3b4d272bf4e8a231954b71201ee7e0963c944aef | [
"BSD-2-Clause-FreeBSD"
] | 2 | 2021-04-21T16:00:21.000Z | 2022-02-03T06:24:52.000Z | //
// Copyright (c) 2015-2020 CNRS INRIA
//
#ifndef __pinocchio_python_joints_models_hpp__
#define __pinocchio_python_joints_models_hpp__
#include <boost/python.hpp>
#include "pinocchio/multibody/joint/joint-collection.hpp"
#include "pinocchio/multibody/joint/joint-composite.hpp"
#include <eigenpy/eigen-to-python.hpp>
namespace pinocchio
{
namespace python
{
namespace bp = boost::python;
// generic expose_joint_model : do nothing special
template <class T>
inline bp::class_<T>& expose_joint_model(bp::class_<T>& cl)
{
return cl;
}
// specialization for JointModelRevoluteUnaligned
template<>
inline bp::class_<JointModelRevoluteUnaligned>& expose_joint_model<JointModelRevoluteUnaligned> (bp::class_<JointModelRevoluteUnaligned> & cl)
{
return cl
.def(bp::init<double, double, double> (bp::args("x", "y", "z"), "Init JointModelRevoluteUnaligned from the components x, y, z of the axis"))
.def(bp::init<Eigen::Vector3d> (bp::args("axis"),
"Init JointModelRevoluteUnaligned from an axis with x-y-z components"))
.def_readwrite("axis",&JointModelRevoluteUnaligned::axis,
"Rotation axis of the JointModelRevoluteUnaligned.")
;
}
// specialization for JointModelPrismaticUnaligned
template<>
inline bp::class_<JointModelPrismaticUnaligned>& expose_joint_model<JointModelPrismaticUnaligned> (bp::class_<JointModelPrismaticUnaligned> & cl)
{
return cl
.def(bp::init<double, double, double> (bp::args("x", "y", "z"),
"Init JointModelPrismaticUnaligned from the components x, y, z of the axis"))
.def(bp::init<Eigen::Vector3d> (bp::args("axis"),
"Init JointModelPrismaticUnaligned from an axis with x-y-z components"))
.def_readwrite("axis",&JointModelPrismaticUnaligned::axis,
"Translation axis of the JointModelPrismaticUnaligned.")
;
}
// specialization for JointModelComposite
struct JointModelCompositeAddJointVisitor : public boost::static_visitor<JointModelComposite &>
{
JointModelComposite & m_joint_composite;
const SE3 & m_joint_placement;
JointModelCompositeAddJointVisitor(JointModelComposite & joint_composite,
const SE3 & joint_placement)
: m_joint_composite(joint_composite)
, m_joint_placement(joint_placement)
{}
template <typename JointModelDerived>
JointModelComposite & operator()(JointModelDerived & jmodel) const
{
return m_joint_composite.addJoint(jmodel,m_joint_placement);
}
}; // struct JointModelCompositeAddJointVisitor
static JointModelComposite & addJoint_proxy(JointModelComposite & joint_composite,
const JointModelVariant & jmodel_variant,
const SE3 & joint_placement = SE3::Identity())
{
return boost::apply_visitor(JointModelCompositeAddJointVisitor(joint_composite,joint_placement), jmodel_variant);
}
BOOST_PYTHON_FUNCTION_OVERLOADS(addJoint_proxy_overloads,addJoint_proxy,2,3)
struct JointModelCompositeConstructorVisitor : public boost::static_visitor<JointModelComposite* >
{
const SE3 & m_joint_placement;
JointModelCompositeConstructorVisitor(const SE3 & joint_placement)
: m_joint_placement(joint_placement)
{}
template <typename JointModelDerived>
JointModelComposite* operator()(JointModelDerived & jmodel) const
{
return new JointModelComposite(jmodel,m_joint_placement);
}
}; // struct JointModelCompositeConstructorVisitor
static JointModelComposite* init_proxy1(const JointModelVariant & jmodel_variant)
{
return boost::apply_visitor(JointModelCompositeConstructorVisitor(SE3::Identity()), jmodel_variant);
}
static JointModelComposite* init_proxy2(const JointModelVariant & jmodel_variant,
const SE3 & joint_placement)
{
return boost::apply_visitor(JointModelCompositeConstructorVisitor(joint_placement), jmodel_variant);
}
template<>
inline bp::class_<JointModelComposite>& expose_joint_model<JointModelComposite> (bp::class_<JointModelComposite> & cl)
{
return cl
.def(bp::init<const size_t> (bp::args("size"), "Init JointModelComposite with a defined size"))
.def("__init__",
bp::make_constructor(init_proxy1,
bp::default_call_policies(),
bp::args("joint_model")
),
"Init JointModelComposite from a joint"
)
.def("__init__",
bp::make_constructor(init_proxy2,
bp::default_call_policies(),
bp::args("joint_model","joint_placement")
),
"Init JointModelComposite from a joint and a placement"
)
.add_property("joints",&JointModelComposite::joints)
.add_property("jointPlacements",&JointModelComposite::jointPlacements)
.add_property("njoints",&JointModelComposite::njoints)
.def("addJoint",
&addJoint_proxy,
addJoint_proxy_overloads(bp::args("joint_model","joint_placement"),
"Add a joint to the vector of joints."
)[bp::return_internal_reference<>()]
)
;
}
} // namespace python
} // namespace pinocchio
#endif // ifndef __pinocchio_python_joint_models_hpp__
| 41.97931 | 155 | 0.611631 | thanhndv212 |
ad879d14f474f56434bb46142ea101b6600c53e1 | 17,253 | cpp | C++ | nTA/Source/unit_Object.cpp | loganjones/nTA-Total-Annihilation-Clone | d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14 | [
"MIT"
] | 2 | 2020-05-09T20:50:12.000Z | 2021-06-20T08:34:58.000Z | nTA/Source/unit_Object.cpp | loganjones/nTA-Total-Annihilation-Clone | d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14 | [
"MIT"
] | null | null | null | nTA/Source/unit_Object.cpp | loganjones/nTA-Total-Annihilation-Clone | d7d0e4d33f1d452d17cf2fed2b2bcb7f6d7d4d14 | [
"MIT"
] | 2 | 2018-01-08T00:12:04.000Z | 2020-06-14T10:56:50.000Z | // unit_Object.cpp // \author Logan Jones
//////////////////// \date 12/29/2001
/// \file
/// \brief ...
/////////////////////////////////////////////////////////////////////
#include "unit.h"
#include "unit_Object.h"
#include "game.h"
#include "gfx.h"
#include "snd.h"
#include "object.h"
// Include inline implementaions here for a debug build
#ifdef _DEBUG
#include "unit_Object.inl"
#endif // defined( _DEBUG )
/////////////////////////////////////////////////////////////////////
// Default Construction/Destruction
//
unit_Object::unit_Object( unit_Factory& Manager ):
physics_Object( OBJ_Unit ),
scene_Object( OBJ_Unit ),
m_Manager( Manager )
{}
unit_Object::~unit_Object()
{}
//
/////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// unit_Object::Create() // \author Logan Jones
////////////////////////// \date 2/24/2002
//
//====================================================================
// Parameters:
// const std_Point& ptPosition -
// const unit_Type* pUnitType -
//
// Return: BOOL -
//
BOOL unit_Object::Create( const std_Point& ptPosition, const unit_Type* pUnitType, game_Player* pPlayer )
{
m_BaseRect.Set( ptPosition, pUnitType->FootPrint * 16 );
m_Orientation.Set( 0, 0, fPI/2 );
m_Direction.Set( 0, 1 );
// Set the type and host player
m_pUnitType = pUnitType;
m_pPlayer = pPlayer;
// Create an model instance for this unit
m_pUnitType->Model->NewInstance( &m_Model );
// Create the script proccess and run the create module
if( bFAILED(theGame.Units.m_ScriptMachine.CreateProccess( m_pUnitType->pScript, this, m_Model, &m_Script )) )
{
//Destroy();
return FALSE;
}
// Initialize the model verts and states
m_Model->SynchronizeVertices();
m_Model->SynchronizeStates();
// If the unit can build let the initial menu be athe first build menu
m_LastMenu = (m_pUnitType->Abilities & unit_Type::CanBuild) ? 1 : 0;
m_LastBuildPage = 1;
// Set the initial orders
m_FireOrder = m_pUnitType->InitialFireOrder;
m_MoveOrder = m_pUnitType->InitialMoveOrder;
m_Cloaked = FALSE;
m_Activation = FALSE;
// Initialize
m_BuildOrders = NULL;
m_bSelected = FALSE;
m_ReadyToBuild = 0;
m_PrimaryJob = m_ProductionJob = NULL;
m_AttachedProject = NULL;
// Call the create script and the creation event
m_Script->Create();
OnCreate();
// Attach to physics and scene systems
m_SceneSortKey = m_VisibleRect.top;
AddToPhysicsSystem();
AttachToScene();
return TRUE;
}
// End unit_Object::Create()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// unit_Object::Update() // \author Logan Jones
////////////////////////// \date 3/3/2002
//
//====================================================================
//
void unit_Object::Update()
{
if( !m_Script->IsAnimating() )
MakeAnimator( false );
/*
Order_t* pOrder = m_OrderQueue.empty() ? NULL : &m_OrderQueue.front();
switch( m_CurrentTask )
{
case TASK_Nothing:
case TASK_BeingBuilt:
break;
case TASK_Pathing:
if( pOrder && !pOrder->Waypoints.empty() && m_BaseRect.PointInRect(pOrder->Waypoints.back()) )
{
pOrder->Waypoints.pop_back();
if( pOrder->Waypoints.empty() )
PathFinished( pOrder );
else ComputeMotion();
}
break;
} // end switch( m_CurrentTask )*/
}
// End unit_Object::Update()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// unit_Object::Animate() // \author Logan Jones
/////////////////////////// \date 6/11/2002
//
//====================================================================
//
void unit_Object::Animate()
{
m_Script->Animate();
}
// End unit_Object::Animate()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// unit_Object::Render() // \author Logan Jones
////////////////////////// \date 2/2/2002
//
//====================================================================
// Parameters:
// std_Vector2 vOffset -
//
void unit_Object::Render( std_Vector2 vOffset ) const
{
const std_RectF ScreenRect( m_BaseRect - vOffset/* - m_HeightOffset*/ );
//const DWORD Flags = (m_bSelected ? gfx_Model::Selected : 0) |
// (m_Elevation < theGame.Terrain.GetSeaLevel() ? gfx_Model::InWater : 0) |
// (TRUE ? gfx_Model::SubmergedVisible : 0);
/* m_pUnitType->Model->Render(
m_Script->GetPieces(),
ScreenRect.Center(),
m_MoveInfo.GetOrientation() + std_Vector3(0,0,fPI/2),
theGame.Terrain.GetSeaLevel() - m_Elevation,
Flags,
this );*/
#ifdef VISUAL_PATHFIND
unit_Factory::PathFind_t* pPath = m_Manager.GetPathInProgress( (unit_Object*)((DWORD)this) );
if( pPath!=NULL )
{
std_RectF rct;
unit_Factory::SearchNodeBank_t::iterator it = pPath->NodeBank.begin();
unit_Factory::SearchNodeBank_t::iterator end= pPath->NodeBank.end();
for( ; it!=end; ++it )
{
unit_Factory::SearchNode_t* pNode = ((*it).second);
rct.Set( pNode->Location * 16, 16, 16 );
if( pNode==pPath->pBest )
gfx->DrawRect( rct - vOffset, 0xFFFFFF77 );
else if( pNode==pPath->pProccessee )
gfx->DrawRect( rct - vOffset, 0xFFFF0077 );
else if( pNode->InOpen )
gfx->DrawRect( rct - vOffset, 0x0000FF77 );
else if( pNode->InClosed )
gfx->DrawRect( rct - vOffset, 0xFF000077 );
else
gfx->DrawRect( rct - vOffset, 0x00000077 );
}
}
#endif
#ifdef VISUAL_PATHFIND_RESULT
/*if( !m_OrderQueue.empty() )
{
const Order_t* pOrder = &m_OrderQueue.front();
Waypoints_t::const_iterator it = pOrder->Waypoints.begin();
Waypoints_t::const_iterator end= pOrder->Waypoints.end();
for( ; it!=end; ++it)
gfx->DrawRect( std_RectF( (*it) - vOffset - std_Vector2( 0, theGame.Terrain.GetHeight((*it)/16) * 0.5f ), std_SizeF(16,16)), DWORD(0xFFFFFF99) );
}*/
#endif
}
// End unit_Object::Render()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// unit_Object::Render() // \author Logan Jones
////////////////////////// \date 5/29/2002
//
//====================================================================
//
void unit_Object::Render()
{
//const DWORD Flags = (m_bSelected ? gfx_Model::Selected : 0) |
// (m_Elevation < theGame.Terrain.GetSeaLevel() ? gfx_Model::InWater : 0) |
// (TRUE ? gfx_Model::SubmergedVisible : 0);
//m_pUnitType->Model->Render(
// m_Script->GetPieces(),
// m_VisibleRect.Center(),
// m_MoveInfo.GetOrientation() + std_Vector3(0,0,fPI/2),
// 0,
// theGame.Terrain.GetSeaLevel() - m_Elevation,
// Flags,
// this );
m_Model->Render( m_VisibleRect.Center(), m_Orientation + std_Vector3(0,0,fPI/2) );
if( m_PrimaryJob && m_PrimaryJob->Active ) {
gfx_ModelPiece* pFrom= m_Script->QueryNanoPiece();
gfx_ModelPiece* pTo = m_PrimaryJob->Project->Target->m_Script->SweetSpot();
std_Vector3 From = pFrom->ScreenPosition();
std_Vector2 To = pTo->ScreenPosition();
gfx->DrawLine( m_VisibleRect.Center() + From, m_PrimaryJob->Project->Target->m_VisibleRect.Center() + To, 0xFFFFFFFF );
}
}
// End unit_Object::Render()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// unit_Object::SetPath() // \author Logan Jones
/////////////////////////// \date 3/5/2002
//
//====================================================================
//
void unit_Object::SetPath()
{
// m_OrderQueue.front().Waypoints.pop_back();
ComputeMotion();
// Move( m_pUnitType->MaxSpeed );
// MakeMover();
MakeMeDynamic();
}
// End unit_Object::SetPath()
//////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// unit_Object::ComputeMotion() // \author Logan Jones
///////////////////////////////// \date 2/24/2002
//
//====================================================================
//
void unit_Object::ComputeMotion()
{
// std_Vector2 Dir( m_Path.front() - m_BaseRect.Center() );
std_Vector2 Dir( Waypoint() - m_BaseRect.Center() );
Dir.Normalize();
// Turn( Dir );
//m_Direction = m_Path.front() - m_BaseRect.Center();
//m_Direction.Normalize();
}
// End unit_Object::ComputeMotion()
//////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// unit_Object::DoJobStep() // \author Logan Jones
///////////////////////////// \date 02-12-2003
//
//===================================================================
// Parameters:
// unit_Job* pJob -
// bool bStep -
//
void unit_Object::DoJobStep( unit_Job* pJob, bool bStep )
{
// TEMP
//if( bStep )
// if( ((pJob->Project->AppliedTime+=pJob->Worker->m_pUnitType->WorkerTime)>=pJob->Project->TargetType->BuildTime) )
// {
// if( pJob->Project->WorkerCount==1 ) delete pJob->Project;
// m_Project = NULL;
// m_pPlayer->KillJob( this ),
// m_Script->Deactivate(),
// m_pPlayer->Update( Metal, Consumption, 0, pJob->Project->TargetType->BuildCostMetal / ),
// m_pPlayer->Update( Energy,Consumption, 0, pJob->EnergyCost);
// }
}
// End unit_Object::DoJobStep()
/////////////////////////////////////////////////////////////////////
static long _yard_open = 0;
/////////////////////////////////////////////////////////////////////
// unit_Object::SetUnitValue() // \author Logan Jones
//////////////////////////////// \date 02-13-2003
//
//===================================================================
// Parameters:
// const long& lUnitValueID -
// long lDesiredValue -
//
void unit_Object::SetUnitValue( const long& lUnitValueID, long lDesiredValue )
{
switch( lUnitValueID )
{
case INBUILDSTANCE:
if( m_ReadyToBuild=lDesiredValue ) ReadyToWork();
break;
case BUSY:
break;
case YARD_OPEN:
_yard_open = lDesiredValue;
case BUGGER_OFF:
case ARMORED:
break;
default:
break;
}
}
// End unit_Object::SetUnitValue()
/////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
// unit_Object::GetUnitValue() // \author Logan Jones
//////////////////////////////// \date 4/18/2002
//
//====================================================================
// Parameters:
// const long lUnitValueID -
//
// Return: const long -
//
const long unit_Object::GetUnitValue( const long lUnitValueID ) const
{
switch( lUnitValueID )
{
case ACTIVATION:
return m_Activation;
case STANDINGMOVEORDERS:
return m_MoveOrder;
case STANDINGFIREORDERS:
return m_FireOrder;
case HEALTH:
return 0;
case INBUILDSTANCE:
return m_ReadyToBuild;
case BUSY:
case PIECE_XZ:
case PIECE_Y:
case UNIT_XZ:
case UNIT_Y:
case UNIT_HEIGHT:
case GROUND_HEIGHT:
case BUILD_PERCENT_LEFT:
return 0;
case YARD_OPEN:
return _yard_open;
case BUGGER_OFF:
case ARMORED:
return 0;
case IN_WATER:
return theGame.Terrain.GetElevation(m_BaseRect.Center()) < theGame.Terrain.GetSeaLevel();
case CURRENT_SPEED:
return long(m_Velocity.Magnitude() * LINEAR_CONSTANT);
case VETERAN_LEVEL:
return 0;
default:
return 0;
}
}
// End unit_Object::GetUnitValue()
//////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// unit_Object::AbsoluteHealth() // \author Logan Jones
////////////////////////////////// \date 03-06-2003
//
//===================================================================
// Return: float -
//
float unit_Object::AbsoluteHealth() const
{
if( m_AttachedProject )
return m_AttachedProject->AppliedTime / m_pUnitType->BuildTime;
else return 1;
}
// End unit_Object::AbsoluteHealth()
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// unit_Object::EconomicActivity() // \author Logan Jones
//////////////////////////////////// \date 03-03-2003
//
//===================================================================
// Parameters:
// float& fMetalProduction -
// float& fMetalConsumtion -
// float& fEnergyProduction -
// float& fEnergyConsumtion -
//
void unit_Object::EconomicActivity( float& fMetalProduction, float& fMetalConsumtion, float& fEnergyProduction, float& fEnergyConsumtion ) const
{
fMetalProduction = m_pUnitType->MetalMake;
fEnergyProduction= m_pUnitType->EnergyMake;
fMetalConsumtion = m_PrimaryJob ? m_PrimaryJob->MetalCost : 0;
fEnergyConsumtion= m_PrimaryJob ? m_PrimaryJob->EnergyCost: 0;
if( m_ProductionJob ) {
if( m_ProductionJob->Active )
fMetalProduction += m_ProductionJob->MetalIncome,
fEnergyProduction+= m_ProductionJob->EnergyIncome;
if( Active() )
fMetalConsumtion += m_ProductionJob->MetalCost,
fEnergyConsumtion+= m_ProductionJob->EnergyCost;
}
}
// End unit_Object::EconomicActivity()
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// unit_Object::DoMovement() // \author Logan Jones
////////////////////////////// \date 05-15-2003
//
//===================================================================
// Return: bool - return true if unit is still alive
//
bool unit_Object::DoMovement()
{
// Save the old base rect
m_MovementBox = m_BaseRect;
// Steering
// Accumulate steering vector
// Locomotion
// Apply steering vector
// Update move state
Locomotion( Steering() );
// Make a movement box that encompasses the old and new position
m_MovementBox.Encompass( m_BaseRect );
// Validation
// Net
return false;
}
// End unit_Object::DoMovement()
/////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////
// unit_Object::Steering() // \author Logan Jones
//////////////////////////// \date 05-21-2003
//
//===================================================================
// Return: std_Vector2 -
//
std_Vector2 unit_Object::Steering()
{
std_Vector2 target = Waypoint();
std_Vector2 position = m_BaseRect.Center();
const std_Vector2 Offset = target - position;
//return ((math_Normalize(Offset) * m_pUnitType->MaxSpeed) - m_Velocity);
const float Distance = Offset.Magnitude();
const float SlowingDistance = sqr(m_pUnitType->MaxSpeed) / m_pUnitType->BrakeRate;
const float RampedSpeed = m_pUnitType->MaxSpeed * Distance / SlowingDistance;
const float ClippedSpeed = min( RampedSpeed, m_pUnitType->MaxSpeed );
const std_Vector2 DesiredVelocity = Offset * (ClippedSpeed / Distance);
return (DesiredVelocity - m_Velocity);
}
// End unit_Object::Steering()
/////////////////////////////////////////////////////////////////////
/*
/////////////////////////////////////////////////////////////////////
// unit_Object::Locomotion() // \author Logan Jones
////////////////////////////// \date 05-21-2003
//
//===================================================================
// Parameters:
// const std_Vector2& vSteering -
//
void unit_Object::Locomotion( const std_Vector2& vSteering )
{
switch( m_pUnitType->Behaviour ) {
case unit_Type::Structure:
break;
case unit_Type::Groundcraft:
break;
case unit_Type::Seacraft:
break;
case unit_Type::Aircraft:
break;
case unit_Type::Hovercraft:
break;
default: // This shouldn't happen
assert( !"Invalid unit type behaviour." );
}
}
// End unit_Object::Locomotion()
/////////////////////////////////////////////////////////////////////
*/
/////////////////////////////////////////////////////////////////////
// End - unit_Object.cpp //
//////////////////////////
| 31.773481 | 149 | 0.481539 | loganjones |
ad8a345a76febdef3fb5fff7e4ba1058b618ec3c | 1,741 | cpp | C++ | src/core/path_controller_component.cpp | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 3 | 2015-02-22T20:34:28.000Z | 2020-03-04T08:55:25.000Z | src/core/path_controller_component.cpp | MrPepperoni/Reaping2-1 | 4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd | [
"MIT"
] | 22 | 2015-12-13T16:29:40.000Z | 2017-03-04T15:45:44.000Z | src/core/path_controller_component.cpp | Reaping2/Reaping2 | 0d4c988c99413e50cc474f6206cf64176eeec95d | [
"MIT"
] | 14 | 2015-11-23T21:25:09.000Z | 2020-07-17T17:03:23.000Z | #include "core/path_controller_component.h"
PathControllerComponent::PathControllerComponent()
: mNextAttackTimer(0.0)
, mNextAttackTimerMax(3.0)
, mDamage(10)
, mAggroDist(800)
, mPeaceDist(1200)
{
}
void PathControllerComponent::SetNextAttackTimer( double nextAttackTimer )
{
mNextAttackTimer = nextAttackTimer;
}
double PathControllerComponent::GetNextAttackTimer() const
{
return mNextAttackTimer;
}
void PathControllerComponent::SetNextAttackTimerMax( double nextAttackTimerMax )
{
mNextAttackTimerMax = nextAttackTimerMax;
}
double PathControllerComponent::GetNextAttackTimerMax() const
{
return mNextAttackTimerMax;
}
void PathControllerComponent::SetDamage( int32_t damage )
{
mDamage = damage;
}
int32_t PathControllerComponent::GetDamage() const
{
return mDamage;
}
void PathControllerComponent::SetAggroDist( int32_t aggroDist )
{
mAggroDist = aggroDist;
}
int32_t PathControllerComponent::GetAggroDist() const
{
return mAggroDist;
}
void PathControllerComponent::SetPeaceDist( int32_t peaceDist )
{
mPeaceDist = peaceDist;
}
int32_t PathControllerComponent::GetPeaceDist() const
{
return mPeaceDist;
}
void PathControllerComponentLoader::BindValues()
{
Bind( "aggro_distance", func_int32_t( &PathControllerComponent::SetAggroDist ) );
Bind( "next_attack_timer", func_int32_t( &PathControllerComponent::SetNextAttackTimerMax ) );
Bind( "damage", func_int32_t( &PathControllerComponent::SetDamage ) );
Bind( "peace_distance", func_int32_t( &PathControllerComponent::SetPeaceDist ) );
}
PathControllerComponentLoader::PathControllerComponentLoader()
{
}
REAPING2_CLASS_EXPORT_IMPLEMENT( PathControllerComponent, PathControllerComponent );
| 22.320513 | 97 | 0.775416 | MrPepperoni |
ad8d113f348e1ad3a516bbea7f09a2dfd13db202 | 8,918 | hpp | C++ | src/scripting/ScriptSymbolStorage.hpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 399 | 2019-01-06T17:55:18.000Z | 2022-03-21T17:41:18.000Z | src/scripting/ScriptSymbolStorage.hpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 101 | 2019-04-18T21:03:53.000Z | 2022-01-08T13:27:01.000Z | src/scripting/ScriptSymbolStorage.hpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 56 | 2019-04-10T10:18:27.000Z | 2022-02-08T01:23:31.000Z | #pragma once
#include "ScriptSymbols.hpp"
#include <BsPrerequisites.h>
#include <RTTI/RTTIUtil.hpp>
namespace REGoth
{
namespace Scripting
{
/**
* Holds the list of all created symbols and their data.
*
* This is the only place where symbols should created and have
* their types and names be set.
*/
class ScriptSymbolStorage : public bs::IReflectable
{
public:
ScriptSymbolStorage() = default;
/**
* Appends a symbol of the given type to the storage.
*
* @tparam T Type of the symbol to create and append.
* @param name Name of the symbol to append.
*
* @return Index of the created symbol.
*/
template <typename T>
SymbolIndex appendSymbol(const bs::String& name)
{
bs::SPtr<SymbolBase> symbol = bs::bs_shared_ptr_new<T>();
mStorage.emplace_back(std::move(symbol));
SymbolIndex index = (SymbolIndex)(mStorage.size() - 1);
mStorage.back()->name = name;
mStorage.back()->index = index;
mStorage.back()->type = T::TYPE;
if (mStorage.size() >= SYMBOL_INDEX_MAX)
{
using namespace bs;
BS_EXCEPT(InvalidStateException, "Symbol Index limit reached!");
}
mSymbolsByName[name] = index;
return index;
}
/**
* Looks up the symbol at the given index.
*
* This will also do sanity checks on whether the given index is pointing to
* a valid object and throws if not.
*
* HOWEVER, this will not do any type checking, and you should only up-cast the
* resulting reference if you know what you are doing.
*
* Use the type-save variant getSymbol() instead!
*
* @param index Index of the symbol to look up.
*
* @return Reference to the symbol with the given index.
*/
SymbolBase& getSymbolBase(SymbolIndex index) const
{
throwOnInvalidSymbol(index);
return getTypedSymbolReference<SymbolBase>(index);
}
/**
* Looks up the name of the symbol at the given index.
*
* This will also do sanity checks on whether the given index is pointing to
* a valid object and throws if not.
*
* @param index Index of the symbol to look up.
*
* @return Name of the symbol with the given index.
*/
const bs::String& getSymbolName(SymbolIndex index) const
{
return getSymbolBase(index).name;
}
/**
* Looks up the symbol at the given index.
*
* This will also do sanity checks on whether the given index is pointing to
* a valid object of the correct type. Throws if not.
*
* @tparam T Type of symbol to look up.
* @param index Index of the symbol to look up.
*
* @return Reference to the symbol with the given index.
*/
template <class T>
T& getSymbol(SymbolIndex index) const
{
throwOnInvalidSymbol(index);
throwOnMismatchingType<T>(*mStorage[index]);
return getTypedSymbolReference<T>(index);
}
/**
* Looks up the symbol with the given name.
*
* This will also do sanity checks on whether the given name is referring
* to an existing symbol. Throws if not.
*
* @tparam T Type of symbol to look up.
* @param name Name of the symbol to look up.
*
* @return Reference to the symbol with the given name.
*/
template <class T>
T& getSymbol(const bs::String& name) const
{
SymbolIndex index = findIndexBySymbolName(name);
throwOnInvalidSymbol(index);
throwOnMismatchingType<T>(*mStorage[index]);
return getTypedSymbolReference<T>(index);
}
/**
* Runs a query agains the symbol storage. Assembles a list of all symbols
* for which the given function returned true.
*
* @param addIf Predicate function. If this returns true, the symbols index will
* be added to the result list.
*
* @return List of indices of all symbols where the predicate function returned true.
*/
bs::Vector<SymbolIndex> query(std::function<bool(const SymbolBase&)> addIf) const
{
bs::Vector<SymbolIndex> result;
for (const auto& s : mStorage)
{
if (addIf(*s))
{
result.push_back(s->index);
}
}
return result;
}
/**
* Looks up the type of the symbol with the given index.
*
* This will also do sanity checks on whether the given index is pointing to
* a valid object of the correct type. Throws if not.
*
* @param index Index of the symbol to lookup the type from.
*
* @return Type of the symbol with the given index.
*/
SymbolType getSymbolType(SymbolIndex index) const
{
throwOnInvalidSymbol(index);
return mStorage[index]->type;
}
/**
* Looks up the type of the symbol with the given name.
*
* This will also do sanity checks on whether the given name is referring to
* a valid object of the correct type. Throws if not.
*
* @param index Index of the symbol to lookup the type from.
*
* @return Type of the symbol with the given name.
*/
SymbolType getSymbolType(const bs::String& name) const
{
SymbolIndex index = findIndexBySymbolName(name);
throwOnInvalidSymbol(index);
return mStorage[index]->type;
}
/**
* @return Whether a symbol with the given name exists.
*/
bool hasSymbolWithName(const bs::String& name) const
{
return mSymbolsByName.find(name) != mSymbolsByName.end();
}
/**
* Tries to find the index of the symbol with the given name.
*
* Throws if no such symbol exists.
*
* @param name Name of the symbol to look for.
*
* @return Index of the symbol with the given name.
*/
SymbolIndex findIndexBySymbolName(const bs::String& name) const
{
auto it = mSymbolsByName.find(name);
if (it == mSymbolsByName.end())
{
using namespace bs;
BS_EXCEPT(InvalidStateException, "Symbol with name " + name + " does not exist!");
}
return it->second;
}
/**
* Registers a mapping of script address -> symbol index so we can get the script
* Symbol from an address. This might not fit here, since the symbol storage doesn't
* know the types of the other symbols, but this seems to be the best place...
*/
void registerFunctionAddress(SymbolIndex index)
{
SymbolScriptFunction& fn = getSymbol<SymbolScriptFunction>(index);
mFunctionsByAddress[fn.address] = index;
}
/**
* @return Symbol of the function with the given address.
*/
SymbolIndex findFunctionByAddress(bs::UINT32 scriptAddress)
{
auto it = mFunctionsByAddress.find(scriptAddress);
if (it == mFunctionsByAddress.end())
{
return SYMBOL_INDEX_INVALID;
}
return it->second;
}
private:
/**
* @return The symbol at the given index cast to the passed type.
*/
template <class T>
T& getTypedSymbolReference(SymbolIndex index) const
{
return *(T*)(mStorage[index].get());
}
template <class T>
void throwOnMismatchingType(const SymbolBase& symbol) const
{
if (T::TYPE != symbol.type)
{
using namespace bs;
BS_EXCEPT(
InvalidStateException,
bs::StringUtil::format("Symbol Type does not match expectation! Expected {0}, got {1}",
(int)T::TYPE, (int)symbol.type));
}
}
void throwOnInvalidSymbol(SymbolIndex index) const
{
using namespace bs;
if (index == SYMBOL_INDEX_INVALID)
{
BS_EXCEPT(InvalidStateException, "Symbol Index is set to INVALID!");
}
if (index >= mStorage.size())
{
BS_EXCEPT(InvalidStateException, "Symbol Index out of range!");
}
if (!mStorage[index])
{
BS_EXCEPT(InvalidStateException,
"Symbol index " + bs::toString(index) + " pointing to NULL!");
}
}
bs::Vector<bs::SPtr<SymbolBase>> mStorage;
bs::Map<bs::String, SymbolIndex> mSymbolsByName;
bs::Map<bs::UINT32, SymbolIndex> mFunctionsByAddress;
public:
REGOTH_DECLARE_RTTI_FOR_REFLECTABLE(ScriptSymbolStorage)
};
} // namespace Scripting
} // namespace REGoth
| 29.726667 | 101 | 0.585445 | KirmesBude |
ad92d8b87b81e135a743d279b9d2394a1e5980ef | 1,267 | cpp | C++ | Practice/2018/2018.9.20/HDU3401.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2018/2018.9.20/HDU3401.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2018/2018.9.20/HDU3401.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
#define ll long long
#define mem(Arr,x) memset(Arr,x,sizeof(Arr))
const int maxN=2020;
const int inf=1000000000;
int n,mxP,W;
int F[maxN][maxN];
int Q[maxN];
int main(){
int TTT;scanf("%d",&TTT);
while (TTT--){
scanf("%d%d%d",&n,&mxP,&W);
for (int i=0;i<=n;i++) for (int j=0;j<=mxP;j++) F[i][j]=-inf;
F[0][0]=0;
for (int i=1;i<=n;i++){
int as,bs,ap,bp;scanf("%d%d%d%d",&ap,&bp,&as,&bs);
int lst=max(0,i-W-1);
for (int j=0;j<=mxP;j++) F[i][j]=max(F[i][j],F[i-1][j]);
int L=1,R=0;
for (int j=0;j<=mxP;j++){
while ((L<=R)&&(Q[L]<j-as)) L++;
if (L<=R) F[i][j]=max(F[i][j],F[lst][Q[L]]+ap*Q[L]-ap*j);
while ((L<=R)&&(F[lst][Q[R]]+ap*Q[R]<=F[lst][j]+ap*j)) R--;
Q[++R]=j;
}
L=1;R=0;
for (int j=mxP;j>=0;j--){
while ((L<=R)&&(Q[L]>j+bs)) L++;
if (L<=R) F[i][j]=max(F[i][j],F[lst][Q[L]]+bp*Q[L]-bp*j);
while ((L<=R)&&(F[lst][Q[R]]+bp*Q[R]<=F[lst][j]+bp*j)) R--;
Q[++R]=j;
}
}
/*
for (int i=1;i<=n;i++){
for (int j=0;j<=mxP;j++)
cout<<F[i][j]<<" ";
cout<<endl;
}
//*/
int Ans=0;
for (int i=0;i<=mxP;i++) Ans=max(Ans,F[n][i]);
printf("%d\n",Ans);
}
return 0;
}
| 21.844828 | 63 | 0.488556 | SYCstudio |
74ec603469299cc223e9acc4b38b1f65f655f6f3 | 7,128 | cpp | C++ | src/lib/foundations/algebra_and_number_theory/null_polarity_generator.cpp | abetten/orbiter | 5994d0868a26c37676d6aadfc66a1f1bcb715c4b | [
"RSA-MD"
] | 15 | 2016-10-27T15:18:28.000Z | 2022-02-09T11:13:07.000Z | src/lib/foundations/algebra_and_number_theory/null_polarity_generator.cpp | abetten/orbiter | 5994d0868a26c37676d6aadfc66a1f1bcb715c4b | [
"RSA-MD"
] | 4 | 2019-12-09T11:49:11.000Z | 2020-07-30T17:34:45.000Z | src/lib/foundations/algebra_and_number_theory/null_polarity_generator.cpp | abetten/orbiter | 5994d0868a26c37676d6aadfc66a1f1bcb715c4b | [
"RSA-MD"
] | 15 | 2016-06-10T20:05:30.000Z | 2020-12-18T04:59:19.000Z | // null_polarity_generator.cpp
//
// Anton Betten
// December 11, 2015
#include "foundations.h"
using namespace std;
namespace orbiter {
namespace foundations {
null_polarity_generator::null_polarity_generator()
{
null();
}
null_polarity_generator::~null_polarity_generator()
{
freeself();
}
void null_polarity_generator::null()
{
nb_candidates = NULL;
cur_candidate = NULL;
candidates = NULL;
Mtx = NULL;
v = NULL;
w = NULL;
Points = NULL;
nb_gens = 0;
Data = NULL;
transversal_length = NULL;
}
void null_polarity_generator::freeself()
{
int i;
if (nb_candidates) {
FREE_int(nb_candidates);
}
if (cur_candidate) {
FREE_int(cur_candidate);
}
if (candidates) {
for (i = 0; i < n + 1; i++) {
FREE_int(candidates[i]);
}
FREE_pint(candidates);
}
if (Mtx) {
FREE_int(Mtx);
}
if (v) {
FREE_int(v);
}
if (w) {
FREE_int(w);
}
if (Points) {
FREE_int(Points);
}
if (Data) {
FREE_int(Data);
}
if (transversal_length) {
FREE_int(transversal_length);
}
null();
}
void null_polarity_generator::init(finite_field *F, int n, int verbose_level)
{
int f_v = (verbose_level >= 1);
int i;
number_theory_domain NT;
geometry_global Gg;
if (f_v) {
cout << "null_polarity_generator::init" << endl;
}
null_polarity_generator::F = F;
null_polarity_generator::n = n;
q = F->q;
qn = NT.i_power_j(q, n);
nb_candidates = NEW_int(n + 1);
cur_candidate = NEW_int(n);
candidates = NEW_pint(n + 1);
for (i = 0; i < n + 1; i++) {
candidates[i] = NEW_int(qn);
}
Mtx = NEW_int(n * n);
v = NEW_int(n);
w = NEW_int(n);
Points = NEW_int(qn * n);
for (i = 0; i < qn; i++) {
Gg.AG_element_unrank(q, Points + i * n, 1, n, i);
}
create_first_candidate_set(verbose_level);
if (f_v) {
cout << "first candidate set has size " << nb_candidates[0] << endl;
}
//backtrack_search(0 /* depth */, verbose_level);
int first_moved = n;
int nb;
nb_gens = 0;
first_moved = n;
transversal_length = NEW_int(n);
for (i = 0; i < n; i++) {
transversal_length[i] = 1;
}
count_strong_generators(nb_gens, transversal_length,
first_moved, 0, verbose_level);
if (f_v) {
cout << "We found " << nb_gens << " strong generators" << endl;
cout << "transversal_length = ";
Orbiter->Int_vec.print(cout, transversal_length, n);
cout << endl;
cout << "group order: ";
print_longinteger_after_multiplying(cout, transversal_length, n);
cout << endl;
}
Data = NEW_int(nb_gens * n * n);
nb = 0;
first_moved = n;
get_strong_generators(Data, nb, first_moved, 0, verbose_level);
if (nb != nb_gens) {
cout << "nb != nb_gens" << endl;
exit(1);
}
if (f_v) {
cout << "The strong generators are:" << endl;
for (i = 0; i < nb_gens; i++) {
cout << "generator " << i << " / " << nb_gens << ":" << endl;
Orbiter->Int_vec.matrix_print(Data + i * n * n, n, n);
}
}
if (f_v) {
cout << "null_polarity_generator::init done" << endl;
}
}
int null_polarity_generator::count_strong_generators(
int &nb, int *transversal_length, int &first_moved,
int depth, int verbose_level)
{
//int f_v = (verbose_level >= 1);
int a;
if (depth == n) {
//cout << "solution " << nb << endl;
//int_matrix_print(Mtx, n, n);
if (first_moved < n) {
transversal_length[first_moved]++;
}
nb++;
return FALSE;
}
for (cur_candidate[depth] = 0;
cur_candidate[depth] < nb_candidates[depth];
cur_candidate[depth]++) {
if (cur_candidate[depth] && depth < first_moved) {
first_moved = depth;
}
a = candidates[depth][cur_candidate[depth]];
if (FALSE) {
cout << "depth " << depth << " " << cur_candidate[depth]
<< " / " << nb_candidates[depth]
<< " which is " << a << endl;
}
Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n);
create_next_candidate_set(depth, 0 /* verbose_level */);
if (!count_strong_generators(nb, transversal_length,
first_moved, depth + 1, verbose_level) &&
depth > first_moved) {
return FALSE;
}
}
return TRUE;
}
int null_polarity_generator::get_strong_generators(
int *Data, int &nb, int &first_moved, int depth,
int verbose_level)
{
//int f_v = (verbose_level >= 1);
int a;
if (depth == n) {
//cout << "solution " << nb << endl;
//int_matrix_print(Mtx, n, n);
Orbiter->Int_vec.copy(Mtx, Data + nb * n * n, n * n);
nb++;
return FALSE;
}
for (cur_candidate[depth] = 0;
cur_candidate[depth] < nb_candidates[depth];
cur_candidate[depth]++) {
if (cur_candidate[depth] && depth < first_moved) {
first_moved = depth;
}
a = candidates[depth][cur_candidate[depth]];
if (FALSE) {
cout << "depth " << depth << " " << cur_candidate[depth]
<< " / " << nb_candidates[depth] << " which is "
<< a << endl;
}
Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n);
create_next_candidate_set(depth, 0 /* verbose_level */);
if (!get_strong_generators(Data, nb, first_moved,
depth + 1, verbose_level) && depth > first_moved) {
return FALSE;
}
}
return TRUE;
}
void null_polarity_generator::backtrack_search(
int &nb_sol, int depth, int verbose_level)
{
int f_v = (verbose_level >= 1);
int a;
if (depth == n) {
if (f_v) {
cout << "solution " << nb_sol << endl;
Orbiter->Int_vec.matrix_print(Mtx, n, n);
}
nb_sol++;
return;
}
for (cur_candidate[depth] = 0;
cur_candidate[depth] < nb_candidates[depth];
cur_candidate[depth]++) {
a = candidates[depth][cur_candidate[depth]];
if (FALSE) {
cout << "depth " << depth << " "
<< cur_candidate[depth] << " / "
<< nb_candidates[depth]
<< " which is " << a << endl;
}
Orbiter->Int_vec.copy(Points + a * n, Mtx + depth * n, n);
create_next_candidate_set(depth, 0 /* verbose_level */);
backtrack_search(nb_sol, depth + 1, verbose_level);
}
}
void null_polarity_generator::create_first_candidate_set(
int verbose_level)
{
int f_v = (verbose_level >= 1);
int i, nb;
if (f_v) {
cout << "null_polarity_generator::create_"
"first_candidate_set" << endl;
}
nb = 0;
for (i = 0; i < qn; i++) {
Orbiter->Int_vec.copy(Points + i * n, v, n);
if (dot_product(v, v) == 1) {
candidates[0][nb++] = i;
}
}
nb_candidates[0] = nb;
if (f_v) {
cout << "null_polarity_generator::create_"
"first_candidate_set done" << endl;
}
}
void null_polarity_generator::create_next_candidate_set(
int level, int verbose_level)
{
int f_v = (verbose_level >= 1);
int i, ai, nb;
if (f_v) {
cout << "null_polarity_generator::create_next_candidate_set "
"level=" << level << endl;
}
nb = 0;
Orbiter->Int_vec.copy(Mtx + level * n, v, n);
for (i = 0; i < nb_candidates[level]; i++) {
ai = candidates[level][i];
Orbiter->Int_vec.copy(Points + ai * n, w, n);
if (dot_product(v, w) == 0) {
candidates[level + 1][nb++] = ai;
}
}
nb_candidates[level + 1] = nb;
if (f_v) {
cout << "null_polarity_generator::create_next_candidate_set "
"done, found " << nb_candidates[level + 1]
<< " candidates at level " << level + 1 << endl;
}
}
int null_polarity_generator::dot_product(int *u1, int *u2)
{
return F->dot_product(n, u1, u2);
}
}
}
| 21.46988 | 77 | 0.621633 | abetten |
74f0c8a1d5da6817ae2eb75fa412eb8d051f6cfa | 8,707 | cpp | C++ | libraries/DueFlash/efc.cpp | sschiesser/Arduino_MPU9150 | 59f338eab642bd15970d929fd939312b1b5b2576 | [
"MIT"
] | 65 | 2015-01-22T15:34:13.000Z | 2022-03-24T17:29:07.000Z | libraries/DueFlash/efc.cpp | sschiesser/Arduino_MPU9150 | 59f338eab642bd15970d929fd939312b1b5b2576 | [
"MIT"
] | 16 | 2015-04-30T01:50:04.000Z | 2021-03-18T11:01:56.000Z | libraries/DueFlash/efc.cpp | sschiesser/Arduino_MPU9150 | 59f338eab642bd15970d929fd939312b1b5b2576 | [
"MIT"
] | 44 | 2015-02-23T11:01:45.000Z | 2021-05-01T07:11:13.000Z | /**
* \file
*
* \brief Enhanced Embedded Flash Controller (EEFC) driver for SAM.
*
* Copyright (c) 2011-2012 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#include "efc.h"
/// @cond 0
/**INDENT-OFF**/
#ifdef __cplusplus
extern "C" {
#endif
/**INDENT-ON**/
/// @endcond
/**
* \defgroup sam_drivers_efc_group Enhanced Embedded Flash Controller (EEFC)
*
* The Enhanced Embedded Flash Controller ensures the interface of the Flash
* block with the 32-bit internal bus.
*
* @{
*/
/* Address definition for read operation */
# define READ_BUFF_ADDR0 IFLASH0_ADDR
# define READ_BUFF_ADDR1 IFLASH1_ADDR
/* Flash Writing Protection Key */
#define FWP_KEY 0x5Au
#if (SAM4S || SAM4E)
#define EEFC_FCR_FCMD(value) \
((EEFC_FCR_FCMD_Msk & ((value) << EEFC_FCR_FCMD_Pos)))
#define EEFC_ERROR_FLAGS (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE | EEFC_FSR_FLERR)
#else
#define EEFC_ERROR_FLAGS (EEFC_FSR_FLOCKE | EEFC_FSR_FCMDE)
#endif
/*
* Local function declaration.
* Because they are RAM functions, they need 'extern' declaration.
*/
extern void efc_write_fmr(Efc *p_efc, uint32_t ul_fmr);
extern uint32_t efc_perform_fcr(Efc *p_efc, uint32_t ul_fcr);
/**
* \brief Initialize the EFC controller.
*
* \param ul_access_mode 0 for 128-bit, EEFC_FMR_FAM for 64-bit.
* \param ul_fws The number of wait states in cycle (no shift).
*
* \return 0 if successful.
*/
uint32_t efc_init(Efc *p_efc, uint32_t ul_access_mode, uint32_t ul_fws)
{
efc_write_fmr(p_efc, ul_access_mode | EEFC_FMR_FWS(ul_fws));
return EFC_RC_OK;
}
/**
* \brief Enable the flash ready interrupt.
*
* \param p_efc Pointer to an EFC instance.
*/
void efc_enable_frdy_interrupt(Efc *p_efc)
{
uint32_t ul_fmr = p_efc->EEFC_FMR;
efc_write_fmr(p_efc, ul_fmr | EEFC_FMR_FRDY);
}
/**
* \brief Disable the flash ready interrupt.
*
* \param p_efc Pointer to an EFC instance.
*/
void efc_disable_frdy_interrupt(Efc *p_efc)
{
uint32_t ul_fmr = p_efc->EEFC_FMR;
efc_write_fmr(p_efc, ul_fmr & (~EEFC_FMR_FRDY));
}
/**
* \brief Set flash access mode.
*
* \param p_efc Pointer to an EFC instance.
* \param ul_mode 0 for 128-bit, EEFC_FMR_FAM for 64-bit.
*/
void efc_set_flash_access_mode(Efc *p_efc, uint32_t ul_mode)
{
uint32_t ul_fmr = p_efc->EEFC_FMR & (~EEFC_FMR_FAM);
efc_write_fmr(p_efc, ul_fmr | ul_mode);
}
/**
* \brief Get flash access mode.
*
* \param p_efc Pointer to an EFC instance.
*
* \return 0 for 128-bit or EEFC_FMR_FAM for 64-bit.
*/
uint32_t efc_get_flash_access_mode(Efc *p_efc)
{
return (p_efc->EEFC_FMR & EEFC_FMR_FAM);
}
/**
* \brief Set flash wait state.
*
* \param p_efc Pointer to an EFC instance.
* \param ul_fws The number of wait states in cycle (no shift).
*/
void efc_set_wait_state(Efc *p_efc, uint32_t ul_fws)
{
uint32_t ul_fmr = p_efc->EEFC_FMR & (~EEFC_FMR_FWS_Msk);
efc_write_fmr(p_efc, ul_fmr | EEFC_FMR_FWS(ul_fws));
}
/**
* \brief Get flash wait state.
*
* \param p_efc Pointer to an EFC instance.
*
* \return The number of wait states in cycle (no shift).
*/
uint32_t efc_get_wait_state(Efc *p_efc)
{
return ((p_efc->EEFC_FMR & EEFC_FMR_FWS_Msk) >> EEFC_FMR_FWS_Pos);
}
/**
* \brief Perform the given command and wait until its completion (or an error).
*
* \note Unique ID commands are not supported, use efc_read_unique_id.
*
* \param p_efc Pointer to an EFC instance.
* \param ul_command Command to perform.
* \param ul_argument Optional command argument.
*
* \note This function will automatically choose to use IAP function.
*
* \return 0 if successful, otherwise returns an error code.
*/
uint32_t efc_perform_command(Efc *p_efc, uint32_t ul_command,
uint32_t ul_argument)
{
/* Unique ID commands are not supported. */
if (ul_command == EFC_FCMD_STUI || ul_command == EFC_FCMD_SPUI) {
return EFC_RC_NOT_SUPPORT;
}
/* Use IAP function with 2 parameters in ROM. */
static uint32_t(*iap_perform_command) (uint32_t, uint32_t);
uint32_t ul_efc_nb = (p_efc == EFC0) ? 0 : 1;
iap_perform_command =
(uint32_t(*)(uint32_t, uint32_t))
*((uint32_t *) CHIP_FLASH_IAP_ADDRESS);
iap_perform_command(ul_efc_nb,
EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(ul_argument) |
EEFC_FCR_FCMD(ul_command));
return (p_efc->EEFC_FSR & EEFC_ERROR_FLAGS);
}
/**
* \brief Get the current status of the EEFC.
*
* \note This function clears the value of some status bits (FLOCKE, FCMDE).
*
* \param p_efc Pointer to an EFC instance.
*
* \return The current status.
*/
uint32_t efc_get_status(Efc *p_efc)
{
return p_efc->EEFC_FSR;
}
/**
* \brief Get the result of the last executed command.
*
* \param p_efc Pointer to an EFC instance.
*
* \return The result of the last executed command.
*/
uint32_t efc_get_result(Efc *p_efc)
{
return p_efc->EEFC_FRR;
}
/**
* \brief Perform read sequence. Supported sequences are read Unique ID and
* read User Signature
*
* \param p_efc Pointer to an EFC instance.
* \param ul_cmd_st Start command to perform.
* \param ul_cmd_sp Stop command to perform.
* \param p_ul_buf Pointer to an data buffer.
* \param ul_size Buffer size.
*
* \return 0 if successful, otherwise returns an error code.
*/
RAMFUNC
uint32_t efc_perform_read_sequence(Efc *p_efc,
uint32_t ul_cmd_st, uint32_t ul_cmd_sp,
uint32_t *p_ul_buf, uint32_t ul_size)
{
volatile uint32_t ul_status;
uint32_t ul_cnt;
uint32_t *p_ul_data =
(uint32_t *) ((p_efc == EFC0) ?
READ_BUFF_ADDR0 : READ_BUFF_ADDR1);
if (p_ul_buf == NULL) {
return EFC_RC_INVALID;
}
p_efc->EEFC_FMR |= (0x1u << 16);
/* Send the Start Read command */
p_efc->EEFC_FCR = EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(0)
| EEFC_FCR_FCMD(ul_cmd_st);
/* Wait for the FRDY bit in the Flash Programming Status Register
* (EEFC_FSR) falls.
*/
do {
ul_status = p_efc->EEFC_FSR;
} while ((ul_status & EEFC_FSR_FRDY) == EEFC_FSR_FRDY);
/* The data is located in the first address of the Flash
* memory mapping.
*/
for (ul_cnt = 0; ul_cnt < ul_size; ul_cnt++) {
p_ul_buf[ul_cnt] = p_ul_data[ul_cnt];
}
/* To stop the read mode */
p_efc->EEFC_FCR =
EEFC_FCR_FKEY(FWP_KEY) | EEFC_FCR_FARG(0) |
EEFC_FCR_FCMD(ul_cmd_sp);
/* Wait for the FRDY bit in the Flash Programming Status Register (EEFC_FSR)
* rises.
*/
do {
ul_status = p_efc->EEFC_FSR;
} while ((ul_status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY);
p_efc->EEFC_FMR &= ~(0x1u << 16);
return EFC_RC_OK;
}
/**
* \brief Set mode register.
*
* \param p_efc Pointer to an EFC instance.
* \param ul_fmr Value of mode register
*/
RAMFUNC
void efc_write_fmr(Efc *p_efc, uint32_t ul_fmr)
{
p_efc->EEFC_FMR = ul_fmr;
}
/**
* \brief Perform command.
*
* \param p_efc Pointer to an EFC instance.
* \param ul_fcr Flash command.
*
* \return The current status.
*/
RAMFUNC
uint32_t efc_perform_fcr(Efc *p_efc, uint32_t ul_fcr)
{
volatile uint32_t ul_status;
p_efc->EEFC_FCR = ul_fcr;
do {
ul_status = p_efc->EEFC_FSR;
} while ((ul_status & EEFC_FSR_FRDY) != EEFC_FSR_FRDY);
return (ul_status & EEFC_ERROR_FLAGS);
}
//@}
/// @cond 0
/**INDENT-OFF**/
#ifdef __cplusplus
}
#endif
/**INDENT-ON**/
/// @endcond
| 25.533724 | 80 | 0.718847 | sschiesser |
74f0dc372993a6eb967f8ac3bcacaef6bf33825f | 825 | cpp | C++ | SkimaServer/SkimaServer/LightningPumpkinSkill.cpp | dlakwwkd/CommitAgain | 3fdad38f7951b1a58ae244bd5d68f5a92e97f633 | [
"MIT"
] | 1 | 2015-04-07T06:08:11.000Z | 2015-04-07T06:08:11.000Z | SkimaServer/SkimaServer/LightningPumpkinSkill.cpp | dlakwwkd/CommitAgain | 3fdad38f7951b1a58ae244bd5d68f5a92e97f633 | [
"MIT"
] | 1 | 2015-01-01T11:14:29.000Z | 2015-01-01T12:19:04.000Z | SkimaServer/SkimaServer/LightningPumpkinSkill.cpp | dlakwwkd/CommitAgain | 3fdad38f7951b1a58ae244bd5d68f5a92e97f633 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "LightningPumpkinSkill.h"
#include "ClientSession.h"
#include "Game.h"
#include "Player.h"
#include "Unit.h"
#include "Timer.h"
#include <time.h>
LightningPumpkinSkill::LightningPumpkinSkill(Player* owner)
{
m_Owner = owner;
m_Damage = 64;
m_Scale = Reduce(80.0f);
}
LightningPumpkinSkill::~LightningPumpkinSkill()
{
}
void LightningPumpkinSkill::SkillCast(SkillKey key, const b2Vec2& heroPos, const b2Vec2& targetPos)
{
auto hero = m_Owner->GetMyHero();
hero->EndMove();
m_TaretPos = targetPos;
auto client = m_Owner->GetClient();
client->SkillBroadCast(hero->GetUnitID(), heroPos, targetPos, key);
auto game = m_Owner->GetGame();
Timer::Push(game, 200, 10, this, &LightningPumpkinSkill::RandomAttack, Reduce(200.0f), 200, 5, 10, EF_LIGHTNING);
}
| 22.916667 | 117 | 0.705455 | dlakwwkd |
74f306a640ce5f8555d7c7dc46484aab8ccfd823 | 7,166 | cpp | C++ | openstudiocore/src/model/SurfacePropertyOtherSideConditionsModel.cpp | hongyuanjia/OpenStudio | 6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0 | [
"MIT"
] | 1 | 2019-04-21T15:38:54.000Z | 2019-04-21T15:38:54.000Z | openstudiocore/src/model/SurfacePropertyOtherSideConditionsModel.cpp | hongyuanjia/OpenStudio | 6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0 | [
"MIT"
] | null | null | null | openstudiocore/src/model/SurfacePropertyOtherSideConditionsModel.cpp | hongyuanjia/OpenStudio | 6cc52f1b66c069cf13f2b6ca2a0cc3c137c37cf0 | [
"MIT"
] | 1 | 2019-07-18T06:52:29.000Z | 2019-07-18T06:52:29.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2018, Alliance for Sustainable Energy, LLC. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* (1) Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* (2) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* (3) Neither the name of the copyright holder nor the names of any contributors may be used to endorse or promote
* products derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative
* works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without
* specific prior written permission from Alliance for Sustainable Energy, LLC.
*
* 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, THE UNITED STATES GOVERNMENT, OR ANY CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**********************************************************************************************************************/
#include "SurfacePropertyOtherSideConditionsModel.hpp"
#include "SurfacePropertyOtherSideConditionsModel_Impl.hpp"
#include <utilities/idd/IddFactory.hxx>
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/OS_SurfaceProperty_OtherSideConditionsModel_FieldEnums.hxx>
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: ResourceObject_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == SurfacePropertyOtherSideConditionsModel::iddObjectType());
}
SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: ResourceObject_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == SurfacePropertyOtherSideConditionsModel::iddObjectType());
}
SurfacePropertyOtherSideConditionsModel_Impl::SurfacePropertyOtherSideConditionsModel_Impl(const SurfacePropertyOtherSideConditionsModel_Impl& other,
Model_Impl* model,
bool keepHandle)
: ResourceObject_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& SurfacePropertyOtherSideConditionsModel_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
IddObjectType SurfacePropertyOtherSideConditionsModel_Impl::iddObjectType() const {
return SurfacePropertyOtherSideConditionsModel::iddObjectType();
}
std::string SurfacePropertyOtherSideConditionsModel_Impl::typeOfModeling() const {
boost::optional<std::string> value = getString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling,true);
OS_ASSERT(value);
return value.get();
}
bool SurfacePropertyOtherSideConditionsModel_Impl::isTypeOfModelingDefaulted() const {
return isEmpty(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling);
}
bool SurfacePropertyOtherSideConditionsModel_Impl::setTypeOfModeling(const std::string& typeOfModeling) {
bool result = setString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling, typeOfModeling);
return result;
}
void SurfacePropertyOtherSideConditionsModel_Impl::resetTypeOfModeling() {
bool result = setString(OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling, "");
OS_ASSERT(result);
}
} // detail
SurfacePropertyOtherSideConditionsModel::SurfacePropertyOtherSideConditionsModel(const Model& model)
: ResourceObject(SurfacePropertyOtherSideConditionsModel::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>());
// TODO: Appropriately handle the following required object-list fields.
bool ok = true;
// ok = setHandle();
OS_ASSERT(ok);
}
IddObjectType SurfacePropertyOtherSideConditionsModel::iddObjectType() {
return IddObjectType(IddObjectType::OS_SurfaceProperty_OtherSideConditionsModel);
}
std::vector<std::string> SurfacePropertyOtherSideConditionsModel::typeOfModelingValues() {
return getIddKeyNames(IddFactory::instance().getObject(iddObjectType()).get(),
OS_SurfaceProperty_OtherSideConditionsModelFields::TypeofModeling);
}
std::string SurfacePropertyOtherSideConditionsModel::typeOfModeling() const {
return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->typeOfModeling();
}
bool SurfacePropertyOtherSideConditionsModel::isTypeOfModelingDefaulted() const {
return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->isTypeOfModelingDefaulted();
}
bool SurfacePropertyOtherSideConditionsModel::setTypeOfModeling(const std::string& typeOfModeling) {
return getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->setTypeOfModeling(typeOfModeling);
}
void SurfacePropertyOtherSideConditionsModel::resetTypeOfModeling() {
getImpl<detail::SurfacePropertyOtherSideConditionsModel_Impl>()->resetTypeOfModeling();
}
/// @cond
SurfacePropertyOtherSideConditionsModel::SurfacePropertyOtherSideConditionsModel(std::shared_ptr<detail::SurfacePropertyOtherSideConditionsModel_Impl> impl)
: ResourceObject(std::move(impl))
{}
/// @endcond
} // model
} // openstudio
| 49.763889 | 156 | 0.712113 | hongyuanjia |
74fb4f9a9e6e4b1e55690f043bf843f1d514fa01 | 493 | hpp | C++ | libs/common/include/zia/common/Network.hpp | IamBlueSlime/Zia | 14aeccaa817171ca9fbd8221c6d9a32ea203a221 | [
"MIT"
] | 1 | 2020-03-09T12:17:55.000Z | 2020-03-09T12:17:55.000Z | libs/common/include/zia/common/Network.hpp | IamBlueSlime/Zia | 14aeccaa817171ca9fbd8221c6d9a32ea203a221 | [
"MIT"
] | null | null | null | libs/common/include/zia/common/Network.hpp | IamBlueSlime/Zia | 14aeccaa817171ca9fbd8221c6d9a32ea203a221 | [
"MIT"
] | null | null | null | /*
** EPITECH PROJECT, 2020
** CPP_zia_2019
** File description:
** zia common Network.hpp
*/
#pragma once
#include "openZia/OperatingSystem.hpp"
#if defined(SYSTEM_LINUX) || defined(SYSTEM_DARWIN)
#include <arpa/inet.h>
#include <unistd.h>
typedef int socket_t;
#elif defined(SYSTEM_WINDOWS)
#define _WINSOCKAPI_
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <BaseTsd.h>
#include <io.h>
typedef SOCKET socket_t;
#endif | 18.259259 | 51 | 0.681542 | IamBlueSlime |
74ffcc1aececed48317c8333de4994d83b35f0fa | 1,576 | cpp | C++ | src/chapter_07_concurrency/problem_064_parallel_sort_algorithm.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_07_concurrency/problem_064_parallel_sort_algorithm.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_07_concurrency/problem_064_parallel_sort_algorithm.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | #include "chapter_07_concurrency/problem_064_parallel_sort_algorithm.h"
#include <algorithm> // shuffle, sort
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#include <iostream> // cout
#include <numeric> // iota
#include <ostream>
#include <random> // default_random_engine, random_device
#include <vector>
void problem_64_main(std::ostream& os) {
std::vector<int> v(20);
std::iota(std::begin(v), std::end(v), -10);
std::ranges::shuffle(v, std::default_random_engine{ std::random_device{}() });
fmt::print(os, "v = {}\n\n", v);
{
auto w{ v };
std::sort(std::begin(w), std::end(w));
fmt::print(os, "std::sort(v); v = {}\n", w);
}
{
auto w{ v };
tmcppc::algorithm::quicksort(std::begin(w), std::end(w));
fmt::print(os, "quicksort(v); v = {}\n", w);
}
{
auto w{ v };
tmcppc::algorithm::parallel_quicksort(std::begin(w), std::end(w));
fmt::print(os, "parallel_quicksort; v = {}\n\n", w);
}
}
// Parallel sort algorithm
//
// Write a parallel version of the sort algorithm
// as defined for problem "57. Sort Algorithm", in "Chapter 6, Algorithms and Data Structures",
// which, given a pair of random access iterators to define its lower and upper bounds,
// sorts the elements of the range using the quicksort algorithm.
// The function should use the comparison operators for comparing the elements of the range.
// The level of parallelism and the way to achieve it is an implementation detail.
void problem_64_main() {
problem_64_main(std::cout);
}
| 33.531915 | 95 | 0.645939 | rturrado |
2d0217af5b5ef2ba1846bb426344741cd144532b | 830 | hpp | C++ | src/user/Session.hpp | hephaisto/sharebuy | 12a14aba0f7119d6db59f57e067d1f438f7a6329 | [
"MIT"
] | null | null | null | src/user/Session.hpp | hephaisto/sharebuy | 12a14aba0f7119d6db59f57e067d1f438f7a6329 | [
"MIT"
] | 9 | 2016-02-15T22:33:31.000Z | 2017-06-18T20:00:30.000Z | src/user/Session.hpp | hephaisto/sharebuy | 12a14aba0f7119d6db59f57e067d1f438f7a6329 | [
"MIT"
] | null | null | null | #ifndef H_SHAREBUY_SESSION
#define H_SHAREBUY_SESSION
#include <Wt/Dbo/Session>
#include <Wt/Dbo/ptr>
#include <Wt/Dbo/backend/Sqlite3>
#include <Wt/Auth/Login>
#include <Wt/Auth/PasswordService>
#include "User.hpp"
namespace dbo = Wt::Dbo;
typedef Wt::Auth::Dbo::UserDatabase<AuthInfo> UserDatabase;
class Session : public dbo::Session
{
public:
Session(const std::string& sqliteDb);
virtual ~Session();
Wt::Auth::AbstractUserDatabase& users();
Wt::Auth::Login& login() { return login_; }
static void configureAuth();
static const Wt::Auth::AuthService& auth();
static const Wt::Auth::PasswordService& passwordAuth();
static const std::vector<const Wt::Auth::OAuthService *>& oAuth();
dbo::ptr<User> user();
private:
dbo::backend::Sqlite3 connection_;
UserDatabase *users_;
Wt::Auth::Login login_;
};
#endif
| 21.842105 | 67 | 0.728916 | hephaisto |
2d04a20ace6f1ce3782ca36e1139c1e13ed135cc | 5,934 | hpp | C++ | engine/include/ph/config/GlobalConfig.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/include/ph/config/GlobalConfig.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/include/ph/config/GlobalConfig.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | // Copyright (c) Peter Hillerström (skipifzero.com, [email protected])
// For other contributors see Contributors.txt
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
#pragma once
#include <sfz/containers/DynArray.hpp>
#include <sfz/memory/Allocator.hpp>
#include "ph/config/Setting.hpp"
namespace ph {
using sfz::Allocator;
using sfz::DynArray;
// GlobalConfig
// ------------------------------------------------------------------------------------------------
struct GlobalConfigImpl; // Pimpl pattern
/// A global configuration class
///
/// The singleton instance should be acquired from the Phantasy Engine global context
///
/// Setting invariants:
/// 1, All settings are owned by the singleton instance, no one else may delete the memory.
/// 2, A setting, once created, can never be destroyed or removed during runtime.
/// 3, A setting will occupy the same place in memory for the duration of the program's runtime.
/// 4, A setting can not change section or key identifiers once created.
///
/// These invariants mean that it is safe (and expected) to store direct pointers to settings and
/// read/write to them when needed. However, settings may change type during runtime. So it is
/// recommended to store a pointer to the setting itself and not its internal int value for
/// example.
///
/// Settings are expected to stay relatively static during the runtime of a program. They are not
/// meant for communication and should not be changed unless the user specifically requests for
/// them to be changed.
class GlobalConfig {
public:
// Constructors & destructors
// --------------------------------------------------------------------------------------------
inline GlobalConfig() noexcept : mImpl(nullptr) {} // Compile fix for Emscripten
GlobalConfig(const GlobalConfig&) = delete;
GlobalConfig& operator= (const GlobalConfig&) = delete;
GlobalConfig(GlobalConfig&&) = delete;
GlobalConfig& operator= (GlobalConfig&&) = delete;
~GlobalConfig() noexcept;
// Methods
// --------------------------------------------------------------------------------------------
void init(const char* basePath, const char* fileName, Allocator* allocator) noexcept;
void destroy() noexcept;
void load() noexcept;
bool save() noexcept;
/// Gets the specified Setting. If it does not exist it will be created (type int with value 0).
/// The optional parameter "created" returns whether the Setting was created or already existed.
Setting* createSetting(const char* section, const char* key, bool* created = nullptr) noexcept;
// Getters
// --------------------------------------------------------------------------------------------
/// Gets the specified Setting. Returns nullptr if it does not exist.
Setting* getSetting(const char* section, const char* key) noexcept;
Setting* getSetting(const char* key) noexcept;
/// Returns pointers to all available settings
void getAllSettings(DynArray<Setting*>& settings) noexcept;
/// Returns all sections available
void getSections(DynArray<str32>& sections) noexcept;
/// Returns all settings available in a given section
void getSectionSettings(const char* section, DynArray<Setting*>& settings) noexcept;
// Sanitizers
// --------------------------------------------------------------------------------------------
/// A sanitizer is basically a wrapper around createSetting, with the addition that it also
/// ensures that the Setting is of the requested type and with values conforming to the
/// specified bounds. If the setting does not exist or is of an incompatible type it will be
/// set to the specified default value.
Setting* sanitizeInt(
const char* section, const char* key,
bool writeToFile = true,
const IntBounds& bounds = IntBounds(0)) noexcept;
Setting* sanitizeFloat(
const char* section, const char* key,
bool writeToFile = true,
const FloatBounds& bounds = FloatBounds(0.0f)) noexcept;
Setting* sanitizeBool(
const char* section, const char* key,
bool writeToFile = true,
const BoolBounds& bounds = BoolBounds(false)) noexcept;
Setting* sanitizeInt(
const char* section, const char* key,
bool writeToFile = true,
int32_t defaultValue = 0,
int32_t minValue = INT32_MIN,
int32_t maxValue = INT32_MAX,
int32_t step = 1) noexcept;
Setting* sanitizeFloat(
const char* section, const char* key,
bool writeToFile = true,
float defaultValue = 0.0f,
float minValue = FLT_MIN,
float maxValue = FLT_MAX) noexcept;
Setting* sanitizeBool(
const char* section, const char* key,
bool writeToFile = true,
bool defaultValue = false) noexcept;
private:
// Private members
// --------------------------------------------------------------------------------------------
GlobalConfigImpl* mImpl;
};
// Statically owned global config
// ------------------------------------------------------------------------------------------------
/// Statically owned global config. Default constructed. Only to be used for setContext() in
/// PhantasyEngineMain.cpp during boot.
GlobalConfig* getStaticGlobalConfigBoot() noexcept;
} // namespace ph
| 38.283871 | 99 | 0.6606 | PetorSFZ |
2d0610dac0adb339db6413db131b63d509369c40 | 1,866 | cpp | C++ | Source/doom.cpp | louistio/devilution | 093dc9b6f6b7b70bcf355d75c9b3c6dcb9efcb22 | [
"Unlicense"
] | 1 | 2018-07-13T13:53:54.000Z | 2018-07-13T13:53:54.000Z | Source/doom.cpp | louistio/devilution | 093dc9b6f6b7b70bcf355d75c9b3c6dcb9efcb22 | [
"Unlicense"
] | null | null | null | Source/doom.cpp | louistio/devilution | 093dc9b6f6b7b70bcf355d75c9b3c6dcb9efcb22 | [
"Unlicense"
] | 1 | 2018-07-13T13:54:03.000Z | 2018-07-13T13:54:03.000Z | //HEADER_GOES_HERE
#include "../types.h"
int doom_quest_time; // weak
int doom_stars_drawn; // weak
void *pDoomCel;
int doomflag; // weak
int DoomQuestState; // idb
int __cdecl doom_get_frame_from_time()
{
int result; // eax
if ( DoomQuestState == 36001 )
result = 31;
else
result = DoomQuestState / 1200;
return result;
}
void __cdecl doom_alloc_cel()
{
pDoomCel = DiabloAllocPtr(229376);
}
void __cdecl doom_cleanup()
{
void *v0; // ecx
v0 = pDoomCel;
pDoomCel = 0;
mem_free_dbg(v0);
}
void __cdecl doom_load_graphics()
{
if ( doom_quest_time == 31 )
{
strcpy(tempstr, "Items\\Map\\MapZDoom.CEL");
}
else if ( doom_quest_time >= 10 )
{
sprintf(tempstr, "Items\\Map\\MapZ00%i.CEL", doom_quest_time);
}
else
{
sprintf(tempstr, "Items\\Map\\MapZ000%i.CEL", doom_quest_time);
}
LoadFileWithMem(tempstr, pDoomCel);
}
// 525750: using guessed type int doom_quest_time;
void __cdecl doom_init()
{
int v0; // eax
doomflag = 1;
doom_alloc_cel();
v0 = -(doom_get_frame_from_time() != 31);
_LOBYTE(v0) = v0 & 0xE1;
doom_quest_time = v0 + 31;
doom_load_graphics();
}
// 525750: using guessed type int doom_quest_time;
// 52575C: using guessed type int doomflag;
void __cdecl doom_close()
{
if ( doomflag )
{
doomflag = 0;
doom_cleanup();
}
}
// 52575C: using guessed type int doomflag;
void __cdecl doom_draw()
{
if ( doomflag )
{
if ( doom_quest_time != 31 && ++doom_stars_drawn >= 5 )
{
doom_stars_drawn = 0;
if ( ++doom_quest_time > doom_get_frame_from_time() )
doom_quest_time = 0;
doom_load_graphics();
}
CelDecodeOnly(64, 511, pDoomCel, 1, 640);
}
}
// 525750: using guessed type int doom_quest_time;
// 525754: using guessed type int doom_stars_drawn;
// 52575C: using guessed type int doomflag;
| 19.642105 | 66 | 0.652197 | louistio |
2d0b27b4ad205dcfd07a552d479c53877489bc22 | 1,859 | hpp | C++ | src/lattices/bravias/offset.hpp | yangqi137/lattices | 91e270fd4e0899f2fc00940ef5ca6f21b0357ab8 | [
"MIT"
] | 1 | 2019-09-25T05:35:07.000Z | 2019-09-25T05:35:07.000Z | src/lattices/bravias/offset.hpp | yangqi137/lattices | 91e270fd4e0899f2fc00940ef5ca6f21b0357ab8 | [
"MIT"
] | null | null | null | src/lattices/bravias/offset.hpp | yangqi137/lattices | 91e270fd4e0899f2fc00940ef5ca6f21b0357ab8 | [
"MIT"
] | null | null | null | #ifndef LATTICES_BRAVIAS_OFFSET_HPP
#define LATTICES_BRAVIAS_OFFSET_HPP
#include "lattice.hpp"
#include <type_traits>
#include <cassert>
#include <algorithm>
namespace lattices {
namespace bravias {
template <typename TAG, typename SIZE_TYPE>
struct OffsetCat {
typedef TAG Tag;
typedef SIZE_TYPE VSize;
typedef LatticeCat<TAG, VSize> LatticeCat;
typedef typename LatticeCat::Lattice Lattice;
typedef typename LatticeCat::Vertex Vertex;
typedef typename LatticeCat::Vid Vid;
typedef typename std::make_signed<Vid>::type OffsetType;
static void offset_rewind(Vid& x,
OffsetType dx,
Vid l) {
assert(dx > -((OffsetType)l));
if (dx < 0)
dx += l;
x += dx;
x %= l;
}
struct Offset {
OffsetType dx;
OffsetType dy;
};
static Vid dx_max(const Lattice& l) { return l.lx / 2; }
static Vid dy_max(const Lattice& l) { return l.ly / 2; }
static void shift(Vertex& v, const Vertex& dv, const Lattice& l) {
v.x += dv.x;
v.x %= l.lx;
v.y += dv.y;
v.y %= l.ly;
}
static void shift(Vertex& v, const Offset& dv, const Lattice& l) {
offset_rewind(v.x, dv.dx, l.lx);
offset_rewind(v.y, dv.dy, l.ly);
}
static void shift(Vid& vid, Vid dvid, const Lattice& l) {
Vertex v = LatticeCat::vertex(vid, l);
Vertex dv = LatticeCat::vertex(dvid, l);
shift(v, dv, l);
vid = LatticeCat::vid(v, l);
}
static Offset offset(const Vertex& v0, const Vertex& v1) {
Offset dv = {v1.x - v0.x, v1.y - v0.y};
return dv;
}
static Vid dv2id(const Offset& dv, const Lattice& l) {
Vertex v = LatticeCat::vertex(0, l);
shift(v, dv, l);
return LatticeCat::vid(v, l);
}
static Offset reverse_offset(const Offset& dv, const Lattice& l) {
Offset dv2 = {-dv.dx, -dv.dy};
return dv2;
}
};
}
}
#endif
| 23.2375 | 72 | 0.622916 | yangqi137 |
2d0b3f3347cebe7280af21004e83d21a90347051 | 946 | cpp | C++ | src/dialogs/asknamedialog.cpp | Phoenard/Phoenard-Toolkit | 395ce79a3c56701073531cb2caad3637312d906c | [
"MIT"
] | 2 | 2016-04-03T19:15:10.000Z | 2020-04-19T16:06:54.000Z | src/dialogs/asknamedialog.cpp | Phoenard/Phoenard-Toolkit | 395ce79a3c56701073531cb2caad3637312d906c | [
"MIT"
] | null | null | null | src/dialogs/asknamedialog.cpp | Phoenard/Phoenard-Toolkit | 395ce79a3c56701073531cb2caad3637312d906c | [
"MIT"
] | 1 | 2020-04-19T16:06:17.000Z | 2020-04-19T16:06:17.000Z | #include "asknamedialog.h"
#include "ui_asknamedialog.h"
AskNameDialog::AskNameDialog(QWidget *parent) :
QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint),
ui(new Ui::AskNameDialog)
{
ui->setupUi(this);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
this->setFixedSize(this->size());
}
AskNameDialog::~AskNameDialog()
{
delete ui;
}
void AskNameDialog::setHelpTitle(const QString &title) {
ui->helpLabel->setText(title);
}
void AskNameDialog::on_lineEdit_textChanged(const QString &text)
{
bool isValid = (text.length() > 0);
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(isValid);
}
QString AskNameDialog::name() {
return ui->lineEdit->text();
}
void AskNameDialog::setName(const QString &name) {
ui->lineEdit->setText(name);
}
void AskNameDialog::setMaxLength(int maxLength) {
ui->lineEdit->setMaxLength(maxLength);
}
| 23.073171 | 96 | 0.714588 | Phoenard |
2d0c2ec0bcebf82902dbbf03d97d4003c6dd190c | 2,884 | cc | C++ | test/cagey/math/MatrixTest.cc | theycallmecoach/cagey-engine | 7a90826da687a1ea2837d0f614aa260aa1b63262 | [
"MIT"
] | null | null | null | test/cagey/math/MatrixTest.cc | theycallmecoach/cagey-engine | 7a90826da687a1ea2837d0f614aa260aa1b63262 | [
"MIT"
] | null | null | null | test/cagey/math/MatrixTest.cc | theycallmecoach/cagey-engine | 7a90826da687a1ea2837d0f614aa260aa1b63262 | [
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// cagey-engine - Toy 3D Engine
// Copyright (c) 2014 Kyle Girard <[email protected]>
//
// The MIT License (MIT)
//
// 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 <cagey/math/Matrix.hh>
#include "gtest/gtest.h"
#include <algorithm>
#include <type_traits>
using namespace cagey::math;
TEST(Matrix, DefaultConstructor) {
typedef Matrix<int, 5, 5> Mat5f;
Mat5f ident;
EXPECT_EQ(1, ident(2,2));
EXPECT_EQ(0, ident(2,3));
}
TEST(Matrix, FillConstructor) {
Mat4<int> mat(4,4);
EXPECT_EQ(4, mat(3,0));
EXPECT_EQ(0, mat(0,1));
Mat4<int> mata(2);
EXPECT_EQ(2, mata(3,0));
}
TEST(Matrix, ArrayConstructor) {
Mat2i ma{{{1, 2, 3, 4}}};
EXPECT_EQ(4, ma(1,1));
std::array<int, 4> b{{1, 2, 3, 4}};
Mat2i mb{b};
EXPECT_EQ(4, mb(1,1));
}
TEST(Matrix, DifferentTypeConstructor) {
Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}};
Mat2i mb{ma};
EXPECT_EQ(4, mb(1,1));
}
TEST(Matrix, PodTest) {
EXPECT_EQ(false, std::is_pod<Mat2f>::value);
}
TEST(Matrix, operatorScale) {
Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}};
ma *= 2.0f;
EXPECT_EQ(8, ma(1,1));
}
TEST(Matrix, operatorDivide) {
Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}};
EXPECT_THROW(ma/=0.0f, cagey::core::DivideByZeroException);
}
TEST(Matrix, operatorNegate) {
Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}};
ma = -ma;
EXPECT_EQ(-4, ma(1,1));
}
TEST(Matrix, adjugateTest) {
Mat2f ma{{{1.0, 2.0, 3.0, 4.0}}};
auto adj = adjugate(ma);
EXPECT_EQ(1, adj(1,1));
EXPECT_EQ(4, adj(0,0));
}
TEST(Matrix, makeScaleTest) {
auto scale = makeScale(2.0f, 2.0f, 2.0f);
EXPECT_EQ(2, scale(1,1));
}
TEST(Matrix, makeTranslationTest) {
auto trans = makeTranslation(2.0f, 2.0f, 2.0f);
EXPECT_EQ(2, trans(0,3));
}
| 27.207547 | 80 | 0.638696 | theycallmecoach |
2d0d006e1c698d81a04fb7663967dffe944ca42f | 1,813 | cpp | C++ | core/src/view/special/CallbackScreenShooter.cpp | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | 2 | 2020-10-16T10:15:37.000Z | 2021-01-21T13:06:00.000Z | core/src/view/special/CallbackScreenShooter.cpp | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | null | null | null | core/src/view/special/CallbackScreenShooter.cpp | azuki-monster/megamol | f5d75ae5630f9a71a7fbf81624bfd4f6b253c655 | [
"BSD-3-Clause"
] | 1 | 2021-01-28T01:19:54.000Z | 2021-01-28T01:19:54.000Z | /*
* CallbackScreenShooter.cpp
*
* Copyright (C) 2019 by VISUS (Universitaet Stuttgart)
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "mmcore/job/TickCall.h"
#include "mmcore/view/special/CallbackScreenShooter.h"
#include <functional>
namespace megamol {
namespace core {
namespace view {
namespace special {
CallbackScreenShooter::CallbackScreenShooter() : ScreenShooter(true),
AbstractWriterParams(std::bind(&CallbackScreenShooter::MakeSlotAvailable, this, std::placeholders::_1)),
inputSlot("inputSlot", "Slot for registering the screen shot callback function"),
tickSlot("tickSlot", "Slot for receiving a tick") {
// In- and output slots
this->inputSlot.SetCompatibleCall<CallbackScreenShooterCall::CallbackScreenShooterDescription>();
Module::MakeSlotAvailable(&this->inputSlot);
this->tickSlot.SetCallback(job::TickCall::ClassName(), job::TickCall::FunctionName(0), &CallbackScreenShooter::Run);
this->MakeSlotAvailable(&this->tickSlot);
}
CallbackScreenShooter::~CallbackScreenShooter() {
Module::Release();
}
bool CallbackScreenShooter::create() {
return true;
}
void CallbackScreenShooter::release() {
}
bool CallbackScreenShooter::Run(Call&) {
auto* call = this->inputSlot.CallAs<CallbackScreenShooterCall>();
if (call != nullptr)
{
call->SetCallback(std::bind(&CallbackScreenShooter::CreateScreenshot, this));
return (*call)();
}
return true;
}
void CallbackScreenShooter::CreateScreenshot() {
const auto filename = AbstractWriterParams::getNextFilename();
if (filename.first) {
ScreenShooter::createScreenshot(filename.second);
}
}
}
}
}
} | 27.059701 | 124 | 0.670712 | azuki-monster |
2d16b5a3cf4673ab64997dc53e89963724b50405 | 1,163 | cpp | C++ | find-duplicates-o1.cpp | whynesspower/best-of-GFG-questions | 90ef96c38965e11c0fc0987955f662d2665b4ff3 | [
"MIT"
] | 1 | 2021-11-06T14:03:06.000Z | 2021-11-06T14:03:06.000Z | find-duplicates-o1.cpp | whynesspower/best-of-GFG-questions | 90ef96c38965e11c0fc0987955f662d2665b4ff3 | [
"MIT"
] | null | null | null | find-duplicates-o1.cpp | whynesspower/best-of-GFG-questions | 90ef96c38965e11c0fc0987955f662d2665b4ff3 | [
"MIT"
] | 2 | 2021-09-12T10:15:54.000Z | 2021-09-26T20:47:19.000Z | // https://practice.geeksforgeeks.org/problems/find-duplicates-in-an-array/1#
#include <bits/stdc++.h>
using namespace std;
class Solution{
public:
vector<int> duplicates(int arr[], int n) {
int count=0;
//raverse the given array from i= 0 to n-1 elements
// Go to index arr[i]%n and increment its value by n.
for(int i=0;i<n;i++){
int index=arr[i]%n;
arr[index]+=n;
}
vector<int>ans;
// Now traverse the array again and print all those
// indexes i for which arr[i]/n is greater than 1
for(int i=0;i<n;i++){
if(arr[i]/n>=2){
ans.push_back(i);
count++;
}
}
if(count==0)ans.push_back(-1);
return ans;
}
};
// { Driver Code Starts.
int main() {
int t;
cin >> t;
while (t-- > 0) {
int n;
cin >> n;
int a[n];
for (int i = 0; i < n; i++) cin >> a[i];
Solution obj;
vector<int> ans = obj.duplicates(a, n);
for (int i : ans) cout << i << ' ';
cout << endl;
}
return 0;
}
// } Driver Code Ends | 24.744681 | 77 | 0.483233 | whynesspower |
2d1cf4110ddaa389048aef7e90547f912f684f48 | 11,954 | hpp | C++ | Tensile/Source/client/include/ResultComparison.hpp | micmelesse/Tensile | 62fb9a16909ddef08010915cfefe4c0341f48daa | [
"MIT"
] | 1 | 2021-12-03T09:42:10.000Z | 2021-12-03T09:42:10.000Z | Tensile/Source/client/include/ResultComparison.hpp | micmelesse/Tensile | 62fb9a16909ddef08010915cfefe4c0341f48daa | [
"MIT"
] | null | null | null | Tensile/Source/client/include/ResultComparison.hpp | micmelesse/Tensile | 62fb9a16909ddef08010915cfefe4c0341f48daa | [
"MIT"
] | null | null | null | /*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*******************************************************************************/
#pragma once
#include <iostream>
#include "Reference.hpp"
namespace Tensile
{
namespace Client
{
template <typename T>
struct NullComparison
{
inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber)
{
}
template <typename... Args>
inline void before(T value, size_t elemIndex, size_t elemCount)
{
}
inline void inside(T value, size_t elemIndex, size_t elemCount)
{
}
template <typename... Args>
inline void after(T value, size_t elemIndex, size_t elemCount)
{
}
void report() const {}
bool error() const { return false; }
};
template <typename T>
class PointwiseComparison
{
public:
PointwiseComparison(bool printValids, size_t printMax, bool printReport)
: m_printValids(printValids),
m_printMax(printMax),
m_doPrint(printMax > 0),
m_printReport(printReport)
{
}
inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber)
{
m_values++;
bool match = AlmostEqual(referenceValue, resultValue);
if(!match)
m_errors++;
if(!match || m_printValids)
{
if(m_doPrint)
{
if(m_printed == 0)
{
std::cout << "Index: Device | Reference" << std::endl;
}
std::cout << "[" << (m_printed) << "] "
<< " elem=" << elemNumber
<< " idx=" << elemIndex << ": "
<< resultValue
<< (match ? "==" : "!=") << referenceValue
<< std::endl;
m_printed++;
if(m_printMax >= 0 && m_printed >= m_printMax)
m_doPrint = false;
}
}
}
void report() const
{
if(0 && m_printReport)
std::cout << "Found " << m_errors << " incorrect values in " << m_values << " total values compared." << std::endl;
}
bool error() const
{
return m_errors != 0;
}
private:
size_t m_errors = 0;
size_t m_values = 0;
bool m_printValids = 0;
size_t m_printMax = 0;
size_t m_printed = 0;
bool m_doPrint = false;
bool m_printReport = false;
};
template <typename T>
struct Magnitude
{
inline static T abs(T val)
{
return std::abs(val);
}
};
template <typename T>
struct Magnitude<std::complex<T>>
{
inline static T abs(std::complex<T> val)
{
return std::abs(val);
}
};
template <>
struct Magnitude<Half>
{
inline static Half abs(Half val)
{
return static_cast<Half>(std::abs(static_cast<float>(val)));
}
};
template <typename T>
class RMSComparison
{
public:
RMSComparison(double threshold, bool printReport)
: m_threshold(threshold),
m_printReport(printReport)
{
}
inline void operator()(T referenceValue, T resultValue, size_t elemIndex, size_t elemNumber)
{
m_values++;
using m = Magnitude<T>;
m_maxReference = std::max(m_maxReference, static_cast<double>(m::abs(referenceValue)));
m_maxResult = std::max(m_maxResult, static_cast<double>(m::abs(resultValue)));
auto diff = m::abs(referenceValue - resultValue);
m_squareDifference += static_cast<double>(diff * diff);
}
inline void report() const
{
if(m_printReport)
{
std::cout << "Max reference value: " << m_maxReference
<< ", max result value: " << m_maxResult
<< " (" << m_values << " values)" << std::endl;
std::cout << "RMS Error: " << errorValue() << " (threshold: " << m_threshold << ")" << std::endl;
}
}
bool error() const
{
auto value = errorValue();
return value > m_threshold;
}
double errorValue() const
{
double maxMagnitude = std::max({m_maxReference, m_maxResult, std::numeric_limits<double>::min()});
double denom = std::sqrt(static_cast<double>(m_values)) * maxMagnitude;
return std::sqrt(m_squareDifference) / denom;
}
private:
size_t m_values = 0;
bool m_printReport = false;
double m_maxReference = 0;
double m_maxResult = 0;
double m_squareDifference = 0;
double m_threshold = 1e-7;
};
template <typename T>
class InvalidComparison
{
public:
InvalidComparison(size_t printMax, bool printReport)
: m_printMax(printMax),
m_printReport(printReport),
m_doPrintBefore(printMax > 0),
m_doPrintInside(printMax > 0),
m_doPrintAfter(printMax > 0)
{
}
inline void before(T value, size_t elemIndex, size_t elemCount)
{
m_checkedBefore++;
if(!DataInitialization::isBadOutput(value))
{
m_errorsBefore++;
if(m_doPrintBefore)
{
if(m_printedBefore == 0)
{
std::cout << "Value written before output buffer:" << std::endl;
m_printedBefore++;
}
std::cout << "Index " << elemIndex << " / " << elemCount
<< ": found " << value
<< " instead of "
<< DataInitialization::getValue<T, InitMode::BadOutput>()
<< std::endl;
if(m_printedBefore >= m_printMax)
m_doPrintBefore = false;
}
}
}
inline void inside(T value, size_t elemIndex, size_t elemCount)
{
m_checkedInside++;
if(!DataInitialization::isBadOutput(value))
{
m_errorsInside++;
if(m_doPrintInside)
{
if(m_printedInside == 0)
{
std::cout << "Value written inside output buffer, ouside tensor:" << std::endl;
m_printedInside++;
}
std::cout << "Index " << elemIndex << " / " << elemCount
<< ": found " << value
<< " instead of "
<< DataInitialization::getValue<T, InitMode::BadOutput>()
<< std::endl;
if(m_printedInside >= m_printMax)
m_doPrintInside = false;
}
}
}
inline void after(T value, size_t elemIndex, size_t elemCount)
{
m_checkedAfter++;
if(!DataInitialization::isBadOutput(value))
{
m_errorsAfter++;
if(m_doPrintAfter)
{
if(m_printedAfter == 0)
{
std::cout << "Value written after output buffer:" << std::endl;
m_printedAfter++;
}
std::cout << "Index " << elemIndex << " / " << elemCount
<< ": found " << value
<< " instead of "
<< DataInitialization::getValue<T, InitMode::BadOutput>()
<< std::endl;
if(m_printedAfter >= m_printMax)
m_doPrintAfter = false;
}
}
}
void report() const
{
if(m_printReport && (m_checkedBefore > 0 || m_checkedInside > 0 || m_checkedAfter > 0))
{
std::cout << "BOUNDS CHECK:" << std::endl;
std::cout << "Before buffer: found " << m_errorsBefore << " errors in " << m_checkedBefore << " values checked." << std::endl;
std::cout << "Inside buffer: found " << m_errorsInside << " errors in " << m_checkedInside << " values checked." << std::endl;
std::cout << "After buffer: found " << m_errorsAfter << " errors in " << m_checkedAfter << " values checked." << std::endl;
}
}
bool error() const
{
return m_errorsBefore != 0 || m_errorsInside != 0 || m_errorsAfter != 0;
}
private:
size_t m_printMax = 0;
bool m_printReport = false;
size_t m_checkedBefore = 0;
size_t m_checkedInside = 0;
size_t m_checkedAfter = 0;
size_t m_errorsBefore = 0;
size_t m_errorsInside = 0;
size_t m_errorsAfter = 0;
size_t m_printedBefore = 0;
size_t m_printedInside = 0;
size_t m_printedAfter = 0;
bool m_doPrintBefore = false;
bool m_doPrintInside = false;
bool m_doPrintAfter = false;
};
}
}
| 34.449568 | 146 | 0.446127 | micmelesse |
2d2267ed5d622867ccea91a7d7a5fab5a7da71ab | 6,676 | cpp | C++ | exportNF/release/windows/obj/src/resources/__res_49.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/src/resources/__res_49.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | exportNF/release/windows/obj/src/resources/__res_49.cpp | theblobscp/NekoFreakMod-FridayNightFunkin | 232bcb08234cfe881fd6d52b13e6ae443e105fd1 | [
"BSD-3-Clause"
] | null | null | null | // Generated by Haxe 4.2.1+bf9ff69
namespace hx {
unsigned char __res_49[] = {
0x80, 0x00, 0x00, 0x80,
60,63,120,109,108,32,118,101,114,115,
105,111,110,61,34,49,46,48,34,32,
101,110,99,111,100,105,110,103,61,34,
117,116,102,45,56,34,32,63,62,13,
10,60,100,97,116,97,62,9,13,10,
9,60,115,112,114,105,116,101,32,105,
100,61,34,98,108,97,99,107,34,32,
120,61,34,48,34,32,121,61,34,48,
34,32,119,105,100,116,104,61,34,49,
48,48,37,34,32,104,101,105,103,104,
116,61,34,49,48,48,37,34,32,99,
111,108,111,114,61,34,48,120,56,56,
48,48,48,48,48,48,34,47,62,13,
10,9,13,10,9,60,99,104,114,111,
109,101,32,105,100,61,34,98,97,99,
107,34,32,99,101,110,116,101,114,95,
120,61,34,116,114,117,101,34,32,99,
101,110,116,101,114,95,121,61,34,116,
114,117,101,34,32,119,105,100,116,104,
61,34,52,48,48,34,32,104,101,105,
103,104,116,61,34,49,48,48,34,47,
62,9,9,13,10,9,13,10,9,60,
116,101,120,116,32,105,100,61,34,116,
105,116,108,101,34,32,120,61,34,48,
34,32,121,61,34,53,34,32,119,105,
100,116,104,61,34,98,97,99,107,46,
119,105,100,116,104,34,32,116,101,120,
116,61,34,36,80,79,80,85,80,95,
84,73,84,76,69,95,68,69,70,65,
85,76,84,34,32,97,108,105,103,110,
61,34,99,101,110,116,101,114,34,62,
13,10,9,9,60,97,110,99,104,111,
114,32,120,61,34,98,97,99,107,46,
108,101,102,116,34,32,120,45,102,108,
117,115,104,61,34,108,101,102,116,34,
32,121,61,34,98,97,99,107,46,116,
111,112,34,32,121,45,102,108,117,115,
104,61,34,116,111,112,34,47,62,9,
9,13,10,9,60,47,116,101,120,116,
62,13,10,9,13,10,9,60,116,101,
120,116,32,105,100,61,34,98,111,100,
121,34,32,120,61,34,53,34,32,121,
61,34,53,34,32,119,105,100,116,104,
61,34,98,97,99,107,46,119,105,100,
116,104,45,49,48,34,32,116,101,120,
116,61,34,36,80,79,80,85,80,95,
66,79,68,89,95,68,69,70,65,85,
76,84,34,32,97,108,105,103,110,61,
34,108,101,102,116,34,62,13,10,9,
9,60,97,110,99,104,111,114,32,120,
61,34,98,97,99,107,46,108,101,102,
116,34,32,120,45,102,108,117,115,104,
61,34,108,101,102,116,34,32,121,61,
34,116,105,116,108,101,46,98,111,116,
116,111,109,34,32,121,45,102,108,117,
115,104,61,34,116,111,112,34,47,62,
9,9,13,10,9,60,47,116,101,120,
116,62,13,10,9,13,10,9,60,98,
117,116,116,111,110,32,105,100,61,34,
98,116,110,48,34,32,121,61,34,45,
53,34,32,108,97,98,101,108,61,34,
36,80,79,80,85,80,95,89,69,83,
34,62,13,10,9,9,60,97,110,99,
104,111,114,32,121,61,34,98,97,99,
107,46,98,111,116,116,111,109,34,32,
121,45,102,108,117,115,104,61,34,98,
111,116,116,111,109,34,47,62,13,10,
9,9,60,112,97,114,97,109,32,116,
121,112,101,61,34,105,110,116,34,32,
118,97,108,117,101,61,34,48,34,47,
62,9,9,13,10,9,60,47,98,117,
116,116,111,110,62,13,10,9,13,10,
9,60,98,117,116,116,111,110,32,105,
100,61,34,98,116,110,49,34,32,108,
97,98,101,108,61,34,36,80,79,80,
85,80,95,78,79,34,62,13,10,9,
9,60,97,110,99,104,111,114,32,121,
61,34,98,116,110,48,46,116,111,112,
34,32,121,45,102,108,117,115,104,61,
34,116,111,112,34,47,62,13,10,9,
9,60,112,97,114,97,109,32,116,121,
112,101,61,34,105,110,116,34,32,118,
97,108,117,101,61,34,49,34,47,62,
13,10,9,60,47,98,117,116,116,111,
110,62,13,10,9,9,13,10,9,60,
98,117,116,116,111,110,32,105,100,61,
34,98,116,110,50,34,32,108,97,98,
101,108,61,34,36,80,79,80,85,80,
95,67,65,78,67,69,76,34,62,13,
10,9,9,60,97,110,99,104,111,114,
32,121,61,34,98,116,110,48,46,116,
111,112,34,32,121,45,102,108,117,115,
104,61,34,116,111,112,34,47,62,9,
9,13,10,9,9,60,112,97,114,97,
109,32,116,121,112,101,61,34,105,110,
116,34,32,118,97,108,117,101,61,34,
50,34,47,62,13,10,9,60,47,98,
117,116,116,111,110,62,13,10,9,13,
10,9,60,109,111,100,101,32,105,100,
61,34,49,98,116,110,34,32,105,115,
95,100,101,102,97,117,108,116,61,34,
116,114,117,101,34,62,13,10,9,9,
60,115,104,111,119,32,105,100,61,34,
98,116,110,48,34,47,62,13,10,9,
9,60,104,105,100,101,32,105,100,61,
34,98,116,110,49,44,98,116,110,50,
34,47,62,13,10,9,9,60,99,104,
97,110,103,101,32,105,100,61,34,98,
116,110,48,34,32,108,97,98,101,108,
61,34,36,80,79,80,85,80,95,79,
75,34,32,119,105,100,116,104,61,34,
98,97,99,107,46,119,105,100,116,104,
42,48,46,50,53,34,47,62,13,10,
9,9,60,112,111,115,105,116,105,111,
110,32,105,100,61,34,98,116,110,48,
34,62,13,10,9,9,9,60,97,110,
99,104,111,114,32,120,61,34,98,97,
99,107,46,99,101,110,116,101,114,34,
32,120,45,102,108,117,115,104,61,34,
99,101,110,116,101,114,34,47,62,13,
10,9,9,60,47,112,111,115,105,116,
105,111,110,62,13,10,9,60,47,109,
111,100,101,62,13,10,9,13,10,9,
60,109,111,100,101,32,105,100,61,34,
50,98,116,110,34,62,13,10,9,9,
60,115,104,111,119,32,105,100,61,34,
98,116,110,48,44,98,116,110,49,34,
47,62,13,10,9,9,60,104,105,100,
101,32,105,100,61,34,98,116,110,50,
34,47,62,13,10,9,9,60,97,108,
105,103,110,32,97,120,105,115,61,34,
104,111,114,105,122,111,110,116,97,108,
34,32,115,112,97,99,105,110,103,61,
34,49,48,34,32,114,101,115,105,122,
101,61,34,116,114,117,101,34,62,13,
10,9,9,9,60,98,111,117,110,100,
115,32,108,101,102,116,61,34,98,97,
99,107,46,108,101,102,116,34,32,114,
105,103,104,116,61,34,98,97,99,107,
46,114,105,103,104,116,45,49,48,34,
47,62,9,9,13,10,9,9,9,60,
111,98,106,101,99,116,115,32,118,97,
108,117,101,61,34,98,116,110,48,44,
98,116,110,49,34,47,62,13,10,9,
9,60,47,97,108,105,103,110,62,13,
10,9,9,60,99,104,97,110,103,101,
32,105,100,61,34,98,116,110,48,34,
32,108,97,98,101,108,61,34,36,80,
79,80,85,80,95,79,75,34,47,62,
13,10,9,9,60,99,104,97,110,103,
101,32,105,100,61,34,98,116,110,49,
34,32,108,97,98,101,108,61,34,36,
80,79,80,85,80,95,67,65,78,67,
69,76,34,47,62,13,10,9,60,47,
109,111,100,101,62,13,10,9,9,13,
10,9,60,109,111,100,101,32,105,100,
61,34,51,98,116,110,34,62,13,10,
9,9,60,115,104,111,119,32,105,100,
61,34,98,116,110,48,44,98,116,110,
49,44,98,116,110,50,34,47,62,13,
10,9,9,60,97,108,105,103,110,32,
97,120,105,115,61,34,104,111,114,105,
122,111,110,116,97,108,34,32,115,112,
97,99,105,110,103,61,34,53,34,32,
114,101,115,105,122,101,61,34,116,114,
117,101,34,62,13,10,9,9,9,60,
98,111,117,110,100,115,32,108,101,102,
116,61,34,98,97,99,107,46,108,101,
102,116,43,53,34,32,114,105,103,104,
116,61,34,98,97,99,107,46,114,105,
103,104,116,45,53,34,47,62,9,9,
13,10,9,9,9,60,111,98,106,101,
99,116,115,32,118,97,108,117,101,61,
34,98,116,110,48,44,98,116,110,49,
44,98,116,110,50,34,47,62,13,10,
9,9,60,47,97,108,105,103,110,62,
13,10,9,9,60,99,104,97,110,103,
101,32,105,100,61,34,98,116,110,48,
34,32,108,97,98,101,108,61,34,36,
80,79,80,85,80,95,89,69,83,34,
47,62,13,10,9,9,60,99,104,97,
110,103,101,32,105,100,61,34,98,116,
110,49,34,32,108,97,98,101,108,61,
34,36,80,79,80,85,80,95,78,79,
34,47,62,13,10,9,9,60,99,104,
97,110,103,101,32,105,100,61,34,98,
116,110,50,34,32,108,97,98,101,108,
61,34,36,80,79,80,85,80,95,67,
65,78,67,69,76,34,47,62,13,10,
9,60,47,109,111,100,101,62,13,10,
60,47,100,97,116,97,62,0x00 };
}
| 33.888325 | 39 | 0.680348 | theblobscp |
2d22a488af91700dbdde75bec12f7c3a600d90dc | 551 | cpp | C++ | hdoj/hdu4841.cpp | songhn233/ACM_Steps | 6f2edeca9bf4fc999a8148bc90b2d8d0e59d48fe | [
"CC0-1.0"
] | 1 | 2020-08-10T21:40:21.000Z | 2020-08-10T21:40:21.000Z | hdoj/hdu4841.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | null | null | null | hdoj/hdu4841.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | null | null | null | #include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<vector>
using namespace std;
const int maxn=100000;
int n,m;
vector<int> a;
int main()
{
while(cin>>n>>m)
{
a.clear();
for(int i=0;i<2*n;i++) a.push_back(i);
int pos=0;
for(int i=0;i<n;i++)
{
pos=(pos+m-1)%a.size();
a.erase(a.begin()+pos);
}
int temp=0;
for(int i=0;i<2*n;i++)
{
if((i%50==0)&&i!=0) puts("");
if(temp<a.size()&&a[temp]==i)
{
cout<<'G';
temp++;
}
else cout<<'B';
}
puts("");puts("");
}
return 0;
}
| 14.891892 | 40 | 0.53539 | songhn233 |
2d22aaba97ced5a101977b949e833bbe27571bdf | 4,193 | cc | C++ | slvn-tech/src/slvn_buffer.cc | Planksu/slvn-tech | 628565e26b0f83f34337937f4bc0b5abf26afe5d | [
"BSD-2-Clause"
] | null | null | null | slvn-tech/src/slvn_buffer.cc | Planksu/slvn-tech | 628565e26b0f83f34337937f4bc0b5abf26afe5d | [
"BSD-2-Clause"
] | null | null | null | slvn-tech/src/slvn_buffer.cc | Planksu/slvn-tech | 628565e26b0f83f34337937f4bc0b5abf26afe5d | [
"BSD-2-Clause"
] | null | null | null | // BSD 2-Clause License
//
// Copyright (c) 2021, Antton Jokinen
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include <slvn_buffer.h>
#include <slvn_debug.h>
namespace slvn_tech
{
SlvnBuffer::SlvnBuffer(VkDevice* device, uint32_t bufferSize, VkBufferUsageFlags usage, VkSharingMode sharingMode)
{
VkBufferCreateInfo info = {};
info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
info.size = bufferSize;
info.usage = usage;
info.sharingMode = sharingMode;
VkResult result = vkCreateBuffer(*device, &info, nullptr, &mBuffer);
assert(result == VK_SUCCESS);
}
SlvnBuffer::SlvnBuffer()
{
SLVN_PRINT("ENTER");
}
SlvnBuffer::~SlvnBuffer()
{
}
SlvnResult SlvnBuffer::Deinitialize(VkDevice* device)
{
vkDestroyBuffer(*device, mBuffer, nullptr);
vkFreeMemory(*device, mMemory, nullptr);
return SlvnResult::cOk;
}
std::optional<VkDeviceSize> SlvnBuffer::getAllocationSize(VkDevice* device) const
{
VkMemoryRequirements memReqs;
vkGetBufferMemoryRequirements(*device, mBuffer, &memReqs);
return std::make_optional<VkDeviceSize>(memReqs.size);
}
std::optional<uint32_t> SlvnBuffer::getMemoryTypeIndex(VkDevice* device, VkPhysicalDevice* physDev, uint32_t wantedFlags) const
{
VkMemoryRequirements memReqs;
vkGetBufferMemoryRequirements(*device, mBuffer, &memReqs);
VkPhysicalDeviceMemoryProperties memProperties;
vkGetPhysicalDeviceMemoryProperties(*physDev, &memProperties);
std::optional<uint32_t> value = std::nullopt;
for (uint32_t i = 0; i < memProperties.memoryTypeCount; i++)
{
if ((memReqs.memoryTypeBits & (1 << i)) && ((memProperties.memoryTypes[i].propertyFlags & wantedFlags) == wantedFlags))
{
value = i;
break;
}
}
return value;
}
SlvnResult SlvnBuffer::Insert(VkDevice* device, VkPhysicalDevice* physDev, uint32_t size, const void* data)
{
uint32_t memFlags = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT;
mBufferByteSize = size;
std::optional<VkDeviceSize> bufferSize = getAllocationSize(device);
assert(bufferSize);
std::optional<uint32_t> bufferMemIndex = getMemoryTypeIndex(device, physDev, memFlags);
assert(bufferMemIndex);
VkMemoryAllocateInfo allocateInfo = {};
allocateInfo.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
allocateInfo.allocationSize = *bufferSize;
allocateInfo.memoryTypeIndex = *bufferMemIndex;
VkResult result = vkAllocateMemory(*device, &allocateInfo, nullptr, &mMemory);
assert(result == VK_SUCCESS);
result = vkBindBufferMemory(*device, mBuffer, mMemory, 0);
assert(result == VK_SUCCESS);
void* bufferMemory;
result = vkMapMemory(*device, mMemory, 0, size, 0, &bufferMemory);
assert(result == VK_SUCCESS);
std::memcpy(bufferMemory, data, size);
vkUnmapMemory(*device, mMemory);
return SlvnResult::cOk;
}
} | 34.941667 | 127 | 0.740281 | Planksu |
2d22b7af185dfcd5848585b115ea9be503cc7190 | 41 | hpp | C++ | src/_Internals/hsl_ma86z.hpp | GitBytes/hiop | 8442c75b7e1e076a8a3bf7028e3cc79c7f8cd07f | [
"BSD-3-Clause"
] | 126 | 2017-12-30T13:06:07.000Z | 2022-03-27T03:30:46.000Z | src/_Internals/hsl_ma86z.hpp | GitBytes/hiop | 8442c75b7e1e076a8a3bf7028e3cc79c7f8cd07f | [
"BSD-3-Clause"
] | 344 | 2018-01-24T22:05:38.000Z | 2022-03-31T17:49:52.000Z | src/_Internals/hsl_ma86z.hpp | GitBytes/hiop | 8442c75b7e1e076a8a3bf7028e3cc79c7f8cd07f | [
"BSD-3-Clause"
] | 30 | 2018-01-20T00:16:06.000Z | 2022-03-18T12:57:19.000Z | #define HSL_MA86Z_HEADER_NOT_CPP_READY 1
| 20.5 | 40 | 0.902439 | GitBytes |
2d245a07a632f00c2b9329b9290fda3b96c39bbf | 269 | hpp | C++ | pythran/pythonic/operator_/__ge__.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/operator_/__ge__.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/operator_/__ge__.hpp | artas360/pythran | 66dad52d52be71693043e9a7d7578cfb9cb3d1da | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_OPERATOR_GE__HPP
#define PYTHONIC_OPERATOR_GE__HPP
#include "pythonic/include/operator_/__ge__.hpp"
#include "pythonic/operator_/ge.hpp"
namespace pythonic
{
namespace operator_
{
FPROXY_IMPL(pythonic::operator_, __ge__, ge);
}
}
#endif
| 14.944444 | 49 | 0.769517 | artas360 |
2d247cd0a8f5408a4c3257dcc636fc5140146b64 | 11,226 | cpp | C++ | BGFXWidget.cpp | PetrPPetrov/bgfx-qt5-win | 1008de71ef2cb061a02ec8c7aaf9ba1a74799f16 | [
"MIT"
] | 6 | 2019-12-12T09:56:36.000Z | 2021-09-04T02:40:27.000Z | BGFXWidget.cpp | PetrPPetrov/bgfx-qt5-win | 1008de71ef2cb061a02ec8c7aaf9ba1a74799f16 | [
"MIT"
] | null | null | null | BGFXWidget.cpp | PetrPPetrov/bgfx-qt5-win | 1008de71ef2cb061a02ec8c7aaf9ba1a74799f16 | [
"MIT"
] | 3 | 2019-12-13T10:42:30.000Z | 2020-11-12T12:51:41.000Z | #include <cassert>
#include <fstream>
#include "BGFXWidget.h"
struct PosColorVertex
{
float m_x;
float m_y;
float m_z;
uint32_t m_abgr;
static void init()
{
ms_layout
.begin()
.add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
.add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
.end();
};
static bgfx::VertexLayout ms_layout;
};
bgfx::VertexLayout PosColorVertex::ms_layout;
static PosColorVertex s_cubeVertices[] =
{
{-1.0f, 1.0f, 1.0f, 0xff000000 },
{ 1.0f, 1.0f, 1.0f, 0xff0000ff },
{-1.0f, -1.0f, 1.0f, 0xff00ff00 },
{ 1.0f, -1.0f, 1.0f, 0xff00ffff },
{-1.0f, 1.0f, -1.0f, 0xffff0000 },
{ 1.0f, 1.0f, -1.0f, 0xffff00ff },
{-1.0f, -1.0f, -1.0f, 0xffffff00 },
{ 1.0f, -1.0f, -1.0f, 0xffffffff },
};
static const uint16_t s_cubeTriList[] =
{
0, 1, 2, // 0
1, 3, 2,
4, 6, 5, // 2
5, 6, 7,
0, 2, 4, // 4
4, 2, 6,
1, 5, 3, // 6
5, 7, 3,
0, 4, 1, // 8
4, 5, 1,
2, 3, 6, // 10
6, 3, 7,
};
inline const bgfx::Memory* loadMem(const std::string& filename)
{
std::ifstream in(filename.c_str(), std::ios_base::binary);
in.exceptions(std::ifstream::failbit | std::ifstream::badbit);
in.seekg(0, std::ifstream::end);
const uint32_t file_size(static_cast<uint32_t>(in.tellg()));
in.seekg(0, std::ifstream::beg);
const bgfx::Memory* mem = bgfx::alloc(file_size + 1);
if (mem && file_size > 0)
{
in.read(reinterpret_cast<char*>(mem->data), file_size);
mem->data[mem->size - 1] = '\0';
}
return mem;
}
inline bgfx::ShaderHandle loadShader(const std::string& filename)
{
std::string shader_path;
switch (bgfx::getRendererType())
{
default:
case bgfx::RendererType::Noop:
assert(false);
case bgfx::RendererType::Direct3D9: shader_path = "shaders/dx9/"; break;
case bgfx::RendererType::Direct3D11:
case bgfx::RendererType::Direct3D12: shader_path = "shaders/dx11/"; break;
case bgfx::RendererType::Gnm: shader_path = "shaders/pssl/"; break;
case bgfx::RendererType::Metal: shader_path = "shaders/metal/"; break;
case bgfx::RendererType::Nvn: shader_path = "shaders/nvn/"; break;
case bgfx::RendererType::OpenGL: shader_path = "shaders/glsl/"; break;
case bgfx::RendererType::OpenGLES: shader_path = "shaders/essl/"; break;
case bgfx::RendererType::Vulkan: shader_path = "shaders/spirv/"; break;
}
std::string file_path = shader_path + filename + ".bin";
bgfx::ShaderHandle handle = bgfx::createShader(loadMem(file_path));
bgfx::setName(handle, filename.c_str());
return handle;
}
inline bgfx::ProgramHandle loadProgram(const std::string& vs_name, const std::string& fs_name)
{
bgfx::ShaderHandle vsh = loadShader(vs_name);
bgfx::ShaderHandle fsh = BGFX_INVALID_HANDLE;
if (!fs_name.empty())
{
fsh = loadShader(fs_name);
}
return bgfx::createProgram(vsh, fsh);
}
BGFXWidget::BGFXWidget(QWidget *parent) : QOpenGLWidget(parent)
{
setDefaultCamera();
}
void BGFXWidget::initializeBGFX(int width, int height, void* native_window_handle)
{
initial_width = width;
initial_height = height;
debug = BGFX_DEBUG_NONE;
reset = BGFX_RESET_NONE;
bgfx::Init init;
init.type = bgfx::RendererType::Direct3D9; // Or OpenGL or Direct3D11
init.vendorId = BGFX_PCI_ID_NONE;
init.resolution.width = width;
init.resolution.height = height;
init.resolution.reset = reset;
init.platformData.nwh = native_window_handle;
bgfx::init(init);
bgfx::setDebug(debug);
bgfx::setViewClear(0, BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH, 0x303030ff, 1.0f, 0);
PosColorVertex::init();
// Create static vertex buffer.
m_vbh = bgfx::createVertexBuffer(
// Static data can be passed with bgfx::makeRef
bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices))
, PosColorVertex::ms_layout
);
// Create static index buffer for triangle list rendering.
m_ibh = bgfx::createIndexBuffer(
// Static data can be passed with bgfx::makeRef
bgfx::makeRef(s_cubeTriList, sizeof(s_cubeTriList))
);
// Create program from shaders.
m_program = loadProgram("vs_cubes", "fs_cubes");
}
BGFXWidget::~BGFXWidget()
{
bgfx::destroy(m_ibh);
bgfx::destroy(m_vbh);
bgfx::destroy(m_program);
bgfx::shutdown();
}
void BGFXWidget::setDefaultCamera()
{
viewer_pos = bx::Vec3(0, 0, 10);
viewer_target = bx::Vec3(0, 0, 0);
viewer_up = bx::Vec3(0, 1, 0);
rotation_radius = bx::length(sub(viewer_pos, viewer_target));
viewer_previous_pos = viewer_pos;
viewer_previous_target = viewer_target;
viewer_previous_up = viewer_up;
minimum_rotation_radius = 0.1;
maximum_rotation_radius = 1000.0;
}
void BGFXWidget::paintEvent(QPaintEvent* event)
{
float view_matrix[16];
bx::mtxLookAt(
view_matrix,
viewer_pos,
viewer_target,
viewer_up
);
float projection_matrix[16];
bx::mtxProj(
projection_matrix, 50.0f,
static_cast<float>(width()) / static_cast<float>(height()),
1.0f,
1024.0f,
bgfx::getCaps()->homogeneousDepth
);
bgfx::setViewTransform(0, view_matrix, projection_matrix);
bgfx::setViewRect(0, 0, 0, width(), height());
bgfx::touch(0);
// Set vertex and index buffer.
bgfx::setVertexBuffer(0, m_vbh);
bgfx::setIndexBuffer(m_ibh);
// Set render states.
bgfx::setState(BGFX_STATE_DEFAULT);
// Submit primitive for rendering to view 0.
bgfx::submit(0, m_program);
// Advance to next frame. Rendering thread will be kicked to
// process submitted rendering primitives.
bgfx::frame();
}
void BGFXWidget::resizeEvent(QResizeEvent* event)
{
// TODO:
}
void BGFXWidget::mouseMoveEvent(QMouseEvent *event)
{
if (left_mouse_pressed && right_mouse_pressed)
{
// Pan mode
QPointF current_point = event->localPos();
const double effective_rotation_radius = std::max(rotation_radius, 10.0);
double delta_x = (current_point.x() - previous_point.x()) / width() * effective_rotation_radius;
double delta_y = (current_point.y() - previous_point.y()) / height() * effective_rotation_radius;
auto user_position = sub(viewer_previous_pos, viewer_previous_target);
auto right = normalize(cross(viewer_up, user_position));
auto offset = add(mul(right, delta_x), mul(viewer_up, delta_y));
viewer_pos = add(viewer_previous_pos, offset);
viewer_target = add(viewer_previous_target, offset);
// Restore rotation orbit radius
viewer_target = add(viewer_pos, mul(normalize(sub(viewer_target, viewer_pos)), rotation_radius));
update();
}
else if (left_mouse_pressed)
{
// Rotation mode
QPointF current_point = event->localPos();
double delta_x = previous_point.x() - current_point.x();
double delta_y = previous_point.y() - current_point.y();
double x_rotation_angle = delta_x / width() * bx::kPi;
double y_rotation_angle = delta_y / height() * bx::kPi;
auto user_position = sub(viewer_previous_pos, viewer_previous_target);
auto rotation_x = bx::rotateAxis(viewer_previous_up, x_rotation_angle);
bx::Vec3 temp_user_position = mul(user_position, rotation_x);
auto left = normalize(cross(temp_user_position, viewer_previous_up));
auto rotation_y = bx::rotateAxis(left, y_rotation_angle);
bx::Quaternion result_rotation = mul(rotation_x, rotation_y);
auto rotated_user_position = mul(normalize(mul(user_position, result_rotation)), rotation_radius);
viewer_pos = add(viewer_previous_target, rotated_user_position);
viewer_up = normalize(mul(viewer_previous_up, result_rotation));
// Restore up vector property: up vector must be orthogonal to direction vector
auto new_left = cross(rotated_user_position, viewer_up);
viewer_up = normalize(cross(new_left, rotated_user_position));
update();
}
else if (right_mouse_pressed)
{
// First person look mode
QPointF current_point = event->localPos();
double delta_x = current_point.x() - previous_point.x();
double delta_y = current_point.y() - previous_point.y();
double x_rotation_angle = delta_x / width() * bx::kPi;
double y_rotation_angle = delta_y / height() * bx::kPi;
auto view_direction = sub(viewer_previous_target, viewer_previous_pos);
auto rotation_x = bx::rotateAxis(viewer_previous_up, x_rotation_angle);
bx::Vec3 temp_view_direction = mul(view_direction, rotation_x);
auto left = normalize(cross(viewer_previous_up, temp_view_direction));
auto rotation_y = bx::rotateAxis(left, y_rotation_angle);
bx::Quaternion result_rotation = mul(rotation_y, rotation_x);
auto rotated_view_direction = mul(normalize(mul(view_direction, result_rotation)), rotation_radius);
viewer_target = add(viewer_previous_pos, rotated_view_direction);
viewer_up = normalize(mul(viewer_previous_up, result_rotation));
// Restore up vector property: up vector must be orthogonal to direction vector
auto new_left = cross(viewer_up, rotated_view_direction);
viewer_up = normalize(cross(rotated_view_direction, new_left));
update();
}
}
void BGFXWidget::mousePressEvent(QMouseEvent *event)
{
bool left_or_right = false;
if (event->buttons() & Qt::LeftButton)
{
left_mouse_pressed = true;
left_or_right = true;
}
if (event->buttons() & Qt::RightButton)
{
right_mouse_pressed = true;
left_or_right = true;
}
if (left_or_right)
{
previous_point = event->localPos();
viewer_previous_pos = viewer_pos;
viewer_previous_target = viewer_target;
viewer_previous_up = viewer_up;
}
}
void BGFXWidget::mouseReleaseEvent(QMouseEvent *event)
{
bool left_or_right = false;
if (!(event->buttons() & Qt::LeftButton))
{
left_mouse_pressed = false;
left_or_right = true;
}
if (!(event->buttons() & Qt::RightButton))
{
right_mouse_pressed = false;
left_or_right = true;
}
if (left_or_right)
{
previous_point = event->localPos();
viewer_previous_pos = viewer_pos;
viewer_previous_target = viewer_target;
viewer_previous_up = viewer_up;
}
}
void BGFXWidget::wheelEvent(QWheelEvent *event)
{
QPoint delta = event->angleDelta();
rotation_radius += delta.y() / 1000.0f * rotation_radius;
if (rotation_radius < minimum_rotation_radius)
{
rotation_radius = minimum_rotation_radius;
}
if (rotation_radius > maximum_rotation_radius)
{
rotation_radius = maximum_rotation_radius;
}
auto user_position = sub(viewer_pos, viewer_target);
auto new_user_position = mul(normalize(user_position), rotation_radius);
viewer_pos = add(viewer_target, new_user_position);
update();
}
| 33.017647 | 108 | 0.656155 | PetrPPetrov |
2d25ff4876071ba76ab86ad68633157e3eabee35 | 956 | hpp | C++ | android-28/android/content/res/AssetFileDescriptor_AutoCloseOutputStream.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-28/android/content/res/AssetFileDescriptor_AutoCloseOutputStream.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-30/android/content/res/AssetFileDescriptor_AutoCloseOutputStream.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "../../os/ParcelFileDescriptor_AutoCloseOutputStream.hpp"
class JByteArray;
namespace android::content::res
{
class AssetFileDescriptor;
}
namespace android::content::res
{
class AssetFileDescriptor_AutoCloseOutputStream : public android::os::ParcelFileDescriptor_AutoCloseOutputStream
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit AssetFileDescriptor_AutoCloseOutputStream(const char *className, const char *sig, Ts...agv) : android::os::ParcelFileDescriptor_AutoCloseOutputStream(className, sig, std::forward<Ts>(agv)...) {}
AssetFileDescriptor_AutoCloseOutputStream(QJniObject obj);
// Constructors
AssetFileDescriptor_AutoCloseOutputStream(android::content::res::AssetFileDescriptor arg0);
// Methods
void write(JByteArray arg0) const;
void write(jint arg0) const;
void write(JByteArray arg0, jint arg1, jint arg2) const;
};
} // namespace android::content::res
| 29.875 | 230 | 0.775105 | YJBeetle |
2d261fc49eb26146deb080dcd097a5bdaccac955 | 12,375 | cxx | C++ | PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskParticleRandomizer.cxx | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskParticleRandomizer.cxx | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | PWGJE/EMCALJetTasks/UserTasks/AliAnalysisTaskParticleRandomizer.cxx | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | /**************************************************************************
* Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: R. Haake. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#include <iostream>
#include <TRandom3.h>
#include <AliLog.h>
#include <TString.h>
#include <TMath.h>
#include <TClonesArray.h>
#include <AliAODTrack.h>
#include <AliPicoTrack.h>
#include <AliEmcalJet.h>
#include <AliRhoParameter.h>
#include "TH1D.h"
#include "TH2D.h"
#include "AliAnalysisTaskEmcal.h"
#include "AliAnalysisTaskParticleRandomizer.h"
/// \cond CLASSIMP
ClassImp(AliAnalysisTaskParticleRandomizer)
/// \endcond
//_____________________________________________________________________________________________________
AliAnalysisTaskParticleRandomizer::AliAnalysisTaskParticleRandomizer() :
AliAnalysisTaskEmcal("AliAnalysisTaskParticleRandomizer", kFALSE), fRandomizeInPhi(1), fRandomizeInEta(0), fRandomizeInTheta(0), fRandomizeInPt(0), fMinPhi(0), fMaxPhi(TMath::TwoPi()), fMinEta(-0.9), fMaxEta(+0.9), fMinPt(0), fMaxPt(120), fDistributionV2(0), fDistributionV3(0), fDistributionV4(0), fDistributionV5(0), fInputArrayName(), fOutputArrayName(), fInputArray(0), fOutputArray(0), fJetRemovalRhoObj(), fJetRemovalArrayName(), fJetRemovalArray(0), fJetRemovalPtThreshold(999.), fJetEmbeddingArrayName(), fJetEmbeddingArray(0), fRandomPsi3(0), fRandom()
{
// constructor
}
//_____________________________________________________________________________________________________
AliAnalysisTaskParticleRandomizer::~AliAnalysisTaskParticleRandomizer()
{
// destructor
}
//_____________________________________________________________________________________________________
void AliAnalysisTaskParticleRandomizer::UserCreateOutputObjects()
{
// Check user input
if(fInputArrayName.IsNull())
AliWarning(Form("Name of input array not given!"));
if(fOutputArrayName.IsNull())
AliFatal(Form("Name of output array not given!"));
fRandom = new TRandom3(0);
}
//_____________________________________________________________________________________________________
void AliAnalysisTaskParticleRandomizer::ExecOnce()
{
// Check if arrays are OK
fInputArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fInputArrayName.Data())));
if(!fInputArrayName.IsNull() && !fInputArray)
AliFatal(Form("Input array '%s' not found!", fInputArrayName.Data()));
// On demand, load also jets
if(!fJetRemovalArrayName.IsNull())
{
fJetRemovalArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fJetRemovalArrayName.Data())));
if(!fJetRemovalArray)
AliError(Form("Jet array '%s' demanded but not found in event!", fJetRemovalArrayName.Data()));
}
// On demand, load array for embedding
if(!fJetEmbeddingArrayName.IsNull())
{
fJetEmbeddingArray = static_cast<TClonesArray*>(InputEvent()->FindListObject(Form("%s", fJetEmbeddingArrayName.Data())));
if(!fJetEmbeddingArray)
AliError(Form("Embedding array '%s' demanded but not found in event!", fJetEmbeddingArrayName.Data()));
}
if((InputEvent()->FindListObject(Form("%s", fOutputArrayName.Data()))))
AliFatal(Form("Output array '%s' already exists in the event! Rename it.", fInputArrayName.Data()));
if(fInputArray)
if(strcmp(fInputArray->GetClass()->GetName(), "AliAODTrack"))
AliError(Form("Track type %s not yet supported. Use AliAODTrack", fInputArray->GetClass()->GetName()));
// Copy the input array to the output array
fOutputArray = new TClonesArray("AliAODTrack");
fOutputArray->SetName(fOutputArrayName.Data());
InputEvent()->AddObject(fOutputArray);
AliAnalysisTaskEmcal::ExecOnce();
}
//_____________________________________________________________________________________________________
Bool_t AliAnalysisTaskParticleRandomizer::Run()
{
fRandomPsi3 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi3
fRandomPsi4 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi4
fRandomPsi5 = fRandom->Rndm()*TMath::Pi(); // once per event, create a random value dedicated for Psi5
Int_t accTracks = 0;
// Add events in input array
if(fInputArray)
for(Int_t iPart=0; iPart<fInputArray->GetEntries(); iPart++)
{
// Remove particles contained in jet array (on demand)
if(fJetRemovalArray && IsParticleInJet(iPart))
continue;
// Take only particles from the randomization acceptance
AliAODTrack* inputParticle = static_cast<AliAODTrack*>(fInputArray->At(iPart));
if(fRandomizeInPhi && (inputParticle->Phi() < fMinPhi || inputParticle->Phi() >= fMaxPhi) )
continue;
if( (fRandomizeInTheta || fRandomizeInEta) && (inputParticle->Eta() < fMinEta || inputParticle->Eta() >= fMaxEta) )
continue;
new ((*fOutputArray)[accTracks]) AliAODTrack(*((AliAODTrack*)fInputArray->At(iPart)));
// Randomize on demand
AliAODTrack* particle = static_cast<AliAODTrack*>(fOutputArray->At(accTracks));
RandomizeTrack(particle);
accTracks++;
}
// Add particles for embedding (on demand)
if(fJetEmbeddingArray)
for(Int_t iPart=0; iPart<fJetEmbeddingArray->GetEntries(); iPart++)
{
// Take only particles from the randomization acceptance
AliPicoTrack* inputParticle = static_cast<AliPicoTrack*>(fJetEmbeddingArray->At(iPart));
if(fRandomizeInPhi && (inputParticle->Phi() < fMinPhi || inputParticle->Phi() >= fMaxPhi) )
continue;
if( (fRandomizeInTheta || fRandomizeInEta) && (inputParticle->Eta() < fMinEta || inputParticle->Eta() >= fMaxEta) )
continue;
new ((*fOutputArray)[accTracks]) AliAODTrack(*(GetAODTrack(inputParticle)));
// Randomize on demand
AliAODTrack* particle = static_cast<AliAODTrack*>(fOutputArray->At(accTracks));
RandomizeTrack(particle);
accTracks++;
}
// std::cout << Form("%i particles from jets removed out of %i tracks. ", fInputArray->GetEntries()-accTracks, fInputArray->GetEntries()) << std::endl;
return kTRUE;
}
//_____________________________________________________________________________________________________
void AliAnalysisTaskParticleRandomizer::RandomizeTrack(AliAODTrack* particle)
{
if(fRandomizeInPhi)
particle->SetPhi(fMinPhi + fRandom->Rndm()*(fMaxPhi-fMinPhi));
if(fRandomizeInTheta)
{
Double_t minTheta = 2.*atan(exp(-fMinEta));
Double_t maxTheta = 2.*atan(exp(-fMaxEta));
particle->SetTheta(minTheta + fRandom->Rndm()*(maxTheta-minTheta));
}
if(fRandomizeInEta)
{
Double_t randomEta = fMinEta + fRandom->Rndm()*(fMaxEta-fMinEta);
Double_t randomTheta = 2.*atan(exp(-randomEta));
particle->SetTheta(randomTheta);
}
if(fRandomizeInPt)
particle->SetPt(fMinPt + fRandom->Rndm()*(fMaxPt-fMinPt));
if(fDistributionV2 || fDistributionV3 || fDistributionV4 || fDistributionV5)
particle->SetPhi(AddFlow(particle->Phi(), particle->Pt()));
}
//_____________________________________________________________________________________________________
AliAODTrack* AliAnalysisTaskParticleRandomizer::GetAODTrack(AliPicoTrack* track)
{
AliAODTrack* newTrack = new AliAODTrack();
newTrack->SetPt(track->Pt());
newTrack->SetTheta(2.*atan(exp(-track->Eta()))); // there is no setter for eta
newTrack->SetPhi(track->Phi());
newTrack->SetCharge(track->Charge());
newTrack->SetLabel(track->GetLabel());
// Hybrid tracks (compatible with LHC11h)
UInt_t filterMap = BIT(8) | BIT(9);
newTrack->SetIsHybridGlobalConstrainedGlobal();
newTrack->SetFilterMap(filterMap);
return newTrack;
}
//_____________________________________________________________________________________________________
Bool_t AliAnalysisTaskParticleRandomizer::IsParticleInJet(Int_t part)
{
for(Int_t i=0; i<fJetRemovalArray->GetEntries(); i++)
{
AliEmcalJet* tmpJet = static_cast<AliEmcalJet*>(fJetRemovalArray->At(i));
Double_t tmpPt = tmpJet->Pt() - tmpJet->Area()*GetExternalRho();
if(tmpPt >= fJetRemovalPtThreshold)
if(tmpJet->ContainsTrack(part)>=0)
return kTRUE;
}
return kFALSE;
}
//_____________________________________________________________________________________________________
Double_t AliAnalysisTaskParticleRandomizer::GetExternalRho()
{
// Get rho from event.
AliRhoParameter* rho = 0;
if (!fJetRemovalRhoObj.IsNull())
{
rho = dynamic_cast<AliRhoParameter*>(InputEvent()->FindListObject(fJetRemovalRhoObj.Data()));
if (!rho) {
AliError(Form("%s: Could not retrieve rho with name %s!", GetName(), fJetRemovalRhoObj.Data()));
return 0;
}
}
else
return 0;
return (rho->GetVal());
}
//_____________________________________________________________________________________________________
Double_t AliAnalysisTaskParticleRandomizer::AddFlow(Double_t phi, Double_t pt)
{
// adapted from AliFlowTrackSimple
Double_t precisionPhi = 1e-10;
Int_t maxNumberOfIterations = 200;
Double_t phi0=phi;
Double_t f=0.;
Double_t fp=0.;
Double_t phiprev=0.;
Int_t ptBin = 0;
// Evaluate V2 for track pt/centrality
Double_t v2 = 0;
if(fDistributionV2)
{
ptBin = fDistributionV2->GetXaxis()->FindBin(pt);
if(ptBin>fDistributionV2->GetNbinsX())
v2 = fDistributionV2->GetBinContent(fDistributionV2->GetNbinsX(), fDistributionV2->GetYaxis()->FindBin(fCent));
else if(ptBin>0)
v2 = fDistributionV2->GetBinContent(ptBin, fDistributionV2->GetYaxis()->FindBin(fCent));
}
// Evaluate V3 for track pt/centrality
Double_t v3 = 0;
if(fDistributionV3)
{
ptBin = fDistributionV3->GetXaxis()->FindBin(pt);
if(ptBin>fDistributionV3->GetNbinsX())
v3 = fDistributionV3->GetBinContent(fDistributionV3->GetNbinsX(), fDistributionV3->GetYaxis()->FindBin(fCent));
else if(ptBin>0)
v3 = fDistributionV3->GetBinContent(ptBin, fDistributionV3->GetYaxis()->FindBin(fCent));
}
// Evaluate V4 for track pt/centrality
Double_t v4 = 0;
if(fDistributionV4)
{
ptBin = fDistributionV4->GetXaxis()->FindBin(pt);
if(ptBin>fDistributionV4->GetNbinsX())
v4 = fDistributionV4->GetBinContent(fDistributionV4->GetNbinsX(), fDistributionV4->GetYaxis()->FindBin(fCent));
else if(ptBin>0)
v4 = fDistributionV4->GetBinContent(ptBin, fDistributionV4->GetYaxis()->FindBin(fCent));
}
// Evaluate V5 for track pt/centrality
Double_t v5 = 0;
if(fDistributionV5)
{
ptBin = fDistributionV5->GetXaxis()->FindBin(pt);
if(ptBin>fDistributionV5->GetNbinsX())
v5 = fDistributionV5->GetBinContent(fDistributionV5->GetNbinsX(), fDistributionV5->GetYaxis()->FindBin(fCent));
else if(ptBin>0)
v5 = fDistributionV5->GetBinContent(ptBin, fDistributionV5->GetYaxis()->FindBin(fCent));
}
// Add all v's
for (Int_t i=0; i<maxNumberOfIterations; i++)
{
phiprev=phi; //store last value for comparison
f = phi-phi0
+ v2*TMath::Sin(2.*(phi-(fEPV0+(TMath::Pi()/2.))))
+2./3.*v3*TMath::Sin(3.*(phi-fRandomPsi3))
+0.5 *v4*TMath::Sin(4.*(phi-fRandomPsi4))
+0.4 *v5*TMath::Sin(5.*(phi-fRandomPsi5));
fp = 1.0+2.0*(
+v2*TMath::Cos(2.*(phi-(fEPV0+(TMath::Pi()/2.))))
+v3*TMath::Cos(3.*(phi-fRandomPsi3))
+v4*TMath::Cos(4.*(phi-fRandomPsi4))
+v5*TMath::Cos(5.*(phi-fRandomPsi5))); //first derivative
phi -= f/fp;
if (TMath::AreEqualAbs(phiprev,phi,precisionPhi)) break;
}
return phi;
}
| 39.410828 | 563 | 0.699879 | wiechula |
2d303bab77750a62a03e74edfd4860b26dc3417a | 1,739 | cpp | C++ | dbms/src/Storages/ColumnDefault.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 85 | 2022-03-25T09:03:16.000Z | 2022-03-25T09:45:03.000Z | dbms/src/Storages/ColumnDefault.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 7 | 2022-03-25T08:59:10.000Z | 2022-03-25T09:40:13.000Z | dbms/src/Storages/ColumnDefault.cpp | solotzg/tiflash | 66f45c76692e941bc845c01349ea89de0f2cc210 | [
"Apache-2.0"
] | 11 | 2022-03-25T09:15:36.000Z | 2022-03-25T09:45:07.000Z | // Copyright 2022 PingCAP, Ltd.
//
// 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 <Parsers/queryToString.h>
#include <Storages/ColumnDefault.h>
namespace DB
{
ColumnDefaultKind columnDefaultKindFromString(const std::string & str)
{
static const std::unordered_map<std::string, ColumnDefaultKind> map{
{ "DEFAULT", ColumnDefaultKind::Default },
{ "MATERIALIZED", ColumnDefaultKind::Materialized },
{ "ALIAS", ColumnDefaultKind::Alias }
};
const auto it = map.find(str);
return it != std::end(map) ? it->second : throw Exception{"Unknown column default specifier: " + str};
}
std::string toString(const ColumnDefaultKind kind)
{
static const std::unordered_map<ColumnDefaultKind, std::string> map{
{ ColumnDefaultKind::Default, "DEFAULT" },
{ ColumnDefaultKind::Materialized, "MATERIALIZED" },
{ ColumnDefaultKind::Alias, "ALIAS" }
};
const auto it = map.find(kind);
return it != std::end(map) ? it->second : throw Exception{"Invalid ColumnDefaultKind"};
}
bool operator==(const ColumnDefault & lhs, const ColumnDefault & rhs)
{
return lhs.kind == rhs.kind && queryToString(lhs.expression) == queryToString(rhs.expression);
}
}
| 31.618182 | 106 | 0.703853 | solotzg |
2d331816394adba21c6cc67f263984cd71d3eda2 | 4,202 | hpp | C++ | src/sparse/KokkosSparse_spgemm.hpp | NexGenAnalytics/kokkos-kernels | 8381db0486674c1be943de23974821ddfb9e6c29 | [
"BSD-3-Clause"
] | null | null | null | src/sparse/KokkosSparse_spgemm.hpp | NexGenAnalytics/kokkos-kernels | 8381db0486674c1be943de23974821ddfb9e6c29 | [
"BSD-3-Clause"
] | 7 | 2020-05-04T16:43:08.000Z | 2022-01-13T16:31:17.000Z | src/sparse/KokkosSparse_spgemm.hpp | NexGenAnalytics/kokkos-kernels | 8381db0486674c1be943de23974821ddfb9e6c29 | [
"BSD-3-Clause"
] | null | null | null | /*
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Siva Rajamanickam ([email protected])
//
// ************************************************************************
//@HEADER
*/
#ifndef _KOKKOS_SPGEMM_HPP
#define _KOKKOS_SPGEMM_HPP
#include "KokkosSparse_spgemm_numeric.hpp"
#include "KokkosSparse_spgemm_symbolic.hpp"
#include "KokkosSparse_spgemm_jacobi.hpp"
namespace KokkosSparse {
template <class KernelHandle, class AMatrix, class BMatrix, class CMatrix>
void spgemm_symbolic(KernelHandle& kh, const AMatrix& A, const bool Amode,
const BMatrix& B, const bool Bmode, CMatrix& C) {
using row_map_type = typename CMatrix::row_map_type::non_const_type;
using entries_type = typename CMatrix::index_type::non_const_type;
using values_type = typename CMatrix::values_type::non_const_type;
row_map_type row_mapC(
Kokkos::view_alloc(Kokkos::WithoutInitializing, "non_const_lnow_row"),
A.numRows() + 1);
entries_type entriesC;
values_type valuesC;
KokkosSparse::Experimental::spgemm_symbolic(
&kh, A.numRows(), B.numRows(), B.numCols(), A.graph.row_map,
A.graph.entries, Amode, B.graph.row_map, B.graph.entries, Bmode,
row_mapC);
const size_t c_nnz_size = kh.get_spgemm_handle()->get_c_nnz();
if (c_nnz_size) {
entriesC = entries_type(Kokkos::view_alloc(Kokkos::WithoutInitializing, "entriesC"),
c_nnz_size);
valuesC = values_type(Kokkos::view_alloc(Kokkos::WithoutInitializing, "valuesC"),
c_nnz_size);
}
C = CMatrix("C=AB", A.numRows(), B.numCols(), c_nnz_size, valuesC, row_mapC, entriesC);
}
template <class KernelHandle, class AMatrix, class BMatrix, class CMatrix>
void spgemm_numeric(KernelHandle& kh, const AMatrix& A, const bool Amode,
const BMatrix& B, const bool Bmode, CMatrix& C) {
// using row_map_type = typename CMatrix::index_type::non_const_type;
// using entries_type = typename CMatrix::row_map_type::non_const_type;
// using values_type = typename CMatrix::values_type::non_const_type;
KokkosSparse::Experimental::spgemm_numeric(
&kh, A.numRows(), B.numRows(), B.numCols(), A.graph.row_map,
A.graph.entries, A.values, Amode, B.graph.row_map, B.graph.entries,
B.values, Bmode, C.graph.row_map, C.graph.entries, C.values);
kh.destroy_spgemm_handle();
}
} // namespace KokkosSparse
#endif
| 42.444444 | 89 | 0.700857 | NexGenAnalytics |
2d3777ba79e78170975462232ac50090c9850def | 820 | cpp | C++ | src/Actions/Action_Help.cpp | PoetaKodu/cpp-pkg | 3d5cabf4e015f4727328db430a003c189aeed88a | [
"MIT"
] | 9 | 2021-05-07T21:18:26.000Z | 2022-02-01T20:44:13.000Z | src/Actions/Action_Help.cpp | PoetaKodu/pacc | 3d5cabf4e015f4727328db430a003c189aeed88a | [
"MIT"
] | null | null | null | src/Actions/Action_Help.cpp | PoetaKodu/pacc | 3d5cabf4e015f4727328db430a003c189aeed88a | [
"MIT"
] | null | null | null | #include PACC_PCH
#include <Pacc/App/App.hpp>
#include <Pacc/App/Help.hpp>
#include <Pacc/Helpers/Formatting.hpp>
///////////////////////////////////////////////////
void PaccApp::displayHelp(bool abbrev_)
{
auto programName = fs::u8path(args[0]).stem();
auto const& style = fmt_args::s();
// Introduction:
fmt::print( "pacc v{} - a C++ package manager.\n\n"
"{USAGE}: {} [action] <params>\n\n",
PaccApp::PaccVersion,
programName.string(),
FMT_INLINE_ARG("USAGE", style.Yellow, "USAGE")
);
//
if (abbrev_)
{
fmt::print("Use \"{} help\" for more information\n", programName.string());
}
else
{
// Display actions
std::cout << "ACTIONS\n";
for (auto action : help::actions)
{
fmt::print("\t{:16}{}\n", action.first, action.second);
}
std::cout << std::endl;
}
} | 20.5 | 77 | 0.576829 | PoetaKodu |
2d3a08f639ed2b9648dd61a154dd07fec0631e68 | 1,294 | cpp | C++ | Game!/main.cpp | leonore13/Game- | d984379f5e301700f973a692fc6b92e3ef852764 | [
"Apache-2.0"
] | null | null | null | Game!/main.cpp | leonore13/Game- | d984379f5e301700f973a692fc6b92e3ef852764 | [
"Apache-2.0"
] | null | null | null | Game!/main.cpp | leonore13/Game- | d984379f5e301700f973a692fc6b92e3ef852764 | [
"Apache-2.0"
] | null | null | null | //
// main.cpp
// Game!
//
// Created by Sophia Nguyen on 2016-05-05.
// Copyright © 2016 Sophia Nguyen. All rights reserved.
//
// The story!
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
#include "Character.hpp"
using namespace std;
int main() {
string char_name;
int age;
string command;
Character Char_1(char_name, age);
cout << "Greetings. What is your name?" << "\n";
getline(cin, char_name); // get character's name
cout << "How many years have you existed in this world?" << "\n";
cin >> age; // get character's age
Char_1.setName(char_name);
Char_1.setAge(age);
cout << "\n\n" << "Hello, " << Char_1.getName() << ". A wise soul you are, your " << Char_1.getAge() << " years on this Earth will come in useful as you navigate through this adventure. To proceed, type in short commands as you think they might pretain to the environment and story you find yourself in. Have fun!" << "\n\n" << "You are in dark room, empty except for the wooden chair you sit on, a bare twin-sized bed in one corner, and a dim oil lamp sitting on a rickety night stand." << "\n\n";
while (command != "QUIT")
{
command.clear();
cin >> command;
}
return 0;
}
| 28.130435 | 502 | 0.623648 | leonore13 |
2d3c4a6ec4f2c2c3a8e7522af43e7e1c1601aeee | 1,312 | hpp | C++ | game/include/Components/PieceComponent.hpp | Hvvang/Puzzle | 0f798e3d1f4388b255a7a393b8671e4d1930cdb0 | [
"MIT"
] | null | null | null | game/include/Components/PieceComponent.hpp | Hvvang/Puzzle | 0f798e3d1f4388b255a7a393b8671e4d1930cdb0 | [
"MIT"
] | null | null | null | game/include/Components/PieceComponent.hpp | Hvvang/Puzzle | 0f798e3d1f4388b255a7a393b8671e4d1930cdb0 | [
"MIT"
] | null | null | null | #pragma once
#include <EntityManager.hpp>
#include <Components/Sprite.hpp>
#include <Components/TileComponent.hpp>
#include <array>
#include <memory>
class TileComponent;
using ::Engine::ECS::Entity;
using ::Engine::ECS::Component;
using ::Engine::ECS::Sprite;
using ::Engine::Math::Vector2i;
using ::Engine::Math::operator+=;
using ::Engine::Math::operator+;
struct PieceComponent : Component {
enum class Shape : uint8_t {
I = 73, O = 79, J = 74, L = 76, T = 84, Z = 90, S = 83
} shape;
PieceComponent() {
for (auto &tile : tiles) {
tile = ::std::make_unique<Entity>(entityManager->createEntity());
tile->addComponent<TileComponent>();
}
}
void activate() {
for (auto &tile : tiles) {
tile->activate();
tile->getComponent<TileComponent>().instance->activate();
}
}
void deactivate() {
for (auto &tile : tiles) {
tile->deactivate();
tile->getComponent<TileComponent>().instance->deactivate();
}
}
private:
::std::array<::std::unique_ptr<Entity>, 4> tiles{ nullptr };
Color color {0.1, 0.1, 0.1};
friend class PieceController;
friend class CollisionSystem;
friend class GridController;
friend class GameController;
}; | 24.296296 | 77 | 0.603659 | Hvvang |
2d3e51c7d7d3345024272f6b973d84b86d115a67 | 6,126 | cpp | C++ | src/graphics/deferredrenderer.cpp | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | src/graphics/deferredrenderer.cpp | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | src/graphics/deferredrenderer.cpp | Eae02/tank-game | 0c526b177ccc15dd49e3228489163f13335040db | [
"Zlib"
] | null | null | null | #include "deferredrenderer.h"
#include "irenderer.h"
#include "quadmesh.h"
#include "gl/shadermodule.h"
#include "../utils/ioutils.h"
#include "../settings.h"
namespace TankGame
{
constexpr GLenum DeferredRenderer::COLOR_FORMAT;
constexpr GLenum DeferredRenderer::NORMALS_AND_SPECULAR_FORMAT;
constexpr GLenum DeferredRenderer::DISTORTION_BUFFER_FORMAT;
constexpr GLenum DeferredRenderer::LIGHT_ACC_FORMAT;
static ShaderProgram LoadCompositionShader()
{
ShaderModule fragmentShader = ShaderModule::FromFile(
GetResDirectory() / "shaders" / "lighting" / "composition.fs.glsl", GL_FRAGMENT_SHADER);
return ShaderProgram({ &QuadMesh::GetVertexShader(), &fragmentShader });
}
DeferredRenderer::DeferredRenderer()
: m_compositionShader(LoadCompositionShader()) { }
void DeferredRenderer::CreateFramebuffer(int width, int height)
{
m_resolutionScale = Settings::GetInstance().GetResolutionScale();
double resScale = static_cast<double>(Settings::GetInstance().GetResolutionScale()) / 100.0;
int scaledW = static_cast<double>(width) * resScale;
int scaledH = static_cast<double>(height) * resScale;
m_geometryFramebuffer = std::make_unique<Framebuffer>();
m_depthBuffer = std::make_unique<Renderbuffer>(scaledW, scaledH, GL_DEPTH_COMPONENT16);
m_colorBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, COLOR_FORMAT);
m_colorBuffer->SetupMipmapping(false);
m_colorBuffer->SetWrapS(GL_CLAMP_TO_EDGE);
m_colorBuffer->SetWrapT(GL_CLAMP_TO_EDGE);
m_colorBuffer->SetMinFilter(GL_LINEAR);
m_colorBuffer->SetMagFilter(GL_LINEAR);
m_normalsAndSpecBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, NORMALS_AND_SPECULAR_FORMAT);
m_normalsAndSpecBuffer->SetupMipmapping(false);
m_normalsAndSpecBuffer->SetWrapS(GL_CLAMP_TO_EDGE);
m_normalsAndSpecBuffer->SetWrapT(GL_CLAMP_TO_EDGE);
m_normalsAndSpecBuffer->SetMinFilter(GL_LINEAR);
m_normalsAndSpecBuffer->SetMagFilter(GL_LINEAR);
m_distortionBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, DISTORTION_BUFFER_FORMAT);
m_distortionBuffer->SetupMipmapping(false);
m_distortionBuffer->SetWrapMode(GL_CLAMP_TO_EDGE);
m_distortionBuffer->SetMinFilter(GL_LINEAR);
m_distortionBuffer->SetMagFilter(GL_LINEAR);
glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_colorBuffer->GetID(), 0);
glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT1, m_normalsAndSpecBuffer->GetID(), 0);
glNamedFramebufferTexture(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT2, m_distortionBuffer->GetID(), 0);
glNamedFramebufferRenderbuffer(m_geometryFramebuffer->GetID(), GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, m_depthBuffer->GetID());
m_lightFramebuffer = std::make_unique<Framebuffer>();
m_lightAccBuffer = std::make_unique<Texture2D>(scaledW, scaledH, 1, LIGHT_ACC_FORMAT);
m_lightAccBuffer->SetupMipmapping(false);
m_lightAccBuffer->SetWrapMode(GL_CLAMP_TO_EDGE);
m_lightAccBuffer->SetMinFilter(GL_LINEAR);
m_lightAccBuffer->SetMagFilter(GL_LINEAR);
glNamedFramebufferTexture(m_lightFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_lightAccBuffer->GetID(), 0);
glNamedFramebufferDrawBuffer(m_lightFramebuffer->GetID(), GL_COLOR_ATTACHMENT0);
m_outputFramebuffer = std::make_unique<Framebuffer>();
m_outputBuffer = std::make_unique<Texture2D>(width, height, 1, LIGHT_ACC_FORMAT);
m_outputBuffer->SetupMipmapping(false);
m_outputBuffer->SetWrapMode(GL_CLAMP_TO_EDGE);
glNamedFramebufferTexture(m_outputFramebuffer->GetID(), GL_COLOR_ATTACHMENT0, m_outputBuffer->GetID(), 0);
glNamedFramebufferDrawBuffer(m_outputFramebuffer->GetID(), GL_COLOR_ATTACHMENT0);
m_postProcessor.OnResize(width, height);
}
bool DeferredRenderer::FramebufferOutOfDate() const
{
return m_resolutionScale != Settings::GetInstance().GetResolutionScale();
}
void DeferredRenderer::Draw(const IRenderer& renderer, const class ViewInfo& viewInfo) const
{
Framebuffer::Save();
Framebuffer::Bind(*m_geometryFramebuffer, 0, 0, m_colorBuffer->GetWidth(), m_colorBuffer->GetHeight());
const float clearColor[] = { 0.0f, 0.0f, 0.0f, 0.0f };
const float depthClear = 1.0f;
glEnable(GL_DEPTH_TEST);
// ** Geometry pass **
GLenum geometryDrawBuffers[] = { GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1 };
glNamedFramebufferDrawBuffers(m_geometryFramebuffer->GetID(), 2, geometryDrawBuffers);
glDepthMask(GL_TRUE);
glClearBufferfv(GL_COLOR, 0, clearColor);
glClearBufferfv(GL_COLOR, 1, clearColor);
glClearBufferfv(GL_DEPTH, 0, &depthClear);
renderer.DrawGeometry(viewInfo);
glEnablei(GL_BLEND, 0);
glBlendFuncSeparatei(0, GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE);
glDepthMask(GL_FALSE);
glNamedFramebufferDrawBuffer(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT0);
renderer.DrawTranslucentGeometry(viewInfo);
// ** Distortion pass **
glNamedFramebufferDrawBuffer(m_geometryFramebuffer->GetID(), GL_COLOR_ATTACHMENT2);
//Enables additive blending for this pass and the light accumulation pass
glBlendFuncSeparatei(0, GL_ONE, GL_ONE, GL_ZERO, GL_ZERO);
glClearBufferfv(GL_COLOR, 0, clearColor);
renderer.DrawDistortions(viewInfo);
glDisable(GL_DEPTH_TEST);
// ** Light pass **
Framebuffer::Bind(*m_lightFramebuffer, 0, 0, m_lightAccBuffer->GetWidth(), m_lightAccBuffer->GetHeight());
m_normalsAndSpecBuffer->Bind(0);
glClearBufferfv(GL_COLOR, 0, clearColor);
renderer.DrawLighting(viewInfo);
glDisablei(GL_BLEND, 0);
// ** Composition pass **
Framebuffer::Bind(*m_outputFramebuffer, 0, 0, m_outputBuffer->GetWidth(), m_outputBuffer->GetHeight());
m_colorBuffer->Bind(0);
m_lightAccBuffer->Bind(1);
m_compositionShader.Use();
QuadMesh::GetInstance().GetVAO().Bind();
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
m_particleRenderer.Begin(*m_lightAccBuffer);
renderer.DrawParticles(viewInfo, m_particleRenderer);
m_particleRenderer.End();
Framebuffer::Restore();
m_postProcessor.DoPostProcessing(*m_outputBuffer, *m_distortionBuffer);
}
}
| 37.353659 | 127 | 0.773425 | Eae02 |
2d42214c1315403d801c760de700eb2f2bf6f190 | 14,820 | cpp | C++ | SRC/DVD/MountSDK.cpp | ogamespec/dolwin | 7aaa864f9070ec14193f39f2e387087ccd5d0a93 | [
"CC0-1.0"
] | 107 | 2015-09-07T21:28:32.000Z | 2022-02-14T03:13:01.000Z | SRC/DVD/MountSDK.cpp | emu-russia/dolwin | 7aaa864f9070ec14193f39f2e387087ccd5d0a93 | [
"CC0-1.0"
] | 116 | 2020-03-11T16:42:02.000Z | 2021-05-27T17:05:40.000Z | SRC/DVD/MountSDK.cpp | ogamespec/dolwin | 7aaa864f9070ec14193f39f2e387087ccd5d0a93 | [
"CC0-1.0"
] | 8 | 2017-05-18T21:01:19.000Z | 2021-04-30T11:28:14.000Z | /*
Code for mounting the Dolphin SDK folder as a virtual disk.
All the necessary data (BI2, Appldr, some DOL executable, we take from the SDK). If they are not there, then the disk is simply not mounted.
*/
#include "pch.h"
using namespace Debug;
namespace DVD
{
MountDolphinSdk::MountDolphinSdk(const wchar_t * DolphinSDKPath)
{
wcscpy(directory, DolphinSDKPath);
// Load dvddata structure.
// TODO: Generate Json dynamically
auto dvdDataInfoText = Util::FileLoad(DvdDataJson);
if (dvdDataInfoText.empty())
{
Report(Channel::Norm, "Failed to load DolphinSDK dvddata json: %s\n", Util::WstringToString(DvdDataJson).c_str());
return;
}
try
{
DvdDataInfo.Deserialize(dvdDataInfoText.data(), dvdDataInfoText.size());
}
catch (...)
{
Report(Channel::Norm, "Failed to Deserialize DolphinSDK dvddata json: %s\n", Util::WstringToString(DvdDataJson).c_str());
return;
}
// Generate data blobs
if (!GenDiskId())
{
Report(Channel::Norm, "Failed to GenDiskId\n");
return;
}
if (!GenApploader())
{
Report(Channel::Norm, "Failed to GenApploader\n");
return;
}
if (!GenBi2())
{
Report(Channel::Norm, "Failed to GenBi2\n");
return;
}
if (!GenFst())
{
Report(Channel::Norm, "Failed to GenFst\n");
return;
}
if (!GenDol())
{
Report(Channel::Norm, "Failed to GenDol\n");
return;
}
if (!GenBb2())
{
Report(Channel::Norm, "Failed to GenBb2\n");
return;
}
// Generate mapping
if (!GenMap())
{
Report(Channel::Norm, "Failed to GenMap\n");
return;
}
if (!GenFileMap())
{
Report(Channel::Norm, "Failed to GenFileMap\n");
return;
}
Report(Channel::DVD, "DolphinSDK mounted!\n");
mounted = true;
}
MountDolphinSdk::~MountDolphinSdk()
{
}
void MountDolphinSdk::MapVector(std::vector<uint8_t>& v, uint32_t offset)
{
std::tuple<std::vector<uint8_t>&, uint32_t, size_t> entry(v, offset, v.size());
mapping.push_back(entry);
}
void MountDolphinSdk::MapFile(wchar_t* path, uint32_t offset)
{
size_t size = Util::FileSize(path);
std::tuple<wchar_t*, uint32_t, size_t> entry(path, offset, size);
fileMapping.push_back(entry);
}
// Check memory mapping
uint8_t* MountDolphinSdk::TranslateMemory(uint32_t offset, size_t requestedSize, size_t& maxSize)
{
for (auto it = mapping.begin(); it != mapping.end(); ++it)
{
uint8_t * ptr = std::get<0>(*it).data();
uint32_t startingOffset = std::get<1>(*it);
size_t size = std::get<2>(*it);
if (startingOffset <= offset && offset < (startingOffset + size))
{
maxSize = my_min(requestedSize, (startingOffset + size) - offset);
return ptr + (offset - startingOffset);
}
}
return nullptr;
}
// Check file mapping
FILE * MountDolphinSdk::TranslateFile(uint32_t offset, size_t requestedSize, size_t& maxSize)
{
for (auto it = fileMapping.begin(); it != fileMapping.end(); ++it)
{
wchar_t* file = std::get<0>(*it);
uint32_t startingOffset = std::get<1>(*it);
size_t size = std::get<2>(*it);
if (startingOffset <= offset && offset < (startingOffset + size))
{
maxSize = my_min(requestedSize, (startingOffset + size) - offset);
FILE* f;
f = fopen( Util::WstringToString(file).c_str(), "rb");
assert(f);
fseek(f, offset - startingOffset, SEEK_SET);
return f;
}
}
return nullptr;
}
void MountDolphinSdk::Seek(int position)
{
if (!mounted)
return;
assert(position >= 0 && position < DVD_SIZE);
currentSeek = (uint32_t)position;
}
bool MountDolphinSdk::Read(void* buffer, size_t length)
{
bool result = true;
assert(buffer);
if (!mounted)
{
memset(buffer, 0, length);
return true;
}
if (currentSeek >= DVD_SIZE)
{
memset(buffer, 0, length);
return false;
}
size_t maxLength = 0;
// First, try to enter the mapped binary blob, if it doesn't work, try the mapped file.
uint8_t* ptr = TranslateMemory(currentSeek, length, maxLength);
if (ptr != nullptr)
{
memcpy(buffer, ptr, maxLength);
if (maxLength < length)
{
memset((uint8_t *)buffer + maxLength, 0, length - maxLength);
}
}
else
{
FILE* f = TranslateFile(currentSeek, length, maxLength);
if (f != nullptr)
{
fread(buffer, 1, maxLength, f);
if (maxLength < length)
{
memset((uint8_t*)buffer + maxLength, 0, length - maxLength);
}
fclose(f);
}
else
{
// None of the options came up - return zeros.
memset(buffer, 0, length);
result = false;
}
}
currentSeek += (uint32_t)length;
return result;
}
#pragma region "Data Generators"
// In addition to the actual files, the DVD image also contains a number of important binary data: DiskID, Apploader image, main program (DOL), BootInfo2 and BootBlock2 structures and FST.
// Generating almost all blobs is straightforward, with the exception of the FST, which will have to tinker with.
bool MountDolphinSdk::GenDiskId()
{
DiskId.resize(sizeof(DiskID));
DiskID* id = (DiskID*)DiskId.data();
id->gameName[0] = 'S';
id->gameName[1] = 'D';
id->gameName[2] = 'K';
id->gameName[3] = 'E';
id->company[0] = '0';
id->company[1] = '1';
id->magicNumber = _BYTESWAP_UINT32(DVD_DISKID_MAGIC);
GameName.resize(0x400);
memset(GameName.data(), 0, GameName.size());
strcpy((char *)GameName.data(), "GameCube SDK");
return true;
}
bool MountDolphinSdk::GenApploader()
{
auto path = fmt::format(L"{:s}{:s}", directory, AppldrPath);
AppldrData = Util::FileLoad(path);
return true;
}
/// <summary>
/// Unfortunately, all demos in the SDK are in ELF format. Therefore, we will use PONG.DOL as the main program, which is included in each Dolwin release and is a full resident of the project :p
/// </summary>
/// <returns></returns>
bool MountDolphinSdk::GenDol()
{
Dol = Util::FileLoad(DolPath);
return true;
}
bool MountDolphinSdk::GenBi2()
{
auto path = fmt::format(L"{:s}{:s}", directory, Bi2Path);
Bi2Data = Util::FileLoad(path);
return true;
}
/// <summary>
/// Add a string with the name of the entry (directory or file name) to the NameTable.
/// </summary>
/// <param name="str"></param>
void MountDolphinSdk::AddString(std::string str)
{
for (auto& c : str)
{
NameTableData.push_back(c);
}
NameTableData.push_back(0);
}
/// <summary>
/// Process original Json with dvddata directory structure. The Json structure is designed to accommodate the weird FST feature when a directory is in the middle of files.
/// For a more detailed description of this oddity, see `dolwin-docs\RE\DVD\FSTNotes.md`.
/// The method is recursive tree descent.
/// In the process, meta information is added to the original Json structure, which is used by the `WalkAndGenerateFst` method to create the final binary FST blob.
/// </summary>
/// <param name="entry"></param>
void MountDolphinSdk::ParseDvdDataEntryForFst(Json::Value* entry)
{
Json::Value* parent = nullptr;
if (entry->type != Json::ValueType::Object)
{
return;
}
if (entry->children.size() != 0)
{
// Directory
// Save directory name offset
size_t nameOffset = NameTableData.size();
if (entry->name)
{
// Root has no name
AddString(entry->name);
}
entry->AddInt("nameOffset", (int)nameOffset);
entry->AddBool("dir", true);
// Save current FST index for directory
entry->AddInt("entryId", entryCounter);
entryCounter++;
// Reset totalChildren counter
entry->AddInt("totalChildren", 0);
}
else
{
// File.
// Differs from a directory in that it has no descendants
assert(entry->name);
std::string path = entry->name;
size_t nameOffset = NameTableData.size();
AddString(path);
parent = entry->parent;
// Save file name offset
entry->AddInt("nameOffset", (int)nameOffset);
// Generate full path to file
do
{
if (parent->ByName("dir"))
{
path = (parent->name ? parent->name + std::string("/") : "/") + path;
}
parent = parent->parent;
} while (parent != nullptr);
assert(path.size() < DVD_MAXPATH);
wchar_t filePath[0x1000] = { 0, };
wcscat(filePath, directory);
wcscat(filePath, FilesRoot);
wchar_t* filePathPtr = filePath + wcslen(filePath);
for (size_t i = 0; i < path.size(); i++)
{
*filePathPtr++ = (wchar_t)path[i];
}
*filePathPtr++ = 0;
//Report(Channel::Norm, "Processing file: %s\n", path.c_str());
// Save file offset
entry->AddInt("fileOffset", userFilesStart + userFilesOffset);
// Save file size
size_t fileSize = Util::FileSize(filePath);
entry->AddInt("fileSize", (int)fileSize);
userFilesOffset += RoundUp32((uint32_t)fileSize);
// Save file path
entry->AddString("filePath", filePath);
// Adjust entry counter
entry->AddInt("entryId", entryCounter);
entryCounter++;
}
// Update parent sibling counters
parent = entry->parent;
while (parent)
{
Json::Value* totalChildren = parent->ByName("totalChildren");
if (totalChildren) totalChildren->value.AsInt++;
parent = parent->parent; // :p
}
// Recursively process descendants
if (entry->ByName("dir") != nullptr)
{
for (auto it = entry->children.begin(); it != entry->children.end(); ++it)
{
ParseDvdDataEntryForFst(*it);
}
}
}
/// <summary>
/// Based on the Json structure with the data of the dvddata directory tree, in which meta-information is added, the final FST binary blob is built.
/// </summary>
/// <param name="entry"></param>
void MountDolphinSdk::WalkAndGenerateFst(Json::Value* entry)
{
DVDFileEntry fstEntry = { 0 };
if (entry->type != Json::ValueType::Object)
{
return;
}
Json::Value* isDir = entry->ByName("dir");
if (isDir)
{
// Directory
fstEntry.isDir = 1;
Json::Value* nameOffset = entry->ByName("nameOffset");
assert(nameOffset);
if (nameOffset)
{
fstEntry.nameOffsetHi = (uint8_t)(nameOffset->value.AsInt >> 16);
fstEntry.nameOffsetLo = _BYTESWAP_UINT16((uint16_t)nameOffset->value.AsInt);
}
if (entry->parent)
{
Json::Value* parentId = entry->parent->ByName("entryId");
if (parentId)
{
fstEntry.parentOffset = _BYTESWAP_UINT32((uint32_t)parentId->value.AsInt);
}
}
Json::Value* entryId = entry->ByName("entryId");
Json::Value* totalChildren = entry->ByName("totalChildren");
if (entryId && totalChildren)
{
fstEntry.nextOffset = _BYTESWAP_UINT32((uint32_t)(entryId->value.AsInt + totalChildren->value.AsInt) + 1);
}
FstData.insert(FstData.end(), (uint8_t*)&fstEntry, (uint8_t*)&fstEntry + sizeof(fstEntry));
if (logMount)
{
Report(Channel::Norm, "%d: directory: %s. nextOffset: %d\n",
entryId->value.AsInt, entry->name, _BYTESWAP_UINT32(fstEntry.nextOffset));
}
for (auto it = entry->children.begin(); it != entry->children.end(); ++it)
{
WalkAndGenerateFst(*it);
}
}
else
{
// File
Json::Value* entryId = entry->ByName("entryId");
Json::Value* nameOffsetValue = entry->ByName("nameOffset");
Json::Value* fileOffsetValue = entry->ByName("fileOffset");
Json::Value* fileSizeValue = entry->ByName("fileSize");
assert(nameOffsetValue && fileOffsetValue && fileSizeValue);
fstEntry.isDir = 0;
uint32_t nameOffset = (uint32_t)(nameOffsetValue->value.AsInt);
uint32_t fileOffset = (uint32_t)(fileOffsetValue->value.AsInt);
uint32_t fileSize = (uint32_t)(fileSizeValue->value.AsInt);
fstEntry.nameOffsetHi = (uint8_t)(nameOffset >> 16);
fstEntry.nameOffsetLo = _BYTESWAP_UINT16((uint16_t)nameOffset);
fstEntry.fileOffset = _BYTESWAP_UINT32(fileOffset);
fstEntry.fileLength = _BYTESWAP_UINT32(fileSize);
FstData.insert(FstData.end(), (uint8_t*)&fstEntry, (uint8_t*)&fstEntry + sizeof(fstEntry));
if (logMount)
{
Report(Channel::Norm, "%d: file: %s\n", entryId->value.AsInt, entry->name);
}
}
}
// The basic idea behind generating FST is to walk by DvdDataJson.
// When traversing a structure a specific meta-information is attached to each node.
// After generation, this meta-information is collected in a final collection (FST).
bool MountDolphinSdk::GenFst()
{
try
{
ParseDvdDataEntryForFst(DvdDataInfo.root.children.back());
}
catch (...)
{
Report(Channel::Norm, "ParseDvdDataEntryForFst failed!\n");
return false;
}
if (logMount)
{
JDI::Hub.Dump(DvdDataInfo.root.children.back());
}
try
{
WalkAndGenerateFst(DvdDataInfo.root.children.back());
}
catch (...)
{
Report(Channel::Norm, "WalkAndGenerateFst failed!\n");
return false;
}
// Add Name Table to the end
FstData.insert(FstData.end(), NameTableData.begin(), NameTableData.end());
Util::FileSave(L"Data/DolphinSdkFST.bin", FstData);
return true;
}
bool MountDolphinSdk::GenBb2()
{
DVDBB2 bb2 = { 0 };
bb2.bootFilePosition = RoundUpSector(DVD_APPLDR_OFFSET + (uint32_t)AppldrData.size());
bb2.FSTLength = (uint32_t)FstData.size();
bb2.FSTMaxLength = bb2.FSTLength;
bb2.FSTPosition = RoundUpSector(bb2.bootFilePosition + (uint32_t)Dol.size() + DVD_SECTOR_SIZE);
bb2.userPosition = 0x80030000; // Ignored
bb2.userLength = RoundUpSector(bb2.FSTLength);
Bb2Data.resize(sizeof(DVDBB2));
memcpy(Bb2Data.data(), &bb2, sizeof(bb2));
return true;
}
bool MountDolphinSdk::GenMap()
{
MapVector(DiskId, DVD_ID_OFFSET);
MapVector(GameName, sizeof(DiskID));
MapVector(Bb2Data, DVD_BB2_OFFSET);
MapVector(Bi2Data, DVD_BI2_OFFSET);
MapVector(AppldrData, DVD_APPLDR_OFFSET);
DVDBB2* bb2 = (DVDBB2 *)Bb2Data.data();
MapVector(Dol, bb2->bootFilePosition);
MapVector(FstData, bb2->FSTPosition);
SwapArea(bb2, sizeof(DVDBB2));
return true;
}
void MountDolphinSdk::WalkAndMapFiles(Json::Value* entry)
{
if (entry->type != Json::ValueType::Object)
{
return;
}
Json::Value* isDir = entry->ByName("dir");
if (!isDir)
{
Json::Value* filePath = entry->ByName("filePath");
Json::Value* fileOffset = entry->ByName("fileOffset");
assert(filePath && fileOffset);
MapFile(filePath->value.AsString, (uint32_t)(fileOffset->value.AsInt));
}
else
{
for (auto it = entry->children.begin(); it != entry->children.end(); ++it)
{
WalkAndMapFiles(*it);
}
}
}
bool MountDolphinSdk::GenFileMap()
{
userFilesOffset = 0;
try
{
WalkAndMapFiles(DvdDataInfo.root.children.back());
}
catch (...)
{
Report(Channel::Norm, "WalkAndMapFiles failed!\n");
return false;
}
return true;
}
void MountDolphinSdk::SwapArea(void* _addr, int sizeInBytes)
{
uint32_t* addr = (uint32_t*)_addr;
uint32_t* until = addr + sizeInBytes / sizeof(uint32_t);
while (addr != until)
{
*addr = _BYTESWAP_UINT32(*addr);
addr++;
}
}
#pragma endregion "Data Generators"
}
| 23.449367 | 194 | 0.65803 | ogamespec |
2d43135d6fbc1a59c5f322668622952109189dd4 | 1,240 | cpp | C++ | tests/inputreader_tests.cpp | Stellaris-code/PEGLib | e106be64c9b2b5ad91b5a580e5c0a722082ef79b | [
"MIT"
] | 1 | 2017-08-18T11:31:33.000Z | 2017-08-18T11:31:33.000Z | tests/inputreader_tests.cpp | Stellaris-code/PEGLib | e106be64c9b2b5ad91b5a580e5c0a722082ef79b | [
"MIT"
] | null | null | null | tests/inputreader_tests.cpp | Stellaris-code/PEGLib | e106be64c9b2b5ad91b5a580e5c0a722082ef79b | [
"MIT"
] | null | null | null | /* inputreader_tests.cpp %{Cpp:License:ClassName} - Yann BOUCHER (yann) 20
**
**
** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
** Version 2, December 2004
**
** Copyright (C) 2004 Sam Hocevar <[email protected]>
**
** Everyone is permitted to copy and distribute verbatim or modified
** copies of this license document, and changing it is allowed as long
** as the name is changed.
**
** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
** TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
**
** 0. You just DO WHAT THE FUCK YOU WANT TO.
*/
#include "gtest/gtest.h"
#include "inputreader.hpp"
#include "terminal.hpp"
MAKE_TERMINAL(DummyToken)
MAKE_TERMINAL(TargetToken)
namespace
{
TEST(InputReaderFailure, NoMoreTokens)
{
InputReader reader;
EXPECT_THROW(reader.fetch<Terminal>(), ParseError);
}
TEST(InputReaderFailure, InvalidToken)
{
std::vector<std::unique_ptr<Terminal>> tokens;
tokens.emplace_back(std::make_unique<DummyToken>());
InputReader reader(std::move(tokens));
reader.set_failure_policy(InputReader::FailurePolicy::Strict);
EXPECT_THROW(reader.fetch<TargetToken>(), ParseError);
}
}
| 26.382979 | 75 | 0.679032 | Stellaris-code |
2d446a4cf725b8535908871c9e316e9f9f518747 | 604 | hpp | C++ | android-31/android/app/appsearch/SetSchemaResponse.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/app/appsearch/SetSchemaResponse.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-31/android/app/appsearch/SetSchemaResponse.hpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #pragma once
#include "../../../JObject.hpp"
namespace android::app::appsearch
{
class SetSchemaResponse : public JObject
{
public:
// Fields
// QJniObject forward
template<typename ...Ts> explicit SetSchemaResponse(const char *className, const char *sig, Ts...agv) : JObject(className, sig, std::forward<Ts>(agv)...) {}
SetSchemaResponse(QJniObject obj);
// Constructors
// Methods
JObject getDeletedTypes() const;
JObject getIncompatibleTypes() const;
JObject getMigratedTypes() const;
JObject getMigrationFailures() const;
};
} // namespace android::app::appsearch
| 23.230769 | 158 | 0.706954 | YJBeetle |
2d4577a61f63ba366c8fa2aca81a7e3dc355fe10 | 1,711 | cpp | C++ | util/qtAbstractSetting.cpp | BetsyMcPhail/qtextensions | b2848e06ebba4c39dc63caa2363abc50db75f9d9 | [
"BSD-3-Clause"
] | 1 | 2017-07-31T07:08:05.000Z | 2017-07-31T07:08:05.000Z | util/qtAbstractSetting.cpp | BetsyMcPhail/qtextensions | b2848e06ebba4c39dc63caa2363abc50db75f9d9 | [
"BSD-3-Clause"
] | null | null | null | util/qtAbstractSetting.cpp | BetsyMcPhail/qtextensions | b2848e06ebba4c39dc63caa2363abc50db75f9d9 | [
"BSD-3-Clause"
] | null | null | null | /*ckwg +5
* Copyright 2013 by Kitware, Inc. All Rights Reserved. Please refer to
* KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
* Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
*/
#include "qtAbstractSetting.h"
#include <QSettings>
//-----------------------------------------------------------------------------
qtAbstractSetting::qtAbstractSetting() : modified(false)
{
}
//-----------------------------------------------------------------------------
qtAbstractSetting::~qtAbstractSetting()
{
}
//-----------------------------------------------------------------------------
void qtAbstractSetting::initialize(const QSettings&)
{
this->currentValue = this->originalValue;
}
//-----------------------------------------------------------------------------
bool qtAbstractSetting::isModified()
{
return this->modified;
}
//-----------------------------------------------------------------------------
QVariant qtAbstractSetting::value() const
{
return this->currentValue;
}
//-----------------------------------------------------------------------------
void qtAbstractSetting::setValue(const QVariant& value)
{
this->currentValue = value;
this->modified = (this->currentValue != this->originalValue);
}
//-----------------------------------------------------------------------------
void qtAbstractSetting::commit(QSettings& store)
{
store.setValue(this->key(), this->currentValue);
this->originalValue = this->currentValue;
this->modified = false;
}
//-----------------------------------------------------------------------------
void qtAbstractSetting::discard()
{
this->currentValue = this->originalValue;
this->modified = false;
}
| 28.516667 | 79 | 0.462887 | BetsyMcPhail |
2d45bbd5e06e0a437259e7fa31a2cf68738d2740 | 1,290 | cc | C++ | auditd/src/audit_interface.cc | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | auditd/src/audit_interface.cc | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | auditd/src/audit_interface.cc | BenHuddleston/kv_engine | 78123c9aa2c2feb24b7c31eecc862bf2ed6325e4 | [
"MIT",
"BSD-3-Clause"
] | null | null | null | /* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2016-Present Couchbase, Inc.
*
* Use of this software is governed by the Business Source License included
* in the file licenses/BSL-Couchbase.txt. As of the Change Date specified
* in that file, in accordance with the Business Source License, use of this
* software will be governed by the Apache License, Version 2.0, included in
* the file licenses/APL2.txt.
*/
#include "audit.h"
#include <logger/logger.h>
#include <memcached/audit_interface.h>
#include <platform/socket.h>
#include <stdexcept>
namespace cb::audit {
UniqueAuditPtr create_audit_daemon(const std::string& config_file,
ServerCookieIface* server_cookie_api) {
if (!cb::logger::isInitialized()) {
throw std::invalid_argument(
"create_audit_daemon: logger must have been created");
}
try {
return std::make_unique<AuditImpl>(
config_file, server_cookie_api, cb::net::getHostname());
} catch (std::runtime_error& err) {
LOG_WARNING("{}", err.what());
} catch (std::bad_alloc&) {
LOG_WARNING("Failed to start audit: Out of memory");
}
return {};
}
} // namespace cb::audit
| 31.463415 | 79 | 0.646512 | BenHuddleston |
2d4c24308bdb7e7553f8c70d8eeff07c8360fdd9 | 1,025 | hh | C++ | plugins/gui/abstract-gui.hh | Schroedingers-Cat/clap-examples | 9cbf04216316ca5bccb75b884906caa15766440b | [
"MIT"
] | null | null | null | plugins/gui/abstract-gui.hh | Schroedingers-Cat/clap-examples | 9cbf04216316ca5bccb75b884906caa15766440b | [
"MIT"
] | null | null | null | plugins/gui/abstract-gui.hh | Schroedingers-Cat/clap-examples | 9cbf04216316ca5bccb75b884906caa15766440b | [
"MIT"
] | null | null | null | #pragma once
#include <clap/clap.h>
namespace clap {
class CorePlugin;
class AbstractGuiListener;
class AbstractGui {
public:
AbstractGui(AbstractGuiListener &listener);
virtual ~AbstractGui();
virtual void defineParameter(const clap_param_info ¶mInfo) = 0;
virtual void updateParameter(clap_id paramId, double value, double modAmount) = 0;
virtual void clearTransport() = 0;
virtual void updateTransport(const clap_event_transport &transport) = 0;
virtual bool attachCocoa(void *nsView) = 0;
virtual bool attachWin32(clap_hwnd window) = 0;
virtual bool attachX11(const char *displayName, unsigned long window) = 0;
virtual bool size(uint32_t *width, uint32_t *height) = 0;
virtual bool setScale(double scale) = 0;
virtual bool show() = 0;
virtual bool hide() = 0;
virtual void destroy() = 0;
protected:
AbstractGuiListener &_listener;
bool _isTransportSubscribed = false;
};
} // namespace clap | 26.973684 | 88 | 0.684878 | Schroedingers-Cat |
2d4c3ec94e49c50d982126d1b2384bbd8c865ebf | 255 | cpp | C++ | code3.cpp | gaosiqiang/CSCode | cce6f63d74cca5fd843ac6a734809cc481b6d618 | [
"MIT"
] | null | null | null | code3.cpp | gaosiqiang/CSCode | cce6f63d74cca5fd843ac6a734809cc481b6d618 | [
"MIT"
] | null | null | null | code3.cpp | gaosiqiang/CSCode | cce6f63d74cca5fd843ac6a734809cc481b6d618 | [
"MIT"
] | null | null | null | #include <iostream>
//循环结构
int main(int argc, char const *argv[])
{
//输出小于a的自然数
int a;
std::cout << "请输入一个整数";
std::cin >> a;
if (a > 0) {
for (int i = 0; i < a; ++i)
{
std::cout << i << std::endl;
}
} else {
std::cout << "不得小于1";
}
} | 12.75 | 38 | 0.494118 | gaosiqiang |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.